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
if fork(): exit(0)
umask(0)
setsid()
if fork(): exit(0)
stdout.flush()
stderr.flush()
si = file('/dev/null', 'r')
so = file('/dev/null', 'a+')
se = file('/dev/null', 'a+', 0)
dup2(si.fileno(), stdin.fileno())
dup2(so.fileno(), stdout.fileno())
dup2(se.fileno(), stderr.fileno())
```
If you need to stop that process again, it is required to know the pid, the usual solution to this is pidfiles. Do this if you need one
```
from os import getpid
outfile = open(pid_file, 'w')
outfile.write('%i' % getpid())
outfile.close()
```
For security reasons you might consider any of these after demonizing
```
from os import setuid, setgid, chdir
from pwd import getpwnam
from grp import getgrnam
setuid(getpwnam('someuser').pw_uid)
setgid(getgrnam('somegroup').gr_gid)
chdir('/')
```
You could also use [nohup](http://en.wikipedia.org/wiki/Nohup) but that does not work well with [python's subprocess module](http://docs.python.org/lib/module-subprocess.html)
|
[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 I have another event listener, mouse\_move that sets the stageLeave boolean to false (when true) and dispatches a custom STAGE\_RETURN event.
The only sidenote here is that you'll have to move with the mouse over the stage to make the video play again. But that's something you will do anyway.
|
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" so it doesn't cut the mustard.
|
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;
Type underlyingType = Enum.GetUnderlyingType(task.GetType());
object value = Convert.ChangeType(task, underlyingType); // x will be int
}
```
|
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 sleeps. You can also test this with a simple python program:
```
import time
from threading import Thread
class worker(Thread):
def run(self):
for x in xrange(0,11):
print x
time.sleep(1)
class waiter(Thread):
def run(self):
for x in xrange(100,103):
print x
time.sleep(5)
def run():
worker().start()
waiter().start()
```
Which will print:
```
>>> thread_test.run()
0
100
>>> 1
2
3
4
5
101
6
7
8
9
10
102
```
|
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 understand the confusion!
|
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 provides but I ran into some cross-browser issues with them.
|
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"><td>3</td><td>Name1</td><td>Details3</td></tr>
<tr id="4"><td>4</td><td>Name1</td><td>Details4</td></tr>
</tbody>
</table>
```
and then in the javascript
```
$('.sort').sortable({
cursor: 'move',
axis: 'y',
update: function(e, ui) {
href = '/myReorderFunctionURL/';
$(this).sortable("refresh");
sorted = $(this).sortable("serialize", 'id');
$.ajax({
type: 'POST',
url: href,
data: sorted,
success: function(msg) {
//do something with the sorted data
}
});
}
});
```
This POSTs a serialized version of the items' IDs to the URL given. This function (PHP in my case) then updates the items' orders in the database.
|
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 guys posts but those are mainly using RSA and in my understanding RSA is generally suitable for encrypting the communication data (with private-public key pair). My need is different, I just want to store the data and retrieve it back by decrypting it. Therefore I don't need any private-public key pairs.
Please let me know if you have any idea about this.
|
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/technicalArticles/Security/AES/AES_v1.html) encryption in Java.
From Wikipedia...
> ... the Advanced
> Encryption Standard (AES), also known
> as Rijndael, is a block cipher adopted
> as an encryption standard by the U.S.
> government. It has been analyzed
> extensively and is now used worldwide,
> as was the case with its
> predecessor, the Data Encryption
> Standard (DES)...
So as a rule of thumb you are not supposed to use DES or its variants because it is being phased out.
As of now, it is better to use AES. There are other options like [Twofish](http://en.wikipedia.org/wiki/Twofish), [Blowfish](http://en.wikipedia.org/wiki/Blowfish_(cipher)) etc also. Note that Twofish can be considered as an advanced version of Blowfish.
|
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(city); // New York
console.log(state); // NY
console.log(zip); // 12345
```
You may have extra items in the input string. In this case, you can use rest operator to get an array for the rest or just ignore them:
```
const input = 'john smith~123 Street~Apt 4~New York~NY~12345';
const [name, street, ...others] = input.split('~');
console.log(name); // john smith
console.log(street); // 123 Street
console.log(others); // ["Apt 4", "New York", "NY", "12345"]
```
I supposed a read-only reference for values and used the `const` declaration.
**Enjoy ES6!**
|
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:
> "Cannot modify the design of table
> 'test$'. It is in a read-only
> database."
My connection seems fine and I can select data fine but I can't seem to insert data into the excel file, does anyone know how I get read/write access to the excel file via OLEDB?
|
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-modifying commands (like `CREATE TABLE` or `DROP TABLE`) don't work.
My working connection string is:
```
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=workbook.xls;Mode=ReadWrite;Extended Properties=\"Excel 8.0;HDR=Yes;\";"
```
|
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 configuration
as well as other differences you can see by clicking on the "Advanced" button
But you can:
* Change the build settings for Debug and Release configurations in Project Propeties / Build
* Create your own custom configurations by right-clicking on the solution in Solution Explorer and selecting Configuration Manager
I think the behaviour of the DEBUG constant is fairly clear (can be referenced in the #if preprocessor directive or in the ConditionalAttribute). But I'm not aware of any comprehensive documentation on exactly what optimizations are enabled - in fact I suspect Microsoft would want to be free to enhance their optimizer without notice
|
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.Groups[1]);
}
}
```
|
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 [CERN Colt library](http://acs.lbl.gov/~hoschek/colt/) is within 90% of compiled, optimised Fortran for numerical work.
If you are worried about speed I'd really recommend a good profiler and get evidence as to where your bottlenecks are - I use [YourKit](http://www.yourkit.com/) and have been very pleased.
We have only resorted to native compiled code for speed in one instance in the last few years, and that was so we could use [CUDA](http://www.nvidia.com/object/cuda_home.html#) and get some serious GPU performance.
|
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(false, "Global\\" + appGuid))
{
if(!mutex.WaitOne(0, false))
{
MessageBox.Show("Instance already running");
return;
}
Application.Run(new Form1());
}
}
private static string appGuid = "c0a76b5a-12ab-45c5-b9d9-d693faa6e7b9";
```
|
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))
{
//there is already another instance running!
Application.Exit();
}
}
}
```
|
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 the custom div, you should also use JavaScript to create it, and to set the display:none style on the button. This way users with JavaScript disabled will still see the submit button and can click on it.
---
It has been noted that display:none will cause IE to ignore the input. I created a [new JSFiddle example](http://jsfiddle.net/Suyw6/1/) that starts as a standard form, and uses progressive enhancement to hide the submit and create the new div. I did use the CSS styling from [StriplingWarrior](https://stackoverflow.com/questions/29943/how-to-submit-a-form-when-the-return-key-is-pressed/6602788#6602788).
|
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)"/>`
This is also the default behaviour of Internet Explorer 7 anyway though (probably earlier versions as well).
|
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 the correct method name to call,
> calling your specified callback. Or,
> if you set the dataType to "jsonp" a
> callback will be automatically added
> to your Ajax request.
Alternatively you could make your ajax request to a server-side script which does the cross-domain call for you, then passes the data back to your script
|
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.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
} catch (e) {
alert("Sorry, browser security settings won't let this program run.");
return;
}
```
(from the RESTful web services book) But, this only works in firefox, when the html file is loaded from local file. So, not that useful.
|
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 function properly without the browser having JS enabled.
Eventually I would want to redirect them to content that is able to work in the absence of JS, but I need this detection as a placeholder to start.
|
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’s the Difference?'") detection, rather than using the [`<noscript>`](https://www.w3.org/TR/html52/semantics-scripting.html#the-noscript-element "WC3 Recommendation: The <noscript> element (HTML 5.2)") element for an unexplained reason.
There is no good way to perform server-side JavaScript detection. As an alternative it is possible to [set a cookie using JavaScript](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie "MDN: Document.cookie"), and then test for that cookie using server-side scripting upon subsequent page views. However this would be unsuitable for deciding what content to deliver, as it would not distinguish visitors without the cookie from new visitors or from visitors who did not accept the JavaScript set cookie.
|
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 started down that road, then you start realizing that the site should be bulletproof with JS turned off, and that's a whole big chunk of additional work.
So, what you really want is a "redirection" to a page that says "turn on JS, silly". But, of course, you can't reliably do meta redirections. So, here's the suggestion:
```
<noscript>
<style type="text/css">
.pagecontainer {display:none;}
</style>
<div class="noscriptmsg">
You don't have javascript enabled. Good luck with that.
</div>
</noscript>
```
...where *all* of the content in your site is wrapped with a div of class "pagecontainer". The CSS inside the noscript tag will then hide all of your page content, and instead display whatever "no JS" message you want to show. This is actually what Gmail appears to do...and if it's good enough for Google, it's good enough for my little site.
|
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! Credentials required
I got the credentials, but how do I pass them to JMXQuery?
/Ace
|
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
> found on nagiosexchange. It lacked a
> username/password/role system. \* \*
> @author unknown \* @author Ryan
> Gravener (ryangravener@gmail.com) \*
> \*/
Does that mean that there's no way to remotely access JMX with original JMXQuery? If so, what *can* you do with it?
|
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 easy way to get **all** items (main item + derived items) from a calendar?
In my specific situation it can be possible to set a date limit but it would be cool just to get all items (my recurring items are time limited themselves).
**I'm using the Microsoft Outlook 12 Object library (Microsoft.Office.Interop.Outlook)**.
|
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.Interop.Outlook.MAPIFolder CalendarFolder = null;
Microsoft.Office.Interop.Outlook.Items outlookCalendarItems = null;
oApp = new Microsoft.Office.Interop.Outlook.Application();
mapiNamespace = oApp.GetNamespace("MAPI"); ;
CalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);
outlookCalendarItems = CalendarFolder.Items;
outlookCalendarItems.IncludeRecurrences = true;
foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems)
{
if (item.IsRecurring)
{
Microsoft.Office.Interop.Outlook.RecurrencePattern rp = item.GetRecurrencePattern();
DateTime first = new DateTime(2008, 8, 31, item.Start.Hour, item.Start.Minute, 0);
DateTime last = new DateTime(2008, 10, 1);
Microsoft.Office.Interop.Outlook.AppointmentItem recur = null;
for (DateTime cur = first; cur <= last; cur = cur.AddDays(1))
{
try
{
recur = rp.GetOccurrence(cur);
MessageBox.Show(recur.Subject + " -> " + cur.ToLongDateString());
}
catch
{ }
}
}
else
{
MessageBox.Show(item.Subject + " -> " + item.Start.ToLongDateString());
}
}
}
```
|
.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 there a way to do this simply using classical tools such as JUnit, or preferrably TestNG? Did I need to embed a tomcat server or something like that?
|
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)
* [HtmlUnit](http://htmlunit.sourceforge.net/) (higher level than HttpUnit, which is better for many projects)
* [JWebUnit](http://jwebunit.sourceforge.net/) (sits on top of other testing tools and tries to simplify them - the one I prefer)
* [WatiJ](http://watij.com/) and Selenium (use your browser to do the testing, which is more heavyweight but realistic)
This is a JWebUnit test for a simple Order Processing Servlet which processes input from the form 'orderEntry.html'. It expects a customer id, a customer name and one or more order items:
```
public class OrdersPageTest {
private static final String WEBSITE_URL = "http://localhost:8080/demo1";
@Before
public void start() {
webTester = new WebTester();
webTester.setTestingEngineKey(TestingEngineRegistry.TESTING_ENGINE_HTMLUNIT);
webTester.getTestContext().setBaseUrl(WEBSITE_URL);
}
@Test
public void sanity() throws Exception {
webTester.beginAt("/orderEntry.html");
webTester.assertTitleEquals("Order Entry Form");
}
@Test
public void idIsRequired() throws Exception {
webTester.beginAt("/orderEntry.html");
webTester.submit();
webTester.assertTextPresent("ID Missing!");
}
@Test
public void nameIsRequired() throws Exception {
webTester.beginAt("/orderEntry.html");
webTester.setTextField("id","AB12");
webTester.submit();
webTester.assertTextPresent("Name Missing!");
}
@Test
public void validOrderSucceeds() throws Exception {
webTester.beginAt("/orderEntry.html");
webTester.setTextField("id","AB12");
webTester.setTextField("name","Joe Bloggs");
//fill in order line one
webTester.setTextField("lineOneItemNumber", "AA");
webTester.setTextField("lineOneQuantity", "12");
webTester.setTextField("lineOneUnitPrice", "3.4");
//fill in order line two
webTester.setTextField("lineTwoItemNumber", "BB");
webTester.setTextField("lineTwoQuantity", "14");
webTester.setTextField("lineTwoUnitPrice", "5.6");
webTester.submit();
webTester.assertTextPresent("Total: 119.20");
}
private WebTester webTester;
}
```
|
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 the spinner arrow) while the first thread is working, I would like to abort the first thread (and the update of the 3D view) and launch a new one with the latest parameter value.
How can I do something like that?
PS: There is no loop in the `run()` method of my thread, so checking for a flag is not an option: the thread updating the 3D view basically only calls a single method that is very long to execute. I can't add any flag in this method asking to abort either as I do not have access to its code.
|
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 non-interruptible event and just let it run through to conclusion, checking afterward if there's a new latest update to perform. This might make the GUI a little choppy to users, as they would be able to make five changes, then see the graphical results from how things were five changes ago, then see the result of their latest change. But depending on how long this process is, it might be tolerable, and it would avoid having to kill the thread. Design might look like this:
```
boolean stopFlag = false;
Object[] latestArgs = null;
public void run() {
while (!stopFlag) {
if (latestArgs != null) {
Object[] args = latestArgs;
latestArgs = null;
perform3dUpdate(args);
} else {
Thread.sleep(500);
}
}
}
public void endThread() {
stopFlag = true;
}
public void updateSettings(Object[] args) {
latestArgs = args;
}
```
|
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 `run` method.
If you truly cannot access the code the Thread is running to have it check a flag, then there is no safe way to stop the Thread. Does this Thread ever terminate normally before your application completes? If so, what causes it to stop?
If it runs for some long period of time, and you simply must end it, you can consider using the deprecated `Thread.stop()` method. However, it was deprecated for a good reason. If that Thread is stopped while in the middle of some operation that leaves something in an inconsistent state or some resource not cleaned up properly, then you could be in trouble. Here's a note from the [documentation](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#stop()):
> This method is inherently unsafe.
> Stopping a thread with Thread.stop
> causes it to unlock all of the
> monitors that it has locked (as a
> natural consequence of the unchecked
> ThreadDeath exception propagating up
> the stack). If any of the objects
> previously protected by these monitors
> were in an inconsistent state, the
> damaged objects become visible to
> other threads, potentially resulting
> in arbitrary behavior. Many uses of
> stop should be replaced by code that
> simply modifies some variable to
> indicate that the target thread should
> stop running. The target thread should
> check this variable regularly, and
> return from its run method in an
> orderly fashion if the variable
> indicates that it is to stop running.
> If the target thread waits for long
> periods (on a condition variable, for
> example), the interrupt method should
> be used to interrupt the wait. For
> more information, see [Why are
> Thread.stop, Thread.suspend and
> Thread.resume Deprecated?](http://java.sun.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html)
|
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.prototype.curry = function() {
if (!arguments.length) return this;
var args = Array.prototype.slice.apply(arguments);
var mmm_curry = this, args;
return function() {
var inner_args = Array.prototype.slice.apply(arguments);
return mmm_curry.apply(this, args.concat(inner_args));
}
}
```
Which is used as follows:
```
var vindaloo = function(a, b) {
return (a + b);
}
var karahi = vindaloo.curry(1);
var masala = karahi(2);
var gulai = karahi(3);
print(masala);
print(other);
```
The output of which is as follows in Spidermonkey:
```
$ js curry.js
3
4
```
His opinion was that since the Javascript `function` primitive does not natively support "partial function application", it's completely wrong to refer to the function bound to the variable `karahi` as partially applied. His argument was that when the `vindaloo` function is curried, the function itself is completely applied and a closure is returned, not a "partially applied function".
Now, my opinion is that while Javascript itself does not provide support for partial application in its' `function` primitives (unlike say, ML or Haskell), that doesn't mean you can't create a higher order function of the language which is capable of encapsulating concept of a partially applied function. Also, despite being "applied", the scope of the function is still bound to the closure returned by it causing it to remain "partially applied".
Which is correct?
|
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) {
return function(b) {
return a + b;
};
};
```
IIUC, this still wouldn't be a partially applied function. But it's closer. A true partially applied function would actually look like this if you can examine the code:
```
function karahi(b) {
return 1 + b;
};
```
So, technically, your original method *is* just returning a function bound within a closure. The only way I can think of to truly partially apply a function in JavaScript would be to parse the function, apply the changes, and then run it through an eval().
However, your solution is a good practical application of the concept to JavaScript, so practically speaking accomplishes the goal, even if it is not technically exact.
|
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 ECMAScript spec,
but when IE would then implement it just as you did, you would have
no way to find out.
|
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) that C++ classes only worked with MFC .dlls and not plain ones, but that's just the windows side.
|
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/drepper/dsohowto.pdf>
The main things to remember are to use the `-fPIC` option when compiling, and the `-shared` option when linking. You can find plenty of examples on the net.
|
# 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::Cat(const string & name):_name(name){}
void Cat::speak()
{
cout << "Meow! I'm " << _name << endl;
}
```
*main.cpp* :
```
#include <iostream>
#include <string>
#include "cat.hh"
using std::cout;using std::endl;using std::string;
int main()
{
string name = "Felix";
cout<< "Meet my cat, " << name << "!" <<endl;
Cat kitty(name);
kitty.speak();
return 0;
}
```
## Compilation
You compile the shared lib first:
```
$ g++ -Wall -g -fPIC -c cat.cpp
$ g++ -shared -Wl,-soname,libcat.so.1 -o libcat.so.1 cat.o
```
Then compile the main executable or C++ program using the classes in the libraries:
```
$ g++ -Wall -g -c main.cpp
$ g++ -Wall -Wl,-rpath,. -o main main.o libcat.so.1 # -rpath linker option prevents the need to use LD_LIBRARY_PATH when testing
$ ./main
Meet my cat, Felix!
Meow! I'm Felix
$
```
|
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 like :
```
"1","","2","","sometimes with comma , inside", ""
```
Can I somehow bulk import them and tell SQL to use the quotes as field delimiters?
**Edit**: The problem with using '","' as delimiter, as in the examples suggested is that :
What most examples do, is they import the data including the first " in the first column and the last " in the last, then they go ahead and strip that out. Alas my first (and last) column are datetime and will not allow a "20080902 to be imported as datetime.
From what I've been reading arround I think FORMATFILE is the way to go, but documentation (including MSDN) is terribly unhelpfull.
|
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 to load the class definitions for those objects before starting the session on the next page. Using [autoload](http://docs.php.net/manual/en/language.oop5.autoload.php) can help you out here.
You must [start a session](http://docs.php.net/manual/en/function.session-start.php) before you can use $\_SESSION. Since starting the session sends headers, you can't have any output before. This can be solved in one of two ways:
Either you always begin the session at the start of your script. Or you [buffer all output](http://docs.php.net/manual/en/book.outcontrol.php), and send it out at the end of the script.
> One good idea is to regenerate the session on each request. this makes hijack much less likely.
That's (slightly) bad advice, since it can make the site inaccessible. You should [regenerate the session-id](http://docs.php.net/manual/en/function.session-regenerate-id.php) whenever a users privileges changes though. In general that means, whenever they log in. This is to prevent session-fixation (A form of session-hijacking). See [this recent thread @ Sitepoint](http://www.sitepoint.com/forums/showthread.php?t=571084) for more on the subject.
Using cookiebased sessions *only* is OK, but if you regenerate session id's on login, it doesn't add any additional security, and it lowers accessibility a bit.
|
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?
```
void api_func(const double matrix[4][4]);
// ...
{
typedef double Matrix[4][4];
double* array1 = new double[16];
double array2[16];
// ...
api_func(reinterpret_cast<Matrix&>(array1));
api_func(reinterpret_cast<Matrix&>(array2));
}
```
|
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 underlying representation.
I.e., given
```
sizeof(double[4]) = 4*sizeof(double)
```
and
```
sizeof(double[4][4]) = 4*sizeof(double[4])
```
then we have
```
sizeof(double[4][4]) = 4*4*sizeof(double) = 16*sizeof(double) = sizeof(double[16])
```
I think a standards-compliant compiler would have to implement these the same, and I think that this isn't something that a compiler would accidentally break. The standard way of implementing multi-dimensional arrays works as expected. Breaking the standard would require extra work, for likely no benefit.
The C++ standard also states that an array consists of contiguously-allocated elements, which eliminates the possibility of doing anything strange using pointers and padding.
|
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/javascript">
alert(document.getElementById("request-method").content);
</script>
```
|
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 getting recently modified files in a directory?
It would check for modifications only when the user asks it to, it will not be a constantly running service.
|
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 time the user requests. I'd probably go with a FileSystemWatcher and just store off your results anyhow.
|
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 specifies which are the events to be monitored
watcher.NotifyFilter = NotifyFilters.LastAccess |
NotifyFilters.LastWrite | NotifyFilters.FileName | notifyFilters.DirectoryName;
watcher.Filter = "*.*"; // Only watch text files.
// Add event handlers for specific change events...
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
}
```
|
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 { ret = factorial< n - 1 >::ret * n }; };
template<>
struct factorial< 0 > { enum { ret = 1 }; };
int main() {
cout << "7! = " << factorial< 7 >::ret << endl; // 5040
return 0;
}
```
If one wants to learn more about C++ static metaprogramming, what are the best sources (books, websites, on-line courseware, whatever)?
|
*[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 Guide* by David Vandevoorder and Nicolai M. Josuttis, ISBN-13: 9780201734843.
   
Todd Veldhuizen has an excellent tutorial [here](http://www.cs.rpi.edu/~musser/design/blitz/meta-art.html).
A good resource for C++ programming in general is *Modern C++ Design* by Andrei Alexandrescu, ISBN-13: 9780201704310. This book mixes a bit of metaprogramming with other template techniques. For metaprogramming in particular, see sections 2.1 "Compile-Time Assertions", 2.4 "Mapping Integral Constants to Types", 2.6 "Type Selection", 2.7 "Detecting Convertibility and Inheritance at Compile Time", 2.9 "`NullType` and `EmptyType`" and 2.10 "Type Traits".
The best intermediate/advanced resource I've found is *C++ Template Metaprogramming* by David Abrahams and Aleksey Gurtovoy, ISBN-13: 9780321227256
If you'd prefer just one book, get *C++ Templates: The Complete Guide* since it is also the definitive reference for templates in general.
|
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, which heavily use these techniques and are usually of very high quality to learn from (although some are quite dense).
|
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 unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit. If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than `0xFFFF`) then the code unit returned will be the first part of a surrogate pair for the code point. If you want the entire code point value, use `codePointAt()`.
If you need to support non-BMP Unicode characters like U+1F602 , then don't use `charCodeAt`, as it will not return 128514 (or 0x1f602 in hexadecimal), it will give a result you don't expect:
```
console.log("\u{1f602}".charCodeAt(0));
// prints 55357 , which is 0xd83d in hexadecimal
```
|
[`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/Reference/Global_Objects/String/fromCharCode) that convert numbers to equal ASCII character. This function can accept multiple numbers and join all the characters then return the string. Example:
```
String.fromCharCode(65,66,67); // returns 'ABC'
```
Here is a quick ASCII characters reference:
```
{
"31": "", "32": " ", "33": "!", "34": "\"", "35": "#",
"36": "$", "37": "%", "38": "&", "39": "'", "40": "(",
"41": ")", "42": "*", "43": "+", "44": ",", "45": "-",
"46": ".", "47": "/", "48": "0", "49": "1", "50": "2",
"51": "3", "52": "4", "53": "5", "54": "6", "55": "7",
"56": "8", "57": "9", "58": ":", "59": ";", "60": "<",
"61": "=", "62": ">", "63": "?", "64": "@", "65": "A",
"66": "B", "67": "C", "68": "D", "69": "E", "70": "F",
"71": "G", "72": "H", "73": "I", "74": "J", "75": "K",
"76": "L", "77": "M", "78": "N", "79": "O", "80": "P",
"81": "Q", "82": "R", "83": "S", "84": "T", "85": "U",
"86": "V", "87": "W", "88": "X", "89": "Y", "90": "Z",
"91": "[", "92": "\\", "93": "]", "94": "^", "95": "_",
"96": "`", "97": "a", "98": "b", "99": "c", "100": "d",
"101": "e", "102": "f", "103": "g", "104": "h", "105": "i",
"106": "j", "107": "k", "108": "l", "109": "m", "110": "n",
"111": "o", "112": "p", "113": "q", "114": "r", "115": "s",
"116": "t", "117": "u", "118": "v", "119": "w", "120": "x",
"121": "y", "122": "z", "123": "{", "124": "|", "125": "}",
"126": "~", "127": ""
}
```
|
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 this a compiler-specific thing (visual C++)? Or is this doing something wrong?
|
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 controls; those are determined by system settings. So if you want the "Copy/Cut/Paste/etc." menu with a custom font size for a WinForms `TextBox`, you'll have to create a `ContextMenuStrip` with the appropriate font size and assign it to the `TextBox`'s *ContextMenuStrip* property.
|
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
INNER JOIN 4e_magic_item_levels
ON 4e_magic_items.id = 4e_magic_item_levels.itemid
INNER JOIN 4e_monster_sources
ON 4e_magic_items.source = 4e_monster_sources.id
WHERE (itemlevel BETWEEN 1 AND 30)
AND source!=16 AND source!=2 AND source!=5
AND source!=13 AND source!=15 AND source!=3
AND source!=4 AND source!=12 AND source!=7
AND source!=14 AND source!=11 AND source!=10
AND source!=8 AND source!=1 AND source!=6
AND source!=9 AND type!='Arms' AND type!='Feet'
AND type!='Hands' AND type!='Head'
AND type!='Neck' AND type!='Orb'
AND type!='Potion' AND type!='Ring'
AND type!='Rod' AND type!='Staff'
AND type!='Symbol' AND type!='Waist'
AND type!='Wand' AND type!='Wondrous Item'
AND type!='Alchemical Item' AND type!='Elixir'
AND type!='Reagent' AND type!='Whetstone'
AND type!='Other Consumable' AND type!='Companion'
AND type!='Mount' AND (type!='Armor' OR (false ))
AND (type!='Weapon' OR (false ))
ORDER BY type ASC, itemlevel ASC, name ASC
```
It seems to work well enough, but it's also not particularly high traffic (a few hundred hits a day or so), and I wonder if it would be worth the effort to try and optimize the queries to remove redundancies and such.
|
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 that's hard to debug.
By the way, may I suggest a reformatted version? This is mostly to demonstrate the importance of formatting; I trust this will be easier to understand.
```
select *
from
4e_magic_items mi
,4e_magic_item_levels mil
,4e_monster_sources ms
where mi.id = mil.itemid
and mi.source = ms.id
and itemlevel between 1 and 30
and source not in(16,2,5,13,15,3,4,12,7,14,11,10,8,1,6,9)
and type not in(
'Arms' ,'Feet' ,'Hands' ,'Head' ,'Neck' ,'Orb' ,
'Potion' ,'Ring' ,'Rod' ,'Staff' ,'Symbol' ,'Waist' ,
'Wand' ,'Wondrous Item' ,'Alchemical Item' ,'Elixir' ,
'Reagent' ,'Whetstone' ,'Other Consumable' ,'Companion' ,
'Mount'
)
and ((type != 'Armor') or (false))
and ((type != 'Weapon') or (false))
order by
type asc
,itemlevel asc
,name asc
/*
Some thoughts:
==============
0 - Formatting really matters, in SQL even more than most languages.
1 - consider selecting only the columns you need, not "*"
2 - use of table aliases makes it short & clear ("MI", "MIL" in my example)
3 - joins in the WHERE clause will un-clutter your FROM clause
4 - use NOT IN for long lists
5 - logically, the last two lines can be added to the "type not in" section.
I'm not sure why you have the "or false", but I'll assume some good reason
and leave them here.
*/
```
|
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" limitation does not map directly to characters in a SQL statement. Surely you want to take into account character encoding within the client, some packet metadata, etc.)
|
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 members to their values.
Is there any way to prevent the initialization, or is there an STL-like container out there with resizeable contiguous storage and uninitialized elements?
(I'm certain that this part of the code needs to be optimized, and I'm certain that the initialization is a significant cost.)
Also, see my comments below for a clarification about when the initialization occurs.
SOME CODE:
```
void GetsCalledALot(int* data1, int* data2, int count) {
int mvSize = memberVector.size()
memberVector.resize(mvSize + count); // causes 0-initialization
for (int i = 0; i < count; ++i) {
memberVector[mvSize + i].d1 = data1[i];
memberVector[mvSize + i].d2 = data2[i];
}
}
```
|
`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 `push_back()`, so that the copy-constructor is used, avoiding default-construction.
Using your example code:
```
struct YourData {
int d1;
int d2;
YourData(int v1, int v2) : d1(v1), d2(v2) {}
};
std::vector<YourData> memberVector;
void GetsCalledALot(int* data1, int* data2, int count) {
int mvSize = memberVector.size();
// Does not initialize the extra elements
memberVector.reserve(mvSize + count);
// Note: consider using std::generate_n or std::copy instead of this loop.
for (int i = 0; i < count; ++i) {
// Copy construct using a temporary.
memberVector.push_back(YourData(data1[i], data2[i]));
}
}
```
The only problem with calling `reserve()` (or `resize()`) like this is that you may end up invoking the copy-constructor more often than you need to. If you can make a good prediction as to the final size of the array, it's better to `reserve()` the space once at the beginning. If you don't know the final size though, at least the number of copies will be minimal on average.
In the current version of C++, the inner loop is a bit inefficient as a temporary value is constructed on the stack, copy-constructed to the vectors memory, and finally the temporary is destroyed. However the next version of C++ has a feature called R-Value references (`T&&`) which will help.
The interface supplied by `std::vector` does not allow for another option, which is to use some factory-like class to construct values other than the default. Here is a rough example of what this pattern would look like implemented in C++:
```
template <typename T>
class my_vector_replacement {
// ...
template <typename F>
my_vector::push_back_using_factory(F factory) {
// ... check size of array, and resize if needed.
// Copy construct using placement new,
new(arrayData+end) T(factory())
end += sizeof(T);
}
char* arrayData;
size_t end; // Of initialized data in arrayData
};
// One of many possible implementations
struct MyFactory {
MyFactory(int* p1, int* p2) : d1(p1), d2(p2) {}
YourData operator()() const {
return YourData(*d1,*d2);
}
int* d1;
int* d2;
};
void GetsCalledALot(int* data1, int* data2, int count) {
// ... Still will need the same call to a reserve() type function.
// Note: consider using std::generate_n or std::copy instead of this loop.
for (int i = 0; i < count; ++i) {
// Copy construct using a factory
memberVector.push_back_using_factory(MyFactory(data1+i, data2+i));
}
}
```
Doing this does mean you have to create your own vector class. In this case it also complicates what should have been a simple example. But there may be times where using a factory function like this is better, for instance if the insert is conditional on some other value, and you would have to otherwise unconditionally construct some expensive temporary even if it wasn't actually needed.
|
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 _:
return 0 # 0 is the default case if x is not found
```
The `match`-`case` statement is considerably more powerful than this simple example.
---
If you need to support Python ≤ 3.9, use a dictionary instead:
```
def f(x):
return {
'a': 1,
'b': 2,
}[x]
```
|
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)),'') + 'SomeText' From NotesTable a
```
|
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 hierarchical method (although I am not sure of that order). The issue is that each style is applied as a "transparent" layer which just masks what it is applying. This is, I feel, a good idea as you can specifiy styles for the whole and then one-off them as needed. Unfortunately I can't tell from which layer the style actually came from.
I could solve this issue by explicitly expressing the style at all layers but that gets bulky and hard to manage and the page(s) works 80% of the time. I just need to figure out where that squirrelly 20% came from.
|
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 can learn more about it?
|
# 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-annotation-processing-api/). Static metaprogramming is (as you already stated in your question)
> compile-time program execution
If you know about metaprogramming, then you also know that this is not really true, but for the sake of simplicity, we will use this. Please look [here](https://stackoverflow.com/questions/514644/what-exactly-is-metaprogramming) if you want to learn more about metaprogramming in general.
The pluggable annotation processing api is called by the compiler, right after the .java files are read but before the compiler writes the byte-code to the .class files. (I had one source for this, but i cannot find it anymore.. maybe someone can help me out here?).
It allows you, to do logic at compile time with pure java-code. However, the world you are coding in is quite different. Not specifically bad or anything, just different. The classes you are analyzing do not yet exist and you are working on meta data of the classes. But the compiler is run in a JVM, which means you can also create classes and program normally. But furthermore, you can analyze generics, because our annotation processor is called **before** type erasure.
The main gist about static metaprogramming in java is, that you provide meta-data (in form of annotations) and the processor will be able to find all annotated classes to process them. On (more easy) example can be found on [Baeldung](https://www.baeldung.com/java-annotation-processing-builder), where an easy example is formed. In my opinion, this is quite a good source for getting started. If you understand this, try to google yourself. There are multiple good sources out there, to much to list here. Also take a look at [Google AutoService](https://github.com/google/auto/tree/master/service), which utilizes an annotation processor, to take away your hassle of creating and maintaining the service files. If you want to create classes, i recommend looking at [JavaPoet](https://github.com/square/javapoet).
Sadly though, this API does not allow us, to manipulate source code. But if you really want to, you should take a look at [Project Lombok](https://projectlombok.org/). They do it, but it is not supported.
---
# Why is this important (Further reading for the interested ones among you)
**TL;DR:** It is quite baffling to me, why we don't use static metaprogramming as much as dynamic, because it has many many advantages.
Most developers see "Dynamic and Static" and immediately jump to the conclusion that dynamic is better. Nothing wrong with that, static has a lot of negative connotations for developers. But in this case (and specifically for java) this is the exact other way around.
Dynamic metaprogramming requires reflections, which has [some](http://blog.icodejava.com/tag/drawbacks-of-java-reflections/) [major](https://medium.com/the-telegraph-engineering/mirror-gazing-a-closer-look-at-the-good-and-bad-sides-of-java-reflection-884f65a4ef20) [drawbacks](https://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-useful). There are quite a lot of them. In short: Performance, Security, and Design.
Static metaprogramming (i.e. Annotation Processing) allows us to intersect the compiler, which already does most of the things we try to accomplish with reflections. We can also create classes in this process, which are again passed to the annotation processors. You then can (for example) generate classes, which do what normally had to be done using reflections. Further more, we can implement a "fail fast" system, because we can inform the compiler about errors, warnings and such.
To conclude and compare as much as possible: let us imagine Spring. Spring tries to find all Component annotated classes at runtime (which we could simplify by using service files at compile time), then generates certain proxy classes (which we already could have done at compile time) and resolves bean dependencies (which, again, we already could have done at compile time). [Jake Whartons talk about Dagger2](https://www.youtube.com/watch?v=plK0zyRLIP8&feature=youtu.be), in which he explains why they switched to static metaprogramming. I still don't understand why the big players like Spring don't use it.
This post is to short to fully explain those differences and why static would be more powerful. If you want, i am currently working on a presentation for this. If you are interested and speak German (sorry about that), you can have a look at [my website](http://meta.thorbenkuck.de). There you find a presentation, which tries to explain the differences in 45 minutes. Only the slides though.
|
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 can be used for such trickery](https://stackoverflow.com/a/8387752/409102).
|
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 auto-test such methods.
Does any framework (e.g. jUnit) provide such a feature? e.g. An annotation that says "this test T should auto-test all the getters/setters on class C, because I assert that they are standard".
It seems to me that it would add value, and if it were configurable, the 'debate' would be left as an option to the user.
|
[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)
* Validate Pojo Identity (i.e. Use annotation based equality & hashcode generation)
[See Tutorial](https://github.com/OpenPojo/openpojo/wiki)
|
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: [Streaming APIs for XML parsers](http://java.sun.com/performance/reference/whitepapers/StAX-1_0.pdf)
|
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 array. The pointer points to the outer structure which points into something like a **wchar\_t** array, so there's some indirection with a C# string and wider characters for Unicode support.
|
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 achieved.
What approach do you use to test your web-services?
**Update:** As entzik pointed out, decoupling the web service from the business logic allows me to unit test the business logic. However, I also want to test for the correct HTTP status codes etc.
|
[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](http://svn.apache.org/viewvc/activemq/camel/trunk/components/camel-rest/src/test/java/org/apache/camel/rest/resources/)
|
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 very very very very very very very very very very very very very very long line.**|**
The cursor is on line number four, not two.
Can someone provide me with the implementation of the method:
```
int getLineNumber(JTextPane pane, int pos)
{
return ???
}
```
|
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.modelToView(pos);
y = (int) caretCoords.getY();
}
catch (BadLocationException ex)
{
}
int lineHeight = component.getFontMetrics(component.getFont()).getHeight();
posLine = (y / lineHeight) + 1;
return posLine;
}
```
|
<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 to have a common parent class, Invitation, that they both would inherit from. Unfortunately, they also have a lot in common with their current ancestors... TextMessage and EmailMessage. Classical desire for multiple inheritance here.
What's the most light-weight approach to solve the issue?
Thanks!
|
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 responsibility and use MessageDispatcher that sends the Message passed using text or html backend. I don't know your code, but let me simulate it this way:
```
$m = new Message();
$m->type = 'text/html';
$m->from = 'John Doe <jdoe@yahoo.com>';
$m->to = 'Random Hacker <rh@gmail.com>';
$m->subject = 'Invitation email';
$m->importBody('invitation.html');
$d = new MessageDispatcher();
$d->dispatch($m);
```
This way you can add some specialisation to Message class:
```
$htmlIM = new InvitationHTMLMessage(); // html type, subject and body configuration in constructor
$textIM = new InvitationTextMessage(); // text type, subject and body configuration in constructor
$d = new MessageDispatcher();
$d->dispatch($htmlIM);
$d->dispatch($textIM);
```
Note that MessageDispatcher would make a decision whether to send as HTML or plain text depending on `type` property in Message object passed.
```
// in MessageDispatcher class
public function dispatch(Message $m) {
if ($m->type == 'text/plain') {
$this->sendAsText($m);
} elseif ($m->type == 'text/html') {
$this->sendAsHTML($m);
} else {
throw new Exception("MIME type {$m->type} not supported");
}
}
```
To sum it up, responsibility is split between two classes. Message configuration is done in InvitationHTMLMessage/InvitationTextMessage class, and sending algorithm is delegated to dispatcher. This is called Strategy Pattern, you can read more on it [here](https://web.archive.org/web/20190613203216/https://www.dofactory.com/net/strategy-design-pattern).
|
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 about that.
|
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 within {} braces inside a HEREDOC string, but you have to go through a bit of work. The function name itself has to be stored in a variable, and you have to call it like it is a dynamically-named function. For example:
```
$fn = 'testfunction';
function testfunction() { return 'ok'; }
$string = <<< heredoc
plain text and now a function: {$fn()}
heredoc;
```
As you can see, this is a bit more messy than just:
```
$string = <<< heredoc
plain text and now a function: {testfunction()}
heredoc;
```
There are other ways besides the first code example, such as breaking out of the HEREDOC to call the function, or reversing the issue and doing something like:
```
?>
<!-- directly output html and only breaking into php for the function -->
plain text and now a function: <?PHP print testfunction(); ?>
```
The latter has the disadvantage that the output is directly put into the output stream (unless I'm using output buffering), which might not be what I want.
So, the essence of my question is: is there a more elegant way to approach this?
**Edit based on responses:** It certainly does seem like some kind of template engine would make my life much easier, but it would require me basically invert my usual PHP style. Not that that's a bad thing, but it explains my inertia.. I'm up for figuring out ways to make life easier though, so I'm looking into templates now.
|
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 hacks like what you're trying to do now to achieve more complex templating, such as looping
Get a basic template engine, or just use PHP with includes - it's why the language has the `<?php` and `?>` delimiters.
**template\_file.php**
```
<html>
<head>
<title><?php echo $page_title; ?></title>
</head>
<body>
<?php echo getPageContent(); ?>
</body>
```
**index.php**
```
<?php
$page_title = "This is a simple demo";
function getPageContent() {
return '<p>Hello World!</p>';
}
include('template_file.php');
```
|
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; static int bar = 20;
foo++; foo++;
bar++; bar++;
printf("%d,%d", foo, bar); printf("%d, %d", foo, bar);
} }
```
If I compile both files and link it to a main that calls fooTest() and barTest repeatedly, the printf statements increment independently. Makes sense since the foo and bar variables are local to the translation unit.
But where is the storage allocated?
To be clear, the assumption is that you have a toolchain that would output a file in ELF format. Thus, I *believe* that there **has** to be some space reserved in the executable file for those static variables.
For discussion purposes, lets assume we use the GCC toolchain.
|
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 uninitialized data are stored in this segment.
Here is a diagram to explain this concept:

Here is very good link explaining these concepts: [Memory Management in C: The Heap and the Stack](https://web.archive.org/web/20170829060314/http://www.inf.udec.cl/%7Eleo/teoX.pdf)
|
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 run under JSE 6 (indicating improved runtime optimization)?
I've noticed that compiling under JDK 6 takes almost twice as long as it did under JDK 5 for the exact same codebase; I'm hoping that at least some of that extra time is being spent on compiler optimizations, hopefully leading to more performant JARs and WARs. Sun's JDK info doesn't really go into detail on the performance improvements they've made - I assume it's a little from column A, and a little from column B, but I wonder which is the greater influence. Does anyone know of any benchmarks done on JDK 6 vs. JDK 5?
|
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/6performance.html>
|
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 about the state of the stack to make verification easier and faster (Java ME does this as well). This only affects class loading speeds.
The real optimising part is the hotspot compiler that compile bytecode to native code. This is even updated on some update releases. On Windows only the slower client C1 version of hotspot is distributed in the JRE by default. The server C2 hotspot runs faster (use -server on the java command line), but is slower to start up and uses more memory.
Also the libraries and tools (including javac) sometimes have optimisation work done.
I don't know why you are finding JDK 6 slower to compile code than JDK 5. Is there some subtle difference in set up?
|
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 still use boost::shared\_ptr etc.
But there are also some boost containers designed explicitly to hold pointers safely:
See [Pointer Container Library](http://www.boost.org/doc/libs/1_36_0/libs/ptr_container/doc/reference.html)
The question is:
Under what conditions should I prefer to use the ptr\_containers over a container of smart\_pointers?
```
boost::ptr_vector<X>
or
std::vector<boost::shared_ptr<X> >
```
|
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 containers of raw pointers.
|
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 article covers this topic, but requires special CPU instructions:
<http://www.ddj.com/architect/184401888>
|
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 platforms/compilers, use the appropriate intrinsic for the LOCK CMPXCHG instruction that MS's \_InterlockedCompareExchange exposes.
|
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
[<http://diveintopython3.ep.io/>](http://diveintopython3.ep.io/) - Intermediate
[<http://www.pythonchallenge.com/>](http://www.pythonchallenge.com/) - Expert Skills
[<http://docs.python.org/>](http://docs.python.org/) - collection of all knowledge
Some more:
[A Byte of Python.](http://www.swaroopch.com/notes/Python)
[Python 2.5 Quick Reference](http://rgruet.free.fr/PQR25/PQR2.5.html)
[Python Side bar](http://www.edgewall.org/python-sidebar/)
[A Nice blog for beginners](http://www.learningpython.com/)
[Think Python: An Introduction to Software Design](http://www.greenteapress.com/thinkpython/thinkpython.html)
|
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/> - outstanding and interesting challenge
And the perfect source of knowledge is <http://docs.python.org/> - collection of all knowledge
|
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.
>
> [...]
>
> "**Immutable objects are simple.** An immutable object can be in
> exactly one state, the state in which it was created. If you make sure
> that all constructors establish class invariants, then it is
> guaranteed that these invariants will remain true for all time, with
> no effort on your part.
>
> [...]
>
> **Immutable objects are inherently thread-safe; they require no synchronization.** They cannot be corrupted by multiple threads
> accessing them concurrently. This is far and away the easiest approach
> to achieving thread safety. In fact, no thread can ever observe any
> effect of another thread on an immutable object. Therefore,
> **immutable objects can be shared freely**
>
> [...]
Other small points from the same chapter:
> Not only can you share immutable objects, but you can share their internals.
>
> [...]
>
> Immutable objects make great building blocks for other objects, whether mutable or immutable.
>
> [...]
>
> The only real disadvantage of immutable classes is that they require a separate object for each distinct value.
|
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 the call
> will be passed to OS. If String was
> mutable it was possible somehow to
> modify its content after the
> authentication check before OS gets
> request from program then it is
> possible to request any file. So if
> you have a right to open text file in
> user directory but then on the fly
> when somehow you manage to change the
> file name you can request to open
> "passwd" file or any other. Then a
> file can be modified and it will be
> possible to login directly to OS.
**Second - Memory efficiency** <http://hikrish.blogspot.com/2006/07/why-string-class-is-immutable.html>
> JVM internally maintains the "String
> Pool". To achive the memory
> efficiency, JVM will refer the String
> object from pool. It will not create
> the new String objects. So, whenever
> you create a new string literal, JVM
> will check in the pool whether it
> already exists or not. If already
> present in the pool, just give the
> reference to the same object or create
> the new object in the pool. There will
> be many references point to the same
> String objects, if someone changes the
> value, it will affect all the
> references. So, sun decided to make it
> immutable.
|
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:
```
enum { xNew, xDeleted, xModified, xExisting }
```
However, in other places in code, I need to select which records are to be visible to the user, so I'd like to be able to pass that as a single parameter, like:
```
showRecords(xNew | xDeleted);
```
So, it seems I have three possible appoaches:
```
#define X_NEW 0x01
#define X_DELETED 0x02
#define X_MODIFIED 0x04
#define X_EXISTING 0x08
```
or
```
typedef enum { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } RecordType;
```
or
```
namespace RecordType {
static const uint8 xNew = 1;
static const uint8 xDeleted = 2;
static const uint8 xModified = 4;
static const uint8 xExisting = 8;
}
```
Space requirements are important (byte vs int) but not crucial. With defines I lose type safety, and with `enum` I lose some space (integers) and probably have to cast when I want to do a bitwise operation. With `const` I think I also lose type safety since a random `uint8` could get in by mistake.
Is there some other cleaner way?
If not, what would you use and why?
P.S. The rest of the code is rather clean modern C++ without `#define`s, and I have used namespaces and templates in few spaces, so those aren't out of question either.
|
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.
```
namespace RecordType {
```
An enum declares and defines a compile time checked typed. Always use compile time type checking to make sure arguments and variables are given the correct type. There is no need for the typedef in C++.
```
enum TRecordType { xNew = 1, xDeleted = 2, xModified = 4, xExisting = 8,
```
Create another member for an invalid state. This can be useful as error code; for example, when you want to return the state but the I/O operation fails. It is also useful for debugging; use it in initialisation lists and destructors to know if the variable's value should be used.
```
xInvalid = 16 };
```
Consider that you have two purposes for this type. To track the current state of a record and to create a mask to select records in certain states. Create an inline function to test if the value of the type is valid for your purpose; as a state marker vs a state mask. This will catch bugs as the `typedef` is just an `int` and a value such as `0xDEADBEEF` may be in your variable through uninitialised or mispointed variables.
```
inline bool IsValidState( TRecordType v) {
switch(v) { case xNew: case xDeleted: case xModified: case xExisting: return true; }
return false;
}
inline bool IsValidMask( TRecordType v) {
return v >= xNew && v < xInvalid ;
}
```
Add a `using` directive if you want to use the type often.
```
using RecordType ::TRecordType ;
```
The value checking functions are useful in asserts to trap bad values as soon as they are used. The quicker you catch a bug when running, the less damage it can do.
Here are some examples to put it all together.
```
void showRecords(TRecordType mask) {
assert(RecordType::IsValidMask(mask));
// do stuff;
}
void wombleRecord(TRecord rec, TRecordType state) {
assert(RecordType::IsValidState(state));
if (RecordType ::xNew) {
// ...
} in runtime
TRecordType updateRecord(TRecord rec, TRecordType newstate) {
assert(RecordType::IsValidState(newstate));
//...
if (! access_was_successful) return RecordType ::xInvalid;
return newstate;
}
```
The only way to ensure correct value safety is to use a dedicated class with operator overloads and that is left as an exercise for another reader.
|
## 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.
> However, bit members in structs have practical drawbacks. First, the ordering of bits in memory varies from compiler to compiler. In addition, **many popular compilers generate inefficient code for reading and writing bit members**, and there are potentially severe **thread safety issues** relating to bit fields (especially on multiprocessor systems) due to the fact that most machines cannot manipulate arbitrary sets of bits in memory, but must instead load and store whole words. e.g the following would not be thread-safe, in spite of the use of a mutex
Source: <http://en.wikipedia.org/wiki/Bit_field>:
And if you need more reasons to **not** use bitfields, perhaps [Raymond Chen](http://en.wikipedia.org/wiki/Raymond_Chen) will convince you in his [The Old New Thing](http://blogs.msdn.com/oldnewthing) Post: **The cost-benefit analysis of bitfields for a collection of booleans** at <http://blogs.msdn.com/oldnewthing/archive/2008/11/26/9143050.aspx>
## const int?
```
namespace RecordType {
static const uint8 xNew = 1;
static const uint8 xDeleted = 2;
static const uint8 xModified = 4;
static const uint8 xExisting = 8;
}
```
Putting them in a namespace is cool. If they are declared in your CPP or header file, their values will be inlined. You'll be able to use switch on those values, but it will slightly increase coupling.
Ah, yes: **remove the static keyword**. static is deprecated in C++ when used as you do, and if uint8 is a buildin type, you won't need this to declare this in an header included by multiple sources of the same module. In the end, the code should be:
```
namespace RecordType {
const uint8 xNew = 1;
const uint8 xDeleted = 2;
const uint8 xModified = 4;
const uint8 xExisting = 8;
}
```
The problem of this approach is that your code knows the value of your constants, which increases slightly the coupling.
## enum
The same as const int, with a somewhat stronger typing.
```
typedef enum { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } RecordType;
```
They are still polluting the global namespace, though.
By the way... **Remove the typedef**. You're working in C++. Those typedefs of enums and structs are polluting the code more than anything else.
The result is kinda:
```
enum RecordType { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } ;
void doSomething(RecordType p_eMyEnum)
{
if(p_eMyEnum == xNew)
{
// etc.
}
}
```
As you see, your enum is polluting the global namespace.
If you put this enum in an namespace, you'll have something like:
```
namespace RecordType {
enum Value { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } ;
}
void doSomething(RecordType::Value p_eMyEnum)
{
if(p_eMyEnum == RecordType::xNew)
{
// etc.
}
}
```
## extern const int ?
If you want to decrease coupling (i.e. being able to hide the values of the constants, and so, modify them as desired without needing a full recompilation), you can declare the ints as extern in the header, and as constant in the CPP file, as in the following example:
```
// Header.hpp
namespace RecordType {
extern const uint8 xNew ;
extern const uint8 xDeleted ;
extern const uint8 xModified ;
extern const uint8 xExisting ;
}
```
And:
```
// Source.hpp
namespace RecordType {
const uint8 xNew = 1;
const uint8 xDeleted = 2;
const uint8 xModified = 4;
const uint8 xExisting = 8;
}
```
You won't be able to use switch on those constants, though. So in the end, pick your poison...
:-p
|
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 familiar with the .Net version of web applications first rather than try and learn that on the fly if you do the port upfront. It's much easier to learn the new concepts like PostBack and ViewState in a 'clean' environment.
There's also less scope to break out of your old way of thinking as you port stuff (just making it work any old how rather than redesigning where needed).
Ultimately there's not a great deal of difference in the long run, it's mostly perceptual and a matter of personal taste but I'd propose learning C# first because it's lack of familiarity will emphasise the fact that you're learning something new. Hopefully thi will help you learn to do things the natural .Net way rather than the largely procedural VB(script) way. You're trying to unlearn as well as learn. Familiarity of some keywords will work against you.
Echoing other benefits throughout some of the posts, and adding a few of my own:
* Future potential earnings : C# developers generally are worth more than VB.Net developers because of the perceptual difference.
* Most of the open source .Net code out there is C#, and the quality of it generally (though not always) tends to be higher.
* There are more Q&A and examples and out there on the internet in C# than VB.Net. At the time I post this there's **1572** posts tagged with C#, only **185** with VB.Net right here on Stack OverFlow.
* C# OO keywords are reasonably standard, it makes it easier to read other OO language code. VB.Net goes off and renames things for no good reason e.g. *abstract* (C#, C++, Java and more...) vs *MustInherit* (VB.Net only).
* It's generally accepted that once your familiar in both languages it's a lot easier to visually parse C# code than VB.Net code
* You won't get 'looked down' on by C#'ers and can help poke fun at the VB.Net people (if you so desire - the culture exists...)
Once you've initially learned it in C#, it should be much easier to roll across to VB.Net than it would be the other way around. Invest in your own future.
|
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, 2) receiving data, 3) reestablishing connection when it is dropped. So, given that there are N nodes in cluster, each machine is going to have 3 threads for each of N-1 neighbours. Typically there will be 12 machines, which comes to 33 communication threads.
Most of those threads will be sleeping most of the time, so for optimization purposes I could reduce number of threads and give more job to each of them. Like, for example. reestablishing connection is responsibility of receiving thread. Or sending to all connected machines is done by single thread.
So is there any significant perfomance impact on having many sleeping threads?
|
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, and when the number of connections grew above 500 connections (about a thousand threads), you tend to get into lots of cases where you get OutOfMemoryError, since the threads stack space usage exceeds the maximum amount of memory for a single process. At least in our case, which was in a Java on 32 bit Windows world. You can tune things and get a bit further, I guess, but in the end it's just not very scalable since you waste lots of memory.
If you need a large number of connections, Java NIO (new IO or whatever) is the way to go, making it possible to handle lots of connections in the same thread.
Having said that, you shouldn't encounter much of a problem with under a 100 threads on a reasonably modern server, even if it's probably still a waste of resources.
|
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 increased the number of connections we could handle a lot, which was really critical for us.
|
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 Cache, email you about it, log it in the Event Log, whatever suits your needs.
Hope that helps,
Pascal
|
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 item gets kicked out.
Hope this helps a bit.
|
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 this method. It must either return a `bool` value which is then directly used, or an `int` value that is considered `False` if equal to zero.
2. Otherwise, if the object has a `__len__` special method (as do container built-ins, `list`, `dict`, `set`, `tuple`, ...), it calls this method, considering a container `False` if it is empty (length is zero).
3. Otherwise, the object is considered `True` unless it is `None` in which case, it is considered `False`.
In the second test, the object is compared for equality to `None`. Here, **we are asking the object, "Are you equal to this other value?"** This is done using the following algorithm :
1. If the object has a `__eq__` method, it is called, and the return value is then converted to a `bool`value and used to determine the outcome of the `if`.
2. Otherwise, if the object has a `__cmp__` method, it is called. This function must return an `int` indicating the order of the two object (`-1` if `self < other`, `0` if `self == other`, `+1` if `self > other`).
3. Otherwise, the object are compared for identity (ie. they are reference to the same object, as can be tested by the `is` operator).
There is another test possible using the `is` operator. **We would be asking the object, "Are you this particular object?"**
Generally, I would recommend to use the first test with non-numerical values, to use the test for equality when you want to compare objects of the same nature (two strings, two numbers, ...) and to check for identity only when using sentinel values (`None` meaning not initialized for a member field for exemple, or when using the `getattr` or the `__getitem__` methods).
To summarize, we have :
```
>>> class A(object):
... def __repr__(self):
... return 'A()'
... def __nonzero__(self):
... return False
>>> class B(object):
... def __repr__(self):
... return 'B()'
... def __len__(self):
... return 0
>>> class C(object):
... def __repr__(self):
... return 'C()'
... def __cmp__(self, other):
... return 0
>>> class D(object):
... def __repr__(self):
... return 'D()'
... def __eq__(self, other):
... return True
>>> for obj in ['', (), [], {}, 0, 0., A(), B(), C(), D(), None]:
... print '%4s: bool(obj) -> %5s, obj == None -> %5s, obj is None -> %5s' % \
... (repr(obj), bool(obj), obj == None, obj is None)
'': bool(obj) -> False, obj == None -> False, obj is None -> False
(): bool(obj) -> False, obj == None -> False, obj is None -> False
[]: bool(obj) -> False, obj == None -> False, obj is None -> False
{}: bool(obj) -> False, obj == None -> False, obj is None -> False
0: bool(obj) -> False, obj == None -> False, obj is None -> False
0.0: bool(obj) -> False, obj == None -> False, obj is None -> False
A(): bool(obj) -> False, obj == None -> False, obj is None -> False
B(): bool(obj) -> False, obj == None -> False, obj is None -> False
C(): bool(obj) -> True, obj == None -> True, obj is None -> False
D(): bool(obj) -> True, obj == None -> True, obj is None -> False
None: bool(obj) -> False, obj == None -> True, obj is None -> True
```
|
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 describe a raft of things which are False; everything else is True. If the value of x wasn't properly boolean to begin with, this implicit conversion isn't really the clearest way to say things.
Before Python 2.2, there was no bool function, so it was even less clear.
Second, you shouldn't really test with `== None`. You should use `is None` and `is not None`.
See PEP 8, [Style Guide for Python Code](http://www.python.org/dev/peps/pep-0008/).
> ```
> - Comparisons to singletons like None should always be done with
> 'is' or 'is not', never the equality operators.
>
> Also, beware of writing "if x" when you really mean "if x is not None"
> -- e.g. when testing whether a variable or argument that defaults to
> None was set to some other value. The other value might have a type
> (such as a container) that could be false in a boolean context!
> ```
How many singletons are there? Five: `None`, `True`, `False`, `NotImplemented` and `Ellipsis`. Since you're really unlikely to use `NotImplemented` or `Ellipsis`, and you would never say `if x is True` (because simply `if x` is a lot clearer), you'll only ever test `None`.
|
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 specification.
If GM metadata is not directly accessible, perhaps there's a way to read the body of the script itself. It's certainly in memory somewhere, and it wouldn't be too awfully hard to parse for `"// @"`. (That may be necessary in my case any way, since the value I'm really interested in is `@version`, which is an extended value read by [userscripts.org](http://userscripts.org/).)
|
**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/greasemonkey/
// @description Read in metadata from the header
// @version 0.9
// @include https://stackoverflow.com/questions/104568/accessing-greasemonkey-metadata-from-within-your-script
// ==/UserScript==
</>.toString();
GM_log(metadata);
```
See [this thread on the greasemonkey-users group](http://groups.google.com/group/greasemonkey-users/browse_thread/thread/2003daba08cc14b6/62a635f278d8f9fc) for more information. A more robust implementation can be found near the end.
|
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://stackoverflow.com/questions/*
// @version 8.8
// ==/UserScript==
unsafeWindow.console.clear ();
unsafeWindow.console.log (GM_info);
```
It will output this object:
```
{
version: (new String("0.9.18")),
scriptWillUpdate: false,
script: {
description: "Tell me more about me, me, ME!",
excludes: [],
includes: ["http://stackoverflow.com/questions/*"],
matches: [],
name: "_GM_info demo",
namespace: "Stack Overflow",
'run-at': "document-end",
unwrap: false,
version: "8.8"
},
scriptMetaStr: "// @name _GM_info demo\r\n// @namespace Stack Overflow\r\n// @description Tell me more about me, me, ME!\r\n// @include http://stackoverflow.com/questions/*\r\n// @version 8.8\r\n"
}
```
|
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 embedded resource which I then place in the appropriate place during execution of the first DLL.
The way I originally planned to do this is by writing code to put the third party DLL in the location specified by `System.Reflection.Assembly.GetExecutingAssembly().Location.ToString()`
minus the last `/nameOfMyAssembly.dll`. I can successfully save the third party `.DLL` in this location (which ends up being
> C:\Documents and Settings\myUserName\Local Settings\Application
> Data\assembly\dl3\KXPPAX6Y.ZCY\A1MZ1499.1TR\e0115d44\91bb86eb\_fe18c901
), but when I get to the part of my code requiring this DLL, it can't find it.
Does anybody have any idea as to what I need to be doing differently?
|
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 to locate an assembly according to the probing (policies) in effect. In the event handler for `AppDomain.AssemblyResolve`, load the resource using [`Assembly.GetManifestResourceStream`](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getmanifestresourcestream.aspx) and feed its content as a byte array into the corresponding [`Assembly.Load`](http://msdn.microsoft.com/en-us/library/h538bck7.aspx) overload. Below is how one such implementation could look like in C#:
```
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
var resName = args.Name + ".dll";
var thisAssembly = Assembly.GetExecutingAssembly();
using (var input = thisAssembly.GetManifestResourceStream(resName))
{
return input != null
? Assembly.Load(StreamToBytes(input))
: null;
}
};
```
where `StreamToBytes` could be defined as:
```
static byte[] StreamToBytes(Stream input)
{
var capacity = input.CanSeek ? (int) input.Length : 0;
using (var output = new MemoryStream(capacity))
{
int readLength;
var buffer = new byte[4096];
do
{
readLength = input.Read(buffer, 0, buffer.Length);
output.Write(buffer, 0, readLength);
}
while (readLength != 0);
return output.ToArray();
}
}
```
Finally, as a few have already mentioned, [ILMerge](http://research.microsoft.com/~mbarnett/ILMerge.aspx) may be another option to consider, albeit somewhat more involved.
|
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 great!
This is what my code ended up looking like:
EDIT: I decided to move this function to another assembly so I could reuse it in multiple files (I just pass in Assembly.GetExecutingAssembly()).
This is the updated version which allows you to pass in the assembly with the embedded dlls.
embeddedResourcePrefix is the string path to the embedded resource, it will usually be the name of the assembly followed by any folder structure containing the resource (e.g. "MyComapny.MyProduct.MyAssembly.Resources" if the dll is in a folder called Resources in the project). It also assumes that the dll has a .dll.resource extension.
```
public static void EnableDynamicLoadingForDlls(Assembly assemblyToLoadFrom, string embeddedResourcePrefix) {
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { // had to add =>
try {
string resName = embeddedResourcePrefix + "." + args.Name.Split(',')[0] + ".dll.resource";
using (Stream input = assemblyToLoadFrom.GetManifestResourceStream(resName)) {
return input != null
? Assembly.Load(StreamToBytes(input))
: null;
}
} catch (Exception ex) {
_log.Error("Error dynamically loading dll: " + args.Name, ex);
return null;
}
}; // Had to add colon
}
private static byte[] StreamToBytes(Stream input) {
int capacity = input.CanSeek ? (int)input.Length : 0;
using (MemoryStream output = new MemoryStream(capacity)) {
int readLength;
byte[] buffer = new byte[4096];
do {
readLength = input.Read(buffer, 0, buffer.Length); // had to change to buffer.Length
output.Write(buffer, 0, readLength);
}
while (readLength != 0);
return output.ToArray();
}
}
```
|
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 returns a `List` of `ContactDetails` objects, then any code calling that getter:
1. can remove `ContactDetail` objects from that list without the `Contact` object knowing of it.
2. can change each `ContactDetail` object without the `Contact` object knowing of it.
So what should we do here? Should we just trust the calling code and return easily mutable objects, or go the hard way and make a immutable class for each mutable class?
|
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, most properties I create are mutable. An occasional user botches this up, but then again it's his/her fault, since it is clearly documented that mutation should not occur via mutable objects received via getters.
|
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 the list may also need to be immutable themselves.
Don't forget, though, that you can return a custom List implementation that knows how to respond safely to mutation requests, whether by firing events or by performing any required actions directly. In fact, this is a classic example of a good time to use an inner class.
|
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 as C# or VB.NET; basically only the syntax changes, e.g. using '->' to point to a member of an object (instead of '.' in C#), using '::' for namespaces, etc.
Managed C++ was made to ease transition from classic C++ to the .NET Framework. It is not intended to be used to start new projects (C# is preferred).
|
"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, userDetails.lname
FROM accountingTab INNER JOIN
(SELECT id, title, first, last FROM memDetTab) AS userDetails ON memID = userDetails.id
```
And then I get the Invalid Column Name `memID` error.
How can I fix this?
|
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 in a lock statement, right? I recently saw some code that looked like the following example, and it made me think there may be some gaps in my multithreading knowledge:
```
class Foo
{
private static readonly string bar = "O_o";
private bool TrySomething()
{
string bar;
lock(Foo.objectToLockOn)
{
bar = Foo.bar;
}
// Do something with bar
}
}
```
That just doesn't make sense to me--why would there by concurrency issues with READING a register?
Also, this example brings up another question. Is one of these better than the other? (E.g. example two holds the lock for less time?) I suppose I could disassemble the MSIL...
```
class Foo
{
private static string joke = "yo momma";
private string GetJoke()
{
lock(Foo.objectToLockOn)
{
return Foo.joke;
}
}
}
```
vs.
```
class Foo
{
private static string joke = "yo momma";
private string GetJoke()
{
string joke;
lock(Foo.objectToLockOn)
{
joke = Foo.joke;
}
return joke;
}
}
```
|
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 synchronization, any shared reference which could be modified is vulnerable to synchronization issues.
```
class Foo
{
private int count = 0;
public void TrySomething()
{
count++;
}
}
```
You might suppose that two threads executing the TrySomething method would be fine. But its not.
1. Thread A reads the value of count (0) into a register so it can be incremented.
2. Context switch! The thread scheduler decides thread A has had enough execution time. Next in line is Thread B.
3. Thread B reads the value of count (0) into a register.
4. Thread B increments the register.
5. Thread B saves the result (1) to count.
6. Context switch back to A.
7. Thread A reloads the register with the value of count (0) saved on its stack.
8. Thread A increments the register.
9. Thread A saves the result (1) to count.
So, even though we called count++ twice, the value of count has just gone from 0 to 1. Lets make the code thread-safe:
```
class Foo
{
private int count = 0;
private readonly object sync = new object();
public void TrySomething()
{
lock(sync)
count++;
}
}
```
Now when Thread A gets interrupted Thread B cannot mess with count because it will hit the lock statement and then block until Thread A has released sync.
By the way, there is an alternative way to make incrementing Int32s and Int64s thread-safe:
```
class Foo
{
private int count = 0;
public void TrySomething()
{
System.Threading.Interlocked.Increment(ref count);
}
}
```
Regarding the second part of your question, I think I would just go with whichever is easier to read, any performance difference there will be negligible. Early optimisation is the root of all evil, etc.
[Why threading is hard](https://learn.microsoft.com/en-us/archive/blogs/jmstall/why-threading-is-hard)
|
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 = fgetcsv($file, $longest, $delimiter))
{
array_push($mdarray, $line);
}
fclose($file);
return $mdarray;
}
```
I need to be able to specify a column to sort so that it rearranges the rows. One of the columns contains date information in the format of `Y-m-d H:i:s` and I would like to be able to sort with the most recent date being the first row.
|
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 column to sort by. No need for the loop:
```
array_multisort(array_column($mdarray, 0), SORT_DESC, $mdarray);
```
|
## 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 can specify multiple sort columns (as many as you want) -- additional columns are used as tiebreakers between items that initially compare equal.
3. It's **reversible**: you can specify that the sort should be reversed -- individually for each column.
4. It's **extensible**: if the data set contains columns that cannot be compared in a "dumb" manner (e.g. date strings) you can also specify how to convert these items to a value that can be directly compared (e.g. a `DateTime` instance).
5. It's **associative if you want**: this code takes care of sorting items, but *you* select the actual sort function (`usort` or `uasort`).
6. Finally, it does not use `array_multisort`: while `array_multisort` is convenient, it depends on creating a projection of all your input data before sorting. This consumes time and memory and may be simply prohibitive if your data set is large.
### The code
```
function make_comparer() {
// Normalize criteria up front so that the comparer finds everything tidy
$criteria = func_get_args();
foreach ($criteria as $index => $criterion) {
$criteria[$index] = is_array($criterion)
? array_pad($criterion, 3, null)
: array($criterion, SORT_ASC, null);
}
return function($first, $second) use (&$criteria) {
foreach ($criteria as $criterion) {
// How will we compare this round?
list($column, $sortOrder, $projection) = $criterion;
$sortOrder = $sortOrder === SORT_DESC ? -1 : 1;
// If a projection was defined project the values now
if ($projection) {
$lhs = call_user_func($projection, $first[$column]);
$rhs = call_user_func($projection, $second[$column]);
}
else {
$lhs = $first[$column];
$rhs = $second[$column];
}
// Do the actual comparison; do not return if equal
if ($lhs < $rhs) {
return -1 * $sortOrder;
}
else if ($lhs > $rhs) {
return 1 * $sortOrder;
}
}
return 0; // tiebreakers exhausted, so $first == $second
};
}
```
## How to use
Throughout this section I will provide links that sort this sample data set:
```
$data = array(
array('zz', 'name' => 'Jack', 'number' => 22, 'birthday' => '12/03/1980'),
array('xx', 'name' => 'Adam', 'number' => 16, 'birthday' => '01/12/1979'),
array('aa', 'name' => 'Paul', 'number' => 16, 'birthday' => '03/11/1987'),
array('cc', 'name' => 'Helen', 'number' => 44, 'birthday' => '24/06/1967'),
);
```
### The basics
The function `make_comparer` accepts a variable number of arguments that define the desired sort and returns a function that you are supposed to use as the argument to `usort` or `uasort`.
The simplest use case is to pass in the key that you 'd like to use to compare data items. For example, to sort `$data` by the `name` item you would do
```
usort($data, make_comparer('name'));
```
**[See it in action](http://ideone.com/g5jNqs)**.
The key can also be a number if the items are numerically indexed arrays. For the example in the question, this would be
```
usort($data, make_comparer(0)); // 0 = first numerically indexed column
```
**[See it in action](http://ideone.com/upHxqf)**.
### Multiple sort columns
You can specify multiple sort columns by passing additional parameters to `make_comparer`. For example, to sort by "number" and then by the zero-indexed column:
```
usort($data, make_comparer('number', 0));
```
**[See it in action](http://ideone.com/C5OqJT)**.
## Advanced features
More advanced features are available if you specify a sort column as an array instead of a simple string. This array should be numerically indexed, and must contain these items:
```
0 => the column name to sort on (mandatory)
1 => either SORT_ASC or SORT_DESC (optional)
2 => a projection function (optional)
```
Let's see how we can use these features.
### Reverse sort
To sort by name descending:
```
usort($data, make_comparer(['name', SORT_DESC]));
```
**[See it in action](http://ideone.com/eLUqjb)**.
To sort by number descending and then by name descending:
```
usort($data, make_comparer(['number', SORT_DESC], ['name', SORT_DESC]));
```
**[See it in action](http://ideone.com/RpyQZ3)**.
### Custom projections
In some scenarios you may need to sort by a column whose values do not lend well to sorting. The "birthday" column in the sample data set fits this description: it does not make sense to compare birthdays as strings (because e.g. "01/01/1980" comes before "10/10/1970"). In this case we want to specify how to *project* the actual data to a form that *can* be compared directly with the desired semantics.
Projections can be specified as any type of [callable](http://php.net/manual/en/language.types.callable.php): as strings, arrays, or anonymous functions. A projection is assumed to accept one argument and return its projected form.
It should be noted that while projections are similar to the custom comparison functions used with `usort` and family, they are simpler (you only need to convert one value to another) and take advantage of all the functionality already baked into `make_comparer`.
Let's sort the example data set without a projection and see what happens:
```
usort($data, make_comparer('birthday'));
```
**[See it in action](http://ideone.com/GvXmoM)**.
That was not the desired outcome. But we can use [`date_create`](http://php.net/manual/en/function.date-create.php) as a projection:
```
usort($data, make_comparer(['birthday', SORT_ASC, 'date_create']));
```
**[See it in action](http://ideone.com/sZE4hO)**.
This is the correct order that we wanted.
There are many more things that projections can achieve. For example, a quick way to get a case-insensitive sort is to use `strtolower` as a projection.
That said, I should also mention that it's better to not use projections if your data set is large: in that case it would be much faster to project all your data manually up front and then sort without using a projection, although doing so will trade increased memory usage for faster sort speed.
Finally, here is an example that uses all the features: it first sorts by number descending, then by birthday ascending:
```
usort($data, make_comparer(
['number', SORT_DESC],
['birthday', SORT_ASC, 'date_create']
));
```
**[See it in action](http://ideone.com/RLmvsm)**.
|
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 main panel that selects the company, and binds to a FormView. The FormView contains a Web User Control that handles the display/configuration of the export details.
The Web User Control Contains a property to define which Config it should be handling, and it gets the value from the FormView using Bind().
Basically the control is used like this:
```
<syn:ExportInfo ID="eiConfigDetails" ExportInfoID='<%# Bind("ExportInfoID" ) %>' runat="server" />
```
The property being bound is declared like this in CodeBehind:
```
public int ExportInfoID
{
get
{
return Convert.ToInt32(hfID.Value);
}
set
{
try
{
hfID.Value = value.ToString();
}
catch(Exception)
{
hfID.Value="-1";
}
}
}
```
Whenever the `ExportInfoID` is null I get a null reference exception, but the kicker is that it happens BEFORE it actually tries to set the property (or it would be caught in this version.)
Anyone know what's going on or, more importantly, how to fix it...?
|
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 uses reflection to get the value
bind attempts to set the ExportInfoID property // boom, error
```
|
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 (window.ActiveXObject) {
// code for IE
ex = xml.transformNode(xsl);
ex = ex.replace(/\\/g, "");
document.getElementById("popularTags").innerHTML = ex;
} else if (document.implementation && document.implementation.createDocument) {
// code for Mozilla, Firefox, Opera, etc.
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml, document);
document.getElementById("popularTags").appendChild(resultDocument);
var ihtml = document.getElementById("popularTags").innerHTML;
ihtml = ihtml.replace(/\\/g, "");
document.getElementById("popularTags").innerHTML = ihtml;
}
}
ShowPopularTags();
```
The issue with this script is sometime it manages to output the resulting HTML code, sometime it doesn't. Anyone knows where is going wrong?
|
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 would lock up for as long as the request was running (which, depending on timeout settings, can take a very long time).
It would require a bit more work on your end, but the solution would be something like the following. This is the code I use for handling XSLT stuff with Ajax (rewrote it slightly because my code is object oriented and contains a loop that parses out the appropriate XSL document from the XML document first loaded)
Note: make sure you declare your version of oCurrentRequest and oXMLRequest outside of the functions, since it will be carried over.
```
if (window.XMLHttpRequest)
{
oCurrentRequest = new XMLHttpRequest();
oCurrentRequest.onreadystatechange = processReqChange;
oCurrentRequest.open('GET', sURL, true);
oCurrentRequest.send(null);
}
else if (window.ActiveXObject)
{
oCurrentRequest = new ActiveXObject('Microsoft.XMLHTTP');
if (oCurrentRequest)
{
oCurrentRequest.onreadystatechange = processReqChange;
oCurrentRequest.open('GET', sURL, true);
oCurrentRequest.send();
}
}
```
After this you'd just need a function named processReqChange that contains something like the following:
```
function processReqChange()
{
if (oCurrentRequest.readyState == 4)
{
if (oCurrentRequest.status == 200)
{
oXMLRequest = oCurrentRequest;
oCurrentRequest = null;
loadXSLDoc();
}
}
}
```
And ofcourse you'll need to produce a second set of functions to handle the XSL loading (starting from loadXSLDoc on, for example).
Then at the end of you processXSLReqChange you can grab your XML result and XSL result and do the transformation.
|
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 are completely sure that your document.getElementById("popularTags") doesn't fail because the scripting is called before the HTML containing the element is fully loaded.
Also, can we see your XMLDocLoad function? If that contains non-sequential elements as well, you might be facing a problem where the XSLT transformation takes place before the objects xml and xsl are fully loaded.
|
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.aspx).
Examples have already been posted here, but I found that the non-.exe version worked better, so something like:
```
foreach ( Process p in System.Diagnostics.Process.GetProcessesByName("winword") )
{
try
{
p.Kill();
p.WaitForExit(); // possibly with a timeout
}
catch ( Win32Exception winException )
{
// process was terminating or can't be terminated - deal with it
}
catch ( InvalidOperationException invalidException )
{
// process has already exited - might be able to let this one go
}
}
```
You probably don't have to deal with `NotSupportedException`, which suggests that the process is remote.
|
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):
```
Dim proc = Process.GetProcessesByName("winword")
For i As Integer = 0 To proc.Count - 1
proc(i).CloseMainWindow()
Next i
```
This will close all open Word windows in an orderly fashion (prompting the user to save his/her work if applicable). Of course, the user can always click 'Cancel' in this scenario, so you should be able to handle this case as well (preferably by putting up a "please close all Word instances, otherwise we can't continue" dialog...)
|
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 would be helpful.
Thanks.
|
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 works great. You can use the IDE that comes with the Workflow examples and put it in your own apps. It's excellent.
|
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 type, which I read successfully and then writes the contents of the file and closes the socket. This seems to work fine.
The client (a C# web app), reads the data:
```
private NetworkStream stream_;
public void WriteDocument(HttpResponse response)
{
while (stream_.DataAvailable)
{
const int bufsize = 4 * 1024;
byte[] buffer = new byte[bufsize];
int nbytes = stream_.Read(buffer, 0, bufsize);
if (nbytes > 0)
{
if (nbytes < bufsize)
Array.Resize<byte>(ref buffer, nbytes);
response.BinaryWrite(buffer);
}
}
response.End();
}
```
This seems to always exit the read loop before all the data has arrived. What am I doing wrong?
|
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) {
byte[] buffer = new byte[4 * 1024];
int n = 1;
while (n > 0) {
n = src.Read(buffer, 0, buffer.Length);
dest.Write(buffer, 0, n);
}
dest.Flush();
}
```
|
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 NOW, it doesn't (and cannot) know if there's more data to be sent or not. To check that the socket is still open you can test for stream\_.Socket.Connected && stream\_.Socket.Readable
```
public static byte[] doFetchBinaryUrl(string url)
{
BinaryReader rdr;
HttpWebResponse res;
try
{
res = fetch(url);
rdr = new BinaryReader(res.GetResponseStream());
}
catch (NullReferenceException nre)
{
return new byte[] { };
}
int len = int.Parse(res.GetResponseHeader("Content-Length"));
byte[] rv = new byte[len];
for (int i = 0; i < len - 1; i++)
{
rv[i] = rdr.ReadByte();
}
res.Close();
return rv;
}
```
|
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:HyperLink ID="hlYes" runat="server" Text="Yes" CssClass="button"></asp:HyperLink>
<asp:LinkButton ID="lnkbtnNo" runat="server" Text="No" CssClass="button"></asp:LinkButton>
</cc1:PopupDialog>
```
It uses a custom control that simply adds code before and after the content to format it as a popup dialog. The **Yes** button is a HyperLink because it executes javascript to hide the dialog and show a different one. The **No** button is a LinkButton because it needs to PostBack to process this value.
I do not have an onClick event registered with the LinkButton because I simply check if IsPostBack is true. When executed locally, the PostBack works fine and all goes well. When published to our Development server, the **No** button does nothing when clicked on. I am using the same browser when testing locally versus on the development server.
My initial thought is that perhaps a Validator is preventing the PostBack from firing. I do use a couple of Validators on another section of the page, but they are all assigned to a specific Validation Group which the **No** LinkButton is not assigned to. However the problem is why it would work locally on not on the development server.
Any ideas?
|
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. Otherwise a "works on my machine" error is kind of hard to debug without being present and knowing the configurations of DEV vs PROD.
|
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, they were the ones that had CausesValidation explicity set (I only put it in for the ones where I would make that true). Adding CausesValidation="false" to all the other linkbuttons allowed them to work correctly after I was authenticated.
Thanks for your comments everyone, it saved my day!
|
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 catch it and instead stops execution as an unhandled exception.
The issue for me is that I can't replicate this issue anywhere else but in my full code. The call stack shows that the exception definitely occurs within my try/catch(Exception) block. The only thing I can think of is that there are a few ANTLR assembly calls that occur between my code and the code throwing the exception and this library does not have debugging enabled, so I can't step through it. I wonder if non-debuggable assemblies inhibit exception bubbling? The call stack looks like this; external assembly calls are in Antlr.Runtime:
```
Expl.Itinerary.dll!TimeDefLexer.mTokens() Line 1213 C#
Antlr3.Runtime.dll!Antlr.Runtime.Lexer.NextToken() + 0xfc bytes
Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.FillBuffer() + 0x22c bytes
Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.LT(int k = 1) + 0x68 bytes
Expl.Itinerary.dll!TimeDefParser.prog() Line 109 + 0x17 bytes C#
Expl.Itinerary.dll!Expl.Itinerary.TDLParser.Parse(string Text = "", Expl.Itinerary.IItinerary Itinerary = {Expl.Itinerary.MemoryItinerary}) Line 17 + 0xa bytes C#
```
The code snippet from the bottom-most call in Parse() looks like:
```
try {
// Execution stopped at parser.prog()
TimeDefParser.prog_return prog_ret = parser.prog();
return prog_ret == null ? null : prog_ret.value;
}
catch (Exception ex) {
throw new ParserException(ex.Message, ex);
}
```
To me, a catch (Exception) clause should've captured any exception whatsoever. Is there any reason why it wouldn't?
**Update:** I traced through the external assembly with Reflector and found no evidence of threading whatsoever. The assembly seems to just be a runtime utility class for ANTLR's generated code. The exception thrown is from the TimeDefLexer.mTokens() method and its type is NoViableAltException, which derives from RecognitionException -> Exception. This exception is thrown when the lexer cannot understand the next token in the stream; in other words, invalid input. This exception is SUPPOSED to happen, however it should've been caught by my try/catch block.
Also, the rethrowing of ParserException is really irrelevant to this situation. That is a layer of abstraction that takes any exception during parse and convert to my own ParserException. The exception handling problem I'm experiencing is never reaching that line of code. In fact, I commented out the "throw new ParserException" portion and still received the same result.
One more thing, I modified the original try/catch block in question to instead catch NoViableAltException, eliminating any inheritance confusion. I still received the same result.
Someone once suggested that sometimes VS is overactive on catching handled exceptions when in debug mode, but this issue also happens in release mode.
Man, I'm still stumped! I hadn't mentioned it before, but I'm running VS 2008 and all my code is 3.5. The external assembly is 2.0. Also, some of my code subclasses a class in the 2.0 assembly. Could a version mismatch cause this issue?
**Update 2:** I was able to eliminate the .NET version conflict by porting relevant portions of my .NET 3.5 code to a .NET 2.0 project and replicate the same scenario. I was able to replicate the same unhandled exception when running consistently in .NET 2.0.
I learned that ANTLR has recently released 3.1. So, I upgraded from 3.0.1 and retried. It turns out the generated code is a little refactored, but the same unhandled exception occurs in my test cases.
**Update 3:**
I've replicated this scenario in a [simplified VS 2008 project](http://www.explodingcoder.com/cms/files/TestAntlr-3.1.zip). Feel free to download and inspect the project for yourself. I've applied all the great suggestions, but have not been able to overcome this obstacle yet.
If you can find a workaround, please do share your findings. Thanks again!
---
Thank you, but VS 2008 automatically breaks on unhandled exceptions. Also, I don't have a Debug->Exceptions dialog. The NoViableAltException that is thrown is fully intended, and designed to be caught by user code. Since it is not caught as expected, program execution halts unexpectedly as an unhandled exception.
The exception thrown is derived from Exception and there is no multi-threading going on with ANTLR.
|
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 user code" and a callstack that looks like this:
```
[External Code]
> TestAntlr-3.1.exe!TimeDefLexer.mTokens() Line 852 + 0xe bytes C#
[External Code]
TestAntlr-3.1.exe!TimeDefParser.prog() Line 141 + 0x14 bytes C#
TestAntlr-3.1.exe!TestAntlr_3._1.Program.ParseTest(string Text = "foobar;") Line 49 + 0x9 bytes C#
TestAntlr-3.1.exe!TestAntlr_3._1.Program.Main(string[] args = {string[0x00000000]}) Line 30 + 0xb bytes C#
[External Code]
```
If you right click in the callstack window and run turn on show external code you see this:
```
Antlr3.Runtime.dll!Antlr.Runtime.DFA.NoViableAlt(int s = 0x00000000, Antlr.Runtime.IIntStream input = {Antlr.Runtime.ANTLRStringStream}) + 0x80 bytes
Antlr3.Runtime.dll!Antlr.Runtime.DFA.Predict(Antlr.Runtime.IIntStream input = {Antlr.Runtime.ANTLRStringStream}) + 0x21e bytes
> TestAntlr-3.1.exe!TimeDefLexer.mTokens() Line 852 + 0xe bytes C#
Antlr3.Runtime.dll!Antlr.Runtime.Lexer.NextToken() + 0xc4 bytes
Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.FillBuffer() + 0x147 bytes
Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.LT(int k = 0x00000001) + 0x2d bytes
TestAntlr-3.1.exe!TimeDefParser.prog() Line 141 + 0x14 bytes C#
TestAntlr-3.1.exe!TestAntlr_3._1.Program.ParseTest(string Text = "foobar;") Line 49 + 0x9 bytes C#
TestAntlr-3.1.exe!TestAntlr_3._1.Program.Main(string[] args = {string[0x00000000]}) Line 30 + 0xb bytes C#
[Native to Managed Transition]
[Managed to Native Transition]
mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args) + 0x39 bytes
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() + 0x2b bytes
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) + 0x3b bytes
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x81 bytes
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x40 bytes
```
The debugger's message is telling you that an exception originating outside your code (from NoViableAlt) is going through code you own in TestAntlr-3.1.exe!TimeDefLexer.mTokens() without being handled.
The wording is confusing, but it does not mean the exception is uncaught. The debugger is letting you know that code you own mTokens()" needs to be robust against this exception being thrown through it.
Things to play with to see how this looks for those who didn't repro the problem:
* Go to Tools/Options/Debugging and
turn off "Enable Just My code
(Managed only)". or option.
* Go to Debugger/Exceptions and turn off "User-unhandled" for
Common-Language Runtime Exceptions.
|
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 propagates out of your code and out to a stack frame associated with a method call that exists in an assembly which is "NOT YOUR CODE" (for example, Antlr), that is considered "unhandled". I turn off that Enable Just My Code feature for this reason. But, if you ask me, this is lame... let's say you do this:
```
ExternalClassNotMyCode c = new ExternalClassNotMyCode();
try {
c.doSomething( () => { throw new Exception(); } );
}
catch ( Exception ex ) {}
```
doSomething calls your anonymous function there and that function throws an exception...
Note that this is an "unhandled exception" according to Visual Studio if "Enable Just My Code" is on. Also, note that it stops as if it were a breakpoint when in debug mode, but in a non-debugging or production environment, the code is perfectly valid and works as expected. Also, if you just "continue" in the debugger, the app goes on it's merry way (it doesn't stop the thread). It is considered "unhandled" because the exception propagates through a stack frame that is NOT in your code (i.e. in the external library). If you ask me, this is lousy. Please change this default behavior Microsoft. This is a perfectly valid case of using Exceptions to control program logic. Sometimes, you can't change the third party library to behave any other way, and this is a very useful way to accomplish many tasks.
Take MyBatis for example, you can use this technique to stop processing records that are being collected by a call to SqlMapper.QueryWithRowDelegate.
|
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
Content-type: application/octet-stream
File A contents
--sub_boundary
Content-type: application/octet-stream
File B contents
--sub_boundary
--main_boundary--
```
(Note: I have indented the sub-parts only to make it more readable for this post.)
I'm not very fluent in PHP and would like to get some help/pointers to figure out how to receive this kind of multipart form request in PHP code. I have once written some code where I received a standard HTML form and then I could access the form elements by using their name as index key in the `$HTTP_GET_VARS` array, but in this case there are no form element names, and the form data parts are not linear (i.e. sub parts = multilevel array).
Grateful for any help!
/Robert
|
`$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_raw_post_data` setting is true in *php.ini*, the data should be in `$HTTP_RAW_POST_DATA`. Also, the whole request should show up when reading *php://input*.
|
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 comment yet but this is intened to complement pilsetnieks answer
|
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 inside `#ifdef -- #endif` pairs. I can see nothing less ugly than that.
|
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);
```
Then, a java source file should be found in a sub-directory of the target directory.
Does anyone know such a framework?
---
**EDIT**:
1. I really need the source files.
2. I also would like to fill out the code of the methods.
3. I'm looking for a high-level abstraction, not direct bytecode manipulation/generation.
4. I also need the "structure of the class" in a tree of objects.
5. The problem domain is general: to generate a large amount of very different classes, without a "common structure".
---
**SOLUTIONS**
I have posted 2 answers based in your answers... [with CodeModel](https://stackoverflow.com/questions/121324/a-java-api-to-generate-java-source-files#136010) and [with Eclipse JDT](https://stackoverflow.com/questions/121324/a-java-api-to-generate-java-source-files#136016).
I have used [CodeModel](http://codemodel.java.net/) in my solution, :-)
|
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, and it's part of the XJC jars. You can use it just for the CodeModel.
Grab it from <http://codemodel.java.net/>
|
**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("./target/classes");
file.mkdirs();
cm.build(file);
```
I can get this output:
```
package foo;
public class Bar {
int foo() {
return 5;
}
}
```
|
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 the front end calling [EJBs](http://en.wikipedia.org/wiki/Enterprise_JavaBean) using [TopLink](http://en.wikipedia.org/wiki/TopLink) vs ADF Business Components through [RMI](http://en.wikipedia.org/wiki/Java_remote_method_invocation) in terms of scalability as the migration from Struts to ADF will also encompass PL/SQL and Oracle Forms, thus increasing the user count drastically?
|
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 about using either TopLink or ADF business components (BC4J) for the data access layer.
I would say that if you are planning on using an RMI based application, that TopLink would probably be better, mainly because the power of BC4J is in its view objects, which don't serialize (hence translating those results into TopLink style value objects, anyway).
If you are doing a straight up and down web application and don't really care about EJBs and RMI then I think you'll find that BC4J offers a lot in the way of making standard web applications scale... Long story short, it maps SQL into view objects, which are basically smart datagrids that have very tunable behavior, which can be bound directly to [JSF](http://en.wikipedia.org/wiki/JavaServer_Faces) components of the Oracle ADF Faces, giving really good seamless RAD.
|
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 pretty good solutions.
However since you mention that the project also involves the migration of Oracle Forms, then it seems that ADF would be the best choice since Oracle seems to be positioning JDeveloper and ADF as the successor for Forms and Reports (see the [ADF Documentation targeting Forms and Designer Developers](http://www.oracle.com/technology/products/jdev/collateral/4gl/formsdesignerj2ee.html)).
|
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 disagree strongly with the 'accepted' answer). Those settings often includes **static code analysis rules** which are vitally important to enforce consistently for any user loading this project into his/her workspace.
* IDE specific settings recommandations must be written in a big README file (and versionned as well of course).
Rule of thumb for me:
You must be able to load a project into a workspace and have in it everything you need to properly set it up in your IDE and get going in minutes.
No additional documentation, wiki pages to read or what not.
Load it up, set it up, go.
|
.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 required for a developer to setup their IDE.
|
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 void Main(string[] args)
{
sampleStruct struct1 = new sampleStruct();
struct1.IntegerValue = 3;
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
sampleStruct struct2 = struct1;
Console.WriteLine();
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
Console.WriteLine("struct2.IntegerValue: {0}", struct2.IntegerValue);
struct1.IntegerValue = 5;
Console.WriteLine();
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
Console.WriteLine("struct2.IntegerValue: {0}", struct2.IntegerValue);
sampleClass class1 = new sampleClass();
class1.IntegerValue = 3;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
sampleClass class2 = class1;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
Console.WriteLine("class2.IntegerValue: {0}", class2.IntegerValue);
class1.IntegerValue = 5;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
Console.WriteLine("class2.IntegerValue: {0}", class2.IntegerValue);
Console.ReadKey();
}
}
struct sampleStruct
{
public int IntegerValue;
}
class sampleClass
{
public int IntegerValue;
}
}
```
|
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(c.Center.X);
c.Center.X = 42;
Console.WriteLine(c.Center.X);
}
```
Output:
```
0
42
```
Example with struct:
```
struct Point {
int double X;
int double Y;
}
class Circle {
PointStruct Center = new PointStruct() { X = 0, Y = 0; }
}
static void Main() {
Circle c = new Circle();
Console.WriteLine(c.Center.X);
c.Center.X = 42;
Console.WriteLine(c.Center.X);
}
```
Output:
```
0
0
```
|
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 the individual differences between a class and a struct, and pieces of it would serve as a *overview explanation*, in particular read the following items:
* Exists on stack or heap?
* Inheritance differences?
But I wouldn't link to that page as an *explanation* for what the differences are. It's like trying to describe what a car is, and just listing up all the parts that make up a car. You still need to understand the big picture to understand what a car is, and such a list would not be able to give you that.
In my mind, an explanation is something that tells you how something works, and then all the details follow naturally from that.
For instance, if you understand the basic underlying principles behind a value type vs. a reference type, a lot of the details on that page makes sense, *if you think about it*.
For instance, a value type (struct) is allocated where it is declared, inline, so to speak. It takes up stack space, or makes a class bigger in memory. A reference type, however, is a pointer, which has a fixed size, to *somewhere else in memory where the actual object is stored*.
With the above explanation, the following details makes sense:
* A struct variable cannot be null (ie. it always takes up the necessary space)
* An object reference can be null (ie. the pointer can point to nothing)
* A struct does not add pressure to garbage collection (garbage collection works with the heap, which is where objects live in that *somewhere else* space)
* Always have a default constructor. Since you can declare any value-type variable (which is basically a kind of struct), without giving it a value, there must be some underlying magic that clears up that space (remember I said it took up space anyhow)
Other things, like all the things related to inheritance, needs their own part in the explanation.
And so on...
|
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 is at <https://python-docx.readthedocs.org/en/latest/>
|
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 to have numerous properties that can be observed, where each property is defined using auto property syntax.
Basically I'm wondering if there is anything similar to either a get/set template or post get/set hook with class scope.
(I know the same end functionality can easily be achieved in slightly more verbose ways - I just hate duplication of a pattern)
|
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 explicitly.
|
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 further comments it looks like the network taffic is HTTP. Depending on the server, it probably has support for compression (especially with deflate/gzip). The problem then becomes on the client. If the client is a browser it probably already supports it. If your client is a webservices client or an [http client](http://hc.apache.org/httpclient-3.x/) check the documentation for that package to see if it is supported.
It looks like jakarta-commons httpclient may require you to manually do the compression. To enable this on the client side you will need to do something like
```
.addRequestHeader("Accept-Encoding","gzip,deflate");
```
|
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 connected to a dialup, you should compress as much as it absolutely possible.
If this is a WAN, you may find hardware solutions like [Riverbed's](http://www.riverbed.com) are more effective, as they work across a range of traffic, and don't require any changes to software.
I have a test case which shows the relative compression difference between [Deflate, Filtered, BZip2, and lzma](http://www.theeggeadventure.com/wikimedia/index.php/Java_Data_Compression). Simply plug in a sample of your data, and test the timing between two machines.
|
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(SQL);
ps.setInt(id);
ps.setString(plaintext);
ps.executeUpdate();
```
The plaintext is not expected to exceed 4000 characters but encrypting makes text longer. Our current approach to encryption uses dbms\_obfuscation\_toolkit.DESEncrypt() but we only process varchars. Will the following work?
```
FUNCTION encrypt(p_clob IN CLOB) RETURN CLOB
IS
encrypted_string CLOB;
v_string CLOB;
BEGIN
dbms_lob.createtemporary(encrypted_string, TRUE);
v_string := p_clob;
dbms_obfuscation_toolkit.DESEncrypt(
input_string => v_string,
key_string => key_string,
encrypted_string => encrypted_string );
RETURN UTL_RAW.CAST_TO_RAW(encrypted_string);
END;
```
I'm confused about the temporary clob; do I need to close it? Or am I totally off-track?
Edit:
The purpose of the obfuscation is to prevent trivial access to the data. My other purpose is to obfuscate clobs in the same way that we are already obfuscating the varchar columns. The oracle sample code does not deal with clobs which is where my specific problem lies; encrypting varchars (smaller than 2000 chars) is straightforward.
|
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,
src IN CLOB CHARACTER SET ANY_CS,
typ IN PLS_INTEGER,
key IN RAW,
iv IN RAW DEFAULT NULL);
DBMS_CRYPT.DECRYPT(
dst IN OUT NOCOPY CLOB CHARACTER SET ANY_CS,
src IN BLOB,
typ IN PLS_INTEGER,
key IN RAW,
iv IN RAW DEFAULT NULL);
```
|
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 VARCHAR2(8) := 'scottsco';
raw_key RAW(128) := UTL_RAW.CAST_TO_RAW(key_string);
encrypted_raw RAW(2048);
encrypted_string VARCHAR2(2048);
decrypted_raw RAW(2048);
decrypted_string VARCHAR2(2048);
error_in_input_buffer_length EXCEPTION;
PRAGMA EXCEPTION_INIT(error_in_input_buffer_length, -28232);
INPUT_BUFFER_LENGTH_ERR_MSG VARCHAR2(100) :=
'*** DES INPUT BUFFER NOT A MULTIPLE OF 8 BYTES - IGNORING
EXCEPTION ***';
double_encrypt_not_permitted EXCEPTION;
PRAGMA EXCEPTION_INIT(double_encrypt_not_permitted, -28233);
DOUBLE_ENCRYPTION_ERR_MSG VARCHAR2(100) :=
'*** CANNOT DOUBLE ENCRYPT DATA - IGNORING EXCEPTION ***';
-- 1. Begin testing raw data encryption and decryption
BEGIN
dbms_output.put_line('> ========= BEGIN TEST RAW DATA =========');
dbms_output.put_line('> Raw input : ' ||
UTL_RAW.CAST_TO_VARCHAR2(raw_input));
BEGIN
dbms_obfuscation_toolkit.DESEncrypt(input => raw_input,
key => raw_key, encrypted_data => encrypted_raw );
dbms_output.put_line('> encrypted hex value : ' ||
rawtohex(encrypted_raw));
dbms_obfuscation_toolkit.DESDecrypt(input => encrypted_raw,
key => raw_key, decrypted_data => decrypted_raw);
dbms_output.put_line('> Decrypted raw output : ' ||
UTL_RAW.CAST_TO_VARCHAR2(decrypted_raw));
dbms_output.put_line('> ');
if UTL_RAW.CAST_TO_VARCHAR2(raw_input) =
UTL_RAW.CAST_TO_VARCHAR2(decrypted_raw) THEN
dbms_output.put_line('> Raw DES Encyption and Decryption successful');
END if;
EXCEPTION
WHEN error_in_input_buffer_length THEN
dbms_output.put_line('> ' || INPUT_BUFFER_LENGTH_ERR_MSG);
END;
dbms_output.put_line('> ');
```
|
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 approach is similar between different frameworks, so I'm more interested in finding out the approach rather than getting bogged down in differences between the different frameworks.
If you are not aware of a good guide, then could you post bullet-point type steps to getting a hello-world running?, i.e.
1. Download XX
2. Write some code to do YY
3. Change file ZZ
4. Other steps...
Note: Just because I have a windows machine at home, I would prefer to run if this could be run on windows, but in the interest of a better answer, linux/mac based implementations are welcome.
|
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 very good JBoss documentation:
[Installation Guide](http://www.redhat.com/docs/manuals/jboss/jboss-eap-4.3/doc/Installation_Guide/html/index.html)
[Getting started](http://www.redhat.com/docs/manuals/jboss/jboss-eap-4.3/doc/Getting_Started/html/index.html)
[Configuration Guide](http://www.redhat.com/docs/manuals/jboss/jboss-eap-4.3/doc/Server_Configuration_Guide/html/index.html)
In general you could also just do the basic installation and change or try the pre-installed example applications.
I currently have JBoss installed (on windows). I develop with Eclipse and use the Java EE server integration to hot deploy or debug my code. After you get your first code running you realy should have a look at the ide integration since it makes development/deploy roundtrips so much faster.
|
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-Tomcat-Tutorial/) for installation instructions. Try installing it with eclipse and create a web project. This will generate some files for you that you can look at and edit. Also starting and stopping the application server is simpler.
|
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 ?? ()
```
The program has crashed with a standard signal 11, segmentation fault.
My application is a multi-threaded FastCGI C++ program running on FreeBSD 6.3, using pthread as the threading library.
It has been compiled with -g and all the symbol tables for my source are loaded, according to info sources.
As is clear, none of my actual code appears in the trace but instead the error seems to originate from standard pthread libraries. In particular, what is ?? () ????
**EDIT**: eventually tracked the crash down to a standard invalid memory access in my main code. Doesn't explain why the stack trace was corrupted, but that's a question for another day :)
|
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 return address.
|
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 be a tough bug to track down, you're gonna need to step through your code and try and narrow down when exactly the crash happens.
|
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.getNewspaceSize());
OracleRuntime.setMaxMemorySize(times *OracleRuntime.getMaxMemorySize());
OracleRuntime.setJavaStackSize(times *OracleRuntime.getJavaStackSize());
OracleRuntime.setThreadStackSize(times *OracleRuntime.getThreadStackSize());
```
This sample code multiplies by 2 memory status in oracle jvm.
Note: import oracle.aurora.vm.OracleRuntime; will be resolved on oracle jvm, found on "aurora.zip"
|
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 object name query1.
|
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 do you handle this?
|
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 environment properties).
|
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)
The advantage of keeping the developer's specific configs in source control makes it easy to migrate from one computer to another (eg. in the case of a hardware failure or upgrade). Its a simple svn co [repos] and ant
|
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 header. After I decode the header I read the pixel values into the "pixels" array. So far I have not had more than 16bpp, so I'm okay. But what if I have 32bpp?
What I want to do is have the type of pixels be determined at runtime. I want to do this after I read the bit depth out of the header and before I copy the pixel data into memory. Any ideas?
|
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 Pixel class with 32-bit and 16-bit sub-classes, overriding various operators up the wazoo, but this incurs a lot of overhead, is tricky to get right and even trickier to determine if its right. Alternately you could create proxy classes for your pixel data (which would contain the ushort[,] or uint32[,] arrays and would have all the necessary accessors to be useful). The downside there is that you would likely end up with a lot of special case code in the ImageData class which executed one way or the other depending on some 16-bit/32-bit mode flag.
The better solution, I think, would be to sub-class ImageData into 16-bit and 32-bit classes, and use a factory method to create instances. E.g. ImageData is the base class, ImageData16bpp and ImageData32bpp are sub-classes, static method ImageData.Create(string imageFilename) is the factory method which creates either ImageData16bpp or ImageData32bpp depending on the header data. For example:
```
public static ImageData Create(string imageFilename)
{
// ...
ImageDataHeader imageHeader = ParseHeader(imageFilename);
ImageData newImageData;
if (imageHeader.bpp == 32)
{
newImageData = new ImageData32(imageFilename, imageHeader);
}
else
{
newImageData = new ImageData16(imageFilename, imageHeader);
}
// ...
return newImageData;
}
```
|
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%>` are where template substitution occurs. My problem is that the item name can contain any character, including single and double quotes. Currently, if it contains single quotes it breaks the JavaScript code.
My first thought was to use the template language's function to JavaScript-escape the item name, which just escapes the quotes. That will not fix the case of the string containing double quotes which breaks the HTML of the link. How is this problem normally addressed? Do I need to HTML-escape the entire onClick handler?
If so, that would look really strange since the template language's escape function for that would also HTMLify the parentheses, quotes, and semicolons...
This link is being generated for every result in a search results page, so creating a separate method inside a JavaScript tag is not possible, because I'd need to generate one per result.
Also, I'm using a templating engine that was home-grown at the company I work for, so toolkit-specific solutions will be of no use to me.
|
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 < 127, and \uXXXX for [Unicode](http://en.wikipedia.org/wiki/Unicode), so armed with this knowledge you can create a robust *JSEncode* function for all characters that are out of the usual whitelist.
For example,
```
<a href="#" onclick="SelectSurveyItem('<% JSEncode(itemid) %>', '<% JSEncode(itemname) %>'); return false;">Select</a>
```
|
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
result = json.dumps(jsString)
```
PHP
```
$result = strtr($jsString, array('\\' => '\\\\', "'" => "\\'", '"' => '\\"',
"\r" => '\\r', "\n" => '\\n' ));
```
Ruby on Rails
```
<%= escape_javascript(jsString) %>
```
|
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 want to monitor the memory usage at a fine level of detail over a long time, and have the graph show both the whole time frame and the level of detail. I need a small sampling interval, and a large graph.
|
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 second intervals (this will generate 2\*60\*24 samples)
* for 1 week : I would use 1 minute intervals (this will generate 60\*24\*7 samples)
With these sampling intervals Perfmon should have no problem generating a nice graphical output of your counters.
|
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 out the [FAQ](http://www.jfree.org/jfreechart/faq.html)).
They also have a port to [.NET](http://www.ujihara.jp/jbyjsharp/jfreechart/) however I have never used it.
Hope that helps.
|
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: The answer I accepted applies directly to compilers I'm targeting (which is why I chose it). However, there are other very good, more portable answers here.
|
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 _byteswap_uint64(unsigned __int64 value);
```
8 bit numbers (chars) don't need to be converted.
Also these are only defined for unsigned values they work for signed integers as well.
For floats and doubles it's more difficult as with plain integers as these may or not may be in the host machines byte-order. You can get little-endian floats on big-endian machines and vice versa.
Other compilers have similar intrinsics as well.
In **GCC** for example you can directly call [some builtins as documented here](https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html):
```
uint32_t __builtin_bswap32 (uint32_t x)
uint64_t __builtin_bswap64 (uint64_t x)
```
(no need to include something). Afaik bits.h declares the same function in a non gcc-centric way as well.
16 bit swap it's just a bit-rotate.
Calling the intrinsics instead of rolling your own gives you the best performance and code density btw..
|
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(T) - k - 1];
return dest.u;
}
```
usage: `swap_endian<uint32_t>(42)`.
|
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 Codepro](https://developers.google.com/java-dev-tools/codepro/doc/)
|
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 browsers?
|
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 in this regard.
|
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, ask a question here! There are lots of great minds.
For JS, there are several frameworks that take care of implementing cross-browser behaviour, such as [jQuery](http://jquery.com/) (used on this site).
|
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 (commandLink && commandLink.onclick) {
var commandLinkOnclick = commandLink.onclick;
commandLink.onclick = function() {
var result = confirm('Do you really want to <c:out value="${msgs.deleteText}" />?');
if (result) {
return commandLinkOnclick();
}
return false;
}
}
}
</script>
```
Other Javascript actions (like validating form input etc) could be performed by replacing the call to `confirm()` with a call to another function.
|
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 variable. However, given the construction of the data vs the question, I'm torn as to which answer to accept. True the question only wants the first character trimmed off not the last (if anny), however, there would never be a "," at the end of the data. So, with that said, I'm going to accept the first answer that that said to use StartTrim assigned to a new variable.*
|
```
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 text in the box, select it, copy it, and then delete the textArea. In most cases this textArea wont even flash onto the screen.
For security reasons, browsers will only allow you copy if a user takes some kind of action (ie. clicking a button). One way to do this would be to add an onClick event to a html button that calls a method which copies the text.
A full example:
```
function copier(){
document.getElementById('myText').select();
document.execCommand('copy');
}
```
```
<button onclick="copier()">Copy</button>
<textarea id="myText">Copy me PLEASE!!!</textarea>
```
|
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-into-clipboard/clipboard.swf';
if(!document.getElementById(flashId)) {
var div = document.createElement('div');
div.id = flashId;
document.body.appendChild(div);
}
document.getElementById(flashId).innerHTML = '';
var content = '<embed src="' +
clipboardSWF +
'" FlashVars="clipboard=' + encodeURIComponent(text) +
'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
document.getElementById(flashId).innerHTML = content;
}
```
The only disadvantage is that this requires Flash to be enabled.
The source is currently dead: <http://bravo9.com/journal/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2-cc6c-4ebf-9724-d23e8bc5ad8a/> (and so is its [Google cache](http://webcache.googleusercontent.com/search?q=cache:DaMt_LgPWUYJ:rokr-blargh.appspot.com/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2cc6c4ebf9724d23e8bc5ad8a%20&cd=1&hl=en&ct=clnk&gl=us))
|
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 comment:
> Can I just say, please don't cast the
> return value of malloc? It is not
> required and can hide errors.
I agree that the cast is not required in C. It is mandatory in C++, so I usually add them just in case I have to port the code in C++ one day.
However, I wonder how casts like this can hide errors. Any ideas?
# Edit:
Seems like there are very good and valid arguments on both sides. Thanks for posting, folks.
|
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 is written about this, a quick google search will turn up more detailed explanations.
## edit
It has been argued that
```
TYPE * p;
p = (TYPE *)malloc(n*sizeof(TYPE));
```
makes it obvious when you accidentally don't allocate enough memory because say, you thought `p` was `TYPe` not `TYPE`, and thus we should cast malloc because the advantage of this method overrides the smaller cost of accidentally suppressing compiler warnings.
I would like to point out 2 things:
1. you should write `p = malloc(sizeof(*p)*n);` to always ensure you malloc the right amount of space
2. with the above approach, you need to make changes in 3 places if you ever change the type of `p`: once in the declaration, once in the `malloc`, and once in the cast.
In short, I still personally believe there is no need for casting the return value of `malloc` and it is certainly not best practice.
|
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.
The real reason that could make you **not** write the cast is that the C compiler already silently cast a `void *` into whatever pointer type you want, and so, doing it yourself is overkill and useless.
If you want to have type safety, you can either switch to C++ or write your own wrapper function, like:
```
int * malloc_Int(size_t p_iSize) /* number of ints wanted */
{
return malloc(sizeof(int) * p_iSize) ;
}
```
# C++
Sometimes, even in C++, you have to make profit of the malloc/realloc/free utils. Then you'll have to cast. But you already knew that. Using static\_cast<>() will be better, as always, than C-style cast.
And in C, you could override malloc (and realloc, etc.) through templates to achieve type-safety:
```
template <typename T>
T * myMalloc(const size_t p_iSize)
{
return static_cast<T *>(malloc(sizeof(T) * p_iSize)) ;
}
```
Which would be used like:
```
int * p = myMalloc<int>(25) ;
free(p) ;
MyStruct * p2 = myMalloc<MyStruct>(12) ;
free(p2) ;
```
and the following code:
```
// error: cannot convert ‘int*’ to ‘short int*’ in initialization
short * p = myMalloc<int>(25) ;
free(p) ;
```
won't compile, so, *no problemo*.
All in all, in pure C++, you now have no excuse if someone finds more than one C malloc inside your code...
:-)
# C + C++ crossover
Sometimes, you want to produce code that will compile both in C and in C++ (for whatever reasons... Isn't it the point of the C++ `extern "C" {}` block?). In this case, C++ demands the cast, but C won't understand the static\_cast keyword, so the solution is the C-style cast (which is still legal in C++ for exactly this kind of reasons).
Note that even with writing pure C code, compiling it with a C++ compiler will get you a lot more warnings and errors (for example attempting to use a function without declaring it first won't compile, unlike the error mentioned above).
So, to be on the safe side, write code that will compile cleanly in C++, study and correct the warnings, and then use the C compiler to produce the final binary. This means, again, write the cast, in a C-style cast.
|
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.