Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a static library that I want to distribute that has includes Foo.c/h and someone picks it up and includes my static library in their application.
Say they also have Foo.c/h in their application. Will they have linking errors? | The name of a source file is not significant in the linking process.
If the file has the same contents, then you'll have a problem, assuming that the .c file contains exported symbols (e.g. non-static or non-template functions, or extern variables). | It depends. If the foo.c and foo.h define the same functions and/or variables, then yes, there will be multiple definition errors. If they just have the same file names, but contain different code, there will be no problem. | Static libraries, linking and dependencies | [
"",
"c++",
"linker",
""
] |
I am trying to download a file over HTTPS and I just keep running into a brick wall with correctly setting Cookies and Headers.
Does anyone have/know of any code that I can review for doing this correctly ? i.e. download a file over https and set cookies/headers ?
Thanks! | I did this the other day, in summary you need to create a HttpWebRequest and HttpWepResponse to submit/receive data. Since you need to maintain cookies across multiple requests, you need to create a cookie container to hold your cookies. You can set header properties on request/response if needed as well....
Basic Concept:
```
Using System.Net;
// Create Cookie Container (Place to store cookies during multiple requests)
CookieContainer cookies = new CookieContainer();
// Request Page
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.amazon.com");
req.CookieContainer = cookies;
// Response Output (Could be page, PDF, csv, etc...)
HttpWebResponse resp= (HttpWebResponse)req.GetResponse();
// Add Response Cookies to Cookie Container
// I only had to do this for the first "login" request
cookies.Add(resp.Cookies);
```
The key to figuring this out is capturing the traffic for real request. I did this using Fiddler and over the course of a few captures (almost 10), I figured out what I need to do to reproduce the login to a site where I needed to run some reports based on different selection critera (date range, parts, etc..) and download the results into CSV files. It's working perfect, but Fiddler was the key to figuring it out.
<http://www.fiddler2.com/fiddler2/>
Good Luck.
Zach | This fellow wrote an application to download files using HTTP:
<http://www.codeproject.com/KB/IP/DownloadDemo.aspx>
Not quite sure what you mean by setting cookies and headers. Is that required by the site you are downloading from? If it is, what cookies and headers need to be set? | Download a file over HTTPS C# - Cookie and Header Prob? | [
"",
"c#",
"asp.net",
"https",
""
] |
When running the following code, which is an easy problem, the Python interpreter works weirdly:
```
n = input()
for i in range(n):
testcase = raw_input()
#print i
print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]
```
The problem consists in taking n strings and deleting a single character from them.
For example, given the string "4 PYTHON", the program should output "PYTON".
The code runs ok, but if I take out the comment mark, the statement print i makes the interpreter give an unexpected EOF while parsing. Any idea on why this happens?
EDIT: I'm working under Python 2.5, 32 bits in Windows. | I am yet another who has no trouble with or without the commented print statement. The input function on the first line is no problem as long as I give it something Python can evaluate. So the most likely explanation is that when you are getting that error, you have typed something that isn't a valid Python expression.
Do you *always* get that error? Can you post a transcript of your interactive session, complete with stack trace? | Are you sure that the problem is the print i statement? The code works as
expected when I uncomment that statement and run it. However, if I forget to
enter a value for the first input() call, and just enter "4 PYTHON" right off
the bat, then I get:
```
"SyntaxError: unexpected EOF while parsing"
```
This happens because input() is not simply storing the text you enter, but also
running eval() on it. And "4 PYTHON" isn't valid python code. | Weird program behaviour in Python | [
"",
"python",
""
] |
I read through [Crockford's JavaScript best practise](http://javascript.crockford.com/code.html), and he stated:
> There is no need to use the language or type attributes. It is the server, not the script tag, that determines the MIME type.
But I've never seen anyone omit the `type` attribute in their `<script>` tag...
Do you guys include `type`? Why (not)? | You misunderstood what Crockford meant, he didn't say the `type` attribute is completely invalid, it's just that it's incorrect. The MIME type for JavaScript is `application/javascript` (or `application/ecmascript` I can't remember right now).
The general usage though is that is `text/javascript` which browsers will handle without any problems as that's been the *defacto* standard for a long time.
In regards to the `<script src="..."` tag it is redundant because the server determines the MIME type of the file and that is what the browser will then deal with.
He best explains it in one of his videos on YUI Theater (<http://developer.yahoo.com/yui/theater/>). I don't remember exactly which one he talks about this, I think it was in the advanced JavaScript series (but yeah I've watched them all a few times so they kind of blur into each other).
So if you want to write valid XHTML you need to provide something like `text/javascript` but it's not the *official* MIME type of the JavaScript language. | If the script is embedded in the page, Crockford's advice isn't relevant.
If you want to write standard-conforming HTML, then it still isn't relevant.
He's generally spot on about everything to do with JavaScript, so he's probably just giving you some background information, rather than telling you what to do.
Having followed the link, that page is showing its age a little. For example:
> `<script src=filename.js>` tags should
> be placed as late in the body as
> possible. This reduces the effects of
> delays imposed by script loading on
> other page components.
The "modern" approach is to use jQuery (or similar style) to perform processing when the document has loaded, which automatically solves that problem, allowing you to put the script tag wherever it makes logical sense. | Should I include type="text/javascript" in my SCRIPT tags? | [
"",
"javascript",
""
] |
I have an image/pixbuf that I want to draw into a gtk.DrawingArea and refresh frequently, so the blitting operation has to be fast. Doing it the easy way:
```
def __init__(self):
self.drawing_area = gtk.DrawingArea()
self.image = gtk.gdk.pixbuf_new_from_file("image.png")
def area_expose_cb(self, area, event):
self.drawing_area.window.draw_pixbuf(self.gc, self.image, 0, 0, x, y)
```
However leads to very slow performance, likely caused by the pixbuf not being in the displays color format.
I had no success with Cairo either, as it seems limited to 24/32bit formats and doesn't have a 16bit format (FORMAT\_RGB16\_565 is unsupported and deprecated).
What alternatives are there to drawing pictures quickly in Gtk+? | Try creating Pixmap that uses the same colormap as your drawing area.
```
dr_area.realize()
self.gc = dr_area.get_style().fg_gc[gtk.STATE_NORMAL]
img = gtk.gdk.pixbuf_new_from_file("image.png")
self.image = gtk.gdk.Pixmap(dr_area.window, img.get_width(), img.get_height())
self.image.draw_pixbuf(self.gc, img, 0, 0, 0, 0)
```
and drawing it to the screen using
```
dr_area.window.draw_drawable(self.gc, self.image, 0, 0, x, y, *self.image.get_size())
``` | Are you really not generating enough raw speed/throughput? Or is it just that you're seeing flickering?
If it's the latter, perhaps you should investigate double buffering for perfomring your updates instead? Basically the idea is to draw to an invisible buffer then tell the graphics card to use the new buffer.
Maybe check out this page which has some [information on double buffering](http://xfc.xfce.org/docs/howto/html/drawingarea.html). | What is the fastest way to draw an image in Gtk+? | [
"",
"python",
"gtk",
"pygtk",
"cairo",
""
] |
I would like to be able to pass parameters in the **installation** of the service. I have modified the C# code of the class that inherit from Installer... My problem is the InstallUtil.exe doesn't work with parameters (well not as I know).
Any suggestion? | We have the same scenario and it works. You've to pass the parameters as follows
```
InstallUtil.exe /Param1="Value" /Param2="Value" "Path to your exe"
```
Then you've to override Install method on your installer
```
public override void Install(System.Collections.IDictionary stateSaver)
{
var lParam1 = GetParam("Param1");
}
private string GetParam(string pKey)
{
try
{
if (this.Context != null)
{
if (this.Context.Parameters != null)
{
string lParamValue = this.Context.Parameters[pKey];
if (lParamValue != null)
return lParamValue;
}
}
}
catch (Exception)
{
}
return string.Empty;
}
``` | Actually it can be done with InstallUtil.exe, the .NET installer utility that comes with the .NET Framework.
Take a look at this [CodeProject](http://www.codeproject.com/KB/dotnet/Windows_Service_Installer.aspx) article. | How to register a .Net service with a command line + parameters? | [
"",
"c#",
".net-3.5",
"service",
""
] |
I have a WCF service where Im building up a block of XML using an XmlWriter. Once complete I want to have the WCF return it as an XmlDocument.
But if I have XmlDocument in the [OperationContract] it doesnt work:
```
[OperationContract]
XmlDocument GetNextLetter();
```
The WCF test utility gives:
> System.Runtime.Serialization.InvalidDataContractException: Type 'System.Xml.XmlDocument' cannot be serialized. | If you are using .Net 3.5 then you can try returning [XElement](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx) instead - this implements [IXmlSerializable](http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx), which is the missing ingredient needed to make it work with DataContractSerializer. | append xmlserializer on what you did in the operational contract
```
[OperationContract,XmlSerializerFormat]
XmlDocument GetNextLetter();
```
this will do it ! | wcf return an XmlDocument? | [
"",
"c#",
"xml",
"wcf",
"xmldocument",
""
] |
I want to be able to supply the data for Reporting Services to use to generate a report (for example an XML Serialized object, but it doesn't have to be). Is this possible? If so, how would I do that? | You can bind all sorts of things to the datasource property of the [report viewer control](http://www.gotreportviewer.com/).
The server always uses the data source that is defined in the report itself. So, if you have to use the report server, you have to funnel any dynamic data through the database. | Just recently implemented a solution where we pulled-down data from a database via a WCF service, mapped it to a complex type (class with several properties, three of which were List), and used that as an object data source to display a report in a ReportViewer control on the client. This did not require Reporting Services at all. | Is it possible to supply an Object's data to Reporting Services via its' web service for it to use to generate reports | [
"",
"c#",
"reporting-services",
""
] |
This works great in PHP
```
date_default_timezone_set('my/timezone');
$actualDate = date('Y-m-d');
```
Now when doing queries, I like to do
```
INSERT INTO articles (title, insert_date) VALUES ('My Title', now())
```
The problem with this is the `now()` in the MySQL is different to what it would be had it been calculated in PHP (and therefore against the timezone being set).
Is there a way, say a SQL query, to set the default timezone for MySQL?
Thanks | <http://dev.mysql.com/doc/refman/5.1/en/time-zone-support.html>
> If you have the SUPER privilege, you can set the global server time zone value at runtime with this statement:
>
> `mysql> SET GLOBAL time_zone = timezone;`
>
> Per-connection time zones. Each client that connects has its own time zone setting, given by the session time\_zone variable. Initially, the session variable takes its value from the global time\_zone variable, but the client can change its own time zone with this statement:
>
> `mysql> SET time_zone = timezone;` | Something you could try is to store all of your date/times in UTC. So, you would use
```
date_default_timezone_set('UTC');
$actualDate = date('Y-m-d');
```
and
```
INSERT INTO articles (title, insert_date) VALUES ('My Title', UTC_TIMESTAMP())
```
Then you would convert the UTC date/time to the timezone of the user before displaying it. | Is there an equivalent to PHP's `date_default_timezone_set()` that works in MySQL? | [
"",
"php",
"mysql",
""
] |
I'm using the System.Management.Automation API to call PowerShell scripts a C# WPF app. In the following example, how would you change the start directory ($PWD) so it executes foo.ps1 from C:\scripts\ instead of the location of the .exe it was called from?
```
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
using (Pipeline pipeline = runspace.CreatePipeline())
{
pipeline.Commands.Add(@"C:\scripts\foo.ps1");
pipeline.Invoke();
}
runspace.Close();
}
``` | You don't need to change the `System.Environment.CurrentDirectory` to change the working path for your PowerShell scripts. It can be quite dangerous to do this because this may have unintentional side effects if you're running other code that is sensitive to your current directory.
Since you're providing a `Runspace`, all you need to do is set the `Path` properties on the `SessionStateProxy`:
```
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
runspace.SessionStateProxy.Path.SetLocation(directory);
using (Pipeline pipeline = runspace.CreatePipeline())
{
pipeline.Commands.Add(@"C:\scripts\foo.ps1");
pipeline.Invoke();
}
runspace.Close();
}
``` | Setting `System.Environment.CurrentDirectory` ahead of time will do what you want.
Rather than adding `Set-Location` to your scrip, you should set `System.Environment.CurrentDirectory` *any time **before** opening* the Runspace. It will inherit whatever the CurrentDirectory is when it's opened:
```
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
System.Environment.CurrentDirectory = "C:\\scripts";
runspace.Open();
using (Pipeline pipeline = runspace.CreatePipeline())
{
pipeline.Commands.Add(@".\foo.ps1");
pipeline.Invoke();
}
runspace.Close();
}
```
And remember, `Set-Location` doesn't set the .net framework's `CurrentDirectory` so if you're calling .Net methods which work on the "current" location, you need to set it yourself. | Setting the start dir when calling Powershell from .NET? | [
"",
"c#",
"powershell",
""
] |
I have a custom Javascript object that I create with `new`, and assign properties to based on creation arguments:
```
function MyObject(argument) {
if (argument) {
this.prop = "foo";
}
}
var objWithProp = new MyObject(true); // objWithProp.prop exists
var objWithoutProp = new MyObject(false); // objWithoutProp.prop does not exist
```
What's the correct way to test for the existence of the `prop` property of the objects? I've seen the following ways used, but I'm not sure if any of these ways is the best way:
* `if (obj.prop) {}`
* `if (obj.hasOwnProperty("prop")) {}`
* `if ("prop" in obj) {}`
Specifically, I'm only interested in testing if the property is explicitly defined for this object, not in the prototype chain. In addition, the value will never be set to `null` or `undefined`, but it could be something like an empty object or array. However, if you want to include what the correct way is if those could be the case, feel free. | `hasOwnProperty` is *exactly* what you're looking for, since you specify "if the property is explicitly defined for this object, not in the prototype chain". Per <https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty> , "This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain." -- seems to exactly match your requirement! | If you are looking for a property defined in an object, you can use hasOwnProperty method of the object. like this:
```
myObject = new MyObject();
// some code
if ( myObject.hasOwnProperty('prop') ) {
// prop exists
}
```
but this is only to know if such a property is defined in object itself, but not its parents. so if such property is inherited by the object, you can not test its existence like this.
the other way is to test the property against undefined value. like this:
```
if ( myObject.prop !== undefined ) {
// prop exists
}
```
remember to use the !== operator instead of != because != will not differ between null and undefined, but !== does. so if your object has a property but the value is null, != will not help you. so this test:
```
if ( myObject.prop ) {
}
```
might have wrong results if "prop" has a false or null value. but by comparing to undefined with !== operator, you can be sure that null/false values will not confuse you. | What's the correct way to test for existence of a property on a JavaScript Object? | [
"",
"javascript",
"object",
"properties",
""
] |
I have a multithreaded application (C++) where I need to increment/change a series of values.
If I use a series of Interlocked operations, are they considered to be a single atomic operation ? Like in this example:
```
InterlockedIncrement(&value1);
InterlockedIncrement(&value2);
InterlockedExchange(&oldValue, newValue);
```
Or it would be better to us a lock to perform the synchronization ? Like this:
```
EnterCriticalSection(&cs);
value1++;
value2++;
oldValue = newValue;
LeaveCriticalSection(&cs);
```
I think a lock is required, but I'm not sure... it's very important that all the values to be either in the old state, or in the new one, together. | [`InterlockedIncrement`](http://msdn.microsoft.com/en-us/library/ms683614(VS.85).aspx) itself is an atomic operation but series of `InterLockedIncrement` are not atomic together. If your requirement is to get the atomicity for series of operation then you can use critical section. | If the values must be fully executed to leave a consistent state, you will need to use the critical section. For example, if your values were actually something like
```
President = Barack Obama;
VP = Joe Biden;
```
and you weren't using a critical section, you could be in a situation where Barack Obama was put in as President and Dick Cheney was VP if you had some kind of interruption or context switch between the execution of those statements. This state is inconsistent I think we would all agree :)
However, if you are doing something like
```
Debit $5 from account;
Credit $2 to account;
```
and the result of each operation left a complete state, the interlock will be fine. | Can I use interlocked operations to update multiple values to avoid locking a critical section/mutex? | [
"",
"c++",
"multithreading",
"synchronization",
"interlocked-increment",
""
] |
I have a simple badly behaved server (written in Groovy)
```
ServerSocket ss = new ServerSocket(8889);
Socket s = ss.accept()
Thread.sleep(1000000)
```
And a client who I want to have timeout (since the server is not consuming it's input)
```
Socket s = new Socket("192.168.0.106", 8889)
s.setSoTimeout(100);
s.getOutputStream.write( new byte[1000000] );
```
However, this client blocks forever. How do I get the client to timeout?
THANKS!! | You could spawn the client in it's own thread and spin lock/wait(timeout long) on it to return. Possibly using a **Future** object to get the return value if the **Socket** is successful.
I do believe that the SO\_TIMEOUT setting for a Socket only effects the read(..) calls from the socket, not the write.
You might try using a **SocketChannel** (rather then Stream) and spawn another thread that also has a handle to that Channel. The other thread can asynchronously close that channel after a certain timeout of it is blocked. | The socket timeout is at the TCP level, not at the application level. The source machine TCP is buffering the data to be sent and the target machine network stack is acknowledging the data received, so there's no timeout. Also, different TCP/IP implementations handle these timeouts differently. Take a look at what's going on on the wire with [tcpdump](http://www.tcpdump.org/) (or [wireshark](http://www.wireshark.org/) if you are so unfortunate :) What you need is application level ACK, i.e. you need to define the protocol between client and the server. I can't comment on Java packages (you probably want to look at [nio](http://en.wikipedia.org/wiki/New_I/O)), but receive timeout on that ACK would usually be handled with [poll/select](http://www.cl.cam.ac.uk/cgi-bin/manpage?2+poll). | java/groovy socket write timeout | [
"",
"java",
"sockets",
"groovy",
""
] |
PHP's mkdir function only returns true and false. Problem is when it returns false.
If I'm running with error reporting enabled, I see the error message on the screen. I can also see the error message in the Apache log. But I'd like to grab the text of the message and do something else with it (ex. send to myself via IM). How do I get the error text?
**Update:** Following Ayman's idea, I came to this:
```
function error_handler($errno, $errstr) {
global $last_error;
$last_error = $errstr;
}
set_error_handler('error_handler');
if (!mkdir('/somedir'))
echo "MKDIR failed, reason: $last_error\n";
restore_error_handler();
```
However, I don't like it because it uses global variable. Any idea for a cleaner solution? | You can [suppress the warning](http://us.php.net/manual/en/language.operators.errorcontrol.php) and make use of [`error_get_last()`](http://us.php.net/manual/en/function.error-get-last.php):
```
if (!@mkdir($dir)) {
$error = error_get_last();
echo $error['message'];
}
``` | You could use exceptions:
Setup some code like so:
```
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
```
And then just do:
```
try {
mkdir('/somedir');
} catch(ErrorException $ex) {
echo "Error: " . $ex->getMessage();
}
```
That should do what you want.
If you want to preserve the php error handler, then after that try catch block, just call:
```
restore_error_handler()
``` | How to find a reason when mkdir fails from PHP? | [
"",
"php",
"error-reporting",
"mkdir",
""
] |
I have come up with the following method to determine is a database is up and running. This trys to open a database connection and if it fails it return false.
```
private static bool IsDatabaseConnectionUp(string connectionString)
{
System.Data.SqlClient.SqlConnection conn = null;
try
{
conn = new SqlConnection(connectionString);
conn.Open();
return conn.State == System.Data.ConnectionState.Open;
}
catch (SqlException)
{
// There was an error in opening the database so it is must not up.
return false;
}
finally
{
if (conn != null)
{
if (conn.State == System.Data.ConnectionState.Open)
{
conn.Close();
}
conn.Dispose();
}
}
}
```
Is this the best way to determine if this database is up? The reason I do not like this method it will rely on the timeout value, and will take as long as the timeout is set.
Is there a better way? | This really depends on exactly what you are trying to determine. If you are truly looking to determine if "The server is running, and able to be accessed", then I would say that this is most likely the most effective manner. The reason I say this is that the server itself could be up, but it might not be accepting connections, OR the connection that the application is using might be invalid (Incorrect username/password).
Therefore, given this, the timeout is a needed thing, as you want to validate true connection. If you want to simply see if the server is there, you could try pinging, but that simply tells you if the device is active, not necessarily if SQL Server is fully up and running, and available. | Since you're specifically looking at a SQLServer connection, take the connection string into a SqlConnectionStringBuilder object and change the timeout value.
```
SqlConnectionStringBuilder csb =
new SqlConnectionStringBuilder(connectionString);
csb.ConnectTimeout = 5;
string newConnectionString = csb.ToString();
```
This way you control the timeout value. Remember, don't set it too low or you'll get false positives. | In C# what is the best way to determine if a database is up and running? | [
"",
"c#",
".net",
"database",
"ado.net",
""
] |
I'm currently implementing memcached into my service but what keeps cropping up is the suggestion that I should also implement APC for caching of the actual code.
I have looked through the few tutorials there are, and the [PHP documentation](https://www.php.net/apc/) as well, but my main question is, how do I implement it on a large scale? PHP documentation talks about storing variables, but it isn't that detailed.
Forgive me for being uneducated in this area but I would like to know where in real sites this is implemented. Do I literally cache everything or only the parts that are used often, such as functions?
Thanks! | As you know PHP is an interpreted language, so everytime a request arrives to the server it need to open all required and included files, parse them and execute them. What APC offers is to skip the require/include and parsing steps (The files still have to be required, but are stored in memory so access is much much faster), so the scripts just have to be executed. On our website, we use a combination of APC and memcached. APC to speed up the above mentioned steps, and memcached to enable fast and distributed storing and accessing of both global variables (precomputed expensive function calls etc that can be shared by multiple clients for a certain amount of time) as well as session variables. This enables us to have multiple front end servers without losing any client state such as login status etc.
When it comes to what you should cache... well, that really depends on your application. If you have a need for multiple frontends somewhere down the line, I would try to go with memcached for such caching and storing, and use APC as an opcode cache. | APC is both an [opcode cache](http://www.google.com/search?q=opcode+cache) and a general data cache. The latter works pretty much like memcached, whereas the opcode cache works by caching the parsed php-files, so that they won't have to be parsed on each request. That can generally speed up execution time up quite a bit. | PHP APC, educate me | [
"",
"php",
"apc",
""
] |
I want to retrieve the first 10k bytes from a URL with curl (using PHP in my case). Is there a way to specify this? I thought CURLOPT\_BUFFERSIZE would do this, but it just appears to determine the size of a buffer that is reused until all of the content is retrieved. | This is how i do it in c++
```
int offset = 0;
int size = 10*1024;
char range[256];
curl_slist_s *pHeaders = NULL;
snprintf(range, 256, "Range: bytes=%d-%d", offset, offset+size-1);
pHeaders = curl_slist_append(pHeaders, range);
curl_easy_setopt(pCurlHandle, CURLOPT_HTTPHEADER, pHeaders);
curl_slist_free_all(pHeaders);
pHeaders = NULL;
```
Edit: Just found out you meant in php. Ill see if i can find out how to port it.
Think this should work in php:
```
$offset = 0;
$size = 10*1024;
$a = $offset;
$b = $offset + $size-1;
curl_easy_setopt(curlHandle, CURLOPT_HTTPHEADER, array("Range: bytes=$a-$b") );
``` | CURLOPT\_RANGE appears to not work in PHP although it's there. At least it didn't have an impact when I tried to use it and a google search will reveal many messages of the same. | curl: How to limit size of GET? | [
"",
"php",
"curl",
""
] |
I've seen many people use the following code:
```
Type t = typeof(SomeType);
if (t == typeof(int))
// Some code here
```
But I know you could also do this:
```
if (obj1.GetType() == typeof(int))
// Some code here
```
Or this:
```
if (obj1 is int)
// Some code here
```
Personally, I feel the last one is the cleanest, but is there something I'm missing? Which one is the best to use, or is it personal preference? | All are different.
* `typeof` takes a type name (which you specify at compile time).
* `GetType` gets the runtime type of an instance.
* `is` returns true if an instance is in the inheritance tree.
### Example
```
class Animal { }
class Dog : Animal { }
void PrintTypes(Animal a) {
Console.WriteLine(a.GetType() == typeof(Animal)); // false
Console.WriteLine(a is Animal); // true
Console.WriteLine(a.GetType() == typeof(Dog)); // true
Console.WriteLine(a is Dog); // true
}
Dog spot = new Dog();
PrintTypes(spot);
```
---
> What about `typeof(T)`? Is it also resolved at compile time?
Yes. T is always what the type of the expression is. Remember, a generic method is basically a whole bunch of methods with the appropriate type. Example:
```
string Foo<T>(T parameter) { return typeof(T).Name; }
Animal probably_a_dog = new Dog();
Dog definitely_a_dog = new Dog();
Foo(probably_a_dog); // this calls Foo<Animal> and returns "Animal"
Foo<Animal>(probably_a_dog); // this is exactly the same as above
Foo<Dog>(probably_a_dog); // !!! This will not compile. The parameter expects a Dog, you cannot pass in an Animal.
Foo(definitely_a_dog); // this calls Foo<Dog> and returns "Dog"
Foo<Dog>(definitely_a_dog); // this is exactly the same as above.
Foo<Animal>(definitely_a_dog); // this calls Foo<Animal> and returns "Animal".
Foo((Animal)definitely_a_dog); // this does the same as above, returns "Animal"
``` | Use `typeof` when you want to get the type at *compilation time*. Use `GetType` when you want to get the type at *execution time*. There are rarely any cases to use `is` as it does a cast and, in most cases, you end up casting the variable anyway.
There is a fourth option that you haven't considered (especially if you are going to cast an object to the type you find as well); that is to use `as`.
```
Foo foo = obj as Foo;
if (foo != null)
// your code here
```
This only uses **one** cast ~~whereas this approach:~~
```
if (obj is Foo)
Foo foo = (Foo)obj;
```
requires **two**.
**Update (Jan 2020):**
* [As of C# 7+](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-cast "See link for more info from Microsoft Docs"), you can now cast inline, so the 'is' approach can now be done in one cast as well.
Example:
```
if(obj is Foo newLocalFoo)
{
// For example, you can now reference 'newLocalFoo' in this local scope
Console.WriteLine(newLocalFoo);
}
``` | Type Checking: typeof, GetType, or is? | [
"",
"c#",
"types",
"typeof",
"gettype",
""
] |
The underlying question to this post is "Why would a non-promoted LTM Transaction ever be in doubt?"
I'm getting System.Transactions.TransactionInDoubtException and i can't explain why. Unfortunately i cannot reproduce this issue but according to trace files it does happen. I am using SQL 2005, connecting to one database and using one SQLConnection so i don't expect promotion to take place. The error message indicates a timeout. However, sometimes I get a timeout message but the exception is that the transaction has aborted as opposed to in doubt, which is much easier to handle.
Here is the full stack trace:
```
System.Transactions.TransactionInDoubtException: The transaction is in doubt. ---> System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error)
at System.Data.SqlClient.TdsParserStateObject.ReadSni(DbAsyncResult asyncResult, TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParserStateObject.ReadNetworkPacket()
at System.Data.SqlClient.TdsParserStateObject.ReadBuffer()
at System.Data.SqlClient.TdsParserStateObject.ReadByte()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.TdsExecuteTransactionManagerRequest(Byte[] buffer, TransactionManagerRequestType request, String transactionName, TransactionManagerIsolationLevel isoLevel, Int32 timeout, SqlInternalTransaction transaction, TdsParserStateObject stateObj, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransactionYukon(TransactionRequest transactionRequest, String transactionName, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransaction(TransactionRequest transactionRequest, String name, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlDelegatedTransaction.SinglePhaseCommit(SinglePhaseEnlistment enlistment)
--- End of inner exception stack trace ---
at System.Transactions.TransactionStateInDoubt.EndCommit(InternalTransaction tx)
at System.Transactions.CommittableTransaction.Commit()
at System.Transactions.TransactionScope.InternalDispose()
at System.Transactions.TransactionScope.Dispose()
```
Any ideas? Why am i getting in doubpt and what should i do when i get it?
**EDIT for more information**
I actually still don't have the answer for this. What I did realize is that the transaction actually partially commits. One table gets the insert but the other does not get the update. The code is HEAVILY traced and there is not much room for me to be missing something.
Is there a way I can easily find out if the transaction has been promoted. Can we tell from the stack trace if it is? SIngle Phase commit (which is in the strack trace) seems to indicate no promotion to me, but maybe i'm missing something. If its not getting promoted then how can it be in doubt.
Another interesting piece to the puzzle is that i create a clone of the current transaction. I do that as a workarround to this issue.
<http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=914869&SiteID=1>
Unfortunately, i don't know if this issue has been resolved. Maybe creating the clone is causing a problem. Here is the relevant code
```
using (TransactionScope ts = new TransactionScope())
{
transactionCreated = true;
//part of the workarround for microsoft defect mentioned in the beginning of this class
Transaction txClone = Transaction.Current.Clone();
transactions[txClone] = txClone;
Transaction.Current.TransactionCompleted += new TransactionCompletedEventHandler(TransactionCompleted);
MyTrace.WriteLine("Transaction clone stored and attached to event");
m_dataProvider.PersistPackage(ControllerID, package);
MyTrace.WriteLine("Package persisted");
m_dataProvider.PersistTransmissionControllerStatus(this);
MyTrace.WriteLine("Transmission controlled updated");
ts.Complete();
}
```
Thanks | The answer is that it can't. What apparently was happening was that promotion was taking place. (We accidentally discovered this) I still don't know how to detect if a promotion attempt is happening. That would have been extreamly useful in detecting this. | The current accepted answer is that a non-promoted LTM (non-MSDTC) Transaction can never be in doubt. After much research into a similar issue, I have found that this is incorrect.
Due to the way the single phase commit protocol is implemented, there is a small period of time where the transaction is "in doubt", after the Transaction Manager sends the SinglePhaseCommit request to its subordinate, and before the subordinate replies with either a committed/aborted/or prepared (needs to promote/escalate to MSDTC) message. If the connection is lost during this time, then the transaction is "in doubt", b/c the TransactionManager never received a response when it asked the subordinate to perform a SinglePhaseCommit.
From [MSDN Single-Phase Commit](http://msdn.microsoft.com/en-us/library/cc229955.aspx "MSDN Single-Phase Commit"), also see "Single phase commit flow" image at the bottom of this answer:
> There is a possible disadvantage to this optimization: if the
> transaction manager loses contact with the subordinate participant
> after sending the Single-Phase Commit request but before receiving an
> outcome notification, it has no reliable mechanism for recovering the
> actual outcome of the transaction. Consequently, the transaction
> manager sends an In Doubt outcome to any applications or voters
> awaiting informational outcome notification
Also here are some practical examples of things I've found that cause System.Transaction promotion/escalation to a MSDTC transaction (this is not directly related to the OP, but I have found very useful. Tested in VS 2013, SQL Server 2008 R2, .NET 4.5 except where noted):
1. (this one is specific to SQL Server 2005 or if compatibility level < 100)- Calling Connection.Open() more than once at any point within a TransactionScope. This also includes calling .Open(), .Close(), .Open() on the SAME connection instance.
2. Opening **nested** connections within a TransactionScope
3. Using multiple connections that **do not use connection pooling**, even if they are not nested and connecting to the same database.
4. Queries that involve linked servers
5. SQL CLR procedures that use TransactionScope. See: <http://technet.microsoft.com/en-us/library/ms131084.aspx> "TransactionScope should be used only when local and remote data sources or external resource managers are being accessed. This is because **TransactionScope [within CLR] always causes transactions to promote**, even if it is being used only within a context connection"
6. It appears that if using connection pooling, and the same exact physical connection that was used in Connection1 is not available for some reason in Connections "2 to N" then the entire transaction will be promoted (b/c these are treated as 2 separate durable resources, item #2 is the MS official list below). I have not tested/confirmed this particular case, but is my understanding of how it works. It makes sense b/c behind the scenes this is similar to using nested connections or not using connection pooling b/c multiple physical connections are used. <http://msdn.microsoft.com/en-us/library/8xx3tyca(v=vs.110).aspx> "When a connection is closed and returned to the pool with an enlisted System.Transactions transaction, it is set aside in such a way that the next request for that connection pool with the same System.Transactions transaction will return the same connection if it is available. If such a request is issued, and there are no pooled connections available, a connection is drawn from the non-transacted part of the pool and enlisted"
And here is the MS official list of what causes escalation: <http://msdn.microsoft.com/en-us/library/ms229978(v=vs.85).aspx>
1. At least one durable resource that does not support single-phase notifications is enlisted in the transaction.
2. At least two durable resources that support single-phase notifications are enlisted in the transaction. For example, enlisting a single connection with SQL Server 2005 does not cause a transaction to be promoted. However, whenever you open a second connection to a SQL Server 2005 database causing the database to enlist, the System.Transactions infrastructure detects that it is the second durable resource in the transaction, and escalates it to an MSDTC transaction.
3. A request to "marshal" the transaction to a different application domain or different process is invoked. For example, the serialization of the transaction object across an application domain boundary. The transaction object is marshaled-by-value, meaning that any attempt to pass it across an application domain boundary (even in the same process) results in serialization of the transaction object. You can pass the transaction objects by making a call on a remote method that takes a Transaction as a parameter or you can try to access a remote transactional-serviced component. This serializes the transaction object and results in an escalation, as when a transaction is serialized across an application domain. It is being distributed and the local transaction manager is no longer adequate.
 | TransactionInDoubtException using System.Transactions on SQL Server 2005 | [
"",
"c#",
"sql-server-2005",
"transactions",
"transactionscope",
"system.transactions",
""
] |
I stand in front of a little problem; *I want to create a modular software.*
Let's make it more general and not specific for my case. What I want to create is a software which loads dlls and those dlls adds features to the software.
Think of the dlls as xvid, divx or whatever additional codec, feature to your favorite video-player. I want a more custom modular program though, in my case I'm creating a software to handle Customers, Invoices and Products and different users might have different needs and therefore I need to handle this somehow!
However, re-compiling the software and specificly sending the new files to each different user is "stupid" I would rather create a modular software ( don't actually know if this is the correct term ).
So what I was thinking is that I begin creating a pattern of which my DLL's should follow.
Then I create a Module handler in my software which loads the actuall DLL and calls the method in it ( here's where the pattern come in! ).
What I'd like to know is; Am I on the right track?
Might you guys give me some pointers or examples on this matter?
This is all in C#, but would of course be interesting to see how it would differ in Java, Python or C++ too. | You have to have a purpose. You either need the module to conform to some kind of interface or something the app can handle (like a method with a known attribute that you find via reflection). The interface then performs known functionality like invoice creation, invoice printing, etc.
Alternatively your app has to conform to some interface and uses [hooks](http://en.wikipedia.org/wiki/Hooking) for the module to use to inject itself into your app.
Plugins would be good for something that can be easily sliced up (media codecs). Hooks would be good for something with a well-defined event model (like a web server). Which you use depends on how you want your modularity for customers, invoices, etc. to work. | create a common interface IMyInterface for your classes which should include everything that is common between all of your Moduals. You should look into the [Managed Extensibility Framework](http://www.google.com/search?q=C%23+MEF) I believe you can get it from [Codeplex](http://www.codeplex.com/MEF). | Programming Modular software | [
"",
"c#",
""
] |
I have a javascript object array:
```
array = [ {x:'x1', y:'y1'}, {x:'x2', y:'y2'}, ... {x:'xn', y:'yn'} ]
```
I want to create a new array of just the `x` values:
```
[ 'x1', 'x2', ..., 'xn' ]
```
I could do this easily in a `for` loop...:
```
var newarray = [];
for (var i = 0; i < array.length; i++){
newarray.push(array[i].x);
}
```
...but I'm wondering if there's a nice one liner way to do this using jquery or even regular javascript? | You can do this with [map](http://docs.jquery.com/Utilities/jQuery.map):
```
var newarray = jQuery.map(array, function (item) { return item.x; });
``` | ECMAScript 5 features a native `map()` method:
```
var newArray = array.map(function(value) { return value.x; });
```
In FF, this should even be faster than looping, but that's not true for all browsers (Opera); others don't even support it (IE). | Javascript - Nice way to create an array from an object array | [
"",
"javascript",
"jquery",
""
] |
I want to make a CSS style switcher in JavaScript, same as Digg does here
[](https://i.stack.imgur.com/6H57J.png)
I am having a div, in which I want to change the style of the div box on the basis of theme selection.
I don't want to use jQuery, I want to develop this code in pure JavaScript. | Inspecting the source code and how it changes as you change themes, it is really quite simple. Digg is harnessing the awesomeness of CSS to drastically change content by simply changing the class of an element. All you have to do is this:
```
<div id="theme_viewer">
<!-- HTML code for your widget/thing to be styled -->
</div>
```
And then you can have your themes:
```
<ul>
<li><a href="#" onclick="return switchTheme('theme1');">theme 1</a></li>
<li><a href="#" onclick="return switchTheme('theme2');">theme 2</a></li>
<li><a href="#" onclick="return switchTheme('theme3');">theme 3</a></li>
<li><a href="#" onclick="return switchTheme('theme4');">theme 4</a></li>
</ul>
```
All `switchTheme` needs to then do is change the class of `theme_viewer` to the class passed:
```
function switchTheme(theclass) {
var viewer = document.getElementById('theme_viewer');
viewer.className = theclass;
return false;
}
```
Your CSS stylesheets can then do whatever the different styles call for:
```
#theme_viewer.theme1 {
background-color: red;
}
#theme_viewer.theme2 {
background-color: blue;
}
#theme_viewer.theme3 {
background-color: black;
color: white;
}
#theme_viewer.theme4 {
background-color: orange;
}
```
[here is an example of this at work](http://jsbin.com/opoji)
As mentioned in the comments by J-P and in edeverett's answer, it is not a good idea to have your events inline as I have them in this example (ie, with the `onclick` attribute). I did it for simplicity, but it's not a good idea. The better idea is to wait for your document to load and attach the event handlers dynamically with Javascript. This is known as unobtrusive Javascript, and it is a Good ThingTM.
An example of the above example following good practices would look like this:
```
<ul id='theme_options'>
<li><a href="#" id='theme1'>theme 1</a></li>
<li><a href="#" id='theme2'>theme 2</a></li>
<li><a href="#" id='theme3'>theme 3</a></li>
<li><a href="#" id='theme4'>theme 4</a></li>
</ul>
```
And then we use this cross browser addEvent function ([written by](http://ejohn.org/blog/flexible-javascript-events) John Resig, author of jQuery):
```
function addEvent( obj, type, fn ) {
if ( obj.attachEvent ) {
obj['e'+type+fn] = fn;
obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
obj.attachEvent( 'on'+type, obj[type+fn] );
} else
obj.addEventListener( type, fn, false );
}
```
To add the event handlers:
```
addEvent(window, 'load', function() {
var opts = document.getElementById('theme_options');
var links = opts.getElementsByTagName('a');
for(var x = 0; x < links.length; x++) {
addEvent(links[x], 'click', function() {
switchTheme(links[x].id);
});
}
});
```
It might be a little more verbose than inline Javascript, but it is worth it. I know you said you'd like to avoid jQuery, but something as simple as this makes you start appreciating the library, as you could do it with jQuery with something as simple as this:
```
$(function() {
$('a','#theme_options').click(function() {
switchTheme($(this).attr('id'));
return false;
});
});
``` | There's three parts to this:
**1) The div itself**
This stays almost the same for all styles. The Javascript will only change the class attribute to change the styles that the CSS applies to the div. Create the div so that it has the default style when the page is created and add an id so we can get at it easily with Javascript later:
```
<div class="style1" id="styleBox"></div>
```
**2) The CSS**
In your CSS you need to have a class for each way you want the div presented. Set up all the generic attributes like width and height first in one style rule:
```
.style1,
.style2,
.style3 {widht:200px; height:400px; text-size:1em;}
```
Then set up the rules for the individual styles:
.style1 {background-color:aqua;}
.style2 {background-color:yellow;}
.style3 {background-color:pink;}
Note that these are all in the same stylesheet, this will make it easier to manage.
**3) The Javascript**
This is where you add the behaviour. You'll also need some links to click, ideally these should be created with JS as they aren't any use to the user without it - but for now lets assume they are in the page:
```
<div id="styleMenu">
<a href="#" id="style1" >Style 1</a>
<a href="#" id="style2" >Style 2</a>
<a href="#" id="style3" >Style 3</a>
</div>
```
You'll need to have a JS function that is run when the page loads (google "javascript onload function"). In this function you'll need to get a reference to the div containing the links and add a onClick event to in. This event will get fired when the links get clicked - this is called Event Delegation (google it). In this event function you'll need to find out which link has been clicked using the [event.target (or event.srcElement for IE).](http://www.quirksmode.org/js/events_properties.html) Then set the className property of the styled div to the id of the link that was clicked.
I'll leave writing the actually JS to you, but if you use this slightly longer way of doing things - and not using inline styles or javascript - you have cleanly seperated HTML, CSS and Javascript which will make maintaining everything a lot easier. | How to create a DIV style switcher? | [
"",
"javascript",
"html",
"css",
""
] |
I am having a serious problem converting my 'select' statement into something that will work with the zend paginator... could someone have a crack at it, as I am having no luck...
Here is my query:
```
$query = "SELECT
user_id, name, gender, city, province, country, image_id, one_liner, self_description, reputation
FROM
users
WHERE
(
(69.1 * (latitude - " . $user->latitude . ")) *
(69.1 * (latitude - " . $user->latitude . "))
) + (
(69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3)) *
(69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3))
) < " . pow($radius, 2) . "
ORDER BY
(
(69.1 * (latitude - " . $user->latitude . ")) *
(69.1 * (latitude - " . $user->latitude . "))
) + (
(69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3)) *
(69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3))
```
Here is what I have so far:
```
$select = $db->select();
$select->from(
array('users'),
array(
'user_id',
'name',
'gender',
'city',
'province',
'country',
'image_id',
'one_liner',
'self_description',
'reputation'
)
);
$select->where("(69.1 * (latitude - " . $user->latitude . ")) * (69.1 * (latitude - " . $user->latitude . "))) + ((69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3)) * (69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3))) < " . pow($radius, 2));
$select->order("(69.1 * (latitude - " . $user->latitude . ")) * (69.1 * (latitude - " . $user->latitude . "))) + ((69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3)) * (69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3))) ASC");
``` | Why do you have "<" in your order by clause? | What does this have to do with Zend\_Paginator? Ah, do you have the query and you don't know how to make a paginator with it, or is the paginator not working with this query?
The only thing I can see is you're missing an opening parenthesis in both the `where()` and `order()` clause:
```
$select->where("((69.1 * [...] ");
$select->order("((69.1 * [...] ");
^
```
So maybe Zend\_Paginator isn't working because the SQL query has errors?
And of course I have to ask: are those variables you're interpolating safe, or should you really be using `$db->quote($user->latitude, Zend_Db::FLOAT_TYPE)`? | Zend_db & Zend_paginator - Not having a fun time | [
"",
"php",
"zend-framework",
"zend-paginator",
""
] |
I'm using Python 2.5. What is going on here? What have I misunderstood? How can I fix it?
*in.txt:*
```
Stäckövérfløw
```
*code.py*
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
print """Content-Type: text/plain; charset="UTF-8"\n"""
f = open('in.txt','r')
for line in f:
print line
for i in line:
print i,
f.close()
```
*output:*
```
Stäckövérfløw
S t � � c k � � v � � r f l � � w
``` | ```
for i in line:
print i,
```
When you read the file, the string you read in is a string of bytes. The for loop iterates over a single byte at a time. This causes problems with a UTF-8 encoded string, where non-ASCII characters are represented by multiple bytes. If you want to work with Unicode objects, where the characters are the basic pieces, you should use
```
import codecs
f = codecs.open('in', 'r', 'utf8')
```
If `sys.stdout` doesn't already have the appropriate encoding set, you may have to wrap it:
```
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
``` | Use codecs.open instead, it works for me.
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
print """Content-Type: text/plain; charset="UTF-8"\n"""
f = codecs.open('in','r','utf8')
for line in f:
print line
for i in line:
print i,
f.close()
``` | UTF-8 problem in python when reading chars | [
"",
"python",
"utf-8",
""
] |
Assume that the class **Data** is defined as **{DateTime TransactionDate, int ItemCount}**.
I get an original IEnumerable containing scattered TransactionDates and ItemCounts and I need to write a method that returns a collection with all the days filled in between the minimum and the maximum days in the original collection.
For instance, if I get:
12/5/2009 15.00
12/7/2009 10.00
12/10/2009 75.00
I need to generate something like this:
12/5/2009 15.00
12/6/2009 0.00
12/7/2009 10.00
12/8/2009 0.00
12/9/2009 0.00
12/10/2009 75.00
Get you give me an elegant way of doing this with c# 3.0?
I have a list of all dates between the minimum and maximum dates. So I assume all I have to do is "foreach" the intersect collection (allDates-existingDates) and insert a new element for each of these. Am I right?
Thanks | Here's an extension method that should do the job. It's purely based on iterators (`IEnumerable<Data>`), so it would seem quite a nice approach to me.
```
public static IEnumerable<Data> FillIn(this IEnumerable<Data> original)
{
Data lastItem = null;
foreach (var item in original)
{
if (lastItem != null)
{
var fakeItem = new DateTime(lastItem.TransactionDate.Year,
lastItem.TransactionDate.Month, lastItem.TransactionDate.Day)
.AddDays(1);
while (fakeItem.TransactionDate != item.TransactionDate)
{
yield return fakeItem;
fakeItem.TransactionDate = fakeItem.TransactionDate.AddDays(1);
}
}
lastItem = item;
yield return item;
}
}
```
Where `Data` is simply defined as:
```
class Data
{
public DateTime TransactionDate;
public int ItemCount;
}
``` | Assuming your collection is a dictionary (dates are unique and can be used as keys), you could do something lik this:
-1. Determinie the first and last date in your source collection (if the collection is a sortedDictionary you have first and last elements).
-2. Create a IEnumerator that can iterate trough all dates between a given start and end date.
-3. Use a foreach structure, using the Enumerator and the obtained start and end dates you gathered. At each step, check if the current date is a key in the source list, in which case you copy it in the result list, otherwise create a new result item with the current date and 0 for item count.
Let me know of this proof-of-concept is enought for you, if not I will try to build an example.
**Edit:** You edited your question, mentionig you already have the list of all dates between the start and end so you can skip the 2nd step. :) | C# - filling in empty dates in a collection | [
"",
"c#",
""
] |
How do I get `datetime.datetime.now()` printed out in the native language?
```
>>> session.deathDate.strftime("%a, %d %b %Y")
'Fri, 12 Jun 2009'
```
I'd like to get the same result but in local language. | You can just set the locale like in this example:
```
>>> import time
>>> print time.strftime("%a, %d %b %Y %H:%M:%S")
Sun, 23 Oct 2005 20:38:56
>>> import locale
>>> locale.setlocale(locale.LC_TIME, "sv_SE") # swedish
'sv_SE'
>>> print time.strftime("%a, %d %b %Y %H:%M:%S")
sön, 23 okt 2005 20:39:15
``` | If your application is supposed to support more than one locale then getting localized format of date/time by changing locale (by means of `locale.setlocale()`) is discouraged. For explanation why it's a bad idea see Alex Martelli's [answer](https://stackoverflow.com/a/1551834/95735) to the the question [Using Python locale or equivalent in web applications?](https://stackoverflow.com/q/1551508/95735) (basically locale is global and affects whole application so changing it might change behavior of other parts of application)
You can do it cleanly using Babel package like this:
```
>>> from datetime import date, datetime, time
>>> from babel.dates import format_date, format_datetime, format_time
>>> d = date(2007, 4, 1)
>>> format_date(d, locale='en')
u'Apr 1, 2007'
>>> format_date(d, locale='de_DE')
u'01.04.2007'
```
See [Date and Time](http://babel.pocoo.org/en/latest/dates.html) section in Babel's documentation. | Locale date formatting in Python | [
"",
"python",
"date",
"locale",
""
] |
I am writing a website using JSP, JSTL, Servlets and JavaBeans.
At one point of my code, I am trying to use an ArrayList of objects, and a strange thing is happening: when I add the first object it is fine, and when I add a second object it adds it in the second place, but the object at index(0) gets the same values as the object at index(1).
Maybe a problem is in the
```
ArrayList<Article> articleList = new ArrayList<Article>();
Article newArticle = new Article();
```
Since articleList is ArrayList of Article class.
Can somebody point me to what I am doing wrong?
Below is my code:
```
public ArrayList<Article> getArticles()
{
baseIO mySql = new baseIO();
ArrayList<Article> articleList = new ArrayList<Article>();
int articleId = 0;
try
{
String sql =
"select * from jsp_blog_article order by article_id Desc Limit 3";
con = (Connection)mySql.getConnection();
pstmt = (PreparedStatement) con.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Article newArticle = new Article();
newArticle.setArticleAuthor(rs.getString("article_name"));
newArticle.setArticleBody(rs.getString("article_body"));
newArticle.setArticleAuthor(rs.getString("article_author"));
newArticle.setArticleDate(rs.getString("article_date"));
articleId = Integer.parseInt(rs.getString("article_id"));
newArticle.setArticleId(String.valueOf(articleId));
newArticle.setArticleComments(this.getCommentsNum(articleId));
articleList.add(newArticle);
}
con.close();
pstmt.close();
}
catch(Exception e)
{
return null;
}
return articleList;
}
```
And the Article class
```
package objects;
import java.io.Serializable;
public class Article implements Serializable{
private String articleName;
private String articleBody;
private String articleAuthor;
private String articleComments;
private String articleDate;
private String articleId;
public Article()
{
}
// all the getters and setters in place, but it is too long
// so i am not going to post them in forum
}
``` | I would try it this way and see what this does.
```
int x = 0;
while (rs.next()) {
articleList.add(new Article());
articleList.get(x).setArticleName(rs.getString("article_name"));
articleList.get(x).setArticleBody(rs.getString("article_body"));
articleList.get(x).setArticleAuthor(rs.getString("article_author"));
articleList.get(x).setArticleDate(rs.getString("article_date"));
articleList.get(x).setArticleId(rs.getString("article_id"));
articleList.get(x).setArticleComments(this.getCommentsNum(articleId));
x++;
}
``` | You are calling newArticle.setArticleAuthor twice...I know that's not part of your list problem, but that is an observation. | Strange behaviour of ArrayList | [
"",
"java",
"jsp",
"jstl",
"javabeans",
""
] |
How do i deploy a java applet for modern browsers?
I know there are somehow 3 possibilities but nobody tells me which one to prefer and how to use them.
Does somebody have any resources on that? i cant find any :( | There is a section in [The Java Tutorials](http://java.sun.com/docs/books/tutorial/index.html) titled [Using applet, object and embed Tags](http://download.oracle.com/javase/1,5.0/docs/guide/plugin/developer_guide/using_tags.html) which addresses the issue.
From the [General Considerations](http://download.oracle.com/javase/1,5.0/docs/guide/plugin/developer_guide/using_tags.html#general):
> Deploying Applets on the Internet Versus an Intranet
>
> When deploying applets:
>
> * Use the `applet` tag if the Web
> page is accessed through the Internet.
> * Use the `object` or `embed` tag if the Web page is accessed through an
> Intranet.
>
> Deploying Applets for Specific
> Browsers
>
> When deploying applets:
>
> * For Internet Explorer only, use the
> `object` tag.
> * For the Mozilla
> family of browsers only, use the
> `embed` tag.
>
> If you must deploy an applet in a mixed-browser environment, follow the guidelines in the section [Deploying Applets in a Mixed-Browser Environment](http://download.oracle.com/javase/1,5.0/docs/guide/plugin/developer_guide/using_tags.html#mixed).
It should be noted that the `applet` tag has been deprecated, so it's probably not desirable to use that tag. ([More information on the `applet` tag from the W3C](http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.4))
(Note: Links have been updated from the previous edit to link to The Java Tutorials.) | If you can target Java 6 update 10 or better, you can [simplify your life](http://java.sun.com/javase/6/docs/technotes/guides/jweb/deployment_advice.html#deployingApplets):
```
<script src="http://java.com/js/deployJava.js"></script>
<script>
var attributes = {codebase:'http://java.sun.com/products/plugin/1.5.0/demos/jfc/Java2D',
code:'java2d.Java2DemoApplet.class',
archive:'Java2Demo.jar',
width:710, height:540} ;
var parameters = {fontSize:16} ;
var version = '1.6' ;
deployJava.runApplet(attributes, parameters, version);
</script>
``` | How to deploy a java applet for today's browsers (applet, embed, object)? | [
"",
"java",
"deployment",
"applet",
""
] |
How do I use `Assert` (or other Test class) to verify that an exception has been thrown when using MSTest/Microsoft.VisualStudio.TestTools.UnitTesting? | For "Visual Studio Team Test" it appears you apply the ExpectedException attribute to the test's method.
Sample from the documentation here: [A Unit Testing Walkthrough with Visual Studio Team Test](http://msdn.microsoft.com/en-us/library/ms379625(VS.80).aspx#vstsunittesting_topic5)
```
[TestMethod]
[ExpectedException(typeof(ArgumentException),
"A userId of null was inappropriately allowed.")]
public void NullUserIdInConstructor()
{
LogonInfo logonInfo = new LogonInfo(null, "P@ss0word");
}
``` | Usually your testing framework will have an answer for this. (See the comments for this thread for examples, there's lots!) But if your framework isn't flexible enough, you can always do this:
```
try {
somethingThatShouldThrowAnException();
Assert.Fail(); // If it gets to this line, no exception was thrown
} catch (GoodException) { }
```
As @Jonas points out, this DOES NOT work for catching a base Exception:
```
try {
somethingThatShouldThrowAnException();
Assert.Fail(); // raises AssertionException
} catch (Exception) {
// Catches the assertion exception, and the test passes
}
```
If you absolutely must catch Exception, you need to rethrow the Assert.Fail(). But really, this is a sign you shouldn't be hand-writing this; check your test framework for options, or see if you can throw a more meaningful exception to test for.
```
catch (AssertionException) { throw; }
```
You should be able to adapt this approach to whatever you like -- including specifying what kinds of exceptions to catch. If you only expect certain types, finish the `catch` blocks off with:
```
} catch (GoodException) {
} catch (Exception) {
// not the right kind of exception
Assert.Fail();
}
``` | How do I use Assert to verify that an exception has been thrown with MSTest? | [
"",
"c#",
"unit-testing",
"mstest",
"assert",
"vs-unit-testing-framework",
""
] |
i have two color "red" also "Salmon". i need create dynamiclly panel also panel background color. These colors must be between two color(red
```
public Color x, y;
protected void Page_Load(object sender, EventArgs e)
{
BackGroundColorArranger(Color.Red, Color.Salmon);
}
void BackGroundColorArranger(Color x, Color y)
{
BackGroundColorArrangerBase(Convert.ToInt32((float)(x.ToArgb() + y.ToArgb()) / 2));
}
void BackGroundColorArrangerBase(int z)
{
Panel panel = new Panel();
panel.ID = z.ToString();
panel.Width = 150;
panel.Height = 50;
panel.BackColor = Color.FromArgb(z);
this.Controls.Add(panel);
BackGroundColorArranger(x, Color.FromArgb(z));
}
```
But how can i do this. Above codes give me stackoverflow error. | As they have said you have an infinite recursive loop, and that's why you're getting the Stack Overflow.
As a quick fix remove this line from BackGroundColorArrangerBase:
```
BackGroundColorArranger(x, Color.FromArgb(z));
```
So it looks like this:
```
void BackGroundColorArrangerBase(int z)
{
Panel panel = new Panel();
panel.ID = z.ToString(); //this wil generate the same id for the same pair of colors
panel.Width = 150;
panel.Height = 50;
panel.BackColor = Color.FromArgb(z);
this.Controls.Add(panel);
}
```
That should stop the recursion. Its not very clear what you need beyond the dynamic panel creation. As is the code will just create one panel, and will create a new panel every time the BackGroundColorArranger is called -WITH A DIFFERENT COLOR PAIR- as you are using the colorpair as an ID for the panel.
If you need more than one panel make a *finite* loop calling BackGroundColorArranger with different pairs of colors ... if you need to actually see the panels on screen you'll need to change panel.Location of each in ArrangerBase, as now each panel starts at the origin with a fixed size. | Because you call BackGroundColorArranger recursively with no exit condition. Here's a tip, when you get the stack overflow exception in the debugger, go to Debug Menu -> Windows -> Call Stack and you'll immediately see the problem. | Stack Overflow error on Color Changer Function | [
"",
"c#",
".net",
"asp.net",
"algorithm",
"stack-overflow",
""
] |
I've been searching the difference between `Select` and `SelectMany` but I haven't been able to find a suitable answer. I need to learn the difference when using LINQ To SQL but all I've found are standard array examples.
Can someone provide a LINQ To SQL example? | `SelectMany` flattens queries that return lists of lists. For example
```
public class PhoneNumber
{
public string Number { get; set; }
}
public class Person
{
public IEnumerable<PhoneNumber> PhoneNumbers { get; set; }
public string Name { get; set; }
}
IEnumerable<Person> people = new List<Person>();
// Select gets a list of lists of phone numbers
IEnumerable<IEnumerable<PhoneNumber>> phoneLists = people.Select(p => p.PhoneNumbers);
// SelectMany flattens it to just a list of phone numbers.
IEnumerable<PhoneNumber> phoneNumbers = people.SelectMany(p => p.PhoneNumbers);
// And to include data from the parent in the result:
// pass an expression to the second parameter (resultSelector) in the overload:
var directory = people
.SelectMany(p => p.PhoneNumbers,
(parent, child) => new { parent.Name, child.Number });
```
[Live Demo on .NET Fiddle](https://dotnetfiddle.net/LNyymI) | Select many is like [cross join operation in SQL](http://msdn.microsoft.com/en-us/library/ms190690%28v=sql.105%29.aspx) where it takes the cross product.
For example if we have
```
Set A={a,b,c}
Set B={x,y}
```
Select many can be used to get the following set
```
{ (x,a) , (x,b) , (x,c) , (y,a) , (y,b) , (y,c) }
```
Note that here we take the all the possible combinations that can be made from the elements of set A and set B.
Here is a LINQ example you can try
```
List<string> animals = new List<string>() { "cat", "dog", "donkey" };
List<int> number = new List<int>() { 10, 20 };
var mix = number.SelectMany(num => animals, (n, a) => new { n, a });
```
the mix will have following elements in flat structure like
```
{(10,cat), (10,dog), (10,donkey), (20,cat), (20,dog), (20,donkey)}
``` | Difference Between Select and SelectMany | [
"",
"c#",
"linq-to-sql",
"linq",
""
] |
I'm very new to sending data over a serial port through .net and I've noticed after implementing a TCP counterpart that I wouldn't get it that easy with serial!
So to start at the top, I am nearly there with my serial bi-directional communication implementation I am just getting stuck on a few things: -
1. My reads are being split across multiple messages or received as a fragmented response over the COM port and I don't know what settings I might need, or how I should write the code differently to fix this. What could cause this? I am inspecting the message at a breakpoint on `SerialPort_DataReceived.`
Basically the data should be sent as:
```
01: LS|DA090521|TI111043|q
02: PS|RN102|PTC|TA1040000|P#0|DA090521|TI111429|j
```
but it is being split (at random positions on each requested read)
```
01: LS|DA090521|TI111
02: 043|q
03: PS|RN102|PTC|TA1
04: 0000|P#0|DA090521|TI111429|j
```
**- Question 1 has been answered, thanks Chris W. and others! I now have the message I expect being built from fragments progressively (looking out for STX, {msg body}, ETX) and then an action performed when message has been completely built, and got it going with a thread-safe Queue, very happy.**
. 2. I am receiving a "|" symbol through my read nearly every cycle, is this due to a command I have set wrongly somehow, an artifact of Serial communication, or something the device is sending me? (I don't think so though, as Hyperterminal connectivity reveals this character is not being sent continuously.)
. 3. Can you confirm I am reading and writing data correctly in the respective methods.
Thanks guys for looking at my other two questions too.
Relevant code as follows:
```
...
// COM3, 9600, None, 8, One
SerialPort = new SerialPort(comPort, baudRate, parity, dataBits, stopBits);
if (SerialPort.IsOpen) SerialPort.Close();
// SerialPort.RtsEnable = true; // Request-to-send
// SerialPort.DtrEnable = true; // Data-terminal-ready
SerialPort.ReadTimeout = 150; // tried this, but didn't help
SerialPort.WriteTimeout = 150; // tried this, but didn't help
SerialPort.Open();
SerialPort.DataReceived += new SerialDataReceivedEventHandler(SerialPort_DataReceived);
}
void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Process received data
SerialPort sp = (SerialPort)sender;
byte[] buffer = new byte[sp.BytesToRead];
int bytesRead = sp.Read(buffer, 0, buffer.Length);
// message has successfully been received
message = Encoding.ASCII.GetString(buffer, 0, bytesRead);
}
public bool SendMessage(string text)
{
// Only send message if a client is connected
if (SerialPort != null && SerialPort.IsOpen)
{
byte[] buffer = Encoding.ASCII.GetBytes(text);
SerialPort.Write(buffer, 0, buffer.Length);
}
}
``` | > My reads are being split across multiple messages
This is normal, expected, inevitable behaviour. It can happen with data-over-TCP as well. To the serial interface it's just an endless stream of bytes. It's your application's responsibility to repackage those bytes into packets.
If the location of packet boundaries is important, and if you can't tell where the packet boundaries are supposed to be from looking at the received data, then you may need to rethink the format of the data so that you *can* tell where the packet boundaries are.
> I am receiving a "|" symbol through my read nearly every cycle
What's the hex value of that character? See whether setting the `Handshake` property to `XOnXOff` or `RequestToSendXOnXOff` improves the situation. | At the lower level the serial port can decide when to trigger the data received event. It might decide to do that before the "full" packet has arrived. But, it looks like you have a terminator character in your expected data set. If so you can do the following (note I have changed your SerialPort assignment to avoid syntax confusion:
```
p = new SerialPort(PortName, BaudRate, Prty, DataBits, SBits);
p.NewLine = Terminator;
```
where Terminator is a string containing your termination character(s). Then you can use SerialPort.ReadLine() (and SerialPort.WriteLine() if that applies). This might at least help with your first issue. | .NET Serial Port help required, primarily with data received in multiple "packets" | [
"",
"c#",
".net",
"serial-port",
""
] |
I have an html file where I'd like to get all the text inside these two tags:
```
<div class="articleTitle">
</div>
```
I'm not entirely sure how to do the php regex.
(I also know there are no html tags inside the div, so there's no problem about nested tags)
update: when i try the solutions given i get this: Warning: preg\_match() [function.preg-match]: Unknown modifier 'd' on line 29 | ```
preg_match('/<div class="articleTitle">(.*?)<\/div>/i', $source, $matches);
print_r($matches);
```
This is the "Explination" from RegexBuddy:
```
<div class="articleTitle">(.*?)</div>
Options: case insensitive
Match the characters “<div class="articleTitle">” literally «<div class="articleTitle">»
Match the regular expression below and capture its match into backreference number 1 «(.*?)»
Match any single character that is not a line break character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the characters “</div>” literally «</div>»
Created with RegexBuddy
```
(.\*?) will capture everything between what comes before it until what comes after it, and it will be places into the $matches var.
I assumed that the HTML will be in the $source var.
I suggest that you look into [RegexBuddy](http://www.regexbuddy.com/), it's 39.95 (USD) but it is worth every penny. It can help build your RegExs with most every major RegEx implementation, and it can help you to learn RegEx | Wrong answers!
```
preg_match('#<div\s+[^>]*class="articleTitle"[^>]*>(.*)</\s*div>#ims', $str, $matches);
```
1. DIV can be empty, so pattrns like (.+) are wrong.
2. you shold use "m" modifier - content can be multiline.
3. you should use "s" modifier to match dot-metacharacter as newline.
4. Just wonder, why escape slash if pattens in php can have ANY delimiter? Usually I use # as delimiter in this case.
5. DIV can have additional attributes and/or space characters (including newlines).
Sorry, have no time to test pattern good, but it seems to be correct. This should work in any case.
PS: and, GONeale, about greediness - pattern must be greedy and it IS greedy without modifier "U". | basic php regex question | [
"",
"php",
"regex",
""
] |
When a user inserts data into a form and then submits it, it goes to my php script and inserts the data. The script will return a value letting the user know if the data was inserted or not. Since I am using JQuery, I have no idea how to do this. Can someone please point me in the right direction? All I'm after here is a nice, neat little 200px by 25px container that will fade in and the user MUST click it to acknowledge it.
Now that I think about it, since users are not the brightest lights in the harbor, it would be really cool if I could not only show then this css box letting them know if the insert was successful but also show them the customer that was inserted in case they forgot where they left off.
Thanks. | I'm not going to mark this as a duplicate, but you are essentially asking the best way to show notifications using jQuery. And that has been [asked before](https://stackoverflow.com/questions/770038/best-ways-to-display-notifications-with-jquery). In a nutshell, in your basic setup all you need to do is show a div and fade it in, but there are a lot of plugins out there that handle more situations.
As far as showing them the customer that was inserted or whatever, all you have to do is return a JSON response from the server and handle it with the success callback of your AJAX request. You will have access to the data passed back from the server then.
To explain a little further: What you seem to be asking to do is how to send a request to a server using Ajax, get a notification that everything went as expected, and then show a notification in the webpage depending on what happened. If that is correct, I'm going to move on with these assumptions.
Let's put together a simple form to add a new customer to a fictional website. It might look like this:
```
<form action='add_customer.php' method='POST' id='add_customer_form'>
First Name: <input type='text' name='first_name'><br>
Last Name: <input type='text' name='last_name'><br>
Email: <input type='text' name='email'><br>
<input type='submit' value='Add Customer'>
</form>
```
Now, our **naive, insecure** PHP code to handle this form submission (through AJAX) might look something like this. I say naive and insecure because you would do more data validation (as you *never* trust anything coming from the client) and would certainly need to clean the data to prevent SQL injections. This is an example, however, so it might look like this:
```
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
if(mysql_query("
INSERT INTO customers
(first_name, last_name, email)
VALUES
('$first_name','$last_name','$email')
")) {
$success = 1;
$message = 'Customer ' . $first_name . ' successfully added!';
} else {
$success = 0;
$message = 'Something went wrong while adding the customer!';
}
print json_encode(array('success' => $success, 'message' => $message));
```
We might then handle the sending of this form and the receiving of data from the server, using jQuery, with code that looks a little something like this:
```
$(function() {
$('#add_customer_form').submit(function() { // handle form submit
var data = $(this).serialize(); // get form's data
var url = $(this).attr('action'); // get form's action
var method = $(this).attr('method'); // get form's method
$.ajax({
url: url, // where is this being sent to?
type: method, // we're performing a POST
data: data, // we're sending the form data
dataType: 'json', // what will the server send back?
success: function(data) { // the request succeeded, now what?
// here data is a JSON object we received from the server
// data.success will be 0 if something went wrong
// and 1 if everything went well. data.message will have
// the message we want to display to the user
// at this point you would use one of the techniques I linked
// to in order to display a fancy notification
// the line below will dynamically create a new div element,
// give it an ID of "message" (presumably for CSS purposes)
// and insert the message returned by the server inside of it
var $div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$div.addClass('error'); // to personalize the type of error
} else {
$div.addClass('success'); // to personalize the type of error
}
$('body').append($div); // add the div to the document
}
});
return false; // prevent non-ajax form submission.
});
});
```
I haven't tested any of this code but the idea is there. You return a format, JSON, from the server, with data, and handle the success callback jQuery fires when the request is complete, and add an element to your document you can style however you want (and show with things like `fadeIn()` if you want) with a message describing what happened. You might also need to catch the error callback (which fires if your server doesn't respond for whatever reason) and firing off another alert in that situation. | [Fading effects](http://docs.jquery.com/Effects) can be accomplished by doing one of the following:
```
jQuery(myDiv).fadeIn()
jQuery(myDiv).fadeOut()
jQuery(myDiv).fadeTo()
```
I'd recommend you first create this css box - create the html and the css. Then you can experiment with fading - jQuery lets you specify arguments like fade color, fade duration, etc. | How can I get a jquery css container to pop up letting the user know data was successfully entered? | [
"",
"javascript",
"jquery",
"html",
"css",
""
] |
I would like to add all unversioned files under a directory to SVN using SharpSVN.
I tried regular svn commands on the command line first:
```
C:\temp\CheckoutDir> svn status -v
```
I see all subdirs, all the files that are already checked in, a few new files labeled "?", nothing with the "L" lock indication
```
C:\temp\CheckoutDir> svn add . --force
```
This results in all new files in the subdirs ,that are already under version control themselves, to be added.
I'd like to do the same using SharpSVN. I copy a few extra files into the same directory and run this code:
```
...
using ( SharpSvn.SvnClient svn = new SvnClient() )
{
SvnAddArgs saa = new SvnAddArgs();
saa.Force = true;
saa.Depth = SvnDepth.Infinity;
try
{
svn.Add(@"C:\temp\CheckoutDir\." , saa);
}
catch (SvnException exc)
{
Log(@"SVN Exception: " + exc.Message + " - " + exc.File);
}
}
```
But an SvnException is raised:
* SvnException.Message: Working copy 'C:\temp\CheckoutDir' locked
* SvnException.File: ..\..\..\subversion\libsvn\_wc\lock.c"
No other svnclient instance is running in my code,
I also tried calling
```
svn.cleanup()
```
right before the Add, but to no avail.
Since the [documentation](http://docs.sharpsvn.net/current/) is rather vague ;),
I was wondering if anyone here knew the answer.
Thanks in advance!
Jan | Use this my tool <http://svncompletesync.codeplex.com/> or take it as a sample.
It does exactly what you need. | I tried Malcolm's tool but couldn't get it to run now that it looks to be a few years old, but after looking at the source code it looks like this is really all you need to use to sync the local checked out folder with the one in SVN:
```
string _localCheckoutPath = @"C:\temp\CheckoutDir\";
SvnClient client = new SvnClient();
Collection<SvnStatusEventArgs> changedFiles = new Collection<SvnStatusEventArgs>();
client.GetStatus(_localCheckoutPath, out changedFiles);
//delete files from subversion that are not in filesystem
//add files to suversion , that are new in filesystem
foreach (SvnStatusEventArgs changedFile in changedFiles)
{
if (changedFile.LocalContentStatus == SvnStatus.Missing)
{
client.Delete(changedFile.Path);
}
if (changedFile.LocalContentStatus == SvnStatus.NotVersioned)
{
client.Add(changedFile.Path);
}
}
SvnCommitArgs ca = new SvnCommitArgs();
ca.LogMessage = "Some message...";
client.Commit(_localCheckoutPath, ca);
``` | Add file using SharpSVN | [
"",
"c#",
"svn",
"sharpsvn",
""
] |
I need to have a common function to convert UTC time to EDT. I have a server in India. An application in it needs to use EDT time for all time purposes.
I am using .NET 3.5.
I found this on some other forum.
```
DateTime eastern = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(
DateTime.UtcNow, "Eastern Standard Time");
```
When i tried with "Easten Daylight Time" I got an error.
> "The time zone ID 'Eastern Daylight Time' was not found on the local computer".
Please help with this or any other solution. | Eastern Daylight Time isn't the name of a "full" time zone - it's "half" a time zone, effectively, always 4 hours behind UTC. (There may be proper terminology for this, but I'm not aware of it.)
Why would you want to use EDT for times which don't have daylight savings applied? If you want a custom time zone that always has the same offset to UTC, use [`TimeZoneInfo.CreateCustomTimeZone`](http://msdn.microsoft.com/en-us/library/bb309898.aspx).
Note that if you use get the Eastern Standard timezone (`TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")`) then that will still have daylight saving time applied appropriately (i.e. during summer).
For example:
```
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
// Prints True
Console.WriteLine(tzi.IsDaylightSavingTime(new DateTime(2009, 6, 1)));
// Prints False
Console.WriteLine(tzi.IsDaylightSavingTime(new DateTime(2009, 1, 1)));
``` | I would have said that you should use UTC for calculations of time periods, so that you avoid issues of daylight saving time and then use LocalTime for display only.
DateTime.ToLocalTime for UTC to whatever the local time zone is and then DateTime.ToUniversalTime to convert from local time to UTC.
**Edit after comment 1**
Do I take it then that you're after displaying a different timezone to that of the server?
If you're using web pages to access your server then use
HttpRequest.UserLanguages to help create a CultureInfo object and use that to parse your DateTime object.
Look here for a full explanation:[Microsoft link on displaying local user time for web pages.](http://msdn.microsoft.com/en-us/library/bb882561.aspx)
If you're using client-server architecture then if the LocalTime call is on the client side it will display the LocalTime for the client. You then convert it to UTC to send back to your server.
Either way your server doesn't need to know where the client is so if you have multiple clients in multiple timezones then all calculations will match. It will also allow you to show the times in any timezone that you wish by use of different Culture objects.
**Edit 2 copied my second comment**
You can get time data in UTC format from the server. Then you can convert it using DateTime.ToLocalTime or DateTime.ToUniversalTime as requried. If you're including dates as well and need to cope with say US MM/dd/yyyy and european dd/MM/yyyy formats the you can use CultureInfo class to parse the DateTime value accordingly. It sounds like more work than what you have at the moment, but it would mean that if you move your server again then you don't need to recode the DateTime handling.
**A new point**
Another point to look at is clock synchronisation between the server and the clients using NTP (Network Time Protocol) or SNTP (Simple Network Time Protocol) if it is accurate enough. I don't know what OS you are using but this is used by Windows Server time services to synchronise networks. | How to convert time between timezones (UTC to EDT)? | [
"",
"c#",
"timezone",
""
] |
What exactly must I replace *???* with to get the iterator (**it**) to some element (for example `Base(2)`) ?
I tried a few shots but nothing, compiler just says that it is wrong.
Here is code
```
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
class Base
{
public:
Base(int a) {ina = a;}
~Base() {}
int Display() {return ina;}
int ina;
};
int main(int argc, char *argv[])
{
vector<Base> myvector;
for(int i=0 ; i<10 ; i++)
{
myvector.push_back(Base(i));
}
vector<Base>::iterator it;
it = find(myvector.begin(), myvector.end(), ??? );
system("PAUSE");
return EXIT_SUCCESS;
}
```
Thanks in advance ! | The third parameter is just the value you look for.
```
it = find(myvector.begin(), myvector.end(), Base(2));
```
The problem is now that the compiler needs to know whether two elements are equal. So you'll have to implement an operator for equality-checking (write this code between `main` and your class definition):
```
// a equals b if a.ina equals b.ina
bool operator == (const Base& a, const Base& b) {
return a.ina == b.ina;
}
```
If you just want to get the nth element of `myvector`, you can also just write `myvector.begin() + n`. | You can just do myvector.begin() + n to get an iterator to the nth element of myvector. | Help with std::find | [
"",
"c++",
"stl",
""
] |
I wrote a method (that works fine) for `a()` in a class. I want to write another method in that class that calls the first method so:
```
void A::a() {
do_stuff;
}
void A::b() {
a();
do_stuff;
}
```
I suppose I could just rewrite `b()` so `b(A obj)` but I don't want to. In java can you do something like `this.a()`.
I want to do `obj.b()` where `obj.a()` would be called as a result of `obj.b()`. | That's exactly what you are doing. | What you have should work fine. You can use "this" if you want to:
```
void A::b() {
this->a();
do_stuff;
}
```
or
```
void A::b() {
this->A::a();
do_stuff;
}
```
or
```
void A::b() {
A::a();
do_stuff;
}
```
but what you have should also work:
```
void A::b() {
a();
do_stuff;
}
``` | Calling a method from another method in the same class in C++ | [
"",
"c++",
"methods",
""
] |
I'm trying to create a J2ME app, which talks to webserver using `HttpConnection` connector.
When I am talking to the WebServer, I have to authenticate using Basic HTTP auth, which normally goes like
`http://username:password@website.com/rest/api/method`
But in J2ME, when I construct a url of this form, it doesn't work.
I also tried adding request property,
`hc = (HttpConnection) Connector.open(url);
hc.setRequestProperty("User", "alagu");
hc.setRequestProperty("pass", "mypassword");`
but didn't work.
Has anyone done j2me based HTTP auth before? Thanks in advance. | It could be J2ME has no support for basic authentication, I might be wrong. If you want to try just setting the authentication header in the request yourself you'll likely need a different header then what you're using.
From the [rfc](http://www.ietf.org/rfc/rfc2617.txt):
> To receive authorization, the client sends the userid and password,
> separated by a single colon (":") character, within a base64 [7]
> encoded string in the credentials.
>
> [...]
>
> If the user agent wishes to send the userid "Aladdin" and password
> "open sesame", it would use the following header field:
>
> ```
> Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
> ```
So just create the string "User:Password", base64 encode it and then call `setRequestProperty("Authorization", "Basic "+ encodedUserAndPass)` | Incredible, it works like a charm:
```
String url = "hppt://www.example.com";
HttpConnection hc = (HttpConnection) Connector.open(url);
hc.setRequestProperty("Authorization", "Basic "+ BasicAuth.encode("user", "password"));
``` | HTTP authentication in J2ME | [
"",
"java",
"mobile",
"java-me",
"midp",
""
] |
How to determine a proper serial version ID? Should it be any big long value using some generators or any integer wld suffice ? | Frankly, as long as the `serialVersionUID` differs between the different versions of your class, that's all that matters.
What would be bad is if there are two versions of the same class with differing serializable fields having the same `serialVersionUID` -- that's probably going to cause a problem when performing serialization.
Additionally, if the changes to the class will not affect serialization (e.g. serializable fields in the class remain the same), then the `serialVersionUID` can remain the same.
IDEs like Eclipse will automatically generate an ID for classes which implement `Serializable` based on the fields and other information regarding the class, so that may be the easiest route to take to generate an unique ID.
For further reading on the topic, the [Discover the secrets of the Java Serialization API](http://java.sun.com/developer/technicalArticles/Programming/serialization/) would be a good read. There is a section called "Version Control" which discusses the `serialVersionUID` issue. | The serialver tool comes with Sun's Java Development Kit (JDK). It takes a full class name on the command line and returns the serial version ID for that compiled class, or can be run with the "-show" parameter to launch a small interactive GUI.
So if your class is Foo, run
serialver Foo
and you'll get some sort of output like this:
Foo: static final long serialVersionUID = -6618469841127325812L;
Take the code starting with "static" and place it inside your class with other static variables. Now the serial version ID is locked in the class. | How to determine a proper serial version ID? | [
"",
"java",
"serialization",
""
] |
I have a relatively simple question. Say I have a file but I only want to access line X of the file until line Y, whats the easiest way of doing that?
I know I can read in the lines one by one keeping count, until I reach the lines that I actually need, but is there a better more elegant solution?
Thanks. | In C++, no, not really (well, not in *any* language I'm familiar with, really).
You have to start at the start of the file so you can figure where line X starts (unless it's a fixed-record-length file but that's unlikely for text).
Similarly, you have to do that until you find the last line you're interested in.
You can read characters instead of lines if you're scared of buffer overflow exploits, or you can read in fixed-size block and count the newlines for speed but it all boils down to reading and checking every character (by your code explicitly or the language libraries implicitly) to count the newlines. | You can use istream::ignore() to avoid buffering the unneeded input.
```
bool skip_lines(std::istream &is, std::streamsize n)
{
while(is.good() && n--) {
is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return is.good();
}
``` | Reading line X until line Y from file in C++ | [
"",
"c++",
"file",
"input",
""
] |
I am trying to compile a c++ application using the following command in command prompt:
```
cl -I"c:\Program files\Java\jdk1.5.0_07\include" -I"c:\program files\java\jdk1.5.0_07\include\win32" -MD -LD HelloWorld.cpp -FeHelloWorld.dll
```
However, this produces the following error:
> LINK : fatal error LNK1104: cannot open file 'MSVCRT.lib'
Have you any ideas of what is causing this and how to fix it?
I have visual studio 2005 installed on windows.
Thanks,
-Pete | > LINK : fatal error LNK1104: cannot open file 'MSVCRT.lib'
>
> Any ideas of what is causing this and how to fix it?
The linker needs to be pointed to the location of MSVCRT.lib, as it doesn't seem to be in your LIBPATH.
It should be here: **C:\Program Files\Microsoft Visual Studio 7\VC\lib**
Add `-link -LIBPATH:"C:\Program Files\Microsoft Visual Studio 8\VC\lib"` | To Solve this Problem in MS Visual studio 2008.
1. Goto Menu Project->Properties (Alt+F7)
2. Configuration Properties
3. Linker -> General -> additional Library Directories -> C:\Program Files\Microsoft Visual Studio 9.0\VC\lib
....do the above steps and enjoy | Compiling C++ Program Causes "Fatal Error LNK1104" | [
"",
"c++",
"visual-studio",
"compilation",
""
] |
Simple question but this is killing my time.
Any simple solution to add 30 minutes to current time in php with GMT+8? | I think one of the best solutions and easiest is:
```
date("Y-m-d", strtotime("+30 minutes"))
```
Maybe it's not the most efficient but is one of the more understandable. | This is an old question that seems answered, but as someone pointed out above, if you use the DateTime class and PHP < 5.3.0, you can't use the add method, but you can use *modify*:
```
$date = new DateTime();
$date->modify("+30 minutes"); //or whatever value you want
``` | PHP Date Time Current Time Add Minutes | [
"",
"php",
""
] |
I know that this probably doesn't really matter, but I would like to know what is correct.
If a piece of code contains some version of `throw new SomeKindOfException()`. Do we say that this piece of code can potentially raise an exception? Or throw an exception?
The keyword is `throw`, so I am kind of leaning towards that, but to raise an exception is also used a lot...
Do they have some sort of different meaning? Does one of them sort of implicate a difference over the other? Or is it just two words meaning exactly the same thing? | In C# terminology, **raising** is used in the context of events and **throwing** is used in the context of exceptions.
Personally, I think `throw/catch` combination is more beautiful than `raise/catch`. | I can't speak for C#, but in C++ "throw" was chosen because "raise" was already taken as a standard function name. | C#: Do you raise or throw an exception? | [
"",
"c#",
"exception",
"terminology",
"throw",
"raise",
""
] |
I'm working on a little project for college, and I need to model transmission over network, and to impment and visualize different sorts of error correction algorithms. My improvized packet consists of one quint8: I need to convert it into a bit array, like QBitArray, append a check bit to it, trasfer it over UDP, check the success of transmission with the check bit, and then construct quint8 out of it.
Once again, it's not a practical but educational task, so don't suggest me to use real algoriths like CRC...
So my question is: **how do I convert any data type (in this case quint8) into QBitArray?** I mean any data in computer is a bit array, but how do I access it is the question.
Thanks, Dmitri. | Lets see if we can get it correct
```
template < class T >
static QBitArray toQBit ( const T &obj ) {
int const bitsInByte= 8;
int const bytsInObject= sizeof(T);
const quint8 *data = static_cast<const quint8*>(&obj) ;
QBitArray result(bytsInObject*bitsInByte);
for ( int byte=0; byte<bytsInObject ; ++byte ) {
for ( int bit=0; bit<bitsInByte; ++bit ) {
result.setBit ( byte*bitsInByte + bit, data[byte] & (1<<bit) ) ;
}
}
return result;
}
void Foo () {
Bar b ;
QBitArray qb = toQBit ( b ) ;
}
``` | qint8 is actually signed char. So you can treat your objs as a char array.
```
template < class T >
QBitArray toQBit ( T &obj ) {
int len = sizeof(obj) * 8 ;
qint8 *data = (qint8*)(&obj) ;
QBitArray result ;
for ( int i=0; i< sizeof(data); ++i ) {
for ( int j=0; j<8; ++j ) {
result.setBit ( i*8 + j, data[i] & (1<<j) ) ;
}
}
return result;
}
void Foo () {
Bar b ;
QBitArray qb = toQBit ( b ) ;
}
``` | C++ Qt: bitwise operations | [
"",
"c++",
"qt",
"bit-manipulation",
""
] |
I want to convert a `byte*` to a `byte[]`, but I also want to have a reusable function to do this:
```
public unsafe static T[] Create<T>(T* ptr, int length)
{
T[] array = new T[length];
for (int i = 0; i < length; i++)
array[i] = ptr[i];
return array;
}
```
Unfortunately I get a compiler error because T might be a ".NET managed type" and we can't have pointers to *those*. Even more frustrating is that there is no generic type constraint which can restrict T to "unmanaged types". Is there a built-in .NET function to do this? Any ideas? | The method that could match what you are trying to do is [Marshal.Copy](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.copy.aspx), but it does not take the appropriate parameters to make a generic method.
Although there it is not possible to write a generic method with generic constraints that could describe what is possible, not every type can be allowed to be copied using an "unsafe" way. There are some exceptions; classes are one of these.
Here is a sample code:
```
public unsafe static T[] Create<T>(void* source, int length)
{
var type = typeof(T);
var sizeInBytes = Marshal.SizeOf(typeof(T));
T[] output = new T[length];
if (type.IsPrimitive)
{
// Make sure the array won't be moved around by the GC
var handle = GCHandle.Alloc(output, GCHandleType.Pinned);
var destination = (byte*)handle.AddrOfPinnedObject().ToPointer();
var byteLength = length * sizeInBytes;
// There are faster ways to do this, particularly by using wider types or by
// handling special lengths.
for (int i = 0; i < byteLength; i++)
destination[i] = ((byte*)source)[i];
handle.Free();
}
else if (type.IsValueType)
{
if (!type.IsLayoutSequential && !type.IsExplicitLayout)
{
throw new InvalidOperationException(string.Format("{0} does not define a StructLayout attribute", type));
}
IntPtr sourcePtr = new IntPtr(source);
for (int i = 0; i < length; i++)
{
IntPtr p = new IntPtr((byte*)source + i * sizeInBytes);
output[i] = (T)System.Runtime.InteropServices.Marshal.PtrToStructure(p, typeof(T));
}
}
else
{
throw new InvalidOperationException(string.Format("{0} is not supported", type));
}
return output;
}
unsafe static void Main(string[] args)
{
var arrayDouble = Enumerable.Range(1, 1024)
.Select(i => (double)i)
.ToArray();
fixed (double* p = arrayDouble)
{
var array2 = Create<double>(p, arrayDouble.Length);
Assert.AreEqual(arrayDouble, array2);
}
var arrayPoint = Enumerable.Range(1, 1024)
.Select(i => new Point(i, i * 2 + 1))
.ToArray();
fixed (Point* p = arrayPoint)
{
var array2 = Create<Point>(p, arrayPoint.Length);
Assert.AreEqual(arrayPoint, array2);
}
}
```
The method can be generic, but it cannot take a pointer of a generic type. This is not an issue since pointers covariance is helping, but this has the unfortunate effect of preventing an implicit resolution of the generic argument type. You then have to specify MakeArray explicitly.
I've added a special case for the structures, where it is best to have types that specify a [struct layout](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.aspx). This might not be an issue in your case, but if the pointer data is coming from native C or C++ code, specifying a layout kind is important (The CLR might choose to reorder fields to have a better memory alignment).
But if the pointer is coming exclusively from data generated by managed code, then you can remove the check.
Also, if the performance is an issue, there are better algorithms to copy the data than doing it byte by byte. (See the countless implementations of memcpy for reference) | Seems that the question becomes: How to specify a generic Type to be a simple type.
```
unsafe void Foo<T>() : where T : struct
{
T* p;
}
```
Gives the error:
Cannot take the address of, get the size of, or declare a pointer to a managed type ('T') | C#: convert generic pointer to array | [
"",
"c#",
"arrays",
"unsafe",
""
] |
I want to get the path of my app like: "\\ProgramFiles\\myApp", I try to use the following code:
```
string path = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;
```
But it returns a path which has "\\myapp.exe" at the end.
I also tried:
```
string path = System.IO.Directory.GetCurrentDirectory();
```
But it throws an “NotSupportedException”.
Is there any way to get a path without .exe at the end? | ```
path = System.IO.Path.GetDirectoryName( path );
``` | `Application.StartupPath` should do that for you.
Update: from you edit I see that you are running on Compact Framework. Then Application.StartupPath will not work. This is the construct that I usually use then:
```
private static string GetApplicationPath()
{
return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
}
``` | How to get the path of app(without app.exe)? | [
"",
"c#",
"windows-mobile",
"compact-framework",
"filepath",
""
] |
I'm using .net 3.5. The problem here is that I cant seem to get the passwords to match. I have tried using the ComputeHash method on both, but it generates a different hash. As they are now the arrays are different sizes. (Obviously they are based on the same string). What have I done wrong? ("password" is byte[] param by user input)
```
object dataPassword = database.ExecuteScalar("GetUserPassword", new object[] {userName});
if(dataPassword != null && !(dataPassword is DBNull))
{
SHA1Managed hashProvider = new SHA1Managed();
byte[] hashedPassword = (byte[])dataPassword;
byte[] hash = hashProvider.ComputeHash(password);
result = hashedPassword.Equals(hash);
}
``` | You can't compare a `byte[]` like that. It just compares references. You should use a loop or use `IEnumerable<T>.SequenceEqual` extension method:
```
result = hashedPassword.SequenceEqual(hash);
```
Old way (pre-LINQ):
```
static bool ArrayEquals<T>(T[] first, T[] second) {
if (first == null && second == null) return true;
if (first == null || second == null) return false;
if (first.Length != second.Length) return false;
for (int i = 0; i < first.Length; ++i)
if (first[i] != second[i]) return false;
return true;
}
``` | It might have something to do with encoding. Try using the `UTF8Encoding` class and encoding the string with the `GetBytes` method.
You can also have a look at a set of [hashing classes I made for password verification at Google Code](http://code.google.com/p/blixt/source/browse/trunk/cs/Hashing/). | Comparing hash passwords | [
"",
"c#",
".net",
""
] |
simple one really, i've written a regular expression to find and replace tags with php constants from within a html snippet. my solution, which works, just doesn't feel right. how can this be improved?
```
preg_match_all('/\{CONSTANT_(.*)\}/', $final, $result, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($result[1]); $i++) {
$final = str_replace($result[0][$i], constant($result[1][$i]),$final);
}
``` | You can do it all in one hit with [preg\_replace\_callback](http://php.net/preg_replace_callback)
```
function getConstant($matches)
{
return constant($matches[1]);
}
$final=preg_replace_callback(
'/\{CONSTANT_(.*?)\}/',
"getConstant",
$final);
```
Note I've made the `.*` non greedy with `.*?`, this will have the effect of ensuring it doesn't go eating a } if a longer match is possible. You could get the same effect with `([^}]*)`, or better yet, `([a-zA-Z0-9_]+)` | I'm always against reinventing the wheel: if you need some sort of template engine (which php already is) take a look at [Smarty](http://www.smarty.net). | can this regular expression find/replace be optimised? | [
"",
"php",
"regex",
""
] |
I have a generic
```
List<MyClass>
```
where `MyClass` has a property `InvoiceNumber` which contains values such as:
200906/1
200906/2
..
200906/10
200906/11
200906/12
My list is bound to a
```
BindingList<T>
```
which supports sorting with linq:
```
protected override void ApplySortCore(
PropertyDescriptor property, ListSortDirection direction)
{
_sortProperty = property;
_sortDirection = direction;
var items = this.Items;
switch (direction)
{
case ListSortDirection.Ascending:
items = items.OrderByDescending(x => property.GetValue(x)).ToList();
break;
case ListSortDirection.Descending:
items = items.OrderByDescending(x => property.GetValue(x)).ToList();
break;
}
this.Items = items;
}
```
However the default comparer sorts (as supposed) like this:
200906/1
200906/10
200906/11
200906/12
200906/2
which is nasty in this case.
Now I want to use my own `IComparer<T>` with this. It looks like this:
```
public class MyComparer : IComparer<Object>
{
public int Compare(Object stringA, Object stringB)
{
String[] valueA = stringA.ToString().Split('/');
String[] valueB = stringB.ToString().Split('/');
if(valueA .Length != 2 || valueB .Length != 2)
return String.Compare(stringA.ToString(), stringB.ToString());
if (valueA[0] == valueB[0])
{
return String.Compare(valueA[1], valueB[1]);
}
else
{
return String.Compare(valueA[0], valueB[0]);
}
}
}
```
and changed the `ApplySortCore` code to use this `IComparer`:
```
case ListSortDirection.Ascending:
MyComparer comparer = new MyComparer();
items = items.OrderByDescending(
x => property.GetValue(x), comparer).ToList();
break;
```
When I debug my code, I see that `MyComparer.Compare(object, object)` is called multiple times and returns the right values (-1, 0, 1) for a compare method.
But my list is still sorted the "wrong" way. Am I missing something? I have no clue. | Your comparer looks wrong to me. You're still just sorting in the default text ordering. Surely you want to be parsing the two numbers and sorting based on that:
```
public int Compare(Object stringA, Object stringB)
{
string[] valueA = stringA.ToString().Split('/');
string[] valueB = stringB.ToString().Split('/');
if (valueA.Length != 2 || valueB.Length != 2)
{
stringA.ToString().CompareTo(stringB.ToString());
}
// Note: do error checking and consider i18n issues too :)
if (valueA[0] == valueB[0])
{
return int.Parse(valueA[1]).CompareTo(int.Parse(valueB[1]));
}
else
{
return int.Parse(valueA[0]).CompareTo(int.Parse(valueB[0]));
}
}
```
(Note that this doesn't sit well with your question stating that you've debugged through and verified that Compare is returning the right value - but I'm afraid I suspect human error on that front.)
Additionally, Sven's right - changing the value of `items` doesn't change your bound list at all. You should add:
```
this.Items = items;
```
at the bottom of your method. | I encountered the issue of general natural sorting and blogged the solution here:
[Natural Sort Compare with Linq OrderBy()](http://zootfroot.blogspot.com/2009/09/natural-sort-compare-with-linq-orderby.html)
```
public class NaturalSortComparer<T> : IComparer<string>, IDisposable
{
private bool isAscending;
public NaturalSortComparer(bool inAscendingOrder = true)
{
this.isAscending = inAscendingOrder;
}
#region IComparer<string> Members
public int Compare(string x, string y)
{
throw new NotImplementedException();
}
#endregion
#region IComparer<string> Members
int IComparer<string>.Compare(string x, string y)
{
if (x == y)
return 0;
string[] x1, y1;
if (!table.TryGetValue(x, out x1))
{
x1 = Regex.Split(x.Replace(" ", ""), "([0-9]+)");
table.Add(x, x1);
}
if (!table.TryGetValue(y, out y1))
{
y1 = Regex.Split(y.Replace(" ", ""), "([0-9]+)");
table.Add(y, y1);
}
int returnVal;
for (int i = 0; i < x1.Length && i < y1.Length; i++)
{
if (x1[i] != y1[i])
{
returnVal = PartCompare(x1[i], y1[i]);
return isAscending ? returnVal : -returnVal;
}
}
if (y1.Length > x1.Length)
{
returnVal = 1;
}
else if (x1.Length > y1.Length)
{
returnVal = -1;
}
else
{
returnVal = 0;
}
return isAscending ? returnVal : -returnVal;
}
private static int PartCompare(string left, string right)
{
int x, y;
if (!int.TryParse(left, out x))
return left.CompareTo(right);
if (!int.TryParse(right, out y))
return left.CompareTo(right);
return x.CompareTo(y);
}
#endregion
private Dictionary<string, string[]> table = new Dictionary<string, string[]>();
public void Dispose()
{
table.Clear();
table = null;
}
}
``` | Use own IComparer<T> with Linq OrderBy | [
"",
"c#",
"linq",
"sql-order-by",
"icomparer",
""
] |
I'm trying to execute a query that currently works in phpMyAdmin but it does not working when executing it in .NET using the MySqlAdapter. This is the Sql statement.
```
SELECT @rownum := @rownum +1 rownum, t . *
FROM (
SELECT @rownum :=0
) r, (
SELECT DISTINCT
TYPE FROM `node`
WHERE TYPE NOT IN ('ad', 'chatroom')
)t
```
It is using the @rownum to number each distinct row that is returned from my inner scalar query. But if I use it in .NET it's assuming that the @rownum is a parameter and throwing an exception because I didn't define it.
```
using (var sqlConnection = new MySqlConnection(SOURCE_CONNECTION))
{
sqlConnection.Open();
MySqlDataAdapter sqlAdapter = new MySqlDataAdapter(SqlStatement, sqlConnection);
DataTable table = new DataTable();
sqlAdapter.Fill(table);
sqlConnection.Close();
return table;
}
```
Any ideas for how I could get around this problem? Or possible ways for me to get a line number? | I found this [blog](http://blog.tjitjing.com/index.php/2009/05/mysqldatamysqlclientmysqlexception-parameter-id-must-be-defined.html), which tells, that with newer versions of .net Connector you have to add
```
;Allow User Variables=True
```
to the connection string.
Compare my SO question [How can I use a MySql User Defined Variable in a .NET MySqlCommand?](https://stackoverflow.com/questions/5524632/how-can-i-use-a-mysql-user-defined-variable-in-a-net-mysqlcommand) | What version of the MySQL data provider are you using? You may need to update.
I found this in the [5.0 documentation](http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlcommand.html):
> Prior versions of the provider used the '@' symbol to mark parameters in SQL. This is incompatible with MySQL user variables, so the provider now uses the '?' symbol to locate parameters in SQL. To support older code, you can set 'old syntax=yes' on your connection string. If you do this, please be aware that an exception will not be throw if you fail to define a parameter that you intended to use in your SQL. | Is it possible to use a MySql User Defined Variable in a .NET MySqlCommand? | [
"",
"c#",
".net",
"mysql",
""
] |
This is a pretty simple question really. If I use `setInterval(something, 1000)`, can I be completely sure that after, say, 31 days it will have triggered "something" exactly `60*60*24*31` times? Or is there any risk for so called drifting? | Here's a benchmark you can run in Firefox:
```
var start = +new Date();
var count = 0;
setInterval(function () {
console.log((new Date() - start) % 1000,
++count,
Math.round((new Date() - start)/1000))
}, 1000);
```
First value should be as close to 0 or 1000 as possible (any other value shows how "off the spot" the timing of the trigger was.) Second value is number of times the code has been triggered, and third value is how many times the could *should* have been triggered. You'll note that if you hog down your CPU it can get quite off the spot, but it seems to correct itself. Try to run it for a longer period of time and see how it handles. | Short answer: No, you can't be sure. Yes, it can drift.
Long answer: John Resig on the [Accuracy of JavaScript Time](http://ejohn.org/blog/accuracy-of-javascript-time/) and [How JavaScript Timers Work](http://ejohn.org/blog/how-javascript-timers-work/).
From the second article:
> In order to understand how the timers work internally there's one important concept that needs to be explored: timer delay is not guaranteed. Since all JavaScript in a browser executes on a single thread asynchronous events (such as mouse clicks and timers) are only run when there's been an opening in the execution.
Both articles (and anything on that site) is great reading, so have at it. | Will setInterval drift? | [
"",
"javascript",
"setinterval",
""
] |
I'm trying to test for a /t or a space character and I can't understand why this bit of code won't work. What I am doing is reading in a file, counting the loc for the file, and then recording the names of each function present within the file along with their individual lines of code. The bit of code below is where I attempt to count the loc for the functions.
```
import re
...
else:
loc += 1
for line in infile:
line_t = line.lstrip()
if len(line_t) > 0 \
and not line_t.startswith('#') \
and not line_t.startswith('"""'):
if not line.startswith('\s'):
print ('line = ' + repr(line))
loc += 1
return (loc, name)
else:
loc += 1
elif line_t.startswith('"""'):
while True:
if line_t.rstrip().endswith('"""'):
break
line_t = infile.readline().rstrip()
return(loc,name)
```
Output:
```
Enter the file name: test.txt
line = '\tloc = 0\n'
There were 19 lines of code in "test.txt"
Function names:
count_loc -- 2 lines of code
```
As you can see, my test print for the line shows a /t, but the if statement explicitly says (or so I thought) that it should only execute with no whitespace characters present.
Here is my full test file I have been using:
```
def count_loc(infile):
""" Receives a file and then returns the amount
of actual lines of code by not counting commented
or blank lines """
loc = 0
for line in infile:
line = line.strip()
if len(line) > 0 \
and not line.startswith('//') \
and not line.startswith('/*'):
loc += 1
func_loc, func_name = checkForFunction(line);
elif line.startswith('/*'):
while True:
if line.endswith('*/'):
break
line = infile.readline().rstrip()
return loc
if __name__ == "__main__":
print ("Hi")
Function LOC = 15
File LOC = 19
``` | `\s` is only whitespace to the `re` package when doing pattern matching.
For `startswith`, an ordinary method of ordinary strings, `\s` is nothing special. Not a pattern, just characters. | Your question has already been answered and this is slightly off-topic, but...
If you want to parse code, it is often easier and less error-prone to use a parser. If your code is Python code, Python comes with a couple of parsers ([tokenize](http://docs.python.org/library/tokenize.html), [ast](http://docs.python.org/library/ast.html), [parser](http://docs.python.org/library/parser.html#module-parser)). For other languages, you can find a lot of parsers on the internet. [ANTRL](http://www.antlr.org/) is a well-known one with Python [bindings](http://www.antlr.org/wiki/display/ANTLR3/Example).
As an example, the following couple of lines of code print all lines of a Python module that are not comments and not doc-strings:
```
import tokenize
ignored_tokens = [tokenize.NEWLINE,tokenize.COMMENT,tokenize.N_TOKENS
,tokenize.STRING,tokenize.ENDMARKER,tokenize.INDENT
,tokenize.DEDENT,tokenize.NL]
with open('test.py', 'r') as f:
g = tokenize.generate_tokens(f.readline)
line_num = 0
for a_token in g:
if a_token[2][0] != line_num and a_token[0] not in ignored_tokens:
line_num = a_token[2][0]
print(a_token)
```
As `a_token` above is already parsed, you can easily check for function definition, too. You can also keep track where the function ends by looking at the current column start `a_token[2][1]`. If you want to do more complex things, you should use ast. | str.startswith() not working as I intended | [
"",
"python",
"string",
"python-3.x",
""
] |
Currently my website is written in ASP.NET Webforms using a SQL Server database. I am planning to build a ASP.NET MVC application not because it's better but because I want to learn the technology. My question is more specific to the database. I can create the database and import my SQL table via the import feature of the web interface to the SQL database or I can use a "local" database MDF file. I like the idea of using a MDF file because it will be easier to backup and deal with. My website doesn't get a lot of traffic... matter of fact I could be the only user. :) Now here is the question.
How much of a performance hit will I get by using a local SQL Server MDF file instead for my database? | Effectively none. Or really none more than having the DB run on the same box as the web site. It is still a Sql Server Express database all the same. Production-wise, you probably want the DB running on a separate box dedicated to serving databases. But code-wise, the only difference will be your connection string. | SQL Server uses a MDF file for each database on its server. There is no difference between a MDF file and a 'database' because the 'database' gets stored in a MDF file anyway. | Is there a performance hit for using MDF SQL Server files instead of "database"? | [
"",
"c#",
"asp.net",
"sql-server",
"asp.net-mvc",
""
] |
In Visual Studio with C#, how can I declare a string inside of a string like this? I saw a few Stack Overflow pages like "Java string inside string to string", but didn't think any of them were the same as my question.
Basically if I have
```
"<?xml version="1.0" encoding="UTF-8"standalone="yes" ?>"
```
How can I declare this, or something like it, in my code as a string? Someone suggested double quotations to me around things like ""1.0"", but I couldn't get that to work.
Thanks for the help. | Either escape the double quotes like this:
```
"<?xml version=\"1.0\" encoding=\"UTF-8\"standalone=\"yes\" ?>"
```
or use a verbatim string (notice the leading **@** symbol in front of the string) like this:
```
@"<?xml version=""1.0"" encoding=""UTF-8""standalone=""yes"" ?>"
``` | Either:
```
@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes"" ?>"
```
or
```
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>"
```
or more simply; use single quotes!
```
"<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>"
``` | String inside of a string Ex: pie = "He said "hi"" - C# | [
"",
"c#",
"string",
"escaping",
""
] |
I have an xml stored property of some control
```
<Prop Name="ForeColor" Type="System.Drawing.Color" Value="-16777216" />
```
I want to convert it back as others
```
System.Type type = System.Type.GetType(propertyTypeString);
object propertyObj =
TypeDescriptor.GetConverter(type).ConvertFromString(propertyValueString);
```
System.Type.GetType("System.Drawing.Color") returns null.
The question is how one can correctly get color type from string
(it will be better not to do a special case just for Color properties)
**Update**
from time to time this xml will be edited by hand | You need to specify the assembly as well as the type name when using [`Type.GetType()`](http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx), unless the type is in `mscorlib` or the currently executing assembly.
If you know it's in the `System.Drawing` assembly, you can use [`Assembly.GetType()`](http://msdn.microsoft.com/en-us/library/y0cd10tb.aspx) instead - or perhaps look in a whole list of possible assemblies:
```
Type type = candidateAssemblies.Select(assembly => assembly.GetType(typeName))
.Where(type => type != null)
.FirstOrDefault();
if (type != null)
{
// Use it
}
else
{
// Couldn't find the right type
}
``` | Do you have the System.Drawing assembly loaded? Do you have a reference to it? | How can I get System.Type from "System.Drawing.Color" string | [
"",
"c#",
".net",
"reflection",
".net-2.0",
""
] |
In one C# maintenance project I came across following variable declaration:
```
Int32* iProgressAddress;
```
Is it pointer declaration in C#?
I thought that there is no pointer concept in C#, what does that statement mean? | C# does support pointers, but it's limited to pointing to primitive data types that are unmanaged types, such as ints, floats, enums, and other pointer types (plus the rest of the primitives).
**edit**: as well as value types | Yes, it is.
Notice, that the method is marked `unsafe`. As well as the assembly.
There is a lot of things to know before using pointers from the managed code.
For instance, pointer pinning. | Pointers in C#? | [
"",
"c#",
".net",
"pointers",
""
] |
I've noticed in several examples i see things such as this:
```
# Comments explaining code i think
@innerclass
```
or:
```
def foo():
"""
Basic Doc String
"""
@classmethod
```
Googling doesn't get me very far, for just a general definition of what this is. Also i cant find anything really in the python documentation.
What do these do? | They're decorators.
`<shameless plug>`
I have a [blog post](http://jasonmbaker.wordpress.com/2009/04/25/the-magic-of-python-decorators/) on the subject.
`</shameless plug>` | They are called decorators. They are functions applied to other functions. Here is a copy of my answer to a similar question.
Python decorators add extra functionality to another function.
An italics decorator could be like
```
def makeitalic(fn):
def newFunc():
return "<i>" + fn() + "</i>"
return newFunc
```
Note that a function is defined inside a function. What it basically does is replace a function with the newly defined one. For example, I have this class
```
class foo:
def bar(self):
print "hi"
def foobar(self):
print "hi again"
```
Now say, I want both functions to print "---" after and before they are done. I could add a print "---" before and after each print statement. But because I don't like repeating myself, I will make a decorator
```
def addDashes(fn): # notice it takes a function as an argument
def newFunction(self): # define a new function
print "---"
fn(self) # call the original function
print "---"
return newFunction
# Return the newly defined function - it will "replace" the original
```
So now I can change my class to
```
class foo:
@addDashes
def bar(self):
print "hi"
@addDashes
def foobar(self):
print "hi again"
```
For more on decorators, check <http://www.ibm.com/developerworks/linux/library/l-cpdecor.html> | Purpose of @ symbols in Python? | [
"",
"python",
""
] |
How can I test the following method?
It is a method on a concrete class implementation of an interface.
I have wrapped the `Process` class with an interface that only exposes the methods and properties I need. The `ProcessWrapper` class is the concrete implementation of this interface.
```
public void Initiate(IEnumerable<Cow> cows)
{
foreach (Cow c in cows)
{
c.Process = new ProcessWrapper(c);
c.Process.Start();
count++;
}
}
``` | There are two ways to get around this. The first is to use dependency injection. You could inject a factory and have `Initiate()` call the create method to get the kind of `ProcessWrapper` you need for your test.
The other solution is to use a mocking framework such as TypeMock, that will let you work around this. TypeMock basically allows you to mock anything, so you could use it to provide a mock object instead of the actual ProcessWrapper instances. | I'm not familiar with C# (I prefer mine without the hash), but you need some sort of interface to the process (IPC or whatever is the most convenient method) so you can send it test requests and get results back. At the simplest level, you would just send a message to the process and receive the result. Or you could have more granularity and send more specific commands from your test harness. It depends on how you have set up your unit testing environment, more precisely how you send the test commands, how you receive them and how you report the results.
I would personally have a test object inside the process that simply receives, runs & reports the unit test results and have the test code inside that object. | How do I unit test code that creates a new Process? | [
"",
"c#",
"unit-testing",
"tdd",
""
] |
I have a big (probably) javascript problem.
i have a long and complex script on the page based on mootools framework,
in FF and other browser everything works fine, but in ie 6 and 7 i got "error:153 (sometimes 84) Unspecified error" and the strange thing is in IE8 that show me the error "Object doesn't support this property or method".
someone know the possible cause of the problem? o maybe someone know a list of IE's unsupported property or method? | In IE8 you can get the line number of the error, then right-click -> view source. IE8 has a proper source, which includes script lines, so you should quickly be able to find the source of your error. | If the script you're using isn't obfuscated or all on one line, you could use the JavaScript debugger in IE8 to pinpoint the object which is causing the error. Press F12 to open the Developer Tools, go to the Script tab, and click the "Start Debugging" option. If there's an error it may well break on the relevant line. If not you can set some breakpoints and step through the code. | IE and unspecified error and in IE8 object doesn't support method | [
"",
"javascript",
""
] |
Is there any good reason to avoid unused import statements in Java? As I understand it, they are there for the compiler, so lots of unused imports won't have any impacts on the compiled code. Is it just to reduce clutter and to avoid naming conflicts down the line?
(I ask because Eclipse gives a warning about unused imports, which is kind of annoying when I'm developing code because I don't want to remove the imports until I'm pretty sure I'm done designing the class.) | I don't think that performance problems or something like that are likely if you are not removing the imports.
But there could be naming conflicts, in rare cases like importing the list interface.
In Eclipse you can always use a shortcut (depends on OS - Win: `Ctrl + SHIFT + O` and Mac: `COMMAND + SHIFT + O`) to organize the imports. Eclipse then cleans up the import section removes all the stale imports etc. If you are needing a imported thing again eclipse will add them automatically while you are completing the statement with `Ctrl + SPACE`. So there is no need in keeping unused code in you class.
As always unused code will distract you and other people while reading the code and leaving something in your active code because of maybe I need it later is mostly seen as bad practice. | One would be that if you remove the class referenced by the import from the classpath, you won't get a silly compiler error that served no purpose. And you won't get false positives when you perform a "where used" search.
Another (but this would be very specific in nature) would be if the unused import had naming conflicts with another import, causing you to use fully qualified names needlessly.
Addendum: Today the build server started failing compilation (not even test running) with an out of memory error. It ran fine forever and the check-ins didn't have any changes to the build process or significant additions that could explain this. After attempting to increase memory settings (this is running a 64 bit JVM on a 64 bit CentOS!) to something well beyond where the clients could compile, I examined the checkins one by one.
There was an improper import that a developer had used and abandoned (they used the class, auto-imported it, and then realized it was a mistake). That unused import pulled in a whole separate tier of the application which, while the IDE isn't configured to separate them, the build process is. That single import dragged in so many classes that the compiler attempted to compile without having the relevant dependent libraries in the classpath, that this caused so many issues that it caused the out of memory error. It took an hour to solve this problem caused by an unused import. | Any reason to clean up unused imports in Java, other than reducing clutter? | [
"",
"java",
"eclipse",
"coding-style",
"import",
""
] |
I want to convert `long` to `int`.
If the value of `long` > `int.MaxValue`, I am happy to let it wrap around.
What is the best way? | Just do `(int)myLongValue`. It'll do exactly what you want (discarding MSBs and taking LSBs) in `unchecked` context (which is the compiler default). It'll throw `OverflowException` in `checked` context if the value doesn't fit in an `int`:
```
int myIntValue = unchecked((int)myLongValue);
``` | ```
Convert.ToInt32(myValue);
```
Though I don't know what it will do when it's greater than int.MaxValue. | Can I convert long to int? | [
"",
"c#",
"types",
"int",
"type-conversion",
"long-integer",
""
] |
Are there any decent BitTorrent libraries for Java? I need to program a simple torrent client, but it would be great if I didn't have to write everything from scratch. | [Snark](http://www.staging.threerings.net/snark.html) by Three Rings is a very lightweight bitorrent library that will give you basic torrent features.
Was [originally](http://www.klomp.org/snark/) written by Mark Wielaard. A github source can be found here <https://github.com/akerigan/born-again-snark> | Turn's [TTorrent](http://mpetazzoni.github.io/ttorrent/) is a pure Java bit torrent library. | Java BitTorrent library | [
"",
"java",
"bittorrent",
""
] |
I need a simple function to create a path in Python where the parent may or may not exist.
From python documentation os.makedirs will fail if one of the parents exists.
I have written the below method as which works by makes as many sub directories as necessary.
Does this look efficient?
```
def create_path(path):
import os.path as os_path
paths_to_create = []
while not os_path.lexists(path):
paths_to_create.insert(0, path)
head,tail = os_path.split(path)
if len(tail.strip())==0: # Just incase path ends with a / or \
path = head
head,tail = os_path.split(path)
path = head
for path in paths_to_create:
os.mkdir(path)
``` | > "From python documentation `os.makedirs` will fail if one of the parents exists."
No, [`os.makedirs`](http://docs.python.org/library/os.html#os.makedirs) will fail if the directory itself already exists. It won't fail if just any of the parent directories already exists. | Here's my take, which lets the system libraries do all the path-wrangling. Any errors other than the directory already existing are propagated.
```
import os, errno
def ensure_dir(dirname):
"""
Ensure that a named directory exists; if it does not, attempt to create it.
"""
try:
os.makedirs(dirname)
except OSError, e:
if e.errno != errno.EEXIST:
raise
``` | Efficient way of creating recursive paths Python | [
"",
"python",
"path",
"operating-system",
""
] |
Is this bad practice to use php statements such as 'if' within a jquery function?
should I really just be writing loads more functions instead of limiting a few using php? it seems to work fine but was wondering if this is a major faux pax?
example:
this is a code snippet, basically if the php variable $url is equal to 'projects' then the code will come back with extra lines, otherwise these will be hidden from other pages. Does this make sense?
```
timer = setTimeout(function() {
$('li#contact').removeClass('cur');
$('li#$url').addClass('cur');
"; if($url=='projects') { echo"
$('ul.projects').fadeIn('slow');
$('ul.image_display').css('display', 'block');"; }
echo"
}, 8625);
``` | Not bad practice as sometimes a PHP variable's value will change what you want the code to do.
You will however have to use to open and close your PHP code. | This is a bad practice in terms of code readability and maintainability, in my opinion. If only because it's two languages embedded within each other, which means you can't understand it without parsing two languages, and for many people that causes a mental 'page fault' as they context switch between parsing JS and parsing PHP.
It is easy enough to have the javascript branch based on what page elements are present, and this is a preferred solution in my opinion. It's better than conditionally providing certain javascript (although I think providing different javascript may begin to make sense when you have an overwhelmingly large amount of js) and it's also better than branching based on URL... what happens when you go and refactor that?
If you really must branch which JS you supply based on PHP, I'd want to see them at least on separate lines... something like:
```
<?php if($stmt): ?>
$(javascript).code.goes.here
<?php else: ?>
$(alernative.javascript).code.goes.here
<?php endif; ?>
```
as that would be nicer than having to read and understand two languages in a single line/statement. | php statements within jquery | [
"",
"php",
"jquery",
"if-statement",
""
] |
I am trapping a `KeyDown` event and I need to be able to check whether the current keys pressed down are : `Ctrl` + `Shift` + `M` ?
---
I know I need to use the `e.KeyData` from the `KeyEventArgs`, the `Keys` enum and something with Enum Flags and bits but I'm not sure on how to check for the combination. | You need to use the [Modifiers](http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.modifiers.aspx) property of the KeyEventArgs class.
Something like:
```
//asumming e is of type KeyEventArgs (such as it is
// on a KeyDown event handler
// ..
bool ctrlShiftM; //will be true if the combination Ctrl + Shift + M is pressed, false otherwise
ctrlShiftM = ((e.KeyCode == Keys.M) && // test for M pressed
((e.Modifiers & Keys.Shift) != 0) && // test for Shift modifier
((e.Modifiers & Keys.Control) != 0)); // test for Ctrl modifier
if (ctrlShiftM == true)
{
Console.WriteLine("[Ctrl] + [Shift] + M was pressed");
}
``` | I think its easiest to use this:
`if(e.KeyData == (Keys.Control | Keys.G))` | C#: Getting the correct keys pressed from KeyEventArgs' KeyData | [
"",
"c#",
"enums",
"enum-flags",
"keyeventargs",
""
] |
I have a a strange problem that I can't seem to identify the cause of.
When I use Zend\_Currency to format a value to to GBP I get an accented A before the £ symbol. If ask it to return any other curreny such as USD the accented A disappears.
The code that is generating this is:
```
$currency = new Zend_Currency('en_GB');
$amount = $currency->toCurrency($value);
```
This displays
```
£ 500.00
```
If I set to en\_US I get
```
$ 500.00
```
Any ideas of why this could be?
Thanks... | 'funny' characters are generally an encoding/display issue. Make sure you are setting the script to output as UTF8 - check your HTML/Xml headers / content-type.
```
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
``` | When you check your encoding, you need to make the HTTP headers match also. If your server is sending the page as ISO8891 and your HTML is self specifying as UTF8, you may have issues in some browsers, choosing the incorrect encoding.
In php you can use the [`header()`](http://php.net/manual/en/function.header.php) builtin function to send http headers to the client. eg;
```
header('Content-Type: text/html; charset=utf-8');
``` | Why when printing GBP symbol using Zend_Currency I get an accented A returned? | [
"",
"php",
"zend-framework",
"currency",
""
] |
I'm including a local class that requests a file from a remote server. This process is rather unreliable — because the remote server is often overloaded — and I sometimes have to wait 20 or so seconds before the include gives up and continues.
I would like to have a limit on the execution time of the included script; say, five seconds.
Current code:
```
include('siteclass.class.php');
```
**Update:**
My code inside the class:
```
$movie = str_replace(" ","+",$movie);
$string = join('',file($siteurl.$l.'/moviename-'.$movie));
if(!$i) { static $i = 1;}
if($file_array = $string)
{
$result = Return_Substrings($file_array, '<item>', '</item>');
foreach($result as $res) {
```
That's basically it, as far as the loading goes. The internal processing takes about 0.1 s. I guess that's pretty doable. | Note that I didn't test this code, take this like a proposition :
```
$fp = fopen('siteclass.class.php', 'r');
stream_set_timeout($fp, 2);
stream_set_timeout($fp,$timeout);
$info = stream_get_meta_data($fp);
if ($info['timed_out']) {
echo "Connection Timed Out!";
} else {
$file = '';
while (!feof($fp)) {
$file .= fgets($fp);
}
eval($file);
}
```
The timeout is set in seconds, so the example set it to two seconds. | This isn't an exact fit to what you're looking for, but this will set the time limit for the include and execution to a total of 25 seconds. If the time limit is reached, it throws a fatal error.
```
set_time_limit(25);
``` | How can I restrict the amount of time a PHP include will wait for a result? | [
"",
"php",
"include",
"timeout",
""
] |
I've got a trigger attached to a table.
```
ALTER TRIGGER [dbo].[UpdateUniqueSubjectAfterInsertUpdate]
ON [dbo].[Contents]
AFTER INSERT,UPDATE
AS
BEGIN
-- Grab the Id of the row just inserted/updated
DECLARE @Id INT
SELECT @Id = Id
FROM INSERTED
END
```
Every time a new entry is inserted or modified, I wish to update a single field (in this table). For the sake of this question, imagine i'm updating a LastModifiedOn (datetime) field.
Ok, so what i've got is a batch insert thingy..
```
INSERT INTO [dbo].[Contents]
SELECT Id, a, b, c, d, YouDontKnowMe
FROM [dbo].[CrapTable]
```
Now all the rows are correctly inserted. The LastModifiedOn field defaults to null. So all the entries for this are null -- EXCEPT the first row.
Does this mean that the trigger is NOT called for each row that is inserted into the table, but once AFTER the insert query is finished, ie. ALL the rows are inserted? Which mean, the INSERTED table (in the trigger) has not one, but 'n' number of rows?!
If so .. er.. :( Would that mean i would need a cursor in this trigger? (if i need to do some unique logic to each single row, which i do currently).
?
### UPDATE
I'll add the full trigger code, to see if it's possible to do it without a cursor.
```
BEGIN
SET NOCOUNT ON
DECLARE @ContentId INTEGER,
@ContentTypeId TINYINT,
@UniqueSubject NVARCHAR(200),
@NumberFound INTEGER
-- Grab the Id. Also, convert the subject to a (first pass, untested)
-- unique subject.
-- NOTE: ToUriCleanText just replaces bad uri chars with a ''.
-- eg. an '#' -> ''
SELECT @ContentId = ContentId, @ContentTypeId = ContentTypeId,
@UniqueSubject = [dbo].[ToUriCleanText]([Subject])
FROM INSERTED
-- Find out how many items we have, for these two keys.
SELECT @NumberFound = COUNT(ContentId)
FROM [dbo].[Contents]
WHERE ContentId = @ContentId
AND UniqueSubject = @UniqueSubject
-- If we have at least one identical subject, then we need to make it
-- unique by appending the current found number.
-- Eg. The first instance has no number.
-- Second instance has subject + '1',
-- Third instance has subject + '2', etc...
IF @NumberFound > 0
SET @UniqueSubject = @UniqueSubject + CAST(@NumberFound AS NVARCHAR(10))
-- Now save this change.
UPDATE [dbo].[Contents]
SET UniqueSubject = @UniqueSubject
WHERE ContentId = @ContentId
END
``` | Why not change the trigger to deal with multiple rows?
No cursor or loops needed: it's the whole point of SQL ...
```
UPDATE
dbo.SomeTable
SET
LastModifiedOn = GETDATE()
WHERE
EXIST (SELECT * FROM INSERTED I WHERE I.[ID] = dbo.SomeTable.[ID]
```
Edit: Something like...
```
INSERT @ATableVariable
(ContentId, ContentTypeId, UniqueSubject)
SELECT
ContentId, ContentTypeId, [dbo].[ToUriCleanText]([Subject])
FROM
INSERTED
UPDATE
[dbo].[Contents]
SET
UniqueSubject + CAST(NumberFound AS NVARCHAR(10))
FROM
--Your original COUNT feels wrong and/or trivial
--Do you expect 0, 1 or many rows.
--Edit2: I assume 0 or 1 because of original WHERE so COUNT(*) will suffice
-- .. although, this implies an EXISTS could be used but let's keep it closer to OP post
(
SELECT ContentId, UniqueSubject, COUNT(*) AS NumberFound
FROM @ATableVariable
GROUP BY ContentId, UniqueSubject
HAVING COUNT(*) > 0
) foo
JOIN
[dbo].[Contents] C ON C.ContentId = foo.ContentId AND C.UniqueSubject = foo.UniqueSubject
```
Edit 2: and again with RANKING
```
UPDATE
C
SET
UniqueSubject + CAST(foo.Ranking - 1 AS NVARCHAR(10))
FROM
(
SELECT
ContentId, --not needed? UniqueSubject,
ROW_NUMBER() OVER (PARTITION BY ContentId ORDER BY UniqueSubject) AS Ranking
FROM
@ATableVariable
) foo
JOIN
dbo.Contents C ON C.ContentId = foo.ContentId
/* not needed? AND C.UniqueSubject = foo.UniqueSubject */
WHERE
foo.Ranking > 1
``` | The trigger will be run only once for an INSERT INTO query. The INSERTED table will contain multiple rows. | Weird trigger problem when I do an INSERT into a table | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2008",
"triggers",
""
] |
I wrote this class for testing:
```
class PassByReference:
def __init__(self):
self.variable = 'Original'
self.change(self.variable)
print(self.variable)
def change(self, var):
var = 'Changed'
```
When I tried creating an instance, the output was `Original`. So it seems like parameters in Python are passed by value. Is that correct? How can I modify the code to get the effect of pass-by-reference, so that the output is `Changed`?
---
Sometimes people are surprised that code like `x = 1`, where `x` is a parameter name, doesn't impact on the caller's argument, but code like `x[0] = 1` does. This happens because *item assignment* and *slice assignment* are ways to **mutate** an existing object, rather than reassign a variable, despite the `=` syntax. See [Why can a function modify some arguments as perceived by the caller, but not others?](https://stackoverflow.com/questions/575196/) for details.
See also [What's the difference between passing by reference vs. passing by value?](https://stackoverflow.com/questions/373419/) for important, language-agnostic terminology discussion. | Arguments are [passed by assignment](http://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference). The rationale behind this is twofold:
1. the parameter passed in is actually a *reference* to an object (but the reference is passed by value)
2. some data types are mutable, but others aren't
So:
* If you pass a *mutable* object into a method, the method gets a reference to that same object and you can mutate it to your heart's delight, but if you rebind the reference in the method, the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object.
* If you pass an *immutable* object to a method, you still can't rebind the outer reference, and you can't even mutate the object.
To make it even more clear, let's have some examples.
## List - a mutable type
**Let's try to modify the list that was passed to a method:**
```
def try_to_change_list_contents(the_list):
print('got', the_list)
the_list.append('four')
print('changed to', the_list)
outer_list = ['one', 'two', 'three']
print('before, outer_list =', outer_list)
try_to_change_list_contents(outer_list)
print('after, outer_list =', outer_list)
```
Output:
```
before, outer_list = ['one', 'two', 'three']
got ['one', 'two', 'three']
changed to ['one', 'two', 'three', 'four']
after, outer_list = ['one', 'two', 'three', 'four']
```
Since the parameter passed in is a reference to `outer_list`, not a copy of it, we can use the mutating list methods to change it and have the changes reflected in the outer scope.
**Now let's see what happens when we try to change the reference that was passed in as a parameter:**
```
def try_to_change_list_reference(the_list):
print('got', the_list)
the_list = ['and', 'we', 'can', 'not', 'lie']
print('set to', the_list)
outer_list = ['we', 'like', 'proper', 'English']
print('before, outer_list =', outer_list)
try_to_change_list_reference(outer_list)
print('after, outer_list =', outer_list)
```
Output:
```
before, outer_list = ['we', 'like', 'proper', 'English']
got ['we', 'like', 'proper', 'English']
set to ['and', 'we', 'can', 'not', 'lie']
after, outer_list = ['we', 'like', 'proper', 'English']
```
Since the `the_list` parameter was passed by value, assigning a new list to it had no effect that the code outside the method could see. The `the_list` was a copy of the `outer_list` reference, and we had `the_list` point to a new list, but there was no way to change where `outer_list` pointed.
## String - an immutable type
**It's immutable, so there's nothing we can do to change the contents of the string**
**Now, let's try to change the reference**
```
def try_to_change_string_reference(the_string):
print('got', the_string)
the_string = 'In a kingdom by the sea'
print('set to', the_string)
outer_string = 'It was many and many a year ago'
print('before, outer_string =', outer_string)
try_to_change_string_reference(outer_string)
print('after, outer_string =', outer_string)
```
Output:
```
before, outer_string = It was many and many a year ago
got It was many and many a year ago
set to In a kingdom by the sea
after, outer_string = It was many and many a year ago
```
Again, since the `the_string` parameter was passed by value, assigning a new string to it had no effect that the code outside the method could see. The `the_string` was a copy of the `outer_string` reference, and we had `the_string` point to a new string, but there was no way to change where `outer_string` pointed.
I hope this clears things up a little.
**EDIT:** It's been noted that this doesn't answer the question that @David originally asked, "Is there something I can do to pass the variable by actual reference?". Let's work on that.
## How do we get around this?
As @Andrea's answer shows, you could return the new value. This doesn't change the way things are passed in, but does let you get the information you want back out:
```
def return_a_whole_new_string(the_string):
new_string = something_to_do_with_the_old_string(the_string)
return new_string
# then you could call it like
my_string = return_a_whole_new_string(my_string)
```
If you really wanted to avoid using a return value, you could create a class to hold your value and pass it into the function or use an existing class, like a list:
```
def use_a_wrapper_to_simulate_pass_by_reference(stuff_to_change):
new_string = something_to_do_with_the_old_string(stuff_to_change[0])
stuff_to_change[0] = new_string
# then you could call it like
wrapper = [my_string]
use_a_wrapper_to_simulate_pass_by_reference(wrapper)
do_something_with(wrapper[0])
```
Although this seems a little cumbersome. | The problem comes from a misunderstanding of what variables are in Python. If you're used to most traditional languages, you have a mental model of what happens in the following sequence:
```
a = 1
a = 2
```
You believe that `a` is a memory location that stores the value `1`, then is updated to store the value `2`. That's not how things work in Python. Rather, `a` starts as a reference to an object with the value `1`, then gets reassigned as a reference to an object with the value `2`. Those two objects may continue to coexist even though `a` doesn't refer to the first one anymore; in fact they may be shared by any number of other references within the program.
When you call a function with a parameter, a new reference is created that refers to the object passed in. This is separate from the reference that was used in the function call, so there's no way to update that reference and make it refer to a new object. In your example:
```
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
def Change(self, var):
var = 'Changed'
```
`self.variable` is a reference to the string object `'Original'`. When you call `Change` you create a second reference `var` to the object. Inside the function you reassign the reference `var` to a different string object `'Changed'`, but the reference `self.variable` is separate and does not change.
The only way around this is to pass a mutable object. Because both references refer to the same object, any changes to the object are reflected in both places.
```
def __init__(self):
self.variable = ['Original']
self.Change(self.variable)
def Change(self, var):
var[0] = 'Changed'
``` | How do I pass a variable by reference? | [
"",
"python",
"reference",
"parameter-passing",
"pass-by-reference",
""
] |
I have the following:
```
config = ConfigParser()
config.read('connections.cfg')
sections = config.sections()
```
How can I close the file opened with `config.read`?
In my case, as new sections/data are added to the `config.cfg` file, I update my wxtree widget. However, it only updates once, and I suspect it's because `config.read` leaves the file open.
And while we are at it, what is the main difference between `ConfigParser` and `RawConfigParser`? | Use [readfp](http://docs.python.org/library/configparser.html#ConfigParser.RawConfigParser.readfp) instead of read:
```
with open('connections.cfg') as fp:
config = ConfigParser()
config.readfp(fp)
sections = config.sections()
``` | `ConfigParser.read(filenames)` actually takes care of that for you.
While coding I have encountered this issue and found myself asking myself the very same question:
> *Reading basically means I also have to close this resource after I'm done with it, right?*
I read the answer you got here suggesting to open the file yourself and use `config.readfp(fp)` as an alternative. I looked at the [documentation](http://docs.python.org/2/library/configparser.html) and saw that indeed there is no `ConfigParser.close()`. So I researched a little more and read the ConfigParser code implementation itself:
```
def read(self, filenames):
"""Read and parse a filename or a list of filenames.
Files that cannot be opened are silently ignored; this is
designed so that you can specify a list of potential
configuration file locations (e.g. current directory, user's
home directory, systemwide directory), and all existing
configuration files in the list will be read. A single
filename may also be given.
Return list of successfully read files.
"""
if isinstance(filenames, basestring):
filenames = [filenames]
read_ok = []
for filename in filenames:
try:
fp = open(filename)
except IOError:
continue
self._read(fp, filename)
fp.close()
read_ok.append(filename)
return read_ok
```
This is the actual `read()` method from ConfigParser.py source code. As you can see, 3rd line from the bottom, `fp.close()` closes the opened resource after its usage in any case. This is offered to you, already included in the box with ConfigParser.read() :) | Closing file opened by ConfigParser | [
"",
"python",
"configparser",
""
] |
I am working on a calendar script where in i need to repeat a calendar event like
"Repeat on every 1st Tuesday of every month"
In the example above. How do you get the "1st"?
for example today is June 12,2009 this would mean it's "2nd Friday of June" How do i get the "2nd"?
Thanks in advance | Divide by 7 and round up:
```
ceil(date('j') / 7);
``` | This works:
```
<?php
$date = date('Y-m-d', mktime(0, 0, 0, date('m'), 1, date('y')));
echo date('Y-m-d', strtotime($date.'next tuesday'));
?>
```
The first line creates a date thats the first day of this month.
The second line get the next tuesday from $date.
You can do much more see [date](http://php.net/manual/en/function.date.php) and [mktime](http://www.php.net/manual/en/function.mktime.php) and [strtotime](https://www.php.net/manual/en/function.strtotime.php). | How do i determine the nth weekday of a given date in php | [
"",
"php",
"datetime",
"date",
""
] |
I need some help - I am trying to use a custom validation attribute in an ASP.NET MVC web project that needs to make a database call.
I have windsor successfully working for the controllers and the IRepository interface is injected normally. The problem arrises when I need to inject the repository into the attribute class.
The attribute class has the following code:
```
public class ValidateUniqueUrlNodeAttribute : AbstractValidationAttribute
{
private readonly string message;
private readonly IArticleRepository articleRepository;
public ValidateUniqueUrlNodeAttribute(string message)
{
this.message = message;
}
public ValidateUniqueUrlNodeAttribute(string message, IArticleRepository articleRepository):this(message)
{
this.articleRepository = articleRepository;
}
public override IValidator Build()
{
var validator = new UniqueUrlNodeValidator(articleRepository) { ErrorMessage = message };
ConfigureValidatorMessage(validator);
return validator;
}
```
My problem is that I cannot seem to make Windsor intercept the contruction of the attribute to pass in the IArticleRepository
The current code in my global.asax file is as follows:
```
container = new WindsorContainer();
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(Container));
container
.RegisterControllers(Assembly.GetExecutingAssembly())
.AddComponent<IArticleRepository, ArticleRepository>()
.AddComponent<ValidateUniqueUrlNodeAttribute>();
```
Any help would be greatly appreciated. | AFAIK no dependency injection container can directly manage an attribute, since it's instantiated by the runtime and there's no way to intercept that.
However, they can *cheat* by either:
1. Using a static gateway to the container ([example](https://stackoverflow.com/questions/553330/how-do-i-use-windsor-to-inject-dependencies-into-actionfilterattributes/553405#553405)), or
2. Using a "BuildUp" feature that injects whatever dependencies are found within an already-constructed object. This is called [BuildUp in Unity](http://msdn.microsoft.com/en-us/library/cc440949.aspx) or [InjectProperties in Autofac](http://code.google.com/p/autofac/wiki/ComponentCreation#Property_Injection).
Windsor doesn't support #2 ([ref1](https://stackoverflow.com/questions/447193), [ref2](https://stackoverflow.com/questions/851940)), so you can either:
1. Try one of the hacks to make Windsor support #2 ([hack1](http://www.jeremyskinner.co.uk/2008/11/08/dependency-injection-with-aspnet-mvc-action-filters/), [hack2](http://groups.google.com/group/castle-project-users/browse_thread/thread/98f27000d07683e4))
2. Use a [static gateway](https://rhino-tools.svn.sourceforge.net/svnroot/rhino-tools/trunk/commons/Rhino.Commons/RhinoContainer/IoC.cs)
3. Implement your own [IValidatorBuilder](https://svn.castleproject.org/svn/castle/trunk/Components/Validator/Castle.Components.Validator/IValidatorBuilder.cs) and make it use Windsor to create validators. I'm sure this is implemented somewhere but I can't find it right now... | Don't know if this helps, but I subclassed `ValidationAttribute` to expose a `Resolve<T>()` method like so:
```
public abstract class IocValidationAttribute : ValidationAttribute
{
protected T Resolve<T>()
{
return IocHelper.Container().Resolve<T>();
}
}
```
Then it can be used in any custom ValidatorAttribute that needs to hit a database:
```
public class UniqueEmailAttribute : IocValidationAttribute
{
public override bool IsValid(object value)
{
ICustomerRepository customerRepository = Resolve<ICustomerRepository>();
return customerRepository.FindByEmail(value.ToString()) == null;
}
}
```
I think it's a variation of the 'Static Gateway' approach mentioned by Mauricio Scheffer. I don't know if this is a good design or not. I'm not a huge fan of it, I'd rather the dependency was injected more 'elegantly', though I can't use constructor injection obviously, I'd like to use Property injection but can't work out a way to hook into the ASP.NET MVC framework code to do this (I've even pored though the MVC2 source code). | Database injection into a validation attribute with ASP MVC and Castle Windsor | [
"",
"c#",
"asp.net-mvc",
"castle-windsor",
""
] |
My priority queue declared as:
```
std::priority_queue<*MyClass> queue;
class MyClass {
bool operator<( const MyClass* m ) const;
}
```
is not sorting the items in the queue.
What is wrong? I would not like to implement a different (Compare) class.
**Answer summary:**
The problem is, the pointer addresses are sorted. The only way to avoid this is a class that 'compares the pointers'.
Now implemented as:
```
std::priority_queue<*MyClass, vector<*MyClass>, MyClass::CompStr > queue;
class MyClass {
struct CompStr {
bool operator()(MyClass* m1, MyClass* m2);
}
}
``` | Give the que the Compare functor ptr\_less.
If you want the ptr\_less to be compatible with the rest of the std library (binders, composers, ... ):
```
template<class T>
struct ptr_less
: public binary_function<T, T, bool> {
bool operator()(const T& left, const T& right) const{
return ((*left) <( *right));
}
};
std::priority_queue<MyClass*, vector<MyClass*>, ptr_less<MyClass*> > que;
```
Otherwise you can get away with the simplified version:
```
struct ptr_less {
template<class T>
bool operator()(const T& left, const T& right) const {
return ((*left) <( *right));
}
};
std::priority_queue<MyClass*, vector<MyClass*>, ptr_less > que;
``` | Since your `priority_queue` contains only pointer values, it will use the default comparison operator for the pointers - this will sort them by address which is obviously not what you want. If you change the `priority_queue` to store the class instances by value, it will use the operator you defined. Or, you will have to provide a comparison function. | How to implement sorting method for a c++ priority_queue with pointers | [
"",
"c++",
"priority-queue",
""
] |
I have a relatively complex console application which relies on several dlls. I would like to "ship" this in the best form. My preferred way would be an exe file with all dependencies embedded in it (not that big, about 800K). Another thing would be to just zip the contents of the "Debug" folder and make that available, but I'm not sure if everything will be available like that (will all dependencies be resolved just by zipping the debug folder?)
What reliable practices exist for deploying console apps written in C# using VisualStudio 2008? | If you just copy the Foo.exe, dlls and Foo.exe.config files, it's likely to be okay. Have a look at what else is in the debug folder though - you (probably) don't want to ship the .pdb files, or Foo.vshost.exe. Is there anything else? If you've got any items marked as Content which are copied to the output folder, you'll need those too.
You *could* use [ilmerge](http://research.microsoft.com/en-us/people/mbarnett/ilmerge.aspx) to put all the dependencies into one exe file, but I'm somewhat leery of that approach - I'd stick with exe + dependency dlls. | You should look into [setup projects](http://support.microsoft.com/kb/307353) in Visual Studio. They let you set up dependencies and include the DLLs you need. The end result is a setup.exe and an MSI installer.
Here's a [walkthrough](http://msdn.microsoft.com/en-us/library/k3bb4tfd(VS.71).aspx) that should help. | Ways to deploying console applications in C# | [
"",
"c#",
"visual-studio",
"console",
""
] |
Let's say I have a file-like object like StreamIO and want the python's warning module write all warning messages to it. How do I do that? | Try reassigning [warnings.showwarning](http://docs.python.org/library/warnings.html#warnings.showwarning) i.e.
```
#!/sw/bin/python2.5
import warnings, sys
def customwarn(message, category, filename, lineno, file=None, line=None):
sys.stdout.write(warnings.formatwarning(message, category, filename, lineno))
warnings.showwarning = customwarn
warnings.warn("test warning")
```
will redirect all warnings to stdout. | I think something like this would work, although it's untested code and the interface looks like there is a cleaner way which eludes me at present:
```
import warnings
# defaults to the 'myStringIO' file
def my_warning_wrapper(message, category, filename, lineno, file=myStringIO, line=None):
warnings.show_warning(message, category, filename, lineno, file, line)
warnings._show_warning = my_warning_wrapper
```
A look inside Lib\warnings.py should help put you on the right track if that isn't enough. | How to redirect python warnings to a custom stream? | [
"",
"python",
"warnings",
"io",
""
] |
How do I remove accentuated characters from a string?
Especially in IE6, I had something like this:
```
accentsTidy = function(s){
var r=s.toLowerCase();
r = r.replace(new RegExp(/\s/g),"");
r = r.replace(new RegExp(/[àáâãäå]/g),"a");
r = r.replace(new RegExp(/æ/g),"ae");
r = r.replace(new RegExp(/ç/g),"c");
r = r.replace(new RegExp(/[èéêë]/g),"e");
r = r.replace(new RegExp(/[ìíîï]/g),"i");
r = r.replace(new RegExp(/ñ/g),"n");
r = r.replace(new RegExp(/[òóôõö]/g),"o");
r = r.replace(new RegExp(/œ/g),"oe");
r = r.replace(new RegExp(/[ùúûü]/g),"u");
r = r.replace(new RegExp(/[ýÿ]/g),"y");
r = r.replace(new RegExp(/\W/g),"");
return r;
};
```
but IE6 bugs me, seems it doesn't like my regular expression. | With ES2015/ES6 [String.prototype.normalize()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize),
```
const str = "Crème Brulée"
str.normalize("NFD").replace(/[\u0300-\u036f]/g, "")
> "Creme Brulee"
```
Note: use `NFKD` if you want things like `\uFB01`(`fi`) normalized (to `fi`).
Two things are happening here:
1. `normalize()`ing to `NFD` Unicode normal form decomposes combined graphemes into the combination of simple ones. The `è` of `Crème` ends up expressed as `e` + `̀`.
2. Using a regex [character class](http://www.regular-expressions.info/charclass.html) to match the U+0300 → U+036F range, it is now trivial to globally get rid of the diacritics, which the Unicode standard conveniently groups as the [Combining Diacritical Marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) Unicode block.
As of 2021, one can also use [Unicode property escapes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Unicode_Property_Escapes):
```
str.normalize("NFD").replace(/\p{Diacritic}/gu, "")
```
See comment for performance testing.
**Alternatively, if you just want sorting**
[Intl.Collator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator) has sufficient support [~95% right now](https://caniuse.com/#search=intl.collator), a polyfill is also available [here](https://github.com/andyearnshaw/Intl.js/) but I haven't tested it.
```
const c = new Intl.Collator();
["creme brulee", "crème brulée", "crame brulai", "crome brouillé",
"creme brulay", "creme brulfé", "creme bruléa"].sort(c.compare)
["crame brulai", "creme brulay", "creme bruléa", "creme brulee",
"crème brulée", "creme brulfé", "crome brouillé"]
["creme brulee", "crème brulée", "crame brulai", "crome brouillé"].sort((a,b) => a>b)
["crame brulai", "creme brulee", "crome brouillé", "crème brulée"]
``` | I slightly modified khel version for one reason: Every regexp parse/replace will cost O(n) operations, where n is number of characters in target text. But, regexp is not exactly what we need. So:
```
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var defaultDiacriticsRemovalMap = [
{'base':'A', 'letters':'\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F'},
{'base':'AA','letters':'\uA732'},
{'base':'AE','letters':'\u00C6\u01FC\u01E2'},
{'base':'AO','letters':'\uA734'},
{'base':'AU','letters':'\uA736'},
{'base':'AV','letters':'\uA738\uA73A'},
{'base':'AY','letters':'\uA73C'},
{'base':'B', 'letters':'\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181'},
{'base':'C', 'letters':'\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E'},
{'base':'D', 'letters':'\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779\u00D0'},
{'base':'DZ','letters':'\u01F1\u01C4'},
{'base':'Dz','letters':'\u01F2\u01C5'},
{'base':'E', 'letters':'\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E'},
{'base':'F', 'letters':'\u0046\u24BB\uFF26\u1E1E\u0191\uA77B'},
{'base':'G', 'letters':'\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E'},
{'base':'H', 'letters':'\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D'},
{'base':'I', 'letters':'\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197'},
{'base':'J', 'letters':'\u004A\u24BF\uFF2A\u0134\u0248'},
{'base':'K', 'letters':'\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2'},
{'base':'L', 'letters':'\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780'},
{'base':'LJ','letters':'\u01C7'},
{'base':'Lj','letters':'\u01C8'},
{'base':'M', 'letters':'\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C'},
{'base':'N', 'letters':'\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4'},
{'base':'NJ','letters':'\u01CA'},
{'base':'Nj','letters':'\u01CB'},
{'base':'O', 'letters':'\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C'},
{'base':'OI','letters':'\u01A2'},
{'base':'OO','letters':'\uA74E'},
{'base':'OU','letters':'\u0222'},
{'base':'OE','letters':'\u008C\u0152'},
{'base':'oe','letters':'\u009C\u0153'},
{'base':'P', 'letters':'\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754'},
{'base':'Q', 'letters':'\u0051\u24C6\uFF31\uA756\uA758\u024A'},
{'base':'R', 'letters':'\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782'},
{'base':'S', 'letters':'\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784'},
{'base':'T', 'letters':'\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786'},
{'base':'TZ','letters':'\uA728'},
{'base':'U', 'letters':'\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244'},
{'base':'V', 'letters':'\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245'},
{'base':'VY','letters':'\uA760'},
{'base':'W', 'letters':'\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72'},
{'base':'X', 'letters':'\u0058\u24CD\uFF38\u1E8A\u1E8C'},
{'base':'Y', 'letters':'\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE'},
{'base':'Z', 'letters':'\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762'},
{'base':'a', 'letters':'\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250'},
{'base':'aa','letters':'\uA733'},
{'base':'ae','letters':'\u00E6\u01FD\u01E3'},
{'base':'ao','letters':'\uA735'},
{'base':'au','letters':'\uA737'},
{'base':'av','letters':'\uA739\uA73B'},
{'base':'ay','letters':'\uA73D'},
{'base':'b', 'letters':'\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253'},
{'base':'c', 'letters':'\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184'},
{'base':'d', 'letters':'\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A'},
{'base':'dz','letters':'\u01F3\u01C6'},
{'base':'e', 'letters':'\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD'},
{'base':'f', 'letters':'\u0066\u24D5\uFF46\u1E1F\u0192\uA77C'},
{'base':'g', 'letters':'\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F'},
{'base':'h', 'letters':'\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265'},
{'base':'hv','letters':'\u0195'},
{'base':'i', 'letters':'\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131'},
{'base':'j', 'letters':'\u006A\u24D9\uFF4A\u0135\u01F0\u0249'},
{'base':'k', 'letters':'\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3'},
{'base':'l', 'letters':'\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747'},
{'base':'lj','letters':'\u01C9'},
{'base':'m', 'letters':'\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F'},
{'base':'n', 'letters':'\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5'},
{'base':'nj','letters':'\u01CC'},
{'base':'o', 'letters':'\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275'},
{'base':'oi','letters':'\u01A3'},
{'base':'ou','letters':'\u0223'},
{'base':'oo','letters':'\uA74F'},
{'base':'p','letters':'\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755'},
{'base':'q','letters':'\u0071\u24E0\uFF51\u024B\uA757\uA759'},
{'base':'r','letters':'\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783'},
{'base':'s','letters':'\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B'},
{'base':'t','letters':'\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787'},
{'base':'tz','letters':'\uA729'},
{'base':'u','letters': '\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289'},
{'base':'v','letters':'\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C'},
{'base':'vy','letters':'\uA761'},
{'base':'w','letters':'\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73'},
{'base':'x','letters':'\u0078\u24E7\uFF58\u1E8B\u1E8D'},
{'base':'y','letters':'\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF'},
{'base':'z','letters':'\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763'}
];
var diacriticsMap = {};
for (var i=0; i < defaultDiacriticsRemovalMap .length; i++){
var letters = defaultDiacriticsRemovalMap [i].letters;
for (var j=0; j < letters.length ; j++){
diacriticsMap[letters[j]] = defaultDiacriticsRemovalMap [i].base;
}
}
// "what?" version ... http://jsperf.com/diacritics/12
function removeDiacritics (str) {
return str.replace(/[^\u0000-\u007E]/g, function(a){
return diacriticsMap[a] || a;
});
}
var paragraph = "L'avantage d'utiliser le lorem ipsum est bien évidemment de pouvoir créer des maquettes ou de remplir un site internet de contenus qui présentent un rendu s'approchant un maximum du rendu final. \n Par défaut lorem ipsum ne contient pas d'accent ni de caractères spéciaux contrairement à la langue française qui en contient beaucoup. C'est sur ce critère que nous proposons une solution avec cet outil qui générant du faux-texte lorem ipsum mais avec en plus, des caractères spéciaux tel que les accents ou certains symboles utiles pour la langue française. \n L'utilisation du lorem standard est facile d’utilisation mais lorsque le futur client utilisera votre logiciel il se peut que certains caractères spéciaux ou qu'un accent ne soient pas codés correctement. \n Cette page a pour but donc de pouvoir perdre le moins de temps possible et donc de tester directement si tous les encodages de base de donnée ou des sites sont les bons de plus il permet de récuperer un code css avec le texte formaté !";
alert(removeDiacritics(paragraph));
```
To test my theory I wrote a test in <http://jsperf.com/diacritics/12>. Results:
Testing in Chrome 28.0.1500.95 32-bit on Windows 8 64-bit:
Using Regexp
4,558 ops/sec ±4.16%. 37% slower
String Builder style
7,308 ops/sec ±4.88%. fastest
## Update
Testing in Chrome 33.0.1750 on Windows 8 64-bit:
Using Regexp
5,260 ±1.25% ops/sec 76% slower
Using @skerit version
22,138 ±2.12% ops/sec fastest
### Update - 19/03/2014
Adding missing "OE" diacritics.
### Update - 27/03/2014
Using a faster way to transverse a string using js - "What?" Version

### Update - 14/05/2014
Community wiki | Remove accents/diacritics in a string in JavaScript | [
"",
"javascript",
"diacritics",
""
] |
This may be a daft question as I can see the security reason for it to happen the way it does...
I have a licensing c# project, this has a class which has a method which generates my license keys. I have made this method private as I do not want anybody else to be able to call my method for obvious reasons
The next thing I want to do is to have my user interface, which is in another c# project which is referencing the licensing dll to be the only other 'thing' which can access this method outside of itself, is this possible or do i need to move it into the same project so that it all compiles to the same dll and I can access its members?
> LicensingProject
> -LicensingClass
> --Private MethodX (GeneratesLicenseKeys)
>
> LicensingProject.UI
> -LicensingUiClass
> --I want to be able to be the only class to be able to access MethodX
There is a reason why the license Key Generator is not just in the UI, that is because the licensing works by generating a hash on itself and compares it to the one generated by the License Generator.
I would prefer not to all compile to the dll as my end users do not need the UI code.
I know that by common sense a private method, is just that. I am stumped. | You could make it an internal method, and use [`InternalsVisibleToAttribute`](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx) to give LicensingProject.UI extra access to LicensingProject.
Merhdad's point about enforcement is right and wrong at the same time. If you don't have [ReflectionPermission](http://msdn.microsoft.com/en-us/library/system.security.permissions.reflectionpermission.aspx), the CLR will stop you from calling things you shouldn't - but if you're using reflection from a fully trusted assembly, you can call anything. You should assume that a potential hacker is able to run a fully trusted assembly on his own machine :)
None of this will stop someone from using [Reflector](http://www.red-gate.com/products/reflector/) to decompile your code. In other words, making it private isn't *really* adding a significant amount of security to your licensing scheme. If anyone actually puts any effort into breaking it, they'll probably be able to. | `public`, `private`, ... stuff are just enforced by the compiler. You can use reflection to access them pretty easily (assuming the code has required permissions, which is a reasonable assumption as he has complete control on the machine). Don't rely on that assuming nobody can call it. | access private method in a different assembly c# | [
"",
"c#",
"namespaces",
"private",
""
] |
I've worked with JSF, Spring MVC and Struts and I think I got a good level on these frameworks. Recently I heard that many good developers I worked with are learning Grails and using it in their projects.
What are the practical advantages of Grails over other frameworks? Is worth to learn it besides I know other frameworks? What is all the buzz around Grails, is it only because of Groovy?
NOTE: I did research in SO and the only related question I found was [this](https://stackoverflow.com/questions/24596/what-web-application-framework-for-java-is-recommended) and Grails is not mentioned | Grails is, like you say, built off Groovy which gives the immediate benefit of being more productive. The Groovy syntax is much terser than Java, it's much easier to do things in one line of Groovy code that would take you several in Java.
Grails specifically provides you with a number of advantages over other web frameworks (I can only talk for Struts 1.x, 2.x and SpringMVC however) - Grails is actually built on top of SpringMVC by the way and you can integrate other components using Spring.
* Database Migrations and Versioning - no more application out of sync with database schema syndrome. Most Java web apps suffer from this.
* Artefacts - which make creating new controllers and components easier. No more create a controller, configure it and stuff it into the right place in your web app. doh! Scaffolding also provides you with all some initial components to allow you to start building your pages and customising
* Simpler validation (def simpler than Struts 1.x), e.g. `username(size:6..10, blank:false)` specifies two validation rules for a username field to be of a specific length and non blank. It's a bit harder in the other Java web app frameworks.
* Built in Webflow (via Spring webflow) which makes creating complex workflows much simpler. Struts 2 can support Webflow, but via a plugin which is a little odd if I rememeber. Spring can too.
* Interceptors - SpringMVC also has these.
* Flash scope, see <http://grails.org/doc/docs/1.1/ref/Controllers/flash.html>
* Better data binding - Struts 2 is pretty good, much better than Struts 1. SpringMVC is also good.
There's a few more, check out the documentation for more details: <http://grails.org/doc/1.1.1/> | BTW, Grails is not considered as a Java Framework, its for Groovy. Groovy has the capability to work with Java seamlessly, but thats the different story.
Yes, its about Groovy, and like Java its awesomely good. Groovy follows the notion "Code less, do more", whereas Java is something like "Code more, do more". No offense to Java folks, I am one of you.
You might want to read these:
* [Success Stories of Grails](http://grails.org/Success+Stories)
* [Whats New in Groovy 1.6](http://www.infoq.com/articles/groovy-1-6) | What are the Grails advantages over other Java Web Frameworks? | [
"",
"java",
"grails",
"jakarta-ee",
""
] |
I am creating a \_\_get() function for a class to control access to my private member variables. Do I need to design the function to handle all possible member value reads or can I not write it for members that are public? Also, I am assuming that classes that inherit this class will use my \_\_get() function to access private members.
```
class ClassA{
private $collection = array();
public $value;
function __get($item){
return $collection[$item];
}
``` | No, you don't.
```
class A {
public $foo = 'bar';
private $private = array();
public function __get($key) {
echo 'Called __get() at line #' ,__LINE__, ' with key {', $key ,'}',"\n";
return $this->private[$key];
}
public function __set($key, $val) {
$this->private[$key] = $val;
}
}
$a = new A();
var_dump($a->foo);
$a->bar = 'baz';
var_dump($a->bar);
```
And yes, it will:
```
class B extends A { private $private = array(); }
$b = new B();
var_dump($b->bar);
``` | First of all PHP searches for property name in class definition and tries to return its value. If there's no property - PHP tries to call \_\_get($var) and here you can return anything you want. This is a little confusing behavior for those, who know Java-like getters/setters where you have to define them for every class member you want to access.
When it's comfortable to use Java-like getters/setters - you may write something like this:
```
public function __set($var, $value)
{
if (method_exists($this, $method = "_set_" . $var))
{
call_user_func(array($this, $method), $value);
}
}
public function __get($var)
{
if (method_exists($this, $method = "_get_" . $var))
{
return call_user_func(array($this, $method), $value);
}
}
```
and then use this code by defining custom getters/setters
```
protected function _get_myValue()
{
return $this->_myValue;
}
protected function _set_myValue($value)
{
$this->_myValue = $value;
}
```
and access to defined methods this way:
```
$obj->myValue = 'Hello world!';
``` | Does an overloaded __get need to manage all member variables? | [
"",
"php",
"variables",
"methods",
"overloading",
"member",
""
] |
I have taken an integer input and tried to reverse it in Python but in vain! I changed it into a string but still I am not able to. Is there any way to reverse it ? Is there any built-in function?
I am not able to convert the integer into a list so not able to apply the reverse function. | You can use the slicing operator to reverse a string:
```
s = "hello, world"
s = s[::-1]
print s # prints "dlrow ,olleh"
```
To convert an integer to a string, reverse it, and convert it back to an integer, you can do:
```
x = 314159
x = int(str(x)[::-1])
print x # prints 951413
``` | Code:
```
>>> n = 1234
>>> print str(n)[::-1]
4321
``` | String reversal in Python | [
"",
"python",
""
] |
I'm investigating the best place to set my error logging options, and it seems the most reliable place would be in .htaccess in the script subdirectory. But this particular script is run via cron, and therefore via command line.
Do php\_value settings made in .htaccess affect scripts that are not run through the web server? | No, `.htaccess` files are only read from the PHP httpd module. | .htaccess is used only by Apache. So the answer is NO. | Do .htaccess php_value settings affect scripts run at command line? | [
"",
"php",
".htaccess",
"command-line",
""
] |
I cannot set the default combobox selected value for an unbound combobox. Here is my code:
```
System.Console.WriteLine("Current Tag Org Id = " + CurrentTag.Org.OrgId);
ddlRUC.SelectedValue = CurrentTag.Org.OrgId;
System.Console.WriteLine("ddlRUC selected value = " + ddlRUC.SelectedValue);
```
Here is the output:
Current Tag Org Id = 285
ddlRUC selected value =
Note that ddlRUC.SelectedValue has not been set to 285. Does the datasource need to be bound in order to use the SelectedValue property? If so, how do I set the default item shown in a combobox that is not bound? | The SelectedValue property will only work for a databound listbox. If you can create your list items in a List<>, you can then bind the list to the control and SelectedValue will work as you would like. | A combobox (like a Listbox) has 2 mechanisms for dealing with the selection. Either:
1. You assign a List to the DataSource
property and set the ValueMember and
DisplayMember to the names of
properties of items of that list. Or,
2. You fill the Items property with
objects of your choice, the `ToString()`
will be displayed.
In scenario 1) you can use SelectedValue to get/set the selection based on the ValueMember.
in scenario 2) you use SelectedItem property instead of SelectedValue
So the question is, how do you fill the Items? | Windows.Form ComboBox Cannot set the SelectedValue Property of Unbound Control | [
"",
"c#",
"combobox",
""
] |
I have an application which spawns a new thread when a user asks for an image to be filtered.
This is the only type of task that I have and all are of equal importance.
If I ask for too many concurrent threads (Max I ever want is 9) the thread manager throws a **RejectedExecutionException**.
At the minute what I do is;
```
// Manage Concurrent Tasks
private Queue<AsyncTask<Bitmap,Integer,Integer>> tasks = new LinkedList<AsyncTask<Bitmap,Integer,Integer>>();
@Override
public int remainingSize() {
return tasks.size();
}
@Override
public void addTask(AsyncTask<Bitmap, Integer, Integer> task) {
try{
task.execute(currentThumbnail);
while(!tasks.isEmpty()){
task = tasks.remove();
task.execute(currentThumbnail);
}
} catch (RejectedExecutionException r){
Log.i(TAG,"Caught RejectedExecutionException Exception - Adding task to Queue");
tasks.add(task);
}
}
```
Simply add the rejected task to a queue and the next time a thread is started the queue is checked to see if there is a backlog.
The obvious issue with this is that if the final task gets rejected on its first attempt it will never be restarted (Until after it's no longer needed).
Just wondering if there's a simple model I should use for managing this sort of thing. I need tasks to notify the queue when they are done. | The reason for the `RejectedExecutionException` is because `AsyncTask` implements a thread pool of its own (per Mr. Martelli's answer), but one that is capped at a maximum of 10 simultaneous tasks. Why they have that limit, I have no idea.
Hence, one possibility is for you to clone `AsyncTask`, raise the limit (or go unbounded, which is also possible with `LinkedBlockingQueue`), and use your clone. Then, perhaps, submit the change as a patch to `AsyncTask` for future Android releases.
Click [here](http://www.google.com/codesearch?q=package%3Aandroid+asynctask) to run a Google Code Search for `AsyncTask` -- the first hit should be the implementation.
If you just want to raise the limit, adjust `MAXIMUM_POOL_SIZE` to be as big as you're likely to need. If you want to go unbounded, use the zero-argument `LinkedBlockingQueue` constructor instead of the one being presently used. AFAICT, the rest of the code probably stays the same. | You seem to have implemented a version of the [Thread Pool](http://en.wikipedia.org/wiki/Thread_pool) design pattern -- the wikipedia article points to many helpful articles on the subject, which may help you refine your implementation. I also recommend [this Java-specific article](http://kahdev.wordpress.com/2008/10/30/the-java-thread-pool/) which has clear code and explanation. | Simple Thread Management - Java - Android | [
"",
"java",
"android",
"multithreading",
""
] |
I have 3 radio buttons in my web page, like below:
```
<label for="theme-grey">
<input type="radio" id="theme-grey" name="theme" value="grey" />Grey</label>
<label for="theme-pink">
<input type="radio" id="theme-pink" name="theme" value="pink" />Pink</label>
<label for="theme-green">
<input type="radio" id="theme-green" name="theme" value="green" />Green</label>
```
In jQuery, I want to get the value of the selected radio button when any of these three are clicked. In jQuery we have id (#) and class (.) selectors, but what if I want to find a radio button by its name, as below?
```
$("<radiobutton name attribute>").click(function(){});
```
Please tell me how to solve this problem. | This should do it, all of this is in the [documentation](http://docs.jquery.com/Selectors/attributeEquals#attributevalue), which has a very similar example to this:
```
$("input[type='radio'][name='theme']").click(function() {
var value = $(this).val();
});
```
I should also note you have multiple identical IDs in that snippet. This is invalid HTML. Use classes to group set of elements, not IDs, as they should be unique. | To determine which radio button is checked, try this:
```
$('input:radio[name=theme]').click(function() {
var val = $('input:radio[name=theme]:checked').val();
});
```
The event will be caught for all of the radio buttons in the group and the value of the selected button will be placed in val.
*Update: After posting I decided that Paolo's answer above is better, since it uses one less DOM traversal. I am letting this answer stand since it shows how to get the selected element in a way that is cross-browser compatible.* | In jQuery, how do I select an element by its name attribute? | [
"",
"javascript",
"jquery",
"html",
"radio-button",
""
] |
I've created a header file called "list\_dec.h", put it in a folder "C:\Headers", and set my compiler to include files from "C:\Headers", so now I can do things like
```
#include<list_dec.h>
int main(){return(0);}
```
but when I try to do something like
```
#include<iostream>
#include<list_dec.h>
int main(){return(0);}
```
I get an error (not anything specific, just a huge list of syntax errors in "list\_dec.h", which I know aren't real because I've been able to compile it as both a main.cpp file and a .h file in a separate project). However, when I change to order so "list\_dec.h" is on top:
```
#include<list_dec.h>
#include<iostream>
int main(){return(0);}
```
all of the errors go away. So why does the order of the error matter?
NB: As far as I know, this occurs when I use "list\_dec.h" with all header files, but the files I'm absolutely positive it occurs in are:
```
#include<iostream>
#include<vector>
#include<time.h>
#include<stdlib.h>
```
EDIT: These are the errors I get when "list\_dec.h" is below any other header:
```
c:\headers\list_dec.h(14) : error C2143: syntax error : missing ')' before 'constant'
c:\headers\list_dec.h(51) : see reference to class template instantiation 'list<T,limit>' being compiled
c:\headers\list_dec.h(14) : error C2143: syntax error : missing ';' before 'constant'
c:\headers\list_dec.h(14) : error C2059: syntax error : ')'
c:\headers\list_dec.h(14) : error C2238: unexpected token(s) preceding ';'
c:\headers\list_dec.h(69) : warning C4346: 'list<T,limit>::{ctor}' : dependent name is not a type
prefix with 'typename' to indicate a type
c:\headers\list_dec.h(69) : error C2143: syntax error : missing ')' before 'constant'
c:\headers\list_dec.h(69) : error C2143: syntax error : missing ';' before 'constant'
c:\headers\list_dec.h(69) : error C2988: unrecognizable template declaration/definition
c:\headers\list_dec.h(69) : error C2059: syntax error : 'constant'
c:\headers\list_dec.h(69) : error C2059: syntax error : ')'
c:\headers\list_dec.h(78) : error C2065: 'T' : undeclared identifier
c:\headers\list_dec.h(78) : error C2065: 'limit' : undeclared identifier
c:\headers\list_dec.h(78) : error C2065: 'T' : undeclared identifier
c:\headers\list_dec.h(78) : error C2065: 'limit' : undeclared identifier
c:\headers\list_dec.h(79) : error C2143: syntax error : missing ';' before '{'
c:\headers\list_dec.h(79) : error C2447: '{' : missing function header (old-style formal list?)
```
If it helps, these are the lines mentioned in the errors (14, 69, 78, and 79):
Line 14: `list(const T& NULL); (A constructor for "list" class)`
Line 69: `inline list<T, limit>::list(const T& NULL): (Definition for the constructor, also, the colon at the end is intentional, It part of the definion ie: void x(int n): VAR(n).)`
Line 78: `inline list<T, limit>::list(const list<T, limit>& lst) (def for the copy constructor)`
Line 79: `{ (the begining of the list-copy contructor)`
And a lot of people want to see the beginning of "list\_dec.h":
```
template<class T, size_t limit>
class list
```
NB: These aren't the first lines, but they're where I think the problem is, the lines before them are simply an enumeration called "err".
EDIT: Just a note, "list\_dec.h" contains no includes, defines, ifdefs, or anything precede with a '#'. Besides the enumeration, it only contains the "list" class declaration and the "list" class member function definitions. | Generally speaking it should not, however it may be possible for there to be conflicting definitions of symbols or preprocessor macros that end up confusing the compiler. Try to narrow down the size of the problem by removing pieces and includes from the conflicting header until you can see what is causing it.
In response to the error messages you posted, the symbol `NULL` is often implemented as a preprocessor macro for the number 0. This is so that you can easily use it as a null pointer. Therefore this:
```
list(const T& NULL);
```
Could be converted into this syntax error by the preprocessor:
```
list(const T& 0);
```
Change the name of the parameter to something other than `NULL`. | Note that here:
`Line 14: list(const T& NULL); (A constructor for "list" class)`
`NULL` is the name of standard macro - when a standard header file is included before list\_dec.h it will most likely cause `NULL` to be defined which will in turn cause your code to look something like this to the compiler:
`list(const T& 0);`
The constant `0` above makes the line ill-formed C++. You might get more information by instructing your compiler to produce preprocessed output file. | Why does the order of my #includes matter? (C++) | [
"",
"c++",
"header",
"include",
""
] |
I want to fetch all the records of First\_Name, LastName, First Name Last Name in a mysql Query.
For example,
mytable looks like this:
```
rec Id First Name Last Name
1 Gnaniyar Zubair
2 Frankyn Albert
3 John Mathew
4 Suhail Ahmed
```
Output should be like this:
```
Gnaniyar Zubair, Frankyn Albert, John Mathew, Suhail Ahmed
```
Give me the SQL. | If this must the done in the query, you can use `GROUP_CONCAT`, but unless you're grouping by something it's a pretty silly query and the concatenation should really be done on the client.
```
SELECT GROUP_CONCAT(FirstName + ' ' + LastName
ORDER BY FirstName, LastName
SEPARATOR ', ') AS Names
FROM People;
``` | It is not a matter of getting one row with all the records, but a matter of representation of data. Therefore, I suggest to take a simple SELECT query, take the records you need, then arrange them in the view layer as you like.
On the other hand, why do you need to solve this record concatenation at SQL level and not on view level? | How to fetch values with a MySQL query? | [
"",
"sql",
"mysql",
""
] |
How do I make my python script wait until the user presses any key? | In **Python 3**, use `input()`:
```
input("Press Enter to continue...")
```
In **Python 2**, use `raw_input()`:
```
raw_input("Press Enter to continue...")
```
This only waits for the user to press enter though.
---
On Windows/DOS, one might want to use `msvcrt`. The `msvcrt` module gives you access to a number of functions in the Microsoft Visual C/C++ Runtime Library (MSVCRT):
```
import msvcrt as m
def wait():
m.getch()
```
This should wait for a key press.
---
Notes:
In Python 3, `raw_input()` does not exist.
In Python 2, `input(prompt)` is equivalent to `eval(raw_input(prompt))`. | In Python 3, use `input()`:
```
input("Press Enter to continue...")
```
In Python 2, use `raw_input()`:
```
raw_input("Press Enter to continue...")
``` | How do I wait for a pressed key? | [
"",
"python",
"wait",
"keyboard-input",
""
] |
Okay, simple situation: I'm writing a simple console application which connects to a SOAP web service. I've imported a SOAP Service reference and as a result, my application has a default endpoint build into it's app.config file.
The web service, however, can run on multiple servers and the URL to the proper web service is passed through the commandline parameters of my application. I can read the URL, but how do I connect the web service to this custom URL?
(It should be very simple, in my opinion. It's something I'm overlooking.) | Well, .NET can provide some very useless error messages sometimes. In IIS, the service was configured to AutoDetect cookieless mode. As a result, I had to append "?AspxAutoDetectCookieSupport=1" to the URL. Although that would fix the problem, it was just easier to go to the IIS console, open the properties of the service, go to the ASP.NET tab page, click the "Edit configuration" button, to to "State Management" in the newly popped up screen and change "Cookieless mode" into something other than "AutoDetect"...
Excuse me. Dumb error. Am going to hit myself on the head a few times for this. ;-) | Is this using an auto-generated class deriving from [`SoapHttpClientProtocol`](http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soaphttpclientprotocol.aspx)? If so, just set the [Url](http://msdn.microsoft.com/en-us/library/system.web.services.protocols.webclientprotocol.url.aspx) property when you create an instance of the class. | C# SOAP with a custom URL | [
"",
"c#",
"soap",
""
] |
I am picking up C# 4.0 and one of the things which is confusing me, is the barrier concept.
Is this not just like using the [`WaitAll`](http://msdn.microsoft.com/en-us/library/system.threading.waithandle.waitall.aspx) method of `WaitHandle`? Doesn't that wait for all threads to finish?
I learnt the barrier construct from this page: <http://www.managed-world.com/archive/2009/02/09/an-intro-to-barrier.aspx>
However, it seems just like the `WaitAll` method. What am I missing? What's the difference here?
Thanks. | It sounds like you are curious as to why a Barrier would be preferred over a WaitHandle + WaitForAll derivative? Both can achieve a similar goal if structured properly.
I'm not extremely familiar with Barrier but one advantage that jumps out at me is a resource issue. To synchronize N threads with a Barrier requires only a single Barrier instance. To synchronize N threads via a WaitHandle and WaitAll requires N handles. These resources are cheap but not free. Reducing the number of resources to synchronize a group of threads has it's advantages. | See [Barrier](http://en.wikipedia.org/wiki/Barrier_%28computer_science%29). It waits for a group of multiple threads to reach certain point, instead of one. It is often used in scientific computing and simulation to represent time "ticks."
Imagine a 1000 x 1000 x 1000 grid of cubes representing cubic mile of air. At time zero a given unit cube gets affected by its neighbors' various parameters like temp and pressure. Once everyone computes time 1, you do the same for time 2... You get a weather simulation. Similar story for nuclear simulation.
There's also a variation of barrier called [CyclicBarrier](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/CyclicBarrier.html) where it accepts threads that didn't take off from the start line and let it join back into the group after some time. It's not clear from the documentation whether C# 4's Barrier is a cyclic barrier, but there's a property called [ParticipantsRemaining](http://msdn.microsoft.com/en-us/library/system.threading.barrier.participantsremaining%28VS.100%29.aspx). | Difference between Barrier in C# 4.0 and WaitHandle in C# 3.0? | [
"",
"c#",
".net",
"multithreading",
".net-4.0",
""
] |
I want to scan a directory tree and list all files and folders inside each directory. I created a program that downloads images from a webcamera and saves them locally. This program creates a filetree based on the time the picture is downloaded. I now want to scan these folders and upload the images to a webserver but I´m not sure how I can scan the directories to find the images.
If anyone could post some sample code it would be very helpful.
**edit**: I´m running this on an embedded linux system and don´t want to use boost | See [`man ftw`](http://linux.die.net/man/3/ftw) for a simple "file tree walk". I also used [`fnmatch`](http://linux.die.net/man/3/fnmatch) in this example.
```
#include <ftw.h>
#include <fnmatch.h>
static const char *filters[] = {
"*.jpg", "*.jpeg", "*.gif", "*.png"
};
static int callback(const char *fpath, const struct stat *sb, int typeflag) {
/* if it's a file */
if (typeflag == FTW_F) {
int i;
/* for each filter, */
for (i = 0; i < sizeof(filters) / sizeof(filters[0]); i++) {
/* if the filename matches the filter, */
if (fnmatch(filters[i], fpath, FNM_CASEFOLD) == 0) {
/* do something */
printf("found image: %s\n", fpath);
break;
}
}
}
/* tell ftw to continue */
return 0;
}
int main() {
ftw(".", callback, 16);
}
```
(Not even compile-tested, but you get the idea.)
This is much simpler than dealing with `DIRENT`s and recursive traversal yourself.
---
For greater control over traversal, there's also [`fts`](http://linux.die.net/man/3/fts). In this example, dot-files (files and directories with names starting with ".") are skipped, unless explicitly passed to the program as a starting point.
```
#include <fts.h>
#include <string.h>
int main(int argc, char **argv) {
char *dot[] = {".", 0};
char **paths = argc > 1 ? argv + 1 : dot;
FTS *tree = fts_open(paths, FTS_NOCHDIR, 0);
if (!tree) {
perror("fts_open");
return 1;
}
FTSENT *node;
while ((node = fts_read(tree))) {
if (node->fts_level > 0 && node->fts_name[0] == '.')
fts_set(tree, node, FTS_SKIP);
else if (node->fts_info & FTS_F) {
printf("got file named %s at depth %d, "
"accessible via %s from the current directory "
"or via %s from the original starting directory\n",
node->fts_name, node->fts_level,
node->fts_accpath, node->fts_path);
/* if fts_open is not given FTS_NOCHDIR,
* fts may change the program's current working directory */
}
}
if (errno) {
perror("fts_read");
return 1;
}
if (fts_close(tree)) {
perror("fts_close");
return 1;
}
return 0;
}
```
Again, it's neither compile-tested nor run-tested, but I thought I'd mention it. | Boost.Filesystem allows you to do that. Check out the [docs](http://www.boost.org/doc/libs/1_39_0/libs/filesystem/doc/index.htm)!
EDIT:
If you are using Linux and you don't want to use Boost, you will have to use the Linux native C functions. [This page](http://developer.novell.com/wiki/index.php/Programming_to_the_Linux_Filesystem) shows many examples on how to do just that. | recursive folder scanning in c++ | [
"",
"c++",
"linux",
"directory",
"embedded",
""
] |
My question is really the same as this one ["Finding out what exceptions a method might throw in C#"](https://stackoverflow.com/questions/264747/finding-out-what-exceptions-a-method-might-throw-in-c). However, I would really like to know if anyone knows of a way to determine the stack of all the exceptions that may be thrown by a given method. I am hoping for a tool or utility that I can analyze code at compile time or through reflection like FxCop, StyleCop, or NCover. I do not need this information at run time I just want to make sure we are trapping exceptions and logging them correctly in out code.
We are currently trapping the exceptions that we know about and logging all the wild cards. This does work well; however, i was just hoping someone has used or knows of a tool that can discover this information. | Following up to my previous answer, I've managed to create a basic exception finder. It utilises a reflection-based `ILReader` class, available [here](http://blogs.msdn.com/haibo_luo/archive/2006/11/06/system-reflection-based-ilreader.aspx) on Haibo Luo's MSDN blog. (Just add a reference to the project.)
**Updates:**
1. Now handles local variables and the stack.
* Correctly detects exceptions returned from method calls or fields and later thrown.
* Now handles stack pushes/pops fully and appropiately.
Here is the code, in full. You simply want to use the `GetAllExceptions(MethodBase)` method either as an extension or static method.
```
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using ClrTest.Reflection;
public static class ExceptionAnalyser
{
public static ReadOnlyCollection<Type> GetAllExceptions(this MethodBase method)
{
var exceptionTypes = new HashSet<Type>();
var visitedMethods = new HashSet<MethodBase>();
var localVars = new Type[ushort.MaxValue];
var stack = new Stack<Type>();
GetAllExceptions(method, exceptionTypes, visitedMethods, localVars, stack, 0);
return exceptionTypes.ToList().AsReadOnly();
}
public static void GetAllExceptions(MethodBase method, HashSet<Type> exceptionTypes,
HashSet<MethodBase> visitedMethods, Type[] localVars, Stack<Type> stack, int depth)
{
var ilReader = new ILReader(method);
var allInstructions = ilReader.ToArray();
ILInstruction instruction;
for (int i = 0; i < allInstructions.Length; i++)
{
instruction = allInstructions[i];
if (instruction is InlineMethodInstruction)
{
var methodInstruction = (InlineMethodInstruction)instruction;
if (!visitedMethods.Contains(methodInstruction.Method))
{
visitedMethods.Add(methodInstruction.Method);
GetAllExceptions(methodInstruction.Method, exceptionTypes, visitedMethods,
localVars, stack, depth + 1);
}
var curMethod = methodInstruction.Method;
if (curMethod is ConstructorInfo)
stack.Push(((ConstructorInfo)curMethod).DeclaringType);
else if (method is MethodInfo)
stack.Push(((MethodInfo)curMethod).ReturnParameter.ParameterType);
}
else if (instruction is InlineFieldInstruction)
{
var fieldInstruction = (InlineFieldInstruction)instruction;
stack.Push(fieldInstruction.Field.FieldType);
}
else if (instruction is ShortInlineBrTargetInstruction)
{
}
else if (instruction is InlineBrTargetInstruction)
{
}
else
{
switch (instruction.OpCode.Value)
{
// ld*
case 0x06:
stack.Push(localVars[0]);
break;
case 0x07:
stack.Push(localVars[1]);
break;
case 0x08:
stack.Push(localVars[2]);
break;
case 0x09:
stack.Push(localVars[3]);
break;
case 0x11:
{
var index = (ushort)allInstructions[i + 1].OpCode.Value;
stack.Push(localVars[index]);
break;
}
// st*
case 0x0A:
localVars[0] = stack.Pop();
break;
case 0x0B:
localVars[1] = stack.Pop();
break;
case 0x0C:
localVars[2] = stack.Pop();
break;
case 0x0D:
localVars[3] = stack.Pop();
break;
case 0x13:
{
var index = (ushort)allInstructions[i + 1].OpCode.Value;
localVars[index] = stack.Pop();
break;
}
// throw
case 0x7A:
if (stack.Peek() == null)
break;
if (!typeof(Exception).IsAssignableFrom(stack.Peek()))
{
//var ops = allInstructions.Select(f => f.OpCode).ToArray();
//break;
}
exceptionTypes.Add(stack.Pop());
break;
default:
switch (instruction.OpCode.StackBehaviourPop)
{
case StackBehaviour.Pop0:
break;
case StackBehaviour.Pop1:
case StackBehaviour.Popi:
case StackBehaviour.Popref:
case StackBehaviour.Varpop:
stack.Pop();
break;
case StackBehaviour.Pop1_pop1:
case StackBehaviour.Popi_pop1:
case StackBehaviour.Popi_popi:
case StackBehaviour.Popi_popi8:
case StackBehaviour.Popi_popr4:
case StackBehaviour.Popi_popr8:
case StackBehaviour.Popref_pop1:
case StackBehaviour.Popref_popi:
stack.Pop();
stack.Pop();
break;
case StackBehaviour.Popref_popi_pop1:
case StackBehaviour.Popref_popi_popi:
case StackBehaviour.Popref_popi_popi8:
case StackBehaviour.Popref_popi_popr4:
case StackBehaviour.Popref_popi_popr8:
case StackBehaviour.Popref_popi_popref:
stack.Pop();
stack.Pop();
stack.Pop();
break;
}
switch (instruction.OpCode.StackBehaviourPush)
{
case StackBehaviour.Push0:
break;
case StackBehaviour.Push1:
case StackBehaviour.Pushi:
case StackBehaviour.Pushi8:
case StackBehaviour.Pushr4:
case StackBehaviour.Pushr8:
case StackBehaviour.Pushref:
case StackBehaviour.Varpush:
stack.Push(null);
break;
case StackBehaviour.Push1_push1:
stack.Push(null);
stack.Push(null);
break;
}
break;
}
}
}
}
}
```
To summarise, this algorithm recursively enumerates (depth-first) any methods called within the specified one, by reading the CIL instructions (as well as keeping track of methods already visited). It maintains a single list of collections that can be thrown using a [`HashSet<T>`](http://msdn.microsoft.com/en-us/library/bb359438.aspx) object, which is returned at the end. It additionally maintains an array of local variables and a stack, in order to keep track of exceptions that aren't thrown immediately after they are created.
Of course, this code isn't infallible in it's current state. There are a few improvements that I need to make for it to be robust, namely:
1. ~~Detect exceptions that aren't thrown directly using an exception constructor. (i.e. The exception is retrieved from a local variable or a method call.)~~
2. ~~Support exceptions popped off the stack then later pushed back on.~~
3. Add flow-control detection. Try-catch blocks that handle any thrown exception should remove the appropiate exception from the list, unless a `rethrow` instruction is detected.
Apart from that, I believe the code is *reasonably* complete. It may take a bit more investigation before I figure out exactly how to do the flow-control detection (though I believe I can see how it operates at the IL-level now).
These functions could probably be turned into an entire library if one was to create a full-featured "exception analyser", but hopefully this will at least provide a sound starting point for such a tool, if not already good enough in its current state.
Anyway, hope that helps! | This should not be extremely hard. You can get list of exceptions created by a method like this:
```
IEnumerable<TypeReference> GetCreatedExceptions(MethodDefinition method)
{
return method.GetInstructions()
.Where(i => i.OpCode == OpCodes.Newobj)
.Select(i => ((MemberReference) i.Operand).DeclaringType)
.Where(tr => tr.Name.EndsWith("Exception"))
.Distinct();
}
```
Snippets use Lokad.Quality.dll from the Open Source [Lokad Shared Libraries](http://abdullin.com/shared-libraries/) (which uses Mono.Cecil to do the heavy-lifting around code reflection). I actually [put this code into one of the test cases in trunk](http://code.google.com/p/lokad-shared-libraries/source/detail?r=61).
Say, we have a class like this:
```
class ExceptionClass
{
public void Run()
{
InnerCall();
throw new NotSupportedException();
}
void InnerCall()
{
throw new NotImplementedException();
}
}
```
then in order to get all exceptions from just the Run method:
```
var codebase = new Codebase("Lokad.Quality.Test.dll");
var type = codebase.Find<ExceptionClass>();
var method = type.GetMethods().First(md => md.Name == "Run");
var exceptions = GetCreatedExceptions(method)
.ToArray();
Assert.AreEqual(1, exceptions.Length);
Assert.AreEqual("NotSupportedException", exceptions[0].Name);
```
Now all that remains is to walk down the method call stack down to a certain depth. You can get a list of methods referenced by a method like this:
```
var references = method.GetReferencedMethods();
```
Now before being able to call *GetCreatedExceptions* upon any method down the stack we just need to actually look up into the codebase and resolve all MethodReference instances to MethodDefinition instances actually containing the byte code (with some caching to avoid scanning existing branches). That's the most time-consuming part of the code (since Codebase object does not implement any method lookups on top of Cecil), but that should be doable. | How can I determine which exceptions can be thrown by a given method? | [
"",
"c#",
"exception",
"error-handling",
""
] |
I have a table that represents Tab-structure.
Some cells are set to display: none; and only the active tab is displayed.
I want to set the max-height to all of them.
To do it, I go through the array of tabs and do the following
```
// get the max-tab-height
for (var i = 0; i < TabPageList.length; i++)
{
// get max height
if (TabPageList[i].offsetHeight>MaxTabHeight)
MaxTabHeight = TabPageList[i].offsetHeight;
}
```
The problem with this approach is that offsetHeight is working only for the active tab that is displayed.
So, what's the Height of the ones that are not shown, when they will be shown? | As the others have said you may get the height by setting the visibility to hidden (which makes the object keep its dimensions while hidden):
```
visibility:hidden;
```
with the additional trick of setting its position to absolute to avoid it taking space on the page (you may do this just for the time needed to get at the height, restoring its position attribute afterward).
A second approach may be to keep the tab visible but move it off the page by setting its absolute position to some sufficiently large coordinates. | Because the inactive tabs are set to `display:none`, the offsetHeight is not useful. Try running your MaxTabHeight routine at the same time that you activate the tab, after it is made visible. I'm assuming that's inside the tab's click event. | Height of invisible objects, when they become visible, in javascript | [
"",
"javascript",
"dhtml",
""
] |
We have a table which is of the form:
```
ID,Value1,Value2,Value3
1,2,3,4
```
We need to transform this into.
```
ID,Name,Value
1,'Value1',2
1,'Value2',3
1,'Value3',4
```
Is there a clever way of doing this in one SELECT statement (i.e without UNIONs)? The column names Value1,Value2 and Value3 are fixed and constant.
The database is oracle 9i. | This works on Oracle 10g:
```
select id, 'Value' || n as name,
case n when 1 then value1 when 2 then value2 when 3 then value3 end as value
from (select rownum n
from (select 1 from dual connect by level <= 3)) ofs, t
```
I think Oracle 9i had recursive queries? Anyway, I'm pretty sure it has CASE support, so even if it doesn't have recursive queries, you can just do "(select 1 from dual union all select 2 from dual union all select 3 from dual) ofs" instead. Abusing recursive queries is a bit more general- for Oracle. (Using unions to generate rows is portable to other DBs, though) | Give a `union` a shot.
```
select ID, 'Value1' as Name, Value1 as Value from table_name union all
select ID, 'Value2', Value2 as Value from table_name union all
select ID, 'Value3', Value3 as Value from table_name
order by ID, Name
```
using `union all` means that the server won't perform a `distinct` (which is implicit in `union` operations). It shouldn't make any difference with the data (since your ID's should HOPEFULLY be different), but it might speed it up a bit. | Single SQL SELECT Returning multiple rows from one table row | [
"",
"sql",
"oracle",
"select",
"plsql",
"oracle9i",
""
] |
A python program needs to draw histograms. It's ok to use 3rd party library (free). What is the best way to do that? | You can use [matplotlib](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.hist). | [Gnuplot.py](http://gnuplot-py.sourceforge.net/) lets you use [Gnuplot](http://www.gnuplot.info/) from python. | Any graphics library for unix that can draw histograms? | [
"",
"python",
"unix",
"graphics",
""
] |
Or more specific to what I need:
If I call a function from within another function, is it going to pull the variable from within the calling function, or from the level above? Ex:
```
myVar=0;
function runMe(){
myVar = 10;
callMe();
}
function callMe(){
addMe = myVar+10;
}
```
What does myVar end up being if callMe() is called through runMe()? | Jeff is right. Note that this is not actually a good test of static scoping (which JS does have). A better one would be:
```
myVar=0;
function runMe(){
var myVar = 10;
callMe();
}
function callMe(){
addMe = myVar+10;
}
runMe();
alert(addMe);
alert(myVar);
```
In a statically scoped language (like JS), that alerts 10, and 0. The var myVar (local variable) in runMe shadows the global myVar in that function. However, it has no effect in callMe, so callMe uses the global myVar which is still at 0.
In a dynamically scoped language (*unlike* JS), callMe would inherit scope from runMe, so addMe would become 20. Note that myVar would still be 0 at the alert, because the alert does not inherit scope from either function. | if your next line is **callMe();**, then addMe will be 10, and myVar will be 0.
if your next line is **runMe();**, then addMe will be 20, and myVar will be 10.
Forgive me for asking - what does this have to do with static/dynamic binding? Isn't myVar simply a global variable, and won't the procedural code (unwrap everything onto the call stack) determine the values? | Are variables statically or dynamically "scoped" in javascript? | [
"",
"javascript",
"scoping",
""
] |
I need to create one of these as the interface requires it. Can someone please let me know how to create one, as there doesn't seem to be a constructor defined? | When you imported the WSDL, you should have an `ObjectFactory` class which should have bunch of methods for creating various input parameters.
```
ObjectFactory factory = new ObjectFactory();
JAXBElement<String> createMessageDescription = factory.createMessageDescription("description");
message.setDescription(createMessageDescription);
``` | ```
ObjectFactory fact = new ObjectFactory();
JAXBElement<String> str = fact.createCompositeTypeStringValue("vik");
comp.setStringValue(str);
CompositeType retcomp = service.getDataUsingDataContract(comp);
System.out.println(retcomp.getStringValue().getValue());
``` | How do I instantiate a JAXBElement<String> object? | [
"",
"java",
"jaxb",
""
] |
```
List list = new ArrayList();
String[] test = {"ram", "mohan", "anil", "mukesh", "mittal"};
for(int i =0; i < test.length; i++)
{
A a = new A();
a.setName(test[i]);
list.add(a);
}
```
How JVM handles creation of object a in each loop? How "list" differntiate between different instance? Is it good practice to create object on each iteration. If no, what is the best solution for adding object into a list. | In your example a new object is created on each iteration of the loop. The list is able to differentiate between them because it does not care that you call them all "a" in your code, it keeps track of them by the reference that gets reassigned each time you call
```
a = new A();
```
Each time that line of code is called, a new object is created on the heap and it's address in memory is assigned to the reference a. It's that reference that the list keeps a record of, not the variable name.
This is a perfectly fine and normal way to populate a list (aside from the syntax errors that others have mentioned, which I'm assuming you can fix when you try to compile your code). | List holds a reference to each instance of a that gets created. It's fine to create each object inside the loop (I'm assuming you mean as opposed to declaring the 'a' variable outside the loop and then re-assigning it each iteration). | how jvm handles creating object inside a loop | [
"",
"java",
"performance",
"jvm",
""
] |
I would like to know whats faster. Help me out.
I have a variable declared in a Method like so:
```
public static Regex FindNumber()
{ return new Regex(@"\d+", RegexOptions.IgnoreCase | RegexOptions.Compiled); }
```
As you can see it returns a Regular Expression.
I also have another Method that looks like so:
```
private static string TestOne(string RawData)
{
Regex rgxFindNumber = FindNumber();
Regex rgxFindDays = FindDays();
for (int i = 0; i < mc.Count; i++)
{
int days = Convert.ToInt32(rgxFindNumber.Match(rgxFindDays.Match(mc[i].Value).Value).Value);
}
return RawData;
}
```
Now is the TestOne Method going to be faster or is TestTwo?
```
private static string TestTwo(string RawData)
{
for (int i = 0; i < mc.Count; i++)
{
int days = Convert.ToInt32(FindNumber().Match( FindDays().Match(mc[i].Value).Value).Value);
}
return RawData;
}
```
Now im curious because TestOne Can get called a aweful lot in my code so I would like to know what would be better to implement.
Thanks guys.
\*\*Edit:\*\*The code I am using has an extremely large class. Its a text parser for a text based strategy game. I am trying to refactor it a bit and thats what I am wondering here. If I do create a private variable for the Regex, wouldn't it be run every time the class is accessed? Thats my question to you. | `TestOne` will be faster than `TestTwo`, because you're not creating a new regular expression for every loop iteration.
This has two benefits:
* The time used to parse and construct the objects for the regex is only done once, instead of `mc.Count` times
* Less pressure on garbage collection since fewer objects are constructed.
However, I would go one step further. If you're always going to return that same regular expression, and you're concerned about speed, I would cache that regex object in a static field.
For instance, you might consider this:
```
private static Regex _FindNumber;
public static Regex FindNumber()
{
if (_FindNumber == null)
_FindNumber = new Regex(@"\d+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
return _FindNumber;
}
```
This would create just one object, total, and keep it around.
However, and here's my real answer.
To actually know which one is going to be the fastest, you're going to have to measure your code, optionally with my variant thrown in for good measure, and then decide. Never decide on optimizations without hard data, you might end up spending time rewriting code, which can introduce new bugs, which will need fixing, which you will spend more time on, only to eek out another 1% of performance.
The big optimizations are done algorithmically, like changing the type of sorting algorithm, and then only afterwards, if necessary, you move on to local optimizations like loop tuning.
Having said that, I would at least avoid constructing the object in the loop, that's just common sense. | I believe `TestOne` will be faster because in `TestTwo` you are creating a new `Regex` object every time you loop. If `FindDays` is implemented the same as `FindNumber` it will be even worse as you'll be creating two objects. | Difference between a Local Variable and a Variable Called from a Method? C# | [
"",
"c#",
"oop",
"testing",
"methods",
""
] |
I'm building a web application in which I need to scan the user-uploaded files for viruses.
Does anyone with experience in building something like this can provide information on how to get this up and running? I'm guessing antivirus software packages have APIs to access their functionality programatically, but it seems it's not easy to get a hand on the details.
FYI, the application is written in C#. | I would probably just make a system call to run an independent process to do the scan. There are a number of command-line AV engines out there from various vendors. | **Important note before use:**
Be aware of TOS agreement. You give them full access to everything: "When you upload or otherwise submit content, you give VirusTotal (and those we work with) a worldwide, royalty free, irrevocable and transferable licence to use, edit, host, store, reproduce, modify, create derivative works, communicate, publish, publicly perform, publicly display and distribute such content."
Instead of using a local Antivirus program (and thus binding your program to that particular Antivirus product and requesting your customers to install that Antivirus product) you could use the services of [VirusTotal.com](https://www.virustotal.com)
This site provides a free service in which your file is given as input to numerous antivirus products and you receive back a detailed report with the evidences resulting from the scanning process. In this way your solution is no more binded to a particular Antivirus product (albeit you are binded to Internet availability)
The site provides also an Application Programming Interface that allows a programmatically approach to its scanning engine.
[Here a VirusTotal.NET a library for this API](https://github.com/Genbox/VirusTotal.NET)
[Here the comprensive documentation about their API](https://www.virustotal.com/it/documentation/)
[Here the documentation with examples in Python of their interface](https://www.virustotal.com/en/documentation/public-api/)
And because no answer is complete without code, this is taken directly from the sample client shipped with the VirusTotal.NET library
```
static void Main(string[] args)
{
VirusTotal virusTotal = new VirusTotal(ConfigurationManager.AppSettings["ApiKey"]);
//Use HTTPS instead of HTTP
virusTotal.UseTLS = true;
//Create the EICAR test virus. See http://www.eicar.org/86-0-Intended-use.html
FileInfo fileInfo = new FileInfo("EICAR.txt");
File.WriteAllText(fileInfo.FullName, @"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*");
//Check if the file has been scanned before.
FileReport fileReport = virusTotal.GetFileReport(fileInfo);
bool hasFileBeenScannedBefore = fileReport.ResponseCode == ReportResponseCode.Present;
Console.WriteLine("File has been scanned before: " + (hasFileBeenScannedBefore ? "Yes" : "No"));
//If the file has been scanned before, the results are embedded inside the report.
if (hasFileBeenScannedBefore)
{
PrintScan(fileReport);
}
else
{
ScanResult fileResult = virusTotal.ScanFile(fileInfo);
PrintScan(fileResult);
}
... continue with testing a web site ....
```
}
**DISCLAIMER**
I am in no way involved with them. I am writing this answer just because it seems to be a good update for these 4 years old answers. | .NET virus scanning API | [
"",
"c#",
".net",
"api",
"antivirus",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.