Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm looking for a robust, easy-to-use, regular expression evaluator for native C++, either platform-independent or Windows-specific.
Requirements:
* Can't use Boost or ACE regex libraries (unfortunately)
* Can't use .NET Regex (or any managed code)
The main requirement is that it should be standalone and open. | C++11 now includes the support of regular expressions.
It will be platform independent. You just need a recent compiler.
Check the following list to know which one to use.
<http://wiki.apache.org/stdcxx/C%2B%2B0xCompilerSupport>
Hope it helps | try [libpcre](http://www.pcre.org/)
If you're stuck on windows they have a windows port which should work. I know [e-texteditor](http://e-texteditor.com) uses it, so at least that's proof it works :-) | Easy-to-Use Regular Expression Support in C++? | [
"",
"c++",
"regex",
"open-source",
""
] |
I'd like to use a database to store i18n key/value pairs so we can modify / reload the i18n data at runtime. Has anyone done this? Or does anyone have an idea of how to implement this? I've read several threads on this, but I haven't seen a workable solution.
I'm specifically refering to something that would work with... | Are you just asking how to store UTF-8/16 characters in a DB? in mysql it's just a matter of making sure you build with UTF8 support and setting that as the default, or specifying it at the column or table level. I've done this in oracle and mysql before. Create a table and cut and paste some i18n data into it and see ... | I finally got this working with danb's help above.
This is my resource bundle class and resource bundle control class.
I used this code from @[danb]'s.
```
ResourceBundle bundle = ResourceBundle.getBundle("AwesomeBundle", locale, DbResourceBundle.getMyControl());
javax.servlet.jsp.jstl.core.Config.set(actionBeanCont... | Database backed i18n for java web-app | [
"",
"java",
"internationalization",
""
] |
Why should I or shouldn't I use dirty reads:
```
set transaction isolation level read uncommitted
```
in SQL Server? | From [MSDN](http://msdn.microsoft.com/en-us/library/aa259216(SQL.80).aspx):
> When this option is set, it is possible to read uncommitted or dirty data; values in the data can be changed and rows can appear or disappear in the data set before the end of the transaction.
Simply put, when you are using this isolation l... | Generally when you need to do a sizeable (or frequent) queries to busy tables, where read committed would possibly be blocked by locks from uncommited transactions, but ONLY when you can live with inaccurate data.
As an example, on a gaming web site I worked on recently there was a summary display of some stats about ... | SQL Server - Dirty Reads Pros & Cons | [
"",
"sql",
"sql-server",
""
] |
When running a Java app from eclipse my ImageIcon shows up just fine.
But after creating a jar the path to the image obviously gets screwed up.
Is there a way to extract an image from the jar at runtime so I can then open it up? Or, is there a better way to do this?
I'd like to distribute a single jar file if possib... | To create an `ImageIcon` from an image file within the same jars your code is loaded:
```
new javax.swing.ImageIcon(getClass().getResource("myimage.jpeg"))
```
`Class.getResource` returns a URL of a resource (or `null`!). `ImageIcon` has a constructors that load from a URL.
To construct a URL for a resource in a jar... | You can try something like:
```
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("/images/image.jpg");
```
In your JAR file, you might have a directory structure of:
> MyJAR.jar
> - com (class files in here)
> - images
> ----image.jpg | Java Swing: Displaying images from within a Jar | [
"",
"java",
"swing",
"embedded-resource",
"imageicon",
""
] |
I want to return `StudentId` to use elsewhere outside of the *scope* of the `$.getJSON()`
```
j.getJSON(url, data, function(result)
{
var studentId = result.Something;
});
//use studentId here
```
I would imagine this has to do with scoping, but it doesn't seem to work the same way *c#* does | Yeah, my previous answer does not work because I didn't pay any attention to your code. :)
The problem is that the anonymous function is a callback function - i.e. getJSON is an async operation that will return at some indeterminate point in time, so even if the scope of the variable were outside of that anonymous fun... | > it doesn't seem to work the same way
> c# does
To accomplish scoping similar to C#, disable async operations and set dataType to json:
```
var mydata = [];
$.ajax({
url: 'data.php',
async: false,
dataType: 'json',
success: function (json) {
mydata = json.whatever;
}
});
alert(mydata); // has value of... | How can I return a variable from a $.getJSON function | [
"",
"javascript",
"jquery",
"ajax",
"scope",
"return-value",
""
] |
How can you allow a PHP script to write to a file with high-security restrictions, such as only allowing a single user to write to it?
The difficulty seems to be that a PHP script is running as a low-permissions user (maybe apache, or www, or nobody?), and even if I `chown` apache the\_writable\_file, the directory it... | Unfortunately, in shared hosts that use **mod\_php, there is no way to restrict access** to secure files to your web app and login user.
The solution is to **run your web app as your login user**. When you do that, UNIX file permissions can correctly lock everyone else out. There are several ways to implement that, in... | Sure, `chgrp apache the_writable_file` and `chmod g+w the_writable_file`. After that, only your secure user and the apache user will be able to write to the file. Since the apache user is typically forbidden from logging in, you only have to worry about web users writing to your secure file using through the http daemo... | php scripts writing to non-world-writable files | [
"",
"php",
"permissions",
""
] |
I was wondering if anybody knew of a method to configure apache to fall back to returning a static HTML page, should it (Apache) be able to determine that PHP has died? This would provide the developer with a elegant solution to displaying an error page and not (worst case scenario) the source code of the PHP page that... | The PHP source code is only displayed when apache is not configured correctly to handle php files. That is, when a proper handler has not been defined.
On errors, what is shown can be configured on php.ini, mainly the display\_errors variable. That should be set to off and log\_errors to on on a production environment... | I would assume that this typically results in a 500 error, and you can configure apaches 500 handler to show a static page:
ErrorDocument 500 /500error.html
You can also read about error handlers on [apaches documentation site](http://httpd.apache.org/docs/2.0/custom-error.html) | Apache Fall Back When PHP Fails | [
"",
"php",
"apache",
"configuration",
""
] |
The compiler usually chokes when an event doesn't appear beside a `+=` or a `-=`, so I'm not sure if this is possible.
I want to be able to identify an event by using an Expression tree, so I can create an event watcher for a test. The syntax would look something like this:
```
using(var foo = new EventWatcher(target... | **Edit:** As [Curt](https://stackoverflow.com/questions/35211/identify-an-event-via-a-linq-expression-tree#36255) has pointed out, my implementation is rather flawed in that it can only be used from within the class that declares the event :) Instead of "`x => x.MyEvent`" returning the event, it was returning the backi... | I too wanted to do this, and I have come up with a pretty cool way that does something like Emperor XLII idea. It doesn't use Expression trees though, as mentioned this can't be done as Expression trees do not allow the use of `+=` or `-=`.
We can however use a neat trick where we use .NET Remoting Proxy (or any other... | Identify an event via a Linq Expression tree | [
"",
"c#",
"linq",
"expression-trees",
""
] |
I am currently writing a simple, timer-based mini app in C# that performs an action `n` times every `k` seconds.
I am trying to adopt a test-driven development style, so my goal is to unit-test all parts of the app.
So, my question is: Is there a good way to unit test a timer-based class?
The problem, as I see it, ... | What I have done is to mock the timer, and also the current system time, so that my events could be triggered immediately, but as far as the code under test was concerned time elapsed was seconds. | [Len Holgate](http://www.lenholgate.com/) has a series of [20 articles on testing timer based code](http://www.lenholgate.com/archives/000306.html). | Unit testing a timer based application? | [
"",
"c#",
".net",
"unit-testing",
"timer",
""
] |
I've heard of a few ways to implement tagging; using a mapping table between TagID and ItemID (makes sense to me, but does it scale?), adding a fixed number of possible TagID columns to ItemID (seems like a bad idea), Keeping tags in a text column that's comma separated (sounds crazy but could work). I've even heard so... | Three tables (one for storing all items, one for all tags, and one for the relation between the two), properly indexed, with foreign keys set running on a proper database, should work well and scale properly.
```
Table: Item
Columns: ItemID, Title, Content
Table: Tag
Columns: TagID, Title
Table: ItemTag
Columns: Ite... | Normally I would agree with Yaakov Ellis but in this special case there is another viable solution:
Use two tables:
```
Table: Item
Columns: ItemID, Title, Content
Indexes: ItemID
Table: Tag
Columns: ItemID, Title
Indexes: ItemId, Title
```
This has some major advantages:
First it makes development much simpler: i... | Recommended SQL database design for tags or tagging | [
"",
"sql",
"database-design",
"tags",
"data-modeling",
"tagging",
""
] |
I'm new to SQL Server Reporting Services, and was wondering the best way to do the following:
> * Query to get a list of popular IDs
> * Subquery on each item to get properties from another table
Ideally, the final report columns would look like this:
```
[ID] [property1] [property2] [SELECT COUNT(*)
... | I would recommend using a [SubReport](http://msdn.microsoft.com/en-us/library/ms160348.aspx). You would place the SubReport in a table cell. | Simplest method is this:
```
select *,
(select count(*) from tbl2 t2 where t2.tbl1ID = t1.tbl1ID) as cnt
from tbl1 t1
```
here is a workable version (using table variables):
```
declare @tbl1 table
(
tbl1ID int,
prop1 varchar(1),
prop2 varchar(2)
)
declare @tbl2 table
(
tbl2ID int,
tbl1ID int
)
select *,
(s... | Best way to perform dynamic subquery in MS Reporting Services? | [
"",
"sql",
"sql-server",
"reporting-services",
"service",
"reporting",
""
] |
I found this open-source library that I want to use in my Java application. The library is written in C and was developed under Unix/Linux, and my application will run on Windows. It's a library of mostly mathematical functions, so as far as I can tell it doesn't use anything that's platform-dependent, it's just very b... | Your best bet is probably to grab a good c book (K&R: The C Progranmming language) a cup of tea and start translating! I would be skeptical about trusting a translation program, more often then not the best translator is yourself! If you do this one, then its done and you don't need to keep re-doing it. There might be ... | On the [Java GNU Scientific Library](http://sf.net/projects/jgsl) project I used [Swig](http://www.swig.org/) to generate the JNI wrapper classes around the C libraries. Great tool, and can also generate wrapper code in several languages including Python. Highly recommended. | What's the easiest way to use C source code in a Java application? | [
"",
"java",
"c",
"translation",
""
] |
We're looking for a Transformation library or engine which can read any input (EDIfact files, CSV, XML, stuff like that. So files (or webservices results) that contain data which must be transformed to a known business object structure.) This data should be transformed this to a existing business object using custom ru... | If you think that XSLT is too difficult for you, I think you can try LINQ to XML for parsing XML files. It is integrated in the .NET framework, and you can use C# (or, if you use VB.NET 9.0, better because of the XML literals) instead of learning another language. You can integrate it with the existing application with... | XSLT is not going to work for EDI and CSV. If you want a completely generic transformation engine, you might have to shell out some cash. I have used [Symphonia](http://www.symphonia3.com/) for dealing with EDI, and it worked, but it is not free.
The thing is the problem you are describing sounds "enterprisey" (I am s... | Is there a Transformation engine or library using .NET? | [
"",
"c#",
"transformation",
"altova",
""
] |
I am using Adobe Flex/Air here, but as far as I know this applies to all of JavaScript. I have come across this problem a few times, and there must be an easy solution out there!
Suppose I have the following XML (using e4x):
```
var xml:XML = <root><example>foo</example></root>
```
I can change the contents of the e... | It seems you confuse variables for the values they contain. The assignment
```
node = textInput.text;
```
changes the value the *variable* `node` points to, it doesn't change anything with the object that `node` currently points to. To do what you want to do you can use the `setChildren` method of the `XML` class:
`... | Ah thank you Theo - indeed seems I was confused there. I think the root of the confustion came from the fact I was able to assign
```
textInput.text = node;
```
Which I now guess is just implicity calling XML.toString() to convert XML->String. setChildren() is what I was looking for. | E4X : Assigning to root node | [
"",
"javascript",
"apache-flex",
"air",
"e4x",
""
] |
If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that?
For example, if I inherit from the Exception class I want to do something like this:
```
class MyExceptionClass : Exception
{
public MyExceptionClass(strin... | Modify your constructor to the following so that it calls the base class constructor properly:
```
public class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extrainfo) : base(message)
{
//other stuff here
}
}
```
Note that a constructor is not something that you ca... | Note that you can use **static** methods within the call to the base constructor.
```
class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extraInfo) :
base(ModifyMessage(message, extraInfo))
{
}
private static string ModifyMessage(string message, string ex... | Calling the base constructor in C# | [
"",
"c#",
".net",
"inheritance",
"constructor",
""
] |
I know that just using `rand()` is predictable, if you know what you're doing, and have access to the server.
I have a project that is **highly** dependent upon choosing a random number that is as unpredictable as possible. So I'm looking for suggestions, either other built-in functions or user functions, that can gen... | Adding, multiplying, or truncating a poor random source will give you a poor random result. See [Introduction to Randomness and Random Numbers](http://random.org/randomness/) for an explanation.
You're right about PHP rand() function. See the second figure on [Statistical Analysis](http://random.org/analysis/) for a s... | [random.org](http://random.org/clients/http/) has an API you can access via HTTP.
> RANDOM.ORG is a true random number service that generates randomness
> via atmospheric noise. | Better Random Generating PHP | [
"",
"php",
"security",
"random",
""
] |
I've created a simple desktop application in C# 3.0 to learn some C#, wpf and .Net 3.5.
My application essentially reads data from a csv file and stores it in a SQL server CE database. I use sqlmetal to generate the ORM code for the database.
My first iteration of this app is ugly as hell and I'm in the process of refa... | I would start with the [Composite Application Guidance for WPF](http://codeplex.com/CompositeWPF) (*cough* PRISM *cough*) from Microsoft's P&P team. With the download comes a great reference application that is the starting point for most of my WPF development today.
The [DotNetRocks crew](http://www.dotnetrocks.com/d... | The answer is "it depends" as always.
A few things to think about:
You may want to make this fat client app a web app (for example) at some point. If so, you should be sure to keep separation between the business layer (and below) and the presentation. The simplest way to do this is to be sure all calls to the busines... | How would you architect a desktop application in C# 3.0 | [
"",
"c#",
"wpf",
"architecture",
""
] |
I've just heard the term covered index in some database discussion - what does it mean? | A *covering index* is an index that contains all of, and possibly more, the columns you need for your query.
For instance, this:
```
SELECT *
FROM tablename
WHERE criteria
```
will typically use indexes to speed up the resolution of which rows to retrieve using *criteria*, but then it will go to the full table to re... | Covering index is just an ordinary index. It's called "covering" if it can satisfy query without necessity to analyze data.
example:
```
CREATE TABLE MyTable
(
ID INT IDENTITY PRIMARY KEY,
Foo INT
)
CREATE NONCLUSTERED INDEX index1 ON MyTable(ID, Foo)
SELECT ID, Foo FROM MyTable -- All requested data are cove... | What is a Covered Index? | [
"",
"sql",
"database",
"indexing",
""
] |
I'm working on a **multithreaded** C++ application that is corrupting the heap. The usual tools to locate this corruption seem to be inapplicable. Old builds (18 months old) of the source code exhibit the same behavior as the most recent release, so this has been around for a long time and just wasn't noticed; on the d... | My first choice would be a dedicated heap tool such as [pageheap.exe](https://support.microsoft.com/en-us/kb/286470).
Rewriting new and delete might be useful, but that doesn't catch the allocs committed by lower-level code. If this is what you want, better to Detour the `low-level alloc API`s using Microsoft Detours.... | I have same problems in my work (we also use `VC6` sometimes). And there is no easy solution for it. I have only some hints:
* Try with automatic crash dumps on production machine (see [Process Dumper](http://www.microsoft.com/downloads/details.aspx?FamilyID=e089ca41-6a87-40c8-bf69-28ac08570b7e&displaylang=en)). My ex... | Heap corruption under Win32; how to locate? | [
"",
"c++",
"windows",
"multithreading",
"debugging",
"memory",
""
] |
I've got two models: Message and Attachment. Each attachment is attached to a specific message, using a ForeignKey on the Attachment model. Both models have an auto\_now DateTimeField called updated. I'm trying to make it so that when any attachment is saved, it also sets the updated field on the associated message to ... | You would also need to then save the message. Then it that should work. | Proper version to work is: (attention to last line `self.message.save()`)
```
class Message(models.Model):
updated = models.DateTimeField(auto_now = True)
...
class Attachment(models.Model):
updated = models.DateTimeField(auto_now = True)
message = models.ForeignKey(Message)
def save(self):
... | Updating an auto_now DateTimeField in a parent model in Django | [
"",
"python",
"database",
"django",
"orm",
""
] |
I'm trying to unit test a custom ConfigurationSection I've written, and I'd like to load some arbitrary configuration XML into a [System.Configuration.Configuration](http://msdn.microsoft.com/en-us/library/system.configuration.configuration.aspx) for each test (rather than put the test configuration xml in the Tests.dl... | There is actually a way I've discovered....
You need to define a new class inheriting from your original configuration section as follows:
```
public class MyXmlCustomConfigSection : MyCustomConfigSection
{
public MyXmlCustomConfigSection (string configXml)
{
XmlTextReader reader = new XmlTextReader(n... | I think what you're looking for is ConfigurationManager.[OpenMappedExeConfiguration](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openmappedexeconfiguration.aspx)
It allows you to open a configuration file that you specify with a file path (wrapped inside a [ExeConfigurationFileMap... | Is there a way to get a System.Configuration.Configuration instance based on arbitrary xml? | [
"",
"c#",
".net",
"testing",
"configuration",
"configurationmanager",
""
] |
In php I have open a .php file and want to evaluate certain lines. Specifically when the $table\_id and $line variables are assigned a value.
Within the text file I have:
```
...
$table_id = 'crs_class'; // table name
$screen = 'crs_class.detail.screen.inc'; // file identifying screen stru... | use !==false instead of ===true
stripos returns the position as an integer if the needle is found. And that's never ===bool.
You might also be interested in PHP's [tokenizer module](https://www.php.net/tokenizer) or the [lexer package](http://pear.php.net/package/PHP_LexerGenerator) in the pear repository. | Variable interpolation is only performed on "strings", not 'strings' (note the quotes). i.e.
```
<?php
$foo = "bar";
print '$foo';
print "$foo";
?>
```
prints $foobar. Change your quotes, and all should be well. | strpos function issue in PHP not finding the needle | [
"",
"php",
"string",
""
] |
I am looking for a good JavaScript library for parsing XML data. It should be much easier to use than the built-in [XML DOM parsers](http://www.w3schools.com/Xml/xml_parser.asp) bundled with the browsers.
I got spoiled a bit working with JSON and am looking forward to something on similar lines for XML. | I use [jQuery](http://jquery.com/) for this. Here is a good example:
(EDIT: Note - the following blog seems to have gone away.)
<http://blog.reindel.com/2007/09/24/jquery-and-xml-revisited/>
There are also lots and lots of good examples in the [jQuery](http://jquery.com/) documentation:
<http://www.webmonkey.com/tu... | **Disclaimer:** I am the author if the open-source [Jsonix](https://github.com/highsource/jsonix) library which *may* be suitable for the task.
---
A couple of years ago I was also looking for a good XML<->JSON parsing/serialization library for JavaScript. I needed to process XML documents conforming to rather comple... | XML parser for JavaScript | [
"",
"javascript",
"xml",
"json",
"browser",
"parsing",
""
] |
As I get more and more namespaces in my solution, the list of using statements at the top of my files grows longer and longer. This is especially the case in my unit tests where for each component that might be called I need to include the using for the interface, the IoC container, and the concrete type.
With upward ... | Some people enjoy hiding the usings in a `#region`. Otherwise, I think you're out of luck. Unless you want to put the namespace on all your referents. | I know I shouldn't say this out loud, but, maybe reconsider your design.
17 usings in 1 file = a lot of coupling (on the namespace level). | Is there any way to get rid of the long list of usings at the top of my .cs files? | [
"",
"c#",
".net",
"visual-studio",
"namespaces",
""
] |
An instance of class A instantiates a couple of other objects, say for example from class B:
```
$foo = new B();
```
I would like to access A's public class variables from methods within B.
Unless I'm missing something, the only way to do this is to pass the current object to the instances of B:
```
$foo = new B($t... | That looks fine to me, I tend to use a rule of thumb of "would someone maintaining this understand it?" and that's an easily understood solution.
If there's only one "A", you could consider using the registry pattern, see for example <http://www.phppatterns.com/docs/design/the_registry> | I would first check if you are not using the wrong pattern: From your application logic, should B really know about A? If B needs to know about A, a parent-child relationship seems not quite adequate. For example, A could be the child, or part of A's logic could go into a third object that is "below" B in the hierarchy... | How do I access class variables of a parent object in PHP? | [
"",
"php",
"oop",
""
] |
I'm quoting part of an answer which I received for [another question of mine](https://stackoverflow.com/questions/83088/phpmysql-regular-recalcuation-of-benchmark-values-as-new-users-submit-their-data):
> In the PHP/MySQL world I would say
> stored procedures are no-go
I would like to know: Is that so? Why? Why not?
... | I develop and maintain a large PHP/MySQL application. Here is my experience with stored procedures.
Over time our application has grown very complex. And with all the logic on the php side, some operations would query the database with over 100 short queries.
MySQL is so quick that the performance was still acceptabl... | When using stored procedures with MySQL, you will often need to use the [mysqli](https://www.php.net/manual/en/book.mysqli.php) interface in PHP and not the regular [mysql](https://www.php.net/manual/en/book.mysql.php) interface.
The reason for this is due to the fact that the stored procedures often will return more ... | Stored procedures a no-go in the php/mysql world? | [
"",
"php",
"mysql",
"stored-procedures",
""
] |
Is there an easy way to avoid dealing with text encoding problems? | You can't really avoid dealing with the text encoding issues, but there are existing solutions in Apache Commons:
* `Reader` to `InputStream`: [`ReaderInputStream`](https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/input/ReaderInputStream.html)
* `Writer` to `OutputStream`: [`Writ... | If you are starting off with a String you can also do the following:
```
new ByteArrayInputStream(inputString.getBytes("UTF-8"))
``` | How to convert a Reader to InputStream and a Writer to OutputStream? | [
"",
"java",
"stream",
""
] |
Sometimes a labeled break or continue can make code a lot more readable.
```
OUTERLOOP: for ( ;/*stuff*/; ) {
//...lots of code
if ( isEnough() ) break OUTERLOOP;
//...more code
}
```
I was wondering what the common convention for the labels was. All caps? first cap? | If you have to use them use capitals, this draws attention to them and singles them out from being mistakenly interpreted as "Class" names. Drawing attention to them has the additional benefit of catching someone's eye that will come along and refactor your code and remove them. ;) | I don't understand where this "don't use labels" rule comes from. When doing non-trivial looping logic, the test to break or continue isn't always neatly at the end of the surrounding block.
```
outer_loop:
for (...) {
// some code
for (...) {
// some code
if (...)
continue outer_loop;
// more... | Java Coding standard / best practices - naming convention for break/continue labels | [
"",
"java",
"label",
"convention",
""
] |
So I came across an interesting problem today. We have a WCF web service that returns an IList. Not really a big deal until I wanted to sort it.
Turns out the IList interface doesn't have a sort method built in.
I ended up using the `ArrayList.Adapter(list).Sort(new MyComparer())` method to solve the problem but it j... | How about using LINQ To Objects to sort for you?
Say you have a `IList<Car>`, and the car had an `Engine` property, I believe you could sort as follows:
```
from c in list
orderby c.Engine
select c;
```
*Edit: You do need to be quick to get answers in here. As I presented a slightly different syntax to the other ans... | You can use LINQ:
```
using System.Linq;
IList<Foo> list = new List<Foo>();
IEnumerable<Foo> sortedEnum = list.OrderBy(f=>f.Bar);
IList<Foo> sortedList = sortedEnum.ToList();
``` | Sorting an IList in C# | [
"",
"c#",
"generics",
"sorting",
"ilist",
""
] |
What tool would you recommend to detect **Java package cyclic dependencies**,
knowing that the goal is to *list explicitly the specific classes involved in the detected 'across-packages cycle'*?
I know about [classycle](http://classycle.sourceforge.net/) and [JDepend](http://clarkware.com/software/JDepend.html), but t... | Findbugs can detect circular class dependencies and has an Eclipse plugin too.
<http://findbugs.sourceforge.net/> | Well... after testing [DepFinder presented above](https://stackoverflow.com/questions/62276/java-package-cycle-detection-how-to-find-the-specific-classes-involved#66059), it turns out it is great for a quick detection of simple dependencies, but it does not scale well with the number of classes...
So the REAL ACTUAL A... | Java package cycle detection: how do I find the specific classes involved? | [
"",
"java",
"class",
"dependencies",
"package",
""
] |
I got this error today when trying to open a Visual Studio 2008 **project** in Visual Studio 2005:
> The imported project "C:\Microsoft.CSharp.targets" was not found. | Open your csproj file in notepad (or notepad++)
Find the line:
```
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
```
and change it to
```
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
``` | > This is a global solution, not dependent on particular package or bin.
In my case, I removed **Packages** folder from my root directory.
> Maybe it happens because of your packages are there but compiler is not finding it's reference. so remove older packages first and add new packages.
Steps to **Add new packages... | The imported project "C:\Microsoft.CSharp.targets" was not found | [
"",
"c#",
"visual-studio",
""
] |
I wonder if anyone uses commercial/free java obfuscators on his own commercial product. I know only about one project that actually had an obfuscating step in the ant build step for releases.
Do you obfuscate? And if so, why do you obfuscate?
Is it really a way to protect the code or is it just a better feeling for t... | If you do obfuscate, stay away from obfuscators that modify the code by changing code flow and/or adding exception blocks and such to make it hard to disassemble it. To make the code unreadable it is usually enough to just change all names of methods, fields and classes.
The reason to stay away from changing code flow... | I think that the old (classical) way of the obfuscation is gradually losing its relevance. Because in most cases a classical obfuscators breaking a stack trace (it is not good for support your clients)
Nowadays the main point to not protect some algorithms, but to protect a sensitive data: API logins/passwords/keys, c... | Do you obfuscate your commercial Java code? | [
"",
"java",
"obfuscation",
""
] |
In PHP, how can I replicate the expand/contract feature for Tinyurls as on search.twitter.com? | If you want to find out where a tinyurl is going, use fsockopen to get a connection to tinyurl.com on port 80, and send it an HTTP request like this
```
GET /dmsfm HTTP/1.0
Host: tinyurl.com
```
The response you get back will look like
```
HTTP/1.0 301 Moved Permanently
Connection: close
X-Powered-By: PHP/5.2.6
Loca... | And here is how to *contract* an arbitrary URL using the TinyURL API. The general call pattern goes like this, it's a simple HTTP request with parameters:
<http://tinyurl.com/api-create.php?url=http://insertyourstuffhere.com>
This will return the corresponding TinyURL for <http://insertyourstuffhere.com>. In PHP, you... | PHP: How to expand/contract Tinyurls | [
"",
"php",
""
] |
What is the preferred way to remove spaces from a string in C++? I could loop through all the characters and build a new string, but is there a better way? | The best thing to do is to use the algorithm [`remove_if`](http://en.cppreference.com/w/cpp/algorithm/remove) and isspace:
```
remove_if(str.begin(), str.end(), isspace);
```
Now the algorithm itself can't change the container(only modify the values), so it actually shuffles the values around and returns a pointer to... | ```
std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');
str.erase(end_pos, str.end());
``` | Remove spaces from std::string in C++ | [
"",
"c++",
"string",
"stl",
"whitespace",
""
] |
```
std::vector<int> ints;
// ... fill ints with random values
for(std::vector<int>::iterator it = ints.begin(); it != ints.end(); )
{
if(*it < 10)
{
*it = ints.back();
ints.pop_back();
continue;
}
it++;
}
```
This code is not working because when `pop_back()` is called, `it` ... | The call to [`pop_back()`](http://en.cppreference.com/w/cpp/container/vector/pop_back) removes the last element in the vector and so the iterator to that element is invalidated. The `pop_back()` call does *not* invalidate iterators to items before the last element, only reallocation will do that. From Josuttis' "C++ St... | Here is your answer, directly from The Holy Standard:
> 23.2.4.2 A vector satisfies all of the requirements of a container and of a reversible container (given in two tables in 23.1) and of a sequence, including most of the optional sequence requirements (23.1.1).
> 23.1.1.12 Table 68
> expressiona.pop\_back()
> retu... | Does pop_back() really invalidate *all* iterators on an std::vector? | [
"",
"c++",
"stl",
""
] |
Say I have an ASMX web service, MyService. The service has a method, MyMethod. I could execute MyMethod on the server side as follows:
```
MyService service = new MyService();
service.MyMethod();
```
I need to do similar, with service and method not known until runtime.
I'm assuming that reflection is the way to go ... | I'm not sure if this would be the best way to go about it. The most obvious way to me, would be to make an HTTP Request, and call the webservice using an actual HTTP GET or POST. Using your method, I'm not entirely sure how you'd set up the data you are sending to the web service. I've added some sample code in VB.Net
... | // Try this ->
```
Type t = System.Web.Compilation.BuildManager.GetType("MyServiceClass", true);
object act = Activator.CreateInstance(t);
object o = t.GetMethod("hello").Invoke(act, null);
``` | Using reflection to call an ASP.NET web service | [
"",
"c#",
"asp.net",
"web-services",
"reflection",
""
] |
If you've used Oracle, you've probably gotten the helpful message "ORA-00942: Table or view does not exist". Is there a legitimate technical reason the message doesn't include the name of the missing object?
Arguments about this being due to security sound like they were crafted by the TSA. If I'm an attacker, I'd kno... | You can set an EVENT in your parameter file (plain text or spfile) to force Oracle to dump a detailed trace file in the user\_dump\_dest, the object name might be in there, if not the SQL should be.
EVENT="942 trace name errorstack level 12"
If you are using a plain text file you need to keep all your EVENT settings ... | SQL\*Plus does tell you the table that doesn't exist. For example:
```
SQL> select
2 *
3 from
4 user_tables a,
5 non_existent_table b
6 where
7 a.table_name = b.table_name;
non_existent_table b
*
ERROR at line 5:
ORA-00942: table or view does not exist
```
Here it shows that the na... | Why doesn't Oracle tell you WHICH table or view does not exist? | [
"",
"sql",
"database",
"oracle",
"ora-00942",
""
] |
What's the best way to delete all rows from a table in sql but to keep n number of rows on the top? | ```
DELETE FROM Table WHERE ID NOT IN (SELECT TOP 10 ID FROM Table)
```
**Edit:**
Chris brings up a good performance hit since the TOP 10 query would be run for each row. If this is a one time thing, then it may not be as big of a deal, but if it is a common thing, then I did look closer at it. | I would select ID column(s) the set of rows that you want to keep into a temp table or table variable. Then delete all the rows that do not exist in the temp table. The syntax mentioned by another user:
```
DELETE FROM Table WHERE ID NOT IN (SELECT TOP 10 ID FROM Table)
```
Has a potential problem. The "SELECT TOP 10... | Delete all but top n from database table in SQL | [
"",
"sql",
""
] |
What are the advantages/disadvantages between MS VS C++ 6.0 and MSVS C++ 2008?
The main reason for asking such a question is that there are still many decent programmers that prefer using the older version instead of the newest version.
Is there any reason the might prefer the older over the new? | Well, for one thing it may be because the executables built with MSVS 6 require only msvcrt.dll (C runtime) which is shipped with Windows now.
The MSVS 2008 executables need msvcrt9 shipped with them (or already installed).
Plus, you have a lot of OSS libraries already compiled for Windows 32 bit with the 6.0 C runti... | Advantages of Visual Studio 2008 over Visual C++ 6.0:
* Much more standards compliant C++ compiler, with better template handling
* Support for x64 / mobile / XBOX targets
* Improved STL implementation
* Support for C++0x TR1 (smart pointers, regular expressions, etc)
* Secure C runtime library
* Improved code navigat... | What are the differences between Visual C++ 6.0 and Visual C++ 2008? | [
"",
"c++",
"visual-studio",
"visual-c++-6",
""
] |
Exceptions in C++ don't need to be caught (no compile time errors) by the calling function. So it's up to the developer's judgment whether to catch them using try/catch (unlike in Java).
Is there a way one can ensure that the exceptions thrown are always caught using try/catch by the calling function? | No.
See [A Pragmatic Look at Exception Specifications](http://www.gotw.ca/publications/mill22.htm) for reasons why not.
The only way you can "help" this is to document the exceptions your function can throw, say as a comment in the header file declaring it. This is not enforced by the compiler or anything. Use code r... | You shouldn't be using an exception here. This obviously isn't an exceptional case if you need to be expecting it everywhere you use this function!
A better solution would be to get the function to return an instance of something like this. In debug builds (assuming developers exercise code paths they've just written)... | Ensuring that Exceptions are always caught | [
"",
"c++",
"exception",
"try-catch",
"exception-safety",
""
] |
Given that indexing is so important as your data set increases in size, can someone explain how indexing works at a database-agnostic level?
For information on queries to index a field, check out [How do I index a database column](https://stackoverflow.com/questions/1156/). | **Why is it needed?**
When data is stored on disk-based storage devices, it is stored as blocks of data. These blocks are accessed in their entirety, making them the atomic disk access operation. Disk blocks are structured in much the same way as linked lists; both contain a section for data, a pointer to the location... | Classic example **"Index in Books"**
Consider a "Book" of 1000 pages, divided by 10 Chapters, each section with 100 pages.
Simple, huh?
Now, imagine you want to find a particular Chapter that contains a word "**Alchemist**". Without an index page, you have no other option than scanning through the entire book/Chapte... | How does database indexing work? | [
"",
"sql",
"database",
"performance",
"indexing",
"database-indexes",
""
] |
A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor? | Python threads are good for **concurrent I/O programming**. Threads are swapped out of the CPU as soon as they block waiting for input from file, network, etc. This allows other Python threads to use the CPU while others wait. This would allow you to write a multi-threaded web server or web crawler, for example.
Howev... | The standard implementation of Python (generally known as CPython as it is written in C) uses OS threads, but since there is the [Global Interpreter Lock](http://en.wikipedia.org/wiki/Global_Interpreter_Lock), only one thread at a time is allowed to run Python code. But within those limitations, the threading libraries... | Are Python threads buggy? | [
"",
"python",
"multithreading",
""
] |
I'm working on a side project that would be a simple web application to maintain a list of classes and their upcoming schedules.
I would really like to use Linq to SQL for this project, but unfortunately the server environment I'm developing for only has MySql available. I've dabbled briefly with Subsonic but it just ... | I've long since completed the project which prompted this question, but recently I've had another project come along with very minor data requirements, so I spent some more time experimenting with this.
I had assumed that Sql Server Express required licensing fees to deploy, but this is not in fact the case. According... | Take a look at Microsoft SQL Server Compact Edition. I believe you can work with MDF files without having to run a server. All code runs in process. I believe it has some limitations but it may work for you and I think it's free. | Would building an application using a Sql Server Database File (mdf) be a terrible idea? | [
"",
"asp.net",
"sql",
"mysql",
"sql-server",
""
] |
One simple method I've used in the past is basically just creating a second table whose structure mirrors the one I want to audit, and then create an update/delete trigger on the main table. Before a record is updated/deleted, the current state is saved to the audit table via the trigger.
While effective, the data in ... | How much writing vs. reading of this table(s) do you expect?
I've used a single audit table, with columns for Table, Column, OldValue, NewValue, User, and ChangeDateTime - generic enough to work with any other changes in the DB, and while a LOT of data got written to that table, reports on that data were sparse enough... | We are using two table design for this.
One table is holding data about transaction (database, table name, schema, column, application that triggered transaction, host name for login that started transaction, date, number of affected rows and couple more).
Second table is only used to store data changes so that we ca... | Suggestions for implementing audit tables in SQL Server? | [
"",
"sql",
"sql-server",
"database",
"audit",
""
] |
I seem right now to be embroiled in a debate with another programmer on this project who thinks that views have no merits. He proposes a system that PHP looks something like this:
```
$draw = new Draw;
$nav = $draw->wideHeaderBox().
$draw->left().
$draw->image().
Image::get($image,60,array('id'=>'header_im... | HTML time-savers are useful, but they're only useful when they're intuitive and easy-to-understand. Having to instantiate a `new Draw` just doesn't sound very natural. Furthermore, `wideHeaderBox` and `left` will only have significance to someone who intimately knows the system. And what if there *is* a redesign, like ... | The argument he uses is the argument you need to *have* views. Both result in only changing it in one place. However, in his version, you are mixing view markup with business code.
I would suggest using more of a templated design. Do all your business logic in the PHP, setup all variables that are needed by your page.... | To use views or not to use views | [
"",
"php",
"model-view-controller",
""
] |
What is the RegEx pattern for DateTime (2008-09-01 12:35:45 ) ?
I get this error:
> No ending delimiter '^' found
Using:
```
preg_match('(?n:^(?=\d)((?<day>31(?!(.0?[2469]|11))|30(?!.0?2)|29(?(.0?2)(?=.{3,4}(1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(16|[2468][048]|[3579][26])00))|0?[1-9]|1\d|2[0-8])(?<sep>[/.... | @Espo: I just have to say that regex is incredible. I'd hate to have to write the code that did something useful with the matches, such as if you wanted to actually find out what date and time the user typed.
It seems like Tom's solution would be more tenable, as it is about a zillion times simpler and with the additi... | A simple version that will work for the format mentioned, but not all the others as per @Espos:
```
(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})
``` | What is the regex pattern for datetime (2008-09-01 12:35:45 )? | [
"",
"php",
"regex",
"datetime",
""
] |
When a java based application starts to misbehave on a windows machine, you want to be able to kill the process in the task manager if you can't quit the application normally. Most of the time, there's more than one java based application running on my machine. Is there a better way than just randomly killing java.exe ... | Download [Sysinternal's Process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx). It's a task manager much more powerfull than Windows's own manager.
One of it's features is that you can see all the resources that each process is using (like registry keys, hard disk directories, named pipes, et... | Run `jps -lv` which shows PIDs and command lines of all running Java processes.
Determine PID of the task you want to kill. Then use command:
```
taskkill /PID <pid>
```
to kill the misbehaving process. | Knowing which java.exe process to kill on a windows machine | [
"",
"java",
"windows",
""
] |
I recently encountered a problem where a value was null if accessed with Request.Form but fine if retrieved with Request.Params. What are the differences between these methods that could cause this? | Request.Form only includes variables posted through a form, while Request.Params includes both posted form variables and get variables specified as URL parameters. | Request.Params contains a combination of QueryString, Form, Cookies and ServerVariables (added in that order).
The difference is that if you have a form variable called "key1" that is in both the QueryString and Form then Request.Params["key1"] will return the QueryString value and Request.Params.GetValues("key1") wil... | When do Request.Params and Request.Form differ? | [
"",
"c#",
"asp.net",
"request",
""
] |
Hopefully, I can get answers for each database server.
For an outline of how indexing works check out: [How does database indexing work?](https://stackoverflow.com/questions/1108/how-does-database-indexing-work) | The following is SQL92 standard so should be supported by the majority of RDMBS that use SQL:
```
CREATE INDEX [index name] ON [table name] ( [column name] )
``` | `Sql Server 2005` gives you the ability to specify a covering index. This is an index that includes data from other columns at the leaf level, so you don't have to go back to the table to get columns that aren't included in the index keys.
```
create nonclustered index my_idx on my_table (my_col1 asc, my_col2 asc) inc... | How do I index a database column | [
"",
"sql",
"database",
"indexing",
""
] |
I'm using namespaces in a project and Eclipse PDT, my IDE of choice, recognizes them as syntax errors. Not only it renders its convenient error checking unusable, but it also ruins Eclipse's PHP explorer.
5.3 features are coming to PDT 2.0 scheduled for release in December. Are there any alternatives for the present m... | Some threads that have been addressed by the various PHP IDE developers regarding the status of 5.3 syntax support:
* **PHPEclipse**: <http://www.phpeclipse.net/ticket/636> or [google](http://www.google.com.au/search?q=php+5.3+phpeclipse)
* **Aptana**: <http://forums.aptana.com/viewtopic.php?t=6538> or [google](http:/... | This [blog](http://spektom.blogspot.com/2009/03/php-53-support-in-pdt-2nd-stage-is-over.html) states that PHP 5.3 support already presents in [latest integration](http://www.eclipse.org/pdt/downloads/) of PDT 2.1.0. | Any PHP editors supporting 5.3 syntax? | [
"",
"php",
"ide",
""
] |
I'm trying to write a stored procedure to select employees who have birthdays that are upcoming.
`SELECT * FROM Employees WHERE Birthday > @Today AND Birthday < @Today + @NumDays`
This will not work because the birth year is part of Birthday, so if my birthday was '09-18-1983' that will not fall between '09-18-2008' ... | *Note: I've edited this to fix what I believe was a significant bug. The currently posted version works for me.*
This should work after you modify the field and table names to correspond to your database.
```
SELECT
BRTHDATE AS BIRTHDAY
,FLOOR(DATEDIFF(dd,EMP.BRTHDATE,GETDATE()) / 365.25) AS AGE_NOW
,FLOOR(DATED... | In case someone is still looking for a solution in **MySQL** (slightly different commands), here's the query:
```
SELECT
name,birthday,
FLOOR(DATEDIFF(DATE(NOW()),birthday) / 365.25) AS age_now,
FLOOR(DATEDIFF(DATE_ADD(DATE(NOW()),INTERVAL 30 DAY),birthday) / 365.25) AS age_future
FROM user
WHERE 1 = (FLOOR(DATED... | SQL Select Upcoming Birthdays | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a decimal number (let's call it **goal**) and an array of other decimal numbers (let's call the array **elements**) and I need to find all the combinations of numbers from **elements** which sum to goal.
I have a preference for a solution in C# (.Net 2.0) but may the best algorithm win irrespective.
Your metho... | Interesting answers. Thank you for the pointers to Wikipedia - whilst interesting - they don't actually solve the problem as stated as I was looking for exact matches - more of an accounting/book balancing problem than a traditional bin-packing / knapsack problem.
I have been following the development of stack overflo... | I think you've got a [bin packing problem](http://en.wikipedia.org/wiki/Bin_packing_problem) on your hands (which is NP-hard), so I think the only solution is going to be to try every possible combination until you find one that works.
Edit: As pointed out in a comment, you won't *always* have to try *every* combinati... | Algorithm to find which numbers from a list of size n sum to another number | [
"",
"c#",
"algorithm",
"math",
"np-complete",
""
] |
What JavaScript keywords (function names, variables, etc) are reserved? | We should be linking to the actual sources of info, rather than just the top google hit.
<http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Reserved_Words>
JScript 8.0:
<http://msdn.microsoft.com/en-us/library/ttyab5c8.aspx> | Here is my poem, which includes all of the reserved keywords in JavaScript, and is dedicated to those who remain honest in the moment, and not just try to score:
```
Let this long package float,
Goto private class if short.
While protected with debugger case,
Continue volatile interface.
Instanceof super synchroniz... | Reserved keywords in JavaScript | [
"",
"javascript",
"reserved-words",
""
] |
I'm using an XmlSerializer to deserialize a particular type in mscorelib.dll
```
XmlSerializer ser = new XmlSerializer( typeof( [.Net type in System] ) );
return ([.Net type in System]) ser.Deserialize( new StringReader( xmlValue ) );
```
This throws a caught `FileNotFoundException` when the assembly is loaded:
> "C... | I'm guessing now. but:
1. The system might be generating a serializer for the whole of mscorlib, which could be very slow.
2. You could probably avoid this by wrapping the system type in your own type and serialising that instead - then you'd get a serializer for your own assembly.
3. You might be able to build the se... | The delay is because, having been unable to find the custom serializer dll, the system is building the equivalent code (which is very time-consuming) on the fly.
The way to avoid the delay is to have the system build the DLL, and make sure it's available to the .EXE - have you tried this? | FileNotFoundException for mscorlib.XmlSerializers.DLL, which doesn't exist | [
"",
"c#",
".net",
"serialization",
"assemblies",
""
] |
I am developing an application that controls an Machine.
When I receive an error from the Machine the users should be able to directly notice it, one way that is done is Flashing the tray on the taskbar. When the machine clears the error the tray should stop flashing.
There's one little annoyance using the `FlashWin... | Behaviour is the same when a window finishes flashing for as long as it's supposed to: the taskbar button stays coloured. I don't think this is a bug. If you think about it, when you use `FLASHW_STOP`, the flashing does in fact stop, but the point of the flashing is to get the user's attention. The button stays coloure... | Here's an error:
> fInfo.uCount = UInt32.MaxValue;
You should set fInfo.uCount to zero when calling with FLASHW\_STOP parameter.
Otherwise when you try to call stop when taskbar button is active it will stay active.
You can check a note about undefined behavior here:
<http://msdn.microsoft.com/en-us/library/windows/... | FlashWindowEx FLASHW_STOP still keeps taskbar colored | [
"",
"c#",
"winapi",
"pinvoke",
""
] |
Nokia has stopped offering its Developer's Suite, relying on other IDEs, including Eclipse. Meanwhile, Nokia changed its own development tools again and EclipseMe has also changed. This leaves most documentation irrelevant.
I want to know what does it take to make a simple Hello-World?
(I already found out myself, so... | Here's what's needed to make a simple hello world -
1. Get [Eclipse](http://www.eclipse.org/downloads/) IDE for Java. I used Ganymede. Set it up.
2. Get Sun's [Wireless Toolkit](http://java.sun.com/products/sjwtoolkit/download.html). I used 2.5.2. Install it.
3. Get Nokia's SDK ([found here](http://developers.nokia.co... | Unless you need to do something Nokia-specific, I suggest avoiding the Nokia device definitions altogether. Develop for a generic device, then download your application to real, physical devices for final testing. The steps I suggest:
1. Download and install Sun's Wireless Toolkit.
2. Install EclipseME, using the meth... | How to create J2ME midlets for Nokia using Eclipse | [
"",
"java",
"eclipse",
"java-me",
"nokia",
"java-wireless-toolkit",
""
] |
I need to write a program used internally where different users will have different abilities within the program.
Rather than making users have a new username and password, how do I tie into an existing domain server's login system?
Assume .NET (C#, VB, ASP, etc)
-Adam | For WinForms, use System.Threading.Thread.CurrentPrincipal with the IsInRole() method to check which groups they are a member of. You do need to set the principal policy of the AppDomain to WindowsPrincipal first.
Use this to get the current user name:
```
private string getWindowsUsername()
{
AppDomain.CurrentDo... | I would use LDAP
and the DirectorySearcher Class:
<http://msdn.microsoft.com/en-us/library/system.directoryservices.directorysearcher.aspx> | How to tie into a domain server's login for program access rights | [
"",
"c#",
""
] |
I need to remotely install windows service on number of computers, so I use CreateService() and other service functions from winapi. I know admin password and user name for machines that I need access to. In order to gain access to remote machine I impersonate calling process with help of LogonUser like this:
```
//al... | You can do it , the account needs to exist on the remote machine and you need to use the machine name for the domain name in the LogonUser call. | Rather than rolling your own, why not just use the SC built-in command? | Remote installing of windows service | [
"",
"c++",
"windows",
"windows-services",
""
] |
I've got an Active Directory synchronization tool (.NET 2.0 / C#) written as a Windows Service that I've been working on for a while and have recently been tasked with adding the ability to drive events based on changes in group membership. The basic scenario is that users are synchronized with a security database and,... | I'd say it depends on how many active directory objects you need to keep track of. If it's a small number (less than 1000 users) you can probably serialize your state data to disk with little noticable performance hit. If you're dealing with a very large number of objects it might be more efficient to create a simple p... | You can set up auditing for the success of account modifications in group policy editor
You may then monitor security log for entries and handle log entries on account modifications.
E.g.
```
EventLog myLog = new EventLog("Security");
// set event handler
myLog.EntryWritten += new EntryWritt... | Monitoring group membership in Active Directory more efficiently (C# .NET) | [
"",
"c#",
".net",
"active-directory",
""
] |
OK, so I don't want to start a holy-war here, but we're in the process of trying to consolidate the way we handle our application configuration files and we're struggling to make a decision on the best approach to take. At the moment, every application we distribute is using it's own ad-hoc configuration files, whether... | XML XML XML XML. We're talking *config files here*. There is no "angle bracket tax" if you're not serializing objects in a performance-intense situation.
Config files must be human readable and human understandable, in addition to machine readable. XML is a good compromise between the two.
If your shop has people tha... | YAML, for the simple reason that it makes for very readable configuration files compared to XML.
XML:
```
<user id="babooey" on="cpu1">
<firstname>Bob</firstname>
<lastname>Abooey</lastname>
<department>adv</department>
<cell>555-1212</cell>
<address password="xxxx">ahunter@example1.com</address>
... | Application configuration files | [
"",
"java",
"xml",
"json",
"cross-platform",
"configuration-files",
""
] |
Why are pointers such a leading factor of confusion for many new, and even old, college-level students in C or C++? Are there any tools or thought processes that helped you understand how pointers work at the variable, function, and beyond level?
What are some good practice things that can be done to bring somebody to... | Pointers is a concept that for many can be confusing at first, in particular when it comes to copying pointer values around and still referencing the same memory block.
I've found that the best analogy is to consider the pointer as a piece of paper with a house address on it, and the memory block it references as the ... | In my first Comp Sci class, we did the following exercise. Granted, this was a lecture hall with roughly 200 students in it...
Professor writes on the board: `int john;`
John stands up
Professor writes: `int *sally = &john;`
Sally stands up, points at john
Professor: `int *bill = sally;`
Bill stands up, points at... | What are the barriers to understanding pointers and what can be done to overcome them? | [
"",
"c++",
"c",
"pointers",
""
] |
I was looking for a tree or graph data structure in C#, but I guess there isn't one provided. [An Extensive Examination of Data Structures Using C# 2.0](http://msdn.microsoft.com/en-us/library/ms379574.aspx) a bit about why. Is there a convenient library which is commonly used to provide this functionality? Perhaps thr... | My best advice would be that there is no standard tree data structure because there are so many ways you could implement it that it would be impossible to cover all bases with one solution. The more specific a solution, the less likely it is applicable to any given problem. I even get annoyed with LinkedList - what if ... | ```
delegate void TreeVisitor<T>(T nodeData);
class NTree<T>
{
private T data;
private LinkedList<NTree<T>> children;
public NTree(T data)
{
this.data = data;
children = new LinkedList<NTree<T>>();
}
public void AddChild(T data)
{
children.AddFirst(new NTree<T>(da... | Tree data structure in C# | [
"",
"c#",
"data-structures",
""
] |
What's the most efficient way to concatenate strings? | The `StringBuilder.Append()` method is much better than using the `+` operator. But I've found that, when executing 1000 concatenations or less, `String.Join()` is even more efficient than `StringBuilder`.
```
StringBuilder sb = new StringBuilder();
sb.Append(someString);
```
The only problem with `String.Join` is th... | [Rico Mariani](https://blogs.msdn.microsoft.com/ricom/), the .NET Performance guru, had [an article](https://blogs.msdn.microsoft.com/ricom/2003/12/15/more-stringbuilder-advice/) on this very subject. It's not as simple as one might suspect. The basic advice is this:
> If your pattern looks like:
>
> `x = f1(...) + f2... | Most efficient way to concatenate strings? | [
"",
"c#",
".net",
"string",
"performance",
"optimization",
""
] |
I need to be able to manipulate a large (10^7 nodes) graph in python. The data corresponding to each node/edge is minimal, say, a small number of strings. What is the most efficient, in terms of ***memory and speed***, way of doing this?
A dict of dicts is more flexible and simpler to implement, but I intuitively expe... | I would strongly advocate you look at [NetworkX](http://networkx.github.com/). It's a battle-tested war horse and the first tool most 'research' types reach for when they need to do analysis of network based data. I have manipulated graphs with 100s of thousands of edges without problem on a notebook. Its feature rich ... | Even though this question is now quite old, I think it is worthwhile to mention my own python module for graph manipulation called [graph-tool](http://graph-tool.skewed.de). It is very efficient, since the data structures and algorithms are implemented in C++, with template metaprograming, using the Boost Graph Library... | What is the most efficient graph data structure in Python? | [
"",
"python",
"performance",
"data-structures",
"graph-theory",
""
] |
Short version: I want to trigger the Form\_Load() event without making the form visible. This doesn't work because Show() ignores the current value of the Visible property:
```
tasksForm.Visible = false;
tasksForm.Show();
```
Long version: I have a WinForms application with two forms: main and tasks. The main form is... | I totally agree with Rich B, you need to look at where you are placing your application logic rather than trying to cludge the WinForms mechanisms. All of those operations and data that your Tasks form is exposing should really be in a separate class say some kind of Application Controller or something held by your mai... | Perhaps it should be noted here that you **can** cause the form's window to be created without showing the form. I think there could be legitimate situations for wanting to do this.
Anyway, good design or not, you can do that like this:
```
MyForm f = new MyForm();
IntPtr dummy = f.Handle; // forces the form Control ... | Load a form without showing it | [
"",
"c#",
"winforms",
""
] |
So you have a String that is retrieved from an admin web UI (so it is definitely a String). How can you find out whether this string is an IP address or a hostname in Java?
Update: I think I didn't make myself clear, I was more asking if there is anything in the Java SDK that I can use to distinguish between IPs and h... | You can use a regular expression with this pattern:
```
\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
```
That will tell you if it's an IPv4 address. | You can see if the string matches the number.number.number.number format, for example:
```
\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b
```
will match anything from `0 - 999`.
Anything else you can have it default to hostname. | How do you tell whether a string is an IP or a hostname | [
"",
"java",
"ip-address",
"hostname",
""
] |
I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.
**For example:**
```
original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
# and I want to become...
result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4])
```
... | In 2.x, [`zip`](http://docs.python.org/library/functions.html#zip) is its own inverse! Provided you [use the special \* operator](https://stackoverflow.com/questions/36901).
```
>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
```
This is equivalent to calling `zip` with each el... | You could also do
```
result = ([ a for a,b in original ], [ b for a,b in original ])
```
It *should* scale better. Especially if Python makes good on not expanding the list comprehensions unless needed.
(Incidentally, it makes a 2-tuple (pair) of lists, rather than a list of tuples, like `zip` does.)
If generators... | Transpose/Unzip Function (inverse of zip)? | [
"",
"python",
"list",
"matrix",
"transpose",
""
] |
One of the sites I maintain relies heavily on the use of `ViewState` (it isn't my code). However, on certain pages where the `ViewState` is extra-bloated, Safari throws a `"Validation of viewstate MAC failed"` error.
This appears to only happen in Safari. Firefox, IE and Opera all load successfully in the same scenari... | I've been doing a little research into this and whilst I'm not entirely sure its the cause I believe it is because Safari is not returning the full result set (hence cropping it).
I have been in dicussion with another developer and found the following post on Channel 9 as well which recommends making use of the SQL St... | While I second the Channel 9 solution, also be aware that in some hosted environments Safari is not considered an up-level browser. You may need to add it to your application's browscap in order to make use of some ASP.Net features.
That was the root cause of some headaches we had for a client's site that used the ASP... | ViewState invalid only in Safari | [
"",
"c#",
".net",
"safari",
"viewstate",
""
] |
I'd like to find the different ways to solve a real life problem I had: imagine to have a contest, or a game, during which the users collect points. You have to build a query to show the list of users with the best "n" scores.
I'm making an example to clarify. Let's say that this is the Users table, with the points ea... | Untested, but should work:
```
select * from users where points in
(select distinct top 3 points from users order by points desc)
``` | Here's one that works - I don't know if it's more efficient, and it's SQL Server 2005+
```
with scores as (
select 1 userid, 100 points
union select 2, 75
union select 3, 50
union select 4, 50
union select 5, 50
union select 6, 25
),
results as (
select userid, points, RANK() over (order by... | SQL query to get the top "n" scores out of a list | [
"",
"sql",
"sql-server",
"puzzle",
""
] |
A friend and I were discussing C++ templates. He asked me what this should do:
```
#include <iostream>
template <bool>
struct A {
A(bool) { std::cout << "bool\n"; }
A(void*) { std::cout << "void*\n"; }
};
int main() {
A<true> *d = 0;
const int b = 2;
const int c = 1;
new A< b > (c) > (d);
}
`... | AFAIK it would be compiled as `new A<b>(c) > d`. This is the only reasonable way to parse it IMHO. If the parser can't assume under normal circumstances a > end a template argument, that would result it much more ambiguity. If you want it the other way, you should have written:
```
new A<(b > c)>(d);
``` | As stated by Leon & Lee, 14.2/3 (C++ '03) explicitly defines this behaviour.
C++ '0x adds to the fun with a similar rule applying to `>>`. The basic concept, is that when parsing a template-argument-list a non nested `>>` will be treated as two distinct `>` `>` tokens and not the right shift operator:
```
template <b... | C++ Template Ambiguity | [
"",
"c++",
"templates",
"grammar",
""
] |
I have three tables: page, attachment, page-attachment
I have data like this:
```
page
ID NAME
1 first page
2 second page
3 third page
4 fourth page
attachment
ID NAME
1 foo.word
2 test.xsl
3 mm.ppt
page-attachment
ID PAGE-ID ATTACHMENT-ID
1 2 1
2 2 2
3... | Change your "inner join" to a "left outer join", which means "get me all the rows on the left of the join, even if there isn't a matching row on the right."
```
select page.name, count(page-attachment.id) as attachmentsnumber
from page
left outer join page-attachment on page.id=page-id
group by page.name
``` | Here's another solution using sub-querying.
```
SELECT
p.name,
(
SELECT COUNT(*) FROM [page-attachment] pa
WHERE pa.[PAGE-ID] = p.id
) as attachmentsnumber
FROM page p
``` | SQL Query, Count with 0 count | [
"",
"sql",
"count",
""
] |
I've been tasked with the the maintenance of a nonprofit website that recently fell victim to a SQL injection attack. Someone exploited a form on the site to add text to every available text-like field in the database (varchar, nvarchar, etc.) which, when rendered as HTML, includes and executes a JavaScript file.
A Go... | Restore the data from a recent backup. | I was victim and you can use it to clean up
```
UPDATE Table
SET TextField = SUBSTRING(TextField, 1, CHARINDEX('</title', TextField) - 1)
WHERE (ID IN (SELECT ID FROM Table WHERE (CHARINDEX('</title', Textfield, 1) > 0)))
``` | What's the best way of cleaning up after a SQL Injection? | [
"",
"sql",
"sql-server",
"database",
"security",
""
] |
What's the easiest way to profile a PHP script?
I'd love tacking something on that shows me a dump of all function calls and how long they took but I'm also OK with putting something around specific functions.
I tried experimenting with the [microtime](http://php.net/microtime) function:
```
$then = microtime();
myF... | The [PECL APD](http://www.php.net/apd) extension is used as follows:
```
<?php
apd_set_pprof_trace();
//rest of the script
?>
```
After, parse the generated file using `pprofp`.
Example output:
```
Trace for /home/dan/testapd.php
Total Elapsed Time = 0.00
Total System Time = 0.00
Total User Time = 0.00
Real ... | You want [xdebug](http://www.xdebug.org/) I think. Install it on the server, turn it on, pump the output through [kcachegrind](http://kcachegrind.github.io/html/Home.html) (for linux) or [wincachegrind](http://sourceforge.net/projects/wincachegrind/) (for windows) and it'll show you a few pretty charts that detail the ... | Simplest way to profile a PHP script | [
"",
"php",
"profiling",
""
] |
here is the input i am getting from my flash file
process.php?Q2=898&Aa=Grade1&Tim=0%3A0%3A12&Q1=908&Bb=lkj&Q4=jhj&Q3=08&Cc=North%20America&Q0=1
and in php i use this code
foreach ($\_GET as $field => $label)
{
$datarray[]=$\_GET[$field];
```
echo "$field :";
echo $_GET[$field];;
echo "<br>";
```
i get this out pu... | ```
ksort($_GET);
```
This should [ksort](http://php.net/manual/en/function.ksort.php) the `$_GET` array by it's keys. [krsort](http://php.net/manual/en/function.krsort.php) for reverse order. | what you're looking for is [ksort](http://php.net/manual/en/function.ksort.php). Dig the PHP manual! ;) | How to sort an array by keys in an ascending direction? | [
"",
"php",
"arrays",
"sorting",
"query-string",
""
] |
For data types such as std::set and std::map where lookup occurs in logarithmic time, is the implementation required to maintain the begin and end iterators? Does accessing begin and end imply a lookup that could occur in logarithmic time?
I have always assumed that begin and end always occur in constant time, however... | They happen in constant time. I'm looking at page 466 of the ISO/IEC 14882:2003 standard:
**Table 65 - Container Requiments**
a.begin(); *(constant complexity)*
a.end(); *(constant complexity)*
**Table 66 - Reversible Container Requirements**
a.rbegin(); *(constant complexity)*
a.rend(); *(constant complexity)* | Yes, according to <http://www.cplusplus.com/reference/stl/>, begin(), end() etc are all O(1). | C++ does begin/end/rbegin/rend execute in constant time for std::set, std::map, etc? | [
"",
"c++",
"stl",
""
] |
We are currently working in a private beta and so are still in the process of making fairly rapid changes, although obviously as usage is starting to ramp up, we will be slowing down this process. That being said, one issue we are running into is that after we push out an update with new JavaScript files, the client br... | As far as I know a common solution is to add a `?<version>` to the script's src link.
For instance:
```
<script type="text/javascript" src="myfile.js?1500"></script>
```
---
> I assume at this point that there isn't a better way than find-replace to increment these "version numbers" in all of the script tags?
You ... | Appending the current time to the URL is indeed a common solution. However, you can also manage this at the web server level, if you want to. The server can be configured to send different HTTP headers for javascript files.
For example, to force the file to be cached for no longer than 1 day, you would send:
```
Cach... | How can I force clients to refresh JavaScript files? | [
"",
"javascript",
"caching",
"versioning",
""
] |
After hours of debugging, it appears to me that in FireFox, the innerHTML of a DOM reflects what is actually in the markup, but in IE, the innerHTML reflects what's in the markup PLUS any changes made by the user or dynamically (i.e. via Javascript).
Has anyone else found this to be true? Any interesting work-arounds ... | I agree with Pat. At this point in the game, writing your own code to deal with cross-browser compatibility given the available Javascript frameworks doesn't make a lot of sense. There's a framework for nearly any taste (some really quite tiny) and they've focused on really abstracting out all of the differences betwee... | I use jQuery's [.html()](http://docs.jquery.com/Attributes/html) to get a consistent result across browsers. | Firefox vs. IE: innerHTML handling | [
"",
"javascript",
"internet-explorer",
"firefox",
"dom",
""
] |
I'm writing a C# POS (point of sale) system that takes input from a keyboard wedge magcard reader. This means that any data it reads off of a mag stripe is entered as if it were typed on the keyboard very quickly. Currently I'm handling this by attaching to the KeyPress event and looking for a series of very fast key p... | One thing you can do is that you should be able to configure your wedge reader so that it presents one or many escape characters before or after the string. You would use these escape characters to know that you are about to have (or just had) a magcard input.
This same technique is used by barcode reader devices so y... | You can also use the Raw Input API if you know the Hardware IDs of the devices ahead of time. [I blogged about this recently.](http://nicholas.piasecki.name/blog/2009/02/distinguishing-barcode-scanners-from-the-keyboard-in-winforms/) It may be insane but it satisifed my requirement: the primary goal in my case was to b... | Best way to handle input from a keyboard "wedge" | [
"",
"c#",
"point-of-sale",
""
] |
I'm tasked with building a .NET client app to detect silence in a WAV files.
Is this possible with the built-in Windows APIs? Or alternately, any good libraries out there to help with this? | Audio analysis is a difficult thing requiring a lot of complex math (think Fourier Transforms). The question you have to ask is "what is silence". If the audio that you are trying to edit is captured from an analog source, the chances are that there isn't any silence... they will only be areas of soft noise (line hum, ... | I'm using [NAudio](https://github.com/naudio/NAudio), and I wanted to detect the silence in audio files so I can either report or truncate.
After a lot of research, I came up with this basic implementation. So, I wrote an extension method for the [`AudioFileReader`](https://github.com/naudio/NAudio/blob/master/NAudio/... | Detecting audio silence in WAV files using C# | [
"",
"c#",
".net",
"audio",
""
] |
My source code needs to support both .NET version 1.1 and 2.0 ... how do I test for the different versions & what is the best way to deal with this situation.
I'm wondering if I should have the two sections of code inline, in separate classes, methods etc. What do you think? | If you want to do something like this you will need to use preprocessor commands and conditional compilation symbols.
I would use symbols that clearly indicate the version of .NET you are targeting (say NET11 and NET20) and then wrap the relevant code like this:
```
#if NET11
// .NET 1.1 code
#elif NET20
// .NET 2.0 ... | There are a lot of different options here. Where I work we use #if pragmas but it could also be done with separate assemblies for the separate versions.
Ideally you would at least keep the version dependant code in separate partial class files and make the correct version available at compile time. I would enforce thi... | How should I write code with unique sections for different versions of .NET | [
"",
"c#",
".net",
"c-preprocessor",
""
] |
Code:
```
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Unusual Array Lengths!</title>
<script type="text/javascript">
var arrayList = new Array();
arrayList = [1, 2, 3, 4, 5, ];
alert(arrayList.length);
</script>
</head>
<body>
</body>
</html>
```
Notice the extra co... | It seems to me that the Firefox behavior is correct. What is the value of the 6th value in IE (sorry I don't have it handy to test). Since there is no actual value provided, I imagine it's filling it with something like 'null' which certainly doesn't seem to be what you intended to have happen when you created the arra... | I was intrigued so I looked it up in the definition of [ECMAScript 262 ed. 3](http://www.ecma-international.org/publications/standards/Ecma-262.htm) which is the basis of JavaScript 1.8. The relevant definition is found in section 11.1.4 and unfortunately is not very clear. The section explicitly states that elisions (... | Javascript Browser Quirks - array.Length | [
"",
"javascript",
""
] |
The following returns
> Type of conditional expression cannot be determined because there is no implicit conversion between 'double' and '<null>'
```
aNullableDouble = (double.TryParse(aString, out aDouble) ? aDouble : null)
```
---
The reason why I can't just use aNullableBool instead of the roundtrip with aDouble... | ```
aNullableDouble = double.TryParse(aString, out aDouble) ? (double?)aDouble : null;
``` | Just blow the syntax out into the full syntax instead of the shorthand ... it'll be easier to read:
```
aNullableDouble = null;
if (double.TryParse(aString, out aDouble))
{
aNullableDouble = aDouble;
}
``` | Shorthand if + nullable types (C#) | [
"",
"c#",
"conditional-operator",
""
] |
This query works great:
```
var pageObject = (from op in db.ObjectPermissions
join pg in db.Pages on op.ObjectPermissionName equals page.PageName
where pg.PageID == page.PageID
select op)
.SingleOrDefault();
```
I get a new type with my 'op' field... | You can use anonymous types for this, i.e.:
```
var pageObject = (from op in db.ObjectPermissions
join pg in db.Pages on op.ObjectPermissionName equals page.PageName
where pg.PageID == page.PageID
select new { pg, op }).SingleOrDefault();
```
This will make pageOb... | If you don't want to use anonymous types b/c let's say you're passing the object to another method, you can use the LoadWith load option to load associated data. It requires that your tables are associated either through foreign keys or in your Linq-to-SQL dbml model.
```
db.DeferredLoadingEnabled = false;
DataLoadOpt... | Creating a LINQ select from multiple tables | [
"",
"c#",
"linq",
""
] |
I'm currently creating an explicit reference to this in the outer class so that I have a name to refer to in the anonymous inner class. Is there a better way to do this? | I just found this recently. Use `OuterClassName.this`.
```
class Outer {
void foo() {
new Thread() {
public void run() {
Outer.this.bar();
}
}.start();
}
void bar() {
System.out.println("BAR!");
}
}
```
**Updated** If you just want the ob... | Use `EnclosingClass.this` | How do you get a reference to the enclosing class from an anonymous inner class in Java? | [
"",
"java",
"oop",
""
] |
In my example below I'm using a `dijit.form.DateTextBox`:
```
<input type="text" name="startDate" dojoType="dijit.form.DateTextBox" constraints="{datePattern:'MM/dd/yyyy'}" value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>' />
```
So for example, if the user starts to enter "asdf" into the date the ... | Try overriding the validate method in your markup.
This will work (just tested):
```
<input type="text" name="startDate" dojoType="dijit.form.DateTextBox"
constraints="{datePattern:'MM/dd/yyyy'}"
value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>'
validate='return true;'
/>
``` | My only suggestion is to programmatically remove the dojoType on the server-side or client-side. It is not possible to keep the dojoType and not have it validate. Unless you create your own type that has you logic in it. | Is there anyway to disable the client-side validation for dojo date text box? | [
"",
"javascript",
"dojo",
""
] |
Given the key for some registry value (e.g. HKEY\_LOCAL\_MACHINE\blah\blah\blah\foo) how can I:
1. Safely determine that such a key exists.
2. Programmatically (i.e. with code) get its value.
I have absolutely no intention of writing anything back to the registry (for the duration of my career if I can help it). So w... | **Here is some pseudo-code to retrieve the following:**
1. If a registry key exists
2. What the default value is for that registry key
3. What a string value is
4. What a DWORD value is
**Example code:**
Include the library dependency: Advapi32.lib
```
HKEY hKey;
LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFT... | Since Windows >=Vista/Server 2008, [RegGetValue](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724868(v=vs.85).aspx) is available, which [is a safer function](https://msdn.microsoft.com/en-us/magazine/mt808504.aspx) than [RegQueryValueEx](https://msdn.microsoft.com/en-us/library/ms724911%28VS.85%29.aspx). ... | How to read a value from the Windows registry | [
"",
"c++",
"windows",
"winapi",
"registry",
""
] |
a colleague pointed me the other day to [BCEL](http://jakarta.apache.org/bcel/) which , as best I can tell from his explanation and a quick read, a way to modify at run time the byte code. My first thought was that it sounded dangerous, and my second thought was that it sounded cool. Then I gave it some more thought an... | It's a bit more low-level than classic monkey patching, and from what I read, the classes already loaded into the VM are not updated. It only supports saving it to class files again, not modifying run time classes. | From BCEL's FAQ:
> Q: Can I create or modify classes
> dynamically with BCEL?
>
> A: BCEL contains useful classes in the
> util package, namely ClassLoader and
> JavaWrapper.Take a look at the
> ProxyCreator example.
But monkeypatching is... uhm... controversial, and you probably shouldn't use it if your language doe... | Is BCEL == monkeypatching for java? | [
"",
"java",
"bytecode",
"monkeypatching",
"bcel",
""
] |
I've been using PHP for too long, but I'm new to JavaScript integration in some places.
I'm trying to find the fastest way to pass database information into a page where it can be modified and displayed dynamically in JavaScript.
Right now, I'm looking at loading a *JSON with PHP* echo statements because it's fast an... | Use the library. If you try to generate it manually, I predict with 99% certainty that the resulting text will be invalid in some way. Especially with more esoteric features like Unicode strings or exponential notation. | the json\_encode and json\_decode methods work perfectly. Just pass them an object or an array that you want to encode and it recursively encodes them to JSON.
Make sure that you give it UTF-8 encoded data! | Loading JSON with PHP | [
"",
"php",
"json",
""
] |
I am currently writing a small calendar in ASP.Net C#. Currently to produce the rows of the weeks I do the following for loop:
```
var iWeeks = 6;
for (int w = 0; w < iWeeks; w++) {
```
This works fine, however, some month will only have 5 weeks and in some rare cases, 4.
How can I calculate the number of rows that ... | Here is the method that does it:
```
public int GetWeekRows(int year, int month)
{
DateTime firstDayOfMonth = new DateTime(year, month, 1);
DateTime lastDayOfMonth = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);
System.Globalization.Calendar calendar = System.Threading.Thread.CurrentThread.Current... | Well, it depends on the culture you're using, but let's assume you can use Thread.CurrentThread.CurrentCulture, then the code to get the week of today would be:
```
Culture culture = Thread.CurrentThread.CurrentCulture;
Calendar cal = culture.Calendar;
Int32 week = cal.GetWeekOfYear(DateTime.Today,
culture.DateTim... | Calculate DateTime Weeks into Rows | [
"",
"c#",
"asp.net",
""
] |
I have a Person object with two constructors - one takes an int (personId), the other a string (logonName). I would like another constructor that takes a string (badgeNumber). I know this can't be done, but seems it might be a common situation. Is there a graceful way of handling this? I suppose this would apply to any... | You might consider using custom types.
For example, create LogonName and BadgeNumber classes.
Then your function declarations look like...
```
public Person(LogonName ln)
{
this.Load(ln.ToString());
}
public Person(BadgeNumber bn)
{
//load logic here...
}
```
Such a solution might give you a good place to ... | You could perhaps use factory methods instead?
```
public static Person fromId(int id) {
Person p = new Person();
p.Load(id);
return p;
}
public static Person fromLogonName(string logonName) {
Person p = new Person();
p.Load(logonName);
return p;
}
public static Person fromBadgeNumber(string ba... | Constructors with the same argument type | [
"",
"c#",
".net",
"oop",
""
] |
I have a method that where I want to redirect the user back to a login page located at the root of my web application.
I'm using the following code:
```
Response.Redirect("~/Login.aspx?ReturnPath=" + Request.Url.ToString());
```
This doesn't work though. My assumption was that ASP.NET would automatically resolve the... | > I think you need to drop the "~/" and replace it with just "/", I believe / is the root
**STOP RIGHT THERE!** :-) unless you want to hardcode your web app so that it can only be installed at the root of a web site.
"~/" ***is*** the correct thing to use, but the reason that your original code didn't work as expecte... | you can resolve the URL first
Response.Redirect("~/Login.aspx);
and add the parameters after it got resolved. | Response.Redirect using ~ Path | [
"",
"c#",
"asp.net",
"response.redirect",
""
] |
Is there any way to use inheritance in database (Specifically in SQL Server 2005)?
Suppose I have few field like **CreatedOn**, **CreatedBy** which I want to add on all of my entities. I looking for an alternative way instead of adding these fields to every table. | There is no such thing as inheritance between tables in SQL Server 2005, and as noted by the others, you can get as far as getting help adding the necessary columns to the tables when you create them, but it won't be inheritance as you know it.
Think of it more like a template for your source code files.
As GateKille... | PostgreSQL has this feature. Just add this to the end of your table definition:
```
INHERITS FROM (tablename[, othertable...])
```
The child table will have all the columns of its parent, and changes to the parent table will change the child. Also, everything in the child table will come up in queries to the parent t... | Inheritance in database? | [
"",
"sql",
"database",
"inheritance",
"sql-server-2005",
""
] |
What's the best way to specify a proxy with username and password for an http connection in python? | Use this:
```
import requests
proxies = {"http":"http://username:password@proxy_ip:proxy_port"}
r = requests.get("http://www.example.com/", proxies=proxies)
print(r.content)
```
I think it's much simpler than using `urllib`. I don't understand why people love using `urllib` so much. | This works for me:
```
import urllib2
proxy = urllib2.ProxyHandler({'http': 'http://
username:password@proxyurl:proxyport'})
auth = urllib2.HTTPBasicAuthHandler()
opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler)
urllib2.install_opener(opener)
conn = urllib2.urlopen('http://python.org')
return_str = co... | How to specify an authenticated proxy for a python http connection? | [
"",
"python",
"http",
"proxy",
""
] |
Anyone know this compiler feature? It seems GCC support that. How does it work? What is the potential gain? In which case it's good? Inner loops?
(this question is specific, not about optimization in general, thanks) | It works by placing extra code to count the number of times each codepath is taken. When you compile a second time the compiler uses the knowledge gained about execution of your program that it could only guess at before. There are a couple things PGO can work toward:
* Deciding which functions should be inlined or no... | PGO gives about a 5% speed boost when compiling x264, the project I work on, and we have a built-in system for it (make fprofiled). Its a nice free speed boost in some cases, and probably helps more in applications that, unlike x264, are less made up of handwritten assembly. | profile-guided optimization (C) | [
"",
"c++",
"c",
"optimization",
"gcc",
"pgo",
""
] |
Html Textarea elements only wrap when they reach a space or tab character. This is fine, until the user types a looooooooooooooooooooooong enough word. I'm looking for a way to strictly enforce line breaks (eg.: even if it results in "loooooooooooo \n ooooooooooong").

... | The CSS settings `word-wrap:break-word` and `text-wrap:unrestricted` appear to be CSS 3 features. Good luck finding a way to do this on current implementations. | * quirksmode.org has an [overview of various methods](http://www.quirksmode.org/oddsandends/wbr.html).
* There's a related SO question: ["In HTML, how to word-break on a dash?"](https://stackoverflow.com/questions/904/in-html-how-to-word-break-on-a-dash)
* In browsers that support it, [`word-wrap: break-word`](http://w... | Most elegant way to force a TEXTAREA element to line-wrap, *regardless* of whitespace | [
"",
"javascript",
"html",
"css",
"text",
""
] |
Using core jQuery, how do you remove all the options of a select box, then add one option and select it?
My select box is the following.
```
<Select id="mySelect" size="9"> </Select>
```
EDIT: The following code was helpful with chaining. However, (in Internet Explorer) `.val('whatever')` did not select the option t... | ```
$('#mySelect')
.find('option')
.remove()
.end()
.append('<option value="whatever">text</option>')
.val('whatever')
;
``` | ```
$('#mySelect')
.empty()
.append('<option selected="selected" value="whatever">text</option>')
;
``` | How do you remove all the options of a select box and then add one option and select it with jQuery? | [
"",
"javascript",
"jquery",
"html-select",
"dynamic-html",
""
] |
I have been sold on mod\_wsgi and apache rather than mod\_python.
I have all the parts installed (django, apache, mod\_wsgi) but have run into a problem deploying.
I am on osx 10.5 with apache 2.2 and django 1.0b2, mod\_wsgi-2.3
My application is called tred.
Here are the relevant files:
httpd-vhosts (included in ht... | What happens if you remove the `Alias /` directive? | Note that Alias and WSGIScriptAlias directives do not have the same precedence. Thus, they will not be processed in file order as written. Instead, all Alias directives get precedence over WSGIScriptAlias directives. Thus, it wouldn't have mattered if the Alias for '/' appeared after WSGIScriptAlias, it would still hav... | Setup django with WSGI and apache | [
"",
"python",
"django",
"apache",
"mod-wsgi",
""
] |
Currently, I am writing up a bit of a product-based CMS as my first project.
Here is my question. How can I add additional data (products) to my Product model?
I have added '/admin/products/add' to my urls.py, but I don't really know where to go from there. How would i build both my view and my template? Please keep ... | You will want to wire your URL to the Django [create\_object generic view](https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-create-update-create-object), and pass it either "model" (the model you want to create) or "form\_class" (a customized [ModelForm](https://docs.djangoproject.com/en/1.... | This topic is covered in [Django tutorials](https://code.djangoproject.com/wiki/Tutorials). | How do I add data to an existing model in Django? | [
"",
"python",
"django",
""
] |
I'm trying out the following query:
```
SELECT A,B,C FROM table WHERE field LIKE 'query%'
UNION
SELECT A,B,C FROM table WHERE field LIKE '%query'
UNION
SELECT A,B,C FROM table WHERE field LIKE '%query%'
GROUP BY B ORDER BY B ASC LIMIT 5
```
That's three queries stuck together, kinda sorta. However, the result set tha... | Maybe you should try including a fourth column, stating the table it came from, and then order and group by it:
```
SELECT A,B,C, "query 1" as origin FROM table WHERE field LIKE 'query%'
UNION
SELECT A,B,C, "query 2" as origin FROM table WHERE field LIKE '%query'
UNION
SELECT A,B,C, "query 3" as origin FROM table WHER... | Add an additional column with hard-coded values that you will use to sort the overall resultset, like so:
```
SELECT A,B,C,1 as [order] FROM table WHERE field LIKE 'query%'
UNION
SELECT A,B,C,2 as [order] FROM table WHERE field LIKE '%query'
UNION
SELECT A,B,C,3 as [order] FROM table WHERE field LIKE '%query%'
GROUP B... | How do I Concatenate entire result sets in MySQL? | [
"",
"mysql",
"sql",
"union",
""
] |
How would you dynamically subscribe to a C# event so that given a Object instance and a String name containing the name of the event, you subscribe to that event and do something (write to the console for example) when that event has been fired?
It would seem using Reflection this isn't possible and I would like to av... | You can compile expression trees to use void methods without any arguments as event handlers for events of any type. To accommodate other event handler types, you have to map the event handler's parameters to the events somehow.
```
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Refle... | It's not a completely general solution, but if all your events are of the form
void Foo(object o, T args) , where T derives from EventArgs, then you can use delegate contravariance to get away with it. Like this (where the signature of KeyDown is not the same as that of Click) :
```
public Form1()
{
Bu... | C# Dynamic Event Subscription | [
"",
"c#",
"events",
"reflection",
"delegates",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.