Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I haven't programmed games for about 10 years (My last experience was DJGPP + Allegro), but I thought I'd check out XNA over the weekend to see how it was shaping up. I am fairly impressed, however as I continue to piece together a game engine, I have a (probably) basic question. How much should you rely on C#'s Dele...
If you were to think of an event as a subscriber list, in your code all you are doing is registering a subscriber. The number of instructions needed to achieve that is likely to be minimal at the CLR level. If you want your code to be generic or dynamic, then you're need to check if something is subscribed prior to ca...
It's important to realize that events in C# are not queued asynchronous events (like, for example the Windows message queue). They are essentially a list of function pointers. So raising an event doesn't have worse performance implications than iterating through a list of function pointers and calling each one. At the...
Game Programming and Event Handlers
[ "", "c#", "xna", "camera", "" ]
I frequently find myself writing code like this: ``` List<int> list = new List<int> { 1, 3, 5 }; foreach (int i in list) { Console.Write("{0}\t", i.ToString()); } Console.WriteLine(); ``` Better would be something like this: ``` List<int> list = new List<int> { 1, 3, 5 }; Console.WriteLine("{0}\t", list); ``` I...
Do this: ``` list.ForEach(i => Console.Write("{0}\t", i)); ``` --- EDIT: To others that have responded - he wants them all on the same line, with tabs between them. :)
A different approach, just for kicks: ``` Console.WriteLine(string.Join("\t", list)); ```
Console.WriteLine and generic List
[ "", "c#", "generics", "console", "list", "" ]
Briefly: Does anyone know of a GUI for gdb that brings it on par or close to the feature set you get in the more recent version of Visual C++? In detail: As someone who has spent a lot of time programming in Windows, one of the larger stumbling blocks I've found whenever I have to code C++ in Linux is that debugging a...
You won't find *anything* overlaying GDB which can compete with the raw power of the Visual Studio debugger. It's just too powerful, and it's just too well integrated inside the IDE. For a Linux alternative, try DDD if free software is your thing.
Eclipse CDT will provide an experience comparable to using Visual Studio. I use Eclipse CDT on a daily basis for writing code and debugging local and remote processes. If you're not familiar with using an Eclipse based IDE, the GUI will take a little getting used to. However, once you get to understand the GUI ideas t...
Is there a C++ gdb GUI for Linux?
[ "", "c++", "linux", "gdb", "debugging", "" ]
In my application I have a DataGridView control that displays data for the selected object. When I select a different object (in a combobox above), I need to update the grid. Unfortunately different objects have completely different data, even different columns, so I need to clear all the existing data and columns, cre...
Rather than adding the rows of the data grid one at a time, use the `DataGridView.Rows.AddRange` method to add all the rows at once. That should only update the display once. There's also a `DataGridView.Columns.AddRange` to do the same for the columns.
People seem to forget a simple fix for this: ``` Object.Visible = false; //do update work Object.Visible = true; ``` I know it seems weird, but that works. When the object is not visible, it won't redraw itself. You still, however, need to do the `begin` and `end` update.
Flickering during updates to Controls in WinForms (e.g. DataGridView)
[ "", "c#", ".net", "winforms", "" ]
One of the things I'd like to do in my browser-based application is allow the user to select some text (not in a <textarea>, just plain ol' text!), and have my application pop up a small toolbar that then can interact with the next (in my case, add annotations). I've found a lot of stuff on google that seems to be foc...
Have a look at [jQuery](http://jquery.com) and the [wrapSelection plugin](http://plugins.jquery.com/project/wrapSelection). It may be what you are looking for.
That jQuery plugin is cool but it accomplishes a very specific task: wrap the text you highlight with a tag. This may be just what you want. But if you don't want to (or are in a situation where you can't) add any extraneous markup to your page, you might try the following solution instead: ``` function getSelectedTex...
Getting selected text in a browser, cross-platform
[ "", "javascript", "browser", "" ]
I need to read from Outlook .MSG file in .NET *without* using COM API for Outlook (cos it will not be installed on the machines that my app will run). Are there any free 3rd party libraries to do that? I want to extract From, To, CC and BCC fields. Sent/Receive date fields would be good if they are also stored in MSG f...
**Update:** I have found a 3rd party COM library called [Outlook Redemption](http://www.dimastr.com/redemption/) which is working fine for me at the moment. If you use it via COM-Interop in .NET, don't forget to release every COM object after you are done with it, otherwise your application crashes randomly.
There is code avaliable on CodeProject for reading .msg files without COM. See [here](http://www.codeproject.com/KB/office/reading_an_outlook_msg.aspx).
Read from .msg files
[ "", "c#", "outlook", "email", "message", "msg", "" ]
In my C++ program I want to parse a small piece of XML, insert some nodes, then extract the new XML (preferably as a `std::string`). [RapidXml](http://rapidxml.sourceforge.net/) has been recommended to me, but I can't see how to retrieve the XML back as a text string. (I could iterate over the nodes and attributes ...
Althoug the documentation is poor on this topic, I managed to get some working code by looking at the source. Although it is missing the xml header which normally contains important information. Here is a small example program that does what you are looking for using rapidxml: ``` #include <iostream> #include <sstream...
Use `print` function (found in `rapidxml_print.hpp` utility header) to print the XML node contents to a `stringstream`.
C++: How to extract a string from RapidXml
[ "", "c++", "xml", "rapidxml", "" ]
I'm working on an exceedingly large codebase, and recently upgraded to GCC 4.3, which now triggers this warning: > warning: deprecated conversion from string constant to ‘char\*’ Obviously, the correct way to fix this is to find every declaration like ``` char *s = "constant string"; ``` or function call like: ```...
I believe passing [-Wno-write-strings](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wno-write-strings) to GCC will suppress this warning.
Any functions into which you pass string literals `"I am a string literal"` should use `char const *` as the type instead of `char*`. If you're going to fix something, fix it right. **Explanation:** You can not use string literals to initialise strings that will be modified, because they are of type `const char*`. C...
How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC
[ "", "c++", "string", "gcc", "" ]
How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#? Something like: ``` DateTime.Now.StartWeek(Monday); ```
Use an extension method: ``` public static class DateTimeExtensions { public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek) { int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7; return dt.AddDays(-1 * diff).Date; } } ``` Which can be used as follows: ``` DateTime dt =...
The quickest way I can come up with is: ``` var sunday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek); ``` If you would like any other day of the week to be your start date, all you need to do is add the DayOfWeek value to the end ``` var monday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (in...
How can I get the DateTime for the start of the week?
[ "", "c#", "datetime", "" ]
The only *nice* way I've found is: ``` import sys import os try: os.kill(int(sys.argv[1]), 0) print "Running" except: print "Not running" ``` ([Source](http://www.unix.com/unix-advanced-expert-users/79267-trick-bash-scripters-check-if-process-running.html)) But is this reliable? Does it wor...
Mark's answer is the way to go, after all, that's why the /proc file system is there. For something a little more copy/pasteable: ``` >>> import os.path >>> os.path.exists("/proc/0") False >>> os.path.exists("/proc/12") True ```
on linux, you can look in the directory /proc/$PID to get information about that process. In fact, if the directory exists, the process is running.
How to check if a process is still running using Python on Linux?
[ "", "python", "linux", "unix", "process", "" ]
``` @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) public class Problem { @ManyToOne private Person person; } @Entity @DiscriminatorValue("UP") public class UglyProblem extends Problem {} @Entity public class Person { @OneToMany(mappedBy="person") private List< UglyProblem > problems; }...
I think it's a wise decision made by the Hibernate team. They could be less arrogante and make it clear why it was implemented this way, but that's just how Emmanuel, Chris and Gavin works. :) Let's try to understand the problem. I think your concepts are "lying". First you say that many **Problem**s are associated to...
In my case I wanted to use the SINGLE\_TABLE inheritance type, so using @MappedSuperclass wasn't an option. What works, although not very clean, is to add the Hibernate proprietary [@Where](http://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/annotations/Where.html) clause to the @OneToMany association to fo...
Why @OneToMany does not work with inheritance in Hibernate
[ "", "java", "hibernate", "inheritance", "orm", "" ]
In the project I am currently working on, we have the need to develop a web chat application, not a very complex chat, just a way to connect two people to talk about a very specific topic, we don't need any kind of authentication for one of the two users, we don't have to support emoticons, avatars, or stuff like that....
You might also want to look into [Comet](http://en.wikipedia.org/wiki/Comet_(programming)). It's used by GTalk, Meebo, and many [other chat applications](http://ajaxian.com/archives/comet-a-new-approach-to-ajax-applications). A few years ago when I was experimenting with it, there weren't very many libraries or detail...
> What would you recommend? XMPP through BOSH There's no need to invent your own message format and transport protocol when somebody else has. If you try, it'll slowly grow to be just as complex as BOSH but without the benefit of third-party library support or standardization.
Chat application AJAX polling
[ "", "php", "ajax", "chat", "" ]
Is there any shorthand way of defining and using generic definitions without having to keep repeating a particular generic description such that if there is a change I don't have to change all definitions/usages though out the codebase for example is something like this possible: ``` Typedef myGenDef = < Object1, Obje...
There's the [pseudo-typedef antipattern](http://www.ibm.com/developerworks/java/library/j-jtp02216/index.html)... ``` class StringList extends ArrayList<String> { } ``` Good stuff, drink up! ;-) As the article notes, this technique has some serious issues, primarily that this "typedef" is actually a separate class a...
In a generic method, you can use a limited form of type inferrence to avoid some repetitions. Example: if you have the function ``` <K, V> Map<K, V> getSomething() { //... } ``` you can use: ``` final Map<String, Object> something = getsomething(); ``` instead of: ``` final Map<String, Object> som...
Generics in Java
[ "", "java", "generics", "" ]
If you create an Oracle dblink you cannot directly access LOB columns in the target tables. For instance, you create a dblink with: ``` create database link TEST_LINK connect to TARGETUSER IDENTIFIED BY password using 'DATABASESID'; ``` After this you can do stuff like: ``` select column_a, column_b from data_u...
Yeah, it is messy, I can't think of a way to avoid it though. You could hide some of the messiness from the client by putting the temporary table creation in a stored procedure (and using "execute immediate" to create they table) One thing you will need to watch out for is left over temporary tables (should somethi...
The best solution by using a query as below, where column\_b is a BLOB: ``` SELECT (select column_b from sample_table@TEST_LINK) AS column_b FROM DUAL ```
Best way to handle LOBs in Oracle distributed databases
[ "", "sql", "oracle", "distributed-transactions", "dblink", "" ]
I had an idea, if I add a python .py file to my C# project, and tag the file with a custom generator that would execute the python file, and treat the output as the result of the code generation, ie. put it into a C# file, that would allow me to do quite a lot of code generation as part of the build process. Does anyo...
OK, I see. Well, as far as I know there isn't any code generator for Python. There is a good introduction on how to roll your own [here](http://www.drewnoakes.com/snippets/WritingACustomCodeGeneratorToolForVisualStudio/). Actually, that's quite an under-used part of the environment, I suppose it's so because it needs ...
I think [Cog](http://nedbatchelder.com/code/cog/) does what you want.
Python code generator for Visual Studio?
[ "", "python", "visual-studio-2008", "code-generation", "" ]
We have a set of applications that basically display a bunch of bitmaps and text, then allow user to press "buttons" (certain bitmaps) that cause actions to occur. We currently have these implemented using DirectX and a bunch of code to place the bitmaps and handle the button-presses. But we'd like to have the followi...
Maybe the way to go is something like [Clutter](http://clutter-project.org/) or [Allegro](http://www.allegro.cc/). If you check in this [article](http://arstechnica.com/news.ars/post/20080604-hands-on-with-the-ubuntu-netbook-remix.html) at ArsTechnica what they are using Clutter for, you might get an idea how to use it...
"We don't like the common GUI toolkits or widgets. We want something that has more of the look of a game than of a dialog box." You realize that Trolltech's QT has a style sheet language for widgets? Take a look at their white paper, specifically page 60 <http://trolltech.com/pdf/qt43-whitepaper-us.pdf> Going over y...
Simple Frameworks for Displaying Bitmaps and Handling Button Presses
[ "", "c++", "user-interface", "graphics", "bitmap", "" ]
Let's say that you want to create a dead simple BlogEditor and, one of your ideas, is to do what Live Writer does and ask only the URL of the persons Blog. How can you detect what type of blog is it? Basic detection can be done with the URL itself, such as “<http://myblog.blogger.com>” etc. But what if it's self hoste...
Many (most?) blogs will have a meta tag for "generator" which will list the blog engine. For example a blogger blog will contain the following meta tag: ``` <meta name="generator" content="Blogger" /> ``` My Subtext blog shows the following generator meta tag: ``` <meta name="Generator" content="Subtext Version 1.9....
Some blogs provide a Generator meta tag - e.g. Wordpress - you could find out if there's any exceptions to this. You'll have to be careful how you detect it though, Google surprised me with this line: ``` <meta content='blogger' name='generator'/> ``` Single quotes are blasphemy.
How to detect which blog API
[ "", "java", "api", "blogs", "" ]
Does anyone know if the Infragistics UltraGrid control provides functionality similar to that of DataGridView.HitTestInfo?
Check [this](http://www.abstraction-systems.com/ttf/HTML/TTFactory_TaskBasedTutorials_UltraWinGrid.htm) out. They don't convert the coordinates, but they use a special Infragistics grid event ([MouseEnterElement](http://help.infragistics.com/Help/NetAdvantage/NET/2008.2/CLR2.0/html/Infragistics2.Win.v8.2~Infragistics....
There's a `.MousePosition` property which returns `System.Drawing.Point` and "Gets the position of the mouse cursor in screen coordinates" but I'm using an older version of their UltraWinGrid (2003). They have a [free trial download](http://www.infragistics.com/downloads/default.aspx), so you could see if they've adde...
DataGridView.HitTestInfo equivalent in Infragistics.Win.UltraWinGrid.UltraGrid?
[ "", "c#", ".net", "infragistics", "ultrawingrid", "" ]
Well behaved windows programs need to allow users to save their work when they are shutting the PC down. How can I make my app detect the shutdown event? Any solution should allow the user to abort the shutdown if user selects, say "Cancel". The normal Swing window closing hook doesn't work, nor does adding a shutdow...
Write some JNI code to WM\_QUERYENDSESSION message. You can get details for this from the MSDN documentation or by googling it. If you don't want to write too much C++ code to do this I can recommend the JNA library [click here](https://jna.dev.java.net/). Which gives you some nice Java abstractions for C code.
[how-do-i-get-my-java-application-to-shutdown-nicely-in-windows](https://stackoverflow.com/questions/61692/how-do-i-get-my-java-application-to-shutdown-nicely-in-windows) That might be of help
How can I detect from a Swing app that the PC is being shut-down?
[ "", "java", "swing", "operating-system", "" ]
For various reasons calling `System.exit` is frowned upon when writing **Java Applications**, so how can I notify the calling process that not everything is going according to plan? **Edit:** The 1 is a `standin` for any non-zero exit code.
The use of `System.exit` is frowned upon when the 'application' is really a sub-application (e.g. servlet, applet) of a larger Java application (server): in this case the `System.exit` could stop the JVM and hence also all other sub-applications. In this situation, throwing an appropriate exception, which could be caug...
I agree with the "*throw an Exception*" crowd. One reason is that calling System.exit makes your code difficult to use if you want other code to be able to use it. For example, if you find out that your class would be useful from a web app, or some kind of message consuming app, it would be nice to allow those containe...
Alternatives to System.exit(1)
[ "", "java", "process", "" ]
I need to run a JavaScript function onLoad(), but only do it if the page loaded the first time (i.e. is not the result of a postback). Basically, I need to check for IsPostBack in JavaScript. Thank you.
Server-side, write: ``` if(IsPostBack) { // NOTE: the following uses an overload of RegisterClientScriptBlock() // that will surround our string with the needed script tags ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true); } ``` Then, in your script which runs...
There is an even easier way that does not involve writing anything in the code behind: Just add this line to your javascript: ``` if(<%=(Not Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here} ``` or ``` if(<%=(Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here} ```
How can I check for IsPostBack in JavaScript?
[ "", "asp.net", "javascript", "" ]
If I have the following: ``` {"hdrs": ["Make","Model","Year"], "data" : [ {"Make":"Honda","Model":"Accord","Year":"2008"} {"Make":"Toyota","Model":"Corolla","Year":"2008"} {"Make":"Honda","Model":"Pilot","Year":"2008"}] } ``` And I have a "hdrs" name (i.e. "Make"), how can I reference the `data` array inst...
I had to alter your code a little: ``` var x = {"hdrs": ["Make","Model","Year"], "data" : [ {"Make":"Honda","Model":"Accord","Year":"2008"}, {"Make":"Toyota","Model":"Corolla","Year":"2008"}, {"Make":"Honda","Model":"Pilot","Year":"2008"}] }; alert( x.data[0]...
First, you forgot your trailing commas in your **data** array items. Try the following: ``` var obj_hash = { "hdrs": ["Make", "Model", "Year"], "data": [ {"Make": "Honda", "Model": "Accord", "Year": "2008"}, {"Make": "Toyota", "Model": "Corolla", "Year": "2008"}, {"Make": "Honda", "Mod...
Javascript array reference
[ "", "javascript", "json", "" ]
I am writing a program that needs to send out an email every hour on the hour, but at a time local to the user. Say I have 2 users in different time zones. John is in New York and Fred is in Los Angeles. The server is in Chicago. If I want to send an email at 6 PM local to each user, I'd have to send the email to John...
You have two options: * Store the adjusted time for the mail action into the database for each user. Then just compare server time with stored time. To avoid confusion and portability issues, I would store all times in UTC. So, send mail when SERVER\_UTC\_TIME() == storedUtcTime. * Store the local time for each mail a...
You can complement your solution with this excellent article "[World Clock and the TimeZoneInformation class](http://www.codeproject.com/KB/dotnet/WorldClock.aspx)", I made a webservice that sent a file with information that included the local and receiver time, what I did was to modify this class so I could handle tha...
How to send out email at a user's local time in .NET / Sql Server?
[ "", "sql", ".net", "sql-server", "timezone", "" ]
I've got a problem similar to,but subtly different from, that described [here](https://stackoverflow.com/questions/22012/loading-assemblies-and-its-dependencies) (Loading assemblies and their dependencies). I have a C++ DLL for 3D rendering that is what we sell to customers. For .NET users we will have a CLR wrapper a...
I finally have an answer for this that appears to work. Compile both 32 & 64 bit versions - both managed & unmanaged - into separate folders. Then have the .NET app choose at run time which directory to load the assemblies from. The problem with using the ResolveEvent is that it only gets called if assemblies aren't ...
I was able to do this about a year ago, but I no longer remember all of the details. Basically, you can use IntPtr.Size to determine which DLL to load, then perform the actual LoadLibrary through p/Invoke. At that point, you've got the module in memory and you ought to be able to just p/Invoke functions from inside of ...
How to late bind 32bit/64 bit libs at runtime
[ "", "c#", ".net", "64-bit", "clr", "x86-64", "" ]
I have been working with Struts for some time, but for a project I am finishing I was asked to separate Templates (velocity .vm files), configs (struts.xml, persistence.xml) from main WAR file. I have all in default structure like: ``` application |-- META-INF -- Some configs are here |-- WEB-I...
If I understood your question about Struts config files right, they are specified in web.xml. Find the Struts servlet config param. The param-value can be a list of comma separated list of XML files to load. Eg: ``` <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionSer...
For *persistence.xml*, specifically, you can put a persistence unit in a separate JAR, which you can deploy separately from your web application WAR, or both together in an EAR archive, depending on what your application server supports. For example, the JBoss manual describes this as [Deploy EAR with EJB3 JAR](http://...
Changing default file structure in a Java Struts App
[ "", "java", "templates", "struts", "configuration-files", "" ]
I'm looking for a way to get the size of an instance of a reference type. sizeof is only for value types. Is this possible?
If you don't mind it being a little less accurate than perfect, and for comparative purposes, you could serialize the object/s and measure that (in bytes for example) *EDIT (I kept thinking after posting)*: Because it's a little more complicated than sizeof for valuetypes, for example: reference types can have referen...
You need [Marshal.SizeOf](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.sizeof.aspx) **Edit:** This *is* for unsafe code, but then, so is sizeof().
sizeof() equivalent for reference types?
[ "", "c#", ".net", "" ]
I'm fairly new to the STL, so I was wondering whether there are any dynamically sortable containers? At the moment my current thinking is to use a vector in conjunction with the various sort algorithms, but I'm not sure whether there's a more appropriate selection given the (presumably) linear complexity of inserting e...
If you know you're going to be sorting on a single value ascending and descending, then set is your friend. Use a reverse iterator when you want to "sort" in the opposite direction. If your objects are complex and you're going to be sorting in many different ways based on the member fields within the objects, then you...
You'll want to look at std::map ``` std::map<keyType, valueType> ``` The map is sorted based on the < operator provided for keyType. Or ``` std::set<valueType> ``` Also sorted on the < operator of the template argument, but does not allow duplicate elements. There's ``` std::multiset<valueType> ``` which does t...
Dynamically sorted STL containers
[ "", "c++", "stl", "containers", "" ]
I find that the .NET event model is such that I'll often be raising an event on one thread and listening for it on another thread. I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is. Based on the community suggestions, I've used this: ``` // earlier in the code mCo...
A couple of observations: * Don't create simple delegates explicitly in code like that unless you're pre-2.0 so you could use: ``` BeginInvoke(new EventHandler<CoolObjectEventArgs>(mCoolObject_CoolEvent), sender, args); ``` * Also you don't need to create and populate the object ar...
I have [some code for this](https://github.com/domenic/extensions/blob/master/WindowsFormsInvokingExtensions.cs) online. It's much nicer than the other suggestions; definitely check it out. Sample usage: ``` private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args) { // You could use "() =>" in ...
Cleanest Way to Invoke Cross-Thread Events
[ "", "c#", "multithreading", "events", "" ]
I'm wondering how you can implement a program similar to `tail -f` in C/C++, a program that watches for and processes new lines added to a log file?
You can use fseek() to clear the eof condition on the stream. Essentially, read to the end of the file, sleep for a while, fseek() (without changing your position) to clear eof, the read to end of file again. wash, rinse, repeat. man fseek(3) for details. Here's what it looks like in perl. perl's seek() is essentially...
[See here](https://stackoverflow.com/questions/18632/how-to-monitor-a-text-file-in-realtime#18635) You could either call out to tail and retrieve the stream back into your app, or as it's open source, maybe try to pull it into your own code. Also, it is possible in C++ iostream to open a file for viewing only and jus...
Implementing a log watcher
[ "", "c++", "c", "file", "io", "" ]
What is the purpose of annotations in Java? I have this fuzzy idea of them as somewhere in between a comment and actual code. Do they affect the program at run time? What are their typical usages? Are they unique to Java? Is there a C++ equivalent?
Annotations are primarily used by code that is inspecting other code. They are often used for modifying (i.e. decorating or wrapping) existing classes at run-time to change their behavior. Frameworks such as [JUnit](http://www.junit.org/) and [Hibernate](http://www.hibernate.org/) use annotations to minimize the amount...
> Also, are they unique to Java, is there a C++ equivalent? No, but VB and C# have [attributes](http://www.codeproject.com/KB/cs/dotnetattributes.aspx) which are the same thing. Their use is quite diverse. One typical Java example, `@Override` has no effect on the code but it can be used by the compiler to generate a...
Java Annotations
[ "", "java", "annotations", "glossary", "" ]
I'm looking at the [PHP Manual](http://www.php.net/manual/en/), and I'm not seeing a section on data structures that most languages have, such as lists and sets. Am I just blind or does PHP not have anything like this built in?
The only native data structure in PHP is array. Fortunately, arrays are quite flexible and can be used as hash tables as well. <http://www.php.net/array> However, there is SPL which is sort of a clone of C++ STL. <http://www.php.net/manual/en/book.spl.php>
PHP offers data structures through the Standard PHP Library (SPL) basic extension, which is available and compiled by default in PHP 5.0.0. The data structures offered are available with PHP 5 >= 5.3.0, and includes: ### Doubly Linked Lists A Doubly Linked List (DLL) is a list of nodes linked in both directions to e...
Does PHP have built-in data structures?
[ "", "php", "data-structures", "" ]
I have a need to convert images from CMYK to RGB - not necessarily back again, but hey, if it can be done... With the release of ColdFusion 8, we got the [CFImage](http://cfquickdocs.com/cf8/?getDoc=cfimage) tag, but it doesn't support this conversion; and nor does [Image.cfc](http://x.com), or [Alagad's Image Compone...
I use the Java ImageIO libraries (<https://jai-imageio.dev.java.net>). They aren't perfect, but can be simple and get the job done. As far as converting from CMYK to RGB, here is the best I have been able to come up with. Download and install the ImageIO JARs and native libraries for your platform. The native librarie...
A very simple formula for converting from CMYK to RGB ignoring all color profiles is: ``` R = ( (255-C)*(255-K) ) / 255; G = ( (255-M)*(255-K) ) / 255; B = ( (255-Y)*(255-K) ) / 255; ``` This code requires CMYK values to be in rage of 0-255. If you have 0 to 100 or 0.0 to 1.0 you'll have to convert the va...
How do I convert images between CMYK and RGB in ColdFusion (Java)?
[ "", "java", "image", "coldfusion", "" ]
The primary class in the `subprocess` module is name `Popen`, and represents a subprocess. `Popen` sounds like someone was trying to force the name to follow some function naming format, rather than chosing a name that actually represents what the object is. Does anyone know why it was chosen over something simple like...
Now, I'm not saying that this is the greatest name in the world, but here was the idea as I understand it. Originally, the popen family was in the os module and was an implementation of the venerable posix popen. The movement to the subprocess module would have been an opportune time to rename them, but I guess that k...
`subprocess.Popen` replaces the group of `os.popenX` POSIX functions (which have a long history). I suppose that the name `Popen` makes it more likely for people used to the old functions to find and use the new ones. The [PEP for subprocess (PEP 324)](http://www.python.org/dev/peps/pep-0324/) has a little bit of disc...
Why is the subprocess.Popen class not named Subprocess?
[ "", "python", "subprocess", "" ]
I have a web system which has a classical parent-children menu saved in a database, with fields id as the PK, and parent\_id to pointing to the owning menu. (Yes, I know this doesn't scale very well, but that's another topic). So for these records (id-parent\_id pairs): ``` 0-7 0-4 4-9 4-14 4-16 9-6 ``` I have this ...
This is the perfect chance to use recursion! Pseudo-code: ``` nodeList = {} enumerateNodes(rootNode, nodeList); function enumerateNodes(node, nodeList) { nodeList += node; foreach ( childnode in node.children ) { enumerateNodes(childnode, nodeList); } } ``` Edit: Didn't notice that your tree is in t...
Adjacent list models are very difficult to deal with. The company I am with now uses them for hierarchies and it causes great headaches. I have successfully used Celko's nested set models for prior employers and they work great for creating, maintaining and using hierarchies (trees). I found this link which describes ...
Retrieve all nodes in a tree that are children of another one
[ "", "php", "tree", "" ]
While writing a custom IHttpHandler I came across a behavior that I didn't expect concerning the HttpCachePolicy object. My handler calculates and sets an entity-tag (using the SetETag method on the HttpCachePolicy associated with the current response object). If I set the cache-control to public using the SetCacheabi...
I think you need to use HttpCacheability.ServerAndPrivate That should give you cache-control: private in the headers and let you set an ETag. The documentation on that needs to be a bit better. **Edit:** Markus found that you also have call cache.SetOmitVaryStar(true) otherwise the cache will add the Vary: \* header...
Unfortunately if you look at `System.Web.HttpCachePolicy.UpdateCachedHeaders()` in .NET Reflector you see that there's an if statement specifically checking that the Cacheability is not Private before doing any ETag stuff. In any case, I've always found that `Last-Modified/If-Modified-Since` works well for our data and...
Why does HttpCacheability.Private suppress ETags?
[ "", "c#", "asp.net", "http", "caching", "" ]
Why wouldn't I choose abstract? What are the limitations to declaring a class member virtual? Can only methods be declared virtual?
An abstract method or property (both can be virtual or abstract) can only be declared in an abstract class and cannot have a body, i.e. you can't implement it in your abstract class. A virtual method or property must have a body, i.e. you must provide an implementation (even if the body is empty). If someone want to ...
You would use abstract if you do not want to define any implementation in the base class and want to force it to be defined in any derived classes. Define it as a virtual if you want to provide a default implementatio that can be overriden by derived classes. Yes, only methods can be virtual.
When should a class member be declared virtual (C#)/Overridable (VB.NET)?
[ "", "c#", ".net", "vb.net", "" ]
I am looking for a little bit of JQuery or JS that allows me to produce a horizontally scrolling "news ticker" list. The produced HTML needs to be standards compliant as well. I have tried [liScroll](http://www.gcmingati.net/wordpress/wp-content/lab/jquery/newsticker/jq-liscroll/scrollanimate.html) but this has a hab...
Smooth Div Scroll can also be used as a news ticker/stock ticker. It can pause on mouse over or mouse down and it can loop endlessly if you want it to. Here's [the example](http://www.maaki.com/) with a running ticker.
<http://www.emrecamdere.com/news_scroller_jquery.html>
What's a good bit of JS or JQuery for horizontally scrolling news ticker
[ "", "javascript", "jquery", "scroll", "client-side", "" ]
I'm getting some strange, intermittent, data aborts (< 5% of the time) in some of my code, when calling `memset()`. The problem is that is usually doesn't happen unless the code is running for a couple days, so it's hard to catch it in the act. I'm using the following code: ``` char *msg = (char*)malloc(sizeof(char)*...
`malloc` can return `NULL` if no memory is available. You're not checking for that.
There's a couple of things. You're using `sprintf` which is inherently unsafe; unless you're 100% positive that you're not going to exceed the size of the buffer, you should almost *always* prefer `snprintf`. The same applies to `strcat`; prefer the safer alternative `strncat`. Obviously this may not fix anything, but...
memset() causing data abort
[ "", "c++", "c", "memory", "windows-mobile", "" ]
What libraries/methods do you know of that can do some basic HTML representation in Swing? Can you comment on your experience?
Many of the Swing controls (like JLabel) can render basic HTML content. [JEditorPane](http://java.sun.com/javase/6/docs/api/javax/swing/JEditorPane.html) can be used to display HTML pages. However, these controls are limited to [HTML 3.2](http://www.w3.org/TR/REC-html32) support. For a richer experience, I would use t...
A good pure Java solution is [JWebEngine](http://www.inetsoftware.de/other-products/jwebengine). It render HTML 4 very good.
Previewing HTML in Java
[ "", "java", "html", "" ]
Is there any difference between: ``` if foo is None: pass ``` and ``` if foo == None: pass ``` The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it sh...
`is` always returns `True` if it compares the same object instance, whereas `==` is ultimately determined by the `__eq__()` method. i.e. ``` >>> class Foo: def __eq__(self, other): return True >>> f = Foo() >>> f == None True >>> f is None False ```
You may want to read this: [object identity and equivalence](http://mail.python.org/pipermail/python-list/2001-November/094920.html). The statement `is` is used for object identity, it checks if objects refer to the same instance (same address in memory). And the `==` statement refers to equality (same value).
Is there any difference between "foo is None" and "foo == None"?
[ "", "python", "" ]
We've got a page with a ton of jQuery (approximately 2000 lines) that we want to trim down b/c it is a maintenance nightmare, and it might be easier to maintain on the server. We've thought about using UpdatePanel for this. However, we don't like the fact that the UpdatePanel is sending the whole page back to the serve...
Don't move to UpdatePanels. After coming from jQuery, [the drop in performance](http://encosia.com/2007/07/11/why-aspnet-ajax-updatepanels-are-dangerous/) would be untenable. Especially on a page as complex as yours sounds. If you have 2,000 lines of JavaScript code, the solution is to refactor that code. If you put 2...
Please don't put your self in that world of pain. Instead use [UFRAME](http://msmvps.com/blogs/omar/archive/2008/05/24/uframe-goodness-of-updatepanel-and-iframe-combined.aspx) which is a lot faster and is implemented in jQuery. Now, to manage those 2000 lines of Javascript code I recommend splitting the code in differ...
jQuery AJAX vs. UpdatePanel
[ "", "javascript", "jquery", "asp.net", "ajax", "updatepanel", "" ]
How do I select all records that contain "LCS" within the title column in sql.
``` SELECT * FROM TABLE WHERE TABLE.TITLE LIKE '%LCS%'; ``` % is the wild card matcher.
Look into the LIKE clause
How do I display records containing specific information in SQl
[ "", "sql", "sql-server", "" ]
The following bit of code catches the EOS Exception ``` using (var reader = new BinaryReader(httpRequestBodyStream)) { try { while (true) { bodyByteList.Add(reader.ReadByte()); } } catch (EndOfStreamException) { } } ``` So why do I still receive first-chance exceptions in my conso...
The point of "first-chance" exceptions is that you're seeing them pre-handler so that you can stop on them during debugging at the point of throwing. A "second-chance" exception is one that has no appropriate handler. Sometimes you want to catch "first-chance" exceptions because it's important to see what's happening w...
To avoid seeing the messages, right-click on the output window and uncheck "Exception Messages". However, seeing them happen might be nice, if you're interested in knowing when exceptions are thrown without setting breakpoints and reconfiguring the debugger.
Avoiding first chance exception messages when the exception is safely handled
[ "", "c#", ".net", "exception", "" ]
I am trying to automate functional testing of a server using a realistic frequency distribution of requests. (sort of load testing, sort of simulation) I've chosen the [Weibull](http://en.wikipedia.org/wiki/Weibull_distribution) distribution as it "sort of" matches the distribution I've observed (ramps up quickly, dro...
This is quick and probably not that accurate, but if you calculate the PDF yourself, then at least you make it easier to lay several smaller/larger ones on a single timeline. `dev` is the std deviation in the Guassian noise, which controls the roughness. Note that this is *not* the 'right' way to generate what you want...
Why don't you try [The Grinder 3](http://grinder.sourceforge.net) to load test your server, it comes with all this and more prebuilt, and it supports python as a scripting language
How do i generate a histogram for a given probability distribution (for functional testing a server)?
[ "", "python", "statistics", "simulation", "stress-testing", "" ]
Speaking as a non-C# savvy programmer, I'm curious as to the evaluation semantics of LINQ queries like the following: ``` var people = from p in Person where p.age < 18 select p var otherPeople = from p in people where p.firstName equals "Daniel" select p ...
They are composable. This is possible because LINQ queries are actually expressions (code as data), which LINQ providers like LINQ-to-SQL can evaluate and generate corresponding SQL. Because LINQ queries are lazily evaluated (e.g. won't get executed until you iterate over the elements), the code you showed won't actua...
``` var people = from p in Person where p.age < 18 select p ``` Translates to: ``` SELECT [t0].[PersonId], [t0].[Age], [t0].[FirstName] FROM [dbo].[Person] AS [t0] WHERE [t0].[Age] < @p0 ``` where @p0 gets sent through as 18 ``` var otherPeople = from p in people where p....
Does LINQ-to-SQL Support Composable Queries?
[ "", "sql", "linq", "linq-to-sql", "code-reuse", "" ]
Can you use windows hooks or other methods to do code injection with c#? I've seen lots of things about code injection but all of them are done in C/C++. I don't know either of those languages and have a really hard time translating. Does anyone have any ideas on how to do this?
Kevin, it is possible. You can create library with window hook proc using managed C++. All you need to do is to inject this hook into some application using standard WinAPI (SetWindowsHookEx etc.). Inside this hook you can call System::AppDomain::CurrentDomain->Load method to load your assembly into target application'...
Mike Stall has [this sample](http://blogs.msdn.com/jmstall/archive/2006/09/28/managed-create-remote-thread.aspx), that uses CreateRemoteThread. It has the advantage of not requiring any C++.
Code Injection With C#
[ "", "c#", "code-injection", "" ]
I would like a panel in GWT to fill the page without actually having to set the size. Is there a way to do this? Currently I have the following: ``` public class Main implements EntryPoint { public void onModuleLoad() { HorizontalSplitPanel split = new HorizontalSplitPanel(); //split.setSize("...
Google has answered the main part of your question in one of their FAQs: <http://code.google.com/webtoolkit/doc/1.6/FAQ_UI.html#How_do_I_create_an_app_that_fills_the_page_vertically_when_the_b> The primary point is that you can't set height to 100%, you must do something like this: ``` final VerticalPanel vp = new Ve...
Ben's answer is very good, but is also out of date. A resize handler was necessary in GWT 1.6, but we are at 2.4 now. You can use a [DockLayoutPanel](http://google-web-toolkit.googlecode.com/svn/javadoc/2.0/com/google/gwt/user/client/ui/DockLayoutPanel.html) to have your content fill the page vertically. See the [sampl...
Creating a fluid panel in GWT to fill the page?
[ "", "java", "gwt", "" ]
What is the difference in C# between `Convert.ToDecimal(string)` and `Decimal.Parse(string)`? In what scenarios would you use one over the other? What impact does it have on performance? What other factors should I be taking into consideration when choosing between the two?
From [bytes.com](http://bytes.com/forum/thread266344.html): > The Convert class is designed to > convert a wide range of Types, so you > can convert more types to Decimal than > you can with Decimal.Parse, which can > only deal with String. On the other > hand Decimal.Parse allows you to > specify a NumberStyle. > > D...
There is one important difference to keep in mind: `Convert.ToDecimal` will return `0` if it is given a `null` string. `decimal.Parse` will throw an `ArgumentNullException` if the string you want to parse is `null`.
Difference between Convert.ToDecimal(string) & Decimal.Parse(string)
[ "", "c#", ".net", "" ]
I have a console program written in C# that I am using to send faxes. When I step through the program in Visual Studio it works fine. When I double click on the program in Windows Explorer it works fine. When I setup a Windows scheduled task to run the program it fails with this in the event log. ``` EventType clr20r3...
I can't explain it - but I have a few ideas. Most of the times, when a program works fine testing it, and doesn't when scheduling it - security is the case. In the context of which user is your program scheduled? Maybe that user isn't granted enough access. Is the resource your programm is trying to access a network ...
I agree with MartinNH. Many of these problems root from the fact that you develop while logged in as an administrator in Visual Studio (so the program has all the permissions for execution set properly) but you deploy as a user with lesser privileges. Try setting the priveleges of the task scheduler user higher.
C# console program can't send fax when run as a scheduled task
[ "", "c#", "console", "fax", "" ]
I would like to read the text and binary attachments in a saved Outlook message (.msg file) from a Java application, without resorting to native code (JNI, Java Native Interface). [Apache POI-HSMF](http://poi.apache.org/hsmf/index.html) seems to be in the right direction, but it's in very early stages of development.....
* You could use Apache POIFS, which seems to be a little more mature, but that would appear to duplicate the efforts of POI-HSMF. * You could use POI-HSMF and contribute changes to get the features you need working. That's often how FOSS projects like that expand. * You could use com4j, j-Interop, or some o...
[msgparser](http://auxilii.com/msgparser/) is a small open source Java library that parses Outlook .msg files and provides their content using Java objects. msgparser uses the [Apache POI - POIFS](http://poi.apache.org/poifs/) library to parse the message files which use the OLE 2 Compound Document format.
What's the best library for reading Outlook .msg files in Java?
[ "", "java", "outlook", "msg", "" ]
I'm currently working on a JavaScript tool that, during the course of its execution, will ultimately traverse each node in the DOM. Because this has potential to be a very expensive task, I'd like to benchmark the performance of this script. What's the best, free tool for benchmarking a script such as this across the ...
**[Firebug](http://getfirebug.com)** does include JS profiling, and it is probably the best out there. While I've had problems with Firebug's debugger, its profiler is currently top-of-the-line. **[Venkman](http://www.mozilla.org/projects/venkman/)** is also an older JS debugger/profiler for Firefox, just in case you r...
In FireBug and FireBug Lite you can call the console.time() and console.timeEnd() methods in your code to start and end a timer around a particular piece of code. The Profiler tool in FireBug will measure how long each function takes. I've used it a lot to narrow down which lines of a particularly slow function are cau...
What is the best tool to benchmark my JavaScript?
[ "", "javascript", "dom", "" ]
How do I call an external command within Python as if I had typed it in a shell or command prompt?
Use [`subprocess.run`](https://docs.python.org/library/subprocess.html#subprocess.run): ``` import subprocess subprocess.run(["ls", "-l"]) ``` Another common way is [`os.system`](https://docs.python.org/library/os.html#os.system) but you shouldn't use it because it is unsafe if any parts of the command come from out...
Here is a summary of ways to call external programs, including their advantages and disadvantages: 1. [`os.system`](https://docs.python.org/3/library/os.html#os.system) passes the command and arguments to your system's shell. This is nice because you can actually run multiple commands at once in this manner and set up...
How do I execute a program or call a system command?
[ "", "python", "shell", "terminal", "subprocess", "command", "" ]
Suppose a large composite application built on several foundation components packaged in their own assemblies: (database reading, protocol handlers, etc.). For some deployments, this can include over 20 assemblies. Each of these assemblies has settings or configuration information. Our team tends to like the VS setting...
You use one master config file that points to other config files. [Here's an example of how to do this.](http://blog.andreloker.de/post/2008/06/Keep-your-config-clean-with-external-config-files.aspx) --- In case the link rots, what you do is specify the [configSource](http://msdn.microsoft.com/en-us/library/system.co...
My preferred method is to use MSBuild, if you right click on a project and click 'unload' a new menu option will pop up that says 'edit '. Select that and it'll open up the project file so you can edit it, scroll down until you find a commented out section that is called "AfterBuild". You can then add something like: ...
How do you manage .NET app.config files for large applications?
[ "", "c#", ".net", "configuration", "" ]
While creating a file synchronization program in C# I tried to make a method `copy` in `LocalFileItem` class that uses `System.IO.File.Copy(destination.Path, Path, true)` method where `Path` is a `string`. After executing this code with destination. `Path = "C:\\Test2"` and `this.Path = "C:\\Test\\F1.txt"` I get an e...
It seems you have misplaced the parameters in File.Copy(), it should be File.Copy(string source, string destination). Also is "C:\Test2" a directory? You can't copy file to a directory. Use something like that instead: ``` File.Copy( sourceFile, Path.Combine(destinationDir,Path.GetFileName(sourceFile)) )...
I was able to solve the problem, Michal pointed me to the right direction. The problem was that I tried to use File.Copy to copy a file from one location to another, while the Copy method does only copy all the contents from one file to another(creating the destination file if it does not already exists). The solution ...
About File permissions in C#
[ "", "c#", "file", "copy", "" ]
I thought jQuery Intellisense was supposed to be improved with SP1. I even downloaded an annotated version of jQuery 1.2.6, but intellisense will not work in a separate jscript file. I have the jQuery library referenced first on my web page in the <head> tag. Am I doing anything wrong?
At the top of your external JavaScript file, add the following: ``` /// <reference path="jQuery.js"/> ``` Make sure the path is correct, relative to the file's position in the folder structure, etc. Also, any references need to be at the top of the file, before *any* other text, including comments - literally, the v...
There is an officially supported jQuery documentation JavaScript file for Visual Studio 2008. This file is only an interim fix until Microsoft releases a hotfix that will more adequately address the issue. Embedded in ASPX: ``` <% if (false) { %> <script src="jquery-1.2.6-vsdoc.js" type="text/javascript"></script...
How do you get JavaScript/jQuery Intellisense Working in Visual Studio 2008?
[ "", "asp.net", "javascript", "jquery", "visual-studio", "intellisense", "" ]
Kind of a special case problem: * I start a process with `System.Diagnostics.Process.Start(..)` * The process opens a splash screen -- this splash screen becomes the main window. * The splash screen closes and the 'real' UI is shown. The main window (splash screen) is now invalid. * I still have the Process object, an...
If you don't mind using the Windows API, you could use [`EnumWindowsProc`](http://msdn.microsoft.com/en-gb/library/windows/desktop/ms633498.aspx), and check each of the handles that that turns up using [`GetWindowThreadProcessId`](http://msdn.microsoft.com/en-gb/library/windows/desktop/ms633522.aspx) (to see that it's ...
@ageektrapped is on the right track, however `FindWindow` will not search child windows. For that you will need to use [`FindWindowEx`](http://pinvoke.net/default.aspx/user32/FindWindowEx.html)
.NET (C#): Getting child windows when you only have a process handle or PID?
[ "", "c#", ".net", "windows", "user-interface", "" ]
The documentation for the [round()](http://docs.python.org/lib/built-in-funcs.html) function states that you pass it a number, and the positions past the decimal to round. Thus it *should* do this: ``` n = 5.59 round(n, 1) # 5.6 ``` But, in actuality, good old floating point weirdness creeps in and you get: ``` 5.59...
I can't help the way it's stored, but at least formatting works correctly: ``` '%.1f' % round(n, 1) # Gives you '5.6' ```
Formatting works correctly even without having to round: ``` "%.1f" % n ```
round() doesn't seem to be rounding properly
[ "", "python", "floating-point", "rounding", "" ]
What is the best C++ IDE or editor for using on Windows? I use Notepad++, but am missing IntelliSense from Visual Studio.
I've found the latest release of NetBeans, which includes C/C++ support, to be excellent. <http://www.netbeans.org/features/cpp/index.html>
Um, that's because Visual Studio is the best IDE. Come back to the darkside.
Best C++ IDE or Editor for Windows
[ "", "c++", "windows", "" ]
Is there a way to embed a browser in Java? more specifically, is there a library that can emulate a browser?
Since JavaFX 2.0 you can use now [webview](http://docs.oracle.com/javafx/2.0/webview/jfxpub-webview.htm) ![enter image description here](https://i.stack.imgur.com/WUfqs.png)
I believe JWebPane is going to be the official way to embed a browser into a java app. Its based on the open sourced engine - WebKit, which is used in Apples Safari and Googles Chrome browsers.See [this blog](http://weblogs.java.net/blog/ixmal/archive/2008/05/introducing_jwe.html) for details.
Is there a way to embed a browser in Java?
[ "", "java", "browser", "cross-platform", "" ]
I know PHP scripts don't actually compile until they are run. However, say I want to create a small simple program and compile it to a binary without requiring the PHP binary. How could I do this? I've seen a few IDE's out there that would do this, but either they are all for windows or the Linux versions don't actual...
Check out [phc: the PHP compiler](https://github.com/pbiggar/phc) If you just want to run it like a script, you may not need to compile it per se, but just run it via the command line. [Read running PHP via the command line.](http://www.php.net/features.commandline)
There is this: <http://www.bambalam.se/bamcompile/> but that compiles to Windows bytecode. There are a few others, but all I have seen will compile for windows only. Few More: <http://www.nusphere.com/products/phpdock.htm> Edit: I almost forgot if your looking to make it work on linux without regard for window...
Compile a PHP script in Linux
[ "", "php", "linux", "" ]
I'm building a function to extend the `Enum.Parse` concept that * Allows a default value to be parsed in case that an Enum value is not found * Is case insensitive So I wrote the following: ``` public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum { if (string.IsNullOrEmpty(value)) re...
## This feature is finally supported in C# 7.3! The following snippet (from [the dotnet samples](https://github.com/dotnet/samples/blob/3ee82879284e3f4755251fd33c3b3e533f7b3485/snippets/csharp/keywords/GenericWhereConstraints.cs#L180-L190)) demonstrates how: ``` public static Dictionary<int, string> EnumNamedValues<T...
Since `Enum` Type implements `IConvertible` interface, a better implementation should be something like this: ``` public T GetEnumFromString<T>(string value) where T : struct, IConvertible { if (!typeof(T).IsEnum) { throw new ArgumentException("T must be an enumerated type"); } //... } ``` This wi...
Create Generic method constraining T to an Enum
[ "", "c#", "generics", "enums", "generic-constraints", "" ]
I have a swf with loads text into a Sprite that resizes based on the content put into - I'd like though for the ones that are longer than the page to have the browser use its native scroll bars rather than handle it in actionscript (very much like <http://www.nike.com/nikeskateboarding/v3/>...) I did have a look at th...
I've never done it that way around but I think [swffit](http://swffit.millermedeiros.com/) might be able to pull it off.
The trick is to use some simple JavaScript to resize the Flash DOM node: ``` function resizeFlash( h ) { // "flash-node-id" is the ID of the embedded Flash movie document.getElementById("flash-node-id").style.height = h + "px"; } ``` Which you call from within the Flash movie like this: ``` ExternalInterface...
How can I resize a swf during runtime to have the browser create html scrollbars?
[ "", "javascript", "apache-flex", "actionscript-3", "flash", "" ]
I'm looking for a builder for [HQL](http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html) in Java. I want to get rid of things like: ``` StringBuilder builder = new StringBuilder() .append("select stock from ") .append( Stock.class.getName() ) .append( " as stock where stock.id = ") .appen...
@[Sébastien Rocca-Serra](https://stackoverflow.com/questions/56843/looking-for-an-hql-builder-hibernate-query-language#57001) Now we're getting somewhere concrete. The sort of join you're trying to do isn't really possible through the Criteria API, but a sub-query should accomplish the same thing. First you create a ...
For a type-safe approach to your problem, consider [Querydsl](http://www.querydsl.com). The example query becomes ``` HQLQuery query = new HibernateQuery(session); List<Stock> s = query.from(stock, bonus) .where(stock.someValue.eq(bonus.id)) .list(stock); ``` Querydsl uses APT for code generation like JPA2 and s...
Looking for an HQL builder (Hibernate Query Language)
[ "", "java", "hibernate", "hql", "" ]
How can I have SQL repeat some set-based operation an arbitrary number of times without looping? How can I have SQL perform an operation against a range of numbers? I'm basically looking for a way to do a set-based for loop. I know I can just create a small table with integers in it, say from 1 to 1000 and then use it...
I think the very short answer to your question is to use WITH clauses to generate your own. Unfortunately, the big names in databases don't have built-in queryable number-range pseudo-tables. Or, more generally, easy pure-SQL data generation features. Personally, I think this is a **huge** failing, because if they did...
I created a SQL CLR table valued function that works great for this purpose. ``` SELECT n FROM dbo.Range(1, 11, 2) -- returns odd integers 1 to 11 SELECT n FROM dbo.RangeF(3.1, 3.5, 0.1) -- returns 3.1, 3.2, 3.3 and 3.4, but not 3.5 because of float inprecision. !fault(this) ``` Here's the code: ``` using System; us...
SQL set-based range
[ "", "sql", "sql-server", "" ]
As a general rule, I prefer using value rather than pointer semantics in C++ (ie using `vector<Class>` instead of `vector<Class*>`). Usually the slight loss in performance is more than made up for by not having to remember to delete dynamically allocated objects. Unfortunately, value collections don't work when you wa...
Since the objects of different classes will have different sizes, you would end up running into the slicing problem if you store them as values. One reasonable solution is to store container safe smart pointers. I normally use boost::shared\_ptr which is safe to store in a container. Note that std::auto\_ptr is not. ...
I just wanted to point out that vector<Foo> is usually more efficient than vector<Foo\*>. In a vector<Foo>, all the Foos will be adjacent to each other in memory. Assuming a cold TLB and cache, the first read will add the page to the TLB and pull a chunk of the vector into the L# caches; subsequent reads will use the w...
Can I have polymorphic containers with value semantics in C++?
[ "", "c++", "stl", "" ]
How to serve users a dynamically generated ZIP archive in Django? I'm making a site, where users can choose any combination of available books and download them as ZIP archive. I'm worried that generating such archives for each request would slow my server down to a crawl. I have also heard that Django doesn't current...
The solution is as follows. Use Python module [zipfile](https://docs.python.org/3/library/zipfile.html) to create zip archive, but as the file specify [StringIO](https://docs.python.org/3/library/io.html#io.StringIO) object (ZipFile constructor requires file-like object). Add files you want to compress. Then in your D...
Here's a Django view to do this: ``` import os import zipfile import StringIO from django.http import HttpResponse def getfiles(request): # Files (local path) to put in the .zip # FIXME: Change this (get paths from DB etc) filenames = ["/tmp/file1.txt", "/tmp/file2.txt"] # Folder name in ZIP archiv...
Serving dynamically generated ZIP archives in Django
[ "", "python", "django", "" ]
When interviewing college coops/interns or recent graduates it helps to have a Java programming question that they can do on a white board in 15 minutes. Does anyone have examples of good questions like this? A C++ question I was once asked in an interview was to write a string to integer function which is along the li...
Some stuff that has showed up on SO: * IsPalindrome(string s) * ReverseWordsInString(string s): "I know java" --> "java know I" Other stuff that springs to mind: * multiply a Vector with a Matrix (can this be done OO-Style?) * `echo` (yes, a simple clone of the unix tool) * `cat` (15 min should be enough, should wee...
Is there any reason why it has to be on a whiteboard? Personally, I'd rather sit them in front of a keyboard and have them write some code. Our test used to be a simple 100 (IIRC) line Swing text editor. We then broke it a few simple ways, some making the code not compile and some a little more subtle, and gave the can...
Good 15 minute Java question to ask recent college graduate
[ "", "java", "" ]
Do you normally set your compiler to optimize for maximum speed or smallest code size? or do you manually configure individual optimization settings? Why? I notice most of the time people tend to just leave compiler optimization settings to their default state, which with visual c++ means max speed. I've always felt t...
As a Gentoo user I have tried quite a few optimizations on the complete OS and there have been endless discussions on the [Gentoo forums](http://forums.gentoo.org/) about it. Some good flags for GCC can be found in the [wiki](http://gentoo-wiki.com/Safe_Cflags). In short, optimizing for size worked best on an old Pent...
I prefer to use minimal size. Memory may be cheap, **cache is not**.
How do you normally set up your compiler's optimization settings?
[ "", "c++", "c", "optimization", "compiler-optimization", "" ]
I want to parse some HTML in order to find the values of some attributes/tags etc. What HTML parsers do you recommend? Any pros and cons?
[NekoHTML](http://sourceforge.net/projects/nekohtml/), [TagSoup](http://home.ccil.org/~cowan/XML/tagsoup/), and [JTidy](http://sourceforge.net/projects/jtidy/) will allow you to parse HTML and then process with XML tools, like XPath.
I have tried [HTML Parser](http://htmlparser.sourceforge.net/) which is dead simple.
What HTML parsing libraries do you recommend in Java
[ "", "java", "html", "parsing", "html-content-extraction", "" ]
This question would probably apply equally as well to other languages with C-like multi-line comments. Here's the problem I'm encountering. I'm working with Java code in Eclipse, and I wanted to comment out a block of code. However, there is a string that contains the character sequence "\*/", and Eclipse thinks that t...
Eclipse is correct. There is no interpretation context inside a comment (no escaping, etc). See [JLS §3.7](http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#48125).
In Eclipse you can highlight the part of the source code you want to comment out and use the Ctrl+/ to single-line comment every line in the highlighted section - puts a "//" at the beginning of the lines. Or if you really want to block-comment the selection use the Ctrl+Shift+/ combination. It will detect the block c...
Do Java multi-line comments account for strings?
[ "", "java", "eclipse", "comments", "" ]
I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this: ``` import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", n...
This is called "parametrization". There are several tools that support this approach. E.g.: * [pytest's decorator](https://docs.pytest.org/en/latest/parametrize.html) * [parameterized](https://github.com/wolever/parameterized) The resulting code looks like this: ``` from parameterized import parameterized class Te...
**Using [unittest](https://docs.python.org/3/library/unittest.html) (since 3.4)** Since Python 3.4, the standard library `unittest` package has the `subTest` context manager. See the documentation: * [26.4.7. Distinguishing test iterations using subtests](https://docs.python.org/3/library/unittest.html#distinguishin...
How do you generate dynamic (parameterized) unit tests in Python?
[ "", "python", "unit-testing", "parameterized-unit-test", "" ]
For a situation like capturing text incrementally, for example if you were receiving all of the output.write calls when a page was rendering, and those were being appended into a textwriter over a stringbuilder. Is there a more efficient way to do this? Something that exists in dotnet already preferably? Especially if...
I think StringBuilder is the most efficient way to append text in .net. To be more efficient you can specify the initial size of the StringBuilder when you create it.
It depends on what you're doing with that text. If the concern is tracing or logging, I'd say your best bet is to use ETW (Event Tracing for Windows). It's a kernel-level tracing facility that's been built into Windows since Windows 2000 and it's much, much faster than doing file I/O. If you're not using .NET 2.0, yo...
Is there a more efficient text spooler than TextWriter/StringBuilder
[ "", "c#", ".net", "performance", "string", "data-structures", "" ]
I'm teaching myself Python and my most recent lesson was that [Python is not Java](http://dirtsimple.org/2004/12/python-is-not-java.html), and so I've just spent a while turning all my Class methods into functions. I now realise that I don't need to use Class methods for what I would done with `static` methods in Java...
Class methods are for when you need to have methods that aren't specific to any particular instance, but still involve the class in some way. The most interesting thing about them is that they can be overridden by subclasses, something that's simply not possible in Java's static methods or Python's module-level functio...
Factory methods (alternative constructors) are indeed a classic example of class methods. Basically, class methods are suitable anytime you would like to have a method which naturally fits into the namespace of the class, but is not associated with a particular instance of the class. As an example, in the excellent [...
What is the purpose of class methods?
[ "", "python", "class-method", "" ]
A simple question, but could someone provide sample code as to how would someone call a web service from within the JBoss Seam framework, and process the results? I need to be able to integrate with a search platform being provided by a private vendor who is exposing his functionality as a web service. So, I'm just lo...
There's roughly a gajillion HTTP client libraries (Restlet is quite a bit more than that, but I already had that code snippet for something else), but they should all provide support for sending GET requests. Here's a rather less featureful snippet that uses [HttpClient](http://hc.apache.org/httpclient-3.x/tutorial.htm...
``` import org.restlet.Client; import org.restlet.data.Protocol; import org.restlet.data.Reference; import org.restlet.data.Response; import org.restlet.resource.DomRepresentation; import org.w3c.dom.Node; /** * Uses YAHOO!'s RESTful web service with XML. */ public class YahooSearch { private static final String...
Calling a Web Service from Seam
[ "", "java", "seam", "" ]
What's a simple way to combine **feed** and **feed2**? I want the items from **feed2** to be added to **feed**. Also I want to avoid duplicates as **feed** might already have items when a question is tagged with both WPF and Silverlight. ``` Uri feedUri = new Uri("http://stackoverflow.com/feeds/tag/silverlight"); XmlR...
You can use LINQ to simplify the code to join two lists (don't forget to put System.Linq in your usings and if necessary reference System.Core in your project) Here's a Main that does the union and prints them to console (with proper cleanup of the Reader). ``` using System; using System.Collections.Generic; using Sys...
Well, one possibility is to create a new syndication feed that is a clone of the first feed, and then simply iterate through each post on the second one, check the first for its existence, and add it if it doesn't exist. Something along the lines of: ``` SyndicationFeed newFeed = feed.clone; foreach(SyndicationItem i...
Combining two SyndicationFeeds
[ "", "c#", "linq", ".net-3.5", "" ]
I have a `XmlDocument` in java, created with the `Weblogic XmlDocument` parser. I want to replace the content of a tag in this `XMLDocument` with my own data, or insert the tag if it isn't there. ``` <customdata> <tag1 /> <tag2>mfkdslmlfkm</tag2> <location /> <tag3 /> </customdata> ``` For example I want...
How about an XPath based approach? I like this approach as the logic is super-easy to understand. The code is pretty much self-documenting. If your xml document is available to you as an org.w3c.dom.Document object (as most parsers return), then you could do something like the following: ``` // get the list of custom...
How about an object oriented approach? You could deserialise the XML to an object, set the location value on the object, then serialise back to XML. [XStream](http://xstream.codehaus.org/tutorial.html) makes this really easy. For example, you would define the main object, which in your case is CustomData (I'm using p...
How to insert/replace XML tag in XmlDocument?
[ "", "java", "xml", "xquery", "" ]
How do you generate and analyze a thread dump from a running JBoss instance?
There is a JBoss-specific method that is slightly more user-friendly: <http://community.jboss.org/wiki/GenerateAThreadDumpWithTheJMXConsole> This is especially useful when you don't have direct access to the host machine (which "kill" would require).
<http://java.sun.com/developer/technicalArticles/Programming/Stacktrace/> ... "On UNIX platforms you can send a signal to a program by using the kill command. This is the quit signal, which is handled by the JVM. For example, on Solaris you can use the command kill -QUIT process\_id, where process\_id is the process ...
How do you generate and analyze a thread dump from a running JBoss instance?
[ "", "java", "multithreading", "dump", "" ]
I am attempting to use the .Net System.Security.SslStream class to process the server side of a SSL/TLS stream with client authentication. To perform the handshake, I am using this code: ``` SslStream sslStream = new SslStream(innerStream, false, RemoteCertificateValidation, LocalCertificateSelectionCallback); sslStr...
It does not look like this is currently possible using the .NET libraries. I solved it by using the Mono class library implementation of System.Security.SslStream, which gives better access to overriding the servers behavior during the handshake.
What the certificate validation is doing is validating all certificates in the chain. In order to truely do that it just contact the root store of each of those cerficates. If that's not something you want to happen you can deploy your own root store locally.
How to specify accepted certificates for Client Authentication in .NET SslStream
[ "", "c#", ".net", "ssl", "sspi", "" ]
I am working on a project that requires the manipulation of enormous matrices, specifically pyramidal summation for a copula calculation. In short, I need to keep track of a relatively small number of values (usually a value of 1, and in rare cases more than 1) in a sea of zeros in the matrix (multidimensional array)....
For C++, a map works well. Several million objects won't be a problem. 10 million items took about 4.4 seconds and about 57 meg on my computer. My test application is as follows: ``` #include <stdio.h> #include <stdlib.h> #include <map> class triple { public: int x; int y; int z; bool operator<(const...
The accepted answer recommends using strings to represent multi-dimensional indices. However, constructing strings is needlessly wasteful for this. If the size isn’t known at compile time (and thus `std::tuple` doesn’t work), `std::vector` works well as an index, both with hash maps and ordered trees. For `std::map`, ...
What is the best way to create a sparse array in C++?
[ "", "c++", "oop", "data-structures", "hash", "maps", "" ]
I am looking for a tool that can serialize and/or transform SQL Result Sets into XML. Getting dumbed down XML generation from SQL result sets is simple and trivial, but that's not what I need. The solution has to be database neutral, and accepts only regular SQL query results (no db xml support used). A particular cha...
With SQL Server you really should consider using the *FOR XML* construct in the query. If you're using .Net, just use a DataAdapter to fill a dataset. Once it's in a dataset, just use its .WriteXML() method. That breaks your DB->object->XML rule, but it's really how things are done. You might be able to work something...
Not that I know of. I would just roll my own. It's not that hard to do, maybe something like this: ``` #!/usr/bin/env jruby import java.sql.DriverManager # TODO some magic to load the driver conn = DriverManager.getConnection(ARGV[0], ARGV[1], ARGV[2]) res = conn.executeQuery ARGV[3] puts "<result>" meta = res.met...
Converting SQL Result Sets to XML
[ "", "sql", "xml", "" ]
In C# documentation tags allow you to produce output similar to MSDN. What are a list of allowable tags for use inside the /// (triple slash) comment area above classes, methods, and properties?
Check out [Great documentation on the various C# XML documentation tags.](http://web.archive.org/web/20100118163744/http://thoughtpad.net/alan-dean/cs-xml-documentation.html) (Go to the bottom to see the tags)
If you type this just above a method or class, intellisense should prompt you with a list of available tags: ``` /// < ```
What are the C# documentation tags?
[ "", "c#", "xml", "documentation", "" ]
I was asked this question in a job interview. The interviewer and I disagreed on what the correct answer was. I'm wondering if anyone has any data on this. Update: I should have mentioned that the use of shuffle() was strictly forbidden... sorry.
You could use the [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Knuth_shuffle).
``` shuffle($arr); ``` :) edit: I should clarify... my definition of best involves not just algorithm efficiency but code readability and maintainability as well. Using standard library functions means maintaining less code and reading much less too. Beyond that, you can get into year-long debates with PhD professors...
What is the best way to randomize an array's order in PHP without using the shuffle() function?
[ "", "php", "arrays", "random", "" ]
one of the most frequent requests I get is to create XY report for YZ App. These apps are normally built on PHP, so far I have manually created most of this reports, and while I enjoy the freedom of building it as I want, it usually becomes pretty tedious to calculate subtotals, averages, exporting to different formats...
The problem you're facing is solved by so-called Business Intelligence software. This software tends to be bloated and expensive, but if you know your way around them you will be able to crank out such reports in no time at all. I'm only familiar with one particular proprietary solution, which isn't too great either. ...
It depends on what kind of reports you're talking about. For example... site stats... you could install google analytics and the client could export whatever format they wanted.
report generation on php?
[ "", "php", "reporting", "" ]
How would you go about proving that two queries are functionally equivalent, eg they will always both return the same result set. --- As I had a specific query in mind when I was doing this, I ended up doing as @dougman suggested, over about 10% of rows the tables concerned and comparing the results, ensuring there w...
The best you can do is compare the 2 query outputs based on a given set of inputs looking for any differences. To say that they will always return the same results for all inputs really depends on the data. For Oracle one of the better if not best approaches (very efficient) is here (`Ctrl`+`F` Comparing the Contents ...
**1) Real equivalency proof with Cosette:** Cosette checks (with a proof) if 2 SQL query's are equivalent and counter examples when not equivalent. It's the only way to be absolutely sure, well almost ;) You can even throw in 2 query's on their website and check (formal) equivalence right away. Link to Cosette: <htt...
Proving SQL query equivalency
[ "", "sql", "oracle", "" ]
Maybe this is a dumb question, but is there any way to convert a boolean value to a string such that 1 turns to "true" and 0 turns to "false"? I could just use an if statement, but it would be nice to know if there is a way to do that with the language or standard libraries. Plus, I'm a pedant. :)
How about using the C++ language itself? ``` bool t = true; bool f = false; std::cout << std::noboolalpha << t << " == " << std::boolalpha << t << std::endl; std::cout << std::noboolalpha << f << " == " << std::boolalpha << f << std::endl; ``` UPDATE: If you want more than 4 lines of code without any console...
We're talking about C++ right? Why on earth are we still using macros!? C++ inline functions give you the same speed as a macro, with the added benefit of type-safety and parameter evaluation (which avoids the issue that Rodney and dwj mentioned. ``` inline const char * const BoolToString(bool b) { return b ? "true...
Converting bool to text in C++
[ "", "c++", "string", "boolean", "" ]
I'm developing a .NET 3.5 XBAP application that runs perfectly fine in FF3 and IE6/7 etc. I'm just wondering if its possible to get these to run under other browsers, specifically (as its in the limelight at the moment) Google Chrome.
XBAP applications do work in google chrome, however you have to set your environments PATH variable to the directory where xpcom.dll is located. for example SET PATH=PATH;"C:\Program Files\Mozilla Firefox"
At the moment, XBAPs do not work in Google Chrome. I've gotten it to run once, somehow, but every time there after I've received an error that the browser cannot locate xpcom.dll. Apparently this error occurs for more than just XBAP applications. From what I've read users will have to wait for a fix seeing as Chrome is...
XBAP Application, can these work in Google Chrome?
[ "", "c#", ".net", "google-chrome", "xbap", "" ]
What is the best C++ IDE for a \*nix envirnoment? I have heard the C/C++ module of Eclipse is decent as well as Notepad++ but beyond these two I have no real idea. Any thoughts or comments?
On Ubuntu, some the IDEs that are available in the repositories are: * [Kdevelop](http://www.kdevelop.org/) * [Geany](http://geany.uvena.de/) * [Anjuta](http://anjuta.sf.net/) There is also: * [Eclipse](http://eclipse.org) (Recommended you don't install from repositories, due to issues with file/folder permissions) ...
As a programmer who has been writing code under linux for many years, I simply cannot seem to move away from using Vim for writing code. Once you learn it, and learn some of its more advanced features (Code Folding, how to use ctags, how to work with multiple buffers effectively, etc) moving to another editor is very ...
Best C++ IDE for *nix
[ "", "c++", "ide", "" ]
I'm looking into sending regular automated text-messages to a list of subscribed users. Having played with Windows Mobile devices, I could easily implement this using the compact .Net framework + a device hooked up to usb and send the messages through this. I would like to explore other solutions like having a server o...
It really all depends on how many text messages you intend to send and how critical it is that the message arrives on time (and, actually arrives). ## SMS Aggregators For larger volume and good reliability, you will want to go with an SMS aggregator. These aggregators have web service API's (or SMPP) that you can use...
You can usually get an account with an sms service provider and send messages using an API (SOAP, resful http, smpp ....) A google search for sms service provider yeilds many results with varying costs. Here is an informative article [How to Choose an SMS Service Provider](http://www.developershome.com/sms/howToChoose...
What kind of technologies are available for sending text messages?
[ "", "c#", "mobile", "messaging", "" ]
I'm a long-time emacs user, and I'm now working about 1/2 time in Java. What are the best emacs libraries for 1. Debugging Java 2. Code Completion/Intellisense 3. Javadoc browsing ?
I've used [JDEE](http://jdee.sourceforge.net/) on several projects. It handles Code Completion. I've never used it for debugging or browsing docs, but it's a big step up from a basic text editor.
For javadoc I found <http://javadochelp.sourceforge.net/index.html> to be the best. Exuberant ctags is your best friend when it comes to navigation.
Best java tools for emacs
[ "", "java", "debugging", "emacs", "ide", "javadoc", "" ]
I have been reading through the [C++ FAQ](http://yosefk.com/c++fqa/) and was curious about the [`friend`](http://yosefk.com/c++fqa/friend.html) declaration. I personally have never used it, however I am interested in exploring the language. What is a good example of using `friend`? --- Reading the FAQ a bit longer I...
Firstly (IMO) don't listen to people who say `friend` is not useful. It IS useful. In many situations you will have objects with data or functionality that are not intended to be publicly available. This is particularly true of large codebases with many authors who may only be superficially familiar with different area...
At work we **use friends for testing code**, extensively. It means we can provide proper encapsulation and information hiding for the main application code. But also we can have separate test code that uses friends to inspect internal state and data for testing. Suffice to say I wouldn't use the friend keyword as an e...
When should you use 'friend' in C++?
[ "", "c++", "oop", "encapsulation", "friend", "" ]
Let's say the first N integers divisible by 3 starting with 9. I'm sure there is some one line solution using lambdas, I just don't know it that area of the language well enough yet.
Just to be different (and to avoid using a where statement) you could also do: ``` var numbers = Enumerable.Range(0, n).Select(i => i * 3 + 9); ``` **Update** This also has the benefit of not running out of numbers.
Using Linq: ``` int[] numbers = Enumerable.Range(9,10000) .Where(x => x % 3 == 0) .Take(20) .ToArray(); ``` Also easily parallelizeable using PLinq if you need: ``` int[] numbers = Enumerable.Range(9,10000) .AsParallel() //added this line .Where(x => x % 3 == 0) .Take(20) ...
What is the simplest way to initialize an Array of N numbers following a simple pattern?
[ "", "c#", "" ]
In C# is there a shorthand way to write this: ``` public static bool IsAllowed(int userID) { return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe ...); } ``` Like: ``` public static bool IsAllowed(int userID) { return (userID in Personnel.JohnDoe, Personnel.JaneDoe ...); } ``` I know I could a...
How about this? ``` public static class Extensions { public static bool In<T>(this T testValue, params T[] values) { return values.Contains(testValue); } } ``` Usage: ``` Personnel userId = Personnel.JohnDoe; if (userId.In(Personnel.JohnDoe, Personnel.JaneDoe)) { // Do something } ``` I can...
How about something like this: ``` public static bool IsAllowed(int userID) { List<int> IDs = new List<string> { 1,2,3,4,5 }; return IDs.Contains(userID); } ``` (You could of course change the static status, initialize the IDs class in some other place, use an IEnumerable<>, etc, based on your needs. The main poi...
Shorthand conditional in C# similar to SQL 'in' keyword
[ "", "c#", "lambda", "conditional-statements", "if-statement", "" ]
I have a table with an XML column. This column is storing some values I keep for configuring my application. I created it to have a more flexible schema. I can't find a way to update this column directly from the table view in SQL Management Studio. Other (INT or Varchar for example) columns are editable. I know I can ...
This is an old question, but I needed to do this today. The best I can come up with is to write a query that generates SQL code that can be edited in the query editor - it's sort of lame but it saves you copy/pasting stuff. Note: you may need to go into Tools > Options > Query Results > Results to Text and set the max...
I have a cheap and nasty workaround, but is ok. So, do a query of the record, i.e. ``` SELECT XMLData FROM [YourTable] WHERE ID = @SomeID ``` Click on the xml data field, which should be 'hyperlinked'. This will open the XML in a new window. Edit it, then copy and paste the XML back into a new query window: ``` UPDA...
How to easily edit SQL XML column in SQL Management Studio
[ "", "sql", "sql-server", "xml", "" ]
I want to put a copyright notice in the footer of a web site, but I think it's incredibly tacky for the year to be outdated. How would I make the year update automatically with PHP
You can use either [date](http://php.net/manual/en/function.date.php) or [strftime](http://php.net/manual/en/function.strftime.php). In this case I'd say it doesn't matter as a year is a year, no matter what (unless there's a locale that formats the year differently?) For example: ``` <?php echo date("Y"); ?> ``` On...
``` <?php echo date("Y"); ?> ```
How do I use PHP to get the current year?
[ "", "php", "date", "" ]
Is there an easy way to set the zoom level for a windows form in C#? In VBA there was a zoom property of the form.
There is no way (that I know of) to do what you ask with typical WinForms. If you're doing custom painting/drawing, you can zoom that by using a zoom transform, but so far as I know there is no "Zoom" property for the form in the entire world of .NET and native Windows/C++ APIs combined. You could probably rig someth...
I had the same problem and I solved it this way in c#. Code goes on Form load ``` float scaleX = ((float)Screen.PrimaryScreen.WorkingArea.Width / 1024); float scaleY = ((float)Screen.PrimaryScreen.WorkingArea.Height / 768); SizeF aSf = new SizeF(scaleX, scaleY); this.Scale(aSf); ``` This "more or less" scales form an...
Zoom for a windows form in C#
[ "", "c#", "winforms", "" ]
What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app.
XHTML is easy, use [lxml](http://lxml.de/validation.html). ``` from lxml import etree from StringIO import StringIO etree.parse(StringIO(html), etree.HTMLParser(recover=False)) ``` HTML is harder, since there's traditionally not been as much interest in validation among the HTML crowd (run StackOverflow itself throug...
[PyTidyLib](http://countergram.github.io/pytidylib/) is a nice python binding for HTML Tidy. Their example: ``` from tidylib import tidy_document document, errors = tidy_document('''<p>f&otilde;o <img src="bar.jpg">''', options={'numeric-entities':1}) print document print errors ``` Moreover it's compatible with ...
Validate (X)HTML in Python
[ "", "python", "html", "validation", "xhtml", "" ]
Is there a difference between `NULL` and `null` in PHP? Sometimes they seem to be interchangeable and sometimes not. edit: for some reason when I read the documentation linked to in the answer (before posting this question) I read it as "case sensitive" instead of "case insensitive" which was the whole reason I posted...
Null is case insensitive. From the [documentation](https://www.php.net/manual/en/language.types.null.php): > There is only one value of type null, and that is the **case-insensitive** keyword NULL.
There is no difference. Same type just its a **case insensitive** keyword. Same as `True`/`False` etc...
Difference between NULL and null in PHP
[ "", "php", "null", "" ]
Normally I would just use: ``` HttpContext.Current.Server.UrlEncode("url"); ``` But since this is a console application, `HttpContext.Current` is always going to be `null`. Is there another method that does the same thing that I could use?
Try this! ``` Uri.EscapeUriString(url); ``` Or ``` Uri.EscapeDataString(data) ``` No need to reference System.Web. **Edit:** Please see [another](https://stackoverflow.com/a/34189188/7391) SO answer for more...
I'm not a .NET guy, but, can't you use: ``` HttpUtility.UrlEncode Method (String) ``` Which is described here: [HttpUtility.UrlEncode Method (String) on MSDN](http://msdn.microsoft.com/en-us/library/4fkewx0t.aspx)
UrlEncode through a console application?
[ "", "c#", ".net", "console", "" ]
I wrote an application that currently runs against a local instance of MySql. I would like to centralize the DB somewhere on the Net, and share my application. But, I'm cheap, and don't want to pay for it. Does anyone know of a free on-line relational DB service that I could connect to via C#?
What about <http://www.freesql.org> ? Seems like you can't be too picky when you're asking for free, and this seems to offer something.
Oops, didn't read the question properly that time! :P Haven't tried this yet, and their site says they had had a major crash recently, but it looks promising: <http://www.freesql.org/>
Anyone know of an on-line free database?
[ "", "c#", "database", "" ]
For reasons I won't go into, I wish to ban an entire company from accessing my web site. Checking the remote hostname in php using gethostbyaddr() works, but this slows down the page load too much. Large organizations (eg. hp.com or microsoft.com) often have blocks of IP addresses. Is there anyway I get the full list, ...
How about an .htaccess: ``` Deny from x.x.x.x ``` if you need to deny a range say: 192.168.0.x then you would use ``` Deny from 192.168.0 ``` and the same applies for hostnames: ``` Deny from sub.domain.tld ``` or if you want a PHP solution ``` $ips = array('1.1.1.1', '2.2.2.2', '3.3.3.3'); if(in_array($_SERVER[...
If you're practicing safe webhosting, then you have a firewall. Use it. Large companies have blocks of IP addresses, but even smaller companies rarely change their IP. So there's an easy way to do this without reducing your performance: Every month do a reverse lookup on all the IPs in your log and then put all the I...
How can I ban a whole company from my web site?
[ "", ".net", "php", "apache", "" ]