Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
It's been a while since I was in college and knew how to calculate a best fit line, but I find myself needing to. Suppose I have a set of points, and I want to find the line that is the best of those points. What is the equation to determine a best fit line? How would I do that with PHP?
Of additional interest is probably how good of a fit the line is. For that, use the Pearson correlation, here in a PHP function: ``` /** * returns the pearson correlation coefficient (least squares best fit line) * * @param array $x array of all x vals * @param array $y array of all y vals */ function pearson(a...
Here's an [article](http://www.johndcook.com/blog/2008/10/20/comparing-two-ways-to-fit-a-line-to-data/) comparing two ways to fit a line to data. One thing to watch out for is that there is a direct solution that is correct in theory but can have numerical problems. The article shows why that method can fail and gives ...
Find a "best fit" equation
[ "", "php", "math", "" ]
I have some data of the form ``` Key ID Link 1 MASTER 123 2 AA 123 3 AA 123 4 BB 123 5 MASTER 456 6 CC 456 ``` I would like to be able to select in the same select all linked items matching the selection criteria, plus the linked master. For example, ...
Here's one method. ``` SELECT DISTINCT key, id, link FROM the_table START WITH id = 'AA' CONNECT BY id = 'MASTER' and link = PRIOR link and 'AA' = PRIOR ID ```
SELECT \* FROM table\_name WHERE ID=your\_id UNION ALL SELECT \* FROM table\_name WHERE ID='MASTER' AND link = (SELECT link FROM table\_name WHERE ID=your\_id) That should answer to the question I understood ;)
How to select a related group of items in Oracle SQL
[ "", "sql", "oracle", "" ]
I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this? Example: ``` testlist = [1,2,3,5,3,1,2,1,6] for item in testlist: if item == 1: print position ```
Hmmm. There was an answer with a list comprehension here, but it's disappeared. Here: ``` [i for i,x in enumerate(testlist) if x == 1] ``` Example: ``` >>> testlist [1, 2, 3, 5, 3, 1, 2, 1, 6] >>> [i for i,x in enumerate(testlist) if x == 1] [0, 5, 7] ``` Update: Okay, you want a generator expression, we'll have...
What about the following? ``` print testlist.index(element) ``` If you are not sure whether the element to look for is actually in the list, you can add a preliminary check, like ``` if element in testlist: print testlist.index(element) ``` or ``` print(testlist.index(element) if element in testlist else None)...
How to get item's position in a list?
[ "", "python", "list", "" ]
I want to know the basic principle used for WYSIWYG pages on the web. I started coding it and made it using a text area, but very soon I realized that I cannot add or show images or any HTML in the text area. So I made it using DIV, but I did not understand how I could make it editable. So, in gist, **I want to know h...
There's the `contentEditable` flag that can be added to any element on a page to make it editable, eg. ``` <div contentEditable>I am editable!!!!</div> ``` Should work in all major browsers nowadays, and things like shortcuts keys (cmd/ctrl-b, etc) will Just Work. Form submission can then be done by pulling innerHTM...
*What you see is what you mean* is the way - don't follow the WYSIWYG path as it is full of traps. [WYMeditor](http://www.wymeditor.org/) is the best when it comes to outputting semantic and clean HTML.
How to make a WYSIWYG section on a web page?
[ "", "javascript", "html", "dom", "wysiwyg", "" ]
In jQuery, if I assign `class=auto_submit_form` to a form, it will be submitted whenever any element is changed, with the following code: ``` /* automatically submit if any element in the form changes */ $(function() { $(".auto_submit_form").change(function() { this.submit(); }); }); ``` However, if I want to...
``` /* submit if elements of class=auto_submit_item in the form changes */ $(function() { $(".auto_submit_item").change(function() { $("form").submit(); }); }); ``` Assumes you only have one form on the page. If not, you'll need to do select the form that is an ancestor of the current element using `$(thi...
You can use an expression in the `parents()` method to filter the parents. Hence this might be a little more efficient: ``` /* submit if elements of class=auto_submit_item in the form changes */ $(".auto_submit_item").change(function() { $(this).parents("form").submit(); }); ```
submit form when elements change
[ "", "javascript", "jquery", "" ]
I'm trying to run Python scripts using Xcode's User Scripts menu. The issue I'm having is that my usual os.sys.path (taken from ~/.profile) does not seem to be imported when running scripts from XCode the way it is when running them at the Terminal (or with IPython). All I get is the default path, which means I can't ...
On the mac, environment variables in your .profile aren't visible to applications outside of the terminal. If you want an environment variable (like PATH, PYTHONPATH, etc) to be available to xcode apps, you should add it to a new plist file that you create at ~/.MacOSX/environment.plist. See the [EnvironmentVars](htt...
A quick but hackish way is to have a wrapper script for python. ``` cat > $HOME/bin/mypython << EOF #!/usr/bin/python import os os.path = ['/list/of/paths/you/want'] EOF ``` and then start all your XCode scripts with ``` #!/Users/you/bin/mypython ```
How do I use my standard python path when running python scripts from xcode macros
[ "", "python", "xcode", "macos", "path", "" ]
I have an array filled with values (twitter ids) and I would like to find the missing data between the lowest id and the highest id? Any care to share a simple function or idea on how to do this? Also, I was wondering if I can do the same with mySQL? I have the key indexed. The table contains 250k rows right now, so a...
I had a similar requirement and wrote a function that would return a list of missing IDs. ``` --------------------------- create function dbo.FreeIDs () --------------------------- returns @tbl table (FreeID int) as begin declare @Max int declare @i int select @Max = MAX(ID) from [TheTable] set @i =...
Do you mean sequential ID's? In that case ``` $new_ids = range($lowid, $highid, 1); $ids = array_merge($ids, $new_ids); $ids = array_unique($ids); sort($ids); ``` And in SQL (with placeholders) ``` SELECT key, other_data from `table` WHERE key > :low_id AND key < :high_id ```
How to find missing data either in array or in mySQL table?
[ "", "php", "mysql", "" ]
so i have a winforms apps that downloads a set of data syncronously on startup. This obviously takes a while but then when any of the services or GUI classes load, they all have this data. I could change this to put on a background thread but then every component that needs access to this data would continuously have t...
I've written a number of applications that have similar behaviour to what you describe, and have three suggestions for you ... **Splash Screen** Add a splash screen to your application that displays the status of a number of startup steps. I've used this in the past when an application has a number of steps that have...
I would suggest you use the Observer Pattern and setup all the classes that rely on the data set being loaded. To minimize the amount of time the user needs to wait you could also consider implemented two categories of classes those that need the entire dataset to function and those that can function once a subset of t...
Loading lots of upfront data. . sync or async .
[ "", "c#", "winforms", "multithreading", "" ]
I'd like to call a function in python using a dictionary with matching key-value pairs for the parameters. Here is some code: ``` d = dict(param='test') def f(param): print(param) f(d) ``` This prints `{'param': 'test'}` but I'd like it to just print `test`. I'd like it to work similarly for more parameters: ...
Figured it out for myself in the end. It is simple, I was just missing the \*\* operator to unpack the dictionary So my example becomes: ``` d = dict(p1=1, p2=2) def f2(p1,p2): print(p1, p2) f2(**d) ```
``` In[1]: def myfunc(a=1, b=2): In[2]: print(a, b) In[3]: mydict = {'a': 100, 'b': 200} In[4]: myfunc(**mydict) 100 200 ``` A few extra details that might be helpful to know (questions I had after reading this and went and tested): 1. The function **can** have parameters that are *not* included in the dictionar...
Passing a dictionary to a function as keyword parameters
[ "", "python", "function", "dictionary", "parameters", "keyword", "" ]
My first instinct is to say each key is an object, and has a hash code, which is what is used to determine if a duplicate is being inserted. However, I can't find anything to back that up for sure. Can someone provide a link that says that, or provide the real answer here? Thanks!
The `Map` interface specifies that if two keys are `null` they are duplicates, otherwise if there's a key `k` such that `key.equals(k)`, then there is a duplicate. See the contains or get method here: <http://java.sun.com/javase/6/docs/api/java/util/Map.html#containsKey(java.lang.Object)> However, it's up to the `Map...
Read the question wrong, but the person's answer above is correct and my link provides the answer as to how it is determined (the equals method). Look at the contains and get methods in the link. How a map inserts: There cannot be a duplicate key in a Map. It will replace the old value with the new value if you find a...
What does Java use to determine if a key is a duplicate in a Map?
[ "", "java", "dictionary", "" ]
I have an exe that I know was written in java. I understand that java programs can be made into an exe and there are tools to convert jar files to exe but is it possible to convert back? AFAIK jar files can be run on any platform that can run java and I would like to use a windows compiled java program on mac without u...
It depends how the exe has been built: * If it has simply wrapped, with a tool like [JSmooth](http://jsmooth.sourceforge.net/docs/jsmooth-doc.html#N1034F), the same tool can [extract the jar](http://jsmooth.sourceforge.net/docs/jsmooth-doc.html#N1034F) * If it it has been compiled, with for instance gcj (as illustrate...
If your application was wrapped using JSmooth, you can look in your default temp directory (C:\Documents and Settings\Username\Local Settings\Temp) while the application is running. Open a windows explorer window to the temp dir, then start up your application. You should see a jar file show up (Temp#.jar). Just make ...
How can I extract java exe to jar
[ "", "java", "" ]
I put together a class yesterday to do some useful task. I started alpha testing, and at some point realized I was adding alpha test related methods to the class itself. It hit me that they don't belong there. After a bit of head scratching I derived a test class from the base class that has access to the protected mem...
One of the goals of unit testing is to verify the *interface* to your classes. This means that, generally speaking, you shouldn't be testing the dirty innards of your class. The unit test is supposed to interact with the public inputs and outputs of your class, and verify that the behaviour is as expected. You are thus...
It sounds like you don't want Unit testing, which is correctly the verification that the interface of a class works. You shouldn't have to change your class at all in order to do unit testing. If you are looking for a way to verify the internal state of your object so that it remains consistent, you should look into [D...
testing classes
[ "", "c++", "unit-testing", "" ]
I'm selecting 1 field from 1 table and storing it into a temp table. Sometimes that table ends up with 0 rows. I want to add that field onto another table that has 20+ fields Regular union won't work for me because of the field # mismatch. Outer wont work for me because there is nothing to compare. NVL doesn't work ...
What field would it match with? BTW, here's how to line them up: ``` SELECT NULL, NULL, NULL, NULL, MySingleField, NULL, NULL, NULL... FROM #temp UNION ALL SELECT Col1, Col2, Col3, Col4, Col5, Col6,... FROM OtherTable ``` UPDATE: OK, after reading your update... I don't think you want a UNION at all, but rather, and...
It sounds like you do want a join, not a union. You don't need to compare anything to do a join. You end up with a cross product if you specify no join condition: ``` SELECT t20.*, t1.* FROM table_with_20_columns AS t20 LEFT OUTER JOIN temp_table_with_1_column AS t1 ON (1=1); ``` When there are zero rows in the te...
Simple SQL code evades me.. Unionize two mismatched tables
[ "", "sql", "join", "union", "sql-update", "" ]
What does generator comprehension do? How does it work? I couldn't find a tutorial about it.
Do you understand list comprehensions? If so, a generator expression is like a list comprehension, but instead of finding all the items you're interested and packing them into list, it waits, and yields each item out of the expression, one by one. ``` >>> my_list = [1, 3, 5, 9, 2, 6] >>> filtered_list = [item for item...
A generator comprehension is the lazy version of a list comprehension. It is just like a list comprehension except that it returns an iterator instead of the list ie an object with a next() method that will yield the next element. If you are not familiar with list comprehensions see [here](http://docs.python.org/tuto...
How does a generator comprehension works?
[ "", "python", "generator", "" ]
I have a situation where in a web application a user may need a variable list of PDFs to be printed. That is, given a large list of PDFs, the user may choose an arbitrary subset of that list to print. These PDFs are stored on the file system. I need a method to allow users to print these batches of PDFs relatively easi...
The best solution I have for you is number 1. There are plenty of libraries that will merge documents. From the one I've used the numbering should not be an issue since all the pages are all ready rendered. If you go with ActiveX you are going to limit yourself to IE which might be acceptable. The only other idea woul...
I think concatenating the documents is the way to go. For tools I recommend iText#. Its free You can download here [iTextSharp](http://sourceforge.net/projects/itextsharp/) > iText# (iTextSharp) is a port of the iText open source java library for PDF generation written entirely in C# for the .NET platform. Use the iT...
Batch Printing PDFs from ASP.NET
[ "", "c#", "asp.net", "pdf", "printing", "" ]
I have a project that builds fine If I build it manually but it fails with CC.NET. The error that shows up on CC.NET is basically related to an import that's failing because file was not found; one of the projects (C++ dll) tries to import a dll built by another project. Dll should be in the right place since there's ...
Can you change CC to use msbuild instead of devenv? That seems like the optimal solution to me, as it means the build is the same in both situations.
After a long investigation - my understanding on this at current stage is that the problem is related to the fact that I am using devenv to build through CruiseControl.NET but when I build manually VisualStudio is using msbuild. Basically this causes dependencies to be ignored (because of some msbuild command arg that...
Why Build Fails with CruiseControl.NET but it builds fine manually with same settings?
[ "", "c++", "dll", "cruisecontrol.net", "" ]
If I have records: ``` Row Date, LocationID, Account 1 Jan 1, 2008 1 1000 2 Jan 2, 2008 1 1000 3 Jan 3, 2008 2 1001 4 Jan 3, 2008 1 1001 5 Jan 3, 2008 3 1001 6 Jan 4, 2008 3 1002 ``` I need to get the row (`date`, `locatinid`,...
I think this would work: ``` SELECT t1.* FROM table t1 JOIN (SELECT MAX(Date), LocationID FROM table GROUP BY Date, LocationID) t2 on t1.Date = t2.Date and t1.LocationID = t2.LocationID ```
Try something like: ``` select * from mytable t1 where date = (select max(date) from mytable t2 where t2.location = t1.location); ```
help with distinct rows and data ordering
[ "", "sql", "sql-server", "" ]
I have a query to the effect of ``` SELECT t3.id, a,bunch,of,other,stuff FROM t1, t2, t3 WHERE (associate t1,t2, and t3 with each other) GROUP BY t3.id LIMIT 10,20 ``` I want to know to many total rows this query would return without the LIMIT (so I can show pagination information). Normally, I would use this que...
There is a nice solution in MySQL. Add the keyword SQL\_CALC\_FOUND\_ROWS right after the keyword SELECT : ``` SELECT SQL_CALC_FOUND_ROWS t3.id, a,bunch,of,other,stuff FROM t1, t2, t3 WHERE (associate t1,t2, and t3 with each other) GROUP BY t3.id LIMIT 10,20 ``` After that, run another query with the function FOU...
Are the "bunch of other stuff" all aggregates? I'm assuming so since your GROUP BY only has t3.id. If that's the case then this should work: ``` SELECT COUNT(DISTINCT t3.id) FROM... ``` The other option of course is: ``` SELECT COUNT(*) FROM ( <Your query here> ) AS SQ ``` I don't use MySQL...
Getting the number of rows with a GROUP BY query
[ "", "sql", "mysql", "" ]
I have an existing database of a film rental system. Each film has a has a rating attribute. In SQL they used a constraint to limit the allowed values of this attribute. ``` CONSTRAINT film_rating_check CHECK ((((((((rating)::text = ''::text) OR ((rating)::text = 'G'::text)) OR ((rating)::te...
Sounds like you need to add support for a custom type: [Extending OracleAS TopLink to Support Custom Type Conversions](http://www.oracle.com/technetwork/middleware/ias/index-097678.html)
have you tried to store the ordinal value. Store the string value works fine if you don't have an associated String to the value: ``` @Enumerated(EnumType.ORDINAL) ```
How to use enums with JPA
[ "", "java", "jpa", "enums", "toplink", "" ]
The top of my `web.xml` file looks like this: ``` <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" version="2.5">...
Perhaps try: ``` http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd ``` Instead of: ``` http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd ``` --- Also, the `<!DOCTYPE ...>` is missing: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE xml> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://ww...
I hate that warning too. Specially because it appears in XML files that you haven't written but appear in your project for whatever reason (if you use MAVEN it's hell). With Eclipse 3.5+ you can easily remove this validation rule. Go to Preferences-->XML-->XML FILES --> Validation and Select "ignore". You may also ha...
Bogus Eclipse warning for web.xml: "No grammar constraints (DTD or XML schema) detected for the document."
[ "", "java", "eclipse", "xsd", "warnings", "" ]
I am developing a HTML form designer that needs to generate static HTML and show this to the user. I keep writing ugly code like this: ``` public string GetCheckboxHtml() { return ("&lt;input type="checkbox" name="somename" /&gt;"); } ``` Isn't there a set of strongly typed classes that describe html elements and...
Well, if you download the [ASP.NET MVC](http://www.codeplex.com/aspnet/Wiki/View.aspx?title=MVC&referringTitle=Home) DLL's (which you can use in *any* type of project... including Console apps)... then you can use the many HTML helpers they have.
One option is to use [XElement](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx) [functional construction](http://msdn.microsoft.com/en-us/library/bb387019.aspx). See [this blog post](http://jacobcarpenter.wordpress.com/2008/04/16/pc1-a-solution/) for an example calendar generator. In your case, ...
In C# 3.0, are there any classes that help me generate static html?
[ "", "c#", "html", "" ]
I have an API call in my application where I am checking the time taken for a single call. I have put this in a FOR loop and using 10000 calls to get the average times of all calls. Now the issue which came up was that the actual application using the API, is multi-threaded. If I wish to make my application also do the...
Probably the best C++ library to use for threading is the thread library in Boost, but like all C++ threading, you will be forced to manually do your synchronization. You will need to use mutex and lock types to make it work properly. Your question isn't very clear, so I can't really help you any more (though I think y...
If you read the Miranda IM source code, it should get you started. It's very well done and there are some nice hints in the code for how to rebase the memory offsets of other executables (on Windows) to make them load faster. <http://www.miranda-im.org/development/>
Implementing threads using C++
[ "", "c++", "multithreading", "" ]
I have three tables in the many-to-many format. I.e, table A, B, and AB set up as you'd expect. Given some set of A ids, I need to select only the rows in AB that match all of the ids. Something like the following won't work: "SELECT \* FROM AB WHERE A\_id = 1 AND A\_id = 2 AND A\_id = 3 AND ... " As no single row w...
A bit of a hacky solution is to use IN with a group by and having filter. Like so: ``` SELECT B_id FROM AB WHERE A_id IN (1,2,3) GROUP BY B_id HAVING COUNT(DISTINCT A_id) = 3; ``` That way, you only get the B\_id values that have exactly 3 A\_id values, and they have to be from your list. I used DISTINCT in the COUNT...
Your database doesn't appear to be normalized correctly. Your `AB` table should have a single `A_id` and a single `B_id` in each of its rows. If that were the case, your `OR`-version should work (although I would use `IN` myself). Ignore the preceding paragraph. From your edit, you really wanted to know all the `B`'s ...
MySQL strict select of rows involving many to many tables
[ "", "sql", "mysql", "many-to-many", "" ]
I need to write a 'simple' util to convert from ASCII to EBCDIC? The Ascii is coming from Java, Web and going to an AS400. I've had a google around, can't seem to find a easy solution (maybe coz there isn't one :( ). I was hoping for an opensource util or paid for util that has already been written. Like this maybe? ...
[JTOpen](http://jt400.sourceforge.net/), IBM's open source version of their Java toolbox has a collection of classes to access AS/400 objects, including a FileReader and FileWriter to access native AS400 text files. That may be easier to use then writing your own conversion classes. From the JTOpen homepage: > Here a...
Please note that a String in Java holds text in Java's native encoding. When holding an ASCII or EBCDIC "string" in memory, prior to encoding as a String, you'll have it in a byte[]. ``` ASCII -> Java: new String(bytes, "ASCII") EBCDIC -> Java: new String(bytes, "Cp1047") Java -> ASCII: string.getBytes("ASCII") J...
Convert String from ASCII to EBCDIC in Java?
[ "", "java", "ascii", "ibm-midrange", "ebcdic", "" ]
I've got a collection of records to process, and the processing can be parallelized, so I've created an [ExecutorService](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ExecutorService.html) (via [Executors#newCachedThreadPool()](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executors.html#...
To answer your question: **no**, two `ExecutorService` objects **cannot** share a thread pool. However you can share an `ExecutorService` between your objects, or alternatively create several Executors, as necessary, though this is less recommended. Best solution: share the `Executor` between your objects.
Short answer: No. Longer answer: You will need your own implementation to do that. `ExecutorService` is an interface and `AbstractExecutorService` is quite easy to implement. If you want two `ExecutorService` sharing same ThreadPool (e.g. with different maximum active thread value), you may use proxy pattern to make T...
Is it possible for two ExecutorServices to share a thread pool?
[ "", "java", "concurrency", "threadpool", "" ]
When designing tables, I've developed a habit of having one column that is unique and that I make the primary key. This is achieved in three ways depending on requirements: 1. Identity integer column that auto increments. 2. Unique identifier (GUID) 3. A short character(x) or integer (or other relatively small numeric...
I follow a few rules: 1. Primary keys should be as small as necessary. Prefer a numeric type because numeric types are stored in a much more compact format than character formats. This is because most primary keys will be foreign keys in another table as well as used in multiple indexes. The smaller your key, the smal...
Natural verses artifical keys is a kind of religious debate among the database community - see [this article](https://web.archive.org/web/20171109021306/http://r937.com:80/natural-or-surrogate-key.html) and others it links to. I'm neither in favour of **always** having artifical keys, nor of **never** having them. I wo...
What's the best practice for primary keys in tables?
[ "", "sql", "sql-server", "database", "relational", "" ]
Ok we have a number of solutions all with a lot of shared binaries: what we do is the following. In a shared drive we have this following layout where there is a directory for every binary dependency and a sub directory for every version BinaryDep1 -----------Volatile -----------1.0 -----------1.1 ----------...
What about the same struture in all developer machines? Like: d:/projects d:/projects/ext (the shared libraries you need here) d:/projects/project1 d:/projects/project2 d:/projects/project3 d:/projects/project4 ... ps: I love conventions.
You may want to have a look at [DEVPATH](http://msdn.microsoft.com/en-us/library/cskzh7h6.aspx). Other StackOverflow reference : [Support for DEVPATH](https://stackoverflow.com/questions/1186892/support-for-devpath)
Managing shared binary dependencies for multiple solutions
[ "", "c#", "winforms", "dependencies", "" ]
I'm doing a PHP site which displays code examples in various languages (C#, PHP, Perl, Ruby, etc.). Are there any PHP functions which add syntax coloring for these and other languages? If not, I would at least like to find that one built-in PHP function which does syntax coloring for PHP code, can't find it anymore. T...
Why not do the syntax coloration in the client side? Use [prettify.js](http://code.google.com/p/google-code-prettify/), its really versatile, Google Code and StackOverflow use it! Check the [test page](http://google-code-prettify.googlecode.com/svn/trunk/tests/prettify_test.html) for the supported languages.
You'd probably be better off formatting it in javascript actually. There are a few mature javascript syntax colors. * [highlight.js](http://softwaremaniacs.org/soft/highlight/en/) * [google highlighter](http://code.google.com/p/syntaxhighlighter/) * [prettify](http://code.google.com/p/google-code-prettify/)
PHP function which does syntax color parsing for multiple languages?
[ "", "php", "syntax-highlighting", "" ]
There's this Excel file I want users to be able to download from my server. There must be an easy way to initiate the download of the file after a click on the "Download" button... but I have no clue how to make that happen. I have this so far: (VBscript and ASP) ``` <head> <script type="text/javascript" src="overzic...
you're not going to believe this. Found it... ``` function exportmasterfile() { var url='../documenten/Master-File.xls'; window.open(url,'Download'); } ``` Sorry guys!
Actually, if you want a 'more-efficient' (and sexier) way, use: ``` location.href = your_url; ``` That way, you will save the compiler some time in going up to the `location`'s prototype chain up to the `window` object.
Download a file using Javascript
[ "", "javascript", "asp-classic", "vbscript", "" ]
Here's my scenario: I've got a table of (let's call them) nodes. Primary key on each one is simply "node\_id". I've got a table maintaining a hierarchy of nodes, with only two columns: parent\_node\_id and child\_node\_id. The hierarchy is maintained in a separate table because nodes can have an N:N relationship. Th...
"which one is likely to have the best performance? " : No one can know ! The only thing you can do is try both and MEASURE. That's sadly enough the main answer to all performance related questions... except in cases where you clearly have a O(n) difference between algorithms. And, by the way, "multiple parents" does n...
If performance is your concern, then that schema design is not going to work as well for you as others could. See [More Trees & Hierarchies in SQL](http://www.sqlteam.com/article/more-trees-hierarchies-in-sql) for more info.
MySQL stored procedure vs. multiple selects
[ "", "php", "mysql", "performance", "apache", "stored-procedures", "" ]
If I have a function that needs to work with a `shared_ptr`, wouldn't it be more efficient to pass it a reference to it (so to avoid copying the `shared_ptr` object)? What are the possible bad side effects? I envision two possible cases: 1) inside the function a copy is made of the argument, like in ``` ClassA::take_...
The point of a distinct `shared_ptr` instance is to guarantee (as far as possible) that as long as this `shared_ptr` is in scope, the object it points to will still exist, because its reference count will be at least 1. ``` Class::only_work_with_sp(boost::shared_ptr<foo> sp) { // sp points to an object that cannot...
I found myself disagreeing with the highest-voted answer, so I went looking for expert opinons and here they are. From <http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2011-Scott-Andrei-and-Herb-Ask-Us-Anything> Herb Sutter: "when you pass shared\_ptrs, copies are expensive" Scott Meyers: "There's nothing spec...
C++ - passing references to std::shared_ptr or boost::shared_ptr
[ "", "c++", "boost", "pass-by-reference", "pass-by-value", "shared-ptr", "" ]
Does anyone have any good suggestions for creating a Pipe object in Java which *is* both an InputStream and and OutputStream since Java does not have multiple inheritance and both of the streams are abstract classes instead of interfaces? The underlying need is to have a single object that can be passed to things whic...
It seems the point of this question is being missed. If I understand you correctly, you want an object that functions like an InputStream in one thread, and an OutputStream in another to create a means of communicating between the two threads. Perhaps one answer is to use composition instead of inheritance (which is r...
java.io.PipedOutputStream and java.io.PipedInputStream look to be the classes to use for this scenario. They are designed to be used together to pipe data between threads. If you really want some single object to pass around it would need to contain one of each of these and expose them via getters.
Input and Output Stream Pipe in Java
[ "", "java", "input", "multiple-inheritance", "" ]
I am giving link of a pdf file on my web page for download, like below ``` <a href="myfile.pdf">Download Brochure</a> ``` The problem is when user clicks on this link then * If the user have installed Adobe Acrobat, then it opens the file in the same browser window in Adobe Reader. * If the Adobe Acrobat is not inst...
Instead of linking to the .PDF file, instead do something like ``` <a href="pdf_server.php?file=pdffilename">Download my eBook</a> ``` which outputs a custom header, opens the PDF (binary safe) and prints the data to the user's browser, then they can choose to save the PDF despite their browser settings. The pdf\_ser...
This is a common issue but few people know there's a simple HTML 5 solution: ``` <a href="./directory/yourfile.pdf" download="newfilename">Download the pdf</a> ``` Where `newfilename` is the suggested filename for the user to save the file. Or it will default to the filename on the serverside if you leave it empty, l...
How to make PDF file downloadable in HTML link?
[ "", "php", "pdf", "xhtml", "download", "markup", "" ]
I have a set of conditions in my where clause like ``` WHERE d.attribute3 = 'abcd*' AND x.STATUS != 'P' AND x.STATUS != 'J' AND x.STATUS != 'X' AND x.STATUS != 'S' AND x.STATUS != 'D' AND CURRENT_TIMESTAMP - 1 < x.CREATION_TIMESTAMP ``` Which of these conditions will be executed first? I am using oracle. Wil...
Are you **sure** you "don't have the authority" to see an execution plan? What about using AUTOTRACE? ``` SQL> set autotrace on SQL> select * from emp 2 join dept on dept.deptno = emp.deptno 3 where emp.ename like 'K%' 4 and dept.loc like 'l%' 5 / no rows selected Execution Plan ------------------------...
The database will decide what order to execute the conditions in. Normally (but not always) it will use an index first where possible.
Execution order of conditions in SQL 'where' clause
[ "", "sql", "oracle", "where-clause", "" ]
I am currently doing some socket programming using C/C++. To be able to use a somewhat cleaner interface, and a more OO structure, I decided to write a few simple wrapper classes around parts of the C socket API, but while doing so I stumbled upon a problem: Given the following code: ``` // Global method int foo(int ...
The problem is that it first looks in the scope of your class, and finds a foo function. The lookup will stop then, and the compiler tries to match arguments. Since it only has the one foo function in that scope in your class, calling the function fails. You need to explicitly state that you want to call the free func...
You must use the scope resolution try: ::foo(1);
How to resolve name collision when using c headers?
[ "", "c++", "c", "scope", "" ]
I would like to manipulate the HTML inside an iframe using jQuery. I thought I'd be able to do this by setting the context of the jQuery function to be the document of the iframe, something like: ``` $(function(){ //document ready $('some selector', frames['nameOfMyIframe'].document).doStuff() }); ``` However th...
I think what you are doing is subject to the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy). This should be the reason why you are getting *permission denied type* errors.
If the `<iframe>` is from the same domain, the elements are easily accessible as ``` $("#iFrame").contents().find("#someDiv").removeClass("hidden"); ``` More on the [jQuery `.contents()` method](https://api.jquery.com/contents/) and ["how to access an iframe in jQuery"](https://web.archive.org/web/20180608003357/http...
How can I access the contents of an iframe with JavaScript/jQuery?
[ "", "javascript", "jquery", "iframe", "same-origin-policy", "" ]
My application is already developed and now we are going to change the connection string whatever stored in the session object (Bcoz of Distributed Database Management System (DDBMS)) Problem is here..... > ``` > In that application There are so many **ObjectDataSource** which are > ``` > > initialize with the using ...
To change the connection of an XSD at runtime you'll need to set the ConnectionModifier property of the table adapter to Public. If they're created by the "wizard" they will be set to Friend/Internal (VB/C#) by default. I had trouble finding the ConnectionModifier property (it's not listed in my vs2005 documentation)!...
This is one of the reasons I hate Typed Datasets, and is actually one of the short-comings of LinqToSQL as well (but is more easily worked around). I think you're stuck either regenerating all your typed datasets once you change the connection string, or going in and "customizing" them to use the connection string out...
Assign connection string to table adapter from session
[ "", "c#", "asp.net", "xsd", "" ]
The only reliable method that I a have found for using a script to download text from wikipedia is with cURL. So far the only way I have for doing that is to call `os.system()`. Even though the output appears properly in the python shell I can't seem to the function it to return anything other than the exit code(`0`). ...
From [Dive into Python:](http://diveintopython.net/html_processing/extracting_data.html) ``` import urllib sock = urllib.urlopen("http://en.wikipedia.org/wiki/Python_(programming_language)") htmlsource = sock.read() sock.close() print htmlsource ``` That will print out the source code for the Python Wikipedia article...
Answering the question, Python has a subprocess module which allows you to interact with spawned processes.<http://docs.python.org/library/subprocess.html#subprocess.Popen> It allows you to read the stdout for the invoked process, and even send items to the stdin. however as you said urllib is a much better option. i...
How do I get data from stdin using os.system()
[ "", "python", "shell", "curl", "urllib", "os.system", "" ]
I need to find the smallest power of two that's greater or equal to a given value. So far, I have this: ``` int value = 3221; // 3221 is just an example, could be any number int result = 1; while (result < value) result <<= 1; ``` It works fine, but feels kind of naive. Is there a better algorithm for that problem? ...
Here's my favorite. Other than the initial check for whether it's invalid (<0, which you could skip if you knew you'd only have >=0 numbers passed in), it has no loops or conditionals, and thus will outperform most other methods. This is similar to erickson's answer, but I think that my decrementing x at the beginning ...
``` ceil(log2(value)) ``` `ilog2()` can be calculated in 3 asm instructions e.g., [http://www.asterisk.org/doxygen/1.4/log2comp\_8h-source.html](https://web.archive.org/web/20081205054906/http://www.asterisk.org/doxygen/1.4/log2comp_8h-source.html)
Algorithm for finding the smallest power of two that's greater or equal to a given value
[ "", "c++", "algorithm", "assembly", "bit-manipulation", "" ]
I need to create simple reusable javascript object publishing several methods and parameterized constructor. After reading through several "OOP in JavaScript" guides I'm sitting here with an empty head. How on the Earth can I do this? Here my last non-working code: ``` SomeClass = function(id) { this._id = id; } ...
All **vars** are private: ``` SomeClass = function (id) { var THIS = this; // unambiguous reference THIS._id = id; var intFun = function () { // private return THIS._id; } this.extFun = function () { // public return intFun(); } } ``` Use **`THIS`** within private methods sin...
This is my usual approach: ``` MyClass = function(x, y, z) { // This is the constructor. When you use it with "new MyClass()," // then "this" refers to the new object being constructed. So you can // assign member variables to it. this.x = x; ... }; MyClass.prototype = { doSomething: function() { ...
Encapsulation in javascript
[ "", "javascript", "" ]
I have, for my game, a Packet class, which represents network packet and consists basically of an array of data, and some pure virtual functions I would then like to have classes deriving from Packet, for example: StatePacket, PauseRequestPacket, etc. Each one of these sub-classes would implement the virtual functions...
For copying you need to write a clone function, since a constructor cannot be virtual: ``` virtual Packet * clone() const = 0; ``` Which each Packet implementation implement like this: ``` virtual Packet * clone() const { return new StatePacket(*this); } ``` for example for StatePacket. Packet classes should be...
Why do we, myself included, always make such simple problems so complicated? --- Perhaps I'm off base here. But I have to wonder: Is this really the best design for your needs? By and large, function-only inheritance can be better achieved through function/method pointers, or aggregation/delegation and the passing a...
C++ design - Network packets and serialization
[ "", "c++", "inheritance", "serialization", "" ]
Let's say that I'm writing a library in C# and I don't know who is going to consume it. The public interface of the library has some unsigned types - uint, ushort. Apparently those types are not CLS-compliant and, theoretically speaking, there may be languages that will not be able to consume them. Are there in reali...
I believe in the original version of VB.NET, unsigned types were usable but there was no support for them built into the language. This has been addressed in later versions, of course. Additionally, I suspect that the now-defunct J# has no support for unsigned types (given that Java doesn't have any).
.NET compatibility and CLS compliance are two different things. Anything that can work in some way with the .NET framework could be said to be compatible with it. CLS compliance is more strict. It provides a set of rules for language implementors and library designers to follow so as to create an ecosystem of mutually ...
Are there languages compatible with .NET that don't support unsigned types?
[ "", "c#", ".net", "programming-languages", "unsigned", "" ]
I am considering Smarty as my web app templating solution, and I am now concerned with its performance against plain PHP. The Smarty site says it should be the same, however, I was not able to find anyone doing real benchmarking to prove the statement right or wrong. Did anyone do some benchmarking of Smarty vs plain...
Because in the end, Smarty compiles and caches the templates files to native PHP-code, there is indeed no theoretical performance difference. Of course there will always be some performance loss due to the chunk of Smarty-code that needs to be interpreted every time.
You might also want to take at a new template library that is similar to Smarty called [Dwoo](http://dwoo.org)
Smarty benchmark, anyone?
[ "", "php", "smarty", "template-engine", "" ]
I need to increment a String in java from "aaaaaaaa" to "aaaaaab" to "aaaaaac" up through the alphabet, then eventually to "aaaaaaba" to "aaaaaabb" etc. etc. Is there a trick for this?
It's not much of a "trick", but this works for 4-char strings. Obviously it gets uglier for longer strings, but the idea is the same. ``` char array[] = new char[4]; for (char c0 = 'a'; c0 <= 'z'; c0++) { array[0] = c0; for (char c1 = 'a'; c1 <= 'z'; c1++) { array[1] = c1; for (char c2 = 'a'; c2 <= 'z'; c2...
You're basically implementing a [Base 26 number system](http://en.wikipedia.org/wiki/Base_26) with leading "zeroes" ("a"). You do it the same way you convert a int to a base-2 or base-10 String, but instead of using 2 or 10, you use 26 and instead of '0' as your base, you use 'a'. In Java you can easily use this: ``...
How to increment a java String through all the possibilities?
[ "", "java", "string", "" ]
I'm not a JS guy so I'm kinda stumbling around in the dark. Basically, I wanted something that would add a link to a twitter search for @replies to a particular user while on that person's page. Two things I am trying to figure out: 1. how to extract the user name from the page so that I can construct the right URL. ...
Here's a pure-DOM method of the above -- and for kicks, I played with the extraction of the username as well: ``` var menuNode = document.getElementById('tabMenu'); if (menuNode!=null) { // extract username from URL; matches /ev and /ev/favourites var username = document.location.pathname.split("/")[1]; /...
Here is a way to do it, not really tested (no twitter account). ``` var userName = window.location.href.match(/^http:\/\/twitter\.com\/(\w+)/) if (userName == null) return; // Problem? userName = userName[1]; var menuNode = document.getElementById('tabMenu'); if (menuNode != null) { var html = '<a href="http://sea...
A little help with DOM manip and GreaseMonkey
[ "", "javascript", "twitter", "greasemonkey", "" ]
I've seen a good bit of setuptools bashing on the internets lately. Most recently, I read James Bennett's [On packaging](http://www.b-list.org/weblog/2008/dec/14/packaging/) post on why no one should be using setuptools. From my time in #python on Freenode, I know that there are a few souls there who absolutely detest ...
pip uses Setuptools, and doesn't require any changes to packages. It actually installs packages with Setuptools, using: ``` python -c 'import setuptools; __file__="setup.py"; execfile(__file__)' \ install \ --single-version-externally-managed ``` Because it uses that option (`--single-version-externally-manag...
For starters, pip is really new. New, incomplete and largely un-tested in the real world. It shows great promise but until such time as it can do everything that easy\_install/setuptools can do it's not likely to catch on in a big way, certainly not in the corporation. Easy\_install/setuptools is big and complex - an...
Questions about Setuptools and alternatives
[ "", "python", "packaging", "setuptools", "pip", "" ]
I need to have one column as the primary key and another to auto increment an order number field. Is this possible? EDIT: I think I'll just use a composite number as the order number. Thanks anyways.
``` CREATE TABLE [dbo].[Foo]( [FooId] [int] IDENTITY(1,1) NOT NULL, [BarId] [int] IDENTITY(1,1) NOT NULL ) ``` returns ``` Msg 2744, Level 16, State 2, Line 1 Multiple identity columns specified for table 'Foo'. Only one identity column per table is allowed. ``` So, no, you can't have two identity columns. Y...
You can use Sequence for second column with default value IF you use SQL Server 2012 ``` --Create the Test schema CREATE SCHEMA Test ; GO -- Create a sequence CREATE SEQUENCE Test.SORT_ID_seq START WITH 1 INCREMENT BY 1 ; GO -- Create a table CREATE TABLE Test.Foo (PK_ID int IDENTITY (1,1) PRIMARY KEY, ...
Can a sql server table have two identity columns?
[ "", "sql", "sql-server", "identity-column", "" ]
I have a database (NexusDB (supposedly SQL-92 compliant)) which contains and Item table, a Category table, and a many-to-many ItemCategory table, which is just a pair of keys. As you might expect, Items are assigned to multiple categories. I am wanting to all the end user to select all items which are ItemID | Catego...
You could try with EXCEPT ``` SELECT ItemID FROM Table EXCEPT SELECT ItemID FROM Table WHERE CategoryID <> 12 ```
> I want to be able to select all > ItemID's that are assigned to > Categories X, Y, and Z but NOT > assigned to Categories P and Q. I can't confirm from the NexusDB documentation on [SELECT](http://www.nexusdb.com/support/index.php?q=node/384) that they support subqueries, but they do support LEFT OUTER JOIN and GROU...
SQL question: excluding records
[ "", "sql", "nexusdb", "sql-match-all", "" ]
The topic generically says it all. Basically in a situation like this: ``` boost::scoped_array<int> p(new int[10]); ``` Is there any appreciable difference in performance between doing: `&p[0]` and `p.get()`? I ask because I prefer the first one, it has a more natural pointer like syntax. In fact, it makes it so you...
OK, I've done some basic tests as per Martin York's suggestions. It seems that g++ (4.3.2) is actually pretty good about this. At both -O2 and -O3 optimization levels, it outputs slightly different but functionally equivalent assembly for both `&p[0]` and `p.get()`. At -Os as expected, it took the path of least compl...
The only way to know is to actually measure it! But if you have the source of the boost:scoped\_array you could llok at the code and see what it does. I am sure it is pretty similar. ``` T * scoped_array::get() const // never throws { return ptr; } T & scoped_array::operator[](std::ptrdiff_t i) const // never th...
Performance implications of &p[0] vs. p.get() in boost::scoped_array
[ "", "c++", "performance", "boost", "" ]
why this is happen ? When u create abstract class in c++ Ex: **Class A** (which has a pure virtual function) after that **class B** is inherited from class **A** And if **class A** has constructor called **A()** suppose i created an **Object** of **class B** then the compiler initializes the base class first i.e.**cl...
Quick answer: constructors are special. When the constructor of A is still running, then the object being constructed is not yet truly of type A. It's still being constructed. When the constructor finishes, it's now an A. It's the same for the derived B. The constructor for A runs first. Now it's an A. Then the const...
`class A` is abstract but `class B` is not. In order to construct `class B`, it must implement all the pure virtual member functions of `class A`. ``` class A { public: A() {} virtual ~A() {} virtual void foo() = 0; // pure virtual int i; }; class B : public A { public: B() {} virtual ~B() {}...
Interesting C++ Abstract Function
[ "", "c++", "internals", "" ]
At a recent discussion on Silverlight the advantage of speed was brought up. The argument for Silverlight was that it performed better in the browser than Javascript because it is compiled (and managed) code. It was then stated that this advantage only applies to IE because IE interprets Javascript which is inefficien...
Speculating is fun. Or we could actually try a test or two... That [Silverlight vs. Javascript chess sample](http://silverlight.net/samples/sl2/silverlightchess/run/Default.html) has been updated for Silverlight 2. When I run it, C# averages 420,000 nodes per second vs. Javascript at 23,000 nodes per second. I'm runni...
Javascript is ran in a virtual machine by most browsers. However, Javascript is still a funky language, and even a "fast" virtual machine like V8 is incredibly slow by modern standards. I'd expect the CLR to be faster.
Does Silverlight have a performance advantage over JavaScript?
[ "", "javascript", "silverlight", "performance", "" ]
I'm currently writing some methods that do some basic operations on form controls eg Textbox, Groupbox, these operations are generic and can be used in any application. I started to write some unit tests and was just wondering should I use the real form controls found in System.Windows.Forms or should I just mock up t...
If you're trying to unit test the application logic by simulating interaction with the UI controls, you should do some abstraction using the [MVC pattern](http://en.wikipedia.org/wiki/Model-view-controller). Then you can just have a stub view and call the controller methods from your unit tests. If it's the actual con...
There are several patterns that are useful for separating UI presentation from UI logic including Model-View-Controller and the various incarnations of Model-View-Presenter (AKA Humble Dialog). Humble Dialog was concocted specifically to make unit testing easier. You should definitely have one of these UI patterns in y...
Unit testing method that uses UI controls
[ "", "c#", "unit-testing", "mocking", "" ]
I have a function which launches a javascript window, like this ``` function genericPop(strLink, strName, iWidth, iHeight) { var parameterList = "location=0,directories=0,status=0,menubar=0,resizable=no, scrollbars=no,toolbar=0,maximize=0,width=" + iWidth + ", height=" + iHeight; var new_wi...
Here is my solution using jQuery and jQuery UI libraries. Your API is not changed ~~, but parameter 'name' is ignored~~. I use `iframe` to load content from given `strLink` and then display that `iframe` as a child to generated `div`, which is then converted to modal pop-up using jQuery: ``` function genericPop(strLin...
I use this [dialog code](http://www.leigeber.com/2008/04/custom-javascript-dialog-boxes/) to do pretty much the same thing. If i remember correctly the default implementation does not support resizing the dialog. If you cant make with just one size you can modify the code or css to display multiple widths. usage is e...
How to refactor from using window.open(...) to an unobtrusive modal dhtml window?
[ "", "javascript", "modal-dialog", "" ]
Am I right to think that there is no way to set the selected value in the C# class SelectList after it is created? Isn't that a bit silly?
I think you are fighting the framework. The data going into your views should be created at the Last Possible Minute (LPM). Thinking this way, a `SelectList` is a type to feed the `DropDownList` HTML helper. It is NOT a place to store data while you decide how to process it. A better solution would be to retrieve you...
Because this is such a high result in Google, I'm providing what I found to work here (despite the age): If you are using a Strongly typed View (i.e. the Model has an assigned type), the SelectedValue provided to the Constructor of the SelectList is overwritten by the value of the object used for the Model of the page...
Set selected value in SelectList after instantiation
[ "", "c#", ".net", "asp.net-mvc", "selectlist", "" ]
As the title suggests. I want to be able to change the label of a single field in the admin application. I'm aware of the Form.field attribute, but how do I get my Model or ModelAdmin to pass along that information?
the [verbose name](http://docs.djangoproject.com/en/dev/topics/db/models/#verbose-field-names) of the field is the (optional) first parameter at field construction.
If your field is a property (a method) then you should use short\_description: ``` class Person(models.Model): ... def address_report(self, instance): ... # short_description functions like a model field's verbose_name address_report.short_description = "Address" ```
Can you change a field label in the Django Admin application?
[ "", "python", "python-3.x", "django", "django-forms", "django-admin", "" ]
I've been using [Rainlendar](http://www.rainlendar.net) for some time and I noticed that it has an option to put the window "on desktop". It's like a bottomMost window (as against topmost). How could I do this on a WPF app? Thanks
My answer is in terms of the Win32 API, not specific to WPF (and probably requiring P/Invoke from C#): Rainlendar has two options: * "On Desktop", it becomes a child of the Explorer desktop window ("Program Manager"). You could achieve this with the [SetParent](http://msdn.microsoft.com/en-us/library/ms633541(VS.85)....
This is what I used so the window is always "on bottom": ``` using System; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; ``` ... ``` [DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int c...
Window "on desktop"
[ "", "c#", "wpf", "" ]
I have an winforms application that was built using MVC. The controller is subscribing to all of the events from the view (button clicks, etc) and connects multiple views with the model. The problem is that the controller is now about 3000 lines of (hard to unit test) code. What is the best practice to avoid getting ...
One obvious thing to point out might be that one controller does not have to be implemented as one class. The MVC design pattern simply states that M, V and C are separate components, but not that each must be one, and only one, class.
### Sub controller Controller can be split in various **sub**-controller without broking the MVC pattern. At 3k lines, it's for sure that the cohesion is broken somewhere. Try to group together same behavior and create new controller. This way, you will have a "main" controller that will invoke "sub" controller. ###...
How to fight against really big controllers . .
[ "", "c#", "winforms", "model-view-controller", "" ]
I keep on hearing this words '**callback**' and '**postback**' tossed around. What is the difference between two ? Is postback very specific to the ASP.NET pages ?
A Postback occurs when the data (the whole page) on the page is posted from the client to the server..ie the **data is posted-back to the server**, and thus the page is refreshed (redrawn)...think of it as '**sending the server the whole page (asp.net) full of data**'. On the other hand, **a callback is also a special...
A postback occurs when a request is sent from the client to the server for the same page as the one the user is currently viewing. When a postback occurs, the entire page is refreshed and you can see the typical progression on the progress bar at the bottom of the browser. A callback, generally used with AJAX, occurs ...
Difference between a Postback and a Callback
[ "", "asp.net", "javascript", "postback", "callback", "" ]
When a pointer goes out of scope, its memory is freed, so why are `destructor`s created in c++?
If you're asking why C++ classes have destructors, some classes have requirements other than just freeing memory. You may have an object that's allocated a socket connection that needs to be shut down cleanly, for example. Also, 'unscoping' a pointer does *not* free the memory that it points to since other pointers ma...
When a pointer goes out of scope, the memory taken by *the pointer* is released. The 4 or 8 bytes (usually) of memory that are taken by the pointer, that is. The *object* (or other memory) that the pointer points to is *not* released when the pointer goes out of scope. You do that by *delete*'ing the pointer. And that...
Why are destructors required in C++?
[ "", "c++", "" ]
In Mootools, I'd just run `if ($('target')) { ... }`. Does `if ($('#target')) { ... }` in jQuery work the same way?
As the other commenters are suggesting the most efficient way to do it seems to be: ``` if ($(selector).length ) { // Do something } ``` If you absolutely must have an exists() function - which will be slower- you can do: ``` jQuery.fn.exists = function(){return this.length>0;} ``` Then in your code you can use...
no, jquery always returns a jquery object regardless if a selector was matched or not. You need to use .length ``` if ( $('#someDiv').length ){ } ```
How do you check if a selector matches something in jQuery?
[ "", "javascript", "jquery", "jquery-selectors", "" ]
I'd like to have my Eclipse plugin cause a URL to be opened by the users' default browser. This seems like pretty standard behavior, but I haven't been able to find any docs on how to do this. Can anyone help?
You are looking for: ``` final IWebBrowser browser = PlatformUI.getWorkbench().getBrowserSupport().createBrowser( ... ); browser.openURL(url); ```
If you want it in an external browser, you don't need to create one. This is the way: ``` PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser().openURL(new URL("http://www.example.com/")); ```
Launching a URL from an Eclipse plugin
[ "", "java", "eclipse", "eclipse-plugin", "" ]
I am interested in enabling code folding in Vim for Python code. I have noticed multiple ways to do so. Does anyone have a preferred way to do Python code folding in Vim? I.e, * Do you have a particular Vim plugin that you use and like? * Do you use manual folding or do you place markers in comments? * Any other reco...
Personally I can't convince myself to litter my code with the markers. I've become pretty used to (and efficient) at using indent-folding. Together with my mapping of space bar (see below) to open/close folds and the zR and zM commands, I'm right at home. Perfect for Python! ``` set foldmethod=indent nnoremap <space> ...
I use [this](http://www.vim.org/scripts/script.php?script_id=2462 "this") syntax file for Python. It sets the folding method to syntax and folds all classes and functions, but nothing else.
What is the recommended way to use Vim folding for Python code?
[ "", "python", "vim", "folding", "" ]
I have a small calculator that I am creating in C# (Sharp Develop). The user enters two values and the code returns the third. I am having trouble rounding the third value once it is returned. I have been through a couple of forums and the msdn site and I understand the code that is posted there, but I cant seem to mak...
Try using Math.Round() ``` tb2_kva.Text = Math.Round(z, # Places).ToString(); ```
Use [Math.Round](http://msdn.microsoft.com/en-us/library/system.math.round.aspx). Or, since you're going into a string, you could use either the [Standard Numeric Format Strings](http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx), or the [Custom ones](http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx). ``` Mat...
C# Round Value of a Textbox
[ "", "c#", "rounding", "" ]
Here's some code I have: ``` MyClass* MyClass::getInstance() { static MyClass instance; return &instance; } ``` I want to look into this singleton's current values. But I'm currently paused three hours into execution, and the reason I'm paused is that I'm out of memory. So I can't put a breakpoint in this metho...
Well, the function-scoped static `instance` variable doesn't show up in a `.map` file generated by `cl.exe /Fm`, and it doesn't show up when I use `x programname!*MyClass*` in WinDbg, so the mangled name doesn't seem to contain `MyClass` at all. **Option 1: Disassemble `MyClass::getInstance`** This approach seems eas...
That code just looks dangerous... :-) But anyway, your mangled name is going to depend on your [Calling Convention](http://www.codeproject.com/KB/cpp/calling_conventions_demystified.aspx) So before you find your mangle name you need to know what your build environment is using as the calling convention. MSDN has a lot...
How does VC++ mangle local static variable names?
[ "", "c++", "scope", "" ]
For a poor man's implementation of *near*-collation-correct sorting on the client side I need a JavaScript function that does *efficient* single character replacement in a string. Here is what I mean (note that this applies to German text, other languages sort differently): ``` native sorting gets it wrong: a b c o u...
I can't speak to what you are trying to do specifically with the function itself, but if you don't like the regex being built every time, here are two solutions and some caveats about each. Here is one way to do this: ``` function makeSortString(s) { if(!makeSortString.translate_re) makeSortString.translate_re = /[...
Here is a more complete version based on the Unicode standard. ``` var Latinise={};Latinise.latin_map={"Á":"A", "Ă":"A", "Ắ":"A", "Ặ":"A", "Ằ":"A", "Ẳ":"A", "Ẵ":"A", "Ǎ":"A", "Â":"A", "Ấ":"A", "Ậ":"A", "Ầ":"A", "Ẩ":"A", "Ẫ":"A", "Ä":"A", "Ǟ":"A", "Ȧ":"A", "Ǡ":"A", "Ạ":"A", "Ȁ":"A", "À":"A", "Ả":"A", "Ȃ":"A", "Ā":"A", ...
Efficiently replace all accented characters in a string?
[ "", "javascript", "sorting", "string", "collation", "" ]
I have a class 'Database' that works as a wrapper for ADO.net. For instance, when I need to execute a procedure, I call Database.ExecuteProcedure(procedureName, parametersAndItsValues). We are experiencing serious problems with Deadlock situations in SQL Server 2000. Part of our team is working on the sql code and tra...
First, I would review my SQL 2000 code and get to the bottom of why this deadlock is happening. Fixing this may be hiding a bigger problem (Eg. missing index or bad query). Second I would review my architecture to confirm the deadlocking statement really needs to be called that frequently (Does `select count(*) from b...
Building on @Sam's response, I present a general purpose retry wrapper method: ``` private static T Retry<T>(Func<T> func) { int count = 3; TimeSpan delay = TimeSpan.FromSeconds(5); while (true) { try { return func(); } catch(SqlException e) { ...
How to get efficient Sql Server deadlock handling in C# with ADO?
[ "", "c#", "sql-server", "ado.net", ".net-2.0", "deadlock", "" ]
Today I found out that putting strings in a resource file will cause them to be treated as literals, i.e putting "Text for first line \n Text for second line" will cause the escape character itself to become escaped, and so what's stored is "Text for first line \n Text for second line" - and then these come out in the ...
Since `\n` is actually a single character, you cannot acheive this by simply replacing the backslashes in the string. You will need to replace each pair of `\` and the following character with the escaped character, like: ``` s.Replace("\\n", "\n"); s.Replace("\\t", "\t"); etc ```
You'd be better served adjusting the resx files themselves. Line breaks can be entered via two mechanisms: You can edit the resx file as XML (right-click in Solution Explorer, choose "Open As," and choose XML), or you can do it in the designer. If you do it in the XML, simply hit Enter, backspace to the beginning of t...
string replace on escape characters
[ "", "c#", "string", "resx", "" ]
How to calculate minute difference between two date-times in PHP?
Subtract the past most one from the future most one and divide by 60. Times are done in Unix format so they're just a big number showing the number of seconds from `January 1, 1970, 00:00:00 GMT`
The answers above are for older versions of PHP. Use the DateTime class to do any date calculations now that PHP 5.3 is the norm. Eg. ``` $start_date = new DateTime('2007-09-01 04:10:58'); $since_start = $start_date->diff(new DateTime('2012-09-11 10:25:00')); echo $since_start->days.' days total<br>'; echo $since_star...
How to get time difference in minutes in PHP
[ "", "php", "date", "time", "minute", "" ]
All the documentation I've found so far is to update keys that are already created: ``` arr['key'] = val; ``` I have a string like this: `" name = oscar "` And I want to end up with something like this: ``` { name: 'whatever' } ``` That is, split the string and get the first element, and then put that in a dictio...
Use the first example. If the key doesn't exist it will be added. ``` var a = new Array(); a['name'] = 'oscar'; alert(a['name']); ``` Will pop up a message box containing 'oscar'. Try: ``` var text = 'name = oscar' var dict = new Array() var keyValuePair = text.replace(/ /g,'').split('='); dict[ keyValuePair[0] ] =...
Somehow all examples, while work well, are overcomplicated: * They use `new Array()`, which is an overkill (and an overhead) for a simple associative array (AKA dictionary). * The better ones use `new Object()`. It works fine, but why all this extra typing? This question is tagged "beginner", so let's make it simple....
Dynamically creating keys in a JavaScript associative array
[ "", "javascript", "associative-array", "" ]
Does anyone know of a `SQL` library in `ASP.NET` that can be used to manage tables? E.g. ``` SQLTable table = new SQLTable(); table.AddColumn(“First name”, varchar, 100); table.AddColumn(“Last name”, varchar, 100); if(table.ColumnExists(“Company”)) table.RemoveColumn(“Company”); ``` The operations I am looking for...
Use Microsoft.SqlServer.Management.Smo Other option would be to install the Microsoft Sql Server Web Data Administrator [Sql Server Web Data Administrator](http://www.microsoft.com/downloads/details.aspx?FamilyID=C039A798-C57A-419E-ACBC-2A332CB7F959&displaylang=en) Some references for Smo: [Create Table in SQL Serv...
[Subsonic](http://subsonicproject.com/) has a [migrations](http://subsonicproject.com/2-1-pakala/subsonic-using-migrations/) feature. It's fairly new, but I think it meets your 'intuitive' requirement.
Does an ASP.NET SQL Library Exist for Managing Tables?
[ "", "sql", ".net", "" ]
So I have an application that is based heavily on the QT API which using the QPlugin system. It's fairly simple to use, you define a class which inherit from an Interface and when the plugin is loaded you get an instance of that class. In the end it'll boil down to a `dlopen`/`dlsym` or `LoadLibrary`/`GetProcAddress`, ...
Create a set of interfaces for the main interaction objects that will be exposed by your application and build them in a lib/dll of their own and implement those interfaces on classes in your application as appropriate. The library should also include a plugin interface with perhaps just an "initialize" method that the...
Create a registry object that is passed to the plugin in the initialization function that contains a dictionary of exposed components. Then allow the plugin to request a pointer to components by string name or other identifier from this registry. It sacrifices compile-time type safety for a stable interface. There are...
Plugin API design
[ "", "c++", "api", "qt", "plugins", "dll", "" ]
I need to make a pop-up window for users to log-in to my website from other websites. I need to use a pop-up window to show the user the address bar so that they know it is a secure login, and not a spoof. For example, if I used a floating iframe, websites could spoof my login window and record the user's login inform...
Take a look at [this site.](http://www.quirksmode.org/js/popup.html) Some code copied from it: ``` <script language="javascript" type="text/javascript"> <!-- function popitup(url) { newwindow=window.open(url,'name','height=200,width=150'); if(!newindow){ alert('We have detected that you are using po...
Sean example is good, but you can still detect if the pop up has been blocked in the following way: ``` <script language="javascript" type="text/javascript"> <!-- function popitup(url) { newwindow=window.open(url,'name','height=200,width=150'); if(!newwindow){ alert('We have detected that you are using popup blocking...
How to create a pop-up window (the good kind)
[ "", "javascript", "popup", "window", "" ]
How do I setup a class that represents an interface? Is this just an abstract base class?
To expand on the answer by [bradtgmurray](https://stackoverflow.com/questions/318064/how-do-you-declare-an-interface-in-c#318084), you may want to make one exception to the pure virtual method list of your interface by adding a virtual destructor. This allows you to pass pointer ownership to another party without expos...
Make a class with pure virtual methods. Use the interface by creating another class that overrides those virtual methods. A pure virtual method is a class method that is defined as virtual and assigned to 0. ``` class IDemo { public: virtual ~IDemo() {} virtual void OverrideMe() = 0; }; class Chi...
How do you declare an interface in C++?
[ "", "c++", "inheritance", "interface", "abstract-class", "pure-virtual", "" ]
When executing the following (complete) SQL query on Microsoft SQL Server 2000: ``` SELECT B.ARTIFACTTNS, B.ARTIFACTNAME, B.ARTIFACTTYPE, B.INITIALBYTES, B.TIMESTAMP1, B.FILENAME, B.BACKINGCLASS, B.CHARENCODING, B.APPNAME, B.COMPONENTTNS, B.COMPONENTNAME, B.SCAMODULENAME, B.SCACOMPONENTNAME FROM (SELECT DISTI...
Because `ARTIFACTTYPE` can refer to either `A.ARTIFACTTYPE` or `B.ARTIFACTTYPE` and the server needs to know which one you want, just change it to `A.ARTIFACTTYPE` and you should be okay in this case. To clarify, you need to specify the alias prefix any time the column name is ambiguous. It isn't bad practice to alway...
If that's the exact query you're running, I have no idea why it would find anything ambiguous. I wrote what I think is an equivalent query and ran it in my database (Oracle) with no problem. **EDIT** Adding exact output of a new experiment in Oracle. The query executed in this experiment is the exact query given by t...
Ambiguous column name error
[ "", "sql", "sql-server", "sqlexception", "" ]
I have a table that looks a bit like this actors(forename, surname, stage\_name); I want to update stage\_name to have a default value of ``` forename." ".surname ``` So that ``` insert into actors(forename, surname) values ('Stack', 'Overflow'); ``` would produce the record ``` 'Stack' 'Overflow' 'Stack O...
MySQL does not support computed columns or expressions in the `DEFAULT` option of a column definition. You can do this in a trigger (MySQL 5.0 or greater required): ``` CREATE TRIGGER format_stage_name BEFORE INSERT ON actors FOR EACH ROW BEGIN SET NEW.stage_name = CONCAT(NEW.forename, ' ', NEW.surname); END ``` ...
According to [10.1.4. Data Type Default Values](http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html) no, you can't do that. You can only use a constant or `CURRENT_TIMESTAMP`. OTOH if you're pretty up-to-date, you could probably use a [trigger](http://dev.mysql.com/doc/refman/5.0/en/triggers.html) to accomp...
MySQL - Set default value for field as a string concatenation function
[ "", "sql", "mysql", "function", "default-value", "" ]
I need to create a trigger in every database on my sql 2005 instance. I'm setting up some auditing ddl triggers. I create a cursor with all database names and try to execute a USE statement. This doesn't seem to change the database - the CREATE TRIGGER statement just fires in adventureworks repeatedly. The other optio...
When you use EXEC() each use is in its own context. So, when you do EXEC('USE MyDB') it switches to MyDB for that context then the command ends and you're back where you started. There are a couple of possible solutions... You can call sp\_executesql with a database name (for example, MyDB..sp\_executesql) and it will...
You don't have to create a CURSOR... ``` sp_msforeachdb 'USE ?; PRINT ''Hello ?''' ``` EDIT: The "USE ?" part is to switch to the specified database... you may want to put an IF statement to make sure that the database name is what you'd like it to be.
Create a DDL trigger in every database on a 2005 instance
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
So I don't do a lot of Win32 calls, but recently I have had to use the [`GetFileTime()`](http://msdn.microsoft.com/en-us/library/ms724320(VS.85).aspx) and [`SetFileTime()`](http://msdn.microsoft.com/en-us/library/ms724933(VS.85).aspx) functions. Now although Win98 and below are not officially supported in my program pe...
If you call the functions directly, then your program will not load on Win98. What you can do is use `LoadLibrary()` / `GetProcAddress()` to get a pointer to `GetFileTime()` / `SetFileTime()`. On Win98 this will fail, giving you a null pointer which you can test for and ignore. On 2000 and later you will get a pointer...
You could call `FindFirstFile()` instead of `GetFileTime()`. I wouldn't know an alternative for `SetFileTime()`, though.
Calling NT function on pre-NT system
[ "", "c++", "windows", "winapi", "dll", "" ]
I am a beginner of python and have a question, very confusing for me. If I define a function first but within the function I have to use a variable which is defined in another function below, can I do it like this? Or how can I import the return things of another function into a function? for example: ``` def hello(x,...
The scope of functions `hello` and `hi` are entirely different. They do not have any variables in common. Note that the result of calling `hi(x,y)` is some object. You save that object with the name `good` in the function `hello`. The variable named `good` in `hello` is a different variable, unrelated to the variable...
If you want to define a variable to the global namespace from inside a function, and thereby make it accessible by other functions in this space, you can use the global keyword. Here's some examples ``` varA = 5 #A normal declaration of an integer in the main "global" namespace def funcA(): print varA #This wor...
A small question about python's variable scope
[ "", "python", "variables", "scope", "" ]
Pour in your posts. I'll start with a couple, let us see how much we can collect. To provide inline event handlers like ``` button.Click += (sender,args) => { }; ``` To find items in a collection ``` var dogs= animals.Where(animal => animal.Type == "dog"); ``` For iterating a collection, like ``` animals.ForEac...
Returning an custom object: ``` var dude = mySource.Select(x => new {Name = x.name, Surname = x.surname}); ```
Here's a slightly different one - you can use them [(like this)](http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/f44dc57a9dc5168d/02c312dcf8a9a769#4805324df6b30218) to simulate the missing "infoof"/"nameof" operators in C# - i.e. so that instead of hard-coding to a property ...
In what ways do you make use of C# Lambda Expressions?
[ "", "c#", ".net", "c#-3.0", "lambda", "" ]
i need a report and i should use pivot table for it.Report will be group by categories .It is not good to use case when statement because there are many categories.u can think Northwind Database as sample and All Categories will be shown as Columns and Report will show customers preference among Categories.I dont know ...
Once you get Oracle 11G there is a [built-in PIVOT feature](http://www.oracle.com/technology/pub/articles/oracle-database-11g-top-features/11g-pivot.html). Prior to that, you are restricted to using CASE (or DECODE) expressions. I have an article on how to automate doing that [on my blog.](http://tonyandrews.blogspot.c...
It is painful to do row/column swaps in SQL. Each row you want to turn into a column, you have to ask for explicitly. So if you have many categories, your query will be very long, and it'll change every time you add/remove/change a category (this is probably the CASE method you're mentioning). You can write a stored pr...
Advice Using Pivot Table in Oracle
[ "", "sql", "oracle", "plsql", "pivot", "" ]
Namely, how does the following code: ``` var sup = new Array(5); sup[0] = 'z3ero'; sup[1] = 'o3ne'; sup[4] = 'f3our'; document.write(sup.length + "<br />"); ``` output '5' for the length, when all you've done is set various elements? My 'problem' with this code is that I don't understand how `length` changes without...
Everything in JavaScript is an object. In the case of an `Array`, the `length` property returns the size of the internal storage area for indexed items of the array. Some of the confusion may come into play in that the `[]` operator works for both numeric and string arguments. For an array, if you use it with a numeric...
Characteristics of a JavaScript array 1. Dynamic - Arrays in JavaScript can grow dynamically .push 2. Can be sparse - for example, array[50000] = 2; 3. Can be dense - for example, array = [1, 2, 3, 4, 5] In JavaScript, it is hard for the runtime to know whether the array is going to be dense or sparse. So all it can ...
How are JavaScript arrays implemented?
[ "", "javascript", "arrays", "associative-array", "" ]
Suppose I have this interface ``` public interface IFoo { ///<summary> /// Foo method ///</summary> void Foo(); ///<summary> /// Bar method ///</summary> void Bar(); ///<summary> /// Situation normal ///</summary> void Snafu(); } ``` And this class ``` public class F...
[GhostDoc](http://www.roland-weigelt.de/ghostdoc/) does exactly that. For methods which aren't inherited, it tries to create a description out of the name. `FlingThing()` becomes `"Flings the Thing"`
You can always use the `<inheritdoc />` tag: ``` public class Foo : IFoo { /// <inheritdoc /> public void Foo() { ... } /// <inheritdoc /> public void Bar() { ... } /// <inheritdoc /> public void Snafu() { ... } } ``` Using the `cref` attribute, you can even refer to an entirely different memb...
Inheriting comments from an interface in an implementing class?
[ "", "c#", "inheritance", "comments", "" ]
I am currently investigating several free/open source OpenGL based 3D engines, and was wondering if you guys could provide some feedback on these engines and how they are to work with in a real world project. The engines being compared are (in no particular order): [Crystal Space](http://www.crystalspace3d.org/main/M...
**You can find a lot of informations on lot of engines [on this database.](http://www.devmaster.net/engines/)** CrystalSpace is a full engine so it's a monolithic bloc that you have to customize for your needs. Irrlicht too but it's made do do things easy. The counter effect is that it's hard to do specific things. N...
More focused on large terrains than games (think GIS or flight simulators) there is also [openscenegraph](http://www.openscenegraph.org/)
3D Engine Comparison
[ "", "c++", "open-source", "opengl", "3d", "cross-platform", "" ]
Given the schema ``` PERSON { name, spouse } ``` where PERSON.spouse is a foreign key to PERSON.name, NULLs will be necessary when a person is unmarried or we don't have any info. Going with the argument against nulls, how do you avoid them in this case? I have an alternate schema ``` PERSON { name } SPOUSE { name...
All right, use Auto-IDs and then use a Check Constraint. The "Name1" column (which would only be an int ID) will be force to only have ODD numbered IDs and Name2 will only have EVEN. Then create a Unique Constraint for Column1 and Column2.
I think that enforcing no NULLs and no duplicates for this type of relationship makes the schema definition way more complicated than it really needs to be. Even if you allow nulls, it would still be possible for a person to have more than one spouse, or to have conflicting records e.g: ``` PERSON { A, B } PERSON { B,...
Factoring out nulls in bill-of-materials style relations
[ "", "sql", "database", "referential-integrity", "" ]
We currently send an email notification in plain text or html format. Our environment is C#/.NET/SQL Server. I'd like to know if anyone recommends a particular solution. I see two ways of doing this: * dynamically convert current email to pdf using a third party library and sending the pdf as an attachment or * use...
You can use [iTextSharp](http://itextsharp.sourceforge.net/) to convert your html pages to pdf. Here's an example: ``` class Program { static void Main(string[] args) { string html = @"<html> <head> <meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8"" /> </head> <body> <p style="...
[iText-Sharp](http://itextsharp.sourceforge.net/) Works very much like the java version, and has both great documentation and multiple books available.
PDF generation in C#
[ "", "c#", ".net", "sql-server", "pdf", "reporting-services", "" ]
It is not uncommon for me (or likely anyone else) to have a list of objects I need to iterate through and then interact with a list of properties. I use a nested loop, like this: ``` IList<T> listOfObjects; IList<TProperty> listOfProperties; foreach (T dataObject in listOfObjects) { foreach (TProperty property in...
Looks like you are trying to cartesian join two lists, and apply a where clause. Here's a simple example showing the Linq syntax for doing this, which I think is what you are looking for. list1 and list2 can be any IEnumerable, your where clause can contain more detailed logic, and in your select clause you can yank ou...
There is certainly nothing wrong with nested loops. They are fast, readable and have been around since software development took its first baby steps. As you want to perform actions as you iterate over a collection, you may find that LINQ would be an interesting avenue to explore: <http://msdn.microsoft.com/en-us/vcs...
Calling fellow code nerds - Alternatives to Nested Loops?
[ "", "c#", "linq", "loops", "" ]
I am working on an If statement and I want to satisfy two conditions to ignore the loop. This seemed easy at first, but now... I don't know. this is my dilemma... ``` if((radButton1.checked == false)&&(radButton2.checked == false)) { txtTitle.Text = "go to work"; } ``` The dilemma is "go to work" is not executed ...
No, it requires them to both be false to *execute* the statement.
Nope, it requires both conditions to be false to *execute* the statement. Read again: ``` if ((radButton1.checked == false) && (radButton2.checked == false)) { txtTitle.Text = "Go to work"; } ``` In English: "If radButton1.checked is false AND radButton2.checked is false, then set the txtTitle.Text to 'Go to work...
Why is this a "so close yet so far" if statement?
[ "", "c#", ".net", "logic", "" ]
I am currently using TcpListener to address incoming connections, each of which are given a thread for handling the communication and then shutdown that single connection. Code looks as follows: ``` TcpListener listener = new TcpListener(IPAddress.Any, Port); System.Console.WriteLine("Server Initialized, listening for...
These are two quick fixes you can use, given the code and what I presume is your design: ## 1. Thread.Abort() If you have started this `TcpListener` thread from another, you can simply call `Abort()` on the thread, which will cause a `ThreadAbortException` within the blocking call and walk up the stack. ## 2. TcpLis...
`listener.Server.Close()` from another thread breaks the blocking call. ``` A blocking operation was interrupted by a call to WSACancelBlockingCall ```
Proper way to stop TcpListener
[ "", "c#", "sockets", "networking", "tcplistener", "" ]
How do you rotate an image with the canvas html5 element from the bottom center angle? ``` <html> <head> <title>test</title> <script type="text/javascript"> function startup() { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('...
First you have to translate to the point around which you would like to rotate. In this case the image dimensions are 64 x 120. To rotate around the bottom center you want to translate to 32, 120. ``` ctx.translate(32, 120); ``` That brings you to the bottom center of the image. Then rotate the canvas: ``` ctx.rotat...
The correct answer is, of course, Vincent's one. I fumbled a bit with this rotation/translation thing, and I think my little experiments could be interesting to show: ``` <html> <head> <title>test</title> <script type="text/javascript"> canvasW = canvasH = 800; imgW = imgH = 128; function start...
Canvas rotate from bottom center image angle?
[ "", "javascript", "html", "canvas", "rotation", "" ]
What do you think is the best way for obtaining the results of the work of a thread? Imagine a Thread which does some calculations, how do you warn the main program the calculations are done? You could poll every X milliseconds for some public variable called "job finished" or something by the way, but then you'll rec...
Don't use low-level constructs such as threads, unless you absolutely need the power and flexibility. You can use a [ExecutorService](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html) such as the [ThreadPoolExecutor](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolEx...
You could create a lister interface that the main program implements wich is called by the worker once it has finished executing it's work. That way you do not need to poll at all. Here is an example interface: ``` /** * Listener interface to implement to be called when work has * finished. */ public interface Wo...
Getting the output of a Thread
[ "", "java", "multithreading", "" ]
Since I've started using NetBeans, I've learned of some [powerful ways](http://www.netbeans.org/kb/60/java/gui-db.html) to abstract away the process of creating Java database applications with automatically generated UI, beans bindings, and a bunch of other stuff I only vaguely understand the workings of at the moment ...
The [JDBC Tutorial](http://java.sun.com/docs/books/tutorial/jdbc/index.html) is a good starting point A snippet from the intro ``` The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database. JDBC helps you to write java applications that manage these three p...
One you get comfortable with JDBC, you might want to consider using [Spring`s support for JDBC](http://static.springframework.org/spring/docs/2.5.x/reference/jdbc.html). It provides a much nicer API (than the standard libraries) for accessing a database via JDBC
What do I need to know to make a Java application that uses a database?
[ "", "java", "database", "netbeans", "" ]
I'm giving my first steps on Python. I saw that we don't have switch case statement, so I would you guys implement a text Menu in python? Thanks
You might do something like this: ``` def action1(): pass # put a function here def action2(): pass # blah blah def action3(): pass # and so on def no_such_action(): pass # print a message indicating there's no such action def main(): actions = {"foo": action1, "bar": action2, "baz": action3} ...
Generally if elif will be fine, but if you have lots of cases, please consider using a dict. ``` actions = {1: doSomething, 2: doSomethingElse} actions.get(n, doDefaultThing)() ```
Suggestion to implement a text Menu without switch case
[ "", "python", "" ]
Is there a way to identify at run-time of an executable is being run from within valgrind? I have a set of C++ unit tests, and one of them expects `std::vector::reserve` to throw `std::bad_alloc`. When I run this under valgrind, it bails out completely, preventing me from testing for both memory leaks (using valgrind) ...
You should look at [this page](http://valgrind.org/docs/manual/manual-core-adv.html#manual-core-adv.clientreq) from the Valgrind manual, it contains a `RUNNING_ON_VALGRIND` macro (included from valgrind.h) which does what you want.
If one does not want to include `valgrind.h` (which requires an autoconf test or similar) or use a wrapper, here's a heuristic for Linux (and other systems using ELF?): test the value of the `LD_PRELOAD` environment variable since Valgrind works by preloading libraries. I use the following test in C to check whether `L...
How can I detect if a program is running from within valgrind?
[ "", "c++", "unit-testing", "valgrind", "" ]
I get the above error whenever I try and use ActionLink ? I've only just started playing around with MVC and don't really understand what it's problem is with the code (below): ``` <%= Html.ActionLink("Lists", "Index", "Lists"); %> ``` This just seems to be a parsing issue but it only happens when I run the page. The...
Remove the semi-colon from the ActionLink line. Note: when using `<%= ... %>` there's no semi-colon and the code should return something, usually a string. When using `<% ...; %>`, i.e. no equals after the percent, the code should return void and you need a semi-colon before the closing percent. When using Html metho...
Use it without trailing semicolon: ``` <%= Html.ActionLink("Lists", "Index", "Lists") %> ```
ActionLink CS1026: ) expected
[ "", "c#", "asp.net", "asp.net-mvc", "" ]
How do I set the executable icon for my C++ application in visual studio 2008?
First go to Resource View (from menu: View --> Other Window --> Resource View). Then in Resource View navigate through resources, if any. If there is already a resource of Icon type, added by Visual Studio, then open and edit it. Otherwise right-click and select Add Resource, and then add a new icon. Use the embedded ...
This is how you do it in Visual Studio 2010. Because it is finicky, this can be quite painful, actually, because you are trying to do something *so incredibly simple*, but it isn't straight forward and there are many gotchas that Visual Studio doesn't tell you about. If at any point you feel angry or like you want to ...
How do I set the icon for my application in visual studio 2008?
[ "", "c++", "visual-studio", "visual-studio-2008", "icons", "" ]
Wnen I use external resources such as files or DB connection I need to close them before I let them go. Do I need to do the same thing with Swing components ? If yes then how ?
Normally, you don't need to dispose of objects when you are done with them (although setting the references to them to null may allow them to be GCed sooner). However, AWT and Swing objects allocate some amount of native resources that need to be freed. Furthermore, the AWT thread treats the windows as top-level object...
At one point it was taught that you had to disconnect all the listeners, because otherwise they'd act as references to the Swing component. But I'm told that this is no longer a problem.
Do I need to free Swing components before letting them get garbage collected?
[ "", "java", "swing", "" ]
I'm having an error where I am not sure what caused it. Here is the error: ``` Exception Type: OperationalError Exception Value: (1054, "Unknown column 'user_id' in 'field list'") ``` Does anyone know why I am getting this error? I can't figure it out. Everything seems to be fine. My view code is below: ``...
You'll have to show your models to get real help, but it looks like your Idea table doesn't have a user\_id column? Did you modify the SQL table structure?
1. The `user_id` field is the FK reference from `Idea` to `User`. It looks like you've changed your model, and not updated your database, then you'll have this kind of problem. Drop the old table, rerun syncdb. 2. Your model tables get an `id` field by default. You can call it `id` in your queries. You can also use...
"Unknown column 'user_id' error in django view
[ "", "python", "django", "django-models", "model", "view", "" ]
I am writing a program that does a lot of writes to a Postgres database. In a typical scenario I would be writing say 100,000 rows to a table that's well normalized (three foreign integer keys, the combination of which is the primary key and the index of the table). I am using PreparedStatements and executeBatch(), yet...
This is an issue that I have had to deal with often on my current project. For our application, insert speed is a critical bottleneck. However, we have discovered for the vast majority of database users, the select speed as their chief bottleneck so you will find that there are more resources dealing with that issue. ...
Check if your connection is set to autoCommit. If autoCommit is true, then if you have 100 items in the batch when you call executeBatch, it will issue 100 individual commits. That can be a lot slower than calling executingBatch() followed by a single explicit commit(). I would avoid the temptation to drop indexes or ...
Tips on Speeding up JDBC writes?
[ "", "java", "performance", "postgresql", "jdbc", "" ]
I have an update query being run by a cron task that's timing out. The query takes, on average, five minutes to execute when executed in navicat. The code looks roughly like this. It's quite simple: ``` // $db is a mysqli link set_time_limit (0); // should keep the script from timing out $query = "SLOW QUERY"; $resul...
I had the same problem somwhere, and "solved" it with the following code (first two lines of my file): ``` set_time_limit(0); ignore_user_abort(1); ```
According to the [manual](https://www.php.net/set_time_limit): > **Note**: The set\_time\_limit() function and the configuration directive max\_execution\_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using sys...
How to keep a php script from timing out because of a long mysql query
[ "", "php", "mysql", "timeout", "" ]
What's the regex to match a square bracket? I'm using `\\]` in a pattern in `eregi_replace`, but it doesn't seem to be able to find a `]`...
`\]` is correct, but note that PHP itself ALSO has `\` as an escape character, so you might have to use `\\[` (or a different kind of string literal).
Works flawlessly: ``` <?php $hay = "ab]cd"; echo eregi_replace("\]", "e", $hay); ?> ``` Output: ``` abecd ```
How do I match a square bracket literal using RegEx?
[ "", "php", "regex", "string", "" ]