Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
We are developing a web application that will be sold to many clients. There is already one client (a bank) which has decided that it will buy the product once it is ready. Unfortunately due to some miscommunication it came out rather late that the only browser they use is IE6. The application was already started with ... | <https://developer.yahoo.com/blogs/ydn/high-performance-sites-rule-7-avoid-css-expressions-7202.html>
Turns out you might want to avoid using these, they are dangerous. | Expressions are re-evaluated on many page events, which has the potential to slow down entire page performance when used too liberally. (And yet still, they can't respond to all events that might cause them to need re-evaluating.)
MS have admitted expression() was a mistake, and are [removing it from future browsers](... | IE6 performance with CSS expressions | [
"",
"javascript",
"css",
"performance",
"internet-explorer-6",
"css-expressions",
""
] |
I want to load and draw pdf files graphically using C#. I don't need to edit them or anything, just render them at a given zoom level.
The pdf libraries I have found seem to be focussed on generation. How do I do this?
Thanks. | There are a few other choices in case the Adobe ActiveX isn't what you're looking for (since Acrobat must be present on the user machine and you can't ship it yourself).
For creating the PDF preview, first have a look at some other discussions on the subject on StackOverflow:
* [How can I take preview of documents?](... | Google has open sourced its excellent PDF rendering engine - [PDFium](https://code.google.com/p/pdfium/) - that it wrote with Foxit Software.
There is a C# nuget package called [PdfiumViewer](https://github.com/Bluegrams/PdfiumViewer) which gives a C# wrapper around PDFium and allows PDFs to be displayed and printed.
... | How to render pdfs using C# | [
"",
"c#",
"pdf",
"drawing",
"rendering",
""
] |
I'm looping through a list of items, and I'd like to get a request parameter based on the item's index.
I could easily do it with a scriptlet as done below, but I'd like to use expression language.
```
<c:forEach var="item" items="${list}" varStatus="count">
<!-- This would work -->
<%=request.getParameter("ite... | ```
<c:set var="index" value="item_${count.index}" />
${param[index]}
```
Unfortunately, + doesn't work for strings like in plain Java, so
```
${param["index_" + count.index]}
```
doesn't work ;-( | There is a list of implicit objects in the [Expression Language documentation](http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPIntro7.html#wp71043) section of the J2EE 1.4 documentation. You're looking for *param*. | How do I dynamically access request parameters with JSP EL? | [
"",
"java",
"jsp",
"jstl",
"el",
""
] |
Problem statement: Implement a plug-in system that allows the associated assemblies to be overwritten (avoid file locking). In .Net, specific assemblies may not be unloaded, only entire AppDomains may be unloaded.
I'm posting this because when I was trying to solve the problem, every solution made reference to using m... | 1. Check if the assembly is already loaded (to avoid memory leaks caused by loading the same assembly over and over again).
2. If its not loaded, read the assembly into a byte array. This will prevent locking the file.
3. Supply the byte array as an arguement to Assembly.Load
The following code assumes you know the Fu... | If you want to isolate your addins, you must...
1. Create a type that extends
MarshallByRefObject which will
interact with your addins (lets call
it FOOMASTER)
2. Create a new appdomain (lets call it
addinLand)
3. Call
addinLand.CreateInstanceAndUnwrap to
create an instance of FOOMASTER in
addinLa... | How do I implement .net plugins without using AppDomains? | [
"",
"c#",
".net",
"iis",
"assemblies",
"appdomain",
""
] |
I have a long snippet of HTML I want some javascript variable to equal and for maintainability I want to store it with actual newlines instead of adding \n (or as it is HTML just omitting newline characters). In Python I would do something like:
```
largeString = """Hello
This is long!"""
```
And that would work perf... | Put a \ at the end of each line. Alternatively store it in a div with display:none and then use .html() to retrieve it | JavaScript doesn't support multi-line strings in the same manner.
You can use `\` to escape a newline for your script, but this is only for developer reading as it won't stay with the string (and most validators will throw errors for it). To keep a newline with the string, you'll still be required to use `\n`.
If you... | Multiline JavaScript Text | [
"",
"javascript",
"html",
"newline",
""
] |
A coworker of mine thought of a great way to visualize a lot of the data we work with in our user-end applications, but we're not aware of many available sdk's or apis that hook in.
We're trying to recreate in essence, the "Magic-Wall" of CNN. We would like to be able to show trends across the country in a 'heat-map' ... | We ended up going with [SharpMap](http://www.codeplex.com/SharpMap). | Hi you can take a look at Telogis GeoBase C# SDK, support WPF, WinForms and there is an XML/SOAP server for webservice implementations.
<http://dev.telogis.com/>
(I work for Telogis) | Powerful .NET Map APIs? | [
"",
"c#",
".net",
"mapping",
"gis",
""
] |
I've got a web application that controls which web applications get served traffic from our load balancer. The web application runs on each individual server.
It keeps track of the "in or out" state for each application in an object in the ASP.NET application state, and the object is serialized to a file on the disk w... | You should only be using Mutexes if you need **cross-process synchronization**.
> Although a mutex can be used for
> intra-process thread synchronization,
> using Monitor is generally preferred,
> because monitors were designed
> specifically for the .NET Framework
> and therefore make better use of
> resources. In co... | If some of the file operations fail, the lock will not be released. Most probably that is the case. Put the file operations in try/catch block, and release the lock in the finally block.
Anyway, if you read the file in your Global.asax Application\_Start method, this will ensure that noone else is working on it (you s... | C# - Locking issues with Mutex | [
"",
"c#",
"asp.net",
"locking",
"mutex",
""
] |
Why does the compiler say "a constant value is required" for the first case...the second case works fine...
```
switch (definingGroup)
{
case Properties.Settings.Default.OU_HomeOffice:
//do something
break;
case "OU=Home Office":
//do something
break;
default:
... | `Properties.Settings.Default.OU_HomeOffice` isn't a constant string - something known at compile time. The C# switch statement requires that every case is a compile-time constant.
(Apart from anything else, that's the only way it can know that there won't be any duplicates.)
See section 8.7.2 of the C# 3.0 spec for m... | This is because the value cannot be determined at compile time (as it is coming out of a configuration setting). You need to supply values that are known at the time the code is compiled (constants). | switch statement in C# and "a constant value is expected" | [
"",
"c#",
"visual-studio",
""
] |
Sorry in advance, I'm struggling a bit with how to explain this... :)
Essentially, I've got a typical windows coordinate system (the Top, Left is 0,0). If anybody's familiar with the haversine query, [like in SQL](http://forums.mysql.com/read.php?10,238858,238858), it can get all points in a radius based on latitude a... | Use Pythagoras:
```
distance = sqrt(xDifference^2 + yDifference^2)
```
Note that '^' in this example means "to the power of" and not C's bitwise XOR operator. In other words the idea is to square both differences. | Straightforward approach:
You can calculate the distance between to points using the [Pythagorean theorem](http://en.wikipedia.org/wiki/Pythagorean_theorem#Distance_in_Cartesian_coordinates):
```
deltaX = x1 - x2
deltaY = y1 - y2
distance = square root of (deltaX * deltaX + deltaY * deltaY)
```
Given point `x1,y1`, ... | (C++) Need to figure out all points within a radius using reg. 2D windows coord. system | [
"",
"c++",
"algorithm",
"visual-c++",
""
] |
Ok, so I wanted to get opinions on this topic.
I have a dumb data object - CustomerOrder.
CustomerOrder has a price and a quantity but also has a TotalCash property (price \* quantity). so I have a totalCash property but I dont want to put the calculation into the object directly because that would be breaking the du... | In the same situation I would break the "dumb data object rule" since I don't expect that particular calculation to change often. I'd probably implement it as a getter.
For more complex scenarios, it makes sense to create an OrderCalculator class that takes in order-related classes and can perform all sorts of calcula... | I understand the rationale of keeping your data objects separate from your business logic. Using LINQ with designer generated classes, I feel comfortable extending the generated class with a partial class implementation that contains the business logic. I feel that this is enough separation for my needs. If this doesn'... | Data modeling question - separation of data and calculation and accessor logic | [
"",
"c#",
"model-view-controller",
""
] |
I need a library that can detect objects in an image (uses edge detection). This is NOT related to captchas. I am working on an MTGO bot that uses OCR and that works in any screen resolution. In order for it to port to any screen resolution my idea is to scan down narrow range on a results page (the cards that a player... | If you don't know of the [OpenCV](http://sourceforge.net/projects/opencvlibrary) collection of examples, then they could help you in the right direction... there's also [Camellia](http://camellia.sourceforge.net/index.html) which doesn't use "edge detection" per-se but could get the results you need with a bit of work. | Its not cheap, but I've used the Intel Processing Primitives, and was very impressed with their performance. They work on Intel and AMD processors, as well as Windows and Linux | Image Processing Library for C++ | [
"",
"c++",
"image-processing",
"ocr",
""
] |
[Wikipedia](http://en.wikipedia.org/wiki/Join_(SQL)#) states:
"In practice, explicit right outer joins are rarely used, since they can always be replaced with left outer joins and provide no additional functionality."
Can anyone provide a situation where they have preferred to use the RIGHT notation, and why?
I can't... | The only reason I can think of to use RIGHT OUTER JOIN is to try to make your SQL more self-documenting.
You might possibly want to use left joins for queries that have null rows in the dependent (many) side of one-to-many relationships and right joins on those queries that generate null rows in the independent side.
... | I've never used `right join` before and never thought I could actually need it, and it seems a bit unnatural. But after I thought about it, it could be really useful in the situation, when you need to outer join one table with intersection of many tables, so you have tables like this:
" - on line 16 the... | You debug javascript in IE6 with:-
[Microsoft Script Debugger](http://www.microsoft.com/downloads/details.aspx?familyid=2F465BE0-94FD-4569-B3C4-DFFDF19CCD99&displaylang=en)
The [QuirksMode](http://www.quirksmode.org/) website is useful site to determine which bits of CSS is implemented in what way by which browser. N... | You can try [Companion JS](http://www.my-debugbar.com/wiki/CompanionJS/HomePage). It is pretty good with respect to debugging. It requires Microsoft Script Debugger as well.
Companion JS thankfully supports "console.log" (via firebug). It is free tool. [Debug-bar](http://www.debugbar.com/) is a good CSS-DOM-Javascript... | debugging javascript for IE6 | [
"",
"javascript",
"css",
"debugging",
"internet-explorer-6",
"cross-browser",
""
] |
Imagine that you have several links on a page. When you clicked, a div gets updated via AJAX. The updated div includes data from the database.
According to this scenario, every time a link is clicked, the date is grabbed from the database and injected into the div.
Would you...
1. support this scenario or...
2. woul... | depends... is the content going to change? If so... Ajax every time.
If not? Ajax once(or zero times if posible) | If the data you are retrieving is changed regularly and needs to be up to date, I would choose option 1, If not, I would choose option 2 and that way opt to reduce network traffic and increase performance.
You could even make option 3 and render the data (in hidden divs) when the page loads, that way you wouldnt need ... | ajax in each time or load everything at once | [
"",
"javascript",
"jquery",
"css",
"ajax",
"dom",
""
] |
Our web page is only available internally in our company and we am very intrested in being able to offer interactive .net usercontrols on our departments website in the **.Net 2.0** enviorment. I have been successful with embeding the object as so:
```
<object id="Object1" classid="http:EmbedTest1.dll#EmbedTest1.UserC... | 1. Not out-dated so much as rarely used, and IE-only. If you want web-like deployment for desktop apps, use ClickOnce. If you want C# code that runs in the browser without security issues, use Silverlight. You could also look at XBAPs, which are sandboxed WPF apps that run in the browser, works on IE and Firefox, but r... | If the things that you are doing with the Windows Controls could be done with ASP.NET web controls instead, I recommend that you consider switching. You'll have much better control over the exchange of info from the client to the server. | c# hosting a usercontrol in IE | [
"",
"c#",
"internet-explorer",
".net-2.0",
"user-controls",
""
] |
Is it possible to make a public method private in a subclass? I don't want other classes extending this one to be able to call some of the methods. Here is an example:
```
class A:
def __init__(self):
#do something here
def method(self):
#some code here
class B(A):
def __init__(self):
... | Python is distributed as source. The very idea of a private method makes very little sense.
The programmer who wants to extend `B`, frustrated by a privacy issue, looks at the source for `B`, copies and pastes the source code for `method` into the subclass `C`.
What have you gained through "privacy"? The best you can... | Contrary to popular fashion on this subject, there **are** legitimate reasons to have a distinction between public, private, and protected members, whether you work in Python or a more traditional OOP environment. Many times, it comes to be that you develop auxiliary methods for a particularly long-winded task at some ... | Making a method private in a python subclass | [
"",
"python",
"oop",
"inheritance",
""
] |
I have a very very simple SQL string that MS Access doesn't seem to like.
> Select Top 5 \* From news\_table Order By news\_date
This is returning ALL rows from the news\_table not just the Top 5.
I thought this was a simple SQL statement, apparently it is not.
Any fixes or idea as to why this is not working? Thank... | Does this do the trick?
```
select top 5 *
from (select * from news_table order by news_date)
```
I don't know why the original doesn't work. Maybe it's a quirk with Access.
Edit: Business rules weren't specified. I didn't fully understand that the goal was to rank the table first and get the top 5 dates. It could ... | Select Top n selects all records where records are equal, that is, if you select Top 2 and you have 20 date1 and 20 date2, 40 records will be selected.
If there is a keyfield,
```
Select Top 5 * Order By KeyField
```
Should return 5 records, because keyfield is unique. | Why doesn't Select Top 5 From news_table order by news_date work? | [
"",
"sql",
"ms-access",
""
] |
I want to cleanup some javascript files and reformat them with nice indents, etc,
Are there recommendations for utilities to do this under Windows? | [Beautify Javascript](http://elfz.laacz.lv/beautify/) is a good, simple option.
(Oops. Thought I grabbed the link for the app, not the home page.) ;) | Try the online [JavaScript Tidy](http://www.howtocreate.co.uk/tutorials/jsexamples/JSTidy.html)
> Several attempts have been made to
> produce programs to reformat code, but
> these often fail to cope with
> situations such as '{', '}' or ';'
> characters inside strings, regular
> expressions, or comments, so **virtua... | Is there a windows utility similar to HTML Tidy for Javascript? | [
"",
"javascript",
"editor",
"code-formatting",
""
] |
What does it mean to call a class like this:
```
class Example
{
public:
Example(void);
~Example(void);
}
int main(void)
{
Example ex(); // <<<<<< what is it called to call it like this?
return(0);
}
```
Like it appears that it isn't calling the default constructor in that case. Can someone give a reason wh... | Currently you are trying to call the default constructor like so.
```
Example ex();
```
This is not actually calling the default constructor. Instead you are defining a function prototype with return type Example and taking no parameters. In order to call the default constructor, omit the ()'s
```
Example ex;
``` | This declares a function prototype for a function named `ex`, returning an `Example`! You are *not* declaring and initializing a variable here. | C++ Question about default constructor | [
"",
"c++",
"class",
""
] |
I added an XML file as an embedded resource in my class library by using the accessing the project properties in Visual Studio and then Resources | Add Resource | Add Existing File...
I've tried to access the file using the following code, but I keep getting a null reference returned. Anyone have any ideas?
```
var p... | The [MSDN page for GetManifestResourceStream](http://msdn.microsoft.com/en-us/library/xc4235zt.aspx) makes this note:
> This method returns a null reference
> (Nothing in Visual Basic) if a private
> resource in another assembly is
> accessed and the caller does not have
> ReflectionPermission with the
> ReflectionPer... | I find it much easier to use the "Resources" tab of the project's properties dialog in Visual Studio. Then you have a generated strongly typed reference to your resource through:
```
Properties.Resources.Filename
``` | How can I retrieve an embedded xml resource? | [
"",
"c#",
"asp.net",
"resources",
"assemblies",
""
] |
Is it possible to create a cursor from an image and have it be semi-transparent?
I'm currently taking a custom image and overylaying the mouse cursor image. It would be great if I could make this semi-transparent, but not necessary. The sales guys love shiny.
Currently doing something like this:
```
Image cursorImag... | I've tried following example, and it was working fine...
```
public struct IconInfo
{
public bool fIcon;
public int xHotspot;
public int yHotspot;
public IntPtr hbmMask;
public IntPtr hbmColor;
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bo... | On the top of my head (I would try that first):
1. create new bitmap with same size as original, but with ARGB structure
2. drawimage: existing bitmap to the new bitmap
3. access raw bitmap data, and replace A bytes with 128
You should have nice semitransparent bitmap there.
If performance allows, you can scan for f... | Create a semi-transparent cursor from an image | [
"",
"c#",
"winforms",
"transparency",
"mouse-cursor",
""
] |
Very similar to [this question](https://stackoverflow.com/questions/157646/best-way-to-encode-text-data-for-xml), except for Java.
What is the recommended way of encoding strings for an XML output in Java. The strings might contain characters like "&", "<", etc. | Very simply: use an XML library. That way it will actually be *right* instead of requiring detailed knowledge of bits of the XML spec. | As others have mentioned, using an XML library is the easiest way. If you do want to escape yourself, you could look into [`StringEscapeUtils`](https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringEscapeUtils.html) from the [Apache Commons Lang](http://commons.apache.org/lan... | Best way to encode text data for XML in Java? | [
"",
"java",
"xml",
"encoding",
""
] |
```
#include "iostream"
class A {
private:
int a;
public :
A(): a(-1) {}
int getA() {
return a;
}
};
class A;
class B : public A {
private:
int b;
public:
B() : b(-1) {}
int getB() {
... | Well, `std::auto_ptr<B>` is not derived from `std::auto_ptr<A>`. But `B` is derived from `A`. The auto\_ptr does not know about that (it's not that clever). Looks like you want to use a shared ownership pointer. `boost::shared_ptr` is ideal, it also provides a dynamic\_pointer\_cast:
```
boost::shared_ptr<A> a = new A... | dynamic cast doesn't work that way. `A : public B` does not imply `auto_ptr<A> : public auto_ptr<B>`. This is why boost's `shared_ptr` provides `shared_dynamic_cast`. You could write an `auto_ptr` dynamic cast though:
```
template<typename R, typename T>
std::auto_ptr<R> auto_ptr_dynamic_cast(std::auto_ptr<T>& in) {
... | Why does this dynamic_cast of auto_ptr fail? | [
"",
"c++",
"casting",
""
] |
Python for Windows by default comes with IDLE, which is the barest-bones IDE I've ever encountered. For editing files, I'll stick to emacs, thank you very much.
However, I want to run programs in some other shell than the crappy windows command prompt, which can't be widened to more than 80 characters.
IDLE lets me r... | For an interactive interpreter, nothing beats [IPython](http://ipython.scipy.org/). It's superb. It's also free and open source. On Windows, you'll want to install the readline library. Instructions for that are on the IPython installation documentation.
[Winpdb](http://winpdb.org/) is my Python debugger of choice. It... | You can easily widen the Windows console by doing the following:
* click the icon for the console window in the upper right
* select **Properties** from the menu
* click the **Layout** tab
* change the **Window Size** > Width to 140
This can also be saved universally by changing the **Defaults** on the menu. | Cleanest way to run/debug python programs in windows | [
"",
"python",
"windows",
"python-idle",
""
] |
I am having problems with my JScript code. I am trying to loop through all of the rows in a table and add an `onclick` event. I can get the `onclick` event to add but have a couple of problems.
The first problem is that all rows end up getting set up with the wrong parameter for the `onclick` event.
The second proble... | When a function is called in javascript, the first thing that happens is that the interpreter sets the scope chain to the state it was in when the function was defined. In your case the scope chain looks like:
```
GLOBAL
|
CAll addTableEvents
|
CALL onclick
```
So when the variable *orderID* is stumbled... | Why not attach the event handler to the table and grab the rowindex of the cell that fired the click event inside the click handler. | Javascript Onclick with Table Rows | [
"",
"javascript",
"onclick",
"dom-events",
""
] |
Why is it impossible to have a reference to void? The only thing I found in the C++ Standard is this line, at **8.3.2.1**
> A declarator that specifies the type "reference to *cv* void" is ill-formed.
Why is it that way? Why can't I write a "generic" function that accept a `void&`?
Just to be clear, I have no useful... | If you did have a reference to void, what would you do with it? It wouldn't be a number, or a character, or a pointer, or anything like that. Your hypothetical generic function couldn't perform any operation on it, except taking its address (and not its size).
"void" has two uses: to disclaim any knowledge of type (as... | OK, one thing is bugging me about this. The idea of a `void*`, as mentioned above, is that you still have a valid variable containing an address, but the type is being ignored. This seems allowable since we can still work with the address data - the type is somewhat superfluous (or less important) in this context. Dere... | Why is it impossible to have a reference-to-void? | [
"",
"c++",
"reference",
"void-pointers",
""
] |
What's the purpose of implementing the IDisposable interface? I've seen some classes implementing it and I don't understand why. | If your class creates unmanaged resources, then you can implement IDisposable so that these resources will be cleaned up properly when the object is disposed of. You override Dispose and release them there. | When your classes makes use of some system resource, it's the class' responsibility to make sure the resource is freed too. By .Net design you're supposed to do that in the Dispose method of the class. The IDisposable interface marks that your class needs to free resource when it's no longer in use, and the Dispose met... | What's the purpose of implementing the IDisposable interface? | [
"",
"c#",
"idisposable",
""
] |
I'm working on a customer's website, and they've asked for a shopping cart. They need to use securetrading.net for the payment, so I don't need to ask for any credit card details. All I need to do is keep track of the items in their cart.
I've read about using PHP sessions, but I'm concerned about security there. Is t... | There is tutorial for simple/small php/MySQL cart that keeps cart status in sessions, there is even downloadable demo code and online demo.
<http://v3.thewatchmakerproject.com/journal/276/building-a-simple-php-shopping-cart>
I used it when full blown online shoping programs were just that "over blown". Same as you th... | I'd use a prefab open-source solution. You really don't want to let in silly security issues when you're dealing with other people's money.
[Magento](http://www.magentocommerce.com) comes to mind. It's certainly the slickest I've seen in a while... And there appears to be securetrading support if [you hack it in yours... | Best way to implement shopping cart using PHP/MySQL | [
"",
"php",
"shopping-cart",
""
] |
I have a stored proc that processes a large amount of data (about 5m rows in this example). The performance varies wildly. I've had the process running in as little as 15 minutes and seen it run for as long as 4 hours.
For maintenance, and in order to verify that the logic and processing is correct, we have the SP bro... | Are you able to determine whether there are any locking problems? Are you running the SP in sufficiently small transactions?
Breaking it up into subprocedures should have no benefit.
Somebody should be concerned about your productivity, working without basic optimization resources. That suggests there may be other po... | Grab the free copy of "Dissecting Execution Plan" in the link below and maybe you can pick up a tip or two from it that will give you some idea of what's really going on under the hood of your SP.
<http://dbalink.wordpress.com/2008/08/08/dissecting-sql-server-execution-plans-free-ebook/> | Stored Procedure Execution Plan - Data Manipulation | [
"",
"sql",
"sql-server",
"stored-procedures",
"sql-execution-plan",
""
] |
Here's a simplified version of my class:
```
public abstract class Task
{
private static object LockObject = new object();
protected virtual void UpdateSharedData() { }
protected virtual void UpdateNonSharedData() { }
public void Method()
{
lock(LockObject)
{
UpdateSharedD... | What if you defined an abstract Task and a IHasSharedData interface, then in Method you check if the derived Task implements IHasSharedData before doing the lock. Only classes that implement the interface need wait. I realize that this avoids answering the actual question, but I think it would be a cleaner solution tha... | You can do this check with a smidge of reflection:
```
bool IsUpdateSharedDataOverridden()
{
Type t = this.GetType();
MethodInfo m = subType.GetMethod("UpdateSharedData");
return m.DeclaringType == t && m.GetBaseDefinition().DeclaringType == typeof(Task);
}
``` | Can a base class determine if a derived class has overridden a virtual member? | [
"",
"c#",
"reflection",
"inheritance",
"overriding",
""
] |
I have a twenty byte hex hash that I would like to store in a django model.
If I use a text field, it's interpreted as unicode and it comes back garbled.
Currently I'm encoding it and decoding it, which really clutters up the code,
because I have to be able to filter by it.
```
def get_changeset(self):
return bin... | I'm assuming if you were writing raw SQL you'd be using a Postgres bytea or a MySQL VARBINARY. There's a [ticket with a patch](http://code.djangoproject.com/ticket/2417) (marked "needs testing") that purportedly makes a field like this (Ticket 2417: Support for binary type fields (aka: bytea in postgres and VARBINARY i... | Starting with 1.6, Django has [`BinaryField`](https://docs.djangoproject.com/en/1.11/ref/models/fields/#binaryfield) allowing to store raw binary data. However, for hashes and other values up to 128 bits it's more efficient (at least with the PostgreSQL backend) to use [`UUIDField`](https://docs.djangoproject.com/en/1.... | Storing a binary hash value in a Django model field | [
"",
"python",
"django",
"encoding",
"django-models",
"binary-data",
""
] |
Usually when defining a DAO, you would have a setter for the datasource on the DAO object.
My problem is that our datasource varies dynamically based on the request to the server. i.e. every request can access different database instance.
The request holds logical properties, that later can be used to retrieve the con... | It sounds like your problem is that you are creating a single DAO instance for your application. You either need to create a separate instance for each datasource (maybe making some kind of dao controller to manage it all for you) or possibly allow your methods in your dao to be static and pass all information about ho... | Your problem is a little confusing. Having one DAO access multiple different datasources would seem to be a maintenance nightmare. As a result, you should define one DAO interface containing all the methods you would want to call. For each database you are connecting to I would construct a new class that implements you... | How to design DAOs when the datasource varies dynamically | [
"",
"java",
"spring",
"dao",
""
] |
In javascript, what is the best way to parse an INT from a string which starts with a letter (such as "test[123]")? I need something that will work for the example below.
My JS:
```
$(document).ready(function() {
$(':input').change( function() {
id = parseInt($(this).attr("id")); //fails for the data be... | You could use a regular expression to match the number:
```
$(this).attr("id").match(/\d+/)
``` | ```
parseInt(input.replace(/[^0-9-]/,""),10)
``` | Parsing an Int from a string in javascript | [
"",
"javascript",
"jquery",
""
] |
We have a crystal report that we need to send out as an e-mail, but the HTML generated from the crystal report is pretty much just plain ugly and causes issues with some e-mail clients. I wanted to export it as rich text and convert that to HTML if it's possible.
Any suggestions? | I would check out this tool on CodeProject RTFConverter. This guy gives a great breakdown of how the program works along with details of the conversion.
[Writing Your Own RTF Converter](http://www.codeproject.com/KB/recipes/RtfConverter.aspx "Writing Your Own RTF Converter") | There is also a sample on the MSDN Code Samples gallery called [Converting between RTF and HTML](http://matthewmanela.com/blog/converting-rtf-to-html/) which allows you to convert between HTML, RTF and XAML. | Convert Rtf to HTML | [
"",
"c#",
"html",
"rtf",
""
] |
I wondering what the "best practice" way (in C#) is to implement this xpath query with LINQ:
```
/topNode/middleNode[@filteringAttribute='filterValue']/penultimateNode[@anotherFilterAttribute='somethingElse']/nodesIWantReturned
```
I would like an IEnumerable list of the 'nodesIWantReturned', but only from a certain ... | A more *verbal* solution:
```
var nodesIWantReturned = from m in doc.Elements("topNode").Elements("middleNode")
from p in m.Elements("penultimateNode")
from n in p.Elements("nodesIWantReturned")
where m.Attribute("filteringAttribute").Value == "filterValue"
where... | In addition to the Linq methods shown, you can also import the `System.Xml.XPath` namespace and then use the [`XPathSelectElements`](http://msdn.microsoft.com/en-us/library/bb342176.aspx) extension method to use your XPath query directly.
It is noted in the class that these methods are slower than 'proper' Linq-to-XML... | What is the LINQ to XML equivalent for this XPath | [
"",
"c#",
"xml",
"linq",
"xpath",
""
] |
I was just wondering whether there is some way to do this:
I have a form in a web page, after the user submits the form, the page is redirected to another static HTML page.
Is there any way to manipulate the data in the second HTML page without the help of any server code?
I mean can I display the form data that the... | You can use a `<form>` with GET method to go to another static HTML page with some query parameters and then grab those parameters with JavaScript:
First page:
```
<form method="GET" action="page2.html">
<input type="text" name="value1"/>
<input type="text" name="value2"/>
<input type="submit"/>
</form>
`... | You can access the pages GET parameters from JavaScript (*window.location.search*, which you still need to parse), and use this to pass some veriables to the static page.
(I suppose there is no way to get to POST content.)
You can also read and set the values of cookies from JavaScript.
If you are within a frameset ... | Data processing in HTML without server code (using just Javascript) | [
"",
"javascript",
"html",
"web-applications",
"client-side",
""
] |
I can do something like this:
```
validator.showErrors({ "nameOfField" : "ErrorMessage" });
```
And that works fine, however if I try and do something like this:
```
var propertyName = "nameOfField";
var errorMessage = "ErrorMessage";
validator.showErrors({ propertyName : errorMessage });
```
It throws an 'element ... | What about:
```
var propertyName = "nameOfField";
var errorMessage = "ErrorMessage";
var obj = new Object();
obj[propertyName] = errorMessage;
validator.showErrors(obj);
```
---
Is worth to notice that the following three syntaxes are equivalent:
```
var a = {'a':0, 'b':1, 'c':2};
var b = new Object();
b['a'] = ... | The reason you're getting an 'element is undefined' error there by the way, is because:
```
var propertyName = "test";
var a = {propertyName: "test"};
```
is equivalent to..
```
var a = {"propertyName": "test"};
```
i.e., you're not assigning the value of propertyName as the key, you're assigning propertyName as a ... | jQuery Validator, programmatically show errors | [
"",
"javascript",
"jquery",
""
] |
I want to do something like `String.Format("[{0}, {1}, {2}]", 1, 2, 3)` which returns:
```
[1, 2, 3]
```
How do I do this in Python? | The previous answers have used % formatting, which is being phased out in Python 3.0+. Assuming you're using Python 2.6+, a more future-proof formatting system is described here:
<http://docs.python.org/library/string.html#formatstrings>
Although there are more advanced features as well, the simplest form ends up loo... | You can do it three ways:
---
Use Python's automatic pretty printing:
```
print([1, 2, 3]) # Prints [1, 2, 3]
```
Showing the same thing with a variable:
```
numberList = [1, 2]
numberList.append(3)
print(numberList) # Prints [1, 2, 3]
```
---
Use 'classic' string substitutions (ala C's printf). Note the dif... | String formatting in Python | [
"",
"python",
"string",
"formatting",
""
] |
So I have ASP.NET running on the server in IIS7. I think I'm going to use MVC for some static pages and basic dynamic forms - but the majority of the client side is written in Flash/ActionScript.
What's the simplest, most succint, most DRY way of building/generating proxies between client and server?
Which format sho... | WSDL web services are very easy to consume in Flash and simple to create in .NET.
I'd also suggest you at least look into AMF, which is Adobe's proprietary binary format for exchanging data between client and server. There are a couple of implementations for .NET, including amf.net and weborb.
I've never used it, but... | i've consumed JSON in swfs .. pretty simple using a3corelib stuff | How should client Flash(SWF) communicate with server-side .NET? | [
"",
"c#",
".net",
"flash",
"actionscript-3",
""
] |
I'm using Java SE 1.6 on Mac OS X 10.5.6. The code for my applet is as follows:
```
import java.awt.Graphics;
import javax.swing.JApplet;
public class HelloWorld extends JApplet {
public void paint( Graphics g ) {
super.paint( g );
g.drawString( "Hello World!", 25, 25 );
}
}
```
I c... | Thank you for all your answers. Some of them pointed me in the right direction to figure out the source of the problem.
I turned on the Java Console in Java Preferences. When I ran the applet again, the following output is what I received:
Java Plug-in 1.5.0
Using JRE version 1.5.0\_16 Java HotSpot(TM) Client VM
... | You do not specify a codebase property in the applet tag, so I'd guess your class can not be found.
Try to enable the java console output window. You can do this in "Java Settings" (use spotlight) under the extended options tab (the one with the tree and many checkboxes). Maybe you can see some more information (like ... | How do I get a simple, Hello World Java applet to work in a browser in Mac OS X? | [
"",
"java",
"html",
"macos",
"applet",
""
] |
I have a `System.Windows.Forms.TreeView` docked inside a panel. I am setting a node selected programmatically. What method or property would I use to have the treeview scroll the selected into view? | ```
node.EnsureVisible();
```
for example:
```
if(treeView.SelectedNode != null) treeView.SelectedNode.EnsureVisible();
```
(see [MSDN](http://msdn.microsoft.com/en-us/library/system.windows.forms.treenode.ensurevisible.aspx)) | To ensure the visibility of selected item:
```
private void EnsureItemVisible()
{
if(treeView1.SelectedNode == null)
{
return;
}
for (int i = treeView1.SelectedNode.Index + treeView1.VisibleCount / 2; i >= 0; i--)
{
if (treeView1.Nodes.Count > i && treeView1.Nodes[i] != null)
... | Scroll selected TreeView node into view | [
"",
"c#",
"winforms",
"treeview",
""
] |
I can think of a few messy ways to solve this, but it strikes me that there should be a far more elegant solution than those which I've already come up with.
What's the most appropriate way for an object to cleanse itself of all of its event handlers prior to being disposed. It's a shame the event handler can't be enu... | > In theory, is it considered more
> correct for the code adding the
> handler to an object to remember to
> remove it than assuming the object
> will clean itself up before it goes
> out of scope?
To the above question, I'll have to say yes. The basic theory about events is that the event firer shouldn't be responsib... | There is a way to avoid this common problem with events - [WeakEvent pattern](https://msdn.microsoft.com/en-us/library/aa970850(v=vs.100).aspx). | Remove handlers on disposing object | [
"",
"c#",
".net",
""
] |
I find long sequences of standard includes annoying:
```
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
```
Considering these header files change only very rarely, is there a reason why I should not make a "std.h" file #including all std headers and just use that everywhere? | Including unnecessary header files will increase compile times. | You might like to add these to your project's standard, precompiled header file: if your project has a standard, precompiled header file, and if your files aren't supposed to be reusuable in other projects which might have a different standard header file. | Disadvantages of a <std.h> file that brings in all std headers? | [
"",
"c++",
"include",
""
] |
I wrote a couple of Java classes—`SingleThreadedCompute` and `MultithreadedCompute`—to demonstrate the fact (or what I always thought was a fact!) that if you parallelize a compute-centric (no I/O) task on a single core machine, you don't get a speedup. Indeed my understanding is that parallelizing such tasks actually ... | I tried turning off the JIT as Pax suggested in the comment above. Pax, if you want to post a quick "Turn off the JIT" answer I'll credit your solution.
Anyway turning off the JIT worked (meaning that it brought the actual results in line with the expected results). I had to back away from one billion as it was taking... | It's possible that this is due to hyper-threading and/or pipelining.
From wikipedia [on hyper-threading](http://en.wikipedia.org/wiki/Hyper-threading):
> Hyper-threading is an advancement over super-threading. Hyper-threading (officially termed Hyper-Threading Technology or HTT) is an Intel-proprietary technology use... | Unexpected multithreaded result | [
"",
"java",
"multithreading",
"concurrency",
""
] |
Based on information in Chapter 7 of [3D Programming For Windows (Charles Petzold)](http://www.charlespetzold.com/3D/), I've attempted to write as helper function that projects a Point3D to a standard 2D Point that contains the corresponding screen coordinates (x,y):
```
public Point Point3DToScreen2D(Point3D point3D,... | Since Windows coordinates are z into the screen (x cross y), I would use something like
```
screenY = viewPort.ActualHeight * (1 - screenY);
```
instead of
```
screenY = screenY * viewPort.ActualHeight;
```
to correct screenY to accomodate Windows.
Alternately, you could use OpenGL. When you set the viewport x/y/z... | I've created and succesfully tested a working method by using the [3DUtils](http://www.codeplex.com/Wiki/View.aspx?ProjectName=3DTools) Codeplex source library.
The real work is performed in the TryWorldToViewportTransform() method from 3DUtils. This method will not work without it (see the above link).
Very useful i... | Projecting a 3D point to a 2D screen coordinate | [
"",
"c#",
"wpf",
"math",
"3d",
""
] |
I'm working on a SQL Reporting Services report (in VS.Net 2005) which displays a count of different data in a matrix. The columns have a count on the amount of customers in a certain set. So I have several columns like these: "1 employer", "2-9 employers", "10-19 employers" and so on.
The problem I have is that SQL Re... | We do a lot of SSRS Reports and this was always an issue with mdx. Here is one way we do it:
Set *Sorting* in the *Grouping and Sorting Properties* to sort by this expression:
```
=iif(Fields!DataSetField.Value = "ColumnName", "zzz", Fields!DataSetField.Value)
```
Where "zzz" could be a number or whatever you need i... | This can also be done by adding a new column to the query for the sort order. Then right click the column group from the matrix and select group properties. On the left hand side select sorting. From here you can specify another column to sort by instead of the column header. No custom formula needed. | How to specify an order for the columns in a matrix? | [
"",
"sql",
"visual-studio",
"reporting-services",
"matrix",
""
] |
Is there a product (ideally open source, but not necessary), that would enable a zero dependency deployment? every service bus or queue library I've been able to find has a dependency on one of the queue apps (like msmq), or a database. I would like a very lightweight solution that I can just add a reference to my appl... | Rhino Queues from Ayende is exactly what you are looking for, this is the blog post introducing it:
<http://ayende.com/Blog/archive/2008/08/01/Rhino-Queues.aspx>
I think that all of the limitations mentioned in this post have been fixed since then.
From the blog post, what rhino queues is:
* XCopyable, Zero Adminis... | In a similar vein to ShuggyCoUk's [suggestion](https://stackoverflow.com/a/546328/3195477), you could rig up a queue (or queues) using the Windows built-in ESENT database (comes already installed with Windows). There is a managed code access library (open source): <http://www.codeplex.com/ManagedEsent>. If you stick wi... | C# Queue or ServiceBus with no dependencies? | [
"",
"c#",
".net",
"iis",
"queue",
"servicebus",
""
] |
Does anyone know a good safe way to redirect the output of a printf-style function to a string? The obvious ways result in buffer overflows.
Something like:
```
string s;
output.beginRedirect( s ); // redirect output to s
... output.print( "%s%d", foo, bar );
output.endRedirect();
```
I think the problem is the s... | [This StackOverflow question](https://stackoverflow.com/questions/69738/c-how-to-get-fprintf-results-as-a-stdstring-w-o-sprintf#69911) has a similar discussion. Also in that question I present my favorite solution, a "format" function that takes identical arguments to printf and returns a std::string. | You can use:
[`std::snprintf`](http://en.cppreference.com/w/cpp/io/c/fprintf) if you are working with a char\*
[`std::stringstream`](http://en.cppreference.com/w/cpp/io/basic_stringstream) if you want to use strings (not same as printf but will allow you to easily manipulate the string using the normal stream functio... | Best way to safely printf to a string? | [
"",
"c++",
"stl",
""
] |
I want to compile a project differently, according to a constant defined by #define, like this:
```
#define USE_COMPONENT_X
#if USE_COMPONENT_X
...
#endif
```
and I can do that in C#. But when I go to another file in the same project, this constant is not defined. Can I in some way define a constant to all the proj... | You can add the /define compiler switch.
1. Open the project's Property Pages dialog box.
2. Click the Configuration Properties folder.
3. Click the Build property page.
4. Modify the Conditional Compilation Constants property. | You may want to go a step further and create different project configurations as variants of the standard Debug and Release project configuration. The Configuration Manager under the build menu will let you accomplish this. Then while you are in the project properties' Build tab you can select the various configuration... | How to define a constant globally in C# (like DEBUG) | [
"",
"c#",
".net",
""
] |
I have a simplified ajay script, from which I have removed all nonrelevant code. The problem I am having is first with my columns array and the subsequent foreach loop. I want to go through each element and change the corresponding element to YES if true and NO if false, I don't see why it isn't working.
If there are ... | Your loop is wrong - $columns['EGGS'] doesn't exist:
```
$columns = array('EGGS', 'SALAD', 'TREES', 'REVISED');
foreach($columns as $column) {
$$column = $columns[$column] ? 'YES' : 'NO';
}
```
it should be:
```
$columns = array('EGGS', 'SALAD', 'TREES', 'REVISED');
foreach($columns as $column) {
$$column = ... | But I just want to add that while using variables like $$COLUMN seems to be a nice feature, it later can get really messy and produces a lot of extra variables.
Why don't you just create a temporary array, holding all YES/NO pairs?
In addition, PHP does not allow variables to contain numbers. I don't know what will h... | looping array problem | [
"",
"php",
""
] |
Does Java have buffer overflows?
If yes can you give me scenarios? | Since Java Strings are based on char arrays and Java automatically checks array bounds, buffer overflows are only possible in unusual scenarios:
1. If you call native code via JNI
2. In the JVM itself (usually written in C++)
3. The interpreter or JIT compiler does not work correctly (Java bytecode mandated bounds che... | Managed languages such as Java and C# do not have these problems, but the specific virtual machines (JVM/CLR/etc) which actually run the code may. | Does Java have buffer overflows? | [
"",
"java",
"buffer-overflow",
"buffer-overrun",
""
] |
I'm looking for a way to reinterpret an array of type byte[] as a different type, say short[]. In C++ this would be achieved by a simple cast but in C# I haven't found a way to achieve this without resorting to duplicating the entire buffer.
Any ideas? | You can achieve this but this is a relatively bad idea. Raw memory access like this is not type-safe and can only be done under a full trust security environment. You should never do this in a properly designed managed application. If your data is masquerading under two different forms, perhaps you actually have two se... | There are four good answers to this question. Each has different downsides. Of course, beware of endianness and realize that all of these answers are holes in the type system, just not particularly treacherous holes. In short, don't do this a lot, and only when you really need to.
1. [Sander](https://stackoverflow.com... | reinterpret_cast in C# | [
"",
"c#",
"arrays",
"casting",
""
] |
What is the best way to return the whole number part of a decimal (in c#)? (This has to work for very large numbers that may not fit into an int).
```
GetIntPart(343564564.4342) >> 343564564
GetIntPart(-323489.32) >> -323489
GetIntPart(324) >> 324
```
The purpose of this is: I am inserting into a decimal (30,4) field... | By the way guys, (int)Decimal.MaxValue will overflow. You can't get the "int" part of a decimal because the decimal is too friggen big to put in the int box. Just checked... its even too big for a long (Int64).
If you want the bit of a Decimal value to the LEFT of the dot, you need to do this:
```
Math.Truncate(numbe... | I think [System.Math.Truncate](http://msdn.microsoft.com/en-us/library/c2eabd70.aspx) is what you're looking for. | Best way to get whole number part of a Decimal number | [
"",
"c#",
".net",
"decimal",
"int",
""
] |
I'm a hobbyist (and fairly new) programmer who has written several useful (to me) scripts in python to handle various system automation tasks that involve copying, renaming, and downloading files amongst other sundry activities.
I'd like to create a web page served from one of my systems that would merely present a fe... | [This page](http://docs.python.org/library/cgi.html) on the python site has a good description and example of what you need to do to run a python CGI script. Start out with the simplest case first. Just make a short script that prints html.
```
#!/usr/bin/python #on windows change to your path to the... | This simple approach requires nothing except Python standard library. Create this directory structure:
```
.
|-- cgi-bin
| `-- script.py
|-- index.html
`-- server.py
```
You put your scripts in "cgi-bin" directory, "index.html" contains links to scripts in "cgi-bin" directory (so you don't have to type them manuall... | How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage? | [
"",
"python",
"windows",
"web-services",
"cgi",
""
] |
I have a few places where I use the line below to clear out a status, for example. I have a few of these that hang out for 10 seconds or more and if the user gets clicking around the action can occur at incorrect time intervals.
```
window.setTimeout(function() { removeStatusIndicator(); }, statusTimeout);
```
Is it ... | ```
var timer1 = setTimeout(function() { removeStatusIndicator(); }, statusTimeout);
clearTimeout(timer1);
``` | ## The Trick
`setTimeout` returns a number:
[](https://i.stack.imgur.com/CEooI.png)
## Solution
Take this number. Pass it to the function `clearTimeout` and you're safe:
[](https:... | Cancel/kill window.setTimeout() before it happens | [
"",
"javascript",
"jquery",
""
] |
I am stuck! this seems really daft but I can not see where I am going wrong. I am creating a 2.0 C# ASP.NET website. I am trying to use a custom section in the web.config file with:
```
DatabaseFactorySectionHandler sectionHandler = ConfigurationManager.GetSection("DatabaseFactoryConfiguration") as DatabaseFactorySect... | Either you're using the wrong name (i.e. it's not called Bailey.DataLayer.dll), or it's not being copied to the bin directory on build. This last one doesn't seem likely however.
(See my comments on the question for clarification). | Ok ... I had the same issue. None of the above solutions helped.
In my case my config file was in the same dll as that of web.config. I simply removed the namespace from the config section and that fixed my issue.
**Not working**
```
<configSections>
<section name="authorizedServerSection" type="ProjectName.ClientApi... | C# ConfigurationManager.GetSection could not load file or assembly | [
"",
"c#",
"configurationmanager",
"configsection",
""
] |
I am creating a MFC application for Windows Mobile and don't know how to enable multiple selection for List Control (CListCtrl). In properties panel Single Selection is set to False but still can't select multiple items.
Any idea? | I have never targeted Windows Mobile but you might try the following:
> list.ModifyStyle(LVS\_SINGLESEL, 0); | ModifyStyle method of CWnd base will work (see post from Diego) if you desire to do this programmatically OR you can define the attribute within the Resource Editor IF your placing the control on a dialog. | CListCtrl - how to enable multiple selection | [
"",
"c++",
"mfc",
"windows-mobile",
"clistctrl",
""
] |
I've got a function inside of a class that returns a string. Inside this function, I can only get it to work when I add `cout<<endl` to the function before the return statement. Any idea why this is, or how I can fix it? I'm running this in Eclipse on a Mac
In "main.cpp":
```
#include <iostream>
#include <fstream>
#i... | actually *getName()* function is probably working correctly. However, the cout 'caches' the output (i.e. it prints the output on screen when it's internal text buffer is full). 'endl' flushes the buffer and forces cout to dump the text (in cache) to screen.
Try cout.flush() in main.cpp | Maybe your terminal is lazy. Try omitting the `endl` and insert `cout.flush(`) as the next line. | C++ function that returns string doesn't work unless there's an endl involved...? | [
"",
"c++",
"string",
"stl",
""
] |
I am making use of AJAX on my site and I would like to show users progress of a file that is being downloaded by my server.
The download is done by script that **outputs a percentage to the shell**. I would like to pass this info back to the user using AJAX. How can I do this?
Thank you for any help and direction.
I... | Instead of exec, you could use [popen](https://www.php.net/popen). This will give you a handle you use with fread to grab the output your command generates as it happens.
You'll need to parse out the updates it makes to the percentage indicator. Once you have that data, there are a few ways you could get it to a clien... | I haven't tried this, but I think this approach would work.
You need three pieces:
1. Have shell script output its stream to netcat connected to a port
2. Have a php script listening to stream coming from said port for incoming data, updating a record in memcache or some database w/ the percentage finished.
3. Have y... | AJAX - Progress bar for a shell command that is executed | [
"",
"php",
"ajax",
"linux",
"shell",
"progress-bar",
""
] |
Basically, I want to do "zipzam&&&?&&&?&&&" -> "zipzam%26%26%26?&&&?&&&". I can do that without regex many different ways, but it'd cleanup things a tad bit if I could do it with regex.
Thanks
Edit: "zip=zam&&&=?&&&?&&&" -> "zip=zam%26%26%26=?&&&?&&&" should make things a little clearer.
Edit: "zip=zam=&=&=&=?&&&?&&... | This should do it:
```
"zip=zam=&=&=&=?&&&?&&&".replace(/^[^?]+/, function(match) { return match.replace(/&/g, "%26"); });
``` | you need negative lookbehinds which are tricky to replicate in JS, but fortunately there are ways and means:
```
var x = "zipzam&&&?&&&?&&&";
x.replace(/(&+)(?=.*?\?)/,function ($1) {for(var i=$1.length, s='';i;i--){s+='%26';} return s;})
```
commentary: this works because it's *not* global. The first match is there... | Regex to match all '&' before first '?' | [
"",
"javascript",
"regex",
""
] |
is it possible, in C++, to get the current RAM and CPU usage? Is there a platform-indepentent function call? | There is an open source library that gives these (and more system info stuff) across many platforms: [SIGAR API](https://github.com/hyperic/sigar)
I've used it in fairly large projects and it works fine (except for certain corner cases on OS X etc.) | Sadly these things rely heavily on the underlying OS, so there are no platform-independent calls. (Maybe there are some wrapper frameworks, but I don't know of any.)
On Linux you could have a look at the [getrusage()](http://linux.die.net/man/2/getrusage) function call, on Windows you can use [GetProcessMemoryInfo()](... | How to get current CPU and RAM usage in C++? | [
"",
"c++",
"cpu-usage",
"ram",
""
] |
How do I print the indicated div (without manually disabling all other content on the page)?
I want to avoid a new preview dialog, so creating a new window with this content is not useful.
The page contains a couple of tables, one of them contains the div I want to print - the table is styled with visual styles for t... | Here is a general solution, using **CSS only**, which I have verified to work.
```
@media print {
body {
visibility: hidden;
}
#section-to-print {
visibility: visible;
position: absolute;
left: 0;
top: 0;
}
}
```
*There's a [Code Sandbox](https://codesandbox.io/s/print-area-vo35v5) if you ... | I have a better solution with minimal code.
Place your printable part inside a div with an id like this:
```
<div id="printableArea">
<h1>Print me</h1>
</div>
<input type="button" onclick="printDiv('printableArea')" value="print a div!" />
```
Then add an event like an onclick (as shown above), and pass the i... | Print <div id="printarea"></div> only? | [
"",
"javascript",
"css",
"printing",
"dhtml",
""
] |
Is there a way to include a javascript-loaded advertisement last on the page, but have it positioned in the content? The primary purpose is to keep the javascript ad from slowing down the page load, so if there are other methods to achieve this please do share. | There is the **[`defer` attribute](http://www.websiteoptimization.com/speed/tweak/defer/)** you could put on script blocks to defer its execution until the page completes loading.
```
<script src="myscript.js" type="text/javascript" defer>
// blah blah
</script>
```
I am not sure about the general recommendation abou... | ```
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
```
The above code is a nice way to add a new onload ... | Is it possible to load a javascript ad last on the page to prevent slow load times? | [
"",
"javascript",
""
] |
I cannot figure out how to make a C# Windows Form application write to a textbox from a thread. For example in the Program.cs we have the standard main() that draws the form:
```
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new... | On your MainForm make a function to set the textbox the checks the InvokeRequired
```
public void AppendTextBox(string value)
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(AppendTextBox), new object[] {value});
return;
}
ActiveForm.Text += value;
}
```
although in your static ... | I would use `BeginInvoke` instead of `Invoke` as often as possible, unless you are really required to wait until your control has been updated (which in your example is not the case). `BeginInvoke` posts the delegate on the WinForms message queue and lets the calling code proceed immediately (in your case the for-loop ... | Writing to a TextBox from another thread? | [
"",
"c#",
"winforms",
"multithreading",
""
] |
When accessing values from an **SqlDataReader** is there a performance difference between these two:
```
string key = reader.GetString("Key");
```
or
```
string key = reader["Key"].ToString();
```
In this code sample:
```
string key;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
... | I’ve just peeked into the .NET source code, and the two access methods are essentially the same. The only difference is that the second does an additional boxing. So the first one corresponds to something like (in case of elementary types):
```
int key = GetInternalSQLDataAsInt32("Key");
```
while the second one woul... | A Microsoft MVP wrote a blog entry about this:
<http://jeffbarnes.net/portal/blogs/jeff_barnes/archive/2006/08/09/Maximize-Performance-with-SqlDataReader.aspx>
Here are his conclusions:
```
.NET 1.1 .NET 2.0
Ordinal Position: 8.47 9.33
Get Methods: ... | SqlDataReader performance differences in accessing values? | [
"",
"c#",
"asp.net",
"sqldatareader",
""
] |
**EDIT:** I suppose I should clarify, in case it matters. I am on a AIX Unix box, so I am using VAC compilers - no gnu compilers.
**End edit**
---
I am pretty rusty in C/C++, so forgive me if this is a simple question.
I would like to take common functions out of a few of my C programs and put them in shared librari... | Yeah you are correct. The first is called a *static library*, while the second is called a *shared library*, because the code is not bound to the executable at compile time, but everytime again when your program is loaded.
## Static library
Compile your library's code as follows:
```
gcc -c *.c
```
The `-c` tells t... | You've got a third option. In general, your C++ compiler should be able to link C routines. The necessary options may vary from compiler to compiler, so R your fine M, but basically, you should be able to compile with g++ as here:
```
$ g++ -o myapp myapp.cpp myfunc.c giveint.c
```
... or compile separately
```
$ gc... | How do I source/link external functions in C or C++? | [
"",
"c++",
"c",
"shared-libraries",
""
] |
I know that accessing and manipulating the DOM can be very costly, so I want to do this as efficiently as possible. My situation is that a certain div will always contain a list of items, however sometimes I want to refresh that list with a completely different set of items. In this case, I can build the new list and a... | Have a look on [QuirksMode](http://quirksmode.org/). It may take some digging, but there are times for just this operation in various browsers. Although the tests were done more than a year ago, setting `innerHTML` to `""` was the fastest in most browsers.
P.S. [here](http://quirksmode.org/dom/innerhtml.html) is the p... | set innerHTML to an empty string. | What is the more efficient way to delete all of the children of an HTML element? | [
"",
"javascript",
"html",
""
] |
First of all, am I the only person using JSONML? And second of all, would you recommend using JSONML for inserting dynamic HTML or is InnerHTML more efficient? | Bare in mind that (in IE) not every innerHTML is writable (innerHTML isn't standar compilant anyway). So closer you come to appending nodes rather then inserting html, better you are. As far as I can see, jsonml thingie creates DOM elements whch is nice. I can only sugest you to make some huge dataset, insert it in two... | While superficially used to perform similar tasks, JsonML and innerHTML are quite different beasts.
innerHTML requires you to have all the markup exactly as you want it ready to go, meaning that either the server is rendering the markup, or you are performing expensive string concatenations in JavaScript.
JsonML open... | JSONML vs. InnerHTML vs.? | [
"",
"javascript",
"dom",
""
] |
Hi have some forms that I want to use some basic php validation (regular expressions) on, how do you go about doing it? I have just general text input, usernames, passwords and date to validate. I would also like to know how to check for empty input boxes. I have looked on the interenet for this stuff but I haven't fou... | 1. Read in the PHP.net documentation on Text processing.
2. Use the string methods and regular expressions to make a function for email type, date type etc., returning true if valid, false otherwise.
3. Test with the functions when submitting the form, and display the appropriate error messages to the user. | Another function you should use is trim() to clean the input from all whitespaces for validation - some users might just enter a single whitespace as data. | Simple PHP form Validation and the validation symbols | [
"",
"php",
"regex",
"validation",
""
] |
I need an example algorithm that will draw pixels one at a time on a grid based (x,y) system, and also color them based on an rbg value based on binary data that is provided in some form. I am looking for anything written in php or a php like language such as C, but that does not use any sort of library or graphics car... | It seem you are trying to output JavaScript commands for drawing on a `<canvas>` tag. A faster way to draw the pixels might be to use `moveTo` and `lineTo`. Btw, why isn't you outer loop a for loop as well?
Doesn't
```
for($row=0; $row<=$r_max; ++$row) {
for($column=0; $column<=$c_max; ++$column) {
# draw... | Not really sure i quite understand your question but .. PHP has GD functions that include image allocate and setpixel calls, line drawing etc .. check [here](https://www.php.net/gd)
oh and yes [imagemagick](https://www.php.net/manual/en/book.imagick.php) also for more exotic uses | Pixel Drawing Algorithm | [
"",
"php",
"algorithm",
"render",
"pixel",
""
] |
I have a year 2009, a month 11 and a day 12. All of these are being passed to me as integers. What I want to do is create a date from these. I want to use these as part of my where statement.
What is the best way to do it from either a clean code and most importantly a speed point of view?
I personally am using MS SQ... | Assuming that your `INT`s are called `@d`, `@m` and `@y`:
```
DATEADD(month, ((@y - 1900) * 12) + @m - 1, @d - 1)
```
**EDIT**
Please note that this technique isn't "canonical" in any way, it relies on manipulating SQL Server's implementation of `DATETIME`.
If you pass invalid values for `@d`, `@m` or `@y` then you... | The most unambiguous formats, using only integers, are `YYYYMMDD`, `YYYY-MM-DD`, and `YYYY/MM/DD`. I can't speak to MSSQL specifically, but in my experience, `YYYY-MM-DD` is the most universally supported (due in no small part to it being part of the [ISO 8601 standard](http://en.wikipedia.org/wiki/ISO_8601)). | What's the canonical way to create a date from three numbers representing days, months and years? | [
"",
"sql",
"sql-server",
"date",
""
] |
So I have [taken over a Java Web project](https://stackoverflow.com/questions/436212/taking-over-a-project-what-should-i-ask-the-previous-programmer). The application was written by another developer who now works for another company. Generally speaking, the application is straightforward, well designed and the code is... | Eldimo,
You should balance the decision to incorporate a new framework based on the return of investment of such change. The longevity of the current project is one way to look at it.
If the project is stable and on maintenance phase then you shouldn't make drastic changes.
But if the project will continue to incorp... | You certainly don't want to add frameworks at a whim, but the opposite is also bad, writing your own psuedo-framework when an acceptable alternative exists. In my job, we had to a do a conversion from JPA to a more JDBC style using Spring. During the conversion, I didn't delete or modify any of the JPA code, I simply r... | Is it OK to have two frameworks in the same project? | [
"",
"java",
"jsp",
"frameworks",
""
] |
I am getting the error OperationalError: FATAL: sorry, too many clients already when using psycopg2. I am calling the close method on my connection instance after I am done with it. I am not sure what could be causing this, it is my first experience with python and postgresql, but I have a few years experience with php... | This error means what it says, there are too many clients connected to postgreSQL.
Questions you should ask yourself:
* Are you the only one connected to this database?
* Are you running a graphical IDE?
* What method are you using to connect?
* Are you testing queries at the same time that you running the code?
Any... | Make sure your db connection command isn't in any kind of loop. I was getting the same error from my script until I moved my db.database() out of my programs repeating execution loop. | Getting OperationalError: FATAL: sorry, too many clients already using psycopg2 | [
"",
"python",
"postgresql",
"psycopg2",
""
] |
I have a map defined like this
```
std::map<some_key_type, std::string::iterator> mIteratorMap;
```
And a huge string named "mHugeString". Then I walk trough the string collecting iterators like this:
```
std::string::iterator It=mHugeString.begin();
std::string::iterator EndIt=mHugeString.end();
for(;It!=EndIt;++It... | I haven't tried it but I would have expected that, of course you **can** store iterator values as values in a map.
Do you know that if you change the contents of `mHugeString` then any iterators into it which you have previously stored are now invalid?
You might choose to store the index into the string, instead of t... | It's fine, you *can* store iterators in the map. If you get some error, that is caused by something else. Note that if you modify your string, iterators pointing into your string will become invalid.
Please show us a complete, compilable code snippet that is rendered unusable, so we can analyze it. | Why can't I put an iterator in map? | [
"",
"c++",
"string",
"stl",
"dictionary",
"iterator",
""
] |
What am I missing here?
I want to do a simple call to Select() like this:
```
List<int> list = new List<int>();
//fill the list
List<int> selections = (List<int>)list.Select(i => i*i); //for example
```
And I keep having trouble casting it. What am I missing? | Select() will return you an IEnumerable<int> type, you have to use the [ToList() operator](http://www.hookedonlinq.com/ToListOperator.ashx):
```
List<int> selections = list.Select(i => i*i).ToList();
``` | Select() doesn't return a List so of course you can't cast it to a list.
You can use the ToList method instead:
```
list.Select(i => i*i).ToList();
``` | Trouble casting results of Select() to a List<T> | [
"",
"c#",
".net",
"linq",
""
] |
A friend of mine is talking about these design techniques regarding state transitions of an object (he's a Java guru, btw), performed without having a `boolean myState` member, but rather declaring the `myState` member as an object that implements the same interface of the "owner" one.
Ok, I've been too much cryptic, ... | It sounds like you're asking whether there's a "concretely useful" benefit to using the state design pattern, to which I'd say definitely yes, particularly if your app actually relies heavily on the "state" of its objects. A popular canonical example is that of the video player, which is always in one state, and can on... | I have to disagree - useful design patterns aside, *this particular example* is ridiculous overkill:
* a 15-line class with an easily-understandable process
* became a 50-line class with an obfuscated purpose
I fail to see how this is an improvement - it violates YAGNI1 and ASAP2, bloats the code, and reduces efficie... | If-less code: is it just an intellectual challenge or is it concretely useful? | [
"",
"java",
"design-patterns",
"oop",
""
] |
I would like to call a windows program within my code with parameters determined within the code itself.
I'm not looking to call an outside function or method, but an actual .exe or batch/script file within the WinXP environment.
C or C++ would be the preferred language but if this is more easily done in any other la... | When you call CreateProcess(), System(), etc., make sure you double quote your file name strings (including the command program filename) in case your file name(s) and/or the fully qualified path have spaces otherwise the parts of the file name path will be parsed by the command interpreter as separate arguments.
```
... | C++ example:
```
char temp[512];
sprintf(temp, "command -%s -%s", parameter1, parameter2);
system((char *)temp);
```
C# example:
```
private static void RunCommandExample()
{
// Don't forget using System.Diagnostics
Process myProcess = new Process();
try
{
myProce... | How to call an external program with parameters? | [
"",
"c++",
"c",
"winapi",
"external-application",
""
] |
I am interested in creating a couple of add-ins for Office 2003 & 2007 for work and home. I see the project templates in VS2008 for creating the addins but I am un-clear as to what to do next. I also have had great difficulty finding direction online so far. I am not looking for cut and paste code but rather a finger p... | Thanks for the time and replies!
Between *gkrodgers* and *Perpetualcoder's* responses I was lead to my ultimate destination --> [Walkthrough: Creating Your First Application-Level Add-in for Excel](http://msdn.microsoft.com/en-us/library/cc668205.aspx)
Why I had such a time finding this in the first place is beyond m... | This is the article that got me started when I needed to write a Word add-in:
<http://support.microsoft.com/kb/302896>
and this is my *actual* "Hello World" code! :-)
```
public void OnStartupComplete(ref System.Array custom)
{
System.Windows.Forms.MessageBox.Show("Hello World!");
}
``` | .Net Excel Add In Help | [
"",
"c#",
".net",
"excel",
"add-in",
""
] |
I am looking for a Java Rules / Workflow engine. Something similar to Microsoft Workflow Engine.
Can someone recommend a product? | [Here](http://java-source.net/open-source/rule-engines) is a rundown of many open-source Java rules engines including the usual suspects like [Drools](http://drools.org/), etc. | * [jBPM](http://www.jboss.com/products/jbpm): aimed at business processes mostly;
* [OSWorkflow](http://www.opensymphony.com/osworkflow/documentation.action): pretty low-level; and
* [Spring Webflow](http://www.springsource.org/webflow): not a generic workflow engine but a notworthy product if you ever need to implemen... | Free / OpenSource Java Rules / Workflow engine | [
"",
"java",
"workflow",
"rules",
""
] |
I have the DGV bound to data and all the other controls properly. What I am trying to do now is update a PictureBox based on the contents of the data row. The picture is not a part of the bound data, its always available on the web. I have a function that will build the url string to a webserver with the images I need.... | Another wild guess: SelectionChanged | EDIT: Realized you wanted it to happen when you selected a row..
```
MyGrid.RowEnter += new DataGridViewCellEventHandler(MyGrid_RowEnter );
void MyGrid_RowEnter(object sender, DataGridViewCellEventHandlere)
{
if (0 > e.RowIndex) return;
//TODO: Do whatever with your image here..
}
``` | DataGridView: Which Event do I need? | [
"",
"c#",
"winforms",
"datagridview",
""
] |
i'm pretty sure it's not possible, but i'll throw this out there anyways.
I have about 10 asp:checkbox controls on the page, and I need to go and update the database every time any of them gets checked/unchecked.
Right now i have all of them tied to one event handler that fires on CheckedChanged, then i cast the send... | Why not make your own custom server checkbox control.
```
namespace CustomControls
{
public class CustomCheckBox : CheckBox
{
string _myValue;
public string MyValue
{
get { return _myValue; }
set { _myValue = value; }
}
public CustomCheckBox()
{
... | It might be an idea to try using regular HTML checkboxes and submitting them as an array / comma-separated list:
```
<input type="checkbox" id="item-1" name="items[]" value="1" />
<label for="item1">Item 1</label>
....
<input type="checkbox" id="item-n" name="items[]" value="n" />
<label for="item1">Item n</label>
```... | Assigning a value (or any other parameter) to asp:checkbox | [
"",
"c#",
".net",
"asp.net",
".net-2.0",
"checkbox",
""
] |
I have a service written in C# (.NET 1.1) and want it to perform some cleanup actions at midnight every night. I have to keep all code contained within the service, so what's the easiest way to accomplish this? Use of `Thread.Sleep()` and checking for the time rolling over? | I wouldn't use Thread.Sleep(). Either use a scheduled task (as others have mentioned), or set up a timer inside your service, which fires periodically (every 10 minutes for example) and check if the date changed since the last run:
```
private Timer _timer;
private DateTime _lastRun = DateTime.Now.AddDays(-1);
protec... | Check out [Quartz.NET](http://quartznet.sourceforge.net/). You can use it within a Windows service. It allows you to run a job based on a configured schedule, and it even supports a simple "cron job" syntax. I've had a lot of success with it.
Here's a quick example of its usage:
```
// Instantiate the Quartz.NET sche... | How might I schedule a C# Windows Service to perform a task daily? | [
"",
"c#",
"windows-services",
"scheduling",
"scheduled-tasks",
""
] |
I try to dynamically add nodes to a Java Swing [`JTree`](http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JTree.html), and the user should be able to browse and to collapse hierarchy while nodes are constantly added. When I add a `Thread.sleep(10)` in my loop, it works fine; but this is a dirty hack...
Here is the ... | tree.expandRow needs to be done in the event thread, so change the loop as follows:
```
while (true)
{
MutableTreeNode child = new DefaultMutableTreeNode("test");
model.insertNodeInto(child, root, root.getChildCount());
final int rowToExpand = tree.getRowCount() - 1; // ? does this work ?
... | Swing is thread-hostile, so do your Swing manipulation in the AWT Event Diaptch Thread (EDT).
The infinite loop is nonsense, so difficult to come up with a suggestion. The best equivalent I can think of is iterating posting an even to run the code again. Because there are certain priorities in the event queue, I'm not... | JTree gives ArrayIndexOutOfBoundsException? | [
"",
"java",
"multithreading",
"swing",
"synchronization",
"jtree",
""
] |
Is there any way or a library to get a system-wide (global) keyboard shortcut to
perform an action in a Java application? | There is not, but in windows you can use this:
[jintellitype](https://github.com/melloware/jintellitype)
Unfortunately there is nothing I'm aware of for Linux and OSX, probably that's why it doesn't come with java out of the box.
If you find for the other platforms post it here please :)
Just for couriosity, what a... | I am the author of JIntellitype and I can tell you for a fact this must be done natively in DLL and called from Java JNI just like JIntellitype does it. This is an OS level hook that is not implemented in the JDK so libraries like JIntellitype and jxGrabKey must be used. As far as I know no one has written one for OSX ... | Java System-Wide Keyboard Shortcut | [
"",
"java",
"keyboard",
"system",
"shortcut",
""
] |
I'm using callables quite often , and I've stubled upon a question that irritates me:
Lets say that to run function foo() , one needs to do a couple of checks first.
Should you
1. Insert the checks as part of the Callable :
```
class A implements Callable<Long> {
...
public Long call() {
check1();
check2();
... | My general advice when implementing callback [Java keyword] interfaces is concentrate on making the [non-Java keyword] interface appropriate for the called type. There generally shouldn't be that much in the anonymous inner class (or whatever), but more than just forwarding call.
Also, it's generally not good to have ... | Which do you feel is simpler or clearer?
I suggest you do that. | How much logic is it "right" to put in a Callable? | [
"",
"java",
"callable",
""
] |
Ok so I have a number of methods that look like this:- which sorts a list by artist, album, year etc.
```
public void SortByAlbum(SortOrder sortOrder)
{
if (sortOrder == SortOrder.Ascending)
_list = _list.OrderBy(x => x.Album).ToList();
else if (sortOrder == SortOrde... | You should be able to mimick the signature of the OrderBy extension method:
**Update 1** you have to be explicit in the first generic parameter to your keySelector Func. I'm going to take a guess at your type and call it "Song".
```
public void Sort<TKey>(SortOrder sortOrder,
Func<Song, TKey> k... | You might try using a [generic comparer](http://www.c-sharpcorner.com/UploadFile/dipenlama22/SortingUsingGeneric07052006081035AM/SortingUsingGeneric.aspx?ArticleID=dafdb8cc-fd02-4a4d-bd17-0c5785b1b91d). | Avoiding code repetition when using LINQ | [
"",
"c#",
".net",
"linq",
"refactoring",
""
] |
Ok, I have a set of checkboxes for selecting criteria. For argument's sake, we'll say the data looks like this:
```
[] Vehicles
[] Unpowered
[] Bicycle
[] Skateboard
[] Powered
[] Two-wheeled
[] Motorcycle
[] Scooter
[] Four-wheeled
etc
```
The []s represent checkboxes.... | ```
<ul>
<li><input type="checkbox" />Vehicles <ul>
<li><input type="checkbox" />Unpowered</li>
<li><input type="checkbox" />Bicycle</li>
<li><input type="checkbox" />Skateboard</li>
</ul></li>
<li><input type="checkbox" />Powered <ul>
<li><input type="checkbox" />Two-wheeled... | You could do this:
```
<ul>
<li>
<input type="checkbox" /> Option 1
<ul>
<li><input type="checkbox" /> Option 1 Sub Option A</li>
</ul>
</li>
</ul>
```
You'd then set the padding/margin of the UL's to 0 and 0. Then set the padding-left of the LI's to 10px.
```
ul {
margin:0;
padding:0;
}
l... | HTML/CSS: what's a better option for layout of a tree of nested elements than nested tables? | [
"",
"javascript",
"jquery",
"html",
"css",
"cross-browser",
""
] |
What would be the most efficient way to do a paging query in SQLServer 2000?
Where a "paging query" would be the equivalent of using the LIMIT statement in MySQL.
EDIT: Could a stored procedure be more efficient than any set based query in that case? | [Paging of Large Resultsets](http://www.codeproject.com/KB/aspnet/PagingLarge.aspx) and the winner is using RowCount. Also there's a generalized version for more complex queries.
But give credit to **Jasmin Muharemovic** :)
```
DECLARE @Sort /* the type of the sorting column */
SET ROWCOUNT @StartRow
SELECT @Sort = So... | I think a nested `SELECT TOP n` query is probably the most efficient way to accomplish it.
```
SELECT TOP ThisPageRecordCount *
FROM Table
WHERE ID NOT IN (SELECT TOP BeforeThisPageRecordCount ID FROM Table ORDER BY OrderingColumn)
ORDER BY OrderingColumn
```
Replace `ThisPageRecordCount` with items per page and `Bef... | Efficient Paging (Limit) Query in SQLServer 2000? | [
"",
"sql",
"sql-server-2000",
"paging",
"limit",
""
] |
I am binding an Image.Source property to the result of the property shown below.
```
public BitmapSource MyImageSource
{
get
{
BitmapSource source = null;
PngBitmapDecoder decoder;
using (var stream = new FileStream(@"C:\Temp\logo.png", FileMode.Open, FileAccess.Read, FileShare.Read))
... | The problem was the BitmapCacheOption option, changing to BitmapCacheOption.OnLoad works.
With BitmapCacheOption.None the BitmapSource isn’t decoded until the image is rendered, but the stream with the png in it is already disposed at that point. If you cache OnLoad, it’ll decode right away and cache the results, rath... | Also, have you tried just using a BitmapImage to load the image? It works fine with PNG, BMP, and JPEG.
It's also a specialized type of BitmapSource, so you could just replace your code in your property with this:
```
BitmapImage img = new BitmapImage(new Uri(@"C:\Temp\logo.png"));
return img;
``` | WPF BitmapSource ImageSource | [
"",
"c#",
"wpf",
"xaml",
"binding",
""
] |
I'm trying to find out the best practice when removing characters from the start of a string.
In some languages, you can use MID without a length parameter however, in TSQL the length is required.
Considering the following code, what is the best practise? (The hex string is variable length)
```
DECLARE @sHex VARCHAR... | Well, the first is more expressive of your intent. The last is clearly messy (hard-coded length etc). I doubt you'd find much performance difference between the first & second, so I'd use the simplest - `RIGHT`.
Of course, if you are doing this lots, you could write a udf that encapsulates this - then if you change yo... | +1 on the right function, it is much clearer what you want to do | SQL SUBSTRING vs RIGHT - Best Practice | [
"",
"sql",
"t-sql",
"string",
""
] |
Is it possible via script/tool to generate a delete statement based on the tables fk relations.
i.e. I have the table: DelMe(ID) and there are 30 tables with fk references to its ID that I need to delete first, is there some tool/script that I can run that will generate the 30 delete statements based on the FK relatio... | DELETE statements generated for use in SP with parameter, and as ON DELETE triggers:
(this variant supports single column FKs only)
```
SELECT 'DELETE '+detail.name+' WHERE '+dcolumn.name+' = @'+mcolumn.name AS stmt,
'DELETE ' + detail.name + ' FROM ' + detail.name + ' INNER JOIN deleted ON ' +
detail.name +... | Here is a script for cascading delete by [Aasim Abdullah](http://connectsql.blogspot.co.il/2011/03/sql-server-cascade-delete.html), works for me on MS SQL Server 2008:
```
IF OBJECT_ID('dbo.udfGetFullQualName') IS NOT NULL
DROP FUNCTION dbo.udfGetFullQualName;
GO
CREATE FUNCTION dbo.udfGetFullQualName
(@ObjectId ... | Generate Delete Statement From Foreign Key Relationships in SQL 2008? | [
"",
"sql",
"code-generation",
"foreign-keys",
"dynamic-sql",
""
] |
When using Python's `super()` to do method chaining, you have to explicitly specify your own class, for example:
```
class MyDecorator(Decorator):
def decorate(self):
super(MyDecorator, self).decorate()
```
I have to specify the name of my class `MyDecorator` as an argument to `super()`. This is not DRY. ... | The BDFL agrees. See [PEP 3135 - New Super](http://www.python.org/dev/peps/pep-3135/) for Python 3.0 (and [Pep 367 - New Super](http://www.python.org/dev/peps/pep-0367/) for Python 2.6). | In Python 3.0, you can use `super()` which is equivalent to `super(ThisClass, self)`.
Documentation [here](http://docs.python.org/3.0/library/functions.html#super). Code sample from the documentation:
```
class C(B):
def method(self, arg):
super().method(arg)
# This does the same thing as: sup... | Why do I have to specify my own class when using super(), and is there a way to get around it? | [
"",
"python",
"multiple-inheritance",
""
] |
I thought that to clone a List you would just call:
```
List<int> cloneList = new List<int>(originalList);
```
But I tried that in my code and I seem to be getting effects that imply the above is simply doing:
cloneList = originalList... because changes to cloneList seem to be affecting originalList.
So what is the... | You can use the below code to make a deep copy of the list or any other object supporting serialization:
Also you can use this for any version of .NET framework from v 2.0 and above, and the similar technique can be applied (removing the usage of generics) and used in 1.1 as well
```
public static class GenericCopier... | This would work...
```
List<Foo> cloneList = new List<Foo>(originalList);
```
When you say "because changes to cloneList seem to be affecting originalList." - do you mean changes to the **list**, or changes to the **items**...
Adding / removing / swapping items is changing the **list** - so if we do:
```
cloneList.... | Cloning List<T> | [
"",
"c#",
".net",
""
] |
Is there a standard way to bind arrays (of scalars) in a SQL query? I want to bind into an `IN` clause, like so:
```
SELECT * FROM junk WHERE junk.id IN (?);
```
I happen to be using `Perl::DBI` which coerces parameters to scalars, so I end up with useless queries like:
```
SELECT * FROM junk WHERE junk.id IN ('ARRA... | You specify "this is the SQL for a query with one parameter" -- that won't work when you want many parameters. It's a pain to deal with, of course. Two other variations to what was suggested already:
1) Use DBI->quote instead of place holders.
```
my $sql = "select foo from bar where baz in ("
. join(",", ... | If you don't like the map there, you can use the 'x' operator:
```
my $params = join ', ' => ('?') x @foo;
my $sql = "SELECT * FROM table WHERE id IN ($params)";
my $sth = $dbh->prepare( $sql );
$sth->execute( @foo );
```
The parentheses are needed around the '?' because that forces 'x' to be in list context.
... | Is there SQL parameter binding for arrays? | [
"",
"sql",
"perl",
"arrays",
"binding",
"parameters",
""
] |
When trying to display a byte stream from HLDS (Half-Life Dedicated Server) in a textbox, it displays strange blocky question mark characters that look something like this:
```
[?]
```
Here's a sample line from the byte stream (with [?] in place of the strange character):
```
CPU In Out Uptime Users FPS ... | Firstly, I believe that if textboxes ever receive a character 0, they will assume that's the end of data - you may want to guard against that specifically.
Where does your byte stream come from? What encoding is it *meant* to be? What are the bytes at that point in the data? | 1. Are you sure that the data is in pure ASCII? Is it perhaps in one of the many, many code-pages?
2. Is it perhaps because of [CR] vs [LF] vs [CR][LF]?
3. Can you tell use the bytes that are around "Players..."? And what you expect to see? We *might* be able to recognize the code-page
Presumably the byte is either in... | Strange characters returned from byte stream? | [
"",
"c#",
"character-encoding",
"arrays",
""
] |
I want to provide dynamic download of files. These files can be generated on-the-fly on serverside so they are represented as byte[] and do not exist on disk. I want the user to fill in an ASP.NET form, hit the download button and return the file he/she wanted.
Here is how my code behind the ASP.NET form looks like:
... | Here's a minor modification you need to make:
```
Response.Clear();
Response.ContentType = "application/x-zip-compressed";
Response.BinaryWrite(binary);
Response.End();
``` | This is my (working) implementation:
```
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=\"{0} {1} Report for Week {2}.pdf\"", ddlClient.SelectedItem.Text, ddlCollectionsDirects.SelectedItem.Text, ddlWeek.SelectedValue));
Response.BinaryW... | providing dynamic file download in ASP.NET2.0 | [
"",
"c#",
"asp.net",
"dynamic",
"download",
""
] |
I'm consuming a webservice from my application in C# .net (2.0) that return values (as string) like this:
```
%23k.%0d%16%c4%8a%18%efG%28%b9c%12%b7%f1%e2%e7j%93
```
I know that the real value for that is:
```
236B2E0D16C48A18EF4728B96312B7F1E2E76A93
```
But I don't know how to convert from the returned value to the... | Going down the line:
If you encounter '%' copy the next two characters
Otherwise take the ascii code of the character found and output as hex
```
%23 => 23
k => 6B
. => 2E
%0d => 0D
```
[ASCII Table](http://www.asciitable.com/)
But in code I'm pretty sure this will work:
```
char c = 'k';
int ascii = (int... | Thanks for the info Rob. If anyone wants the full method here it is:
```
static private string convertInfoHash(string encodedHash)
{
string convertedHash = string.Empty;
for (int i = 0; i < encodedHash.Length; i++)
{
if (encodedHash[i] == '%')
{
convertedHash += String.Format("{... | How to convert this sequence to this hash? | [
"",
"c#",
".net",
"hash",
""
] |
I'm working on a web app which is heavy on the client side, which is a first for me. I'm also using jQuery for the first time. I need to have my client-side code keep track of model data which it fetches via Ajax calls.
What's a good way to store this data? Does jQuery provide a good solution, or is there a good gener... | jQuery developer [Adam Wulf released a series of tutorials](http://welcome.totheinter.net/2008/08/05/mvc-pattern-for-the-web/) covering his development of MVC patterns on the client with jQuery some time back. You may find them to be very helpful in your current project. Also, JollyToad did some work in this area as we... | There is also, I've discovered, a technique known as Concrete Javascript, where the DOM objects are used as model objects. Effen sounds like a nice way to implement that: <http://github.com/nkallen/effen/tree/master>. | What's a good way to store model data in a jQuery app? | [
"",
"javascript",
"jquery",
"model",
""
] |
I've been using the `==` operator in my program to compare all my strings so far.
However, I ran into a bug, changed one of them into `.equals()` instead, and it fixed the bug.
Is `==` bad? When should it and should it not be used? What's the difference? | `==` tests for reference equality (whether they are the same object).
`.equals()` tests for value equality (whether they contain the same data).
[Objects.equals()](http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#equals(java.lang.Object,%20java.lang.Object)) checks for `null` before calling `.equals()`... | `==` tests object references, `.equals()` tests the string values.
Sometimes it looks as if `==` compares values, because Java does some behind-the-scenes stuff to make sure identical in-line strings are actually the same object.
For example:
```
String fooString1 = new String("foo");
String fooString2 = new String(... | How do I compare strings in Java? | [
"",
"java",
"string",
"equality",
""
] |
Simple question, but I haven't found a good explanation on google. When using Set Statistics IO ON, the logical reads and scan count is provided in the message window of management studio. If I have:
tblExample, scan count 5, logical reads 20
What does scan count signify? | From Books On Line
**Scan count:**
Number of index or table scans performed.
**logical reads:**
Number of pages read from the data cache.
**physical reads:**
Number of pages read from disk.
**read-ahead reads:**
Number of pages placed into the cache for the query.
See also here: <http://technet.microsoft.com/en-us... | As far as what a "table scan" *means*, the best I could find is this:
> **Scan count simply means how many times the table or index was accessed during the query.** It may be a full scan, partial scan, or simply a seek.
In other words, scan count alone by itself is *not enough information* to proceed. You need to kno... | sql statistics io scan count explanation | [
"",
"sql",
"performance",
"count",
"statistics",
"database-scan",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.