Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools. | See [Stevens](http://www.kohala.com/start/) and also this [lengthy thread on activestate](http://code.activestate.com/recipes/278731/) which I found personally to be both mostly incorrect and much to verbose, and I came up with this:
```
from os import fork, setsid, umask, dup2
from sys import stdin, stdout, stderr
i... | [nohup](http://en.wikipedia.org/wiki/Nohup)
[Creating a daemon the Python way](http://code.activestate.com/recipes/278731/) | What would be the simplest way to daemonize a python script in Linux? | [
"",
"python",
"scripting",
"daemon",
""
] |
I got this flash application where you can click a link while watching a video. It will open a new tab and pause the video. Now when you come back to the flash application it would be nice if the video would start playing again. Is there a way, an event or so to do this ? | I think i have solved it like this:
I listen to a mouse\_leave event on the stage, because your mouse will leave the stage when in another tab. (or at least, you have to click a tab to get back to the flash, so you always end up outside of the flash). When you left the stage a stageLeave boolean is set to true.
Then ... | A cleaner approach would be to use something along the lines of this:
```
stage.addEventListener( Event.ACTIVATE, playMovie );
stage.addEventListener( Event.DEACTIVATE, pauseMovie );
``` | Flash: Coming back from another tab in browser, can flash listen to return to tab event of some sort? | [
"",
"javascript",
"actionscript-3",
"events",
"focus",
"stage",
""
] |
I know there is a way to add a IE control, how do you add a chrome control...? Is it even possible right now?
I'm need this because of the fast javascript VM found in chrome. | I searched around and I don't think Google Chrome registers itself as a Windows COM+ component. I think you're out of luck. | Check this out: [Use chrome as browser in C#?](https://stackoverflow.com/q/2141668/258482) | How can I open a google chrome control in C# | [
"",
"c#",
""
] |
I have the following enum declared:
```
public enum TransactionTypeCode { Shipment = 'S', Receipt = 'R' }
```
How do I get the value 'S' from a TransactionTypeCode.Shipment or 'R' from TransactionTypeCode.Receipt ?
Simply doing TransactionTypeCode.ToString() gives a string of the Enum name "Shipment" or "Receipt" s... | Marking this as not correct, but I can't delete it.
Try this:
```
string value = (string)TransactionTypeCode.Shipment;
``` | You have to check the underlying type of the enumeration and then convert to a proper type:
```
public enum SuperTasks : int
{
Sleep = 5,
Walk = 7,
Run = 9
}
private void btnTestEnumWithReflection_Click(object sender, EventArgs e)
{
SuperTasks task = SuperTasks.Walk;
... | How to get the underlying value of an enum | [
"",
"c#",
".net",
"enums",
""
] |
What object do you query against to select all the table names in a schema in Oracle? | To see all the tables you have access to
```
select table_name from all_tables where owner='<SCHEMA>';
```
To select all tables for the current logged in schema (eg, your tables)
```
select table_name from user_tables;
``` | you're looking for:
```
select table_name from user_tables;
``` | What table/view do you query against to select all the table names in a schema in Oracle? | [
"",
"sql",
"oracle",
""
] |
In Python for \*nix, does `time.sleep()` block the thread or the process? | It blocks the thread. If you look in Modules/timemodule.c in the Python source, you'll see that in the call to `floatsleep()`, the substantive part of the sleep operation is wrapped in a Py\_BEGIN\_ALLOW\_THREADS and Py\_END\_ALLOW\_THREADS block, allowing other threads to continue to execute while the current one slee... | It will just sleep the thread except in the case where your application has only a single thread, in which case it will sleep the thread and effectively the process as well.
The python documentation on [`sleep()`](https://docs.python.org/3/library/time.html#time.sleep) doesn't specify this however, so I can certainly ... | time.sleep -- sleeps thread or process? | [
"",
"python",
"multithreading",
"time",
"sleep",
"python-internals",
""
] |
Ever wanted to have an HTML drag and drop sortable table in which you could sort both rows and columns? I know it's something I'd die for. There's a lot of sortable lists going around but finding a sortable table seems to be impossible to find.
I know that you can get pretty close with the tools that script.aculo.us p... | I've used [dhtmlxGrid](http://www.dhtmlx.com/docs/products/dhtmlxGrid/index.shtml) in the past. Among other things it supports drag-and-drop rows/columns, client-side sorting (string, integer, date, custom) and multi-browser support.
Response to comment:
No, not found anything better - just moved on from that project.... | I've used jQuery UI's sortable plugin with good results. Markup similar to this:
```
<table id="myTable">
<thead>
<tr><th>ID</th><th>Name</th><th>Details</th></tr>
</thead>
<tbody class="sort">
<tr id="1"><td>1</td><td>Name1</td><td>Details1</td></tr>
<tr id="2"><td>2</td><td>Name1</td><td>Details2</td></tr>
<tr id="3... | HTML drag and drop sortable tables | [
"",
"javascript",
"html",
"drag-and-drop",
"html-table",
""
] |
I need to store some sensitive data by encrypting it with atleast 128 bit key. I investigated into javax.crypto package and found that there are certain Cipher names, like
PBEWithMD5AndDES or PBEWithSHA1AndDESede which provides encryption upto 56 bit and 80 bit (<http://en.wikipedia.org/wiki/DESede>).
I referred other... | Use [Advanced Encryption Standard](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard) (AES). It supports Key lengths of 128, 192, or 256 bits.
The [algorithm](http://www.hoozi.com/Articles/AESEncryption.htm) is simple. The Sun Java website has a [section explaining how to do AES](http://java.sun.com/developer/... | I have had good success in the past with <http://www.bouncycastle.org/> (they have a C# version as well). | 128 bit data encryption using Java | [
"",
"java",
"cryptography",
""
] |
I have this string
```
'john smith~123 Street~Apt 4~New York~NY~12345'
```
Using JavaScript, what is the fastest way to parse this into
```
var name = "john smith";
var street= "123 Street";
//etc...
``` | With JavaScript’s [`String.prototype.split`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) function:
```
var input = 'john smith~123 Street~Apt 4~New York~NY~12345';
var fields = input.split('~');
var name = fields[0];
var street = fields[1];
// etc.
``` | According to ECMAScript6 `ES6`, the clean way is destructuring arrays:
```
const input = 'john smith~123 Street~Apt 4~New York~NY~12345';
const [name, street, unit, city, state, zip] = input.split('~');
console.log(name); // john smith
console.log(street); // 123 Street
console.log(unit); // Apt 4
console.log... | How do I split a string, breaking at a particular character? | [
"",
"javascript",
"split",
""
] |
Does anyone know how to write to an excel file (.xls) via OLEDB in C#? I'm doing the following:
```
OleDbCommand dbCmd = new OleDbCommand("CREATE TABLE [test$] (...)", connection);
dbCmd.CommandTimeout = mTimeout;
results = dbCmd.ExecuteNonQuery();
```
But I get an OleDbException thrown with message:
> "Can... | You need to add `ReadOnly=False;` to your connection string
```
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=fifa_ng_db.xls;Mode=ReadWrite;ReadOnly=false;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";
``` | I was also looking for and answer but Zorantula's solution didn't work for me.
I found the solution on <http://www.cnblogs.com/zwwon/archive/2009/01/09/1372262.html>
I removed the `ReadOnly=false` parameter and the `IMEX=1` extended property.
The `IMEX=1` property opens the workbook in import mode, so structure-modif... | Writing into excel file with OLEDB | [
"",
"c#",
"excel",
"oledb",
""
] |
Continuing from my [previous question](https://stackoverflow.com/questions/90751/double-and-floats-in-c), is there a comprehensive document that lists all available differences between debug and release modes in a C# application, and particularly in a web application?
What differences are there? | "Debug" and "Release" are just names for predefined project configurations defined by Visual Studio.
To see the differences, look at the Build Tab in Project Properties in Visual Studio.
The differences in VS2005 include:
* DEBUG constant defined in Debug configuration
* Optimize code enabled in Release configurati... | I'm not aware of one concise document, but:
* Debug.Write calls are stripped out in Release
* In Release, your CallStack may look a bit "strange" due to optimizations, as outlined by [Scott Hanselman](http://www.hanselman.com/blog/ReleaseISNOTDebug64bitOptimizationsAndCMethodInliningInReleaseBuildCallStacks.aspx) | Debug vs. release in .NET | [
"",
"c#",
".net",
"asp.net",
""
] |
How can I take the string `foo[]=1&foo[]=5&foo[]=2` and return a collection with the values `1,5,2` in that order. I am looking for an answer using regex in C#. Thanks | In C# you can use capturing groups
```
private void RegexTest()
{
String input = "foo[]=1&foo[]=5&foo[]=2";
String pattern = @"foo\[\]=(\d+)";
Regex regex = new Regex(pattern);
foreach (Match match in regex.Matches(input))
{
Console.Out.WriteLine(match.Grou... | I don't know C#, but...
In java:
```
String[] nums = String.split(yourString, "&?foo[]");
```
The second argument in the `String.split()` method is a regex telling the method where to split the String. | How can I split a string using regex to return a list of values? | [
"",
"c#",
"regex",
""
] |
Is there any performance to be gained these days from compiling java to native code, or do modern hotspot compilers end up doing this over time anyway? | There was a similar discussion here recently, for the question [What are advantages of bytecode over native code?](https://stackoverflow.com/questions/48144/what-are-advantages-of-bytecode-over-native-code). You can find interesting answers in that thread. | Some more anecdotal evidence. I've worked on a few performance critical real-time trading financial applications. I agree with Frank, nearly every time your problem is not the lack of being compiled, it is your algorithm or data structure. Modern hot-spot compilers are very good with the right code, for example the [CE... | Performance gain in compiling java to native code? | [
"",
"java",
"performance",
""
] |
In .NET, how can I prevent multiple instances of an app from running at the same time and what caveats should I consider if there are multiple ways to do it? | Use Mutex. One of the examples above using GetProcessByName has many caveats. Here is a good article on the subject:
<https://web.archive.org/web/20230610150623/https://odetocode.com/blogs/scott/archive/2004/08/20/the-misunderstood-mutex.aspx>
```
[STAThread]
static void Main()
{
using(Mutex mutex = new Mutex(fal... | Here is the code you need to ensure that only one instance is running. This is the method of using a named mutex.
```
public class Program
{
static System.Threading.Mutex singleton = new Mutex(true, "My App Name");
static void Main(string[] args)
{
if (!singleton.WaitOne(TimeSpan.Zero, true))
... | Prevent multiple instances of a given app in .NET? | [
"",
"c#",
".net",
""
] |
How do I submit an HTML form when the return key is pressed and if there are no buttons in the form?
**The submit button is not there**. I am using a custom div instead of that. | This is the cleanest answer:
```
<form action="" method="get">
Name: <input type="text" name="name"/><br/>
Pwd: <input type="password" name="password"/><br/>
<div class="yourCustomDiv"/>
<input type="submit" style="display:none"/>
</form>
```
Better yet, if you are using JavaScript to submit the form using th... | To submit the form when the enter key is pressed create a javascript function along these lines.
```
function checkSubmit(e) {
if(e && e.keyCode == 13) {
document.forms[0].submit();
}
}
```
Then add the event to whatever scope you need eg on the div tag:
`<div onKeyPress="return checkSubmit(event)"/>`
T... | How do I submit a form when the return key is pressed? | [
"",
"javascript",
"html",
""
] |
How do you get around this Ajax cross site scripting problem on FireFox 3? | If you're using jQuery it has a callback function to overcome this:
<http://docs.jquery.com/Ajax/jQuery.ajax#options>
> As of jQuery 1.2, you can load JSON
> data located on another domain if you
> specify a JSONP callback, which can be
> done like so: "myurl?callback=?".
> jQuery automatically replaces the ?
> with ... | To update the answer (I guess, mostly for my benefit when I come looking for this answer later on), if are loading XML or something else, you can always ask the user if he will allow us to read from another site with this code:
```
try {
if (netscape.security.PrivilegeManager.enablePrivilege)
netscape.secu... | Access to restricted URI denied code: 1012 | [
"",
"javascript",
"jquery",
"ajax",
"xss",
""
] |
There was a post this morning asking about how many people disable JavaScript. Then I began to wonder what techniques might be used to determine if the user has it disabled.
Does anyone know of some short/simple ways to detect if JavaScript is disabled? My intention is to give a warning that the site is not able to fu... | I assume you're trying to decide whether or not to deliver JavaScript-enhanced content. The best implementations degrade cleanly, so that the site will still operate without JavaScript. I also assume that you mean [server-side](https://www.seguetech.com/client-server-side-code/ "'Client-Side vs. Server-Side Code: What’... | I'd like to add my .02 here. It's not 100% bulletproof, but I think it's good enough.
The problem, for me, with the preferred example of putting up some sort of "this site doesn't work so well without Javascript" message is that you then need to make sure that your site works okay without Javascript. And once you've s... | How to detect if JavaScript is disabled? | [
"",
"javascript",
"html",
"css",
""
] |
Hey all. Newbie question time. I'm trying to setup JMXQuery to connect to my MBean, so far this is what I got.
java -classpath jmxquery org.nagios.JMXQuery -U service:jmx:rmi:///jndi/rmi://localhost:8004/jmxrmi -O java.lang:type=Memory -A "NonHeapMemoryUsage"
Here's what I get.
JMX CRITICAL Authentication failed! Cr... | According to the source, you should be able to use -username and -password arguments.
<http://code.google.com/p/jmxquery/source/browse/trunk/src/main/java/jmxquery/JMXQuery.java?r=3> | It seems that this is an addon to the original JMX-query, look at the comment field.
> /\*\* \* \* JMXQuery is used for local
> or remote request of JMX attributes \*
> It requires JRE 1.5 to be used for
> compilation and execution. \* Look
> method main for description how it can
> be invoked. \* \* This plugin was
>... | JMXQuery connection - authentication failed | [
"",
"java",
"monitoring",
"jmx",
"mbeans",
"nagios",
""
] |
How can I get all items from a specific calendar (for a specific date).
Lets say for instance that I have a calendar with a recurring item every Monday evening. When I request all items like this:
```
CalendarItems = CalendarFolder.Items;
CalendarItems.IncludeRecurrences = true;
```
I only get 1 item...
Is there an ... | I believe that you must Restrict or Find in order to get recurring appointments, otherwise Outlook won't expand them. Also, you must Sort by Start *before* setting IncludeRecurrences. | I've studied the docs and this is my result:
I've put a time limit of one month hard-coded, but this is just an example.
```
public void GetAllCalendarItems()
{
Microsoft.Office.Interop.Outlook.Application oApp = null;
Microsoft.Office.Interop.Outlook.NameSpace mapiNamespace = null;
Microsoft.Office.Intero... | .NET: Get all Outlook calendar items | [
"",
"c#",
".net",
"outlook",
"calendar",
"recurring",
""
] |
I would like to know what would be the best way to do unit testing of a servlet.
Testing internal methods is not a problem as long as they don't refer to the servlet context, but what about testing the doGet/doPost methods as well as the internal method that refer to the context or make use of session parameters?
Is ... | Try [HttpUnit](http://httpunit.sourceforge.net/), although you are likely to end up writing automated tests that are more 'integration tests' (of a module) than 'unit tests' (of a single class). | Most of the time I test Servlets and JSP's via 'Integration Tests' rather than pure Unit Tests. There are a large number of add-ons for JUnit/TestNG available including:
* [HttpUnit](http://httpunit.sourceforge.net/) (the oldest and best known, very low level which can be good or bad depending on your needs)
* [HtmlUn... | Unit testing a Java Servlet | [
"",
"java",
"unit-testing",
"servlets",
""
] |
Here is my problem: I've got a dialog with some parameters that the user can change (via a spinner for example). Each time one of these parameters is changed, I launch a thread to update a 3D view according to the new parameter value.
If the user changes another value (or the same value again by clicking many times on ... | Try interrupt() as some have said to see if it makes any difference to your thread. If not, try destroying or closing a resource that will make the thread stop. That has a chance of being a little better than trying to throw Thread.stop() at it.
If performance is tolerable, you might view each 3D update as a discrete ... | The thread that is updating the 3D view should periodically check some flag (use a `volatile boolean`) to see if it should terminate. When you want to abort the thread, just set the flag. When the thread next checks the flag, it should simply break out of whatever loop it is using to update the view and return from its... | How to abort a thread in a fast and clean way in java? | [
"",
"java",
"multithreading",
""
] |
A friend of mine and I were having a discussion regarding currying and partial function application in Javascript, and we came to very different conclusions as to whether either were achievable. I came up with this implementation of `Function.prototype.curry`, which was the basis of our discussion:
```
Function.protot... | Technically you're creating a brand new function that calls the original function. So if my understanding of partially applied functions is correct, this is not a partially applied function. A partially applied function would be closer to this (note that this isn't a general solution):
```
vindaloo.curry = function(a)... | I think it's perfectly OK to talk about partial function application
in JavaScript - if it works like partial application, then it must
be one. How else would you name it?
How your *curry* function accomplishes his goal is just an implementation
detail. In a similar way we could have partial application in the ECMAScr... | Is "Partial Function Application" a misnomer in the context of Javascript? | [
"",
"javascript",
"functional-programming",
""
] |
I'm trying to write a small class library for a C++ course.
I was wondering if it was possible to define a set of classes in my shared object and then using them directly in my main program that demos the library. Are there any tricks involved? I remember reading this long ago (before I started really programming) tha... | C++ classes work fine in .so shared libraries (they also work in non-MFC DLLs on Windows, but that's not really your question). It's actually easier than Windows, because you don't have to explicitly export any symbols from the libraries.
This document will answer most of your questions: <http://people.redhat.com/drep... | # My solution/testing
Here's my solution and it does what i expected.
## Code
*cat.hh* :
```
#include <string>
class Cat
{
std::string _name;
public:
Cat(const std::string & name);
void speak();
};
```
*cat.cpp* :
```
#include <iostream>
#include <string>
#include "cat.hh"
using namespace std;
Cat... | Using C++ classes in .so libraries | [
"",
"c++",
"linux",
"class-library",
""
] |
I need to import a large CSV file into an SQL server. I'm using this :
```
BULK
INSERT CSVTest
FROM 'c:\csvfile.txt'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO
```
problem is all my fields are surrounded by quotes (" ") so a row actually looks ... | I know this isn't a real solution but I use a dummy table for the import with nvarchar set for everything. Then I do an insert which strips out the " characters and does the conversions. It isn't pretty but it does the job. | Try `FIELDTERMINATOR='","'`
Here is a great link to help with the first and last quote...look how he used the substring the SP
<http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file> | SQL Bulk import from CSV | [
"",
"sql",
"sql-server",
"t-sql",
"bulkinsert",
""
] |
Sessions in PHP seemed to have changed since the last time I used them, so I'm looking for a simple way of using sessions but at the same time for it to be relatively secure and a good common practice. | Session management changed some time back (I think it was around 4.4). The old mechanism still works, but is deprecated. It's rather confusing, so I recommend staying clear of it. Today, you use sessions by accessing the global variable $\_SESSION (It's an array). You *can* put object instances in there, but you need t... | As far as simplicity, it doesn't get any better than:
```
# Start the session manager
session_start();
# Set a var
$_SESSION['foo'] = 'whatever';
# Access the var
print $_SESSION['foo'];
``` | What's the most current, good practice, and easiest way to use sessions in PHP? | [
"",
"php",
"session",
""
] |
This came up from [this answer to a previous question of mine](https://stackoverflow.com/questions/55093/how-to-deal-with-arrays-declared-on-the-stack-in-c#55183).
Is it guaranteed for the compiler to treat `array[4][4]` the same as `array[16]`?
For instance, would either of the below calls to `api_func()` be safe?
`... | From the C++ standard, referring to the `sizeof` operator:
> When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of `n` elements is `n` times the size of an element.
From this, I'd say that `double[4][4]` and `double[16]` would have to have the same u... | I don't think there is a problem with padding introduced by having a **multi-dimensional** array.
Each element in an array must satisfy the padding requirements imposed by the architecture. An array [N][M] is always going to have the same in memory representation as one of [M\*N]. | Casting between multi- and single-dimentional arrays | [
"",
"c++",
"arrays",
""
] |
Is it possible to detect the HTTP request method (e.g. GET or POST) of a page from JavaScript? If so, how? | In a word - No | I don't believe so. If you need this information, I suggest including a `<meta>` element generated on the server that you can check with JavaScript.
For example, with PHP:
```
<meta id="request-method" name="request-method" content="<?php echo htmlentities($_SERVER['REQUEST_METHOD']); ?>">
<script type="text/javascri... | Client-side detection of HTTP request method | [
"",
"javascript",
"http-headers",
""
] |
I'm building a C# application that will monitor a specified directory for changes and additions and storing the information in a database.
I would like to avoid checking each individual file for modifications, but I'm not sure if I can completely trust the file access time.
What would be the best method to use for ge... | Hmm... interesting question. Initially I'd point you at the [FileSystemWatcher](http://msdn.microsoft.com/en-GB/library/system.io.filesystemwatcher.aspx) class. If you are going to have it work, however, on user request, then it would seem you might need to store off the directory info initially and then compare each t... | Use the FileSystemWatcher object. Here is some code to do what you are looking for.
```
// Declares the FileSystemWatcher object
FileSystemWatcher watcher = new FileSystemWatcher();
// We have to specify the path which has to monitor
watcher.Path = @"\\somefilepath";
// This property spec... | Directory Modification Monitoring | [
"",
"c#",
"file",
"directory",
"filesystems",
""
] |
Static metaprogramming (aka "template metaprogramming") is a great C++ technique that allows the execution of programs at compile-time. A light bulb went off in my head as soon as I read this canonical metaprogramming example:
```
#include <iostream>
using namespace std;
template< int n >
struct factorial { enum { re... | *[Answering my own question]*
The best introductions I've found so far are chapter 10, "Static Metaprogramming in C++" from *Generative Programming, Methods, Tools, and Applications* by Krzysztof Czarnecki and Ulrich W. Eisenecker, ISBN-13: 9780201309775; and chapter 17, "Metaprograms" of *C++ Templates: The Complete ... | Andrei Alexandrescu's [Modern C++ Design](http://erdani.com/index.php/books/modern-c-design/) book covers a lot of this and other tricks for speedy and efficient modern C++ code and is the basis for the [Loki](http://loki-lib.sourceforge.net/) library.
Also worth mentioning is the [Boost](http://boost.org) libraries, ... | Best introduction to C++ template metaprogramming? | [
"",
"c++",
"templates",
"metaprogramming",
""
] |
How can I convert a character to its ASCII code using JavaScript?
For example:
> get 10 from "\n". | ```
"\n".charCodeAt(0);
```
Here is the documentation for [`charCodeAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt):
> The `charCodeAt()` method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
>
> The UTF-16 code uni... | [`String.prototype.charCodeAt()`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/charCodeAt) can convert string characters to ASCII numbers. For example:
```
"ABC".charCodeAt(0) // returns 65
```
For opposite use [`String.fromCharCode(10)`](https://developer.mozilla.org/en/JavaScript/Refe... | Convert character to ASCII code in JavaScript | [
"",
"javascript",
""
] |
Suppose I have the following code:
```
class some_class{};
some_class some_function()
{
return some_class();
}
```
This seems to work pretty well and saves me the trouble of having to declare a variable just to make a return value. But I don't think I've ever seen this in any kind of tutorial or reference. Is th... | No this is perfectly valid. This will also be more efficient as the compiler is actually able to optimise away the temporary. | Returning objects from a function call is the "Factory" Design Pattern, and is used extensively.
However, you will want to be careful whether you return objects, or pointers to objects. The former of these will introduce you to copy constructors / assignment operators, which can be a pain. | Is there anything wrong with returning default constructed values? | [
"",
"c++",
"oop",
"visual-c++",
"constructor",
""
] |
Is it possible to change the font size used in a ContextMenu using the .NET Framework 3.5 and C# for a desktop application? It seems it's a system-wide setting, but I would like to change it only within my application. | If you are defining your own context menu via a `ContextMenuStrip` in Windows Forms, use the *Font* property.
If you are defining your own context menu via a `ContextMenu` in WPF, use the various *Fontxxx* properties such as *FontFamily* and *FontSize*.
You cannot change the default context menus that come with contr... | In WPF:
```
<Window.ContextMenu FontSize="36">
<!-- ... -->
</Window.ContextMenu
```
In WinForms:
```
contextMenuStrip1.Font = new System.Drawing.Font("Segoe UI", 24F);
``` | Change ContextMenu Font Size in C# | [
"",
"c#",
".net",
"contextmenu",
"font-size",
""
] |
Is it particularly bad to have a very, very large SQL query with lots of (potentially redundant) WHERE clauses?
For example, here's a query I've generated from my web application with everything turned off, which should be the largest possible query for this program to generate:
```
SELECT *
FROM 4e_magic_items
INN... | Reading your query makes me want to play an RPG.
This is definitely not too long. As long as they are well formatted, I'd say a practical limit is about 100 lines. After that, you're better off breaking subqueries into views just to keep your eyes from crossing.
I've worked with some queries that are 1000+ lines, and... | Default MySQL 5.0 server limitation is "**1MB**", configurable up to 1GB.
This is configured via the [max\_allowed\_packet](http://dev.mysql.com/doc/refman/5.0/en/packet-too-large.html) setting on both client and server, and the effective limitation is the lessor of the two.
Caveats:
* It's likely that this "packet"... | Practical limit to length of SQL query (specifically MySQL) | [
"",
"mysql",
"sql",
"optimization",
""
] |
I'm writing an inner loop that needs to place `struct`s in contiguous storage. I don't know how many of these `struct`s there will be ahead of time. My problem is that STL's `vector` initializes its values to 0, so no matter what I do, I incur the cost of the initialization plus the cost of setting the `struct`'s membe... | `std::vector` must initialize the values in the array somehow, which means some constructor (or copy-constructor) must be called. The behavior of `vector` (or any container class) is undefined if you were to access the uninitialized section of the array as if it were initialized.
The best way is to use `reserve()` and... | In C++11 (and boost) you can use the array version of `unique_ptr` to allocate an uninitialized array. This isn't quite an stl container, but is still memory managed and C++-ish which will be good enough for many applications.
```
auto my_uninit_array = std::unique_ptr<mystruct[]>(new mystruct[count]);
``` | STL vectors with uninitialized storage? | [
"",
"c++",
"optimization",
"stl",
"vector",
""
] |
I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | Python 3.10 (2021) introduced the [`match`-`case`](https://www.python.org/dev/peps/pep-0634/) statement, which provides a first-class implementation of a "switch" for Python. For example:
```
def f(x):
match x:
case 'a':
return 1
case 'b':
return 2
case _:
... | If you'd like defaults, you could use the dictionary [`get(key[, default])`](https://docs.python.org/3/library/stdtypes.html#dict.get) function:
```
def f(x):
return {
'a': 1,
'b': 2
}.get(x, 9) # 9 will be returned default if x is not found
``` | Replacements for switch statement in Python? | [
"",
"python",
"switch-statement",
""
] |
The following SQL:
```
SELECT notes + 'SomeText'
FROM NotesTable a
```
Give the error:
> The data types nvarchar and text are incompatible in the add operator. | The only way would be to convert your text field into an nvarchar field.
```
Select Cast(notes as nvarchar(4000)) + 'SomeText'
From NotesTable a
```
Otherwise, I suggest doing the concatenation in your application. | You might want to consider NULL values as well. In your example, if the column **notes** has a null value, then the resulting value will be NULL. If you want the null values to behave as empty strings (so that the answer comes out 'SomeText'), then use the IsNull function:
```
Select IsNull(Cast(notes as nvarchar(4000... | How do I concatenate text in a query in sql server? | [
"",
"sql",
"sql-server",
""
] |
I have a quandary. My web application (C#, .Net 3.0, etc) has Themes, CSS sheets and, of course, inline style definitions. Now that's alot of chefs adding stuff to the soup. All of this results, not surprisingly, in my pages having bizarre styling on occasion.
I am sure that all these styles are applied in a hierarchi... | IMHO, Firebug is going to be your best bet. It will tell you which file the style came from and you can click on the filename to be transported instantly to the relevant line in the file.
Note: You can hit `ctrl`+`shift`+`C` on any page to select and inspect an element with the mouse. | Here's a quick sreencast of how to use Firebug to find out from where an element is getting it's style.
<http://screencast.com/t/oFpuDUoJ0> | How can you find out where the style for a ASP .Net web page element came from? | [
"",
"c#",
"asp.net",
"css",
"themes",
""
] |
I am a fan of [static metaprogramming in C++](https://stackoverflow.com/questions/112277/best-intro-to-c-static-metaprogramming). I know Java now has generics. Does this mean that static metaprogramming (i.e., compile-time program execution) is possible in Java? If so, can anyone recommend any good resources where one ... | # The short answer
This question is nearly more than 10 years old, but I am still missing one answer to this. And this is: **yes**, but not *because* of generics and note quite the same as C++.
As of Java 6, we have [the pluggable annotation processing api](https://javabeat.net/java-6-0-features-part-2-pluggable-anno... | No, this is not possible. Generics are not as powerful as templates. For instance, a template argument can be a user-defined type, a primitive type, or a value; but a generic template argument can only be `Object` or a subtype thereof.
Edit: This is an old answer; since 2011 we have Java 7, which has [Annotations that... | Is static metaprogramming possible in Java? | [
"",
"java",
"metaprogramming",
""
] |
There is a well-known debate in Java (and other communities, I'm sure) whether or not trivial getter/setter methods should be tested. Usually, this is with respect to code coverage. Let's agree that this is an open debate, and not try to answer it here.
There have been several blog posts on using Java reflection to au... | [Unitils](http://www.unitils.org) does this w/ the static method `assertRefEquals`. | I created the [OpenPojo](https://github.com/OpenPojo/openpojo) project for solving this *exact* problem.
The project allows you to validate:
* Enforce Pojo coding standard (i.e. All fields private, or no native variables, ...etc)
* Enforce Pojo behaviour (i.e. setter does JUST setting, no transformation, etc)
* Valid... | Is there a Java unit-test framework that auto-tests getters and setters? | [
"",
"java",
"unit-testing",
"junit",
""
] |
My quick search reveals the reference implementation (<http://stax.codehaus.org>), the Woodstox implementation (<http://woodstox.codehaus.org>), and Sun's SJSXP implementation (<https://sjsxp.dev.java.net/>).
Please comment on the relative merits of these, and fill me in on any other implementations I should consider. | Woodstox wins every time for me. It's not just performance, either - sjsxp is twitchy and overly pedantic, woodstox just gets on with it. | Interesting to note that:
> SJSXP performance is consistently faster than BEA, Oracle and RI for all
> of the documents described here in this study. However, it lags behind
> Woodstox and XPP3 in some document sizes and in the best cases, exhibits
> similar performance compared to these two parsers.
Article from Sun... | Best StAX Implementation | [
"",
"java",
"xml",
"parsing",
"stax",
""
] |
Is this function declaration in C#:
```
void foo(string mystring)
```
the same as this one in C:
```
void foo(char *)
```
i.e. In C#, does the called function receive a pointer behind the scenes? | In this specific instance, it is more like:
```
void foo(const char *);
```
.Net strings are immutable and passed by reference. However, in general C# receives a pointer or reference to an object behind the scenes. | There are pointers behind the scenes in C#, though they are more like C++'s smart pointers, so the raw pointers are encapsulated. A char\* isn't really the same as System.String since a pointer to a char usually means the start of a character array, and a C# string is an object with a length field *and* a character arr... | C pointers in C# | [
"",
"c#",
"c",
"string",
"pointers",
"language-implementation",
""
] |
I'm currently looking for ways to create automated tests for a [JAX-RS](https://jsr311.dev.java.net/) (Java API for RESTful Web Services) based web service.
I basically need a way to send it certain inputs and verify that I get the expected responses. I'd prefer to do this via JUnit, but I'm not sure how that can be a... | [Jersey](http://jersey.java.net/) comes with a great RESTful client API that makes writing unit tests really easy. See the unit tests in the examples that ship with Jersey. We use this approach to test the REST support in [Apache Camel](http://activemq.apache.org/camel/), if you are interested the [test cases are here]... | You can try out [REST Assured](http://code.google.com/p/rest-assured/) which makes it *very* simple to test REST services and validating the response in Java (using JUnit or TestNG). | Testing a JAX-RS Web Service? | [
"",
"java",
"web-services",
"unit-testing",
"junit",
"jax-rs",
""
] |
I'm looking for a method that computes the line number of a given text position in a JTextPane with wrapping enabled.
Example:
> This a very very very very very very very very very very very very very very very very very very very very very very long line.
> This is another very very very very very very very very v... | Try this
```
/**
* Return an int containing the wrapped line index at the given position
* @param component JTextPane
* @param int pos
* @return int
*/
public int getLineNumber(JTextPane component, int pos)
{
int posLine;
int y = 0;
try
{
Rectangle caretCoords = component.mo... | <http://java-sl.com/tip_row_column.html>
An alternative which works with text fragments formatted with different styles | Method that returns the line number for a given JTextPane position? | [
"",
"java",
"user-interface",
"swing",
"jtextpane",
""
] |
I'm looking for a good, clean way to go around the fact that PHP5 still doesn't support multiple inheritance. Here's the class hierarchy:
Message
-- TextMessage
-------- InvitationTextMessage
-- EmailMessage
-------- InvitationEmailMessage
The two types of Invitation\* classes have a lot in common; i'd love t... | Alex, most of the times you need multiple inheritance is a signal your object structure is somewhat incorrect. In situation you outlined I see you have class responsibility simply too broad. If Message is part of application business model, it should not take care about rendering output. Instead, you could split respon... | Maybe you can replace an 'is-a' relation with a 'has-a' relation? An Invitation might have a Message, but it does not necessarily need to 'is-a' message. An Invitation f.e. might be confirmed, which does not go well together with the Message model.
Search for 'composition vs. inheritance' if you need to know more abou... | Multiple Inheritance in PHP | [
"",
"php",
"oop",
"inheritance",
""
] |
In PHP, the HEREDOC string declarations are really useful for outputting a block of html. You can have it parse in variables just by prefixing them with $, but for more complicated syntax (like $var[2][3]), you have to put your expression inside {} braces.
In PHP 5, it *is* possible to actually make function calls wit... | I would not use HEREDOC at all for this, personally. It just doesn't make for a good "template building" system. All your HTML is locked down in a string which has several disadvantages
* No option for WYSIWYG
* No code completion for HTML from IDEs
* Output (HTML) locked to logic files
* You end up having to use hack... | If you really want to do this but a bit simpler than using a class you can use:
```
function fn($data) {
return $data;
}
$fn = 'fn';
$my_string = <<<EOT
Number of seconds since the Unix Epoch: {$fn(time())}
EOT;
``` | Calling PHP functions within HEREDOC strings | [
"",
"php",
"string",
"heredoc",
""
] |
In what segment (.BSS, .DATA, other) of an executable file are static variables stored so that they don't have name collision?
For example:
```
foo.c: bar.c:
static int foo = 1; static int foo = 10;
void fooTest() { void barTest() {
static int bar = 2; stat... | Where your statics go depends on whether they are *zero-initialized*. *zero-initialized* static data goes in [.BSS (Block Started by Symbol)](http://en.wikipedia.org/wiki/.bss), *non-zero-initialized* data goes in [.DATA](http://en.wikipedia.org/wiki/Data_segment) | When a program is loaded into memory, it’s organized into different segments. One of the segment is **DATA segment**. The Data segment is further sub-divided into two parts:
* **Initialized data segment:** All the global, static and constant data are stored here.
* **Uninitialized data segment (BSS):** All the unini... | Where are static variables stored in C and C++? | [
"",
"c++",
"c",
"compiler-construction",
""
] |
I've been wondering about the performance improvements touted in Java SE 6 - is it in the compiler or the runtime? Put another way, would a Java 5 application compiled by JDK 6 see an improvement run under JSE 5 (indicating improved compiler optimization)? Would a Java 5 application compiled by JDK 5 see an improvement... | I have not heard about improvements in the compiler, but extensive information has been published on the runtime performance improvements.
**Migration guide:**
<http://java.sun.com/javase/6/webnotes/adoption/adoptionguide.html>
**Performance whitepaper:**
<https://www.oracle.com/java/technologies/javase/6performanc... | javac, which compiles from Java source to bytecodes, does almost no optimisation. Indeed optimisation would often make code actually run slower by being harder to analyse for later optimisation.
The only significant difference between generated code for 1.5 and 1.6 is that with -target 1.6 extra information is added a... | Are Java 6's performance improvements in the JDK, JVM, or both? | [
"",
"java",
"performance",
"comparison",
"benchmarking",
"versions",
""
] |
We all know that RAW pointers need to be wrapped in some form of smart pointer to get Exception safe memory management. But when it comes to containers of pointers the issue becomes more thorny.
The std containers insist on the contained object being copyable so this rules out the use of std::auto\_ptr, though you can... | Boost pointer containers have strict ownership over the resources they hold. A std::vector<boost::shared\_ptr<X>> has shared ownership. There are reasons why that may be necessary, but in case it isn't, I would default to boost::ptr\_vector<X>. YMMV. | Steady on: smart pointers are a very good method of handling resource management, but not the only one. I agree you will see very few raw pointers in well-written C++ code, but in my experience you don't see that many smart pointers either. There are plenty of perfectly exception-safe classes implemented using containe... | Pointers and containers | [
"",
"c++",
"stl",
"containers",
"smart-pointers",
""
] |
How do you implement an **efficient and thread safe reference counting system** on X86 CPUs in the C++ programming language?
I always run into the problem that the **critical operations not atomic**, and the available X86 Interlock operations are not sufficient for implementing the ref counting system.
The following ... | Nowadays, you can use the Boost/TR1 shared\_ptr<> smart pointer to keep your reference counted references.
Works great; no fuss, no muss. The shared\_ptr<> class takes care of all the locking needed on the refcount. | In VC++, you can use [\_InterlockedCompareExchange](http://msdn.microsoft.com/en-us/library/ttk2z1ws.aspx).
```
do
read the count
perform mathematical operation
interlockedcompareexchange( destination, updated count, old count)
until the interlockedcompareexchange returns the success code.
```
On other platf... | How to implement thread safe reference counting in C++ | [
"",
"c++",
"multithreading",
"atomic",
"reference-counting",
""
] |
I am new to any scripting language. But, Still I worked on scripting a bit like tailoring other scripts to work for my purpose. For me, What is the best online resource to learn Python?
[Response Summary:]
Some Online Resources:
[<http://docs.python.org/tut/tut.html>](http://docs.python.org/tut/tut.html) - Beginners... | If you need to learn python from scratch - you can start here: <http://docs.python.org/tut/tut.html> - good begginers guide
If you need to extend your knowledge - continue here <http://diveintopython3.ep.io/> - good intermediate level book
If you need perfect skills - complete this <http://www.pythonchallenge.com/> -... | If you're a beginner, try my book [A Byte of Python](http://www.swaroopch.com/notes/Python).
If you're already experienced in programming, try [Dive Into Python](http://www.diveintopython.org). | Best online resource to learn Python? | [
"",
"python",
""
] |
Why is it that they decided to make `String` immutable in Java and .NET (and some other languages)? Why didn't they make it mutable? | According to [Effective Java](http://www.oracle.com/technetwork/java/effectivejava-136174.html), chapter 4, page 73, 2nd edition:
> "There are many good reasons for this: Immutable classes are easier to
> design, implement, and use than mutable classes. They are less prone
> to error and are more secure.
>
> [...]
>
>... | There are at least two reasons.
**First - security** <http://www.javafaq.nu/java-article1060.html>
> The main reason why String made
> immutable was security. Look at this
> example: We have a file open method
> with login check. We pass a String to
> this method to process authentication
> which is necessary before ... | Why can't strings be mutable in Java and .NET? | [
"",
"java",
".net",
"string",
"mutable",
""
] |
In a C++ project I'm working on, I have a *flag* kind of value which can have four values. Those four flags can be combined. Flags describe the records in database and can be:
* new record
* deleted record
* modified record
* existing record
Now, for each record I wish to keep this attribute, so I could use an enum:
... | Combine the strategies to reduce the disadvantages of a single approach. I work in embedded systems so the following solution is based on the fact that integer and bitwise operators are fast, low memory & low in flash usage.
Place the enum in a namespace to prevent the constants from polluting the global namespace.
`... | ## Forget the defines
They will pollute your code.
## bitfields?
```
struct RecordFlag {
unsigned isnew:1, isdeleted:1, ismodified:1, isexisting:1;
};
```
**Don't ever use that**. You are more concerned with speed than with economizing 4 ints. Using bit fields is actually slower than access to any other type.
... | Should I use #define, enum or const? | [
"",
"c++",
"enums",
"bit-manipulation",
"c-preprocessor",
""
] |
We have a large ASP classic code base but I'm looking to do future development in ASP.NET (and potentially in the future port across what we have). The natural choice of language seems to be VB (existing code is VBScript) but am I being too hasty? Does the choice of language, in the long run, even make a difference? | It's learning .Net (framework) that takes the time.
The specific language doesn't matter and is more a matter of taste. I'd normally recommend trying a few play projects in both languages (and any others that may take your fancy), and then decide which one you're more comfortable with (or have more success with!) | First of all, don't port something for the sake of it. If it's working fine and there's little to be gained from porting it, leave it alone, and continue doing bugfixes and small enhancements in VBScript. If there's sufficient reason to move things across, then do it at that point, but you're much better off becoming f... | Moving to ASP.NET - VB or C#? | [
"",
"c#",
".net",
"asp.net",
"vb.net",
"webforms",
""
] |
I'm looking for a good tool to profile a java webapp. I'd like to get performance information and memory usage if possible.
Any suggestions? | [JProfiler](http://www.ej-technologies.com/products/jprofiler/overview.html) is a really good one. It integrates with all the major IDEs and application servers. | The [Eclipse Memory Analyzer](http://www.eclipse.org/mat/) is the best tool for analysing the memory usage of java applications | Does anyone here have a favorite memory profiling/memory leak tool they like to use for their java webapps? | [
"",
"java",
"profiling",
"web-applications",
""
] |
I'm wondering, how expensive it is to have many threads in waiting state in java 1.6 x64.
To be more specific, I'm writing application which runs across many computers and sends/receives data from one to another. I feel more comfortable to have separate thread for each connected machine and task, like 1) sending data,... | For most cases, the resources consumed by a sleeping thread will be its stack space. Using a 2-threads-per-connection-model, which I think is similar to what you're describing, is known to cause great scalability issues for this very reason when the number of connections grow large.
I've been in this situation myself,... | We had very much the same problem before we switched to NIO, so I will second Liedmans recommendation to go with that framework. You should be able to find a tutorial, but if you want the details, I can recommend [Java NIO](https://rads.stackoverflow.com/amzn/click/com/0596002882) by Ron Hitchens.
Swithcing to NIO inc... | How much resources do sleeping and waiting threads consume | [
"",
"java",
"multithreading",
"sleep",
"wait",
""
] |
In ASP.NET, when storing a value in the application cache with absolute expiry is there a method to retrieve the date/time when the item will expire? The application cache item will be refreshed if expired based on user requests. | There is a method signature on the HttContext.Cache object which allows you to specify a method to be called in the event that a Cached item is removed when you set a new Cache item.
Define yourself a method that'll allow you to process that information, whether you want it to re-submit the item to the Applcation Cach... | Not sure if I've understood your question right, but I'll give it a try: I believe there is no way to actually figure out, when a certain cache-item is going to expire. In most scenarios, I use a delegate passed in as a parameter (CacheItemRemovedCallback) when adding objects to the cache, so I get notified when the it... | Determine when application cache item will timeout? | [
"",
"c#",
"asp.net",
"asp.net-1.1",
""
] |
I've seen several examples of code like this:
```
if not someobj:
#do something
```
But I'm wondering why not doing:
```
if someobj == None:
#do something
```
Is there any difference? Does one have an advantage over the other? | In the first test, Python try to convert the object to a `bool` value if it is not already one. Roughly, **we are asking the object : are you meaningful or not ?** This is done using the following algorithm :
1. If the object has a `__nonzero__` special method (as do numeric built-ins, `int` and `float`), it calls thi... | These are actually both poor practices. Once upon a time, it was considered OK to casually treat None and False as similar. However, since Python 2.2 this is not the best policy.
First, when you do an `if x` or `if not x` kind of test, Python has to implicitly convert `x` to boolean. The rules for the `bool` function ... | Why is "if not someobj:" better than "if someobj == None:" in Python? | [
"",
"python",
""
] |
Is there any way that my script can retrieve metadata values that are declared in its own header? I don't see anything promising in the API, except perhaps `GM_getValue()`. That would of course involve a special name syntax. I have tried, for example: `GM_getValue("@name")`.
The motivation here is to avoid redundant s... | **This answer is out of date :** As of Greasemonkey 0.9.16 (Feb 2012) please see [Brock's answer](https://stackoverflow.com/a/10475344/1820) regarding `GM_info`
---
Yes. A very simple example is:
```
var metadata=<>
// ==UserScript==
// @name Reading metadata
// @namespace http://www.afunamatata.com/... | Use [the `GM_info` object](http://wiki.greasespot.net/GM_info), which was added to Greasemonkey in version 0.9.16.
For example, if You run this script:
```
// ==UserScript==
// @name _GM_info demo
// @namespace Stack Overflow
// @description Tell me more about me, me, ME!
// @include http... | Accessing Greasemonkey metadata from within your script? | [
"",
"javascript",
"metadata",
"greasemonkey",
""
] |
How do I programatically (Using C#) find out what the path is of my My Pictures folder?
Does this work on XP and Vista? | The following will return a full-path to the location of the users picture folder (Username\My Documents\My Pictures on XP, Username\Pictures on Vista)
```
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
``` | Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); | Location of My Pictures | [
"",
"c#",
"windows",
"windows-vista",
"windows-xp",
""
] |
I've got a situation where I have a DLL I'm creating that uses another third party DLL, but I would prefer to be able to build the third party DLL into my DLL instead of having to keep them both together if possible.
This with is C# and .NET 3.5.
The way I would like to do this is by storing the third party DLL as an... | Once you've embedded the third-party assembly as a resource, add code to subscribe to the [`AppDomain.AssemblyResolve`](http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx) event of the current domain during application start-up. This event fires whenever the Fusion sub-system of the CLR fails... | In the end I did it almost exactly the way raboof suggested (and similar to what dgvid suggested), except with some minor changes and some omissions fixed. I chose this method because it was closest to what I was looking for in the first place and didn't require using any third party executables and such. It works grea... | Embedding one dll inside another as an embedded resource and then calling it from my code | [
"",
"c#",
".net-3.5",
"dll",
""
] |
When a getter returns a property, such as returning a `List` of other related objects, should that list and it's objects be immutable to prevent code outside of the class, changing the state of those objects, without the main parent object knowing?
For example if a `Contact` object, has a `getDetails` getter, which re... | It's a matter of whether you should be "defensive" in your code. If you're the (sole) user of your class and you trust yourself then by all means no need for immutability. However, if this code needs to work no matter what, or you don't trust your user, then make everything that is externalized immutable.
That said, m... | It depends on the context. If the list is intended to be mutable, there is no point in cluttering up the API of the main class with methods to mutate it when List has a perfectly good API of its own.
However, if the main class can't cope with mutations, then you'll need to return an immutable list - and the entries in... | Considering object encapsulation, should getters return an immutable property? | [
"",
"java",
"oop",
""
] |
The second question is: When do I use what of these two? | When not specified, C++ is unmanaged C++, compiled to machine code. In unmanaged C++ you must manage memory allocation manually.
Managed C++ is a language invented by Microsoft, that compiles to bytecode run by the .NET Framework. It uses mostly the same syntax as C++ (hence the name) but is compiled in the same way a... | "Managed C++" refers to a language that was included in Visual Studio.NET/Visual Studio.NET 2003. It has since [been deprecated](https://en.wikipedia.org/wiki/Managed_Extensions_for_C%2B%2B#.E2.80.A6to_C.23), with the latest .NET C++ being C++/CLI. | Difference between managed C++ and C++ | [
"",
"c++",
"visual-c++",
"programming-languages",
"managed-c++",
""
] |
Previously I have asked to strip text from a field and convert it to an int, this works successfully. But now, I would like to do an INNER JOIN on this new value.
So I have this:
```
SELECT CONVERT(int, SUBSTRING(accountingTab.id, PATINDEX('%[0-9]%', accountingTab.id), 999))
AS 'memId', userDetails.title, userDetai... | If you have to do this, you have design problems. If you're able, I would suggest you need to refactor your table or relationships. | You can either repeat the whole expression or reverse your join:
```
SELECT *
FROM memDetTab
JOIN (SELECT CONVERT(int, SUBSTRING(accountingTab.id, PATINDEX('%[0-9]%', accountingTab.id), 999)) AS 'memId', userDetails.title, userDetails.lname
FROM accountingTab) subquery
ON subquery.memID = memDetTab.ID
``` | SQL: inner join on alias column | [
"",
"sql",
"inner-join",
""
] |
I'm still a little unclear and when to wrap a *lock* around some code. My general rule-of-thumb is to wrap an operation in a lock when it reads or writes to a static variable. But when a static variable is ONLY read (e.g. it's a readonly that is set during type initialization), accessing it doesn't need to be wrapped i... | Since none of the code you've written modifies the static field after initialization, there is no need for any locking. Just replacing the string with a new value won't need synchronization either, unless the new value depends on the results of a read of the old value.
Static fields aren't the only things that need sy... | Reading or writing a 32-bit or smaller field is an atomic operation in C#. There's no need for a lock in the code you presented, as far as I can see. | Locking in C# | [
"",
"c#",
"multithreading",
"concurrency",
"synchronization",
""
] |
I have CSV data loaded into a multidimensional array. In this way each "row" is a record and each "column" contains the same type of data. I am using the function below to load my CSV file.
```
function f_parse_csv($file, $longest, $delimiter)
{
$mdarray = array();
$file = fopen($file, "r");
while ($line = fg... | You can use [array\_multisort()](http://php.net/manual/en/function.array-multisort.php)
Try something like this:
```
foreach ($mdarray as $key => $row) {
// replace 0 with the field's index/key
$dates[$key] = $row[0];
}
array_multisort($dates, SORT_DESC, $mdarray);
```
For PHP >= 5.5.0 just extract the col... | ## Introducing: a very generalized solution for PHP 5.3+
I 'd like to add my own solution here, since it offers features that other answers do not.
Specifically, advantages of this solution include:
1. It's **reusable**: you specify the sort column as a variable instead of hardcoding it.
2. It's **flexible**: you ca... | How do I Sort a Multidimensional Array in PHP | [
"",
"php",
"sorting",
"multidimensional-array",
""
] |
Working on a somewhat complex page for configuring customers at work. The setup is that there's a main page, which contains various "panels" for various groups of settings.
In one case, there's an email address field on the main table and an "export" configuration that controls how emails are sent out. I created a mai... | The Bind can't convert the null value to an int value, to set the ExportInfoID property. That's why it's not getting caught in your code. You can make the property a nullable type (int?) or you can handle the null in the bind logic.
so it would be something like this
```
bind receives field to get value from
bind use... | It seems like it's because `hfID.Value` isn't initialized to a value yet so it can't be converted. You may wanna add a null check in your getter or some validation to make sure `hfID.Value` isn't null and is numeric. | Binding a null value to a property of a web user control | [
"",
"c#",
".net",
"asp.net",
""
] |
The following JavaScript supposes to read the popular tags from an XML file and applies the XSL Stylesheet and output to the browser as HTML.
```
function ShowPopularTags() {
xml = XMLDocLoad("http://localhost/xml/tags/popular.xml?s=94987898");
xsl = XMLDocLoad("http://localhost/xml/xsl/popular-tags.xsl");
if... | Are you forced into the synchronous solution you are using now, or is an asynchronous solution an option as well? I recall Firefox has had it's share of problems with synchronous calls in the past, and I don't know how much of that is still carried with it. I have seen situations where the entire Firefox interface woul... | To avoid problems with things loading in parallel (as hinted by Dan), it is always a good idea to call such scripting only when the page has fully loaded.
Ideally you put the script-tags in the page head and call ShowPopularTags(); in the body Onload item. I.e.
```
<BODY onLoad="ShowPopularTags();">
```
That way you... | javascript XSLTProcessor occasionally not working | [
"",
"javascript",
"xml",
"firefox",
"xslt",
""
] |
I have a scenario where I have to check whether user has already opened Microsoft Word. If he has, then I have to kill the winword.exe process and continue to execute my code.
Does any one have any straight-forward code for killing a process using vb.net or c#? | You'll want to use the [System.Diagnostics.Process.Kill](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx) method. You can obtain the process you want using
[System.Diagnostics.Proccess.GetProcessesByName](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getprocessesbyname.... | Killing the Word process outright is possible (see some of the other replies), but outright rude and dangerous: what if the user has important unsaved changes in an open document? Not to mention the stale temporary files this will leave behind...
This is probably as far as you can go in this regard (VB.NET):
```
... | How do I kill a process using Vb.NET or C#? | [
"",
"c#",
"vb.net",
"process",
"kill",
""
] |
I'm supposed to create a simple rule engine in C#. Any leads on how I can proceed?. It's a minimalistic rule engine, and would use SQL server as the back end. Do we have any general blueprint or design patterns that generally apply to rule engines? What kind of .Net technologies can I use to design one? Any directions ... | If you're using .NET 3.0 or later, you [can use the Rules Engine of Windows Workflow Foundation](http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/08/09/WF-Rules-Engine-without-Workflow.aspx) without having to acutally use Workflow.
I've done this on a project, and you can use SQL or XML as the backend, and it w... | 1. I cannot believe you would implement your own considering there are so many available commercially and open source.
2. I recommend taking a look at InRule as a great commercial option that is reasonable priced, or NxBRE in the open source space. | How to design a rule engine? | [
"",
"c#",
"sql-server",
"rule-engine",
""
] |
I have a web app which connects to a server using a TCP connection and reads a binary document which it then writes to its response object. In other words it's transferring a file from a backend server using a custom protocol and returning that file to its client through HTTP.
The server sends a status code and a mime... | I would use the `OutputStream` directly with a general-purpose function. With the `Stream`, you can control `Flush`.
```
public void WriteDocument(HttpResponse response) {
StreamCopy(response.OutputStream, stream_);
response.End();
}
public static void StreamCopy(Stream dest, Stream src) {... | Here's what I do. Usually the content length is desired to know when to end the data storing loop. If your protocol does not send the amount of data to expect as a header then it should send some marker to signal the end of transmission.
The DataAvailable property just signals if there's data to read from the socket N... | How do I determine when there is no more data to read in a NetworkStream? | [
"",
"c#",
"networkstream",
""
] |
This is a good candidate for the ["Works on My Machine Certification Program"](http://www.codinghorror.com/blog/archives/000818.html).
I have the following code for a LinkButton...
```
<cc1:PopupDialog ID="pdFamilyPrompt" runat="server" CloseLink="false" Display="true">
<p>Do you wish to upgrade?</p>
<asp:HyperLi... | Check the html that is emitted on production and make sure that it has the \_\_doPostback() and that there are no global methods watching click and canceling the event. Other than that if you think it could be related to validation you could try adding CausesValidation or whatever to false and see if that helps. Otherw... | I had a similar problem. I created a form with an updatePanel, in the form were some linkbuttons that would open a modalpopup Ajax extender. They worked fine until I added authentication to the site. After that they didn't do anything at all.
Reading your solution I found that some of the linkbuttons WERE working, the... | LinkButton not firing on production server | [
"",
"c#",
"asp.net",
""
] |
I'm working on a project using the [ANTLR](http://antlr.org) parser library for C#. I've built a grammar to parse some text and it works well. However, when the parser comes across an illegal or unexpected token, it throws one of many exceptions. The problem is that in some cases (not all) that my try/catch block won't... | I believe I understand the problem. The exception is being caught, the issue is confusion over the debugger's behavior and differences in the debugger settings among each person trying to repro it.
In the 3rd case from your repro I believe you are getting the following message: "NoViableAltException was unhandled by u... | I can tell you what's happening here...
Visual Studio is breaking because it thinks the exception is unhandled. What does unhandled mean? Well, in Visual Studio, there is a setting in the Tools... Options... Debugging... General... "Enable Just My Code (Managed only)". If this is checked and if the exception propagate... | Why is .NET exception not caught by try/catch block? | [
"",
"c#",
".net",
"exception",
"antlr",
""
] |
I want to receive the following `HTTP` request in `PHP:`
```
Content-type: multipart/form-data;boundary=main_boundary
--main_boundary
Content-type: text/xml
<?xml version='1.0'?>
<content>
Some content goes here
</content>
--main_boundary
Content-type: multipart/mixed;boundary=sub_boundary
--sub_boundary
Conten... | `$HTTP_GET_VARS`, `$HTTP_POST_VARS`, etc. is an obsolete notation, you should be using `$_GET`, `$_POST`, etc.
Now, the file contents should be in the `$_FILES` global array, whereas, if there are no element names, I'm not sure about whether the rest of the content will show up in `$_POST`. Anyway, if `always_populate... | You should note:
“php://input allows you to read raw POST data. It is a less memory intensive alternative to $HTTP\_RAW\_POST\_DATA and does not need any special php.ini directives. php://input is not available with enctype=”multipart/form-data”
From php manual... so it seems php://input is not available
Cannot comm... | Receiving multipart POST data requests in PHP | [
"",
"php",
"http",
"mime",
"multipart",
"form-data",
""
] |
What I'm looking for is a simple timer queue possibly with an external timing source and a poll method (in this way it will be multi-platform). Each enqueued message could be an object implementing a simple interface with a `virtual onTimer()` member function. | `Boost::ASIO` contains an asynchronous timer implementation. That might work for you. | There is a nice article in CodeProject, [here](http://www.codeproject.com/KB/system/timers_intro.aspx), that describes the various timers available in Windows, and has chapters titled "Queue timers" and "Make your own timer".
For platform independence, you'd have to make implementations for the different platforms ins... | Is there a good lightweight multiplatform C++ timer queue? | [
"",
"c++",
"queue",
"timer",
""
] |
I'm looking for a framework to generate Java source files.
Something like the following API:
```
X clazz = Something.createClass("package name", "class name");
clazz.addSuperInterface("interface name");
clazz.addMethod("method name", returnType, argumentTypes, ...);
File targetDir = ...;
clazz.generate(targetDir);
`... | Sun provides an API called CodeModel for generating Java source files using an API. It's not the easiest thing to get information on, but it's there and it works extremely well.
The easiest way to get hold of it is as part of the JAXB 2 RI - the XJC schema-to-java generator uses CodeModel to generate its java source, ... | **Solution found with CodeModel**
Thanks, [skaffman](https://stackoverflow.com/users/21234/skaffman).
For example, with this code:
```
JCodeModel cm = new JCodeModel();
JDefinedClass dc = cm._class("foo.Bar");
JMethod m = dc.method(0, int.class, "foo");
m.body()._return(JExpr.lit(5));
File file = new File("./targe... | A Java API to generate Java source files | [
"",
"java",
"eclipse",
"code-generation",
""
] |
What would the differences be in implementing remote business logic?
Currently we are planning on using [ADF](http://en.wikipedia.org/wiki/Oracle_Application_Development_Framework) to develop front-end web applications (moving from [Struts](http://en.wikipedia.org/wiki/Apache_Struts)). What are the differences between... | ADF is pretty broad, as it encompasses front end all the way down through data access. It's a great [RAD](http://en.wikipedia.org/wiki/Rapid_application_development) framework if you are going to use the entire stack, but isn't so hot if you are only going to use one portion or the other.
I am assuming you are talking... | I'm going through a similar situation right now. I'm am not an expert, but here what I've gathered from my experience. Whether EJB's using Toplink or ADF scales better depends quite a bit on the particulars of your situation. In some cases one might be better than the other, but I get the feeling that they are both pre... | ADF business components through RMI vs EJB and Toplink | [
"",
"java",
"jakarta-ee",
"ejb",
"oracle-adf",
""
] |
Should I keep project filesm like Eclipse's .project, .classpath, .settings, under version control (e.g. Subversion, GitHub, CVS, Mercurial, etc)? | You do want to keep in version control **any portable setting files**,
meaning:
Any file which has no absolute path in it.
That includes:
* .project,
* .classpath (*if no absolute path used*, which is possible with the use of IDE variables, or user environment variables)
* **IDE settings** (which is where i disa... | .project and .classpath files yes. We do not however keep our IDE settings in version control. There are some plugins that do not do a good job of persisting settings and we found that some settings were not very portable from one dev machine to the next. So, we instead have a Wiki page that highlights the steps requir... | Should I keep my project files under version control? | [
"",
"java",
"eclipse",
"version-control",
"ide",
""
] |
The code below shows a sample that I've used recently to explain the different behaviour of structs and classes to someone brand new to development. Is there a better way of doing so? (Yes - the code uses public fields - that's purely for brevity)
```
namespace StructsVsClasses
{
class Program
{
static... | The difference might be easier to understand when the struct/class is a member of another class.
Example with class:
```
class PointClass {
int double X;
int double Y;
}
class Circle {
PointClass Center = new PointClass() { X = 0, Y = 0; }
}
static void Main() {
Circle c = new Circle();
Console.WriteLine(... | Well, your *explanation* isn't an explanation at all, it's an observation of behavior, which is different.
If you want an explanation of what the difference is, then you need a piece of text *explaining* it. And the behavior explained can be ed with the code.
The page linked to by Grimtron is good for detailing all t... | Is there a better way to explain the behaviour differences between structs and classes in .net? | [
"",
"c#",
".net",
""
] |
I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word.
Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase". | More exactly, a .docx document is a Zip archive in OpenXML format: you have first to uncompress it.
I downloaded a sample (Google: *some search term filetype:docx*) and after unzipping I found some folders. The *word* folder contains the document itself, in file *document.xml*. | After reading your post above, I made a 100% native Python docx module to solve this specific problem.
```
# Import the module
from docx import document, opendocx
# Open the .docx file
document = opendocx('A document.docx')
# Search returns true if found
search(document,'your search string')
```
The docx module... | How can I search a word in a Word 2007 .docx file? | [
"",
"python",
"ms-word",
"openxml",
"docx",
""
] |
I would like to know if there is any way to add custom behaviour to the auto property get/set methods.
An obvious case I can think of is wanting every set property method to call on any `PropertyChanged` event handlers as part of a `System.ComponentModel.INotifyPropertyChanged` implementation. This would allow a class... | No, you'll have to use "traditional" property definitions for custom behavior. | No you cannot : auto property are a shortcut for an explicit accessor to a private field. e.g.
```
public string Name { get; set;}
```
is a shortcut to
```
private string _name;
public string Name { get { return _name; } set { _name = value; } };
```
If you want to put custom logic you must write get and set explic... | C# 3.0 Auto-Properties - Is it possible to add custom behaviour? | [
"",
"c#",
".net",
"properties",
"automatic-properties",
""
] |
I need to compress portions of our application's network traffic for performance. I presume this means I need to stay away from some of the newer algorithms like bzip2, which I think I have heard is slower. | You can use [Deflater](https://docs.oracle.com/javase/8/docs/api/java/util/zip/Deflater.html)/[Inflater](http://docs.oracle.com/javase/7/docs/api/java/util/zip/Inflater.html) which is built into the JDK. There are also GZIPInputStream and GZIPOutputStream, but it really depends on your exact use.
Edit:
Reading furthe... | Your compression algorithm depends on what your trying to optimize, and how much bandwidth you have available.
If you're on a gigibit LAN, almost any compression algorithm is going to slow your program down just a bit. If your connecting over a WAN or internet, you can afford to do a bit more compression. If you conne... | What's a good compression library for Java? | [
"",
"java",
"compression",
""
] |
I am using Oracle 9 and JDBC and would like to encyrpt a clob as it is inserted into the DB. Ideally I'd like to be able to just insert the plaintext and have it encrypted by a stored procedure:
```
String SQL = "INSERT INTO table (ID, VALUE) values (?, encrypt(?))";
PreparedStatement ps = connection.prepareStatement(... | I note you are on Oracle 9, but just for the record in Oracle 10g+ the dbms\_obfuscation\_toolkit was deprecated in favour of dbms\_crypto.
[dbms\_crypto](http://68.142.116.68/docs/cd/B28359_01/appdev.111/b28419/d_crypto.htm#i1005082) does include CLOB support:
```
DBMS_CRYPTO.ENCRYPT(
dst IN OUT NOCOPY BLOB,
s... | There is an example in Oracle Documentation:
<http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96612/d_obtoo2.htm>
You do not need to close it
```
DECLARE
input_string VARCHAR2(16) := 'tigertigertigert';
raw_input RAW(128) := UTL_RAW.CAST_TO_RAW(input_string);
key_string VA... | What is the best way to encrypt a clob? | [
"",
"java",
"oracle",
"encryption",
"jdbc",
"plsql",
""
] |
I am fairly comfortable with standalone Java app development, but will soon be working on a project using a Java EE application server.
Does anyone know of a straightforward how-to tutorial to getting a hello-world type application working in an application server? I'm (perhaps naievly) assuming that the overall appro... | I would choose JBoss AS or GlassFish for a start. However I'm not sure what you mean by Java EE "Hello World". If you just want to deploy some JSP you could use this tutorial (for JBoss):
<http://www.centerkey.com/jboss/>
If you want to get further and do the EJB stack and/or deploy an ear-file, you could read the ve... | The JavaEE (they dropped the 2) space is pretty big. A good tutorial to start is [the one from Sun](http://java.sun.com/javaee/5/docs/tutorial/doc/). For a simple hello world application, the web container only would suffice. A well known servlet jsp container is tomcat. See [here](http://www.coreservlets.com/Apache-To... | Java EE App Server Hello World | [
"",
"java",
"jakarta-ee",
""
] |
What does it mean when it gives a backtrace with the following output?
```
#0 0x00000008009c991c in pthread_testcancel () from /lib/libpthread.so.2
#1 0x00000008009b8120 in sigaction () from /lib/libpthread.so.2
#2 0x00000008009c211a in pthread_mutexattr_init () from /lib/libpthread.so.2
#3 0x0000000000000000 in ?... | gdb wasn't able to extract the proper return address from pthread\_mutexattr\_init; it got an address of 0. The "??" is the result of looking up address 0 in the symbol table. It cannot find a symbolic name, so it prints a default "??"
Unfortunately right offhand I don't know why it could not extract the correct retur... | Something you did cause the threading library to crash. Since the threading library itself is not compiled with debugging symbols (-g), it cannot display the source code file or line number the crash happened on. In addition, since it's threads, the call stack does not point back to your file. Unfortunately this will b... | What does the GDB backtrace message "0x0000000000000000 in ?? ()" mean? | [
"",
"c++",
"gdb",
"pthreads",
"fastcgi",
"freebsd",
""
] |
Does someone know if it is possible to modify the JVM settings at runtime (e.g. -dname=value)?
I need this little trick to run my Java stored procedure (oracle 10g). | Assuming you mean system properties (-D...; -d picks data model) System.setProperty(...) may do what you want. | You can use the OracleRuntime class inside your java stored procedure.
```
int times = 2;
OracleRuntime.setMaxRunspaceSize(times *OracleRuntime.getMaxRunspaceSize());
OracleRuntime.setSessionGCThreshold(times *OracleRuntime.getSessionGCThreshold());
OracleRuntime.setNewspaceSize(times *OracleRuntime.getNewspace... | Modifying JVM parameters at runtime | [
"",
"java",
""
] |
I have a paradox table from a legacy system I need to run a single query on. The field names have spaces in them - i.e. "Street 1". When I try and formulate a query in delphi for only the "Street 1" field, I get an error - Invalid use of keyword. Token: 1, Line Number: 1
Delphi V7 - object pascal, standard Tquery obje... | You need to prefix the string with the table name in the query.
For example: field name is 'Street 1', table is called customers the select is:
```
SELECT customers."Street 1" FROM customers WHERE ...
``` | You normally need to quote the field name in this case. For example:
select \* from t1 where "street 1" = 'test';
I tried this on a paradox 7 table and it worked. If that doesn't help, can you post the query you are trying to use? It would be easier to help with that info. | Delphi: Paradox DB Field Name Issue (Spaces in field name) | [
"",
"sql",
"delphi",
"paradox",
"tquery",
""
] |
Some files in our repository are individual to each developer. For example some developers use a local database, which is configured in a properties file in the project. So each developer has different settings. When one developer commits, he always has to take care to not commit his individually configured files.
How... | Our properties files are under a "properties" directory. Each developer has their own "username.properties" files which they can override properties in the environment-specific files such as "dev.properties", or "test.properties". This takes advantage of ANT's immutable properties (include personal first, THEN environm... | Keep a set of defaults in source control and then either:
* have each developer have an optional set of configs that they manage themselves (eg. not kept in source control) or
* have each developer keep their own configs in source control under some sort of identification scheme (username.properties like @Dustin uses)... | How do you handle developer individual files under version control? | [
"",
"java",
"version-control",
""
] |
C# question (.net 3.5). I have a class, ImageData, that has a field ushort[,] pixels. I am dealing with proprietary image formats. The ImageData class takes a file location in the constructor, then switches on file extension to determine how to decode. In several of the image files, there is a "bit depth" field in the ... | To boil down your problem, you want to be able to have a class that has a **ushort[,] pixels** field (16-bits per pixel) sometimes and a **uint32[,] pixels** field (32-bits per pixel) some other times. There are a couple different ways to achieve this.
You could create replacements for ushort / uint32 by making a Pixe... | I would say not to do that work in the construtor - A constructor should not do so much work, in my opinion. Use a factory method that reads the file to determine the bit depth, then have it construct the correct generic variant of the class and return it. | C# 'generic' type problem | [
"",
"c#",
"generics",
"image",
""
] |
Maybe I'm just thinking about this too hard, but I'm having a problem figuring out what escaping to use on a string in some JavaScript code inside a link's onClick handler. Example:
```
<a href="#" onclick="SelectSurveyItem('<%itemid%>', '<%itemname%>'); return false;">Select</a>
```
The `<%itemid%>` and `<%itemname%... | In JavaScript you can encode single quotes as "\x27" and double quotes as "\x22". Therefore, with this method you can, once you're inside the (double or single) quotes of a JavaScript string literal, use the \x27 \x22 with impunity without fear of any embedded quotes "breaking out" of your string.
\xXX is for chars < ... | Depending on the server-side language, you could use one of these:
.NET 4.0
```
string result = System.Web.HttpUtility.JavaScriptStringEncode("jsString")
```
Java
```
import org.apache.commons.lang.StringEscapeUtils;
...
String result = StringEscapeUtils.escapeJavaScript(jsString);
```
Python
```
import json
res... | How do I escape a string inside JavaScript code inside an onClick handler? | [
"",
"javascript",
"html",
"string",
"escaping",
""
] |
What is the best available tool to monitor the memory usage of my C#/.Net windows service over a long period of time. As far as I know, tools like perfmon can monitor the memory usage over a short period of time, but not graphically over a long period of time. I need trend data over days, not seconds.
To be clear, I w... | Perfmon in my opinion is one of the best tools to do this but make sure you properly configure the sampling interval according to the time you wish to monitor.
For example if you want to monitor a process:
* for 1 hour : I would use 1 second intervals (this will generate 60\*60 samples)
* for 1 day : I would use 30 s... | Well I used perfmon, exported the results to a csv and used excel for statistics afterwards. That worked pretty well last time I needed to monitor a process | What's the best tool to track a process's memory usage over a long period of time in Windows? | [
"",
"c#",
".net",
"performance",
"memory",
""
] |
Can anyone recommend a library for chart generation (bar charts, pie charts etc.) which runs on both Java and .Net? | [ChartDirector](http://www.advsofteng.com/) is fantastic and supports more than just Java and .NET. | Have you looking into using **[JFreeChart](http://www.jfree.org/jfreechart/).** I have used it on a few Java projects and its very configurable. Its free but I think you can purchase the developers guide for $50. Its good for quick simple charts too. However performance for real-time data is not quite up to par (Check ... | Charting library for Java and .Net | [
"",
"java",
".net",
"charts",
""
] |
How do I convert between big-endian and little-endian values in C++?
For clarity, I have to translate binary data (double-precision floating point values and 32-bit and 64-bit integers) from one CPU architecture to another. This doesn't involve networking, so ntoh() and similar functions won't work here.
---
Note: T... | If you're using **Visual C++** do the following: You include intrin.h and call the following functions:
For 16 bit numbers:
```
unsigned short _byteswap_ushort(unsigned short value);
```
For 32 bit numbers:
```
unsigned long _byteswap_ulong(unsigned long value);
```
For 64 bit numbers:
```
unsigned __int64 _bytes... | Simply put:
```
#include <climits>
template <typename T>
T swap_endian(T u)
{
static_assert (CHAR_BIT == 8, "CHAR_BIT != 8");
union
{
T u;
unsigned char u8[sizeof(T)];
} source, dest;
source.u = u;
for (size_t k = 0; k < sizeof(T); k++)
dest.u8[k] = source.u8[sizeof(... | How do I convert between big-endian and little-endian values in C++? | [
"",
"c++",
"endianness",
""
] |
I have a .net (3.5) WinForms application and want to display some html on one of the forms. Is there a control that I can use for this? | Yep sure is, the WebBrowser control. | I was looking at the WebBrowser control but couldn't work out how to assign (set) the HTML to it...?
EDIT: Found it - Document Text | Is there a control for a .Net WinForm app that will display HTML | [
"",
"c#",
".net",
"winforms",
""
] |
Being vaguely familiar with the Java world I was googling for a static analysis tool that would also was intelligent enough to fix the issues it finds. I ran at CodePro tool but, again, I'm new to the Java community and don't know the vendors.
What tool can you recommend based on the criteria above? | FindBugs, PMD and Checkstyle are all excellent choices especially if you integrate them into your build process.
At my last company we also used [Fortify](http://www.fortify.com) to check for potential security problems. We were fortunate to have an enterprise license so I don't know the cost involved. | * [Findbugs](http://findbugs.sourceforge.net/)
* [PMD](http://pmd.sourceforge.net)
* [Checkstyle](http://checkstyle.sourceforge.net)
* [Lint4J](http://www.jutils.com)
* [Classycle](http://classycle.sourceforge.net)
* [JDepend](http://sourceforge.net/projects/jdepends)
* [SISSy](http://sissy.sourceforge.net)
* [Google C... | Static Analysis tool recommendation for Java? | [
"",
"java",
"static-analysis",
""
] |
This is not a new topic, but I am curious how everyone is handling either `.js` or `.css` that is browser specific.
Do you have `.js` functions that have `if/else` conditions in them or do you have separate files for each browser?
Is this really an issue these days with the current versions of each of the popular bro... | It's a very real issue. Mostly just because of IE6. You can handle IE6-specific CSS by using [conditional comments](http://msdn.microsoft.com/en-us/library/ms537512.aspx).
For JavaScript, I'd recommend using a library that has already done most of the work of abstracting away browser differences. jQuery is really good... | Don't write them?
Honestly, browser specific CSS is not really necessary for most layouts - if it is, consider changing the layout. What happens when the next browser comes out that needs another variation? Yuck. If you have something that you really need to include, and it doesn't seem to be working in one browser, a... | How do you handle browser specific .js and .css | [
"",
"javascript",
"css",
""
] |
If you have a JSF `<h:commandLink>` (which uses the `onclick` event of an `<a>` to submit the current form), how do you execute JavaScript (such as asking for delete confirmation) prior to the action being performed? | ```
<h:commandLink id="myCommandLink" action="#{myPageCode.doDelete}">
<h:outputText value="#{msgs.deleteText}" />
</h:commandLink>
<script type="text/javascript">
if (document.getElementById) {
var commandLink = document.getElementById('<c:out value="${myPageCode.myCommandLinkClientId}" />');
if (commandLi... | Can be simplified like this
```
onclick="return confirm('Are you sure?');"
``` | How can I execute Javascript before a JSF <h:commandLink> action is performed? | [
"",
"javascript",
"jsf",
""
] |
I have a string that is like below.
```
,liger, unicorn, snipe
```
in other languages I'm familiar with I can just do a string.trim(",") but how can I do that in c#?
Thanks.
---
*There's been a lot of back and forth about the StartTrim function. As several have pointed out, the StartTrim doesn't affect the primary... | ```
string sample = ",liger, unicorn, snipe";
sample = sample.TrimStart(','); // to remove just the first comma
```
Or perhaps:
```
sample = sample.Trim().TrimStart(','); // to remove any whitespace and then the first comma
``` | ```
string s = ",liger, unicorn, snipe";
s.TrimStart(',');
``` | How can I Trim the leading comma in my string | [
"",
"c#",
".net",
"string",
"trim",
""
] |
Why is it not a good idea to use SOAP for communicating with the front end? For example, a web browser using JavaScript. | * Because it's bloated
* Because JSON is natively understandable by the JavaScript
* Because XML isn't fast to manipulate with JavaScript. | Because SOAP reinvents a lot of the HTTP wheel in its quest for protocol-independence. What's the point if you *know* you're going to serve the response over HTTP anyway (since your client is a web browser)?
UPDATE: I second gizmo's (implied) suggestion of JSON. | Why is it not a good idea to use SOAP for communicating with the front end (ie web browser)? | [
"",
"javascript",
"soap",
""
] |
In Internet Explorer I can use the clipboardData object to access the clipboard. How can I do that in FireFox, Safari and/or Chrome? | There is now a way to easily do this in most modern browsers using
```
document.execCommand('copy');
```
This will copy currently selected text. You can select a textArea or input field using
```
document.getElementById('myText').select();
```
To invisibly copy text you can quickly generate a textArea, modify the t... | For security reasons, Firefox doesn't allow you to place text on the clipboard. However, there is a workaround available using Flash.
```
function copyIntoClipboard(text) {
var flashId = 'flashId-HKxmj5';
/* Replace this with your clipboard.swf location */
var clipboardSWF = 'http://appengine.bravo9.com/... | Copy / Put text on the clipboard with FireFox, Safari and Chrome | [
"",
"javascript",
"dom",
"clipboard",
""
] |
I got a comment to my answer on this thread:
[Malloc inside a function call appears to be getting freed on return?](https://stackoverflow.com/questions/105477)
In short I had code like this:
```
int * somefunc (void)
{
int * temp = (int*) malloc (sizeof (int));
temp[0] = 0;
return temp;
}
```
I got this comme... | It seems fitting I post an answer, since I left the comment :P
Basically, if you forget to include `stdlib.h` the compiler will assume `malloc` returns an `int`. Without casting, you will get a warning. With casting you won't.
So by casting you get nothing, and run the risk of suppressing legitimate warnings.
Much i... | This question is tagged both for C and C++, so it has at least two answers, IMHO:
# C
Ahem... Do whatever you want.
I believe the reason given above "If you don't include "stdlib" then you won't get a warning" is not a valid one because one should not rely on this kind of hacks to not forget to include an header.
T... | Needless pointer-casts in C | [
"",
"c++",
"c",
"pointers",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.