Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
Is there a way to tell the debugger to stop just before returning, on whichever statement exits from the method, be it return, exception, or fall out the bottom? I am inspired by the fact that the Java editor shows me all the places that my method *can* exit - it highlights them when you click on the return type of the method declaration, (Mark Occurrences enabled).
[eclipse 3.4]
|
Put a breakpoint on the line of the method signature. That is where you write
```
public void myMethod() {
```
Then right-click on the breakpoint and select "Breakpoint Properties". At the bottom of the pop-up there are two checkboxes: "Method Entry", "Method Exit". Check the latter.
|
You can set a method breakpoint.
Double click in the margin next to the method declaration. A breakpoint with an arrow decoration appears. Right-clicking to examine the properties, you can set "Suspend on:" for "Method Entry" and/or "Method Exit".
You can read more about them in the [Eclipse Cookbook](http://books.google.com/books?id=U4UuyIU6bZAC&pg=PA132&lpg=PA132&dq=%22method+breakpoint%22+%22eclipse%22&source=web&ots=eOj8Od5DLx&sig=g-cThDlC2pZ9Alvk5RD8fZ3-0TU&hl=en).
|
eclipse beakpoint: stop before leaving a Java method
|
[
"",
"java",
"eclipse",
"debugging",
"breakpoints",
"eclipse-3.4",
""
] |
I just found myself creating a class called "InstructionBuilderFactoryMapFactory". That's 4 "pattern suffixes" on one class. It immediately reminded me of this:
<http://www.jroller.com/landers/entry/the_design_pattern_facade_pattern>
Is this a design smell? Should I impose a limit on this number?
I know some programmers have similar rules for other things (e.g. no more than N levels of pointer indirection in C.)
All the classes seem necessary to me. I have a (fixed) map from strings to factories - something I do all the time. The list is getting long and I want to move it out of the constructor of the class that uses the builders (that are created by the factories that are obtained from the map...) And as usual I'm avoiding Singletons.
|
I see it as a design smell - it will make me think if all those levels of abstraction are pulling enough weight.
I can't see why you wanted to name a class 'InstructionBuilderFactoryMapFactory'? Are there other kinds of factories - something that doesn't create an InstructionBuilderFactoryMap? Or are there any other kinds of InstructionBuildersFactories that it needs to be mapped?
These are the questions that you should be thinking about when you start creating classes like these. It is possible to just aggregate all those different factory factories to just a single one and then provide separate methods for creating factories. It is also possible to just put those factory-factory in a different package and give them a more succinct name. Think of alternative ways of doing this.
|
A good tip is: Your class public API (and that includes it's name) should reveal intention, not implementation. I (as a client) don't care whether you implemented the builder pattern or the factory pattern.
Not only the class name looks bad, it also tells nothing about what it does. It's name is based on its implementation and internal structure.
I rarely use a pattern name in a class, with the exception of (sometimes) Factories.
Edit:
Found an interesting [article](http://www.codinghorror.com/blog/archives/000553.html) about naming on Coding Horror, please check it out!
|
Too many "pattern suffixes" - design smell?
|
[
"",
"java",
"design-patterns",
"naming-conventions",
""
] |
Are there any **professional** Combobox controls (dropdown list with autosuggestion) based on the jQuery library?
It should be able to handle **large datasets** and have some **skinning** options. A **multi-column result list** would be great too. I'm working with ASP.NET, but it's a not a problem if I had to write a wrapper for it.

*I'm already using a third-party control, but I ran into some compatibilty issues between two vendor's controls. Well, I want to get rid of this kind of dependencies.*
|
Unfortunately, the best thing I have seen is the [jquery.combobox](http://web.archive.org/web/20130430100104/http://jquery.sanchezsalvador.com/page/jquerycombobox.aspx), but it doesn't really look like something I'd really want to use in my web applications. I think there are some usability issues with this control, but as a user I don't think I'd know to start typing for the dropdownlist to turn into a textbox.
I much prefer the [Combo Dropdown Box](http://simpletutorials.com/?path=tutorials/javascript/jquery/ddcombobox), but it still has some features that I'd want and it's still in alpha. The only think I don't like about this other than its being alpha... is that once I type in the combobox, the original dropdownlist items disappear. However, maybe there is a setting for this... or maybe it could be added fairly easily.
Those are the only two options that I know of. Good luck in your search. I'd love to hear if you find one or if the second option works out for you.
|
Here's one that looks very promising. It's a true combo - you see what you type. Has a cool feature I haven't seen elsewhere: paging results.
[FlexBox](http://www.codeplex.com/flexbox)
|
Professional jQuery based Combobox control?
|
[
"",
"javascript",
"jquery",
"combobox",
"controls",
""
] |
What is the best way to determine whether there is an available Internet connection for a WinForms app. (Programatically of course) I want to disable/hide certain functions if the user is not connected to the Internet.
|
The following will determine if you are connected to a network, however, that doesn't necessarily mean that you are connected to the Internet:
```
NetworkInterface.GetIsNetworkAvailable()
```
Here is a C# translation of Steve's code that seems to be pretty good:
```
private static int ERROR_SUCCESS = 0;
public static bool IsInternetConnected() {
long dwConnectionFlags = 0;
if (!InternetGetConnectedState(dwConnectionFlags, 0))
return false;
if(InternetAttemptConnect(0) != ERROR_SUCCESS)
return false;
return true;
}
[DllImport("wininet.dll", SetLastError=true)]
public static extern int InternetAttemptConnect(uint res);
[DllImport("wininet.dll", SetLastError=true)]
public static extern bool InternetGetConnectedState(out int flags,int reserved);
```
|
sbeskur's response has a bug in the translation of InternetGetConnectedState. The parameters are both DWORD's (first one is an LPDWORD). Both of these translate to int's in C# (technically, uint but int will work for most scenarios).
Correct translation below.
```
[DllImport("wininet.dll", SetLastError=true)]
public static extern bool InternetGetConnectedState(out int flags,int reserved);
```
|
How do you determine if an Internet connection is available for your WinForms App?
|
[
"",
"c#",
".net",
"winforms",
""
] |
So I made some timers for a quiz. The thing is, I just realized when I put
```
javascript: alert("blah");
```
in the address, the popup alert box **pauses** my timer. Which is very unwanted in a quiz.
I don't think there is any way to stop this behaviour... but I'll ask anyway.
If there is not, mind suggesting what should I do?
|
Apparently the preview rendering differs from the posted rendering. This paragraph is here to make sure the next two lines show up as code.
```
// Preserve native alert() if you need it for something special
window.nativeAlert = window.alert;
window.alert = function(msg) {
// Do something with msg here. I always write mine to console.log,
// but then I have rarely found a use for a real modal dialog,
// and most can be handled by the browser (like window.onbeforeunload).
};
```
|
Never, ever rely on javascript (or any other client-side time) to calculate elapsed times for operations done between postbacks, or different pages.
If you always compare server dates, it will be hard for people to cheat:
1. first page request, store the server time
2. ping with javascript calls each N seconds, compare the 2 server times, and return the elapsed (just for show)
3. when the user submits the form, compare the 2 server times, calculate the elapsed time, and discard the ones which took too long (ie: possible cheaters)
|
Prevent js alert() from pausing timers
|
[
"",
"javascript",
"timer",
""
] |
I was always wondering if there is operator for deleting multi dimensional arrays in the standard C++ language.
If we have created a pointer to a single dimensional array
```
int *array = new int[size];
```
the delete looks like:
```
delete [] array;
```
That's great. But if we have two dimension array, we can not do
```
delete [][] twoDimenstionalArray;
```
Instead, we should loop and delete the items, like in [this](http://eli.thegreenplace.net/2003/07/23/allocating-multi-dimensional-arrays-in-c/) example.
Can anybody explain why?
|
Technically, there aren't two dimensional arrays in C++. What you're using as a two dimensional array is a one dimensional array with each element being a one dimensional array. Since it doesn't technically exist, C++ can't delete it.
|
Because there is no way to call
```
int **array = new int[dim1][dim2];
```
All news/deletes must be balanced, so there's no point to a `delete [][]` operator.
`new int[dim1][dim2]` returns a pointer to an array of size `dim1` of type `int[dim2]`. So `dim2` must be a compile time constant. This is similar to allocating multi-dimensional arrays on the stack.
|
Why "delete [][]... multiDimensionalArray;" operator in C++ does not exist
|
[
"",
"c++",
"arrays",
""
] |
I am using trigger\_error to "throw" errors in a custom class. My problem is that trigger\_error prints out the line number where trigger\_error was called. For example, given the following code:
```
01 <?php
02 class Test {
03 function doAction() {
04 $this->doSubAction();
05 }
06
07 function doSubAction() {
08 if(true)
09 trigger_error('Custom error', E_USER_WARNING);
10 }
11 }
12
13 $var = new Test();
14 $var->doAction();
15 ?>
```
PHP will print out the following:
> **Warning:** Custom error in **test.php** on line **9**
How would you make PHP return the line where the doAction() function was called (the method called outside the class, ignoring all calls made internally) as follows?
> **Warning:** Custom error in **test.php** on line **14**
**Edit:** Modified my example to be something a bit closer to what I'm trying to achieve.
|
Alright, for those of you who are interested in my final solution, I integrated the following piece of code in our framework which returns the correct line number in all the cases that we could of tested. We are using it in production.
[`ErrorHandler` class](http://pastebin.com/f12a290d1)
It catches uncaught PHP exceptions, PHP errors and `PEAR::Error` s. You will need to modify it a bit has the code has some framework specific functions, but they shouldn't be to hard to track down. Enjoy!
|
The best thing to do is set up an error handler that shows a full stack trace.
Set up a custom error handler, and call debug\_print\_backtrace() in it. You will find this useful in general, as well in this specific circumstance.
|
How to get proper line number when using trigger_error in PHP?
|
[
"",
"php",
"error-handling",
""
] |
I have a ArrayList made up of different elements imported from a db, made up of strings, numbers, doubles and ints. Is there a way to use a reflection type technique to find out what each type of data each element holds?
FYI: The reason that there is so many types of data is that this is a piece of java code being written to be implemented with different DB's.
|
In C#:
Fixed with recommendation from [Mike](https://stackoverflow.com/users/14359/mike-brown)
```
ArrayList list = ...;
// List<object> list = ...;
foreach (object o in list) {
if (o is int) {
HandleInt((int)o);
}
else if (o is string) {
HandleString((string)o);
}
...
}
```
In Java:
```
ArrayList<Object> list = ...;
for (Object o : list) {
if (o instanceof Integer)) {
handleInt((Integer o).intValue());
}
else if (o instanceof String)) {
handleString((String)o);
}
...
}
```
|
You can use the `getClass()` method, or you can use instanceof. For example
```
for (Object obj : list) {
if (obj instanceof String) {
...
}
}
```
or
```
for (Object obj : list) {
if (obj.getClass().equals(String.class)) {
...
}
}
```
Note that instanceof will match subclasses. For instance, of `C` is a subclass of `A`, then the following will be true:
```
C c = new C();
assert c instanceof A;
```
However, the following will be false:
```
C c = new C();
assert !c.getClass().equals(A.class)
```
|
How do I find out what type each object is in a ArrayList<Object>?
|
[
"",
"java",
"generics",
"reflection",
"arraylist",
""
] |
What is the best way to secure the use/loading of a DLL with a license file?
|
A couple of things you might want to consider:
Check sum the DLL. Using a [cryptographic hash function](http://en.wikipedia.org/wiki/Cryptographic_hash_function), you can store this inside the license file or inside the DLL. This provides a verification method to determined if my original DLL file is unhacked, or if it is the license file for this DLL. A few simple byte swapping techniques can quickly take your hash function off the beaten track (and thus not easy to reproduce).
Don't store you hash as a string, split it into unsigned shorts in different places.
As Larry said, a MAC address is fairly common. There are lots of examples of how to get that on [The Code Project](http://en.wikipedia.org/wiki/The_Code_Project), but be aware it's easy to fake these days.
My suggestion, should be use [private/public](http://en.wikipedia.org/wiki/Public-key_cryptography) keys for license generation.
In short, modes of attack will be binary (modify the instructions of your DLL file) so protect against this, or key generation so make each license user, machine, and even the install specific.
|
You can check for a license inside of DllMain() and die if it's not found.
|
Secure a DLL file with a license file
|
[
"",
"c++",
"dll",
"licensing",
""
] |
I've got a client that, during testing, is giving me conflicting information. I don't think they are lying but more confused. So, I would like to setup some simple auditing in my ASP.Net application. Specifically, right when any page is called, I want to immediately insert the Querystring and/or form POST data into a log table. Just the raw values.
Querystring is easy. But there doesn't seem to be a way to get the raw form POST'ed data without using BinaryRead, and if I do that, then I screw myself out of using the Request.Form collection later on.
Does anyone know a way around this?
EDIT: tvanfosson suggested Request.Params. I was looking for something that was easier to use (like Request.Querystring, only for POST), but I guess I could just as easily loop through all params and build a string of name=value&, etc).
|
All of the form data should be in [Request.Params](http://msdn.microsoft.com/en-us/library/system.web.httprequest.params.aspx). You'd need to do this on every page, though or maybe use an HttpModule.
[EDIT] If you want to get the form parameters separately use [Request.Form](http://msdn.microsoft.com/en-us/library/system.web.httprequest.form.aspx), along with Request.QueryString
|
You can create a custom HttpModule to capture all request made to your application so you don't need to touch every page and you can use it only during testing just not to slow down performance in production.
A sample implementation would be:
```
public class CustomModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.EndRequest += new EventHandler(context_BeginRequest);
}
private void context_BeginRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
// you can use the context.Request here to send it to the database or a log file
}
}
```
You need to add the module to your web.config
```
<httpModules>
<add name="CustomModule" type="CustomModule"/>
</httpModules>
```
|
.Net Form POST
|
[
"",
"c#",
"asp.net",
"form-post",
""
] |
Has anyone got to some good code to zoom into an image using javascript?
I know I could just resize it etc but was being lazy and looking for something clever to zoom to different levels, move around when zoomed etc
|
This really depends on what quality you are after. If you need a hires hiquality image with detailed zoom levels and proper interpolation you will need to write a backend service to serve up zoomed portions of your images. If you have no care for quality or speed, you could download the entire image and fit it to display inside a div absolutely positioned, offset for the area you want to view and sized as determined by your zoom level.
I would say you are probably after the first option. There are some tools already made [for this](http://blogs.zdnet.com/microsoft/?p=1252), I persoanlly havnt used any of the tools; I am sure othes will post links to others you can try; I have written my own service and client. I cant go into the exact details as its proprietary, but I can give you an overview of what I do.
I have an asp.net generic handler that takes a query string denoting which image (by an id) and the coordinates to zoom on and the target image size. I have the service load the image and crop and resize it (its more complicated than that as I have many optimizations and preparsing when the file is originally uploaded, such as multiple cross sections of the file for faster serving when zooming, but what I describing here is the basics).
That service simply returns type image/jpeg and sends the image.
On the client side I have written a marquee box control that allows the user to marquee an area on the image they want to zoom in on. they marquee the area and click zoom. This then calculates the offsets into the image of the selected coordinates based on the original image size and the viewable image size. I send hese coords to the handler previously mentioned.I load the the url with query string of the srvice into an Image object, and handle onload. If all went well i then swap that to the viewed image and updates all my client side variables for determining where on the image I am zoomed into and then it can be zoomed again or zoomed out or panned further from there.
Now i understand your lazy requirement, but i need to say that writing this is actually quite easy to do to get the basics going. the hardest part you will find is doing a select box. But then even that can be as simple as tracking two click. Top left of the zoom select marque and bottom right. Or not having a select box at all and have a zoom in and out only at predetermined intervals. I on my projects required a zoom box as its a fairly complex image analysis solution.
I hope this at least helpful and leads you to something useful.
|
Check this:
* [jQZoom](http://www.mind-projects.it/blog/jqzoom_v10)
* [Zoomimage - jQuery plugin](http://www.eyecon.ro/zoomimage/)
* [jQuery ImgZoom](http://plugins.jquery.com/project/imgzoom)
* [FancyBox](http://fancy.klade.lv/)
|
Image Zoom using javascript?
|
[
"",
"javascript",
"imaging",
""
] |
I recall reading somewhere that using references to smart pointers can cause memory corruption. Is this simply because of using the reference of the smart pointer after its been destroyed? Or does the reference counting get messed up?
Thanks for clarifying
|
Assuming you are talking about shared\_ptr here...
> Is this simply because of using the
> reference of the smart pointer after
> its been destroyed?
This is a good answer. You may not know absolutely the lifetime of the pointer your reference refers too.
To get around this, you'd want to look into boost::weak\_ptr. It doesn't participate in reference counting. When you need to use it, it gives you a shared\_ptr which goes away once your done with it. It will also let you know when the refered to pointer has been collected.
From the [weak\_ptr](http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/weak_ptr.htm#expired) documentation
> The weak\_ptr class template stores a
> "weak reference" to an object that's
> already managed by a shared\_ptr. To
> access the object, a weak\_ptr can be
> converted to a shared\_ptr using the
> shared\_ptr constructor or the member
> function lock. When the last
> shared\_ptr to the object goes away and
> the object is deleted, the attempt to
> obtain a shared\_ptr from the weak\_ptr
> instances that refer to the deleted
> object will fail: the constructor will
> throw an exception of type
> boost::bad\_weak\_ptr, and
> weak\_ptr::lock will return an empty
> shared\_ptr.
Note the method expired() will also tell you if your ptr is still around.
|
When using smart pointers (or any allocation management object) you are counting on the behaviors defined in the constructor/destructor to manage refs/derefs/locks/unlocks. As a result, those types of objects must be true objects to perform properly. when using references to such objects (or pointers) you are bypassing the mechanism (and asking for a wedgie).
|
Why shouldn't you use references to smart pointers?
|
[
"",
"c++",
"smart-pointers",
""
] |
I have a some JPA entities that inherit from one another and uses discriminator to determine what class to be created (untested as of yet).
```
@Entity(name="switches")
@DiscriminatorColumn(name="type")
@DiscriminatorValue(value="500")
public class DmsSwitch extends Switch implements Serializable {}
@MappedSuperclass
public abstract class Switch implements ISwitch {}
@Entity(name="switch_accounts")
public class SwitchAccounts implements Serializable {
@ManyToOne()
@JoinColumn(name="switch_id")
DmsSwitch _switch;
}
```
So in the SwitchAccounts class I would like to use the base class Switch because I don't know which object will be created until runtime. How can I achieve this?
|
As your switch class is not an entity, it cannot be used in an entity relationship... Unfortunately, you'll have to transform your mappedsuperclass as an entity to involve it in a relationship.
|
As the previous commentors I agree that the class model should be different. I think something like the following would suffice:
```
@Entity(name="switches")
@DiscriminatorColumn(name="type")
@DiscriminatorValue(value="400")
public class Switch implements ISwitch {
// Implementation details
}
@Entity(name="switches")
@DiscriminatorValue(value="500")
public class DmsSwitch extends Switch implements Serializable {
// implementation
}
@Entity(name="switches")
@DiscriminatorValue(value="600")
public class SomeOtherSwitch extends Switch implements Serializable {
// implementation
}
```
You could possibly prevent instantiation of a Switch directly by making the constructor protected. I believe Hibernate accepts that.
|
JPA and inheritance
|
[
"",
"java",
"jpa",
""
] |
I want to write a query like this:
```
SELECT o.OrderId, MAX(o.NegotiatedPrice, o.SuggestedPrice)
FROM Order o
```
But this isn't how the `MAX` function works, right? It is an aggregate function so it expects a single parameter and then returns the MAX of all rows.
Does anyone know how to do it my way?
|
You'd need to make a `User-Defined Function` if you wanted to have syntax similar to your example, but could you do what you want to do, inline, fairly easily with a `CASE` statement, as the others have said.
The `UDF` could be something like this:
```
create function dbo.InlineMax(@val1 int, @val2 int)
returns int
as
begin
if @val1 > @val2
return @val1
return isnull(@val2,@val1)
end
```
... and you would call it like so ...
```
SELECT o.OrderId, dbo.InlineMax(o.NegotiatedPrice, o.SuggestedPrice)
FROM Order o
```
|
If you're using SQL Server 2008 (or above), then this is the better solution:
```
SELECT o.OrderId,
(SELECT MAX(Price)
FROM (VALUES (o.NegotiatedPrice),(o.SuggestedPrice)) AS AllPrices(Price))
FROM Order o
```
All credit and votes should go to [Sven's answer to a related question, "SQL MAX of multiple columns?"](https://stackoverflow.com/a/6871572/2865345)
I say it's the "*best answer*" because:
1. It doesn't require complicating your code with UNION's, PIVOT's,
UNPIVOT's, UDF's, and crazy-long CASE statments.
2. It isn't plagued with the problem of handling nulls, it handles them just fine.
3. It's easy to swap out the "MAX" with "MIN", "AVG", or "SUM". You can use any aggregate function to find the aggregate over many different columns.
4. You're not limited to the names I used (i.e. "AllPrices" and "Price"). You can pick your own names to make it easier to read and understand for the next guy.
5. You can find multiple aggregates using SQL Server 2008's [derived\_tables](http://msdn.microsoft.com/en-us/library/ms177634.aspx) like so:
SELECT MAX(a), MAX(b) FROM (VALUES (1, 2), (3, 4), (5, 6), (7, 8), (9, 10) ) AS MyTable(a, b)
|
Is there a Max function in SQL Server that takes two values like Math.Max in .NET?
|
[
"",
"sql",
"sql-server",
"max",
""
] |
I installed Tomcat 6.0.18 on a windows server 2003 box and it will not start as a service.
I'm running it with jdk 1.6.0\_07.
It runs when I start it with tomcat6.exe.
I got a vague error in the System Event Log on Windows.
The Apache Tomcat 6 service terminated with service-specific error 0 (0x0).
|
I'll bite it :-)
Tomcat Service on windows is dependent on the MS C Runtime library msvcr71.dll. As long as it is in the path, the service will start just fine.
Just to prevent your other windows to be forced to use this version of the runtime library, you might want to copy the DLL to just the tomcat bin path instead of windows\system32.
|
From [gobaco.wordpress.com](http://gobaco.wordpress.com/2007/07/04/could-not-start-tomcat-6-on-windows-xp/)
Tomcat 6 couldn’t find a file called msvcr71.dll.
I just copied it over from
c:\windows\microsoft.net\framework\v1.1.4322
to
c:\windows\system32
and was able to start tomcat.
I thought this was very strange, so I wanted to post it on SO in case anyone else runs into this problem. If someone wants to post the same answer I'll accept it.
|
Tomcat 6.0.18 service will not start on a windows server
|
[
"",
"java",
"tomcat",
"windows-server-2003",
""
] |
I want to put a `Canvas` with an image in my window, and then I want to *pack* widgets on top of it, so the Canvas acts as a background.
Is it possible to have two states for the `pack` manager: one for one set of widgets and another for another set?
|
The answer to your specific question is no. You can't have two states or otherwise use pack two different ways in the same parent.
However, what I think you want to accomplish is simple. Use the built-in features of the canvas to create an image item that is part of the canvas, then pack things into the canvas as if it were a frame.
You can accomplish a similar thing by creating a label widget with an image, then pack your other widgets into the label.
One advantage to using a canvas is you can easily tile an image to fill the whole canvas with a repeating background image so as the window grows the image will continue to fill the window (of course you can just use a sufficiently large original image...)
|
I believe that Bryan's answer is probably the best general solution. However, you may also want to look at the [place](http://www.pythonware.com/library/tkinter/introduction/place.htm) geometry manager. The **place** geometry manager lets you specify the exact size and position of the widget... which can get tedious quickly, but will get the job done.
|
How do I overlap widgets with the Tkinter pack geometry manager?
|
[
"",
"python",
"tkinter",
"geometry",
"pack",
""
] |
I have a curious question about efficiency. Say I have a field on a database that is just a numeric digit that represents something else. Like, a value of 1 means the term is 30 days.
Would it be better (more efficient) to code a SELECT statement like this...
```
SELECT
CASE TermId
WHEN 1 THEN '30 days'
WHEN 2 THEN '60 days'
END AS Term
FROM MyTable
```
...and bind the results directly to the GridView, or would it be better to evaluate the TermId field in RowDataBound event of the GridView and change the cell text accordingly?
Don't worry about extensibility or anything like that, I am only concerned about the differences in overall efficiency. For what it's worth, the database resides on the web server.
|
Efficiency probably wouldn't matter here - code maintainability does though.
Ask yourself - will these values change? What if they do? What would I need to do after 2 years of use if these values change?
If it becomes evident that scripting them in SQL would mean better maintainability (easier to change), then do it in a stored Procedure. If it's easier to change them in code later, then do that.
The benefits from doing either are quite low, as the code doesn't look complex at all.
|
For a number of reasons, I would process the translation in the grid view.
Reason #1: SQL resource is shared. Grid is distributed. Better scalability.
Reason #2: Lower bandwidth to transmit a couple integers vs. strings.
Reason #3: Code can be localized for other languages without affecting the SQL Server code.
|
Manipulate Results in GridView RowDataBound or Directly in SQL?
|
[
"",
"asp.net",
"sql",
"optimization",
""
] |
When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it [here](http://malektips.com/dos0017.html), which describes a callable "wait.bat", implemented as follows:
```
@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul
```
You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep.
[Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command](http://malektips.com/xp_dos_0002.html) (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) [Windows NT](http://en.wikipedia.org/wiki/Windows_NT), is there a better way?
I modified the `sleep.py` script in the [accepted answer](https://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290), so that it defaults to one second if no arguments are passed on the command line:
```
import time, sys
time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)
```
|
# UPDATE
The `timeout` command, available from Windows Vista and onwards should be the command used, as described in another [answer](https://stackoverflow.com/a/5483958/6899) to this question. What follows here is an *old* answer.
### Old answer
If you have Python installed, or don't mind installing it (it has other uses too :), just create the following **sleep.py** script and add it somewhere in your PATH:
```
import time, sys
time.sleep(float(sys.argv[1]))
```
It will allow sub-second pauses (for example, 1.5 sec, 0.1, etc.), should you have such a need. If you want to call it as `sleep` rather than `sleep.py`, then you can add the `.PY` extension to your PATHEXT environment variable. On Windows XP, you can edit it in:
My Computer → Properties (menu) → Advanced (tab) → Environment Variables (button) → System variables (frame)
|
The [`timeout`](http://technet.microsoft.com/en-us/library/cc754891.aspx) command is available from Windows Vista onwards:
```
c:\> timeout /?
TIMEOUT [/T] timeout [/NOBREAK]
Description:
This utility accepts a timeout parameter to wait for the specified
time period (in seconds) or until any key is pressed. It also
accepts a parameter to ignore the key press.
Parameter List:
/T timeout Specifies the number of seconds to wait.
Valid range is -1 to 99999 seconds.
/NOBREAK Ignore key presses and wait specified time.
/? Displays this help message.
NOTE: A timeout value of -1 means to wait indefinitely for a key press.
Examples:
TIMEOUT /?
TIMEOUT /T 10
TIMEOUT /T 300 /NOBREAK
TIMEOUT /T -1
```
Note: It does not work with input redirection - trivial example:
```
C:\>echo 1 | timeout /t 1 /nobreak
ERROR: Input redirection is not supported, exiting the process immediately.
```
|
Sleeping in a batch file
|
[
"",
"python",
"batch-file",
""
] |
I'm trying to get the contents of a XML document element, but the element has a colon in it's name.
This line works for every element but the ones with a colon in the name:
```
$(this).find("geo:lat").text();
```
I assume that the colon needs escaping. How do I fix this?
|
Use a backslash, which itself should be escaped so JavaScript doesn't eat it:
```
$(this).find("geo\\:lat").text();
```
|
That isn't just an ordinary element name. That's a qualified name, meaning that it is a name that specifically refers to an element type within a namespace. The element type name is 'lat', and the namespace prefix is 'geo'.
Right now, jQuery can't deal with namespaces very well, see [bug 155](http://dev.jquery.com/ticket/155) for details.
Right now, as a workaround, you should be able to select these elements with just the local name:
```
$(this).find("lat").text();
```
If you have to distinguish between element types with the same local name, then you can use `filter()`:
```
var NS = "http://example.com/whatever-the-namespace-is-for-geo";
$(this).find("lat").filter(function() { return this.namespaceURI == NS; }).text();
```
**Edit:** my mistake, I was under the impression that patch had already landed. Use Adam's suggestion for the selector, and `filter()` if you need the namespacing too:
```
var NS = "http://example.com/whatever-the-namespace-is-for-geo";
$(this).find("geo\\:lat").filter(function() { return this.namespaceURI == NS; }).text();
```
|
Parsing XML with namespaces using jQuery $().find
|
[
"",
"javascript",
"jquery",
"xml",
"namespaces",
""
] |
So most Java resources when speaking of packages mention a `com.yourcompany.project` setup. However, I do not work for a company, and don't have a website. Are there any naming conventions that are common? An email address, perhaps?
|
Use a top-level domain like 'bernard' or something else unique. The important part is that the domain is unique so that you avoid clashes, and not that it starts with a real Internet top-level domain like org or com. E.g.
```
import java.util.*;
import bernard.myProject.*;
import org.apache.commons.lang.*;
```
|
If your creating an open source project, you could register it with Sourceforge and use net.sourceforge.myproject. This is common with a lot of Java projects. An example is PMD <http://pmd.sourceforge.net/>.
|
How should I name packages if I don't have a domain associated with me?
|
[
"",
"java",
"namespaces",
"package",
""
] |
Basically, I'm trying to create an object of unique objects, a set. I had the brilliant idea of just using a JavaScript object with objects for the property names. Such as,
```
set[obj] = true;
```
This works, up to a point. It works great with string and numbers, but with other objects, they all seem to "hash" to the same value and access the same property. Is there some kind of way I can generate a unique hash value for an object? How do strings and numbers do it, can I override the same behavior?
|
JavaScript objects can only use strings as keys (anything else is converted to a string).
You could, alternatively, maintain an array which indexes the objects in question, and use its index string as a reference to the object. Something like this:
```
var ObjectReference = [];
ObjectReference.push(obj);
set['ObjectReference.' + ObjectReference.indexOf(obj)] = true;
```
Obviously it's a little verbose, but you could write a couple of methods that handle it and get and set all willy nilly.
Edit:
> Your guess is fact -- this is defined behaviour in JavaScript -- specifically a toString conversion occurs meaning that you can can define your own toString function on the object that will be used as the property name. - olliej
This brings up another interesting point; you can define a toString method on the objects you want to hash, and that can form their hash identifier.
|
If you want a hashCode() function like Java's in JavaScript, that is yours:
```
function hashCode(string){
var hash = 0;
for (var i = 0; i < string.length; i++) {
var code = string.charCodeAt(i);
hash = ((hash<<5)-hash)+code;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
```
That is the way of implementation in Java (bitwise operator).
Please note that hashCode could be positive and negative, and that's normal, see [HashCode giving negative values](https://stackoverflow.com/questions/9249983/hashcode-giving-negative-values). So, you could consider to use `Math.abs()` along with this function.
|
Is there hash code function accepting any object type?
|
[
"",
"javascript",
"hash",
"set",
"hashcode",
""
] |
Consider a database table holding names, with three rows:
```
Peter
Paul
Mary
```
Is there an easy way to turn this into a single string of `Peter, Paul, Mary`?
|
If you are on SQL Server 2017 or Azure, see [Mathieu Renda answer](https://stackoverflow.com/a/42778050/1178676).
I had a similar issue when I was trying to join two tables with one-to-many relationships. In SQL 2005 I found that `XML PATH` method can handle the concatenation of the rows very easily.
If there is a table called `STUDENTS`
```
SubjectID StudentName
---------- -------------
1 Mary
1 John
1 Sam
2 Alaina
2 Edward
```
Result I expected was:
```
SubjectID StudentName
---------- -------------
1 Mary, John, Sam
2 Alaina, Edward
```
I used the following `T-SQL`:
```
SELECT Main.SubjectID,
LEFT(Main.Students,Len(Main.Students)-1) As "Students"
FROM
(
SELECT DISTINCT ST2.SubjectID,
(
SELECT ST1.StudentName + ',' AS [text()]
FROM dbo.Students ST1
WHERE ST1.SubjectID = ST2.SubjectID
ORDER BY ST1.SubjectID
FOR XML PATH (''), TYPE
).value('text()[1]','nvarchar(max)') [Students]
FROM dbo.Students ST2
) [Main]
```
You can do the same thing in a more compact way if you can concat the commas at the beginning and use `substring` to skip the first one so you don't need to do a sub-query:
```
SELECT DISTINCT ST2.SubjectID,
SUBSTRING(
(
SELECT ','+ST1.StudentName AS [text()]
FROM dbo.Students ST1
WHERE ST1.SubjectID = ST2.SubjectID
ORDER BY ST1.SubjectID
FOR XML PATH (''), TYPE
).value('text()[1]','nvarchar(max)'), 2, 1000) [Students]
FROM dbo.Students ST2
```
|
> **This answer may return [unexpected results](https://stackoverflow.com/questions/15138593/nvarchar-concatenation-index-nvarcharmax-inexplicable-behavior/15163136#15163136) For consistent results, use one of the FOR XML PATH methods detailed in other answers.**
Use `COALESCE`:
```
DECLARE @Names VARCHAR(8000)
SELECT @Names = COALESCE(@Names + ', ', '') + Name
FROM People
```
Just some explanation (since this answer seems to get relatively regular views):
* Coalesce is really just a helpful cheat that accomplishes two things:
1) No need to initialize `@Names` with an empty string value.
2) No need to strip off an extra separator at the end.
* The solution above will give incorrect results if a row has a *NULL* Name value (if there is a *NULL*, the *NULL* will make `@Names` *NULL* after that row, and the next row will start over as an empty string again. Easily fixed with one of two solutions:
```
DECLARE @Names VARCHAR(8000)
SELECT @Names = COALESCE(@Names + ', ', '') + Name
FROM People
WHERE Name IS NOT NULL
```
or:
```
DECLARE @Names VARCHAR(8000)
SELECT @Names = COALESCE(@Names + ', ', '') +
ISNULL(Name, 'N/A')
FROM People
```
Depending on what behavior you want (the first option just filters *NULL*s out, the second option keeps them in the list with a marker message [replace 'N/A' with whatever is appropriate for you]).
|
How to concatenate text from multiple rows into a single text string in SQL Server
|
[
"",
"sql",
"sql-server",
"csv",
"string-concatenation",
"group-concat",
""
] |
I'm looking for some succinct, modern C# code to generate a random date between Jan 1 1995 and the current date.
I'm thinking some solution that utilizes Enumerable.Range somehow may make this more succinct.
|
```
private Random gen = new Random();
DateTime RandomDay()
{
DateTime start = new DateTime(1995, 1, 1);
int range = (DateTime.Today - start).Days;
return start.AddDays(gen.Next(range));
}
```
For better performance if this will be called repeatedly, create the `start` and `gen` (and maybe even `range`) variables *outside* of the function.
|
This is in slight response to Joel's comment about making a slighly more optimized version. Instead of returning a random date directly, why not return a generator function which can be called repeatedly to create a random date.
```
Func<DateTime> RandomDayFunc()
{
DateTime start = new DateTime(1995, 1, 1);
Random gen = new Random();
int range = ((TimeSpan)(DateTime.Today - start)).Days;
return () => start.AddDays(gen.Next(range));
}
```
|
Random date in C#
|
[
"",
"c#",
"datetime",
"random",
"date",
""
] |
I have a pretty standard django app, and am wondering how to set the url routing so that I don't have to explicitly map each url to a view.
For example, let's say that I have the following views: `Project, Links, Profile, Contact`. I'd rather not have my `urlpatterns` look like this:
```
(r'^Project/$', 'mysite.app.views.project'),
(r'^Links/$', 'mysite.app.views.links'),
(r'^Profile/$', 'mysite.app.views.profile'),
(r'^Contact/$', 'mysite.app.views.contact'),
```
And so on. In [Pylons](http://www.pylonshq.com), it would be as simple as:
```
map.connect(':controller/:action/:id')
```
And it would automatically grab the right controller and function. Is there something similar in Django?
|
```
mods = ('Project','Links','Profile','Contact')
urlpatterns = patterns('',
*(('^%s/$'%n, 'mysite.app.views.%s'%n.lower()) for n in mods)
)
```
|
Unless you have a really *huge* number of views, writing them down explicitly is not too bad, from a style perspective.
You can shorten your example, though, by using the prefix argument of the `patterns` function:
```
urlpatterns = patterns('mysite.app.views',
(r'^Project/$', 'project'),
(r'^Links/$', 'links'),
(r'^Profile/$', 'profile'),
(r'^Contact/$', 'contact'),
)
```
|
Django: How do I create a generic url routing to views?
|
[
"",
"python",
"django",
"pylons",
""
] |
I have an XmlDocument that already exists and is read from a file.
I would like to add a chunk of Xml to a node in the document. Is there a good way to create and add all the nodes without cluttering my code with many .CreateNote and .AppendChild calls?
I would like some way of making a string or stringBuilder of a valid Xml section and just appending that to an XmlNode.
ex:
Original XmlDoc:
```
<MyXml>
<Employee>
</Employee>
</MyXml>
```
and, I would like to add a Demographic (with several children) tag to Employee:
```
<MyXml>
<Employee>
<Demographic>
<Age/>
<DOB/>
</Demographic>
</Employee>
</MyXml>
```
|
I suggest using [XmlDocument.CreateDocumentFragment](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.createdocumentfragment.aspx) if you have the data in free form strings. You'll still have to use AppendChild to add the fragment to a node, but you have the freedom of building the XML in your StringBuilder.
```
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(@"<MyXml><Employee></Employee></MyXml>");
XmlDocumentFragment xfrag = xdoc.CreateDocumentFragment();
xfrag.InnerXml = @"<Demographic><Age/><DOB/></Demographic>";
xdoc.DocumentElement.FirstChild.AppendChild(xfrag);
```
|
Try this:
```
employeeNode.InnerXml = "<Demographic><Age/><DOB/></Demographic>";
```
Alternatively (if you have another XML document that you want to use):
```
employeeNode.AppendChild(employeeNode.OwnerDocument.ImportNode(otherXmlDocument.DocumentElement, true));
```
|
Append XML string block to existing XmlDocument
|
[
"",
"c#",
"xml",
""
] |
Is a new (or different) instance of `TestCase` object is used to run each test method in a JUnit test case? Or one instance is reused for all the tests?
```
public class MyTest extends TestCase {
public void testSomething() { ... }
public void testSomethingElse() { ... }
}
```
While running this test, how many instances of `MyTest` class is created?
If possible, provide a link to a document or source code where I can verify the behaviour.
|
I couldn't find a clear answer in the JUnit docs about your question, but the intent, as anjanb wrote, is that each test is independent of the others, so a new TestCase instance could be created for each test to be run.
If you have expensive test setup ("*fixtures*") that you want to be shared across all test cases in a test class, you can use the **@BeforeClass** annotation on a static method to achieve this result: <http://junit.sourceforge.net/javadoc_40/org/junit/BeforeClass.html>. Note however, that a new instance may still be created for each test, but that won't affect the static data your @BeforeTest method has initialized.
|
Yes, a separate instance is created.
While running that test, 2 instances of MyTest gets created.
If you want a different behavior, one option is to use a similar tool called TestNG(<http://testng.org/doc/>).
|
JUnit TestCase object instantiation
|
[
"",
"java",
"junit",
"instantiation",
"testcase",
""
] |
I've just found out about Stack Overflow and I'm just checking if there are ideas for a constraint I'm having with some friends in a project, though this is more of a theoretical question to which I've been trying to find an answer for some time.
I'm not much given into cryptography but if I'm not clear enough I'll try to edit/comment to clarify any questions.
Trying to be brief, the environment is something like this:
* An application where the front-end as access to encrypt/decrypt keys and the back-end is just used for storage and queries.
* Having a database to which you can't have access for a couple of fields for example let's say "address" which is text/varchar as usual.
* You don't have access to the key for decrypting the information, and all information arrives to the database already encrypted.
The main problem is something like this, how to consistently make queries on the database, it's impossible to do stuff like "where address like '%F§YU/´~#JKSks23%'". (IF there is anyone feeling with an answer for this feel free to shoot it).
But is it ok to do `where address='±!NNsj3~^º-:'`? Or would it also completely eat up the database?
Another restrain that might apply is that the front end doesn't have much processing power available, so already encrypting/decrypting information starts to push it to its limits. (Saying this just to avoid replies like "Exporting a join of tables to the front end and query it there".)
Could someone point me in a direction to keep thinking about it?
---
Well thanks for so fast replies at 4 AM, for a first time usage I'm really feeling impressed with this community. (Or maybe I'm it's just for the different time zone)
Just feeding some information:
The main problem is all around partial matching. As a mandatory requirement in most databases is to allow partial matches. The main constraint is actually **the database owner would not be allowed to look inside the database for information**. During the last 10 minutes I've come up with a possible solution which extends again to possible database problems, to which I'll add here:
Possible solution to allow semi partial matching:
* The password + a couple of public fields of the user are actually the key for encrypting. For authentication the idea is to encrypt a static value and compare it within the database.
* Creating a new set of tables where information is stored in a parsed way, meaning something like: "4th Street" would become 2 encrypted rows (one for '4th' another for 'Street'). This would already allow semi-partial matching as a search could already be performed on the separate tables.
New question:
* Would this probably eat up the database server again, or does anyone think it is a viable solution for the partial matching problem?
*Post Scriptum: I've unaccepted the answer from Cade Roux just to allow for further discussion and specially a possible answer to the new question.*
|
You can do it the way you describe - effectively querying the hash, say, but there's not many systems with that requirement, because at that point the security requirements are interfering with other requirements for the system to be usable - i.e. no partial matches, since the encryption rules that out. It's the same problem with compression. Years ago, in a very small environment, I had to compress the data before putting it in the data format. Of course, those fields could not easily be searched.
In a more typical application, ultimately, the keys are going to be available to someone in the chain - probably the web server.
For end user traffic SSL protects that pipe. Some network switches can protect it between web server and database, and storing encrypted data in the database is fine, but you're not going to query on encrypted data like that.
And once the data is displayed, it's out there on the machine, so any general purpose computing device can be circumvented at that point, and you have perimeter defenses outside of your application which really come into play.
|
why not encrypt the disk holding the database tables, encrypt the database connections, and let the database operate normally?
[i don't really understand the context/contraints that require this level of paranoia]
EDIT: "law constraints" eh? I hope you're not involved in anything illegal, I'd hate to be an inadvertent accessory... ;-)
if the - ahem - legal constraints - force this solution, then that's all there is to be done - no LIKE matches, and slow response if the client machines can't handle it.
|
Encrypted database query
|
[
"",
"sql",
"database",
"encryption",
"theory",
""
] |
When is it better to use a [List](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1) vs a [LinkedList](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1)?
|
## Edit
> Please read the comments to this answer. People claim I did not do
> proper tests. I agree this should not be an accepted answer. As I was
> learning I did some tests and felt like sharing them.
## Original answer...
I found interesting results:
```
// Temporary class to show the example
class Temp
{
public decimal A, B, C, D;
public Temp(decimal a, decimal b, decimal c, decimal d)
{
A = a; B = b; C = c; D = d;
}
}
```
## Linked list (3.9 seconds)
```
LinkedList<Temp> list = new LinkedList<Temp>();
for (var i = 0; i < 12345678; i++)
{
var a = new Temp(i, i, i, i);
list.AddLast(a);
}
decimal sum = 0;
foreach (var item in list)
sum += item.A;
```
## List (2.4 seconds)
```
List<Temp> list = new List<Temp>(); // 2.4 seconds
for (var i = 0; i < 12345678; i++)
{
var a = new Temp(i, i, i, i);
list.Add(a);
}
decimal sum = 0;
foreach (var item in list)
sum += item.A;
```
**Even if you only access data essentially it is much slower!!** I say never use a linkedList.
---
---
---
**Here is another comparison performing a lot of inserts (we plan on inserting an item at the middle of the list)**
## Linked List (51 seconds)
```
LinkedList<Temp> list = new LinkedList<Temp>();
for (var i = 0; i < 123456; i++)
{
var a = new Temp(i, i, i, i);
list.AddLast(a);
var curNode = list.First;
for (var k = 0; k < i/2; k++) // In order to insert a node at the middle of the list we need to find it
curNode = curNode.Next;
list.AddAfter(curNode, a); // Insert it after
}
decimal sum = 0;
foreach (var item in list)
sum += item.A;
```
## List (7.26 seconds)
```
List<Temp> list = new List<Temp>();
for (var i = 0; i < 123456; i++)
{
var a = new Temp(i, i, i, i);
list.Insert(i / 2, a);
}
decimal sum = 0;
foreach (var item in list)
sum += item.A;
```
## Linked List having reference of location where to insert (.04 seconds)
```
list.AddLast(new Temp(1,1,1,1));
var referenceNode = list.First;
for (var i = 0; i < 123456; i++)
{
var a = new Temp(i, i, i, i);
list.AddLast(a);
list.AddBefore(referenceNode, a);
}
decimal sum = 0;
foreach (var item in list)
sum += item.A;
```
So only if you plan on inserting several items and you **also** somewhere have the reference of where you plan to insert the item then use a linked list. Just because you have to insert a lot of items it does not make it faster because searching the location where you will like to insert it takes time.
|
In most cases, `List<T>` is more useful. `LinkedList<T>` will have less cost when adding/removing items in the middle of the list, whereas `List<T>` can only cheaply add/remove at the *end* of the list.
`LinkedList<T>` is only at it's most efficient if you are accessing sequential data (either forwards or backwards) - random access is relatively expensive since it must walk the chain each time (hence why it doesn't have an indexer). However, because a `List<T>` is essentially just an array (with a wrapper) random access is fine.
`List<T>` also offers a lot of support methods - `Find`, `ToArray`, etc; however, these are also available for `LinkedList<T>` with .NET 3.5/C# 3.0 via extension methods - so that is less of a factor.
|
When should I use a List vs a LinkedList
|
[
"",
"c#",
".net",
"vb.net",
"data-structures",
"linked-list",
""
] |
What is the easiest way to find out how much memory an object uses in .NET?
Preferably without having to resort to a third party tool. Marshal.SizeOf or the sizeof operator look useful but only work with a restricted range of types.
Some related posts:
* [Object Memory Analysis in .NET](https://stackoverflow.com/questions/109836/object-memory-analysis-in-net)
* [Does an empty array in .NET use any space?](https://stackoverflow.com/questions/151936/does-an-empty-array-in-net-use-any-space)
|
you could also do something like this:
```
int startMem = GC.GetTotalMemory(true);
YourClass c = new YourClass();
int endMem = GC.GetTotalMemory(true);
int usedMeme = endMem - startMem;
```
|
Asked and answered here: [Determine how much memory a class uses?](https://stackoverflow.com/questions/51540/determine-how-much-memory-a-class-uses#51895)
The quick summary is that if you don't want to use a tool, you need to use the [.NET Profiling API](http://msdn.microsoft.com/en-us/library/ms404386.aspx)
The Profiling API is amazingly powerful, but I don't think it would qualify as "easy" by any stretch of the imagination, so I would strongly recommend using a memory profiling tool - there are some free ones that are OK, and some not-too-expensive commercial ones ([JetBrains dotTrace](http://www.jetbrains.com/profiler/index.html) in particular) that are really good.
|
What is the easiest way to find out how much memory an object uses in .NET?
|
[
"",
"c#",
".net",
"memory",
""
] |
I got one big question.
I got a linq query to put it simply looks like this:
```
from xx in table
where xx.uid.ToString().Contains(string[])
select xx
```
The values of the `string[]` array would be numbers like (1,45,20,10,etc...)
the Default for `.Contains` is `.Contains(string)`.
I need it to do this instead: `.Contains(string[])`...
**EDIT :** One user suggested writing an extension class for `string[]`. I would like to learn how, but any one willing to point me in the right direction?
**EDIT :** The uid would also be a number. That's why it is converted to a string.
Help anyone?
|
spoulson has it nearly right, but you need to create a `List<string>` from `string[]` first. Actually a `List<int>` would be better if uid is also `int`. `List<T>` supports `Contains()`. Doing `uid.ToString().Contains(string[])` would imply that the uid as a string contains all of the values of the array as a substring??? Even if you did write the extension method the sense of it would be wrong.
**[EDIT]**
Unless you changed it around and wrote it for `string[]` as Mitch Wheat demonstrates, then you'd just be able to skip the conversion step.
**[ENDEDIT]**
Here is what you want, if you don't do the extension method (unless you already have the collection of potential uids as ints -- then just use `List<int>()` instead). This uses the chained method syntax, which I think is cleaner, and
does the conversion to int to ensure that the query can be used with more providers.
```
var uids = arrayofuids.Select(id => int.Parse(id)).ToList();
var selected = table.Where(t => uids.Contains(t.uid));
```
|
If you are truly looking to replicate *Contains*, but for an array, here is an [extension method](http://msdn.microsoft.com/en-us/library/bb383977.aspx) and sample code for usage:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ContainsAnyThingy
{
class Program
{
static void Main(string[] args)
{
string testValue = "123345789";
//will print true
Console.WriteLine(testValue.ContainsAny("123", "987", "554"));
//but so will this also print true
Console.WriteLine(testValue.ContainsAny("1", "987", "554"));
Console.ReadKey();
}
}
public static class StringExtensions
{
public static bool ContainsAny(this string str, params string[] values)
{
if (!string.IsNullOrEmpty(str) || values.Length > 0)
{
foreach (string value in values)
{
if(str.Contains(value))
return true;
}
}
return false;
}
}
}
```
|
How do I use LINQ Contains(string[]) instead of Contains(string)
|
[
"",
"c#",
"linq",
"string",
"contains",
""
] |
I'd love to figure it out myself but I was wondering **roughly what's the algorithm for converting a function with yield statements into a state machine for an enumerator?** For example how does C# turn this:
```
IEnumerator<string> strings(IEnumerable<string> args)
{ IEnumerator<string> enumerator2 = getAnotherEnumerator();
foreach(var arg in arg)
{ enumerator2.MoveNext();
yield return arg+enumerator.Current;
}
}
```
into this:
```
bool MoveNext()
{ switch (this.state)
{
case 0:
this.state = -1;
this.enumerator2 = getAnotherEnumerator();
this.argsEnumerator = this.args.GetEnumerator();
this.state = 1;
while (this.argsEnumerator.MoveNext())
{
this.arg = this.argsEnumerator.Current;
this.enumerator2.MoveNext();
this.current = this.arg + this.enumerator2.Current;
this.state = 2;
return true;
state1:
this.state = 1;
}
this.state = -1;
if (this.argsEnumerator != null) this.argsEnumerator.Dispose();
break;
case 2:
goto state1;
}
return false;
}
```
Of course the result can be completely different depending on the original code.
|
The particular code sample you are looking at involves a series of transformations.
Please note that this is an approximate description of the algorithm. The actual names used by the compiler and the exact code it generates may be different. The idea is the same, however.
The first transformation is the "foreach" transformation, which transforms this code:
```
foreach (var x in y)
{
//body
}
```
into this code:
```
var enumerator = y.GetEnumerator();
while (enumerator.MoveNext())
{
var x = enumerator.Current;
//body
}
if (y != null)
{
enumerator.Dispose();
}
```
The second transformation finds all the yield return statements in the function body, assigns a number to each (a state value), and creates a "goto label" right after the yield.
The third transformation lifts all the local variables and function arguments in the method body into an object called a closure.
Given the code in your example, that would look similar to this:
```
class ClosureEnumerable : IEnumerable<string>
{
private IEnumerable<string> args;
private ClassType originalThis;
public ClosureEnumerator(ClassType origThis, IEnumerable<string> args)
{
this.args = args;
this.origianlThis = origThis;
}
public IEnumerator<string> GetEnumerator()
{
return new Closure(origThis, args);
}
}
class Closure : IEnumerator<string>
{
public Closure(ClassType originalThis, IEnumerable<string> args)
{
state = 0;
this.args = args;
this.originalThis = originalThis;
}
private IEnumerable<string> args;
private IEnumerator<string> enumerator2;
private IEnumerator<string> argEnumerator;
//- Here ClassType is the type of the object that contained the method
// This may be optimized away if the method does not access any
// class members
private ClassType originalThis;
//This holds the state value.
private int state;
//The current value to return
private string currentValue;
public string Current
{
get
{
return currentValue;
}
}
}
```
The method body is then moved from the original method to a method inside "Closure" called MoveNext, which returns a bool, and implements IEnumerable.MoveNext.
Any access to any locals is routed through "this", and any access to any class members are routed through this.originalThis.
Any "yield return expr" is translated into:
```
currentValue = expr;
state = //the state number of the yield statement;
return true;
```
Any yield break statement is translated into:
```
state = -1;
return false;
```
There is an "implicit" yield break statement at the end of the function.
A switch statement is then introduced at the beginning of the procedure that looks at the state number and jumps to the associated label.
The original method is then translated into something like this:
```
IEnumerator<string> strings(IEnumerable<string> args)
{
return new ClosureEnumerable(this,args);
}
```
The fact that the state of the method is all pushed into an object and that the MoveNext method uses a switch statement / state variable is what allows the iterator to behave as if control is being passed back to the point immediately after the last "yield return" statement the next time "MoveNext" is called.
It is important to point out, however, that the transformation used by the C# compiler is not the best way to do this. It suffers from poor performance when trying to use "yield" with recursive algorithms. There is a good paper that outlines a better way to do this here:
<http://research.microsoft.com/en-us/projects/specsharp/iterators.pdf>
It's worth a read if you haven't read it yet.
|
Just spotted this question - I [wrote an article](http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx) on it recently. I'll have to add the other links mentioned here to the article though...
|
Algorithm for implementing C# yield statement
|
[
"",
"c#",
"algorithm",
"compiler-construction",
"iterator",
"state-machine",
""
] |
On my homepage I got:
```
<ul id="login">
<li> <a id="loginswitch" href="./login-page">log-in</a> | </li>
<li> <a id="signupswitch" href="./signup-page">sign-up</a> </li>
</ul>
```
Via MooTools, I get these anchor elements by id so that once they're clicked, a flashy div will popup below them that contains the login or signup form (with methods to stop the propagation of events of course)
and upon filling-up the fields the AJAX call kicks in - that's supposed to create a session and reload the page so that the user would have a visual that he is now logged in and user-level-controls appears etc..
The ajax call is initiated by the MooTools AJAX class and `evalScripts` option is set to true. The AJAX page returns the script code:
```
<script type="text/javascript">window.location = self.location;</script>
```
This system works perfectly - now I'm wondering why if I change the anchors' `href` values to `href="#"` my scripts won't work anymore?
Does it have anything to do with the window?
Did it change its property when I clicked a link or so even when the event's propagation was stopped??
|
```
window.location = self.location;
```
**This JavaScript is executing**.
When it executes, the browser is being told to replace the value of `window.location` with a new value. **Not all browsers** will react the same way here. Some will probably work as you expect, but others will get smart about it and compare the two values. **The browser knows** what page it's on, and it knows that you're just asking for it to go to the same page.
**Browser Cache**
The browser even has a copy of your current page in **cache**. It can talk to the server and ask whether the page it has in cache is still valid. If the cache is valid, it may decide not to force a reload of the page. Behind the scenes, this happens with HTTP headers. Browsers and servers can communicate over HTTP in many ways. In this case, your browser sends a quick request to the server saying something like this:
```
GET /stackoverflow.com/posts/196643/index.html
HTTP/1.1
Host: www.stackoverflow.com
User-Agent: Mozilla/5.0
If-Modified-Since: Sun, 12 Oct 2008 20:41:31 GMT
```
This is called a **conditional GET request**. By saying *If-Modified-Since*, your browser is saying, "Give me that file, but only if it has been modified since the last time I saw it."
Long story short, you haven't explicitly told the browser to reload the page.
**Here's how you can:**
```
location.reload( true );
```
The "true" is an **optional parameter**, for **forcing a reload**. The browser won't even look at the cache. It will just do as you say.
|
Going to an anchor on a page -- which is what `#` signifies -- does not require a reload.
|
Reloading a page via AJAX when window.location=self.location doesn't work
|
[
"",
"javascript",
"browser",
"caching",
"reload",
""
] |
I'm trying to generate a unique ID in php in order to store user-uploaded content on a FS without conflicts. I'm using php, and at the moment this little snippet is responsible for generating the UID:
```
$id = tempnam (".", "");
unlink($id);
$id = substr($id, 2);
```
This code is hideous: it creates a temporary file on the FS and deletes it, retaining only the relevant unique part of the generated string.
Is there any better way to do this, most preferably without any external dependencies?
Thanks much!
|
```
string uniqid ([ string $prefix [, bool $more_entropy ]] )
```
Gets a prefixed unique identifier based on the current time in microseconds.
```
USAGE: $id = uniqid(rand(), true);
```
|
Since both uniqid() and rand() are functions based on the current time, rand() adds almost no entropy, since the time will change only a tiny amount between the respective calls.
As long as you use the `more_entropy` option, you should never have a collision within a single server. If you use clustering, be sure to include a prefix that differs between servers.
|
Generating a unique ID in PHP
|
[
"",
"php",
"guid",
"unique",
"uuid",
"identifier",
""
] |
Let's say:
```
<div>
pre text
<div class="remove-just-this">
<p>child foo</p>
<p>child bar</p>
nested text
</div>
post text
</div>
```
to this:
```
<div>
pre text
<p>child foo</p>
<p>child bar</p>
nested text
post text
</div>
```
I've been figuring out using Mootools, jQuery and even (raw) JavaScript, but couldn't get the idea how to do this.
|
Using [jQuery](http://jquery.com/) you can do this:
```
var cnt = $(".remove-just-this").contents();
$(".remove-just-this").replaceWith(cnt);
```
Quick links to the documentation:
* [contents](http://docs.jquery.com/Traversing/contents)( ) : *jQuery*
* [replaceWith](http://docs.jquery.com/Manipulation/replaceWith)( *content* : [*String* | *Element* | *jQuery*] ) : *jQuery*
|
The library-independent method is to insert all child nodes of the element to be removed before itself (which implicitly removes them from their old position), before you remove it:
```
while (nodeToBeRemoved.firstChild)
{
nodeToBeRemoved.parentNode.insertBefore(nodeToBeRemoved.firstChild,
nodeToBeRemoved);
}
nodeToBeRemoved.parentNode.removeChild(nodeToBeRemoved);
```
This will move all child nodes to the correct place in the right order.
|
How to remove only the parent element and not its child elements in JavaScript?
|
[
"",
"javascript",
"dom",
""
] |
I am creating a lightweight editor in C# and would like to know the best method for converting a string into a nicely formatted XML string. I would hope that there's a public method in the C# library like "public bool FormatAsXml(string text, out string formattedXmlText)", but it couldn't be that easy, could it?
Very specifically, what would the method "SomeMethod" have to be that would produce the output below?
```
string unformattedXml;
string formattedXml;
unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>"
formattedXml = SomeMethod(unformattedXml);
Console.WriteLine(formattedXml);
```
Output:
```
<?xml version="1.0"?>
<book id="123">
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>
```
|
```
string unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>";
string formattedXml = XElement.Parse(unformattedXml).ToString();
Console.WriteLine(formattedXml);
```
Output:
```
<book>
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>
```
The Xml Declaration isn't output by ToString(), but it is by Save() ...
```
XElement.Parse(unformattedXml).Save(@"C:\doc.xml");
Console.WriteLine(File.ReadAllText(@"C:\doc.xml"));
```
Output:
```
<?xml version="1.0" encoding="utf-8"?>
<book>
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>
```
|
Unfortunately no, it's not as easy as a FormatXMLForOutput method, this is Microsoft were talking about here ;)
Anyway, as of .NET 2.0, the recommended approach is to use the XMlWriterSettingsClass to set up formatting, as opposed to setting properties directly on the XmlTextWriter object. [See this MSDN page](http://msdn.microsoft.com/en-us/library/kkz7cs0d.aspx) for more details. It says:
"In the .NET Framework version 2.0 release, the recommended practice is to create XmlWriter instances using the XmlWriter.Create method and the XmlWriterSettings class. This allows you to take full advantage of all the new features introduced in this release. For more information, see Creating XML Writers. "
Here is an example of the recommended approach:
```
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = (" ");
using (XmlWriter writer = XmlWriter.Create("books.xml", settings))
{
// Write XML data.
writer.WriteStartElement("book");
writer.WriteElementString("price", "19.95");
writer.WriteEndElement();
writer.Flush();
}
```
|
In C#, what is the best method to format a string as XML?
|
[
"",
"c#",
"xml",
"string",
"formatting",
"string-formatting",
""
] |
Has anyone got this working in a web application?
No matter what I do it seems that my appSettings section (redirected from web.config using appSettings file=".\Site\site.config") does not get reloaded.
Am I doomed to the case of having to just restart the application? I was hoping this method would lead me to a more performant solution.
Update:
By 'reloading' I mean refreshing ConfigurationManager.AppSettings without having to completely restart my ASP.NET application and having to incur the usual startup latency.
|
Make sure you are passing the correct [case sensitive](http://en.wikipedia.org/wiki/Case_sensitivity) value to RefreshSection, i.e.
```
ConfigurationManager.RefreshSection("appSettings");
```
|
This seems to be a flaw (maybe a bug) when using an external config file for your appSettings. I've tried it using the configSource attribute and RefreshSection simply never works, I'm assuming this is the same when using the file attribute.
If you move your appSettings back inside your web.config RefreshSection will work perfectly but otherwise I'm afraid you're doomed.
|
Reloading configuration without restarting application using ConfigurationManager.RefreshSection
|
[
"",
"c#",
"asp.net",
"performance",
"settings",
""
] |
I hope this isn't considered a duplicate since it's more pointed than similar questions (I'm curious about a specific weakness in C# to VB.net conversion utilities).
I've been looking at using a tool like this [.net code converter](http://www.developerfusion.com/tools/convert/csharp-to-vb/) to convert a class library to VB since I'm the only one in my group comfortable with C#. The problem I've run into is that it doesn't generate proper VB for automatic properties. It creates empty get/set routines.
So this:
```
public string TransactionType { get; private set; }
```
Becomes this:
```
Public Property TransactionType() As String
Get
End Get
Private Set(ByVal value As String)
End Set
End Property
```
The tools linked [here](https://stackoverflow.com/questions/102956/c-vbnet-conversion "here") and [here](https://stackoverflow.com/questions/88359/what-is-the-best-c-to-vbnet-converter) have similar issues - some create valid properties, but they don't respect the access level of the set routine.
Side question - If you were going to fix the converter on DeveloperFusion, would you have it return something like this?
```
Private _TransactionType As String
Public Property TransactionType() As String
Get
Return _TransactionType
End Get
Private Set(ByVal value As String)
_TransactionType = value
End Set
End Property
```
|
We've now updated the code generator to support this scenario. If you spot any others that we're not doing very well, please do drop me a line.
|
I'd recommend compiling the code and using something like Red-Gate's reflector <http://www.red-gate.com/products/reflector/index.htm> to handle the conversion. Now it's not "perfect," and I'm not sure if it handles automatic properties (though I'd imagine it would).
What makes this possible is that when you compile .NET language down to IL they're exactly the same. The language is just another layer on top of that. So 2 properties that would look at the same in their native languages compile to the exact same IL code. So reversing this to other languages using something like Reflector is easy and quick.
|
A C# to VB.Net conversion utility that handles Automatic properties correctly?
|
[
"",
"c#",
"vb.net",
"automatic-properties",
""
] |
I need to evaluate a mathmatical expression that is presented to me as a string in C#. Example noddy but gets the point across that the string as the expression.
I need the evaluate to then populate an int.
There is no Eval() in C# like in others langugaes...
```
String myString = "3*4";
```
Edit:
I am on VS2008
Tried the Microsoft.JScript. = Its deprecated method (but still complies - warning)
However the Microsoft.JScript dll that I have doens work on
> public object InvokeMember(string
> name, BindingFlags invokeAttr, Binder
> binder, object target, object[] args);
Complains that there is a missing ";" go figure...
EDIT 2
Solution - was the codeDom one - it worked for as there are no security issue - only me ever going to be running the code. Many thanks for the replies ...
And the link to the new Dragon Book awesome
EDIT 3
Matt dataTable.Compute() also works - even better for the security conscious. (parameter checking noted)
|
The way I see it, you have two options - use an expression evaluator or construct, compile
and run C# code on the fly.
I would go with an expression evaluator library, as you do not have to worry about any security issues. That is, you might not be able to use code generation in medium trust environments, such as most shared hosting servers.
Here is an example for generating code to evaluate expressions:
<http://www.vbforums.com/showthread.php?t=397264>
|
All the other answers are possible overkill.
If all you need is simple arithmetic, do this.
```
DataTable dummy = new DataTable();
Console.WriteLine(dummy.Compute("15 / 3",string.Empty));
```
EDIT: a little more information. Check out the MSDN documentation for the `Expression` property of the `System.Data.DataColumn` class. The stuff on "Expression Syntax" outlines a list of commands you can use in addition to the arithmetic operators. (ex. IIF, LEN, etc.). Thanks everyone for voting up my first posted answer!
|
operators as strings
|
[
"",
"c#",
""
] |
I'd like to get all the permutations of swapped characters pairs of a string. For example:
Base string: `abcd`
Combinations:
1. `bacd`
2. `acbd`
3. `abdc`
etc.
### Edit
I want to swap only letters that are next to each other. Like first with second, second with third, but not third with sixth.
What's the best way to do this?
### Edit
Just for fun: there are three or four solutions, could somebody post a speed test of those so we could compare which is fastest?
### Speed test
I made speed test of nickf's code and mine, and results are that mine is beating the nickf's at four letters (0.08 and 0.06 for 10K times) but nickf's is beating it at 10 letters (nick's 0.24 and mine 0.37)
|
Edit: Markdown hates me today...
```
$input = "abcd";
$len = strlen($input);
$output = array();
for ($i = 0; $i < $len - 1; ++$i) {
$output[] = substr($input, 0, $i)
. substr($input, $i + 1, 1)
. substr($input, $i, 1)
. substr($input, $i + 2);
}
print_r($output);
```
|
nickf made beautiful solution thank you , i came up with less beautiful:
```
$arr=array(0=>'a',1=>'b',2=>'c',3=>'d');
for($i=0;$i<count($arr)-1;$i++){
$swapped="";
//Make normal before swapped
for($z=0;$z<$i;$z++){
$swapped.=$arr[$z];
}
//Create swapped
$i1=$i+1;
$swapped.=$arr[$i1].$arr[$i];
//Make normal after swapped.
for($y=$z+2;$y<count($arr);$y++){
$swapped.=$arr[$y];
}
$arrayswapped[$i]=$swapped;
}
var_dump($arrayswapped);
```
|
Swap every pair of characters in string
|
[
"",
"php",
"string",
""
] |
As part of a project at work I have to calculate the centroid of a set of points in 3D space. Right now I'm doing it in a way that seems simple but naive -- by taking the average of each set of points, as in:
```
centroid = average(x), average(y), average(z)
```
where `x`, `y` and `z` are arrays of floating-point numbers. I seem to recall that there is a way to get a more accurate centroid, but I haven't found a simple algorithm for doing so. Anyone have any ideas or suggestions? I'm using Python for this, but I can adapt examples from other languages.
|
Contrary to the common refrain here, there are different ways to define (and calculate) a center of a point cloud. The first and most common solution has been suggested by you already and I will **not** argue that there is anything wrong with this:
`centroid = average(x), average(y), average(z)`
The "problem" here is that it will "distort" your center-point depending on the distribution of your points. If, for example, you assume that all your points are within a cubic box or some other geometric shape, but most of them happen to be placed in the upper half, your center-point will also shift in that direction.
As an alternative you could use the mathematical middle (the mean of the extrema) in each dimension to avoid this:
`middle = middle(x), middle(y), middle(z)`
You can use this when you don't care much about the number of points, but more about the global bounding box, because that's all this is - the center of the bounding box around your points.
Lastly, you could also use the `median` (the element in the middle) in each dimension:
`median = median(x), median(y), median(z)`
Now this will sort of do the opposite to the `middle` and actually help you ignore outliers in your point cloud and find a centerpoint **based on** the distribution of your points.
A more and robust way to find a "good" centerpoint might be to ignore the top and bottom 10% in each dimension and then calculate the `average` or `median`. As you can see you can define the centerpoint in different ways. Below I am showing you examples of 2 2D point clouds with these suggestions in mind.
The dark blue dot is the average (mean) centroid.
The median is shown in green.
And the middle is shown in red.
In the second image you will see exactly what I was talking about earlier: The green dot is "closer" to the densest part of the point cloud, while the red dot is further way from it, taking into account the most extreme boundaries of the point cloud.
[](https://i.stack.imgur.com/8qSQA.png)
[](https://i.stack.imgur.com/iZSSi.png)
|
You vaguely mention "a way to get a more accurate centroid". Maybe you're talking about a centroid that isn't affected by outliers. For example, the *average* household income in the USA is probably very high, because a small number of *very* rich people skew the average; they are the "outliers". For that reason, statisticians use the *median* instead. One way to obtain the median is to sort the values, then pick the value halfway down the list.
Maybe you're looking for something like this, but for 2D or 3D points. The problem is, in 2D and higher, you can't sort. There's no natural order. Nevertheless, there are ways to get rid of outliers.
One way is to find the [convex hull](http://en.wikipedia.org/wiki/Convex_hull) of the points. The convex hull has all the points on the "outside" of the set of points. If you do this, and throw out the points that are on the hull, you'll be throwing out the outliers, and the points that remain will give a more "representative" centroid. You can even repeat this process several times, and the result is kind like peeling an onion. In fact, it's called "convex hull peeling".
|
What's the best way to calculate a 3D (or n-D) centroid?
|
[
"",
"python",
"math",
"3d",
"geometry",
""
] |
How do I parse the first, middle, and last name out of a fullname field with SQL?
I need to try to match up on names that are not a direct match on full name. I'd like to be able to take the full name field and break it up into first, middle and last name.
The data does not include any prefixes or suffixes. The middle name is optional. The data is formatted 'First Middle Last'.
I'm interested in some practical solutions to get me 90% of the way there. As it has been stated, this is a complex problem, so I'll handle special cases individually.
|
Here is a self-contained example, with easily manipulated test data.
With this example, if you have a name with more than three parts, then all the "extra" stuff will get put in the LAST\_NAME field. An exception is made for specific strings that are identified as "titles", such as "DR", "MRS", and "MR".
If the middle name is missing, then you just get FIRST\_NAME and LAST\_NAME (MIDDLE\_NAME will be NULL).
You could smash it into a giant nested blob of SUBSTRINGs, but readability is hard enough as it is when you do this in SQL.
**Edit-- Handle the following special cases:**
**1 - The NAME field is NULL**
**2 - The NAME field contains leading / trailing spaces**
**3 - The NAME field has > 1 consecutive space within the name**
**4 - The NAME field contains ONLY the first name**
**5 - Include the original full name in the final output as a separate column, for readability**
**6 - Handle a specific list of prefixes as a separate "title" column**
```
SELECT
FIRST_NAME.ORIGINAL_INPUT_DATA
,FIRST_NAME.TITLE
,FIRST_NAME.FIRST_NAME
,CASE WHEN 0 = CHARINDEX(' ',FIRST_NAME.REST_OF_NAME)
THEN NULL --no more spaces? assume rest is the last name
ELSE SUBSTRING(
FIRST_NAME.REST_OF_NAME
,1
,CHARINDEX(' ',FIRST_NAME.REST_OF_NAME)-1
)
END AS MIDDLE_NAME
,SUBSTRING(
FIRST_NAME.REST_OF_NAME
,1 + CHARINDEX(' ',FIRST_NAME.REST_OF_NAME)
,LEN(FIRST_NAME.REST_OF_NAME)
) AS LAST_NAME
FROM
(
SELECT
TITLE.TITLE
,CASE WHEN 0 = CHARINDEX(' ',TITLE.REST_OF_NAME)
THEN TITLE.REST_OF_NAME --No space? return the whole thing
ELSE SUBSTRING(
TITLE.REST_OF_NAME
,1
,CHARINDEX(' ',TITLE.REST_OF_NAME)-1
)
END AS FIRST_NAME
,CASE WHEN 0 = CHARINDEX(' ',TITLE.REST_OF_NAME)
THEN NULL --no spaces @ all? then 1st name is all we have
ELSE SUBSTRING(
TITLE.REST_OF_NAME
,CHARINDEX(' ',TITLE.REST_OF_NAME)+1
,LEN(TITLE.REST_OF_NAME)
)
END AS REST_OF_NAME
,TITLE.ORIGINAL_INPUT_DATA
FROM
(
SELECT
--if the first three characters are in this list,
--then pull it as a "title". otherwise return NULL for title.
CASE WHEN SUBSTRING(TEST_DATA.FULL_NAME,1,3) IN ('MR ','MS ','DR ','MRS')
THEN LTRIM(RTRIM(SUBSTRING(TEST_DATA.FULL_NAME,1,3)))
ELSE NULL
END AS TITLE
--if you change the list, don't forget to change it here, too.
--so much for the DRY prinicple...
,CASE WHEN SUBSTRING(TEST_DATA.FULL_NAME,1,3) IN ('MR ','MS ','DR ','MRS')
THEN LTRIM(RTRIM(SUBSTRING(TEST_DATA.FULL_NAME,4,LEN(TEST_DATA.FULL_NAME))))
ELSE LTRIM(RTRIM(TEST_DATA.FULL_NAME))
END AS REST_OF_NAME
,TEST_DATA.ORIGINAL_INPUT_DATA
FROM
(
SELECT
--trim leading & trailing spaces before trying to process
--disallow extra spaces *within* the name
REPLACE(REPLACE(LTRIM(RTRIM(FULL_NAME)),' ',' '),' ',' ') AS FULL_NAME
,FULL_NAME AS ORIGINAL_INPUT_DATA
FROM
(
--if you use this, then replace the following
--block with your actual table
SELECT 'GEORGE W BUSH' AS FULL_NAME
UNION SELECT 'SUSAN B ANTHONY' AS FULL_NAME
UNION SELECT 'ALEXANDER HAMILTON' AS FULL_NAME
UNION SELECT 'OSAMA BIN LADEN JR' AS FULL_NAME
UNION SELECT 'MARTIN J VAN BUREN SENIOR III' AS FULL_NAME
UNION SELECT 'TOMMY' AS FULL_NAME
UNION SELECT 'BILLY' AS FULL_NAME
UNION SELECT NULL AS FULL_NAME
UNION SELECT ' ' AS FULL_NAME
UNION SELECT ' JOHN JACOB SMITH' AS FULL_NAME
UNION SELECT ' DR SANJAY GUPTA' AS FULL_NAME
UNION SELECT 'DR JOHN S HOPKINS' AS FULL_NAME
UNION SELECT ' MRS SUSAN ADAMS' AS FULL_NAME
UNION SELECT ' MS AUGUSTA ADA KING ' AS FULL_NAME
) RAW_DATA
) TEST_DATA
) TITLE
) FIRST_NAME
```
|
Alternative simple way is to use `parsename` :
```
select full_name,
parsename(replace(full_name, ' ', '.'), 3) as FirstName,
parsename(replace(full_name, ' ', '.'), 2) as MiddleName,
parsename(replace(full_name, ' ', '.'), 1) as LastName
from YourTableName
```
[source](https://dba.stackexchange.com/a/42398/83480)
|
SQL: parse the first, middle and last name from a fullname field
|
[
"",
"sql",
"sql-server",
"t-sql",
"parsing",
""
] |
In VB.NET I often `Catch…When`:
```
Try
…
Catch e As ArgumentNullException When e.ParamName.ToUpper() = "SAMPLES"
…
End Try
```
Is there a C# equivalent to `Catch…When`?
I don't want to resort to using an `if` statement inside a `catch` if possible.
|
This functionality was announced for C# 6. It is now possible to write
```
try { … }
catch (MyException e) when (myfilter(e))
{
…
}
```
You can download the preview of [Visual Studio 2015](http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs.aspx) now to check this out, or wait for the official release.
|
There's no equivalent to `Catch…When` in C#. You will really have to resort to an `if` statement inside your `catch`, then rethrow if your condition isn't fulfilled:
```
try
{
…
}
catch (ArgumentNullException e)
{
if ("SAMPLES" == e.ParamName.ToUpper())
{
… // handle exception
}
else
{
throw; // condition not fulfilled, let someone else handle the exception
}
}
```
|
C# equivalent to VB.NET's Catch...When
|
[
"",
"c#",
"vb.net",
"exception",
"vb.net-to-c#",
""
] |
I am making extensive use of `boost:shared_ptr` in my code. In fact, most of the objects that are allocated on the heap are held by a `shared_ptr`. Unfortunately this means that I can't pass `this` into any function that takes a `shared_ptr`. Consider this code:
```
void bar(boost::shared_ptr<Foo> pFoo)
{
...
}
void Foo::someFunction()
{
bar(this);
}
```
There are two problems here. First, this won't compile because the T\* constructor for `shared_ptr` is explicit. Second, if I force it to build with `bar(boost::shared_ptr<Foo>(this))` I will have created a second shared pointer to my object that will eventually lead to a double-delete.
This brings me to my question: Is there any standard pattern for getting a copy of the existing shared pointer you know exists from inside a method on one of those objects? Is using intrusive reference counting my only option here?
|
You can derive from [enable\_shared\_from\_this](http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/enable_shared_from_this.html) and then you can use "shared\_from\_this()" instead of "this" to spawn a shared pointer to your own self object.
Example in the link:
```
#include <boost/enable_shared_from_this.hpp>
class Y: public boost::enable_shared_from_this<Y>
{
public:
shared_ptr<Y> f()
{
return shared_from_this();
}
}
int main()
{
shared_ptr<Y> p(new Y);
shared_ptr<Y> q = p->f();
assert(p == q);
assert(!(p < q || q < p)); // p and q must share ownership
}
```
It's a good idea when spawning threads from a member function to boost::bind to a shared\_from\_this() instead of this. It will ensure that the object is not released.
|
Just use a raw pointer for your function parameter instead of the shared\_ptr. The purpose of a smart pointer is to control the lifetime of the object, but the object lifetime is already guaranteed by C++ scoping rules: it will exist for at least as long as the end of your function. That is, the calling code can't possibly delete the object before your function returns; thus the safety of a "dumb" pointer is guaranteed, as long as you don't try to delete the object inside your function.
The only time you need to pass a shared\_ptr into a function is when you want to pass ownership of the object to the function, or want the function to make a copy of the pointer.
|
Getting a boost::shared_ptr for this
|
[
"",
"c++",
"boost",
""
] |
Is there any easy way to create a class that uses **IFormatProvider** that writes out a user-friendly file-size?
```
public static string GetFileSizeString(string filePath)
{
FileInfo info = new FileInfo(@"c:\windows\notepad.exe");
long size = info.Length;
string sizeString = size.ToString(FileSizeFormatProvider); // This is where the class does its magic...
}
```
It should result in strings formatted something like "*2,5 MB*", "*3,9 GB*", "*670 bytes*" and so on.
|
I use this one, I get it from the web
```
public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter)) return this;
return null;
}
private const string fileSizeFormat = "fs";
private const Decimal OneKiloByte = 1024M;
private const Decimal OneMegaByte = OneKiloByte * 1024M;
private const Decimal OneGigaByte = OneMegaByte * 1024M;
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (format == null || !format.StartsWith(fileSizeFormat))
{
return defaultFormat(format, arg, formatProvider);
}
if (arg is string)
{
return defaultFormat(format, arg, formatProvider);
}
Decimal size;
try
{
size = Convert.ToDecimal(arg);
}
catch (InvalidCastException)
{
return defaultFormat(format, arg, formatProvider);
}
string suffix;
if (size > OneGigaByte)
{
size /= OneGigaByte;
suffix = "GB";
}
else if (size > OneMegaByte)
{
size /= OneMegaByte;
suffix = "MB";
}
else if (size > OneKiloByte)
{
size /= OneKiloByte;
suffix = "kB";
}
else
{
suffix = " B";
}
string precision = format.Substring(2);
if (String.IsNullOrEmpty(precision)) precision = "2";
return String.Format("{0:N" + precision + "}{1}", size, suffix);
}
private static string defaultFormat(string format, object arg, IFormatProvider formatProvider)
{
IFormattable formattableArg = arg as IFormattable;
if (formattableArg != null)
{
return formattableArg.ToString(format, formatProvider);
}
return arg.ToString();
}
}
```
an example of use would be:
```
Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", 100));
Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", 10000));
```
Credits for <http://flimflan.com/blog/FileSizeFormatProvider.aspx>
There is a problem with ToString(), it's expecting a NumberFormatInfo type that implements IFormatProvider but the NumberFormatInfo class is sealed :(
If you're using C# 3.0 you can use an extension method to get the result you want:
```
public static class ExtensionMethods
{
public static string ToFileSize(this long l)
{
return String.Format(new FileSizeFormatProvider(), "{0:fs}", l);
}
}
```
You can use it like this.
```
long l = 100000000;
Console.WriteLine(l.ToFileSize());
```
|
OK I'm not going to wrap it up as a Format provider but rather than reinventing the wheel there's a Win32 api call to format a size string based on supplied bytes that I've used many times in various applications.
```
[DllImport("Shlwapi.dll", CharSet = CharSet.Auto)]
public static extern long StrFormatByteSize( long fileSize, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder buffer, int bufferSize );
```
So I imagine you should be able to put together a provider using that as the core conversion code.
Here's a [link](http://msdn.microsoft.com/en-us/library/bb759974(VS.85).aspx) to the MSDN spec for StrFormatByteSize.
|
File-size format provider
|
[
"",
"c#",
"formatting",
"filesize",
""
] |
What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors:
```
class foo
{
private:
static int i;
};
int foo::i = 0;
```
I'm guessing this is because I can't initialize a private member from outside the class. So what's the best way to do this?
|
The class declaration should be in the header file, or in the source file, if the class is not used in other files.
```
// foo.h
class foo
{
private:
static int i;
};
```
However, the initialization should be in the source file.
```
// foo.cpp
int foo::i = 0;
```
If the initialization is in the header file, then each file that includes the header file will have a definition of the static member. Thus during the link phase, you will get linker errors as the code to initialize the variable will be defined in multiple source files.
The initialization of the `static int i` must be done outside of any function.
**Note:** Matt Curtis: points out that C++ allows the simplification of the above if the static data member is of [const integer type](https://en.cppreference.com/w/cpp/language/types) (*`bool`, `char`, `char8_t` [since C++20], `char16_t`, `char32_t`, `wchar_t`, `short`, `int`, `long`, `long long`, or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants.*). You can then declare and initialize the data member directly inside the class declaration in the header file:
```
class foo
{
private:
static int const i = 42;
};
```
|
For a **variable**:
foo.h:
```
class foo
{
private:
static int i;
};
```
foo.cpp:
```
int foo::i = 0;
```
This is because there can only be one instance of `foo::i` in your program. It's sort of the equivalent of `extern int i` in a header file and `int i` in a source file.
For a **constant** you can put the value straight in the class declaration:
```
class foo
{
private:
static int i;
const static int a = 42;
};
```
|
How to initialize private static data members in a header file
|
[
"",
"c++",
"initialization",
"header-files",
"static-members",
""
] |
How can I disable all table constrains in Oracle with a single command?
This can be either for a single table, a list of tables, or for all tables.
|
It is better to avoid writing out temporary spool files. Use a PL/SQL block. You can run this from SQL\*Plus or put this thing into a package or procedure. The join to USER\_TABLES is there to avoid view constraints.
It's unlikely that you really want to disable all constraints (including NOT NULL, primary keys, etc). You should think about putting constraint\_type in the WHERE clause.
```
BEGIN
FOR c IN
(SELECT c.owner, c.table_name, c.constraint_name
FROM user_constraints c, user_tables t
WHERE c.table_name = t.table_name
AND c.status = 'ENABLED'
AND NOT (t.iot_type IS NOT NULL AND c.constraint_type = 'P')
ORDER BY c.constraint_type DESC)
LOOP
dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" disable constraint ' || c.constraint_name);
END LOOP;
END;
/
```
Enabling the constraints again is a bit tricker - you need to enable primary key constraints before you can reference them in a foreign key constraint. This can be done using an ORDER BY on constraint\_type. 'P' = primary key, 'R' = foreign key.
```
BEGIN
FOR c IN
(SELECT c.owner, c.table_name, c.constraint_name
FROM user_constraints c, user_tables t
WHERE c.table_name = t.table_name
AND c.status = 'DISABLED'
ORDER BY c.constraint_type)
LOOP
dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" enable constraint ' || c.constraint_name);
END LOOP;
END;
/
```
|
To take in count the dependencies between the constraints:
```
SET Serveroutput ON
BEGIN
FOR c IN
(SELECT c.owner,c.table_name,c.constraint_name
FROM user_constraints c,user_tables t
WHERE c.table_name=t.table_name
AND c.status='ENABLED'
ORDER BY c.constraint_type DESC,c.last_change DESC
)
LOOP
FOR D IN
(SELECT P.Table_Name Parent_Table,C1.Table_Name Child_Table,C1.Owner,P.Constraint_Name Parent_Constraint,
c1.constraint_name Child_Constraint
FROM user_constraints p
JOIN user_constraints c1 ON(p.constraint_name=c1.r_constraint_name)
WHERE(p.constraint_type='P'
OR p.constraint_type='U')
AND c1.constraint_type='R'
AND p.table_name=UPPER(c.table_name)
)
LOOP
dbms_output.put_line('. Disable the constraint ' || d.Child_Constraint ||' (on table '||d.owner || '.' ||
d.Child_Table || ')') ;
dbms_utility.exec_ddl_statement('alter table ' || d.owner || '.' ||d.Child_Table || ' disable constraint ' ||
d.Child_Constraint) ;
END LOOP;
END LOOP;
END;
/
```
|
Disable all table constraints in Oracle
|
[
"",
"sql",
"oracle",
""
] |
Since generics were introduced, Class is parametrized, so that List.class produces Class<List>. This is clear.
What I am not able to figure out is how to get a instance of Class of type which is parametrized itself, i.e. Class<List<String>>. Like in this snippet:
```
public class GenTest {
static <T> T instantiate(Class<T> clazz) throws Exception {
return clazz.newInstance();
}
public static void main(String[] args) throws Exception {
// Is there a way to avoid waring on the line below
// without using @SuppressWarnings("unchecked")?
// ArrayList.class is Class<ArrayList>, but I would like to
// pass in Class<ArrayList<String>>
ArrayList<String> l = GenTest.instantiate(ArrayList.class);
}
}
```
I run into variations of this problem quite often and I still don't know, if I just miss something, or if there is really no better way. Thanks for suggestions.
|
The Class class is a run-time representation of a type. Since parametrized types undergo type erasure at runtime, the class object for Class would be the same as for Class<List<Integer>> and Class<List<String>>.
The reason you cannot instantiate them using the .class notation is that this is a special syntax used for class literals. The [Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.8.2) specifically forbids this syntax when the type is parametrized, which is why List<String>.class is not allowed.
|
Classes represent classes loaded by a class loader, which are raw types. To represent a parameterized type, use java.lang.reflect.ParameterizedType.
|
How to get parametrized Class instance
|
[
"",
"java",
"generics",
""
] |
My group is a Perl shop in an organization that is very heterogenous. Although we support the odd Java, PHP, or Python installation, we're using Perl for nearly all of our web applications and systems/data marshalling tasks. All of our boxes are Linux, although we interface with IIS systems as well.
We're coming under some pressure from management to move to Java for at least some of our work. I'd like to use the right tool for the right task, but for our work, and due to our collective experience, Perl seems like the right tool for everything.
My initial thought is to use Java for applications that are open to the organization at large, since there is more Java mindshare *out there* than Perl.
Does anyone have similar experience? If I'm given the choice, what kinds of tasks should we start with applying Java? What kinds of tasks should we insist on sticking with Perl? Does it make any difference? Why or why not?
|
Is there a specific technical reason for switching to Java? Is there something you can do in Java but not Perl? Is there a performance difference? Is some other group/person all about Java and doesn't want to learn Perl?
My experience has been that you should stick with what you know. Your group knows Perl really well. You've had your share of teeth gnashing and some of you have probably attained uber Perl guru status.
So I'd say stick with what you know unless you can think of some good reasons.
|
If your team is going to be supporting the applications, then stick with what you know.
If another team is supporting your apps then you may need to consider Java as it definetly has a greater penetration in today's corporate world.
Management are told that Java is the only way, or "real enterprises use Java", and therefore they think they have to use Java. I know where I work they think that Java is the only language out there, and things like C# are just for 'tactical' projects and not 'strategic' - whatever that means.
You should use the best tool for the job.
|
Java development in a Perl shop: How to select the right tool?
|
[
"",
"java",
"perl",
""
] |
I am trying to copy a file using the following code:
```
File targetFile = new File(targetPath + File.separator + filename);
...
targetFile.createNewFile();
fileInputStream = new FileInputStream(fileToCopy);
fileOutputStream = new FileOutputStream(targetFile);
byte[] buffer = new byte[64*1024];
int i = 0;
while((i = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, i);
}
```
For some users the `targetFile.createNewFile` results in this exception:
```
java.io.IOException: The filename, directory name, or volume label syntax is incorrect
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:850)
```
Filename and directory name seem to be correct. The directory `targetPath` is even checked for existence before the copy code is executed and the filename looks like this: `AB_timestamp.xml`
The user has write permissions to the `targetPath` and can copy the file without problems using the OS.
As I don't have access to a machine this happens on yet and can't reproduce the problem on my own machine I turn to you for hints on the reason for this exception.
|
Try this, as it takes more care of adjusting directory separator characters in the path between targetPath and filename:
```
File targetFile = new File(targetPath, filename);
```
|
This can occur when filename has timestamp with colons, eg. `myfile_HH:mm:ss.csv` Removing colons fixed the issue.
|
What are possible reasons for java.io.IOException: "The filename, directory name, or volume label syntax is incorrect"
|
[
"",
"java",
"exception",
"file-io",
""
] |
I am wondering what security concerns there are to implementing a `PHP evaluator` like this:
```
<?php eval($_POST['codeInput']); %>
```
This is in the context of making a `PHP sandbox` so sanitising against `DB input` etc. isn't a massive issue.
Users destroying the server the file is hosted on is.
I've seen `Ruby simulators` so I was curious what's involved security wise (vague details at least).
---
Thanks all. I'm not even sure on which answer to accept because they are all useful.
[Owen's answer](https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#131911) summarises what I suspected (the server itself would be at risk).
[arin's answer](https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#137019) gives a great example of the potential problems.
[Geoff's answer](https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#137167) and [randy's answer](https://stackoverflow.com/questions/131902/what-are-the-security-concerns-of-evaluating-user-code-in-php#137118) echo the general opinion that you would need to write your own evaluator to achieve simulation type capabilities.
|
could potentially be in really big trouble if you `eval()`'d something like
```
<?php
eval("shell_exec(\"rm -rf {$_SERVER['DOCUMENT_ROOT']}\");");
?>
```
it's an extreme example but it that case your site would just get deleted. hopefully your permissions wouldn't allow it but, it helps illustrate the need for sanitization & checks.
|
don't do that.
they basically have access to anything you can do in PHP (look around the file system, get/set any sort of variables, open connections to other machines to insert code to run, etc...)
|
What are the security concerns of evaluating user code?
|
[
"",
"php",
"security",
""
] |
This snippet works well if I try to write in a user directory but as soon as I try to write in Program Files, it just executes silently and the file has not been copied (no exception). If I try to copy the file in C:\ or in C:\Windows I catch an UnauthorizedAccessException.
Do you know another way to get the permissions to write in that directory or to make it work another way?
Any help greatly appreciated! Thanks
```
using(FileStream fs=File.Open(source, FileMode.Open)){ }
try
{
FileIOPermission fp = new FileIOPermission(FileIOPermissionAccess.Write,
AccessControlActions.Change, "C:\\Program Files\\MyPath");
fp.Demand(); //<-- no exception but file is not copied
File.Copy("C:\\Users\\teebot\\Documents\\File.xml","C:\\Program Files\\MyPath\\File.xml",true);
}
catch(SecurityExceptions)
{
throw(s);
}
catch(UnauthorizedAccessException unauthroizedException)
{
throw unauthroizedException;
}
```
|
If you are running under Vista then the system just redirects writes to the program files folder, this is done so old program that keep their configuration in the program directory will continue to work when the user is not an Admin (or UAC is enabled).
All you have to do is add a manifest to your program that specify the required access level, then the system assume your program is Vista-aware and turns off all those compatibility patches.
You can see an example of a manifest file on my blog at:
<http://www.nbdtech.com/blog/archive/2008/06/16/The-Application-Manifest-Needed-for-XP-and-Vista-Style-File.aspx>
(the focus of the post is on getting the right version of the common controls, but the Vista security declarations are also there)
|
**Don't write in the Program Files folder.**
That's a big no-no, and will especially cause problems when the day comes where your code runs in Vista or on a machine at a company where users only get standard security rather than admin rights. Use the Application Data folder instead.
|
Can't copy file with appropriate permissions using FileIOPermission
|
[
"",
"c#",
"file",
"permissions",
"copy",
""
] |
I'm trying to use boost::signal to implement a callback mechanism, and I'm getting a memory access assert in the boost::signal code on even the most trivial usage of the library. I have simplified it down to this code:
```
#include <boost/signal.hpp>
typedef boost::signal<void (void)> Event;
int main(int argc, char* argv[])
{
Event e;
return 0;
}
```
Thanks!
Edit: This was Boost 1.36.0 compiled with Visual Studio 2008 w/ SP1. Boost::filesystem, like boost::signal also has a library that must be linked in, and it seems to work fine. All the other boost libraries I use are headers-only, I believe.
|
I've tested your code on my system, and it works fine. I think that there's a mismatch between your compiler, and the compiler that your Boost.Signals library is built on. Try to download the Boost source, and compile Boost.Signals using the same compiler as you use for building your code.
Just for my info, what compiler (and version) are you using?
|
I have confirmed this as a problem - Stephan T Lavavej (STL!) at Microsoft [blogged about this](http://blogs.msdn.com/vcblog/archive/2007/02/26/stl-destructor-of-bugs.aspx).
Specifically, he said:
> The general problem is that the linker does not diagnose all One Definition Rule (ODR) violations. Although not impossible, this is a difficult problem to solve, which is why the Standard specifically permits certain ODR violations to go undiagnosed.
>
> I would certainly love for the compiler and linker to have a special mode that would catch all ODR violations at build time, but I recognize that that would be difficult to achieve (and would consume resources that could perhaps be put to even better use, like more conformance). In any event, ODR violations can be avoided without extreme effort by properly structuring your code, so we as programmers can cope with this lack of linker checking.
>
> However, macros that change the functionality of code by being switched on and off are flirting dangerously with the ODR, and the specific problem is that \_SECURE\_SCL and \_HAS\_ITERATOR\_DEBUGGING both do exactly this. At first glance, this might not seem so bad, since you should already have control over which macros are defined project-wide in your build system. However, separately compiled libraries complicate things - if you've built (for example) Boost with \_SECURE\_SCL on, which is the default, your project must not turn \_SECURE\_SCL off. If you're intent on turning \_SECURE\_SCL off in your project, now you have to re-build Boost accordingly. And depending on the separately compiled library in question, that might be difficult (with Boost, according to my understanding, it can be done, I've just never figured out how).
He lists some possible workarounds later on in a comment, but none looked appropriate to this situation. Someone else reported being able to turn off these flags when compiling boost by inserting some defines in **boost/config/compiler/visualc.hpp**, but this did **NOT** work for me. However inserting the following line **VERBATIM** in **tools/build/v2/user-config.jam** did the trick. Note that the whitespace is important to boost jam.
```
using msvc : 9.0 : : <cxxflags>-D _SECURE_SCL=0 <cxxflags>-D _HAS_ITERATOR_DEBUGGING=0 ;
```
|
Boost::signal memory access error
|
[
"",
"c++",
"boost-signals",
""
] |
On an ASP.NET website, are static classes unique to each web request, or are they instantiated whenever needed and GCed whenever the GC decides to disposed of them?
The reason I ask is because I've written some static classes before in C# and the behavior is different than I would have expected. I would have expected static classes to be unique to each request, but it doesn't seem like that is the case.
If they are not unique to each request, is there a way to allow them to be?
**UPDATE:**
The answer driis gave me was exactly what I needed. I was already using a singleton class, however it was using a static instance and therefore was being shared between requests even if the users were different which in this case was a bad thing. Using `HttpContext.Current.Items` solves my problem perfectly. For anyone who stumbles upon this question in the future, here is my implementation, simplified and shortened so that it easy to understand the pattern:
```
using System.Collections;
using System.Web;
public class GloballyAccessibleClass
{
private GloballyAccessibleClass() { }
public static GloballyAccessibleClass Instance
{
get
{
IDictionary items = HttpContext.Current.Items;
if(!items.Contains("TheInstance"))
{
items["TheInstance"] = new GloballyAccessibleClass();
}
return items["TheInstance"] as GloballyAccessibleClass;
}
}
}
```
|
Your static classes and static instance fields are shared between all requests to the application, and has the same lifetime as the application domain. Therefore, you should be careful when using static instances, since you might have synchronization issues and the like. Also bear in mind, that static instances will not be GC'ed before the application pool is recycled, and therefore everything that is referenced by the static instance, will not be GC'ed. This can lead to memory usage problems.
If you need an instance with the same lifetime as a request, I would suggest to use the `HttpContext.Current.Items` collection. This is by design meant to be a place to store stuff that you need througout the request. For nicer design and readability, you can use the Singleton pattern to help you manage these items. Simply create a Singleton class that stores its instance in `HttpContext.Current.Items`. (In my common library for ASP.NET, I have a generic SingletonRequest class for this purpose).
|
Static members have a scope of the current worker process only, so it has nothing to do with requests, because different requests may or may not be handled by the same worker process.
* In order to share data with a specific user and across requests, use HttpContext.Current.Session.
* In order to share data within a specific request, use HttpContext.Current.Items.
* In order to share data across the entire application, either write a mechanism for that, or configure IIS to work with a single process and write a singleton / use Application.
By the way, the default number of worker processes is 1, so this is why the web is full of people thinking that static members have a scope of the entire application.
|
Are static class instances unique to a request or a server in ASP.NET?
|
[
"",
"c#",
"asp.net",
"static",
""
] |
I have a database issue that i currently cannot wrap my head around with an easy solution. In my db I have a table that stores event values.. 0's and 1's with a timestamp. Issue being that it is possible for there to be the same event to occur twice as a business rule. Like below
* '2008-09-22 16:28:14.133', 0
* '2008-09-22 16:28:35.233', 1
* '2008-09-22 16:29:16.353', 1
* '2008-09-22 16:31:37.273', 0
* '2008-09-22 16:35:43.134', 0
* '2008-09-22 16:36:39.633', 1
* '2008-09-22 16:41:40.733', 0
in real life these events are cycled and I’m trying to query over to get the cycles of these but I need to ignore the duplicate values ( 1,1 ) the current solution is using a SQL cursor to loop each and throw out the value if the previous was the same. I’ve considered using a trigger on the insert to clean up in a post processed table but I can’t think of an easy solution to do this set based.
Any ideas or suggestions?
Thanks
|
This uses a SQL Server Common Table Expression, but it can be inlined, with table t with columns dt and cyclestate:
```
;WITH Firsts AS (
SELECT t1.dt
,MIN(t2.dt) AS Prevdt
FROM t AS t1
INNER JOIN t AS t2
ON t1.dt < t2.dt
AND t2.cyclestate <> t1.cyclestate
GROUP BY t1.dt
)
SELECT MIN(t1.dt) AS dt_start
,t2.dt AS dt_end
FROM t AS t1
INNER JOIN Firsts
ON t1.dt = Firsts.dt
INNER JOIN t AS t2
ON t2.dt = Firsts.Prevdt
AND t1.cyclestate <> t2.cyclestate
GROUP BY t2.dt
,t2.cyclestate
HAVING MIN(t1.cyclestate) = 0
```
|
(preface.......i've only done this in oracle, but I'm pretty sure if the db supports triggers it's all possible)
Have a before insert trigger that selects the row with the max timestamp value. If that row's value is the same as the one you wish to insert, ignore it.
This should keep them all in a correct state.
Now, if you need both sets of states stored, the trigger can always insert on the all-inclusive table, but do the lookup and insert on the 'filtered' table only when the value changes.
|
Filtering out duplicate values at runtime in a sql database - set based
|
[
"",
"sql",
"filtered-lookup",
""
] |
Greetings!
I am trying to check directory write-permissions from within a Windows MFC/ATL program using C++. My first guess is to use the C-standard \_access function, e.g.:
```
if (_access("C:\mydir", 2) == -1)
// Directory is not writable.
```
But apparently on Windows 2000 and XP, \_access can't determine directory permissions. (i.e. the Security tab in the Properties dialog when you right-click on a directory in Explorer) So, is there an elegant way to determine a directory's write-permissions in Windows 2000/XP using any of the Windows C++ libraries? If so, how?
Thanks
Evan
|
You can call CreateFile with GENERIC\_WRITE access to check this.
<http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx>
It's not a C++ library but it still counts as elegant because it directly does what you want...
|
Use sec api.
You can ask on Adv. Win32 api newsgroup :
news://194.177.96.26/comp.os.ms-windows.programmer.win32
where it has often been discussed (C/C++ code)
|
Code for checking write-permissions for directories in Win2K/XP
|
[
"",
"c++",
"windows",
"security",
"permissions",
"atl",
""
] |
Slashdot has a little widget that allows you to tweak your comment threshold to filter out down-modded comments. It will be in one place if you scroll to the top of the page, and as you scroll down, at some point, where its original home is about to scroll off the page, it will switch to fixed position, and stay on your screen. (To see an example, click [here](http://news.slashdot.org/news/08/09/10/2257242.shtml).)
My question is, how can I accomplish the same effect of having a menu be in one place when scrolled up, and switch to fixed position as the user scrolls down? I know this will involve a combination of CSS and javascript. I'm not necessarily looking for a full example of working code, but what steps will my code need to go through?
|
Okay, I figured it out. I will post it here in case it help anyone else. This solution uses prototype, and an internal library that gives me the registerEvent, getElementX and getElementY functions, which do what you would think.
```
var MenuManager = Class.create({
initialize: function initialize(menuElt) {
this.menu = $(menuElt);
this.homePosn = { x: getElementX(this.menu), y: getElementY(this.menu) };
registerEvent(document, 'scroll', this.handleScroll.bind(this));
this.handleScroll();
},
handleScroll: function handleScroll() {
this.scrollOffset = document.viewport.getScrollOffsets().top;
if (this.scrollOffset > this.homePosn.y) {
this.menu.style.position = 'fixed';
this.menu.style.top = 0;
this.menu.style.left = this.homePosn.x;
} else {
this.menu.style.position = 'absolute';
this.menu.style.top = null;
this.menu.style.left = null;
}
}
});
```
Just call the constructor with the id of your menu, and the class will take it from there.
|
Thanks for the effort of sharing this code.
I made some small changes to make it work with the current release of Prototype.
```
var TableHeaderManager = Class.create({
initialize: function initialize(headerElt) {
this.tableHeader = $(headerElt);
this.homePosn = { x: this.tableHeader.cumulativeOffset()[0], y: this.tableHeader.cumulativeOffset()[1] };
Event.observe(window, 'scroll', this.handleScroll.bind(this));
this.handleScroll();
},
handleScroll: function handleScroll() {
this.scrollOffset = document.viewport.getScrollOffsets().top;
if (this.scrollOffset > this.homePosn.y) {
this.tableHeader.style.position = 'fixed';
this.tableHeader.style.top = 0;
this.tableHeader.style.left = this.homePosn.x;
} else {
this.tableHeader.style.position = 'absolute';
this.tableHeader.style.top = null;
this.tableHeader.style.left = null;
}
}
});
```
|
How can I get a fixed-position menu like slashdot's comment filtration menu
|
[
"",
"javascript",
"css",
""
] |
Sometimes when using eclipse it loses references to the JRE.
i.e. It cannot find classes like Object or Arraylist.
Some projects report a problem while others don't and they both use the same JRE.
I have found that if you switch the installed JRE to another and then back again to the one you want to use, it will then work again
Is there a better way to stop it doing this?
EDIT: Reloading Eclipse doesn't solve the problem
|
I may have a resolution for this. Eclipse was losing the JRE references on many of my Java projects almost daily, and restarting or starting with -clean wasn't helping. I realised that it is clearly a classloader issue of some kind, so what I did was to open the ".classpath" file of each project in the editor and manually move the JRE reference classpathentry line to be the first entry in the file, in the hope that it would load the JRE before any other classes which might be affecting it's ability to load successfully.
Since doing this, the problem has not reoccurred.
I think the files starting with a "." are hidden by filter in the package explorer on a default eclipse install, so you may need to disable the ".\* Resources" filter to be able to open the ".classpath" file.
|
The JRE reference in your project is stored using the name you give it in the Installed JREs preference page. Change the name and you break the reference. Just pick names you can keep reusing when switching JREs, or select the workspace default as the JRE for the project.
|
How to stop Eclipse 3.4 losing reference to the JRE in projects
|
[
"",
"java",
"eclipse",
"eclipse-3.4",
"ganymede",
""
] |
I've just started using Java's enums in my own projects (I have to use JDK 1.4 at work) and I am confused as to the best practice of using JavaDoc for an enum.
I have found that this method works, but the resultant code is a little unrefined:
```
/**
* Doc for enum
*/
public enum Something {
/**
* First thing
*/
FIRST_THING,
/**
* Second thing
*/
SECOND_THING;
//could continue with more
}
```
Is there any way I could break up the enum declarations on their own lines without chaining them by commas, or is this the best approach for using JavaDoc for an enum?
|
To answer the first part of your question, you do have to separate each enum value with a comma. As far as I know, there's no way around that.
Personally I don't have a problem with the code the way you've presented it. Seems like a perfectly reasonable way to document an enum to me.
|
As Mike mentioned, you do have to separate the enum values with commas, and they have to be the first things listed in the enum declaration (instance variables, constants, constructors and methods may follow).
I think the best way to document enums is similar to regular classes: the enum type gets a description of the function and role of the enum as a whole ("`Something values are used to indicate which mode of operation a client wishes...`") and each enum value gets a Javadoc description of its purpose and function ("`FIRST_THING indicates that the operation should evaluate the first argument first..`").
If the enum value descriptions are short you might want to put them on one line as `/** Evaluate first argument first. */`, but I recommend keeping each enum value on its own line. Most IDEs can be configured to format them this way automatically.
|
What is the best way to use JavaDoc to document a Java enum?
|
[
"",
"java",
"enums",
"javadoc",
""
] |
Let's say I have an existing trivial XML file named 'MyData.xml' that contains the following:
```
<?xml version="1.0" encoding="utf-8" ?>
<myElement>foo</myElement>
```
I want to change the text value of 'foo' to 'bar' resulting in the following:
```
<?xml version="1.0" encoding="utf-8" ?>
<myElement>bar</myElement>
```
Once I am done, I want to save the changes.
What is the easiest and simplest way to accomplish all this?
|
Use Python's [minidom](http://docs.python.org/library/xml.dom.minidom.html)
Basically you will take the following steps:
1. Read XML data into DOM object
2. Use DOM methods to modify the document
3. Save new DOM object to new XML document
The python spec should hold your hand rather nicely though this process.
|
For quick, non-critical XML manipulations, i really like [P4X](http://ponderer.org/p4x). It let's you write like this:
```
import p4x
doc = p4x.P4X (open(file).read)
doc.myElement = 'bar'
```
|
What is the best way to change text contained in an XML file using Python?
|
[
"",
"python",
"xml",
"text",
""
] |
I've downloaded the IKVM sources (<http://www.ikvm.net/>) from <http://sourceforge.net/cvs/?group_id=69637>
Now I'm trying to get it to build in Visual Studio 2008 and am stuck. Does anyone know of documentation of how to build the thing, or could even give me pointers?
I've tried opening the ikvm8.sln, which opens all the projects, but trying to build the solution leads to a bunch of "type or namespace could not be found" errors.
As you can probably guess I'm no Visual Studio expert, but rather am used to working with Java in Eclipse.
So again, I'm looking for either: step-by-step instructions or a link to documentation on how to build IKVM in Visual Studio.
Let me know if you need any more info. Thanks for any help!
**Edit:** I've also tried a manual "MsBuild.exe IKVM8.sln", but also get a bunch of:
```
JniInterface.cs(30,12): error CS0234: The type or namespace name 'Internal' does not exist in the namespace 'IKVM' (a
re you missing an assembly reference?)
JniInterface.cs(175,38): error CS0246: The type or namespace name 'ClassLoaderWrapper' could not be found (are you mi
ssing a using directive or an assembly reference?)
JniInterface.cs(175,13): error CS0246: The type or namespace name 'ClassLoaderWrapper' could not be found (are you mi
ssing a using directive or an assembly reference?)
```
**Edit #2**: I noticed a "ikvm.build" file so I downloaded and ran nant on the folder, which got me a step further. A few things start to build successfully, unfortunately I now get the following error:
ikvm-native-win32:
```
[mkdir] Creating directory 'C:\Documents and Settings\...\My Documents\ikvm\ikvm\native\Release'.
[cl] Compiling 2 files to 'C:\Documents and Settings\...\My Documents\ikvm\ikvm\native\Release'.
BUILD FAILED
C:\Documents and Settings\...\My Documents\ikvm\ikvm\native\native.build(17,10):
'cl' failed to start.
The system cannot find the file specified
Total time: 0.2 seconds.
```
**Edit #3**: OK solved that by putting `cl.exe` in the path, still getting other errors though. ***Note this is all for building it on the console e.g. with Nant. Is there no way to get it to build in Visual Studio? That would be sad...***
**Edit #4**: Next step was installing GNU classpath 0.95, and now it looks like I need a specific OpenJDK installation... Linux AMD64?!
```
[exec] javac: file not found: ..\..\openjdk6-b12\control\build\linux-amd64\gensrc\com\sun\accessibility\internal\resources\accessibility.java
[exec] Usage: javac <options> <source files>
[exec] use -help for a list of possible options
```
**Edit #5**: Got an answer from the author. See below or at <http://weblog.ikvm.net/CommentView.aspx?guid=7e91b51d-6f84-4485-b61f-ea9e068a5fcf> Let's see if it works...
**Edit #6** As I feared, next problem: "cannot open windows.h", see separate question [here](https://stackoverflow.com/questions/80788/fatal-error-c1083-cannot-open-include-file-windowsh-no-such-file-or-directory).
**Final Edit: Found Solution!** After getting the Platform SDK folders in the Lib and Path environment variables, the solution I described below worked for me.
|
OK just got the following reply from the author: <http://weblog.ikvm.net/CommentView.aspx?guid=7e91b51d-6f84-4485-b61f-ea9e068a5fcf>
> If you want to build from cvs, you're on your own. However, you can more easily build from source if you use an official release.
>
> If you download ikvm-0.36.0.11.zip, classpath-0.95-stripped.zip and openjdk-b13-stripped.zip from SourceForge (the last two are under the ikvm 0.36.0.5 release) you have all the sources that are needed.
>
> Now you'll have to open a Visual Studio 2008 Command Prompt (i.e. one that has cl.exe and peverify in the path).
>
> Then in the ikvm root directory, do a "nant clean" followed by "nant". That should build the whole project. After you done that, you should be able to build in Visual Studio (debug target only), but you may need to repair the assembly references in the projects (unless you have ikvm installed in c:\ikvm).
>
> Regards,
> Jeroen
**Edit**: After making sure the Platform SDK folders were in the Path and Lib environment variables, this worked for me. Thanks, Jeroen!
|
I don't know that this would do it for you but can you try building from the command line?
msbuild \_\_\_\_\_\_\_\_
I think that's how I built the application due to the same issues.
|
How to get IKVM to build in Visual Studio 2008?
|
[
"",
"c#",
"visual-studio-2008",
"compiler-errors",
"ikvm",
""
] |
Can anyone recommend a good .NET based lexical analyser, preferably written in C#?
|
ANTLR has a [C# target](http://www.antlr.org/wiki/display/ANTLR3/Antlr+3+CSharp+Target)
|
Download the Visual Studio SDK; it includes a managed parser/lexer generator.
(Edit: It was written on my university campus, apparantly :D)
|
Recommendations for a good C#/ .NET based lexical analyser
|
[
"",
"c#",
"lexical-analysis",
""
] |
When I want to validate my XML docuemnts against a schema in my server-side Java, I use the built-in JRE Xerces implementation and javax.xml.validation.Schema. It works fine, but when validation fails, Xerces gives error messages that are very close to useless, for example:
```
cvc-minLength-valid: Value '' with length = '0' is not facet-valid with respect to minLength '1' for type 'PopulatedStringType'
```
These can take an age to diagnose and track down to the particular part of the XML document that fails validation, and all because of a poor error message.
So my question is, do you use an alternative means of validating XML against Schema, that gives a more useful output on validation failure?
Please not that this is server-side Java, so please don't say "use XML Spy" or similar.
|
In your handler for the validation, you should receive a SAXParseException with that message, as well as the [column number and the line number](http://xerces.apache.org/xerces2-j/javadocs/api/org/xml/sax/SAXParseException.html#method_summary) in the XML file. Isnt't it the case?
|
We use [Castor](http://www.castor.org).
> Castor is an Open Source data binding framework for Java[tm]. It's the shortest path between Java objects, XML documents and relational tables. Castor provides Java-to-XML binding, Java-to-SQL persistence, and more.
|
What do you use for validation against XML schema?
|
[
"",
"java",
"validation",
"xsd",
""
] |
Some ways to iterate through the characters of a string in Java are:
1. Using `StringTokenizer`?
2. Converting the `String` to a `char[]` and iterating over that.
What is the easiest/best/most correct way to iterate?
|
I use a for loop to iterate the string and use `charAt()` to get each character to examine it. Since the String is implemented with an array, the `charAt()` method is a constant time operation.
```
String s = "...stuff...";
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
//Process char
}
```
That's what I would do. It seems the easiest to me.
As far as correctness goes, I don't believe that exists here. It is all based on your personal style.
|
Two options
```
for(int i = 0, n = s.length() ; i < n ; i++) {
char c = s.charAt(i);
}
```
or
```
for(char c : s.toCharArray()) {
// process c
}
```
The first is probably faster, then 2nd is probably more readable.
|
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
|
[
"",
"java",
"string",
"iteration",
"character",
"tokenize",
""
] |
I'm failing to understand exactly what the IF statement is doing, from what I can see it is checking if the variable `x` is equal to the int `0`. If this is `true` the ABSOLUTE value of the variable `y` is returned... this is when I lose the plot, why would the return statement then go on to include `<= ESPILON`? Surely this means less than or equal to the value of epsilon? if so how is that working? If it doesn't mean that then what does it mean?
(JAVA CODE)
```
final double EPSILON = 1E-14;
if (x == 0)
return Math.abs(y) <= EPSILON;
```
|
Floating-point math is by its nature inaccurate, so rather than testing for equivalence (which is always a bad idea), instead the developer has chosen a small number (1x10^-14 in this case) as the acceptable tolerance for proximity to zero. The return statement returns a comparison, so what this will do is take the absolute value of y, and return true if and only if it is sufficiently close to zero, where sufficiently close is defined by EPSILON.
|
It returns true if the absolute value of y is <= EPSILON, and false otherwise. The <= is evaluated before the return statement. This code is equivalent:
```
if(x == 0)
{
boolean ret = Math.abs(y) <= EPSILON;
return ret;
}
```
The code isn't simply read from left to right. A simpler example is
```
int x = 3 + 4 * 5;
```
After evaluating this, x is 23, not 35. The evaluation is 3 + (4\*5), not (3+4)\*5, because the \* has a higher precedence than the +. The return statement in the original example has a very low precedence. All operators like +, -, <, >= are evaluated before it.
|
Confusing return statement
|
[
"",
"java",
"floating-point",
"operator-precedence",
""
] |
.NET has a lot of complex data structures. Unfortunately, some of them are quite similar and I'm not always sure when to use one and when to use another. Most of my C# and VB books talk about them to a certain extent, but they never really go into any real detail.
What's the difference between Array, ArrayList, List, Hashtable, Dictionary, SortedList, and SortedDictionary?
Which ones are enumerable (IList -- can do 'foreach' loops)? Which ones use key/value pairs (IDict)?
What about memory footprint? Insertion speed? Retrieval speed?
Are there any other data structures worth mentioning?
I'm still searching for more details on memory usage and speed (Big-O notation)
|
Off the top of my head:
* `Array`\* - represents an old-school memory array - kind of like a alias for a normal `type[]` array. Can enumerate. Can't grow automatically. I would assume very fast insert and retrival speed.
* `ArrayList` - automatically growing array. Adds more overhead. Can enum., probably slower than a normal array but still pretty fast. These are used a lot in .NET
* `List` - one of my favs - can be used with generics, so you can have a strongly typed array, e.g. `List<string>`. Other than that, acts very much like `ArrayList`
* `Hashtable` - plain old hashtable. O(1) to O(n) worst case. Can enumerate the value and keys properties, and do key/val pairs
* `Dictionary` - same as above only strongly typed via generics, such as `Dictionary<string, string>`
* `SortedList` - a sorted generic list. Slowed on insertion since it has to figure out where to put things. Can enum., probably the same on retrieval since it doesn't have to resort, but deletion will be slower than a plain old list.
I tend to use `List` and `Dictionary` all the time - once you start using them strongly typed with generics, its really hard to go back to the standard non-generic ones.
There are lots of other data structures too - there's `KeyValuePair` which you can use to do some interesting things, there's a `SortedDictionary` which can be useful as well.
|
**If at all possible, use generics.** This includes:
* List instead of ArrayList
* Dictionary instead of HashTable
|
.Net Data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?
|
[
"",
"c#",
".net",
"vb.net",
"arrays",
"data-structures",
""
] |
I'm experiencing what I believe is a circular dependency issue with my PHP application. Please let me know if this is incorrect. Here is the situation:
Two classes, LogManager and DBSession.
DBSession is used to interact with the database, and LogManager is used to log to files. Both are widely used in my application. When you create an instance of DBSession, you must give it an instance of LogManager via a constructor parameter. This because DBSession will sometimes log information to a file, and will use the LogManager instance to do this.
Now, I wanted to extend LogManager so that it could also log to a database table, rather than a text file. Naturally, my preference is to re-use existing classes, but I soon realized this brought about an interesting situation.
DBSession already requires an instance of LogManager for construction. If I want to re-use the DBSession class in LogManager, it will now require an instance of DBSession. How can I satisfy both demands? Clearly, something must be wrong with my approach.
How would you suggest I fix this?
Thanks in advance, guys.
|
Don't extend LogManager, let it be an aggregate type. And delay the choice of where you want to log, i.e.:
```
$logManager = new LogManager();
$dbSession = new DbSession($logManager);
$logManager->add(new FileLog($filename) );
$logManager->add(new DBLog($dbSession) );
```
Where of course FileLog and DBLog share a common interface.
This is an application of the Observer pattern, where add() is the "subscribe" operation, and FileLog/DBLog are the observers of logging events.
(In this way you could also save logs in many places.)
**Owen edit**: adjusted to php syntax.
|
One of these objects doesn't actually need the other: you guessed it, it's the DBSession. Modify that object so that the logger can be attached to it after construction.
|
Possible circular dependency issue with PHP application
|
[
"",
"php",
"oop",
"dependencies",
"instantiation",
"circular-dependency",
""
] |
In Python, you can do this:
```
print "Hi! I'm %(name)s, and I'm %(age)d years old." % ({"name":"Brian","age":30})
```
What's the closest, simplest Ruby idiom to replicate this behavior? (No monkeypatching the String class, please.)
One of the really excellent benefits of this is that you can store the pre-processed string in a variable and use it as a "template", like so:
```
template = "Hi! I'm %(name)s, and I'm %(age)d years old."
def greet(template,name,age):
print template % ({"name":name,"age":age})
```
This is obviously a trivial example, but there is a lot of utility in being able to store such a string for later use. Ruby's `"Hi! I'm #{name}"` convention is cursorily similar, but the immediate evaluation makes it less versatile.
|
You can also use
```
printf "1: %<key1>s 2: %<key2>s\n", {:key1 => "value1", :key2 => "value2"}
```
or
```
data = {:key1 => "value1", :key2 => "value2"}
printf "1: %<key1>s 2: %<key2>s\n", data
```
or (this needs ruby 1.9, for the other examples I'm not sure)
```
data = {key1: "value1", key2: "value2"}
printf "1: %<key1>s 2: %<key2>s\n", data
```
This prints
```
1: value1 2: value2
```
Important restriction: The used keys of the hash (*data* in my example) must be symbols.
---
A remark on the example above:
`printf` takes one format string and optional parameters. But there is also a `String#%`-method.
The following four calls have all the same result:
```
printf "1: %<key1>s 2: %<key2>s\n" , {:key1 => "value1", :key2 => "value2"}
printf "1: %<key1>s 2: %<key2>s\n" % {:key1 => "value1", :key2 => "value2"}
print "1: %<key1>s 2: %<key2>s\n" % {:key1 => "value1", :key2 => "value2"}
puts "1: %<key1>s 2: %<key2>s" % {:key1 => "value1", :key2 => "value2"}
```
The second version uses first the `String#%`-method and sends the result to `printf`.
|
you do it like this:
```
values = {:hello => 'world', :world => 'hello'}
puts "%{world} %{hello}" % values
```
Read this for more info:
<http://ruby.runpaint.org/strings#sprintf-hash>
If you need something more sophisticated, read about ERB, and google template engines.
If you need to generate web pages, emails etc. you'll find that using template engines is a more robust solution.
|
How do I emulate Python's named printf parameters in Ruby?
|
[
"",
"python",
"ruby",
"string",
"printf",
""
] |
I've inherited a mobile app which sends auth credentials (userid/password) in the clear.
I'd imagine that I have 2 choices:
a) use TLS.
b) write my own auth protocol.
If I choose (b) what are the key guidelines that I must follow to make it it secure.
e.g. how to avoid replay attacks, encryption strategies.
|
For both *"you can't get sued for it"* and *"reasonably protected"* definitions of 'safe', for a mobile application, you can assume that the line is secure vs man-in-the-middle attacks and wide open to eavesdropping. SSL/TLS sounds the easiest way to go, but this might depend on your carrier and target phones.
If you can't make TLS work and you need to roll your own, use [Diffie-Hellman](http://en.wikipedia.org/wiki/Diffie-Hellman) key exchange and established crypto library ([Legion of the Bouncy Castle](http://www.bouncycastle.org/latest_releases.html) have a jightweight implementation that is J2ME compliant.)
|
If you use b), the key guidelines are: Don't. If you want it secure, that is.
Try to stick with a).
|
Searching for a safe way to do authentication from a mobile app
|
[
"",
"java",
"security",
"mobile",
""
] |
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GenericCount
{
class Program
{
static int Count1<T>(T a) where T : IEnumerable<T>
{
return a.Count();
}
static void Main(string[] args)
{
List<string> mystring = new List<string>()
{
"rob","tx"
};
int count = Count1<List<string>>(mystring);******
Console.WriteLine(count.ToString());
}
}
}
```
What do I have to change in the above indicated line of code to make it work. I am just trying to pass either List or array in order to get the count.
|
You want this
```
static int Count1<T>(IEnumerable<T> a)
{
return a.Count();
}
```
|
Your generic constraint is wrong. You cannot enforce it to implement IEnumerabl<T>
|
Generic method call
|
[
"",
"c#",
"generics",
""
] |
I am starting my first independent for profit venture. I am having a hard time deciding what language to use. I want to write my app in Perl, but I don't think it will be simple enough to compile. If I don't write it in Perl I will write it in C++.
The application will have many features, including [wxwidgets](http://www.wxwidgets.org/) interface, Deal with SDL, timers, some threading, and audio processing. The program itself will be somewhat complex, but not terribly large.
So my question's are:
1. Can PAR, Perl2exe, or equivalent compile more than a basic test cases?
2. Speed, and compilation aside why should I use C++ over Perl?
---
Edit:
Some of my project specifications.
* Multi Platform. I am expecting 50% or more of my users to own macs, with Most of the rest being Windows users. If possible I also want to support Linux since It is my everyday operating system.
* Since it's multi Platform I need a unified GUI creation tool. It needs to be able to use basic types, and allow me to create custom event handlers, and custom GUI objects.
* It needs audio processing. Read and play, wav's and/or mp3's. Also I will be using some custom algorithms to determine special properties of the audio files; things like tempo, patterns, and so on.
* I would like but don't require SDL/OpenGL support.
Everything else is pretty mundane. Some different classes and containers. A few custom GUI controls.
|
Why not use a hybrid of both? It's generally the way a lot of development is going these days.
I'd suggest a Lua/C++ or a Python/C++ combo (I'm not sure how well a Perl/C++ combo works, but that may be a good option too).
Personally I've done a bunch with the Lua/C++ combo and it's pretty fantastic.
|
I'm both a C++ and Perl programmer. C++ is a nice language, but whenever I have the choice, I go with Perl since development simply proceeds so much more quickly.
A couple of comments:
1. PAR, perlapp, and perl2exe are not compilers. They are packagers. There is no Perl compiler except perl itself. If you want some form of bytecode form of Perl code, you'll have to wait for Perl 6 on Parrot.
2. I have used PAR to package an application with a total of about 500k SLOC, not including perl itself. It worked fine, ran the same speed as perl itself, but startup was slower. This was 2005. Since then, the startup performance has improved significantly if you install the Archive::Unzip::Burst module on the development machine where you package the program. I have successfully used PAR for various applications varying in size from tiny to the aforementioned 500k lines. If you need help with PAR, there's an active and friendly mailing list. Just do us and yourself the favour of not chiming in with "OMG, nothing works, help me, kthx!". People do that all the time (and sometimes still get help). :)
3. Perl's threading isn't great. Check whether something like POE fits your bill instead. I'm a threads.pm user, but I'd rather not be. With appropriate apologies to the hard-working maintainer, Jerry D. Hedden.
4. wxPerl is in a pretty good shape and there's a community around it. Naturally, since wxWidgets is C++, it's always a tad bit more current and complete.
5. SDL Perl is a straight wrapper around the library. The (little) documentation assumes you already know it. In my experience, reading docs for a library in a different language can be a bit of a hassle.
6. Timers are fine in perl: [Time::HiRes](http://search.cpan.org/perldoc?Time::HiRes)
7. Portability is hard. More so in C++ than in Perl, but it really always comes down to discipline and being able to test on many platforms.
8. For Perl on Windows, make sure you check out Strawberry Perl.
|
New project: I am having troubles picking a language to use
|
[
"",
"c++",
"perl",
"wxwidgets",
"packaging",
""
] |
Suppose I have a set of values, stored in a std::set:
{1, 2, 6, 8}
and I have a search key, say, 3. I want to put 3 into a function and get the first value greater than or equal to 3, in this case I would want to get 6.
The find() function provided in map/set/multimap/and set will, of course, return the end iterator for this case. Is there a similar function to find that would return 6 in this case?
|
Yes: `upper_bound(X)` returns an iterator pointing to the first element greater than `X`. There is also a `lower_bound(X)` function which returns an iterator pointing to the first element not less than `X`. Thus, all of the elements in the half-open interval `[lower_bound(X), upper_bound(X))` will be equal to X.
|
You want the [upper\_bound](http://www.sgi.com/tech/stl/upper_bound.html) function.
```
map<int, int> mymap = { 1,2,6,8 };
map<int,int>::iterator i = mymap.upper_bound(3); // returns an iterator to the '6' element.
```
|
With a STL map/set/multiset/multimap, How to find the first value greater than or equal to the search key?
|
[
"",
"c++",
"stl",
"containers",
""
] |
I have some c(++) code that uses sprintf to convert a uint\_64 to a string. This needs to be portable to both linux and Solaris.
On linux we use %ju, but there does not appear to be any equivalent on Solaris. The closest I can find is %lu, but this produces incorrect output. Some sample code:
```
#include <stdio.h>
#include <sys/types.h>
#ifdef SunOS
typedef uint64_t u_int64_t;
#endif
int main(int argc, char **argv) {
u_int64_t val = 123456789123L;
#ifdef SunOS
printf("%lu\n", val);
#else
printf("%ju\n", val);
#endif
}
```
On linux, the output is as expected; on Solaris 9 (don't ask), it's "28"
What can I use?
|
If you have have inttypes.h available you can use the macros it provides:
```
printf( "%" PRIu64 "\n", val);
```
Not pretty (I seem to be saying that a lot recently), but it works.
|
On a C99 compliant system:
```
#include <inttypes.h>
uint64_t big = ...;
printf("%" PRIu64 "\n", big);
```
See section 7.8 of the C99 standard.
The specifiers are {PRI,SCN}[diouxX]{N,LEASTN,MAX,FASTN,PTR}
Where PRI is for the printf() family, SCN is for the scanf() family, d and i for signed integral types; o,u,x,X are for unsigned integral types as octal, decimal, hex, and Hex; N is one of the supported widths; LEAST and FAST correspond to those modifiers; PTR is for intptr\_t; and MAX is for intmax\_t.
|
printf + uint_64 on Solaris 9?
|
[
"",
"c++",
"c",
"printf",
""
] |
I'm stuck trying to create a dynamic linq extension method that returns a string in JSON format - I'm using System.Linq.Dynamic and Newtonsoft.Json and I can't get the Linq.Dynamic to parse the "cell=new object[]" part. Perhaps too complex? Any ideas? :
**My Main method:**
```
static void Main(string[] args)
{
NorthwindDataContext db = new NorthwindDataContext();
var query = db.Customers;
string json = JSonify<Customer>
.GetJsonTable(
query,
2,
10,
"CustomerID"
,
new string[]
{
"CustomerID",
"CompanyName",
"City",
"Country",
"Orders.Count"
});
Console.WriteLine(json);
}
```
**JSonify class**
```
public static class JSonify<T>
{
public static string GetJsonTable(
this IQueryable<T> query,
int pageNumber,
int pageSize,
string IDColumnName,
string[] columnNames)
{
string selectItems =
String.Format(@"
new
{
{{0}} as ID,
cell = new object[]{{{1}}}
}",
IDColumnName,
String.Join(",", columnNames));
var items = new
{
page = pageNumber,
total = query.Count(),
rows =
query
.Select(selectItems)
.Skip(pageNumber * pageSize)
.Take(pageSize)
};
return JavaScriptConvert.SerializeObject(items);
// Should produce this result:
// {
// "page":2,
// "total":91,
// "rows":
// [
// {"ID":"FAMIA","cell":["FAMIA","Familia Arquibaldo","Sao Paulo","Brazil",7]},
// {"ID":"FISSA","cell":["FISSA","FISSA Fabrica Inter. Salchichas S.A.","Madrid","Spain",0]},
// {"ID":"FOLIG","cell":["FOLIG","Folies gourmandes","Lille","France",5]},
// {"ID":"FOLKO","cell":["FOLKO","Folk och fä HB","Bräcke","Sweden",19]},
// {"ID":"FRANK","cell":["FRANK","Frankenversand","München","Germany",15]},
// {"ID":"FRANR","cell":["FRANR","France restauration","Nantes","France",3]},
// {"ID":"FRANS","cell":["FRANS","Franchi S.p.A.","Torino","Italy",6]},
// {"ID":"FURIB","cell":["FURIB","Furia Bacalhau e Frutos do Mar","Lisboa","Portugal",8]},
// {"ID":"GALED","cell":["GALED","Galería del gastrónomo","Barcelona","Spain",5]},
// {"ID":"GODOS","cell":["GODOS","Godos Cocina Típica","Sevilla","Spain",10]}
// ]
// }
}
}
```
|
This is really ugly and there may be some issues with the string replacement, but it produces the expected results:
```
public static class JSonify
{
public static string GetJsonTable<T>(
this IQueryable<T> query, int pageNumber, int pageSize, string IDColumnName, string[] columnNames)
{
string select = string.Format("new ({0} as ID, \"CELLSTART\" as CELLSTART, {1}, \"CELLEND\" as CELLEND)", IDColumnName, string.Join(",", columnNames));
var items = new
{
page = pageNumber,
total = query.Count(),
rows = query.Select(select).Skip((pageNumber - 1) * pageSize).Take(pageSize)
};
string json = JavaScriptConvert.SerializeObject(items);
json = json.Replace("\"CELLSTART\":\"CELLSTART\",", "\"cell\":[");
json = json.Replace(",\"CELLEND\":\"CELLEND\"", "]");
foreach (string column in columnNames)
{
json = json.Replace("\"" + column + "\":", "");
}
return json;
}
}
```
|
Thanks for the quick response.
However, note the required output does not have property names in the "cell" array ( that's why I was using object[]):
"cell":["FAMIA","Familia Arquibaldo",...
vs.
"cell":{"CustomerID":"FAMIA","CompanyName","Familia Arquibaldo",...
The result is meant to be used with a JQuery grid called "flexify" which requires the output in this format.
|
Dynamic linq:Creating an extension method that produces JSON result
|
[
"",
"c#",
"linq",
"json",
""
] |
I am designing a contact management system and have come across an interesting issue regarding modeling geographic locations in a consistent way. I would like to be able to record locations associated with a particular person (mailing address(es) for work, school, home, etc.) My thought is to create a table of locales such as the following:
**Locales (ID, LocationName, ParentID)** where autonomous locations (such as countries, e.g. USA) are parents of themselves. This way I can have an arbitrarily deep nesting of 'political units' (COUNTRY > STATE > CITY or COUNTRY > STATE > CITY > UNIVERSITY). Some queries will necessarily involve recursion.
I would appreciate any other recommendations or perhaps advice regarding predictable issues that I am likely to encounter with such a scheme.
|
You might want to have a look at Freebase.com as a site that's had some open discussion about what a "location" means and what it means when a location is included in another. These sorts of questions can generate a lot of discussion.
For example, there is the obvious "geographic nesting", but there are less obvious logical nestings. For example, in a strictly geographic sense, Vatican City is nested within Italy. But it's not nested politically. Similarly, if your user is located in a research center that belongs to a university, but isn't located on the University's property, do you model that relationship or not?
|
Sounds like a good approach to me. The one thing that I'm not clear on when reading you post is what "parents of themselves" means - if this is to indicate that the locale does not have a parent, you're better off using null than the ID of itself.
|
Modeling Geographic Locations in an Relational Database
|
[
"",
"sql",
"database-design",
""
] |
I subscribe to a newsletter from www.sqlservercentral.com that I like because each day I get an email digest with some interesting headlines & summaries of SQL Server articles that are already out there on the web. It's a great way to learn something new a bit at a time.
Is there something like this for C#?
(If your favorite one is already listed, can you vote for it so I can see what's most popular? Thanks!)
|
In addition to [codeproject](http://www.codeproject.com/), I believe there are other sites like [C# Corner](http://www.c-sharpcorner.com/), [C# help](http://www.csharphelp.com/) which does the same..
Couple more I found useful (Not specific to C#):
[visualstudiomagazine](http://visualstudiomagazine.com/)
[Dr. Dobb's](http://www.ddj.com/newsletters/)
|
Have you ever considered subscribing to blogs? You can often get better content than the daily subscription emails and if you want can even become a part of the discussion through the comments. Two that are generally good for learning more about the trade and C# are [CodingBetter.com](http://codebetter.com/Default.aspx) and [Los Techies](http://www.lostechies.com/). If you are looking for something that is more of an aggregate of other sources [Scott Gu](http://weblogs.asp.net/Scottgu/) routinely puts out a list of links that can be very informative in addition to helpful walk through articles.
Good luck,
|
Is there a site that emails out daily C# tips and tricks?
|
[
"",
"c#",
"newsletter",
""
] |
I'm currently in the planning stage for a web application and I find myself trying to decide on using Grails or Django. From an operation perspective:
1. Which ecosystem is easier to maintain (migrations, backup, disaster recovery etc.)? If using grails it'll probably be a typical tomcat + mysql on linux. If django it'll be apache + mysql on linux.
2. Does django or grails have a better choice of cheap and flexible hosting? Initially it'll probably be low bandwidth requirements. I'm not sure about the exact specs required, but from what I've been reading it seems like django would require far less server resources (even 256MB server is ok) than grails.
|
You can run grails in 256 megs of ram. Many members of the community are doing so. That being said I would say in either platform you want much more ram than that to make sure your performant. But I might also reccomend checking out www.linode.com. You can get quality hosting for a very reasonable cost and adding a bit of ram for grails will not break your budget. Also if your interested in cloud based solutions Morph is hosting grails apps.
<http://developer.mor.ph/grails>
I like Django, but I for the maturity of the platform and the amount of quality Java work out there in terms of libaries and frameworks I chose grails. In truth I think they are both good solutions but you cannot deny that your options are much greater with grails.
|
With Java hosting you don't need to do all the stupid tricks with apache, or nginx. Jetty itself can host everything you need, that's how the guys at www.mor.ph do it, and they find it to be pretty fast.
The memory usage that way is pretty minimal, I host mine on a 256MB Ubuntu server from RapidXen, so it's about $10/month.
I tried developing in Django, and while it runs all the scripts faster (like bootstrapping, or test cases) it's not as well-crafted in my oppinion
|
Running a web app in Grails vs Django
|
[
"",
"python",
"django",
"grails",
"groovy",
"web-applications",
""
] |
Let's look at an example - books. A book can have 1..n authors. An author can have 1..m books. What is a good way to represent all of the authors of a book?
I came up with an idea to create a Books table and an Authors table. The Authors table has a primary AuthorID key the author's name. The Books table has a primary Book ID and metadata about the book (title, publication date, so on). However, there needs to be a way to link the books to authors and authors to books. And this is where the problem is.
Let's say we have three books by Bob. However, on one book, he wrote it as Bob, PhD. Another he wrote as Dr. Bob, and a third he wrote as Dr. Robert. I want to be able to identify the fact that these authors are, in reality, the same person but credited under different names. I also want to distinguish Bob from another Bob who wrote different books.
Now let's also add in another part to an application, a Person table that keeps track of interesting people. And let's say that Bob is an interesting person. I want to not only say that the author of all three books is Bob, but that this interesting Bob is the same Bob as the author Bob.
So what strategies exist for such potentially complicated mapping, while ensuring that the book authors are identified by the name on the cover?
|
Add another table called BookAuthors with columns for BookID, AuthorID, and NameUsed. A NULL value for NameUsed would mean to pull it from the Author's table instead. This is called an Intersection table.
|
You'd need three tables -
1. Book
2. Author
3. BookAuthors
Book would contain book id, book title, and all the other information you need to collect about the book.
Author would contain author ID as well as other information such as First name, last name that you need to collect about any given author.
BookAuthors would be a many-to-many join, containing BookID, AuthorID, and NameUsed. This would allow the book to have either zero or many authors, for an author to have either zero or many books, and for information about that relationship to be captured. You could also, for example, have a column on the BookAuthor table that described the author's relationship to the book ("Edited By", "Fore word by").
|
How do you deal with m..n relationships in a relational database?
|
[
"",
"sql",
"database",
"database-design",
""
] |
I'm creating a Firefox extension for demo purposes.
I to call a specific JavaScript function in the document from the extension.
I wrote this in my HTML document (not inside extension, but a page that is loaded by Firefox):
```
document.funcToBeCalled = function() {
// function body
};
```
Then, the extension will run this on some event:
```
var document = Application.activeWindow.activeTab.document;
document.funcToBeCalled();
```
However it raises an error saying that `funcToBeCalled` is not defined.
Note: I could get an element on the document by calling `document.getElementById(id);`
|
It is for security reasons that you have limited access to the content page from extension. See [XPCNativeWrapper](http://developer.mozilla.org/en/docs/XPCNativeWrapper) and [Safely accessing content DOM from chrome](http://developer.mozilla.org/en/Safely_accessing_content_DOM_from_chrome),
If you control the page, the best way to do this is set up an event listener in the page and dispatch an event from your extension (addEventListener in the page, dispatchEvent in the extension).
Otherwise, see <http://groups.google.com/group/mozilla.dev.extensions/msg/bdf1de5fb305d365>
|
```
document.wrappedJSObject.funcToBeCalled();
```
This is **not secure** and allows a malicious page to elevate its permissions to those of your extension... But, it does do what you asked. Read up on the early [greasemonkey vulnerabilities](http://www.oreillynet.com/pub/a/network/2005/11/01/avoid-common-greasemonkey-pitfalls.html?page=1) for why this is a bad idea.
|
How do I execute a page-defined JavaScript function from a Firefox extension?
|
[
"",
"javascript",
"firefox",
"dom",
"document",
""
] |
Is it possible to programaticly run compiled Python (comiled via py2exe) as administrator in Vista?
Some more clarification:
I have written a program that modifies the windows hosts file (c:\Windows\system32\drivers\etc\hosts) in Vista the program will not run and will fail with an exception unless you right-click and run as administrator even when the user has administrator privileges, unlike in XP where it will run if the user has administration rights, so I need a way to elevate it to the correct privileges programaticly.
|
Do you mean that you want Windows to prompt for elevation when your program is run? This is controlled by adding a UAC manifest to the EXE's resources. [This blog entry](http://blogs.msdn.com/shawnfa/archive/2006/04/06/568563.aspx) explains how to create the manifest and how to compile it into a .RES file.
I don't know what facilities py2exe has for embedding custom .RES files, so you might need to use the MT.EXE tool from the Platform SDK to embed the manifest in your program. MT.EXE doesn't need .RES files; it can merge the .manifest file directly.
|
Following the examples from `Python2x\Lib\site-packages\py2exe\samples\user_access_control` just add `uac_info="requireAdministrator"` to console or windows dict:
```
windows = [{
'script': "admin.py",
'uac_info': "requireAdministrator",
},]
```
|
Running compiled python (py2exe) as administrator in Vista
|
[
"",
"python",
"windows-vista",
"permissions",
"py2exe",
""
] |
I'm trying to do a custom button to my form (which has FormBorderStyle = none) using Visual Studio 2005. I have my 3 states button images in an ImageList linked to the button.
```
this.btnClose.AutoSize = false;
this.btnClose.BackColor = System.Drawing.Color.Transparent;
this.btnClose.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.btnClose.FlatAppearance.BorderSize = 0;
this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnClose.ForeColor = System.Drawing.Color.Transparent;
this.btnClose.ImageKey = "Disabled";
this.btnClose.ImageList = this.imageList1;
this.btnClose.Location = new System.Drawing.Point(368, -5);
this.btnClose.Margin = new System.Windows.Forms.Padding(0);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(31, 31);
this.btnClose.TabIndex = 0;
this.btnClose.UseVisualStyleBackColor = false;
this.btnClose.MouseLeave += new System.EventHandler(this.btnClose_MouseLeave);
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
this.btnClose.MouseDown += new System.Windows.Forms.MouseEventHandler(this.btnClose_MouseDown);
this.btnClose.MouseHover += new System.EventHandler(this.btnClose_MouseHover);
private void btnClose_MouseHover(object sender, EventArgs e)
{
btnClose.ImageKey = "enabled";
}
private void btnClose_MouseDown(object sender, MouseEventArgs e)
{
btnClose.ImageKey = "down";
}
private void btnClose_MouseLeave(object sender, EventArgs e)
{
btnClose.ImageKey = "disabled";
}
```
All is working, but there's one catch. Whenever I move the mouse hover the button I get a really annoying grey background.
How can I remove that?
|
The grey background is due to the setting of "System.Windows.Forms.FlatStyle.Flat", it's the default behaviour, since it need to highlight the button when you hover. To eliminate that, you might have to write a custom button class, inherit from the original button and do some custom painting to achieve that.
Btw, instead of setting "enabled" in MouseHover, you should do it in MouseEnter. MouseEnter and MouseLeave is a pair which indicate whether is the mouse is within the button or not, and it's fired once per entry/exit. Where as MouseHover is fire whenever the mouse moved within the button, which create unnessecery repeated setting of "enabled".
|
```
btnClose.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
```
|
Custom button in C#: How to remove hover background?
|
[
"",
"c#",
".net",
"winforms",
"button",
""
] |
Does anyone know of a faster decimal implementation in python?
As the example below demonstrates, the standard library's decimal module is ~100 times slower than `float`.
```
from timeit import Timer
def run(val, the_class):
test = the_class(1)
for c in xrange(10000):
d = the_class(val)
d + test
d - test
d * test
d / test
d ** test
str(d)
abs(d)
if __name__ == "__main__":
a = Timer("run(123.345, float)", "from decimal_benchmark import run")
print "FLOAT", a.timeit(1)
a = Timer("run('123.345', Decimal)", "from decimal_benchmark import run; from decimal import Decimal")
print "DECIMAL", a.timeit(1)
```
*Outputs:*
```
FLOAT 0.040635041427
DECIMAL 3.39666790146
```
|
The [GMP](http://gmplib.org) library is one of the best arbitrary precision math libraries around, and there is a Python binding available at [GMPY](http://www.aleax.it/gmpy.html). I would try that method.
|
You can try [cdecimal](http://www.bytereef.org/mpdecimal/index.html):
```
from cdecimal import Decimal
```
As of Python 3.3, the cdecimal implementation is now the built-in implementation of the `decimal` standard library module, so you don't need to install anything. Just use `decimal`.
For Python 2.7, installing `cdecimal` and using it instead of `decimal` should provide a speedup similar to what Python 3 gets by default.
|
Is there a faster alternative to python's Decimal?
|
[
"",
"python",
"python-decimal",
""
] |
I have a function that looks like this
```
class NSNode {
function insertAfter(NSNode $node) {
...
}
}
```
I'd like to be able to use that function to indicate that the node is being inserted at the start, therefore it is after *nothing*. The way I think about that is that `null` means "nothing", so I'd write my function call like this:
```
$myNode->insertAfter(null);
```
Except PHP throws an error saying that it was expecting an `NSNode` object. I'd like to stick to using the strict data typing in my function, but would like to be able to specify a null-esque value.
So, short of changing it to `function insertAfter($node) { }`, is there a way I can pass something else to that function?
---
Update: I've accepted Owen's answer because it answered the question itself. Everyone else's suggestions were really good and I'll actually be implementing them in this project, thanks!
|
sure, just set a default "null"
```
function(NSNode $node = null) {
// stuff....
}
```
result being:
```
$obj->insertAfter(); // no error
$obj->insertAfter(new NSNode); // no error
$obj->insertAfter($somevar); // error expected NSNode
```
|
No, you can't pass something else to the function as that defeats the purpose of the static typing. In this situation, something like C# nullable would be nice i.e. NSNode?
I'd suggest creating NSNode::insertFirst() although I think that you have it the wrong way round, why is a node inserting itself, shouldn't the collection be inserting and taking the node as a parameter?
|
PHP5: Specifying a datatype in method parameters
|
[
"",
"php",
"parameters",
""
] |
How do you set up your .NET development tree? I use a structure like this:
```
-projectname
--config (where I put the configuration files)
--doc (where I put all the document concerning the project: e-mails, documentation)
--tools (all the tools I use: Nunit, Moq)
--lib (all the libraries used by the solution: ninject or autofac)
--src
---app (sourcefiles)
---test (unittests)
solutionfile.sln
build.csproj
```
The sign "-" marks directories.
I think it's very important to have a good structure on this stuff. You should be able to get the source code from the source control system and then build the solution without opening Visual Studio or installing any third party libraries.
Any thoughts on this?
|
We use a very similar layout as covered in JP Boodhoo's blog post titled [Directory Structure For Projects](http://blog.developwithpassion.com/2007/10/01/directory-structure-for-projects/).
|
Check out these other StackOverflow questions...
* [Structure of Projects in Version Control](https://stackoverflow.com/questions/16829/structure-of-projects-in-version-control#16915)
* [Best Practice: Collaborative Environment, Bin Directory, SVN](https://stackoverflow.com/questions/265/best-practice-collaborative-environment-bin-directory-svn)
|
How do you set up your .NET development tree?
|
[
"",
"c#",
".net",
"development-environment",
""
] |
I am looking for instructions on how to setup a PEAR channel for our project so that we can deploy it with the pear installer. I have searched the web for a while and cannot find any straightforward information. I followed [this tutorial](http://greg.chiaraquartet.net/archives/123-Setting-up-your-own-PEAR-channel-with-Chiara_PEAR_Server-the-official-way.html) for a while, but I am having a hell of a time getting this to work. Does anyone know how to do this? Is there a simpler way?
|
It looks like you are one of the few people who want to do this. That tutorial you linked to appears to be the latest (!) but the package is still [somewhat in development](http://pear.chiaraquartet.net/index.php?package=Chiara_PEAR_Server). The documentation in that package is also non-existent. It looks like it's up to you to write the docs. Or maybe contact [Greg Beaver](http://greg.chiaraquartet.net/); the author of the package and blog post you linked to. He also [wrote a book about PEAR](https://rads.stackoverflow.com/amzn/click/com/1904811191) (albeit in 2006.) The amazon writeup mentions this:
> Next, you will learn how to set up
> your own PEAR Channel for distributing
> PHP applications, both open-source and
> proprietary closed-source PHP
> applications that can be secured using
> technology already built into the PEAR
> Installer
.
|
What problems are you encountering on following the tutorial that you linked to?
You could set up your own channel with pirum or the chiara server ( <http://pear.chiaraquartet.net/> ) but you could also look into getting an account on <http://pearfarm.org> and hosting your packages there (or on <http://pearhub.org>).
|
How to set up your own PEAR Channel?
|
[
"",
"php",
"deployment",
"pear",
""
] |
I have an asp.net text form that contains numerous decimal fields that are optional. I want to selectively update the database but not inserting a "0" for fields that do not have data (maintaining the null status).
Typically, I would create multiple functions, each with a different signature to handle this. However, I am inserting the data through a webservice which does not allow a function with the same name to have multiple signatures. I can think of a couple ways to work around this, but none "pragmatically".
|
[Nullable Types](http://msdn.microsoft.com/en-us/library/b3h38hb0(VS.80).aspx) are meant for the same purpose. They represent value types with the possibility of having no data in them. Presence of value can be checked using HasValue property of these types.
Pseudo code to read the fields:
```
decimal? dValue; // default value is null
if(decimalValueExists)
{
dValue = <value read from text file>
}
```
When you say multiple methods - I assume these are overloaded methods to be able to add optional fields (so n optional fields means n more methods)
You can avoid writing those methods by writing single method. Suppose you have one required field and one optional field:
```
public class MyFields
{
decimal req1;
decimal? opt1; // optional field 1
}
```
Then define the web service method to use it:
```
[WebMethod]
void MyWSMethod(MyFields myFields)
{/* code here will ultimately call InsertMyFields */}
void InsertMyFields(MyFields myFields)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create the command and set its properties.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "AddMyFields";
command.CommandType = CommandType.StoredProcedure;
// Add the required input parameter
SqlParameter parameter1 = new SqlParameter();
parameter1.ParameterName = "@ReqField1";
parameter1.SqlDbType = SqlDbType.NVarChar;
parameter1.Direction = ParameterDirection.Input;
parameter1.Value = myFields.req1;
// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter1);
// Add the optional parameter and set its properties.
SqlParameter parameter2 = new SqlParameter();
parameter2.ParameterName = "@OptField1";
parameter2.SqlDbType = SqlDbType.NVarChar;
parameter2.Direction = ParameterDirection.Input;
parameter2.Value = myFields.opt1 ?? DBNull.Value; //null coalescing operator
// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter2);
//.. rest of the code
}
}
```
If the nullable type has a value, [Null Coalescing Operator](http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx) will set the value or else it will set the other value that you specify (DBNull.Value in our case).
|
You may be able to define your parameters as nullable decimals. The C# syntax for a nullable value type like this:
```
decimal? rebateAmountOrWhatever;
```
You can then store nulls in the variable and compare the variable to null.
```
new SqlParameter("@RebateAmount",
rebateAmountOrWhatever == null ? (object)DBNull.Value : (object)rebateAmountOrWhatever)
```
There is also great fun to be had using the ?? operator like this:
```
new SqlParameter("@RebateAmount",
(object)rebateAmountOrWhatever ?? (object)DBNull.Value)
```
An equivalent way to declare the variable is with the Nullable<> generic type like this:
```
Nullable<decimal> currentIraBalance = null;
```
|
Update the database maintaining the Null status
|
[
"",
"c#",
"asp.net",
"sql-server",
"web-services",
""
] |
Is there anyway to build a solution to target 64 bit environment in vs2003? My solution is native c++ not visual c++. Any help would be greatly appreciated.
cheers,
RWendi
|
This page on 2003's lack of 64-bit targeting seems to address your issue: <http://www.toymaker.info/Games/html/64_bit.html>.
> The first step was to set up my development environment for 64 bit development. I use Visual Studio 2003 which has little built in support for 64 bit development.
>
> In order to create 64 bit applications you need to install the latest Platform SDK from Microsoft (Microsoft Platform SDK for Windows Server 2003). The SDK, as well as having libraries for 32 bit programming, has 64 bit versions for AMD64 and IA64 (Intel) development.
>
> Getting the correct library and header file paths set up in Visual Studio proved surprisingly difficult. I wanted the choice of developing 32 bit or 64 bit projects. While the platform SDK comes with command files to set up the correct paths they wipe out any other paths. Since T2 uses DirectX I also needed the DirectX paths setting correctly.
Upgrading to a newer edition of Visual Studio looks like the safer, non-hackish solution, if possible.
|
As Warren points out, this isn't easy with VS2003. You need to install the x64 compiler from the [platform SDK](http://www.microsoft.com/downloads/details.aspx?FamilyID=a55b6b43-e24f-4ea3-a93e-40c0ec4f68e5&DisplayLang=en).
We ran this way for a couple of years (starting with even earlier versions and the IA64 compiler). There were separate project configurations for X64 builds, so in addition to the normal DEBUG and RELEASE configurations we had DEBUG\_X64 and RELEASE\_X64.
But you have to launch VS studio with the paths set up for either the x86 or x64 compilers & libraries. You couldn't switch between them on the fly. I believe there was a command line switch /useenv that told VS to set its various paths from environment variables. We had bat files to set this all up.
It is messy, and every now and then we'd build the wrong project configuration for the environment which always took a while to sort out. You are much better off upgrading to VS2005/VS2008 where the target architecture is exposed directly in the GUI.
|
How to build a solution to target 64 bit environment?
|
[
"",
"c++",
"64-bit",
"visual-studio-2003",
""
] |
Just looking at ways of getting named constants in python.
```
class constant_list:
(A_CONSTANT, B_CONSTANT, C_CONSTANT) = range(3)
```
Then of course you can refer to it like so:
```
constant_list.A_CONSTANT
```
I suppose you could use a dictionary, using strings:
```
constant_dic = {
"A_CONSTANT" : 1,
"B_CONSTANT" : 2,
"C_CONSTANT" : 3,}
```
and refer to it like this:
```
constant_dic["A_CONSTANT"]
```
---
My question, then, is simple. Is there any better ways of doing this? Not saying that these are inadequate or anything, just curious - any other common idioms that I've missed?
Thanks in advance.
|
For 2.3 or after:
```
class Enumerate(object):
def __init__(self, names):
for number, name in enumerate(names.split()):
setattr(self, name, number)
```
To use:
```
codes = Enumerate('FOO BAR BAZ')
```
`codes.BAZ` will be 2 and so on.
If you only have 2.2, precede this with:
```
from __future__ import generators
def enumerate(iterable):
number = 0
for name in iterable:
yield number, name
number += 1
```
(*This was taken from [here](http://www.velocityreviews.com/forums/t322211-enum-in-python.html)*)
|
I find the enumeration class recipe (Active State, [Python Cookbook](http://code.activestate.com/recipes/67107/)) to be very effective.
Plus it has a lookup function which is nice.
Pev
|
Is there a better way to get a named series of constants (enumeration) in Python?
|
[
"",
"python",
""
] |
How do I read a time value and then insert it into a TimeSpan variables?
|
If I understand you correctly you're trying to get some user input in the form of "08:00" and want to store the time in a timespan variable?
So.. something like this?
```
string input = "08:00";
DateTime time;
if (!DateTime.TryParse(input, out time))
{
// invalid input
return;
}
TimeSpan timeSpan = new TimeSpan(time.Hour, time.Minute, time.Second);
```
|
From [MSDN](http://msdn.microsoft.com/en-us/library/system.timespan.aspx): A TimeSpan object represents a time interval, or duration of time, measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The largest unit of time used to measure duration is a day.
Here's how you can initialize it to CurrentTime (in ticks):
```
TimeSpan ts = new TimeSpan(DateTime.Now.Ticks);
```
|
How do I read a time value and then insert it into a TimeSpan variable
|
[
"",
"c#",
".net",
"time",
"timespan",
""
] |
I have a web page in which people go to register for my site. I use server side validation to authenticate them. I need to call some Javascript to tell GA that user was or was not registered. Later I need stats on success in registration.
How can I call the GA function on my server side C# code?
|
I don't think Google Analytics is set up to do what you are trying to do.
You should just be pasting the code into your master page. From there, you should be able to get a good idea of how many people have registered based on how many visited the landing page after they register.
|
A project i have released under open source allows for easy integration with Google Analytics from .net native code to fire page views, events etc through code.
It's called GaDotNet and can be found here:
<http://www.diaryofaninja.com/projects/details/ga-dot-net>
|
How do I use Google Analytics in ASP.NET?
|
[
"",
"c#",
"asp.net",
"google-analytics",
""
] |
Are there are good uses of Partial Classes outside the webforms/winforms generated code scenarios? Or is this feature basically to support that?
|
It is in part to support scenarios (WebForms, WinForms, LINQ-to-SQL, etc) mixing generated code with programmer code.
There are more reasons to use it. For example, if you have big classes in large, unwieldy files, but the classes have groups of logically related methods, partial classes may be an option to make your file sizes more manageable.
|
I use partial classes as a means of separating out the different sub elements of custom controls that I write. Also, when used with entity creation software, it allows products like LLBLGen to create generated versions of classes, as well as a custom, user edited version, that won't get replaced if the entities need to be regenerated.
|
Partial Classes in C#
|
[
"",
"c#",
"partial-classes",
""
] |
I know this is a subjective question, but why does Hibernate seem to be designed for short lived sessions? Generally in my apps I create DAOs to abstract my data layer, but since I can't predict how the entity objects are going to be used some of its collections are lazy loaded, or I should say fail to load once the session is closed.
Why did they not design it so that it would automatically re-open the session, or have sessions always stay open?
|
Becuase once you move out of your transaction boundary you can't hit the database again without starting a new transaction. Having long running transactions 'just in case' is a bad thing (tm).
I guess you want to lazy load object from your view - take a look [here](http://www.hibernate.org/43.html) for some options. I prefer to define exactly how much of the object map is going to be returned by my session facade methods. I find this makes it easier to unit test and to performance test my business tier.
|
I worked on a desktop app that used EJB and Hibernate. We had to set `lazy=false` everywhere, because when the objects get serialized, they lose their ability to be fetched from the backend. That's just how it goes, unfortunately.
If you are concerned with performance, you could use caching on the backend so that your non-lazy fetches are not as painful.
|
Why does Hibernate seem to be designed for short lived sessions?
|
[
"",
"java",
"hibernate",
""
] |
Given a simple (id, description) table t1, such as
```
id description
-- -----------
1 Alice
2 Bob
3 Carol
4 David
5 Erica
6 Fred
```
And a parent-child relationship table t2, such as
```
parent child
------ -----
1 2
1 3
4 5
5 6
```
Oracle offers a way of traversing this as a tree with some custom syntax extensions:
```
select parent, child, sys_connect_by_path(child, '/') as "path"
from t2
connect by prior parent = child
```
The exact syntax is not important, and I've probably made a mistake in the above. The
important thing is that the above will produce something that looks like
```
parent child path
------ ----- ----
1 2 /1/2
1 3 /1/3
4 5 /4/5
4 6 /4/5/6
5 6 /5/6
```
My question is this: is it possible to join another table within the sys\_connect\_by\_path(), such as the t1 table above, to produce something like:
```
parent child path
------ ----- ----
1 2 /Alice/Bob
1 3 /Alice/Carol
... and so on...
```
|
In your query, replace T2 with a subquery that joins T1 and T2, and returns parent, child and child description. Then in the sys\_connect\_by\_path function, reference the child description from your subquery.
|
Based on Mike McAllister's idea, the following uses a derived table to achieve the desired result:
```
select
T.PARENT
,T.CHILD
,sys_connect_by_path(T.CDESC, '/')
from
(
select
t2.parent as PARENT
,t2.child as CHILD
,t1.description as CDESC
from
t1, t2
where
t2.child = t1.id
) T
where
level > 1 and connect_by_isleaf = 1
connect by prior
T.CHILD = T.PARENT
```
In my problem, all the parents are anchored under a "super-parent" root, which means that the paths can be fully described with SYS\_CONNECT\_BY\_PATH, thereby obviating the need for cagcowboy's technique of concatenating the parent with the path.
|
Joining other tables in oracle tree queries
|
[
"",
"sql",
"oracle",
"tree",
"connect-by",
""
] |
How do I create a file-like object (same duck type as File) with the contents of a string?
|
For Python 2.x, use the [StringIO](https://docs.python.org/2/library/stringio.html) module. For example:
```
>>> from cStringIO import StringIO
>>> f = StringIO('foo')
>>> f.read()
'foo'
```
I use cStringIO (which is faster), but note that it doesn't [accept Unicode strings that cannot be encoded as plain ASCII strings](http://docs.python.org/lib/module-cStringIO.html). (You can switch to StringIO by changing "from cStringIO" to "from StringIO".)
For Python 3.x, use the [`io`](https://docs.python.org/3/library/io.html#text-i-o) module.
```
f = io.StringIO('foo')
```
|
In Python 3.0:
```
import io
with io.StringIO() as f:
f.write('abcdef')
print('gh', file=f)
f.seek(0)
print(f.read())
```
The output is:
```
'abcdefgh'
```
|
How do I wrap a string in a file in Python?
|
[
"",
"python",
"string",
"file",
"stringio",
""
] |
I need to profile a java application for a customer. It's an eclipse/maven project, so I decided on using eclipse TPTP ( <http://www.eclipse.org/tptp> ).
I tried to install eclipse TPTP through the update manager from a standard eclipse installation, but I gave up because of the unbelievable complex setup and downloading of dependencies with very cryptic names.
Then I downloaded the "all in one TPTP 4.5.1" package from <http://www.eclipse.org/tptp/home/downloads/?ver=4.5.1> but when I start it up, it pops up an error saying "The eclipse executable launcher was unable to locate it's companion shared library".
I'm running Windows XP, Sun Java 1.5, and clicked on "eclipse.exe" in the unpacked eclipse TPTP installation.
What do I need to do to get eclipse TPTP running?
|
An alternative is to use Netbeans to profile an Eclipse Application.
I have a blog post on the link below that explains how to configure both applications:
<http://www.jroller.com/ortegon/entry/on_profiling_eclipse_rcp_applications>
It works very well. I've been profiling this way from over a year. Easy to use, easy to setup and nice graphics also.
I found installing TPTP a pain, at least the version I used is not very well integrated with Eclipse. It took me a very long time to get it to work correctly. Netbeans was way quicker to learn and to get up to speed. In the newer versions, it is also possible to import the source code of the Eclipse Projects using a special netbeans plugin (albeit it needs to be downloaded separately).
|
[VisualVM 1.1.1](https://visualvm.dev.java.net/) is a nice alternative to using NetBeans, being a standalone app, so you don't have to bring a Maven/Ant/Eclipse project into it's project format. It can see any local Java process upon opening, so just double click your app in the list of Java processes and off you go. You can:
1. Take Heap Dumps
2. Compare Memory Snapshots
3. [View garbage collection with the VisualGC plugin](https://visualvm.dev.java.net/plugins.html)
4. [Run BTrace scripts](https://btrace.dev.java.net/) to add run-time profiling & debugging advice to your code.
|
How to set up Eclipse TPTP
|
[
"",
"java",
"eclipse",
"jakarta-ee",
"profiling",
""
] |
I have just found a static nested interface in our code-base.
```
class Foo {
public static interface Bar {
/* snip */
}
/* snip */
}
```
I have never seen this before. The original developer is out of reach. Therefore I have to ask SO:
What are the semantics behind a static interface? What would change, if I remove the `static`? Why would anyone do this?
|
The static keyword in the above example is redundant (a nested interface is automatically "static") and can be removed with no effect on semantics; I would recommend it be removed. The same goes for "public" on interface methods and "public final" on interface fields - the modifiers are redundant and just add clutter to the source code.
Either way, the developer is simply declaring an interface named Foo.Bar. There is no further association with the enclosing class, except that code which cannot access Foo will not be able to access Foo.Bar either. (From source code - bytecode or reflection can access Foo.Bar even if Foo is package-private!)
It is acceptable style to create a nested interface this way if you expect it to be used only from the outer class, so that you do not create a new top-level name. For example:
```
public class Foo {
public interface Bar {
void callback();
}
public static void registerCallback(Bar bar) {...}
}
// ...elsewhere...
Foo.registerCallback(new Foo.Bar() {
public void callback() {...}
});
```
|
The question has been answered, but one good reason to use a nested interface is if its function is directly related to the class it is in. A good example of this is a `Listener`. If you had a class `Foo` and you wanted other classes to be able to listen for events on it, you could declare an interface named `FooListener`, which is ok, but it would probably be more clear to declare a nested interface and have those other classes implement `Foo.Listener` (a nested class `Foo.Event` isn't bad along with this).
|
Why would a static nested interface be used in Java?
|
[
"",
"java",
"interface",
"static",
""
] |
I enjoy developing algorithms using the STL, however, I have this recurring problem where my data sets are too large for the heap.
I have been searching for drop-in replacements for STL containers and algorithms which are disk-backed, i.e. the data structures on stored on disk rather than the heap.
A friend recently pointed me towards [stxxl](http://stxxl.sourceforge.net). Before I get too involved with it... Are any other disk-backed STL replacements available that I should be considering?
**NOTE: I'm not interested in persistence or embedded databases. Please don't mention boost::serialization, POST++, Relational Template Library, Berkeley DB, sqlite, etc. I am aware of these projects and use them when they are appropriate for my purposes.**
*UPDATE: Several people have mentioned memory-mapping files and using a custom allocator, good suggestions BTW, but I would point them to the discussion [here](http://lists.boost.org/Archives/boost/2002/11/39388.php) where David Abraham suggests that custom iterators would be needed for disk-backed containers. Meaning the custom allocator approach isn't likely to work.*
|
I have implemented some thing very similar. Implementing the iterators is the most challenging. I used **[boost::iterator\_facade](http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/iterator_facade.html)** to implement the iterators. Using `boost::iterator_facade` you can **easy adapt** any cached on **disk data structures** to have a STL container interface.
|
I've never had to do anything quite like this, but It might be possible to do what you want to do by writing a custom allocator that makes use of a memory mapped files to back your data.
See [boost::interprocesses](http://www.boost.org/doc/libs/1_36_0/doc/html/interprocess/sharedmemorybetweenprocesses.html#interprocess.sharedmemorybetweenprocesses.mapped_file) for docs on their easy to use implementation of memory mapped files, [this Dr. Dobbs article](http://www.ddj.com/cpp/184406243) for a detailed discussion on writing allocators, and [this IEEE Software column](http://www.spinellis.gr/blog/20101030/) for a description of the problem and [example code](http://www.spinellis.gr/blog/20101030/smap.cpp).
|
Disk-backed STL container classes?
|
[
"",
"c++",
"algorithm",
"data-structures",
"stl",
"on-disk",
""
] |
I've been arguing with my coworkers about Pascal casing (upper camel case) vs. lower [CamelCasing](http://en.wikipedia.org/wiki/CamelCase). They are used to lower camel casing for everything from table names in SQL databases to property naming in C# code but I like Pascal casing better, lower camel casing for variables and Pascal casing for properties:
```
string firstName;
public string FirstName {
...
}
```
But they are used to this:
```
string _firstname;
public string firstName {
...
}
```
I try to keep up with their "standard" so the code looks the same but I just don't like it.
I've seen that at least the .NET framework uses this convention and that is how I try to keep my code, e.g.:
```
System.Console.WriteLine("string")
```
What do you use/prefer and why? I'm sorry if somebody else asked this question but I searched and did not find anything.
**Update:**
I've given a method example and not a property but it's the same. As I stated in the first paragraph my colleagues use the Pascal convention for everything (variables, methods, table names, etc.)
|
I use what the Framework uses, as it's the de-facto best practice. However, so long as the code in your company is **consistently** using their style, then you're much better off getting used to it. If every developer has their own standard, then there's no standard at all.
|
A link to the official [design guidelines](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/) might help. Specifically, read the section on [Capitalization styles](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions#capitalizing-compound-words-and-common-terms).
In the grand scheme of things, Pascal vs Camel doesn't matter that much and you're not likely to convince anyone to go back over an existing code base just to change the case of names. What's really important is that you want to be consistent within a given code base.
I'm just happy as long as you're not using Hungarian.
|
Pascal casing or Camel Casing for C# code?
|
[
"",
"c#",
".net",
"naming-conventions",
"standards",
""
] |
I have an API that is dependent on certain state information between requests. As an easy first version of the code, I am simply using PHP session's to store the state information instead of something more advanced (APC, memcache, DB). Throughout my initial testing in a web browser, everything worked perfectly. However, it seems that when clients try to connect through non-browser methods such as Curl or wget, the state information is not being preserved.
Will a PHP session only be created if a browser is requesting the page? I am explicitly starting the session with session\_start() as well as naming it before hand with session\_name().
**An added note**. I learned that one of the major problems I was having was that I was naming the session instead of setting the session id via session\_id($id); My intention in using session\_name() was to retrieve the same session that was previously created, and the correct way to do this is by setting the session\_id not the session\_name.
It seems that session information will be persisted on the server as noted below (THANK YOU). But to keep this you must pass the session id, or, as in my case, any other id that would uniquely identify the user. Use this id as the session\_id and your sessions will function as expected.
|
**Session Cookies**
Remember that HTTP is **stateless**, so sessions are tracked on your server, but the **client** has to identify itself with each request. When you declare session\_start(), **your browser is usually setting a cookie** (the "PHP Session Id"), and then identifying itself by sending the cookie value with each request. When a script is called using a request with a session value, then the session\_start() function will try to look up the session. To prove this to yourself, notice that sessions die when you clear your cookies.. many will die even as soon as you quit the browser, if the cookie is a "session" cookie (a temporary one). You mentioned that you're naming the session.. take a look in your browser cookies and see if you can find a cookie with the same name.
All of this is to say that cookies are playing an active role in your sessions, so if the **client doesn't support cookies**, then you can't do a session the way you're currently doing it.. at least not for those alternative clients. A session will be created on the server; the question is whether or not the client is participating.
If cookies aren't an option for your client, you're going to have to find **another way** to pass a session id to the server. This can be done in the **query string**, for example, although it's a considered a bit less private to send a session id in this way.
```
mysite.com?PHPSESSID=10alksdjfq9e
```
How do to this specifically may vary with your version of PHP, but it's basically just a configuration. If the proper runtime options are set, PHP will transparently add the session id as a query parameter to links on the page (same-source only, of course). You can find the specifics for setting that up on the [PHP website](https://www.php.net/manual/en/session.idpassing.php).
**Sidenote:** Years ago, this was a common problem when attempting to implement a session. Cookies were newer and many people were turning off the cookie support in their browsers because of purported security concerns.
**Sidenote:** *@Uberfuzzy* makes a good point- Using sessions with curl or wget is actually possible. The problem is that it's less automatic. A user might dump header values into a file and use the values on future requests. curl has some "cookie awareness" flags, which allow you to handle this more easily, but you still must explicitly do it. Then again, you could use this to your advantage. If curl is available on your alternative client, then you can plausibly make the call yourself, using the cookie awareness flags. Refer to the [curl manual](http://curl.netmirror.org/docs/manual.html).
|
*Will a PHP session only be created if a browser is requesting the page?*
**Short answer**: Yes. Sessions were created specifically to solve the HTTP stateless problem by leveraging browser features. APC, memcached, DB, etc. don't matter. Those are just storage methods for the session, and will suffer from the same problem.
**Longer answer**: The concept of sessions were created to account for the fact that HTTP is a stateless protocol, and it turns out that state's pretty important for a wide variety of software applications.
The most common way of implementing sessions is with cookies. PHP sends the session ID in a cookie, and the browser sends the cookie with the session ID back. This ID is used on the server to find whatever information you've stored in the session. PHP has the capacity to include and read a session ID at the end of a URLs, **but** this assumes that users will navigate to pages on your site/application by clicking links that include a generated session ID.
In your specific case, it is possible to use cookies with curl (and possibly wget). Curl **is** a web browser, just one without a GUI. If it's the command line curl program you're using (as opposed to the C library, PHP extension,etc.) read up on the following options
```
-b/--cookie
-c/--cookie-jar
-j/--junk-session-cookies
```
|
In PHP will a session be created if a browser is not used
|
[
"",
"php",
"session",
"browser",
""
] |
I'm looking for an add-in to VS2008 that can enable structural highlighting (**vertical** lines in blocks of code) in the C# code editor.
I tried out CodeRush, but while the structural highlighting was great, I was annoyed with all the other stuff in CodeRush. No matter how much I disabled in the options, I couldn't quite get rid of it.
So I'm looking for another add-in that enables structural highlighting and (ideally) nothing else. Know of any?
|
While browsing the [ViEmu](http://viemu.com) site, I saw the [Codekana](http://codekana.com) product which looks like it may do what you want.
|
Is the Indentation Guide from the [SlickEdit Free Gadgets](http://www.slickedit.com/content/view/441) what you're looking for?
|
C# structural highlighting in Visual Studio 2008
|
[
"",
"c#",
"visual-studio",
""
] |
[Ryan Delucchi](https://stackoverflow.com/users/9931/ryan-delucchi) asked [here](https://stackoverflow.com/questions/194698/how-to-load-a-jar-file-at-runtime#194712) in comment #3 to [Tom Hawtin](https://stackoverflow.com/users/4725/tom-hawtin-tackline)'s answer:
> why is Class.newInstance() "evil"?
this in response to the code sample:
```
// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
```
so, why is it Evil?
|
The Java API documentation explains why (<http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance()>):
> Note that this method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The `Constructor.newInstance` method avoids this problem by wrapping any exception thrown by the constructor in a (checked) `InvocationTargetException`.
In other words, it can defeat the checked exceptions system.
|
One more reason:
Modern IDEs allow you to find class usages - it helps during refactoring, if you and your IDE know what code is using class that you plan to change.
When you don't do an explicit usage of the constructor, but use Class.newInstance() instead, you risk not to find that usage during refactoring and this problem will not manifest itself when you compile.
|
Why is Class.newInstance() "evil"?
|
[
"",
"java",
"constructor",
"runtime",
"instantiation",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.