Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I have a friend who is need of a web page. He does interior construction, and would like to have a gallery of his work. I'll probably go for a php host, and was thinking about the best way to implement the image gallery for him. I came up with:
* Use flickr to host the images. They can be tagged, added to sets, and I can use both the tag and set information to display "categories" for the gallery, as well as browsing. Flickr also has multi-upload tools so that a 20 photo job won't be a PITA to upload.
* How to best get at the api? Is there a good PHP library for flickr integration? Should I roll my own?
* API key - is this considered a commercial project? The web page is for his business, and he will be paying me to create the site...
* Is flickr the wrong tool for the job? It seems like a pretty good solution in my head, but is there something I'm missing? I haven't used their APIs at all.
Thanks for any input!
|
It sounds like a difficult way to do things - have you considered [Gallery](http://gallery.menalto.com/) (No points on creativity for the name!).
Unless you're really wanting to save on bandwidth, I think you'd get much better results from installing some pre-built gallery.
|
The perfect solution for this kind of thing is [Picasa](http://www.picasa.com) (from Google ofcourse)
You get:
* 1gb of free storage space on a Google Picasaweb account that already has a web interface with embeddable slideshows and stuff
* A compete image browse and upoad program for the client side (namely Picasa) that's directly connected to the web albums. It's so user friendly that even your grandma can put her pictures online with that.
* RSS feeds and an [API](http://googledataapis.blogspot.com/2007/07/picasa-web-albums-adds-new-api-features.html) from google.
* [there's a custom light-weight PHP api available](http://cameronhinkle.com/blog/id/3696159074811309536)
Need anyting else?
---
Note from Chris to others that may be looking for an answer: The API can be found [here](http://code.google.com/apis/picasaweb/developers_guide_protocol.html).
|
Quickest way to implement a searchable, browsable image gallery - flickr integration?
|
[
"",
"php",
"flickr",
"image-gallery",
""
] |
I need to determine the highest .NET framework version installed on a desktop machine from C\C++ code. Looks like I can iterate the folders under `%systemroot%\Microsoft.NET\Framework`, but that seems kind of error prone. Is there a better way? Perhaps a registry key I can inspect? Thanks.
|
Use the [Windows Registry](http://en.wikipedia.org/wiki/Windows_Registry) location `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP`.
|
Registry keys for the .NET Framework start like this:
```
HKEY_LOCAL_MACHINE\Software\Microsoft\NET Framework Setup\NDP\
```
Depending on the version, the rest of the key will be different (check [this page](http://www.walkernews.net/2007/07/30/how-to-verify-dot-net-framework-version/)).
You can look up how to access the registry in MSDN article *[Using the registry in a C++ application](http://msdn.microsoft.com/en-us/library/ms838625.aspx)*.
|
Determine highest .NET Framework version
|
[
"",
".net",
"c++",
"c",
"version-detection",
""
] |
I want to draw DirectX content so that it appears to be floating over top of the desktop and any other applications that are running. I also need to be able to make the directx content semi-transparent, so other things show through. Is there a way of doing this?
I am using Managed DX with C#.
|
I found a solution which works on Vista, starting from the link provided by OregonGhost. This is the basic process, in C# syntax. This code is in a class inheriting from Form. It doesn't seem to work if in a UserControl:
```
//this will allow you to import the necessary functions from the .dll
using System.Runtime.InteropServices;
//this imports the function used to extend the transparent window border.
[DllImport("dwmapi.dll")]
static extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref Margins pMargins);
//this is used to specify the boundaries of the transparent area
internal struct Margins {
public int Left, Right, Top, Bottom;
}
private Margins marg;
//Do this every time the form is resized. It causes the window to be made transparent.
marg.Left = 0;
marg.Top = 0;
marg.Right = this.Width;
marg.Bottom = this.Height;
DwmExtendFrameIntoClientArea(this.Handle, ref marg);
//This initializes the DirectX device. It needs to be done once.
//The alpha channel in the backbuffer is critical.
PresentParameters presentParameters = new PresentParameters();
presentParameters.Windowed = true;
presentParameters.SwapEffect = SwapEffect.Discard;
presentParameters.BackBufferFormat = Format.A8R8G8B8;
Device device = new Device(0, DeviceType.Hardware, this.Handle,
CreateFlags.HardwareVertexProcessing, presentParameters);
//the OnPaint functions maked the background transparent by drawing black on it.
//For whatever reason this results in transparency.
protected override void OnPaint(PaintEventArgs e) {
Graphics g = e.Graphics;
// black brush for Alpha transparency
SolidBrush blackBrush = new SolidBrush(Color.Black);
g.FillRectangle(blackBrush, 0, 0, Width, Height);
blackBrush.Dispose();
//call your DirectX rendering function here
}
//this is the dx rendering function. The Argb clearing function is important,
//as it makes the directx background transparent.
protected void dxrendering() {
device.Clear(ClearFlags.Target, Color.FromArgb(0, 0, 0, 0), 1.0f, 0);
device.BeginScene();
//draw stuff here.
device.EndScene();
device.Present();
}
```
Lastly, a Form with default setting will have a glassy looking partially transparent background. Set the FormBorderStyle to "none" and it will be 100% transparent with only your content floating above everything.
|
You can either use DirectComposition, LayeredWindows, DesktopWindowManager or WPF. All methods come with their advantages and disadvantages:
-DirectComposition is the most efficient one, but needs Windows 8 and is limited to 60Hz.
-LayeredWindows are tricky to get working with D3D via Direct2D-interop using DXGI.
-WPF is relatively easy to use via D3DImage, but is also limited to 60Hz and DX9 and no MSAA. Interops to higher DX-Versions via DXGI are possible, also MSAA can be used when the MSAA-Rendertarget is resolved to the native nonMSAA surface.
-DesktopWindowManager is great for high performance available since Windows Vista, but DirectX-Versions seem to be limited by the Version the DWM uses (still DX9 on Vista). Workarounds for higher DX-Versions should be possible via DXGI where available.
If you don't need per pixel aplha, you can also use the opacity-value of a semi-transparent form.
Or you use the native Win32 method for the Window global alpha (Remember a alpha of 0 will not catch the mouse input):
```
SetWindowLong(hWnd, GWL_EXSTYLE, GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_LAYERED);
COLORREF color = 0;
BYTE alpha = 128;
SetLayeredWindowAttributes(hWnd, color, alpha, LWA_ALPHA);
```
I have been able to use all of the described techniques with C# and SharpDX, but in case of DirectComposition, LayeredWindows and native Win32 a little C++-Wrappercode was needed. For starters I would suggest to go via WPF.
|
How do I draw transparent DirectX content in a transparent window?
|
[
"",
"c#",
"windows",
"directx",
"transparent",
"direct3d",
""
] |
How can I write from Java to the Windows Event Log?
|
**EDIT (2023)**: See JNA <https://stackoverflow.com/a/3815771/3937>
### Old answer
Log4J is a Java-based logging utility. The class `NTEventLogAppender` can be used to "append to the NT event log system". See the documentation here:
<http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/nt/NTEventLogAppender.html>
**Edit:** There is a newer version, [Log4j 2](http://logging.apache.org/log4j/2.x/) "that provides significant improvements over its predecessor."
|
You can use [JNA](https://github.com/twall/jna/) to write to the Event Log directly without the need of any native DLLs. See Advapi32 and Advapi32Util classes for various event log methods (ships since JNA 3.2.8).
If you're using Log4j, consider [Log4jna](https://github.com/dblock/log4jna) instead of NTEventLogAppender.
|
How to write from Java to the Windows Event Log?
|
[
"",
"java",
"windows",
"logging",
"event-log",
""
] |
I have a fairly large codebase that depends on MooTools v1.11 and am about to convert to version 1.2. Since this is a pretty major overhaul, I've toyed with the idea of converting to jQuery.
Anyone have advice on whether to update to jQuery or just stick with MooTools?
I mostly use MooTools for Ajax, drag and drop, and some minor effects.
|
If you're upgrading *anyway*, then it may be worth looking into.
jQuery seems to be well on its way to becoming the One True Javascript library (given that MS and others have decided to embrace it), so if this is code you intend to work on for a while, then it's probably a good idea to switch at some point (if only because there will be more places to get help and plugin code, as it's very likely to continue to be popular for a while, which will help ensure the long-term flexibility and maintainability of your code). So, given that you're having to convert it anyway, now might be the best time to do it.
I think jQuery becoming *the* framework to use is a good thing. It wouldn't have been my choice (I like MooTools, too), but it's certainly an excellent bit of code and definitely fits the purpose with at least the competence of its competition. I'm happy to see any kind of consistency, and I will be moving my code to jQuery at some point.
|
If it's not broken. Don't fix it.
jQuery might have X or Y but if everything is dependent on MooTools, you might have a lot of work ahead of you to convert from MooTools.
Keep MooTools if you used it extensively through out your site. However, if you only have 2-3 pages with minor effects... the change might be worth it.
|
Should I convert from MooTools to jQuery?
|
[
"",
"javascript",
"jquery",
"mootools",
""
] |
Is there any way to format a string by name rather than position in C#?
In python, I can do something like this example (shamelessly stolen from [here](http://docs.python.org/lib/typesseq-strings.html)):
```
>>> print '%(language)s has %(#)03d quote types.' % \
{'language': "Python", "#": 2}
Python has 002 quote types.
```
Is there any way to do this in C#? Say for instance:
```
String.Format("{some_variable}: {some_other_variable}", ...);
```
Being able to do this using a variable name would be nice, but a dictionary is acceptable too.
|
There is no built-in method for handling this.
[Here's one method](http://mo.notono.us/2008/07/c-stringinject-format-strings-by-key.html)
```
string myString = "{foo} is {bar} and {yadi} is {yada}".Inject(o);
```
[Here's another](http://james.newtonking.com/archive/2008/03/29/formatwith-2-0-string-formatting-with-named-variables.aspx)
```
Status.Text = "{UserName} last logged in at {LastLoginDate}".FormatWith(user);
```
[A third improved method partially based on the two above](http://haacked.com/archive/2009/01/04/fun-with-named-formats-string-parsing-and-edge-cases.aspx), from Phil Haack
---
**Update:** This is now built-in as of C# 6 (released in 2015).
[**String Interpolation**](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated)
```
$"{some_variable}: {some_other_variable}"
```
|
I have an implementation I just posted to my blog here: <http://haacked.com/archive/2009/01/04/fun-with-named-formats-string-parsing-and-edge-cases.aspx>
It addresses some issues that these other implementations have with brace escaping. The post has details. It does the DataBinder.Eval thing too, but is still very fast.
|
Named string formatting in C#
|
[
"",
"c#",
".net-3.5",
"string-formatting",
""
] |
The output we get when printing C++ sources from Eclipse is rather ugly.
Is there are way/a plugin to pretty print C++ source code like e.g. with a2ps (which is probably using yet another filter for C source code)?
|
I also use `enscript` for this. Here's an alias I often use:
```
alias cpp2ps='enscript --color --pretty-print=cpp --language=PostScript'
```
and I use it like this:
```
cpp2ps -P main.ps main.cpp
```
There are several other great options in `enscript` including rotating, 2-column output, line numbers, headers/footers, etc. Check out the [enscript man page](http://linux.die.net/man/1/enscript).
Also, on Macs, XCode prints C++ code very nicely.
|
See this [DDJ](http://www.ddj.com/cpp/197002115?pgno=4) article which uses *enscript* as the pretty print engine.
|
Eclipse C++ pretty printing?
|
[
"",
"c++",
"eclipse",
"printing",
"eclipse-cdt",
""
] |
Okay, we know that the following two lines are equivalent -
1. `(0 == i)`
2. `(i == 0)`
Also, the first method was encouraged in the past because that would have allowed the compiler to give an error message if you accidentally used '=' instead of '=='.
My question is - in today's generation of pretty slick IDE's and intelligent compilers, do you still recommend the first method?
In particular, this question popped into my mind when I saw the following code -
```
if(DialogResult.OK == MessageBox.Show("Message")) ...
```
In my opinion, I would never recommend the above. Any second opinions?
|
I prefer the second one, (i == 0), because it feel much more natural when reading it. You ask people, "Are you 21 or older?", not, "Is 21 less than or equal to your age?"
|
It doesn't matter in C# if you put the variable first or last, because assignments don't evaluate to a bool (or something castable to bool) so the compiler catches any errors like "if (i = 0) EntireCompanyData.Delete()"
So, in the C# world at least, its a matter of style rather than desperation. And putting the variable last is unnatural to english speakers. Therefore, for more readable code, variable first.
|
How to check for equals? (0 == i) or (i == 0)
|
[
"",
"c++",
"c",
"coding-style",
""
] |
Well, after a long time writing .net programs in C# I started to feel angry and frustrated about all that syntactic trash that comes with statically typed languages. Now I want to change to dynamically typed languages, that takes advantage of CLI.
So I searched a bit around and I didn't like of what I saw. I first looked for IronPython. But the project feels disorganized, it just didn't look well at all. Then I heard about Boo. I liked boo's, the ideal and all, but it kinda feels like the project is halted. Then I heard of IronRuby, but the project is still at beta, and so I decided to wait until it gets more mature.
So as I couldn't find a good CLR compatible dynamic language, I'm asking you guys what do you(would you) use?
Since people started asking what is the reason for not choosing IronPython. Well the reason is, like I stated earlier, it seems disorganized. Why?
1- The homepage points to another page at codeplex, the homepage should be clean and just point the advantages of IronPython, take the IronRuby page as an example <http://www.ironruby.net/> its that hides language-developent stuff from the user(even though the user has to access IronRuby's svn prior using it).
What kind of issues IPython was trying to addres when it was created. Is there a page with that kind of information?
Well the page is there, but its hidden on the 'More Information Page' among a bunch of meaningless links to articles.
On Boo's page its at clear sight named as Manifesto <http://boo.codehaus.org/BooManifesto.pdf> .
There is more but the feeling that I have is that IPython is just a home-brewed interpreter, despite the quality that it can actually have.
I felt that it was safer to download Boo and use IronPython(but no worries Microsoft I had also downloaded IPython).
About Duck-Typing and Boo's static typing they both seems to work fine for me.
|
I'd still use [**Boo**](http://boo.codehaus.org/). I'm not sure why you believe Boo has been halted. Development sometimes seems slow, but there are multiple people currently working on bug fixes as demonstrated by [**this list of recently fixed issues (bugs)**](http://jira.codehaus.org/sr/jira.issueviews:searchrequest-printable/temp/SearchRequest.html?&pid=10671&resolution=1&status=5&status=6&sorter/field=issuekey&sorter/order=DESC&tempMax=1000).
For those unfamiliar with Boo, it's very similar to Python, but includes things that Python does not (like [**string interpolation**](http://boo.codehaus.org/String+Interpolation) and [**syntatic macros**](http://boo.codehaus.org/Syntactic+Macros)). You can compile Boo programs or use Boo through the "Boo Interactive Shell" *booish*.
By the way, I didn't like IronPython either when I looked at it a couple years ago. To me it looked like a straight port of Python to the CLI, but as far as I could tell it did not include new features typical .NET development requires.
**EDIT**: IronPython does seem to have progressed since I first looked at it (thanks for Curt pointing this out). However I have not bothered to look at IronPython again since I found Boo.
|
In terms of practical usability **[IronPython](http://www.codeplex.com/IronPython)** is going to be your best bet right now.
Why are people suggesting Boo? It's a statically typed language, which is not what this question is asking for. Yes, I know it has optional duck typing, but really if Boo-related information is acceptable to the question author then the question should really be edited to make that clear.
Regarding IronPython, you said you didn't like it, but there really isn't any response I can give to critical comments that are so vague :)
Alternatively, I would suggest that you take a look at [cPython](http://python.org). A couple points:
* You can building .exe files with py2exe and other tools.
* Much larger access to 3rd-party Python libraries and frameworks
* Access to Windows APIs via pywin32
* Python extension writen in C are usable (unlike IronPython, though there are [efforts](http://pythonnet.sourceforge.net/) underway to improve this situation)
You will find that you really don't need .NET for most things. Of course this all depends on your application. For integrating with existing .NET code then obviously you have to use IronPython.
|
Good dynamic programming language for .net recommendation
|
[
"",
"c#",
".net",
"ironpython",
"boo",
""
] |
ReSharper Code cleanup feature (with "[reorder members](http://www.jetbrains.com/resharper/features/code_formatting.html#Reordering_Type_Members_C#_only)" and "[reformat code](http://www.jetbrains.com/resharper/features/code_formatting.html#Code_Style_Configuration_and_Sharing)" enabled) is really great. You define a layout template using XML, then a simple key combination reorganizes your whole source file (or folder/project/solution) according to the rules you set in the template.
Anyway, do you think that could be a problem regarding VCS like subversion, cvs, git, etc. ? Is there a chance that it causes many undesired conflicts ?
Thank you.
|
Yes, it will definitely cause problems. In addition to creating conflicts that have to be manually resolved, when you check in a file that has been reformatted, the VCS will note almost every line as having been changed. This will make it hard for you or a teammate to look back at the history and see what changed when.
That said, if everyone autoformats their code the same way (ie, you distribute that XML template to the team), then it might work well. The problems really only come in when not everyone is doing the same thing.
|
I'm waiting for an IDE or an editor that always saves source code using some baseline formatting rules, but allows each individual developer to display and edit the code in their own preferred format. That way I can put my open curly brace at the beginning of the next line and not at the end of the current line where all you heathens seem to think it goes.
My guess is I'll be waiting for a long time.
|
ReSharper Code Cleanup/Reformat Code feature vs Versioning Control Systems
|
[
"",
"c#",
"version-control",
"resharper",
""
] |
I'm trying to create a character generation wizard for a game. In one class I calculate the attributes of the character. In a different class, I'm displaying to the user which specialties are available based on the attributes of the character. However, I can't remember how to pass variables between different classes.
Here is an example of what I have:
```
class BasicInfoPage(wx.wizard.WizardPageSimple):
def __init__(self, parent, title):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
<---snip--->
self.intelligence = self.genAttribs()
class MOS(wx.wizard.WizardPageSimple):
def __init__(self, parent, title):
wiz.WizardPageSimple.__init__(self, parent)
self.next = self.prev = None
self.sizer = makePageTitle(self, title)
def eligibleMOS(self, event):
if self.intelligence >= 12:
self.MOS_list.append("Analyst")
```
The problem is that I can't figure out how to use the "intelligence" variable from the BasicInfoPage class to the MOS class. I've tried several different things from around the Internet but nothing seems to work. What am I missing?
**Edit** I realized after I posted this that I didn't explain it that well. I'm trying to create a computer version of the Twilight 2000 RPG from the 1980s.
I'm using wxPython to create a wizard; the parent class of my classes is the Wizard from wxPython. That wizard will walk a user through the creation of a character, so the Basic Information page (class BasicInfoPage) lets the user give the character's name and "roll" for the character's attributes. That's where the "self.intelligence" comes from.
I'm trying to use the attributes created her for a page further on in the wizard, where the user selects the speciality of the character. The specialities that are available depend on the attributes the character has, e.g. if the intelligence is high enough, the character can be an Intel Anaylst.
It's been several years since I've programmed, especially with OOP ideas. That's why I'm confused on how to create what's essentially a global variable with classes and methods.
|
You may have "Class" and "Instance" confused. It's not clear from your example, so I'll presume that you're using a lot of class definitions and don't have appropriate object instances of those classes.
Classes don't really have usable attribute values. A class is just a common set of definitions for a collection of objects. You should think of of classes as definitions, not actual things.
Instances of classes, "objects", are actual things that have actual attribute values and execute method functions.
You don't pass variables among *classes*. You pass variables among *instances*. As a practical matter only instance variables matter. [Yes, there are class variables, but they're a fairly specialized and often confusing thing, best avoided.]
When you create an object (an instance of a class)
```
b= BasicInfoPage(...)
```
Then `b.intelligence` is the value of intelligence for the `b` instance of `BasicInfoPage`.
A really common thing is
```
class MOS( wx.wizard.PageSimple ):
def __init__( self, parent, title, basicInfoPage ):
<snip>
self.basicInfo= basicInfoPage
```
Now, within MOS methods, you can say `self.basicInfo.intelligence` because MOS has an object that's a BasicInfoPage available to it.
When you build MOS, you provide it with the instance of BasicInfoPage that it's supposed to use.
```
someBasicInfoPage= BasicInfoPage( ... )
m= MOS( ..., someBasicInfoPage )
```
Now, the object `m` can examine `someBasicInfoPage.intelligence`
|
Each page of a Wizard -- by itself -- shouldn't actually be the container for the information you're gathering.
Read up on the [Model-View-Control](http://en.wikipedia.org/wiki/Model-view-controller) design pattern. Your pages have the View and Control parts of the design. They aren't the data model, however.
You'll be happier if you have a separate object that is "built" by the pages. Each page will set some attributes of that underlying model object. Then, the pages are independent of each other, since the pages all get and set values of this underlying model object.
Since you're building a character, you'd have some class like this
```
class Character( object ):
def __init__( self ):
self.intelligence= 10
<default values for all attributes.>
```
Then your various Wizard instances just need to be given the underlying Character object as a place to put and get values.
|
Python-passing variable between classes
|
[
"",
"python",
"oop",
"variables",
"wxpython",
""
] |
im trying to locate the position of the minimum value in a vector, using STL find algorithm (and the min\_element algorithm), but instead of returning the postion, its just giving me the value. E.g, if the minimum value is it, is position will be returned as 8 etc. What am I doing wrong here?
```
int value = *min_element(v2.begin(), v2.end());
cout << "min value at position " << *find(v2.begin(), v2.end(), value);
```
|
`min_element` already gives you the iterator, no need to invoke `find` (additionally, it's inefficient because it's twice the work). Use `distance` or the `-` operator:
```
cout << "min value at " << min_element(v2.begin(), v2.end()) - v2.begin();
```
|
Both algorithms you're using return iterators. If you dereference an iterator, you get the object which is "pointed" by this iterator, which is why you print the *value* and not the *position* when doing
> ```
> cout << "min value at position " << *find(v2.begin(), v2.end(), value);
> ```
An iterator can be seen as a pointer (well, not exactly, but let's say so for the sake of simplicity); therefore, an iterator alone can't give you the position in the container. Since you're iterating a vector, you can use the minus operator, as Konrad said:
> ```
> cout << "min value at " << min_element(v2.begin(), v2.end()) - v2.begin();
> ```
but I would recommend using the std::distance algorithm, which is much more flexible and will work on all standard containers:
> ```
> cout << "min value at " << distance(v2.begin(), min_element(v2.begin(), v2.end()));
> ```
|
Position in Vector using STL
|
[
"",
"c++",
"stl",
""
] |
I have the following in my Global.asax.cs
```
routes.MapRoute(
"Arrival",
"{partnerID}",
new { controller = "Search", action = "Index", partnerID="1000" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
```
My SearchController looks like this
```
public class SearchController : Controller
{
// Display search results
public ActionResult Index(int partnerID)
{
ViewData["partnerID"] = partnerID;
return View();
}
}
```
and Index.aspx simply shows ViewData["partnerID"] at the moment.
I have a virtual directory set up in IIS on Windows XP called Test.
If I point my browser at <http://localhost/Test/> then I get 1000 displayed as expected. However, if I try <http://localhost/Test/1000> I get a page not found error. Any ideas?
Are there any special considerations for running MVC in a virtual directory?
|
IIS 5.1 interprets your url such that its looking for a folder named 1000 under the folder named Test. Why is that so?
> This happens because IIS 6 only
> invokes ASP.NET when it sees a
> “filename extension” in the URL that’s
> mapped to aspnet\_isapi.dll (which is a
> C/C++ ISAPI filter responsible for
> invoking ASP.NET). Since routing is a
> .NET IHttpModule called
> UrlRoutingModule, it doesn’t get
> invoked unless ASP.NET itself gets
> invoked, which only happens when
> aspnet\_isapi.dll gets invoked, which
> only happens when there’s a .aspx in
> the URL. So, no .aspx, no
> UrlRoutingModule, hence the 404.
Easiest solution is:
> If you don’t mind having .aspx in your
> URLs, just go through your routing
> config, adding .aspx before a
> forward-slash in each pattern. For
> example, use
> {controller}.aspx/{action}/{id} or
> myapp.aspx/{controller}/{action}/{id}.
> Don’t put .aspx inside the
> curly-bracket parameter names, or into
> the ‘default’ values, because it isn’t
> really part of the controller name -
> it’s just in the URL to satisfy IIS.
Source: <http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/>
|
If you are doing this on Windows XP, then you're using IIS 5.1. You need to get ASP.Net to handle your request. You need to either add an extension to your routes ({controller}.mvc/{action}/{id}) and map that extension to ASP.Net or map all requests to ASP.Net. The <http://localhost/Test> works because it goes to Default.aspx which is handled specially in MVC projects.
Additionally, you need to specify <http://localhost/Test/Search/Index/1000>. The controller and action pieces are not optional if you want to specify an ID.
|
ASP.NET MVC in a virtual directory
|
[
"",
"c#",
"asp.net-mvc",
"model-view-controller",
"iis-5",
""
] |
A friend of mine has embedded a google earth plugin into a C# user control. All works fine but when you close the window we recieve and "Unspecified Error" with the option to continue running the scripts or not. From our tracking it down it appears this is being cause by a script that google is dropping onto the page. Any ideas?
|
Here is an example, by me, of c#/Google Earth API integration that covers the problem you are having (see the comments)
<http://fraserchapman.blogspot.com/2008/08/google-earth-plug-in-and-c.html>
Also, here is another of my projects that uses COM Google Earth Plugin Type Library (plugin\_ax.dll) converted into the equivalent definitions in a common language run time assembly. It may be of some use. <http://fraserchapman.blogspot.com/2008/12/google-earth-plugin-control-library.html>
|
We have now tried this in both IE and FF. Works fine. Any ideas why the error only comes up on close? can we somehow disable it? here is our code.
```
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<html>
<head>
<script src="http://www.google.com/jsapi?key=ABQIAAAAzghEPRV_D0MDzTELJ4nkXBT2AlVLQD8Rz4_aVbiXesLoyhRIMBRo399nnxv9aY-fqnkVGgTgR-pTsg">
</script>
<script>
google.load("earth", "1");
var ge = null;
var placemark;
function init(){
google.earth.createInstance("map3d", initCallback, failureCallback);
}
function initCallback(object){
ge = object;
ge.getWindow().setVisibility(true);
ge.getNavigationControl().setVisibility(ge.VISIBILITY_SHOW);
ge.getLayerRoot().enableLayerById(ge.LAYER_TERRAIN, false);
placemark = ge.createPlacemark('');
placemark.setName("Current Position");
// Create style map for placemark
var normal = ge.createIcon('');
normal.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png');
var iconNormal = ge.createStyle('');
iconNormal.getIconStyle().setIcon(normal);
var highlight = ge.createIcon('');
highlight.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png');
var iconHighlight = ge.createStyle('');
iconHighlight.getIconStyle().setIcon(highlight);
var styleMap = ge.createStyleMap('');
styleMap.setNormalStyle(iconNormal);
styleMap.setHighlightStyle(iconHighlight);
placemark.setStyleSelector(styleMap);
var options = ge.getOptions();
options.setStatusBarVisibility(true);
options.setScaleLegendVisibility(true);
}
function failureCallback(object){
// Gracefully handle failure.
alert("Error");
}
function changeViewAngle(angle){
var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_ABSOLUTE);
lookAt.setTilt(angle);
ge.getView().setAbstractView(lookAt);
}
function ShowMarker(){
ge.getFeatures().appendChild(placemark);
}
function MoveMarker(lon, lat){
// Create point
var la = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
var point = ge.createPoint('');
point.setLatitude(lat);
point.setLongitude(lon);
placemark.setGeometry(point);
}
function HideMarker(){
ge.getFeatures().removeChild(placemark);
}
function SetPosition(lon, lat, heading){
var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
lookAt.setLatitude(lat);
lookAt.setLongitude(lon);
lookAt.setHeading(heading);
ge.getView().setAbstractView(lookAt);
}
function SetAltitude(alt){
var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
lookAt.set(lookAt.getLatitude(), lookAt.getLongitude(), 0, ge.ALTITUDE_RELATIVE_TO_GROUND, 0, lookAt.getTilt(), alt);
ge.getView().setAbstractView(lookAt);
}
function ResizeMap(w, h){
var map = document.getElementById('map3d_container');
map.style.height = h;
map.style.width = w;
}
function AddKML(kml){
var parseKML = ge.parseKml(kml);
ge.getFeatures().appendChild(parseKML);
return ge.getFeatures().getLastChild().getName();
}
function RemoveKML(kmlName){
if (ge.getFeatures().hasChildNodes()) {
var nodes = ge.getFeatures().getChildNodes();
for (var i = 0; i < nodes.getLength(); i++) {
var child = nodes.item(i);
if (child.getName() == kmlName) {
ge.getFeatures().removeChild(child);
}
}
}
}
function OptionsChanged(nav, status, scale, grid, map, terrain, road, border, building){
var options = ge.getOptions();
var form = document.options;
if (nav) {
ge.getNavigationControl().setVisibility(ge.VISIBILITY_SHOW);
}
else {
ge.getNavigationControl().setVisibility(ge.VISIBILITY_HIDE);
}
options.setStatusBarVisibility(status);
options.setScaleLegendVisibility(scale);
options.setGridVisibility(grid);
options.setOverviewMapVisibility(map);
ge.getLayerRoot().enableLayerById(ge.LAYER_TERRAIN, terrain);
ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, road);
ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, border);
ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, building);
}
</script>
</head>
<body onload='init()'>
<center>
<div id='map3d_container' style='border: 1px solid silver; height: 510px; width: 767px;'>
<DIV id=map3d style="HEIGHT: 100%">
</DIV>
</div>
</center>
</body>
</html>
```
|
C# Google Earth Error
|
[
"",
"c#",
"controls",
"google-earth-plugin",
""
] |
Suppose that two tables exist: `users` and `groups`.
**How does one provide "simple search" in which a user enters text and results contain both users and groups whose names contain the text?**
The result of the search must distinguish between the two types.
|
The trick is to combine a `UNION` with a literal string to determine the type of 'object' returned. In most (?) cases, UNION ALL will be more efficient, and should be used unless duplicates are required in the sub-queries. The following pattern should suffice:
```
SELECT "group" type, name
FROM groups
WHERE name LIKE "%$text%"
UNION ALL
SELECT "user" type, name
FROM users
WHERE name LIKE "%$text%"
```
**NOTE**: I've added the answer myself, because I came across this problem yesterday, couldn't find a good solution, and used this method. If someone has a better approach, please feel free to add it.
|
If you use "UNION ALL" then the db doesn't try to remove duplicates - you won't have duplicates between the two queries anyway (since the first column is different), so UNION ALL will be faster.
(I assume that you don't have duplicates inside each query that you want to remove)
|
How do I perform a simple one-statement SQL search across tables?
|
[
"",
"sql",
"search",
""
] |
Does anyone have experience with [**LLVM**](http://llvm.org/), [**llvm-gcc**](http://dragonegg.llvm.org/), or [**Clang**](http://clang.llvm.org/)?
The whole idea behind llvm seems very intriguing to me and I'm interested in seeing how it performs. I just don't want to dump a whole lot of time into trying the tools out if the tools are not ready for production.
If you have experience with the tools, what do you think of them? What major limitations have you encountered? What are the greatest benefits?
Many thanks!
|
I've had an initial play around with LLVM and working through [this tutorial](http://llvm.org/docs/tutorial/LangImpl1.html) left me very very excited about it's potential; the idea that I can use it to build a JIT into an app with relative ease has me stoked.
I haven't gone deep enough to be able to offer any kind of useful opinion on it's limitations, stability, performance and suchlike. I understand that it's good on all counts but that's purely hearsay.
|
I can't say enough good things about LLVM. It is so easy to work with compared to other compiler projects I have looked at. I am not a compiler guy, but when I get frustrated with some limitation of LLVM or clang it is usually pretty easy to dive in and change it.
We (Nate Begeman, myself, and a few others) wrote the PPC backend with no real experience in compiler design, but it looked simple enough that non-experts could approach it. We were pretty familiar with PPC assembly, but it was still pretty incredible we managed to get LLVM-gcc outputting PPC code in a few weeks of our spare time. Definitely one of the most satisfying Hello World's I have ever compiled.
|
What are the greatest benefits of LLVM?
|
[
"",
"c++",
"c",
"llvm",
"clang",
""
] |
**I do not currently have this issue**, but you never know, and thought experiments are always fun.
**Ignoring the obvious problems that you would have to have with your architecture to even be attempting this**, let's assume that you had some horribly-written code of someone else's design, and you needed to do a bunch of wide and varied operations in the same code block, e.g.:
```
WidgetMaker.SetAlignment(57);
contactForm["Title"] = txtTitle.Text;
Casserole.Season(true, false);
((RecordKeeper)Session["CasseroleTracker"]).Seasoned = true;
```
Multiplied by a hundred. Some of these might work, others might go badly wrong. What you need is the C# equivalent of "on error resume next", otherwise you're going to end up copying and pasting try-catches around the many lines of code.
How would you attempt to tackle this problem?
|
It's pretty obvious that you'd write the code in VB.NET, which actually does have [On Error Resume Next](http://msdn.microsoft.com/en-us/library/5hsw66as.aspx), and export it in a DLL to C#. Anything else is just being a glutton
for punishment.
|
```
public delegate void VoidDelegate();
public static class Utils
{
public static void Try(VoidDelegate v) {
try {
v();
}
catch {}
}
}
Utils.Try( () => WidgetMaker.SetAlignment(57) );
Utils.Try( () => contactForm["Title"] = txtTitle.Text );
Utils.Try( () => Casserole.Season(true, false) );
Utils.Try( () => ((RecordKeeper)Session["CasseroleTracker"]).Seasoned = true );
```
|
Try-catch every line of code without individual try-catch blocks
|
[
"",
"c#",
"try-catch",
"expression-trees",
""
] |
Many languages have standard repositories where people donate useful libraries that they want others to have access to. For instance Perl has CPAN, PHP has PEAR, Ruby has RubyGems, and so on. What is the best option for JavaScript?
I ask because a few months ago I ported [Statistics::Distributions](http://search.cpan.org/~mikek/Statistics-Distributions-1.02/Distributions.pm) from Perl to JavaScript. (When I say ported I mean, "Ran text substitutions, fixed a few things by hand." I did *not* rewrite it.) Since I've used this module a number of times in Perl, I figure that [statistics-distributions.js](http://elem.com/~btilly/effective-ab-testing/statistics-distributions.js) is likely to be useful to someone. So I've put it under the same open source license as the original (your choice of the GPL or the Artistic License). But I have no idea where to put it so that people who might want it are likely to find it.
It doesn't fit into any sort of framework. It is just a standalone library that gives you the ability to calculate a number of useful statistics distributions to 5 digits of accuracy. In JavaScript.
|
AFAIK, there is no central JavaScript repository, but you might have success promoting it on [Snipplr](http://snipplr.com/) or as a project on [Google Code](http://code.google.com/).
|
[JSAN (JavaScript Archive Network)](http://openjsan.org) sounds like the kind of thing you're looking for, but I've never personally used anything from it apart from Test.Builder.
As long as your JavaScript can be dropped in to people's projects without polluting the global namespace or doing things which are liable to cause breakage in other people's code (adding to Object.prototype, for example) I would just stick it somewhere like Google Code as already suggested.
|
What JavaScript Repository should I use?
|
[
"",
"javascript",
"open-source",
""
] |
How do I locate resources on the classpath in java?
Specifically stuff that ends in .hbm.xml.
My goal is to get a List of all resources on the classpath that end with ".hbm.xml".
|
You have to get a [classloader](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#getContextClassLoader()), and test whether it's a URLClassLoader. If so, downcast and [get its URLs](http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLClassLoader.html#getURLs()). From there, open each as a JarFile and look at its [entries](http://java.sun.com/j2se/1.5.0/docs/api/java/util/jar/JarFile.html#entries()). Apply a [regex](http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html) to each entry and see if it's one that interests you.
Clearly, this isn't fast. It's best to be given a name to be looked up in the classpath, perhaps listed in a standard file name in the META-INF directory of each classpath element, similar to the technique used by the [ServiceProvider facility](http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html#Service%20Provider). Note that you can [list all files](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ClassLoader.html#getResources(java.lang.String)) with a given name on the classpath.
|
Method `findClasses` from our `ClassLoaderUtil` might be a good starting point to adapt to your needs.
```
public class ClassLoaderUtil {
/**
* Recursive method used to find all classes in a given path (directory or zip file url). Directories
* are searched recursively. (zip files are
* Adapted from http://snippets.dzone.com/posts/show/4831 and extended to support use of JAR files
*
* @param path The base directory or url from which to search.
* @param packageName The package name for classes found inside the base directory
* @param regex an optional class name pattern. e.g. .*Test
* @return The classes
*/
private static TreeSet<String> findClasses(String path, String packageName, Pattern regex) throws Exception {
TreeSet<String> classes = new TreeSet<String>();
if (path.startsWith("file:") && path.contains("!")) {
String[] split = path.split("!");
URL jar = new URL(split[0]);
ZipInputStream zip = new ZipInputStream(jar.openStream());
ZipEntry entry;
while ((entry = zip.getNextEntry()) != null) {
if (entry.getName().endsWith(".class")) {
String className = entry.getName().replaceAll("[$].*", "").replaceAll("[.]class", "").replace('/', '.');
if (className.startsWith(packageName) && (regex == null || regex.matcher(className).matches()))
classes.add(className);
}
}
}
File dir = new File(path);
if (!dir.exists()) {
return classes;
}
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
assert !file.getName().contains(".");
classes.addAll(findClasses(file.getAbsolutePath(), packageName + "." + file.getName(), regex));
} else if (file.getName().endsWith(".class")) {
String className = packageName + '.' + file.getName().substring(0, file.getName().length() - 6);
if (regex == null || regex.matcher(className).matches())
classes.add(className);
}
}
return classes;
}
public static <T> List<T> instances(Class<? extends T>[] classList) {
List<T> tList = new LinkedList<T>();
for(Class<? extends T> tClass : classList) {
try {
// Only try to instantiate real classes.
if(! Modifier.isAbstract(tClass.getModifiers()) && ! Modifier.isInterface(tClass.getModifiers())) {
tList.add(tClass.newInstance());
}
} catch (Throwable t) {
throw new RuntimeException(t.getMessage(), t);
}
}
return tList;
}
public static Class[] findByPackage(String packageName, Class isAssignableFrom) {
Class[] clazzes = getClassesInPackage(packageName, null);
if(isAssignableFrom == null) {
return clazzes;
} else {
List<Class> filteredList = new ArrayList<Class>();
for(Class clazz : clazzes) {
if(isAssignableFrom.isAssignableFrom(clazz))
filteredList.add(clazz);
}
return filteredList.toArray(new Class[0]);
}
}
/**
* Scans all classes accessible from the context class loader which belong to the given package and subpackages.
* Adapted from http://snippets.dzone.com/posts/show/4831 and extended to support use of JAR files
*
* @param packageName The base package
* @param regexFilter an optional class name pattern.
* @return The classes
*/
public static Class[] getClassesInPackage(String packageName, String regexFilter) {
Pattern regex = null;
if (regexFilter != null)
regex = Pattern.compile(regexFilter);
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
assert classLoader != null;
String path = packageName.replace('.', '/');
Enumeration<URL> resources = classLoader.getResources(path);
List<String> dirs = new ArrayList<String>();
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
dirs.add(resource.getFile());
}
TreeSet<String> classes = new TreeSet<String>();
for (String directory : dirs) {
classes.addAll(findClasses(directory, packageName, regex));
}
ArrayList<Class> classList = new ArrayList<Class>();
for (String clazz : classes) {
classList.add(Class.forName(clazz));
}
return classList.toArray(new Class[classes.size()]);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
```
|
How do I locate resources on the classpath in java? Specifically stuff that ends in .hbm.xml
|
[
"",
"java",
""
] |
Is there any easy way to retrieve table creation DDL from Microsoft Access (2007) or do I have to code it myself using VBA to read the table structure?
I have about 30 tables that we are porting to Oracle and it would make life easier if we could create the tables from the Access definitions.
|
Thanks for the other suggestions. While I was waiting I wrote some VBA code to do it. It's not perfect, but did the job for me.
```
Option Compare Database
Public Function TableCreateDDL(TableDef As TableDef) As String
Dim fldDef As Field
Dim FieldIndex As Integer
Dim fldName As String, fldDataInfo As String
Dim DDL As String
Dim TableName As String
TableName = TableDef.Name
TableName = Replace(TableName, " ", "_")
DDL = "create table " & TableName & "(" & vbCrLf
With TableDef
For FieldIndex = 0 To .Fields.Count - 1
Set fldDef = .Fields(FieldIndex)
With fldDef
fldName = .Name
fldName = Replace(fldName, " ", "_")
Select Case .Type
Case dbBoolean
fldDataInfo = "nvarchar2"
Case dbByte
fldDataInfo = "number"
Case dbInteger
fldDataInfo = "number"
Case dbLong
fldDataInfo = "number"
Case dbCurrency
fldDataInfo = "number"
Case dbSingle
fldDataInfo = "number"
Case dbDouble
fldDataInfo = "number"
Case dbDate
fldDataInfo = "date"
Case dbText
fldDataInfo = "nvarchar2(" & Format$(.Size) & ")"
Case dbLongBinary
fldDataInfo = "****"
Case dbMemo
fldDataInfo = "****"
Case dbGUID
fldDataInfo = "nvarchar2(16)"
End Select
End With
If FieldIndex > 0 Then
DDL = DDL & ", " & vbCrLf
End If
DDL = DDL & " " & fldName & " " & fldDataInfo
Next FieldIndex
End With
DDL = DDL & ");"
TableCreateDDL = DDL
End Function
Sub ExportAllTableCreateDDL()
Dim lTbl As Long
Dim dBase As Database
Dim Handle As Integer
Set dBase = CurrentDb
Handle = FreeFile
Open "c:\export\TableCreateDDL.txt" For Output Access Write As #Handle
For lTbl = 0 To dBase.TableDefs.Count - 1
'If the table name is a temporary or system table then ignore it
If Left(dBase.TableDefs(lTbl).Name, 1) = "~" Or _
Left(dBase.TableDefs(lTbl).Name, 4) = "MSYS" Then
'~ indicates a temporary table
'MSYS indicates a system level table
Else
Print #Handle, TableCreateDDL(dBase.TableDefs(lTbl))
End If
Next lTbl
Close Handle
Set dBase = Nothing
End Sub
```
I never claimed to be VB programmer.
|
I've done this:
There's a tool for "upsizing" from Access to SQL Server. Do that, then use the excellent SQL Server tools to generate the script.
<http://support.microsoft.com/kb/237980>
|
Table Creation DDL from Microsoft Access
|
[
"",
"sql",
"ms-access",
""
] |
I know Googling I can find an appropriate answer, but I prefer listening to your personal (and maybe technical) opinions.
**What is the main reason of the difference between Java and C# in throwing exceptions?**
In Java the signature of a method that throws an exception has to use the "throws" keyword, while in C# you don't know in compilation time if an exception could be thrown.
|
Because the response to checked exceptions is almost always:
```
try {
// exception throwing code
} catch(Exception e) {
// either
log.error("Error fooing bar",e);
// OR
throw new RuntimeException(e);
}
```
If you actually know that there is something you can do if a particular exception is thrown, then you can catch it and then handle it, but otherwise it's just incantations to appease the compiler.
|
In the article [The Trouble with Checked Exceptions](http://www.artima.com/intv/handcuffs.html) and in Anders Hejlsberg's (designer of the C# language) own voice, there are three main reasons for C# not supporting checked exceptions as they are found and verified in Java:
* **Neutral on Checked Exceptions**
> “C# is basically silent on the checked
> exceptions issue. Once a better
> solution is known—and trust me we
> continue to think about it—we can go
> back and actually put something in
> place.”
* **Versioning with Checked Exceptions**
> “Adding a new exception to a throws
> clause in a new version breaks client
> code. It's like adding a method to an
> interface. After you publish an
> interface, it is for all practical
> purposes immutable, …”
> “It is funny how people think that the
> important thing about exceptions is
> handling them. That is not the
> important thing about exceptions. In a
> well-written application there's a
> ratio of ten to one, in my opinion, of
> try finally to try catch. Or in C#,
> [`using`](http://msdn.microsoft.com/en-us/library/aa664736.aspx) statements, which are
> like try finally.”
* **Scalability of Checked Exceptions**
> “In the small, checked exceptions are
> very enticing…The trouble
> begins when you start building big
> systems where you're talking to four
> or five different subsystems. Each
> subsystem throws four to ten
> exceptions. Now, each time you walk up
> the ladder of aggregation, you have
> this exponential hierarchy below you
> of exceptions you have to deal with.
> You end up having to declare 40
> exceptions that you might throw.…
> It just balloons out of control.”
In his article, “[Why doesn't C# have exception specifications?](http://msdn.microsoft.com/en-us/vcsharp/aa336812.aspx)”, [Anson Horton](http://blogs.msdn.com/ansonh/) (Visual C# Program Manager) also lists the following reasons (see the article for details on each point):
* Versioning
* Productivity and code quality
* Impracticality of having class author differentiate between
*checked* and *unchecked* exceptions
* Difficulty of determining the correct exceptions for interfaces.
It is interesting to note that C# does, nonetheless, support documentation of exceptions thrown by a given method via the [`<exception>`](http://msdn.microsoft.com/en-us/library/w1htk11d.aspx) tag and the compiler even takes the trouble to verify that the referenced exception type does indeed exist. There is, however, no check made at the call sites or usage of the method.
You may also want to look into the [Exception Hunter](http://www.red-gate.com/products/exception_hunter/index.htm), which is a commerical tool by [Red Gate Software](http://www.red-gate.com/), that uses static analysis to determine and report exceptions thrown by a method and which may potentially go uncaught:
> Exception Hunter is a new analysis
> tool that finds and reports the set of
> possible exceptions your functions
> might throw – before you even ship.
> With it, you can locate unhandled
> exceptions easily and quickly, down to
> the line of code that is throwing the
> exceptions. Once you have the results,
> you can decide which exceptions need
> to be handled (with some exception
> handling code) before you release your
> application into the wild.
Finally, [Bruce Eckel](https://www.mindviewllc.com/about/), author of [Thinking in Java](https://rads.stackoverflow.com/amzn/click/com/0131872486), has an article called, “[Does Java need Checked Exceptions?](https://web.archive.org/web/20180516002915/http://www.mindview.net/Etc/Discussions/CheckedExceptions)”, that may be worth reading up as well because the question of why checked exceptions are not there in C# usually takes root in comparisons to Java.
|
Why are Exceptions not Checked in .NET?
|
[
"",
"java",
".net",
"exception",
""
] |
I have a class in system-C with some data members as such:
```
long double x[8];
```
I'm initializing it in the construction like this:
```
for (i = 0; i < 8; ++i) {
x[i] = 0;
}
```
But the first time I use it in my code I have garbage there.
Because of the way the system is built I can't connect a debugger easily. Are there any methods to set a data breakpoint in the code so that it tells me where in the code the variables were actually changed, but without hooking up a debugger?
|
You could try starting a second thread which spins, looking for changes in the variable:
```
#include <pthread.h>
void *ThreadProc(void *arg)
{
volatile long double *x = (volatile long double *)arg;
while(1)
{
for(int i = 0; i < 8; i++)
{
if(x[i] != 0)
{
__asm__ __volatile__ ("int 3"); // breakpoint (x86)
}
}
return 0; // Never reached, but placate the compiler
}
...
pthread_t threadID;
pthread_create(&threadID, NULL, ThreadProc, &x[0]);
```
This will raise a SIGTRAP signal to your application whenever any of the x values is not zero.
|
Just use [printk/syslog](http://linux.die.net/man/2/syslog).
It's old-fashioned, but super duper easy.
|
Can I set a data breakpoint in runtime in System C (or in Plain Vanilla C++)?
|
[
"",
"c++",
"linux",
"debugging",
""
] |
We've got a scenario that requires us to parse lots of e-mail (plain text), each e-mail 'type' is the result of a script being run against various platforms. Some are tab delimited, some are space delimited, some we simply don't know yet.
We'll need to support more 'formats' in the future too.
Do we go for a solution using:
* Regex
* Simply string searching (using string.IndexOf etc)
* Lex/ Yacc
* Other
The overall solution will be developed in C# 2.0 (hopefully 3.5)
|
The three solutions you stated each cover very different needs.
**Manual parsing** (simple text search) is the most flexible and the most adaptable, however, it very quickly becomes a real pain in the ass as the parsing required is more complicated.
**Regex** are a middle ground, and probably your best bet here. They are powerful, yet flexible as you can yourself add more logic from the code that call the different regex. The main drawback would be speed here.
**Lex/Yacc** is really only adapted to very complicated, predictable syntaxes and lacks a lot of post compile flexibility. You can't easily change parser in mid parsing, well actually you can but it's just too heavy and you'd be better using regex instead.
I know this is a cliché **answer**, it all really comes down to what your exact needs are, but from what you said, I would personally probably go with a bag of regex.
As an **alternative**, as Vaibhav poionted out, if you have several different situations that can arise and that you cna easily detect which one is coming, you could make a plugin system that chooses the right algorithm, and those algorithms could all be very different, one using Lex/Yacc in pointy cases and the other using IndexOf and regex for simpler cases.
|
Regex.
Regex can solve almost everything except for world peace. Well maybe world peace too.
|
What's the best way of parsing strings?
|
[
"",
"c#",
"email",
"parsing",
"projects-and-solutions",
""
] |
There is a way to keep the scroll on bottom for a multi line textbox?
Something like in the vb6
```
txtfoo.selstart=len(txtfoo.text)
```
I'm trying with txtfoo.selectionstart=txtfoo.text.length without success.
Regards.
|
Ok, I found that the solution was to use
```
txtfoo.AppendText
```
instead of
```
txtfoo.text+="something"
```
|
The other solution is to use:
```
txtfoo.Text += "something";
txtfoo.SelectionStart = txtfoo.Text.Length;
txtfoo.ScrollToCaret();
```
|
Scroll of a texbox always on bottom
|
[
"",
"c#",
"winforms",
""
] |
I have an RFID reader connected to an Arduino board. I'd like to connect to it over its serial interface, and whenever the RFID reader omits a signal ( when it has read an (RF)ID ), I'd like to retrieve it in my C++ program.
I already have the code for simply printing the RFID to serial from the Arduino.
What I don't know, is *how to read it from C++* in Linux ?
I have looked at **libserial**, which looks straightforward. However, how can I *have the C++ program react to a signal and then read the RFID*, instead of listening continously? Is this necessary?
EDIT: In most examples I have read, the (c++) program sends input, and recieves output. I just want to listen and recieve output from the Arduino.
|
I found the Boost::Asio library, which reads from serial interfaces asynchronously. [Boost::Asio Documentation](http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio.html)
|
On unix you use the select() call to wait for an input.
The select() call acts like a sleep - using no CPU until the kernel receives the hardware interrupt and triggers the select().
<http://tldp.org/HOWTO/Serial-Programming-HOWTO/index.html>
|
How to communicate with an Arduino over its serial interface in C++ on Linux?
|
[
"",
"c++",
"linux",
"serial-port",
"arduino",
"rfid",
""
] |
In my tests I need to test what happens when an OracleException is thrown (due to a stored procedure failure). I am trying to setup Rhino Mocks to
```
Expect.Call(....).Throw(new OracleException());
```
For whatever reason however, OracleException seems to be sealed with no public constructor. What can I do to test this?
**Edit:** Here is exactly what I'm trying to instantiate:
```
public sealed class OracleException : DbException {
private OracleException(string message, int code) { ...}
}
```
|
It seems that Oracle changed their constructors in later versions, therefore the solution above will not work.
If you only want to set the error code, the following will do the trick for 2.111.7.20:
```
ConstructorInfo ci = typeof(OracleException)
.GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
new Type[] { typeof(int) },
null
);
Exception ex = (OracleException)ci.Invoke(new object[] { 3113 });
```
|
Here is how you do it:
```
ConstructorInfo ci = typeof(OracleException).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] {typeof(string), typeof(int)}, null);
var c = (OracleException)ci.Invoke(new object[] { "some message", 123 });
```
Thanks to all that helped, you have been upvoted
|
How can I mock/fake/stub sealed OracleException with no public constructor?
|
[
"",
"c#",
".net",
"oracle",
"mocking",
"oracleclient",
""
] |
Are C++ enums signed or unsigned? And by extension is it safe to validate an input by checking that it is <= your max value, and leave out >= your min value (assuming you started at 0 and incremented by 1)?
|
You shouldn't rely on any specific representation. Read the following [link](http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.19). Also, the standard says that it is implementation-defined which integral type is used as the underlying type for an enum, except that it shall not be larger than int, unless some value cannot fit into int or an unsigned int.
In short: you cannot rely on an enum being either signed or unsigned.
|
Let's go to the source. Here's what the C++03 standard (ISO/IEC 14882:2003) document says in 7.2-5 (Enumeration declarations):
> The underlying type of an enumeration
> is an integral type that can represent
> all the enumerator values defined in
> the enumeration. It is
> implementation-defined which integral
> type is used as the underlying type
> for an enumeration except that the
> underlying type shall not be larger
> than int unless the value of an
> enumerator cannot fit in an int or
> unsigned int.
In short, your compiler gets to choose (obviously, if you have negative numbers for some of your ennumeration values, it'll be signed).
|
Are C++ enums signed or unsigned?
|
[
"",
"c++",
"enums",
""
] |
One thing I am concerned with is that I discovered two ways of registering delegates to events.
1. OnStuff += this.Handle;
2. OnStuff += new StuffEventHandler(this.Handle);
The first one is clean, and it makes sense doing "OnStuff -= this.Handle;" to unregister from the event... But with the latter case, should I do "OnStuff -= new StuffEventHandler(this.Handle);"? It feels like I am not removing anything at all, since I'm throwing in another StuffEventHandler reference. Does the event compare the delegate by reference? I am concerned I could start a nasty memory pool here. Get me? I don't have the reference to the "new StuffEventHandler" I previously registered.
What is the downside of doing #1?
What is benefit of doing #2?
|
You don't need to worry about keeping a reference to the originally registered delegate, and you will not start a "nasty memory pool".
When you call "OnStuff -= new StuffEventHandler(this.Handle);" the removal code does *not* compare the delegate you are removing by reference: it checks for equality by comparing references to the target method(s) that the delegate will call, and removes the matching delegates from "OnStuff".
By the way, "OnStuff" itself is a delegate object (the event keyword that I assume you have in your declaration simply restricts the accessibility of the delegate).
|
Number one is just shorthand that will generate the same MSIL as the 2nd one, at compile type it'll look at this.Handle and infer the delegate to instantiate. But you should never unsubscribe by using new.
So there is no difference between the 2, just some syntactic sugar to make our code cleaner.
|
Is it safe to add delegates to events with keyword new?
|
[
"",
"c#",
".net",
"events",
"delegates",
""
] |
I am developping a (relatively small) website in ASP.Net 2.0. I am also using nAnt to perform some easy tweaking on my project before delivering executables. In its current state, the website is "precompiled" using
> `aspnet_compiler.exe -nologo -v ${Appname} -u ${target}`
I have noticed that after the IIS pool is restarted (after a idle shutdown or a recycle), the application takes up to 20 seconds before it is back online (and Application\_start is reached).
I don't have the same issue when I am debugging directly within Visual Studio (it takes 2 seconds to start) so I am wondering if the aspnet\_compiler is really such a good idea.
I couldn't find much on MSDN. How do you compile your websites for production?
|
Make sure that:
1. You are using a Web Application project rather than a Web Site project, this will result in a precompiled binary for your code behind
2. You have turned off debug code generation in the web.config file - I guess if this is different to when you used aspnet\_compiler the code may be recompiled
If you've tried those, you could maybe try running ngen over your assembly thus saving the JIT time?
|
For ultimate reponsiveness, don't allow your app to be shutdown.
The first method is to make sure that it's incredibly popular so that there's always someone using it.
Alternatively, fetching a tiny keep-alive page from somewhere else as a scheduled activity can be used to keep your site 'hot'.
|
Precompilation and startup times on ASP.Net
|
[
"",
"c#",
"asp.net",
"compilation",
"startup",
"aspnet-compiler",
""
] |
I wrote a sample program at <http://codepad.org/ko8vVCDF> that uses a template function.
How do I retrict the template function to only use numbers? (int, double etc.)
```
#include <vector>
#include <iostream>
using namespace std;
template <typename T>
T sum(vector<T>& a)
{
T result = 0;
int size = a.size();
for(int i = 0; i < size; i++)
{
result += a[i];
}
return result;
}
int main()
{
vector<int> int_values;
int_values.push_back(2);
int_values.push_back(3);
cout << "Integer: " << sum(int_values) << endl;
vector<double> double_values;
double_values.push_back(1.5);
double_values.push_back(2.1);
cout << "Double: " << sum(double_values);
return 0;
}
```
|
The only way to restrict a template is to make it so that it uses something from the types that you want, that other types don't have.
So, you construct with an int, use + and +=, call a copy constructor, etc.
Any type that has all of these will work with your function -- so, if I create a new type that has these features, your function will work on it -- which is great, isn't it?
If you want to restrict it more, use more functions that only are defined for the type you want.
Another way to implement this is by creating a traits template -- something like this
```
template<class T>
SumTraits
{
public:
const static bool canUseSum = false;
}
```
And then specialize it for the classes you want to be ok:
```
template<>
class SumTraits<int>
{
public:
const static bool canUseSum = true;
};
```
Then in your code, you can write
```
if (!SumTraits<T>::canUseSum) {
// throw something here
}
```
edit: as mentioned in the comments, you can use BOOST\_STATIC\_ASSERT to make it a compile-time check instead of a run-time one
|
This is possible by using [SFINAE](https://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error), and made easier by using helpers from either Boost or C++11
Boost:
```
#include <vector>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_arithmetic.hpp>
template<typename T>
typename boost::enable_if<typename boost::is_arithmetic<T>::type, T>::type
sum(const std::vector<T>& vec)
{
typedef typename std::vector<T>::size_type size_type;
T result;
size_type size = vec.size();
for(size_type i = 0; i < size; i++)
{
result += vec[i];
}
return result;
}
```
C++11:
```
#include <vector>
#include <type_traits>
template<typename T>
typename std::enable_if<std::is_arithmetic<T>::value, T>::type
sum(const std::vector<T>& vec)
{
T result;
for (auto item : vec)
result += item;
return result;
}
```
|
Restrict Template Function
|
[
"",
"c++",
"templates",
""
] |
Been running into this problem lately... When debugging an app in VS.Net 2005, breakpoints are not connected. Error indicates that the compiled code is not the same as the running version and therefore there's a mismatch that causes the breakpoint to be disconnected.
Cleaned solution of all bin file and re-compile doesn't help. Not just happening on a single box or person either.
Added Note:
This solution is in TFS for Source Control. If I delete my local TFS repository and get it from source control from scratch, SOMETIMES the problem goes away. I've also tried un-installing and re-installed Visual Studio. That also SOMETIMES helps. That fact that both of those work some of the time indicates that the problem isn't caused by either directly.
|
Maybe this suggestion might help:
1. While debugging in Visual Studio, click on Debug > Windows > Modules. The IDE will dock a Modules window, showing all the modules that have been loaded for your project.
2. Look for your project's DLL, and check the Symbol Status for it.
3. If it says Symbols Loaded, then you're golden. If it says something like Cannot find or open the PDB file, right-click on your module, select Load Symbols, and browse to the path of your PDB.
I've found that it's sometimes necessary to:
1. stop the debugger
2. close the IDE
3. close the hosting application
4. nuke the obj and bin folders
5. restart the IDE
6. rebuild the project
7. go through the Modules window again
8. Once you browse to the location of your PDB file, the Symbol Status should change to Symbols Loaded, and you should now be able to set and catch a breakpoint at your line in code.
Source: [The breakpoint will not currently be hit. No symbols have been loaded for this document.](https://web.archive.org/web/20201024041557/http://geekswithblogs.net/dbutscher/archive/2007/06/26/113472.aspx)
|
<http://dpotter.net/Technical/2009/05/upgrading-to-ie8-breaks-debugging-with-visual-studio-2005/>
|
Breakpoint not hooked up when debugging in VS.Net 2005
|
[
"",
"c#",
"debugging",
"visual-studio-2005",
"breakpoints",
""
] |
I'm trying to pass in a Base64 string into a C#.Net web application via the QueryString. When the string arrives the "+" (plus) sign is being replaced by a space. It appears that the automatic URLDecode process is doing this. I have no control over what is being passed via the QueryString. Is there any way to handle this server side?
Example:
```
http://localhost:3399/Base64.aspx?VLTrap=VkxUcmFwIHNldCB0byAiRkRTQT8+PE0iIHBsdXMgb3IgbWludXMgNSBwZXJjZW50Lg==
```
Produces:
```
VkxUcmFwIHNldCB0byAiRkRTQT8 PE0iIHBsdXMgb3IgbWludXMgNSBwZXJjZW50Lg==
```
People have suggested URLEncoding the querystring:
```
System.Web.HttpUtility.UrlEncode(yourString)
```
I can't do that as I have no control over the calling routine (which is working fine with other languages).
There was also the suggestion of replacing spaces with a plus sign:
```
Request.QueryString["VLTrap"].Replace(" ", "+");
```
I had though of this but my concern with it, and I should have mentioned this to start, is that I don't know what *other* characters might be malformed in addition to the plus sign.
***My main goal is to intercept the QueryString before it is run through the decoder.***
To this end I tried looking at Request.QueryString.toString() but this contained the same malformed information. Is there any way to look at the raw QueryString *before* it is URLDecoded?
After further testing it appears that .Net expects everything coming in from the QuerString to be URL encoded but the browser does not automatically URL encode GET requests.
|
You could manually replace the value (`argument.Replace(' ', '+')`) or consult the `HttpRequest.ServerVariables["QUERY_STRING"]` (even better the HttpRequest.Url.Query) and parse it yourself.
You should however try to solve the problem where the URL is given; a plus sign needs to get encoded as "%2B" in the URL because a plus otherwise represents a space.
If you don't control the inbound URLs, the first option would be preferred as you avoid the most errors this way.
|
The suggested solution:
```
Request.QueryString["VLTrap"].Replace(" ", "+");
```
Should work just fine. As for your concern:
> I had though of this but my concern with it, and I should have mentioned this to start, is that I don't know what other characters might be malformed in addition to the plus sign.
This is easy to alleviate by [reading about base64](http://en.wikipedia.org/wiki/Base64). The only non alphanumeric characters that are legal in modern base64 are "/", "+" and "=" (which is only used for padding).
Of those, "+" is the only one that has special meaning as an escaped representation in URLs. While the other two have special meaning in URLs (path delimiter and query string separator), they shouldn't pose a problem.
So I think you should be OK.
|
QueryString malformed after URLDecode
|
[
"",
"c#",
"asp.net",
"url",
""
] |
In SQL Server 2005, are there any disadvantages to making all character fields nvarchar(MAX) rather than specifying a length explicitly, e.g. nvarchar(255)? (Apart from the obvious one that you aren't able to limit the field length at the database level)
|
Same question was asked on MSDN Forums:
* [Varchar(max) vs Varchar(255)](https://social.msdn.microsoft.com/Forums/sqlserver/en-US/4d9c6504-496e-45ba-a7a3-ed5bed731fcc/varcharmax-vs-varchar255)
From the original post (much more information there):
> When you store data to a VARCHAR(N) column, the values are physically stored in the same way. But when you store it to a VARCHAR(MAX) column, behind the screen the data is handled as a TEXT value. So there is some additional processing needed when dealing with a VARCHAR(MAX) value. (only if the size exceeds 8000)
>
> VARCHAR(MAX) or NVARCHAR(MAX) is considered as a 'large value type'. Large value types are usually stored 'out of row'. It means that the data row will have a pointer to another location where the 'large value' is stored...
|
Based on the link provided in the accepted answer it appears that:
1. 100 characters stored in an `nvarchar(MAX)` field will be stored no different to 100 characters in an `nvarchar(100)` field - the data will be stored inline and you will not have the overhead of reading and writing data 'out of row'. So no worries there.
2. If the size is greater than 4000 the data would be stored 'out of row' automatically, which is what you would want. So no worries there either.
However...
3. You cannot create an index on an `nvarchar(MAX)` column. You can use full-text indexing, but you cannot create an index on the column to improve query performance. For me, this seals the deal...it is a definite disadvantage to always use nvarchar(MAX).
Conclusion:
If you want a kind of "universal string length" throughout your whole database, which can be indexed and which will not waste space and access time, then you could use `nvarchar(4000)`.
|
Are there any disadvantages to always using nvarchar(MAX)?
|
[
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I've seen a few different ways to iterate over a dictionary in C#. Is there a standard way?
|
```
foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
```
|
If you are trying to use a generic Dictionary in C# like you would use an associative array in another language:
```
foreach(var item in myDictionary)
{
foo(item.Key);
bar(item.Value);
}
```
Or, if you only need to iterate over the collection of keys, use
```
foreach(var item in myDictionary.Keys)
{
foo(item);
}
```
And lastly, if you're only interested in the values:
```
foreach(var item in myDictionary.Values)
{
foo(item);
}
```
(Take note that the `var` keyword is an optional C# 3.0 and above feature, you could also use the exact type of your keys/values here)
|
How to iterate over a dictionary?
|
[
"",
"c#",
"dictionary",
"loops",
""
] |
Why does the code below return true only for a = 1?
```
main(){
int a = 10;
if (true == a)
cout<<"Why am I not getting executed";
}
```
|
When a Bool true is converted to an int, it's always converted to 1. Your code is thus, equivalent to:
```
main(){
int a = 10;
if (1 == a)
cout<<"y i am not getting executed";
}
```
This is part of the [C++ standard](http://www.bond.id.au/~gnb/wp/cd2/conv.html), so it's something you would expect to happen with every C++ standards compliant compiler.
|
The reason your print statement is not getting executed is because your boolean is getting implicitly converted to a number instead of the other way around. I.e. your if statement is equivalent to this: if (1 == a)
You could get around this by first explicitly converting it to a boolean:
```
main(){
int a = 10;
if (((bool)a) == true)
cout<<"I am definitely getting executed";
}
```
In C/C++ false is represented as 0.
Everything else is represented as non zero. That is sometimes 1, sometimes anything else.
So you should never test for equality (==) to something that is true.
Instead you should test for equality to something that is false. Since false has only 1 valid value.
Here we are testing for all non false values, any of them is fine:
```
main(){
int a = 10;
if (a)
cout<<"I am definitely getting executed";
}
```
And one third example just to prove that it is safe to compare any integer that is considered false to a false (which is only 0):
```
main(){
int a = 0;
if (0 == false)
cout<<"I am definitely getting executed";
}
```
|
Why does the code below return true only for a = 1?
|
[
"",
"c++",
"conditional-statements",
""
] |
I need to scramble the names and logins of all the users in a UAT database we have. (because of the data protection act)
However, there is a catch.
The testers still need to be able to login using the hashed login names
so if a user login is "Jesse.J.James" then the hash should be something like
Ypois.X.Qasdf
i.e. approximately the same length, with the dots in the same place
so MD5, sha1 etc would not be suitable as they would create very long strings and also add their own special characters such as + and = which are not allowed by the validation regex.
So I'm looking for some suggestions as to how to achieve this
I guess I need to rollmy own hashing algorith
anyone done anything similar?
I am using c# but I guess that is not so important to the algorithm
thanks alot
**ADDED -**
Thanks for all the answers. I think I am responsible for the confusion by using the word "Hash" when that is not what needed to be done
|
You do not need to hash the data. You should just randomize it so it has no relation to the original data.
For example, update all the login names, and replace each letter with another random letter.
|
Testers should NOT be logging in as legitimate users. That would clearly violate the non-repudiation requirement of whatever data protection act you're working under.
The system should not allow anyone to log in using the hashed value. That defeats the whole purpose of hashing!
I'm sorry I am not answering your specific question, but I really think your whole testing system should be reevaluated.
**ADDED:**
The comments below by JPLemme shed a lot of light on what you are doing, and I'm afraid that I completely misunderstood (as did those who voted for me, presumably).
Part of the confusion is based on the fact that hashes are typically used to scramble passwords so that no one can discover what another person's password is, including those working on the system. That is, evidently, the wrong context (and now I understand why you are hashing usernames instead of just passwords). As JPLemme has pointed out, you are actually working with a completely separate parrallel system into which live data has been copied and anonymized, and the secure login process that uses hashed (and salted!) passwords will not be molested.
In that case, WW's answer below is more relevant, and I recommend everyone to give your up votes to him/her instead. I'm sorry I misunderstood.
|
hashing sensitive data
|
[
"",
"c#",
"encryption",
"hash",
""
] |
I have a set of callback classes that I use for handling callbacks with variable numbers of parameters. Right now I have about 6 different instances of it to handle differing numbers of arguments. Is there a way to make one instance than can handle a variable number of arguments?? Ultimately I would love to have each parameter be a POD type or a class pointer, or a struct pointer. Any ideas?
```
template <class T>
class kGUICallBackPtr
{
public:
kGUICallBackPtr() {m_obj=0;m_func=0;}
void Set(void *o,void (*f)(void *,T *));
inline void Call(T *i) {if(m_func) m_func(m_obj,i);}
inline bool IsValid(void) {return (m_func!=0);}
private:
void *m_obj;
void (*m_func)(void *,T *);
};
template <class T,class U>
class kGUICallBackPtrPtr
{
public:
kGUICallBackPtrPtr() {m_obj=0;m_func=0;}
void Set(void *o,void (*f)(void *,T *,U *));
inline void Call(T *i, U *j) {if(m_func) m_func(m_obj,i,j);}
inline bool IsValid(void) {return (m_func!=0);}
private:
void *m_obj;
void (*m_func)(void *,T *,U *j);
};
```
|
Not yet in the language itself but C++0x will have support for [variadic templates](http://en.wikipedia.org/wiki/C%2B%2B0x#Variadic_templates).
|
C++0x variatdic templates is your best bet, but it will also be a while before you can use them.
If you need sequences of types today, take a look at MPL's [vector](http://www.boost.org/doc/libs/1_36_0/libs/mpl/doc/refmanual/vector.html) of types, as well as other type sequence types. It's part of the [Boost](http://boost.org/) library. It allows you to provide a template argument that is a sequence of types, instead of just a single type.
|
Is there a way to handle a variable number of parameters in a template class?
|
[
"",
"c++",
"parameters",
"templates",
"arguments",
""
] |
I just set up my new homepage at <http://ritter.vg>. I'm using jQuery, but very minimally.
It loads all the pages using AJAX - I have it set up to allow bookmarking by detecting the hash in the URL.
```
//general functions
function getUrl(u) {
return u + '.html';
}
function loadURL(u) {
$.get(getUrl(u), function(r){
$('#main').html(r);
}
);
}
//allows bookmarking
var hash = new String(document.location).indexOf("#");
if(hash > 0)
{
page = new String(document.location).substring(hash + 1);
if(page.length > 1)
loadURL(page);
else
loadURL('news');
}
else
loadURL('news');
```
But I can't get the back and forward buttons to work.
Is there a way to detect when the back button has been pressed (or detect when the hash changes) without using a setInterval loop? When I tried those with .2 and 1 second timeouts, it pegged my CPU.
|
Use the [jQuery hashchange event](https://github.com/cowboy/jquery-hashchange) plugin instead. Regarding your full ajax navigation, try to have [SEO friendly ajax](http://www.chazzuka.com/blog/?p=90). Otherwise your pages shown nothing in browsers with JavaScript limitations.
|
The answers here are all quite old.
In the HTML5 world, you should the use [`onpopstate`](https://developer.mozilla.org/en-US/docs/DOM/window.onpopstate) event.
```
window.onpopstate = function(event)
{
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
```
Or:
```
window.addEventListener('popstate', function(event)
{
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
});
```
The latter snippet allows multiple event handlers to exist, whereas the former will replace any existing handler which may cause hard-to-find bugs.
|
Detecting Back Button/Hash Change in URL
|
[
"",
"javascript",
"ajax",
"navigation",
"fragment-identifier",
"hashchange",
""
] |
Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves.
My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound like a good idea as the people I sell it to too could just make copies of them and pass them on.
I think for the purpose of this problem it would be safe to assume that everyone who buys this would be running the same (LAMP) setup.
|
Don't try and obfuscate or encrypt the code - it will never work.
I would suggest selling the Django application "as a service" - either host it for them, or sell them the code *and support*. Write up a contract that forbids them from redistributing it.
That said, if you were determined to obfuscate the code in some way - you can distribute python applications entirely as .pyc (Python compiled byte-code).. It's how Py2App works.
It will still be re-distributable, *but* it will be very difficult to edit the files - so you could add some basic licensing stuff, and not have it foiled by a few `#`s..
As I said, I don't think you'll succeed in anti-piracy via encryption or obfuscation etc.. Depending on your clients, a simple contract, and maybe some really basic checks will go a long much further than some complicated decryption system (And make the experience of using your application *better*, instead of *hopefully not any worse*)
|
You could package the whole thing up as an Amazon Machine Instance (AMI), and then have them run your app on [Amazon EC2](http://aws.amazon.com/ec2/). The nice thing about this solution is that Amazon will [take care of billing for you](http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/index.html?paidamis-intro.html), and since you're distributing the entire machine image, you can be certain that all your clients are using the same LAMP stack. The AMI is an encrypted machine image that is configured however you want it.
You can have Amazon bill the client with a one-time fee, usage-based fee, or monthly fee.
Of course, this solution requires that your clients host their app at Amazon, and pay the appropriate fees.
|
How would I package and sell a Django app?
|
[
"",
"python",
"django",
"piracy-prevention",
""
] |
I'm a big fan of Capistrano but I need to develop an automated deployment script for a Java-only shop. I've looked at Ant and Maven and they don't seem to be well geared towards remote administration the way Capistrano is - they seem much more focused on simply building and packaging applications. Is there a better tool out there?
|
I don't think there is a Capistrano-like application for Java Web Applications, but that shouldn't really keep you from using it (or alternatives like Fabric) to deploy your applications. As you've already said, Ant is more a replacement for GNU Make while Maven is primary a buildout/dependency-management application.
Since Java Web Applications are thanks to the .war container less dependent on external libraries, you can (depending on your application server) make deploying an application as easy as running a simple HTTP PUT-request.
But if you require additional steps, [Fabric](http://docs.fabfile.org/en/1.4.0/index.html) has worked very well for me so far and I assume that Capistrano also offers generic shell-command, put and get operations. So I wouldn't look for too long for an alternative if what you already have already works :-)
|
I think that controltier (see: <http://controltier.org>) is what you are looking for. Though controltier doesn't need to be exclusively used for Java deploys.
See this excerpt from the docs (see: [control tier documentation](http://doc36.controltier.org/wiki/ControlTier#Is_ControlTier_the_same_as_Capistrano.2C_Fabric.2C_or_Func.3F "test")):
> **Is ControlTier the same as Capistrano, Fabric, or Func?**
>
> In their most fundamental concepts,
> ControlTier, Capistrano, Fabric, and
> Func are similar tools. We'd
> definitely call Capistrano, Fabric,
> and Func basic Command Dispatching
> Frameworks.
>
> However, ControlTier, by
> design, goes far beyond what these
> other tools provide. The automation
> libraries and the web-based tools that
> ControlTier provides are designed to
> let you build full automation systems
> ready for use by enterprise or
> large-scale web operations teams.
> There are also features like
> error-handling and centralized logging
> that just aren't in the scope of other
> command dispatching tools.
>
> Also, Capistrano is a Ruby-based tool
> that is primarily focused on the needs
> of the Ruby on Rails community.
> ControlTier, while written in Java,
> doesn't require you to know Java to
> use it. In fact, you can use whatever
> scripting languages you are
> comfortable with (including ruby).
> ControlTier attempts to be as language
> and platform (Linux, Unix, Windows,
> etc..) neutral as possible.
|
Capistrano for Java?
|
[
"",
"java",
"deployment",
"capistrano",
""
] |
I have a C++ template class that gets instantiated with 3 different type parameters. There's a method that the class needs to have for only one of those types and that isn't ever called with the two other types.
Will object code for that method be generated thrice (for all types for which the template is instantiated), or is object code generated only once (for the type with which it is actually used)?
|
Virtual member functions are instantiated when a class template is instantiated, but non-virtual member functions are instantiated only if they are called.
This is covered in [temp.inst] in the C++ standard (In C++11, this is §14.7.1/10. In C++14, it is §14.7.1/11, and in C++17 it is §17.7.1/9. Excerpt from C++17 below)
> An implementation shall not implicitly instantiate a function template, a variable template, a member
> template, a non-virtual member function, a member class, a static data member of a class template, or
> a substatement of a `constexpr` if statement (9.4.1), unless such instantiation is required
Also note that it is possible to instantiate a class template even if some of the member functions are not instantiable for the given template parameters. For example:
```
template <class T>
class Xyzzy
{
public:
void CallFoo() { t.foo(); } // Invoke T::foo()
void CallBar() { t.bar(); } // Invoke T::bar()
private:
T t;
};
class FooBar
{
public:
void foo() { ... }
void bar() { ... }
};
class BarOnly
{
public:
void bar() { ... }
};
int main(int argc, const char** argv)
{
Xyzzy<FooBar> foobar; // Xyzzy<FooBar> is instantiated
Xyzzy<BarOnly> baronly; // Xyzzy<BarOnly> is instantiated
foobar.CallFoo(); // Calls FooBar::foo()
foobar.CallBar(); // Calls FooBar::bar()
baronly.CallBar(); // Calls BarOnly::bar()
return 0;
}
```
This is valid, even though Xyzzy::CallFoo() is not instantiable because there is no such thing as BarOnly::foo(). This feature is used often as a template metaprogramming tool.
Note, however, that "instantiation" of a template does not directly correlate to how much object code gets generated. That will depend upon your compiler/linker implementation.
|
I think it depends on the compiler and settings. For example, I believe MSVC6 generated everything, but VS2005 does not. The spec says the compiler should not, but in the real world, it depends on the actual compiler (there are many work-arounds in boost for MSVC6, for example). The linker can remove unreferenced functions if /opt:ref is enabled (for VS, equivalent options exist for other compilers).
|
Is object code generated for unused template class methods?
|
[
"",
"c++",
"templates",
"footprint",
""
] |
In SQL Server you can use the `IsNull()` function to check if a value is null, and if it is, return another value. Now I am wondering if there is anything similar in C#.
For example, I want to do something like:
```
myNewValue = IsNull(myValue, new MyValue());
```
instead of:
```
if (myValue == null)
myValue = new MyValue();
myNewValue = myValue;
```
Thanks.
|
It's called the null coalescing (`??`) operator:
```
myNewValue = myValue ?? new MyValue();
```
|
Sadly, there's no equivalent to the null coalescing operator that works with DBNull; for that, you need to use the ternary operator:
```
newValue = (oldValue is DBNull) ? null : oldValue;
```
|
C# equivalent of the IsNull() function in SQL Server
|
[
"",
"c#",
".net",
"sql-server",
"isnull",
""
] |
Is there an efficient way to tell if a DOM element (in an HTML document) is currently visible (appears in the **viewport**)?
(The question refers to Firefox.)
|
**Update:** Time marches on and so have our browsers. **This technique is no longer recommended** and you should use [Dan's solution](https://stackoverflow.com/questions/123999/how-can-i-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433) if you do not need to support version of Internet Explorer before 7.
**Original solution (now outdated):**
This will check if the element is entirely visible in the current viewport:
```
function elementInViewport(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top >= window.pageYOffset &&
left >= window.pageXOffset &&
(top + height) <= (window.pageYOffset + window.innerHeight) &&
(left + width) <= (window.pageXOffset + window.innerWidth)
);
}
```
You could modify this simply to determine if any part of the element is visible in the viewport:
```
function elementInViewport2(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
}
```
|
Now [most browsers](http://www.quirksmode.org/dom/w3c_cssom.html) support [getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) method, which has become the best practice. Using an old answer is very slow, [not accurate](http://weblogs.asp.net/bleroy/archive/2008/01/29/getting-absolute-coordinates-from-a-dom-element.aspx) and [has several bugs](http://javascript.info/tutorial/coordinates).
The solution selected as correct is [almost never precise](http://www.quirksmode.org/js/findpos.html).
---
This solution was tested on Internet Explorer 7 (and later), iOS 5 (and later) Safari, [Android 2.0](https://en.wikipedia.org/wiki/Android_Eclair) (Eclair) and later, BlackBerry, Opera Mobile, and Internet Explorer Mobile [9](http://ejohn.org/blog/getboundingclientrect-is-awesome/).
---
```
function isElementInViewport (el) {
// Special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /* or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */
);
}
```
---
## How to use:
You can be sure that the function given above returns correct answer at the moment of time when it is called, but what about tracking element's visibility as an event?
Place the following code at the bottom of your `<body>` tag:
```
function onVisibilityChange(el, callback) {
var old_visible;
return function () {
var visible = isElementInViewport(el);
if (visible != old_visible) {
old_visible = visible;
if (typeof callback == 'function') {
callback();
}
}
}
}
var handler = onVisibilityChange(el, function() {
/* Your code go here */
});
// jQuery
$(window).on('DOMContentLoaded load resize scroll', handler);
/* // Non-jQuery
if (window.addEventListener) {
addEventListener('DOMContentLoaded', handler, false);
addEventListener('load', handler, false);
addEventListener('scroll', handler, false);
addEventListener('resize', handler, false);
} else if (window.attachEvent) {
attachEvent('onDOMContentLoaded', handler); // Internet Explorer 9+ :(
attachEvent('onload', handler);
attachEvent('onscroll', handler);
attachEvent('onresize', handler);
}
*/
```
---
If you do any DOM modifications, they can change your element's visibility of course.
**Guidelines and common pitfalls:**
**Maybe you need to track page zoom / mobile device pinch?** jQuery should handle [zoom/pinch](http://api.jquery.com/resize/) cross browser, otherwise [first](https://stackoverflow.com/questions/995914/catch-browsers-zoom-event-in-javascript) or [second](https://stackoverflow.com/questions/11183174/simplest-way-to-detect-a-pinch) link should help you.
If you **modify DOM**, it can affect the element's visibility. You should take control over that and call `handler()` manually. Unfortunately, we don't have any cross browser `onrepaint` event. On the other hand that allows us to make optimizations and perform re-check only on DOM modifications that can change an element's visibility.
**Never Ever** use it inside jQuery [$(document).ready()](http://api.jquery.com/ready/) only, because [there is no warranty CSS has been applied](https://stackoverflow.com/questions/1324568/is-document-ready-also-css-ready) in this moment. Your code can work locally with your CSS on a hard drive, but once put on a remote server it will fail.
After `DOMContentLoaded` is fired, [styles are applied](https://stackoverflow.com/questions/3520780/when-is-window-onload-fired), but [the images are not loaded yet](https://stackoverflow.com/questions/8835413/difference-between-load-vs-domcontentloaded). So, we should add `window.onload` event listener.
We can't catch zoom/pinch event yet.
The last resort could be the following code:
```
/* TODO: this looks like a very bad code */
setInterval(handler, 600);
```
You can use the awesome feature [pageVisibiliy](https://developer.mozilla.org/en-US/docs/DOM/Using_the_Page_Visibility_API) of the HTML5 API if you care if the tab with your web page is active and visible.
TODO: this method does not handle two situations:
* Overlapping using `z-index`.
* Using `overflow-scroll` in element's container.
* Try something new - *[The Intersection Observer API explained](https://pawelgrzybek.com/the-intersection-observer-api-explained/)*.
|
How can I tell if a DOM element is visible in the current viewport?
|
[
"",
"javascript",
"html",
"firefox",
"dom",
"browser",
""
] |
I'm writing a Java Tree in which tree nodes could have children that take a long time to compute (in this case, it's a file system, where there may be network timeouts that prevent getting a list of files from an attached drive).
The problem I'm finding is this:
1. `getChildCount()` is called before the user specifically requests opening a particular branch of the tree. I believe this is done so the `JTree` knows whether to show a + icon next to the node.
2. An accurate count of children from `getChildCount()` would need to perform the potentially expensive operation
3. If I fake the value of `getChildCount()`, the tree only allocates space for that many child nodes before asking for an enumeration of the children. (If I return '1', I'll only see 1 child listed, despite that there are more)
The enumeration of the children can be expensive and time-consuming, I'm okay with that. But I'm not okay with `getChildCount()` needing to know the exact number of children.
Any way I can work around this?
**Added:** The other problem is that if one of the nodes represents a floppy drive (how archaic!), the drive will be polled before the user asks for its files; if there's no disk in the drive, this results in a system error.
**Update:** Unfortunately, implementing the `TreeWillExpand` listener isn't the solution. That can allow you to veto an expansion, but the number of nodes shown is still restricted by the value returned by `TreeNode.getChildCount()`.
|
There are a few parts to the solution:
* Like Lorenzo Boccaccia said, use the [TreeWillExpandListener](http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#data)
* **Also**, need to call nodesWereInserted on the tree, so the proper number of nodes will be displayed. [See this code](http://www.jroller.com/Thierry/resource/SwingX/LazyLoadingTreeNode.java)
* I have determined that if you don't know the child count, TreeNode.getChildCount() needs to return at least 1 (it can't return 0)
|
<http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#data>
scroll a little down, there is the exact tutorial on how to create lazy loading nodes for the jtree, complete with examples and documentation
|
Java TreeNode: How to prevent getChildCount from doing expensive operation?
|
[
"",
"java",
"swing",
"jtree",
""
] |
I want to display the TIME field from my mysql table on my website, but rather than showing 21:00:00 etc I want to show 8:00 PM. I need a function/code to do this or even any pointers in the right direction. Will mark the first reply with some code as the correct reply.
|
Check this out: <http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html>
I'd imagine you'd want date\_format().
Example: DATE\_FORMAT($date, "%r")
|
Show the date & time data in AM/PM format with the following example...
```
SELECT DATE_FORMAT(`t`.`date_field`,'%h:%i %p') AS `date_field` FROM `table_name` AS `t`
```
OR
```
SELECT DATE_FORMAT(`t`.`date_field`,'%r') AS `date_field` FROM `table_name` AS `t`
```
Both are working properly.
|
Converting mysql TIME from 24 HR to AM/PM format
|
[
"",
"php",
"mysql",
"datetime",
"date",
"time",
""
] |
I'm used to writing classes like this:
```
public class foo {
private string mBar = "bar";
public string Bar {
get { return mBar; }
set { mBar = value; }
}
//... other methods, no constructor ...
}
```
Converting Bar to an auto-property seems convenient and concise, but how can I retain the initialization without adding a constructor and putting the initialization in there?
```
public class foo2theRevengeOfFoo {
//private string mBar = "bar";
public string Bar { get; set; }
//... other methods, no constructor ...
//behavior has changed.
}
```
You could see that adding a constructor isn't inline with the effort savings I'm supposed to be getting from auto-properties.
Something like this would make more sense to me:
```
public string Bar { get; set; } = "bar";
```
|
Update - the answer below was written before C# 6 came along. In C# 6 you can write:
```
public class Foo
{
public string Bar { get; set; } = "bar";
}
```
You can *also* write read-only automatically-implemented properties, which are only writable in the constructor (but can also be given a default initial value):
```
public class Foo
{
public string Bar { get; }
public Foo(string bar)
{
Bar = bar;
}
}
```
---
It's unfortunate that there's no way of doing this right now. You have to set the value in the constructor. (Using constructor chaining can help to avoid duplication.)
Automatically implemented properties are handy right now, but could certainly be nicer. I don't find myself wanting this sort of initialization as often as a read-only automatically implemented property which could only be set in the constructor and would be backed by a read-only field.
This hasn't happened up until and including C# 5, but is being planned for C# 6 - both in terms of allowing initialization at the point of declaration, *and* allowing for read-only automatically implemented properties to be initialized in a constructor body.
|
You can do it via the constructor of your class:
```
public class foo {
public foo(){
Bar = "bar";
}
public string Bar {get;set;}
}
```
If you've got another constructor (ie, one that takes paramters) or a bunch of constructors you can always have this (called constructor chaining):
```
public class foo {
private foo(){
Bar = "bar";
Baz = "baz";
}
public foo(int something) : this(){
//do specialized initialization here
Baz = string.Format("{0}Baz", something);
}
public string Bar {get; set;}
public string Baz {get; set;}
}
```
If you always chain a call to the default constructor you can have all default property initialization set there. When chaining, the chained constructor will be called before the calling constructor so that your more specialized constructors will be able to set different defaults as applicable.
|
Initializing C# auto-properties
|
[
"",
"c#",
"initialization",
"automatic-properties",
""
] |
Does any one know of an opensource Java VNC server, that can be run from a web page, so requiring no installation on the server end, possibley applet based.
|
<http://vncj.com/default.aspx>
Once you get it setup you wont know how you lived w/o it. The server and the client are using the same .jar file all in the html page pointing where your listen client is at.
|
A signed Java applet (or application) can use the Robot class to get screenshots of the current window and use this for remote control. It will never be very efficient, but it can be done.
|
Java VNC Applet
|
[
"",
"java",
"applet",
"vnc",
""
] |
If I have a script tag like this:
```
<script
id = "myscript"
src = "http://www.example.com/script.js"
type = "text/javascript">
</script>
```
I would like to get the content of the "script.js" file. I'm thinking about something like `document.getElementById("myscript").text` but it doesn't work in this case.
|
Do you want to get the contents of the file <http://www.example.com/script.js>? If so, you could turn to AJAX methods to fetch its content, assuming it resides on the same server as the page itself.
|
**tl;dr** script tags are not subject to [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) and [same-origin-policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) and therefore javascript/DOM cannot offer access to the text content of the resource loaded via a `<script>` tag, or it would break `same-origin-policy`.
**long version:**
Most of the other answers (and the accepted answer) indicate correctly that the "*correct*" way to get the text content of a javascript file inserted via a `<script>` loaded into the page, is using an [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) to perform another seperate additional request for the resource indicated in the scripts `src` property, something which the short javascript code below will demonstrate. I however found that the other answers did not address the point why to get the javascript files text content, which is that allowing to access content of the file included via the `<script src=[url]></script>` would break the `CORS` policies, e.g. modern browsers prevent the XHR of resources that do not provide the [Access-Control-Allow-Origin](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin) header, hence browsers do not allow any other way than those subject to `CORS`, to get the content.
With the following code (as mentioned in the other questions "use XHR/AJAX") it is possible to do another request for all not inline script tags in the document.
```
function printScriptTextContent(script)
{
var xhr = new XMLHttpRequest();
xhr.open("GET",script.src)
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log("the script text content is",xhr.responseText);
}
};
xhr.send();
}
Array.prototype.slice.call(document.querySelectorAll("script[src]")).forEach(printScriptTextContent);
```
and so I will not repeat that, but instead would like to add via this answer upon the aspect why itthat
|
How can I get the content of the file specified as the 'src' of a <script> tag?
|
[
"",
"javascript",
""
] |
I have a number of code value tables that contain a code and a description with a Long id.
I now want to create an entry for an Account Type that references a number of codes, so I have something like this:
```
insert into account_type_standard (account_type_Standard_id,
tax_status_id, recipient_id)
( select account_type_standard_seq.nextval,
ts.tax_status_id, r.recipient_id
from tax_status ts, recipient r
where ts.tax_status_code = ?
and r.recipient_code = ?)
```
This retrieves the appropriate values from the tax\_status and recipient tables if a match is found for their respective codes. Unfortunately, recipient\_code is nullable, and therefore the ? substitution value could be null. Of course, the implicit join doesn't return a row, so a row doesn't get inserted into my table.
I've tried using NVL on the ? and on the r.recipient\_id.
I've tried to force an outer join on the r.recipient\_code = ? by adding (+), but it's not an explicit join, so Oracle still didn't add another row.
Anyone know of a way of doing this?
I can obviously modify the statement so that I do the lookup of the recipient\_id externally, and have a ? instead of r.recipient\_id, and don't select from the recipient table at all, but I'd prefer to do all this in 1 SQL statement.
|
Outter joins don't work "as expected" in that case because you have explicitly told Oracle you only want data if that criteria on that table matches. In that scenario, the outter join is rendered useless.
A work-around
```
INSERT INTO account_type_standard
(account_type_Standard_id, tax_status_id, recipient_id)
VALUES(
(SELECT account_type_standard_seq.nextval FROM DUAL),
(SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?),
(SELECT recipient_id FROM recipient WHERE recipient_code = ?)
)
```
[Edit]
If you expect multiple rows from a sub-select, you can add ROWNUM=1 to each where clause OR use an aggregate such as MAX or MIN. This of course may not be the best solution for all cases.
[Edit] Per comment,
```
(SELECT account_type_standard_seq.nextval FROM DUAL),
```
can be just
```
account_type_standard_seq.nextval,
```
|
A slightly simplified version of Oglester's solution (the sequence doesn't require a select from DUAL:
```
INSERT INTO account_type_standard
(account_type_Standard_id, tax_status_id, recipient_id)
VALUES(
account_type_standard_seq.nextval,
(SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?),
(SELECT recipient_id FROM recipient WHERE recipient_code = ?)
)
```
|
Oracle Insert via Select from multiple tables where one table may not have a row
|
[
"",
"sql",
"oracle",
"select",
"insert",
""
] |
Is there a way through the .net framework to determine if a folder is shared or not?
Neither Diretory, DirectoryInfo or FileAttributes seem to have any corresponding field.
One thing I forgot to mention was that I want to be checking for network shares. But I'll investigate the WMI stuff.
|
You can use WMI Win32\_Share.
Take a look at:
<http://www.gamedev.net/community/forums/topic.asp?topic_id=408923>
Shows a sample for querying, creating and deleting shared folders.
|
You can get a list of all the shared folders using the WMI Win32\_Share and see if the folder you're looking for is between them. Here's a snippet that might help you with this:
```
public static List<string> GetSharedFolders()
{
List<string> sharedFolders = new List<string>();
// Object to query the WMI Win32_Share API for shared files...
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from win32_share");
ManagementBaseObject outParams;
ManagementClass mc = new ManagementClass("Win32_Share"); //for local shares
foreach (ManagementObject share in searcher.Get()){
string type = share["Type"].ToString();
if (type == "0") // 0 = DiskDrive (1 = Print Queue, 2 = Device, 3 = IPH)
{
string name = share["Name"].ToString(); //getting share name
string path = share["Path"].ToString(); //getting share path
string caption = share["Caption"].ToString(); //getting share description
sharedFolders.Add(path);
}
}
return sharedFolders;
}
```
Please note that I brutally copy-pasted from this [link](http://bytes.com/forum/thread624242.html) on bytes
|
Determining if a folder is shared in .NET
|
[
"",
"c#",
".net",
"windows",
""
] |
I'm at the beginning/middle of a project that we chose to implement using GWT. Has anyone encountered any major pitfalls in using GWT (and GWT-EXT) that were unable to be overcome? How about from a performance perspective?
A couple things that we've seen/heard already include:
* Google not being able to index content
* CSS and styling in general seems to be a bit flaky
Looking for any additional feedback on these items as well. Thanks!
|
I'll start by saying that I'm a massive GWT fan, but yes there are many pitfalls, but most if not all we were able to overcome:
**Problem:** Long compile times, as your project grows so does the amount of time it takes to compile it. I've heard of reports of 20 minute compiles, but mine are on average about 1 minute.
**Solution:** Split your code into separate modules, and tell ant to only build it when it's changed. Also while developing, you can massively speed up compile times by only building for one browser. You can do this by putting this into your .gwt.xml file:
```
<set-property name="user.agent" value="gecko1_8" />
```
Where gecko1\_8 is Firefox 2+, ie6 is IE, etc.
---
**Problem:** Hosted mode is very slow (on OS X at least) and does not come close to matching the 'live' changes you get when you edit things like JSPs or Rails pages and hit refresh in your browser.
**Solution:** You can give the hosted mode more memory (I generally got for 512M) but it's still slow, I've found once you get good enough with GWT you stop using this. You make a large chunk of changes, then compile for just one browser (generally 20s worth of compile) and then just hit refresh in your browser.
Update: With GWT 2.0+ this is no longer an issue, because you use the new 'Development Mode'. It basically means you can run code directly in your browser of choice, so no loss of speed, plus you can firebug/inspect it, etc.
<http://code.google.com/p/google-web-toolkit/wiki/UsingOOPHM>
---
**Problem:** GWT code is java, and has a different mentality to laying out a HTML page, which makes taking a HTML design and turning it into GWT harder
**Solution:** Again you get used to this, but unfortunately converting a HTML design to a GWT design is always going to be slower than doing something like converting a HTML design to a JSP page.
---
**Problem:** GWT takes a bit of getting your head around, and is not yet mainstream. Meaning that most developers that join your team or maintain your code will have to learn it from scratch
**Solution:** It remains to be seen if GWT will take off, but if you're a company in control of who you hire, then you can always choose people that either know GWT or want to learn it.
---
**Problem:** GWT is a sledgehammer compared to something like jquery or just plain javascript. It takes a lot more setup to get it happening than just including a JS file.
**Solution:** Use libraries like jquery for smaller, simple tasks that are suited to those. Use GWT when you want to build something truly complex in AJAX, or where you need to pass your data back and forth via the RPC mechanism.
---
**Problem:** Sometimes in order to populate your GWT page, you need to make a server call when the page first loads. It can be annoying for the user to sit there and watch a loading symbol while you fetch the data you need.
**Solution:** In the case of a JSP page, your page was already rendered by the server before becoming HTML, so you can actually make all your GWT calls then, and pre-load them onto the page, for an instant load. See here for details:
[Speed up Page Loading by pre-serializing your GWT calls](http://wiki.shiftyjelly.com/index.php/GWT#Speed_up_Page_Loading.2C_by_pre-serializing_your_GWT_calls)
---
I've never had any problems CSS styling my widgets, out of the box, custom or otherwise, so I don't know what you mean by that being a pitfall?
As for performance, I've always found that once compiled GWT code is fast, and AJAX calls are nearly always smaller than doing a whole page refresh, but that's not really unique to GWT, though the native RPC packets that you get if you use a JAVA back end are pretty compact.
|
We have been working with gwt for almost 2 years. We have learned a lot of lessons. Here is what we think:
1. Dont use third party widget libraries especially gwt-ext. It will kill your debugging, development and runtime performance. If you have questions about how this happens, contact me directly.
2. Use gwt to only fill in the dynamic parts of your apps. So if you have some complex user interactions with lots of fields. However, don't use the panels that come with it. Take your existing stock designer supplied pages. Carve out the areas that will contain the controls for your app. Attach these controls to the page within onModuleLoad(). This way you can use the standard pages from your designer and also do all the styling outside the gwt.
3. Don't build the entire app as one standard page that then dynamically builds all the pieces. If you do what I suggest in item 2, this won't happen anyway. If you build everything dynamically you will kill performance and consume huge amounts of memory for medium to large apps. Also, if you do what I am suggesting, the back button will work great, so will search engine indexing etc.
The other commenters also had some good suggestions. The rule of thumb i use is to create pages like you were doing a standard web page. Then carve out the pieces that need to be dynamic. Replace them with elements that have id's and then use `RootPanel.get( id ).add( widget )` to fill those areas in.
|
Biggest GWT Pitfalls?
|
[
"",
"java",
"ajax",
"gwt",
"gwt-ext",
""
] |
I want to create basic line, bar, pie and area charts for .NET 3.5 WinForms and I'm interested in finding a free, mature, open-source .NET (preferably C# based) project to help me accomplish that. I would consider a WPF based project, however I'm more comfortable in GDI+ so I'd rather it used System.Drawing and/or GDI interop as its base technology.
Thanks!
|
[ZedGraph](http://zedgraph.org/). 'Nuff said.
|
This one's quite nice: [zed graph](http://zedgraph.org)
|
What's a good f/oss GDI+ (System.Drawing) based graphing and charting component for .NET?
|
[
"",
"c#",
".net",
"vb.net",
"gdi+",
"graph",
""
] |
I've got a function that runs a user generated Regex. However, if the user enters a regex that won't run then it stops and falls over. I've tried wrapping the line in a Try/Catch block but alas nothing happens.
If it helps, I'm running jQuery but the code below does not have it as I'm guessing that it's a little more fundamental than that.
Edit: Yes, I know that I am not escaping the "[", that's intentional and the point of the question. I'm accepting user input and I want to find a way to catch this sort of problem without the application falling flat on it's face.
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Regex</title>
<script type="text/javascript" charset="utf-8">
var grep = new RegExp('gr[');
try
{
var results = grep.exec('bob went to town');
}
catch (e)
{
//Do nothing?
}
alert('If you can see this then the script kept going');
</script>
</head>
<body>
</body>
</html>
```
|
Try this the new RegExp is throwing the exception
Regex
```
<script type="text/javascript" charset="utf-8">
var grep;
try {
grep = new RegExp("gr[");
}
catch(e) {
alert(e);
}
try
{
var results = grep.exec('bob went to town');
}
catch (e)
{
//Do nothing?
}
alert('If you can see this then the script kept going');
</script>
```
|
The problem is with this line:
```
var grep = new RegExp('gr[');
```
'[' is a special character so it needs to be escaped. Also this line is not wrapped in try...catch, so you still get the error.
**Edit**: You could also add an
```
alert(e.message);
```
in the catch clause to see the error message. It's useful for all kind of errors in javascript.
**Edit 2**: OK, I needed to read more carefully the question, but the answer is still there. In the example code the offending line is not wrapped in the try...catch block. I put it there and didn't get errors in Opera 9.5, FF3 and IE7.
|
Javascript Try/Catch
|
[
"",
"javascript",
"regex",
"try-catch",
""
] |
Given the following:
```
&row->count
```
Would &(row->count) be evaluated or (&row)->count be evaluated in C++?
EDIT: Here's a great [link](http://www.cppreference.com/wiki/operator_precedence) for C++ precedence.
|
[&(row->count)](http://www.cppreference.com/wiki/operator_precedence)
|
As far as precedence rules go, I've always liked the one put forth by Steve Oualline in "Practical C":
> There are fifteen precedence rules in
> C (&& comes before || comes before
> ?:). The practical programmer reduces
> these to two:
>
> 1) Multiplication and division come
> before addition and subtraction.
>
> 2) Put parentheses around everything
> else.
|
Priority of C++ operators "&" and "->"
|
[
"",
"c++",
"operators",
"operator-precedence",
""
] |
In C++ you can initialize a variable in an if statement, like so:
```
if (CThing* pThing = GetThing())
{
}
```
Why would one consider this bad or good style? What are the benefits and disadvantages?
Personally i like this style because it limits the scope of the pThing variable, so it can never be used accidentally when it is NULL. However, i don't like that you can't do this:
```
if (CThing* pThing = GetThing() && pThing->IsReallySomeThing())
{
}
```
If there's a way to make the above work, please post. But if that's just not possible, i'd still like to know why.
[Question borrowed from here, similar topic but PHP.](https://stackoverflow.com/questions/136373/initializing-a-variable-in-a-conditional-statment)
|
The important thing is that a declaration in C++ is not an expression.
```
bool a = (CThing* pThing = GetThing()); // not legit!!
```
You can't do both a declaration and boolean logic in an if statement, C++ language spec specifically allows either an expression or a declaration.
```
if(A *a = new A)
{
// this is legit and a is scoped here
}
```
How can we know whether a is defined between one term and another in an expression?
```
if((A *a = new A) && a->test())
{
// was a really declared before a->test?
}
```
Bite the bullet and use an internal if. The scope rules are useful and your logic is explicit:
```
if (CThing* pThing = GetThing())
{
if(pThing->IsReallySomeThing())
{
}
}
```
|
You can have initialization statements inside `if` and `switch` since **C++17**.
Your code would now be:
```
if (CThing* pThing = GetThing(); pThing->IsReallySomeThing())
{
// use pThing here
}
// pThing is out of scope here
```
|
Pro/con: Initializing a variable in a conditional statement
|
[
"",
"c++",
"coding-style",
"if-statement",
""
] |
Which of these queries is the faster?
NOT EXISTS:
```
SELECT ProductID, ProductName
FROM Northwind..Products p
WHERE NOT EXISTS (
SELECT 1
FROM Northwind..[Order Details] od
WHERE p.ProductId = od.ProductId)
```
Or NOT IN:
```
SELECT ProductID, ProductName
FROM Northwind..Products p
WHERE p.ProductID NOT IN (
SELECT ProductID
FROM Northwind..[Order Details])
```
The query execution plan says they both do the same thing. If that is the case, which is the recommended form?
This is based on the NorthWind database.
[Edit]
Just found this helpful article:
<http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx>
I think I'll stick with NOT EXISTS.
|
I always default to `NOT EXISTS`.
The execution plans may be the same at the moment but if either column is altered in the future to allow `NULL`s the `NOT IN` version will need to do more work (even if no `NULL`s are actually present in the data) and the semantics of `NOT IN` if `NULL`s *are* present are unlikely to be the ones you want anyway.
When neither `Products.ProductID` or `[Order Details].ProductID` allow `NULL`s the `NOT IN` will be treated identically to the following query.
```
SELECT ProductID,
ProductName
FROM Products p
WHERE NOT EXISTS (SELECT *
FROM [Order Details] od
WHERE p.ProductId = od.ProductId)
```
The exact plan may vary but for my example data I get the following.

A reasonably common misconception seems to be that correlated sub queries are always "bad" compared to joins. They certainly can be when they force a nested loops plan (sub query evaluated row by row) but this plan includes an anti semi join logical operator. Anti semi joins are not restricted to nested loops but can use hash or merge (as in this example) joins too.
```
/*Not valid syntax but better reflects the plan*/
SELECT p.ProductID,
p.ProductName
FROM Products p
LEFT ANTI SEMI JOIN [Order Details] od
ON p.ProductId = od.ProductId
```
If `[Order Details].ProductID` is `NULL`-able the query then becomes
```
SELECT ProductID,
ProductName
FROM Products p
WHERE NOT EXISTS (SELECT *
FROM [Order Details] od
WHERE p.ProductId = od.ProductId)
AND NOT EXISTS (SELECT *
FROM [Order Details]
WHERE ProductId IS NULL)
```
The reason for this is that the correct semantics if `[Order Details]` contains any `NULL` `ProductId`s is to return no results. See the extra anti semi join and row count spool to verify this that is added to the plan.

If `Products.ProductID` is also changed to become `NULL`-able the query then becomes
```
SELECT ProductID,
ProductName
FROM Products p
WHERE NOT EXISTS (SELECT *
FROM [Order Details] od
WHERE p.ProductId = od.ProductId)
AND NOT EXISTS (SELECT *
FROM [Order Details]
WHERE ProductId IS NULL)
AND NOT EXISTS (SELECT *
FROM (SELECT TOP 1 *
FROM [Order Details]) S
WHERE p.ProductID IS NULL)
```
The reason for that one is because a `NULL` `Products.ProductId` should not be returned in the results **except** if the `NOT IN` sub query were to return no results at all (i.e. the `[Order Details]` table is empty). In which case it should. In the plan for my sample data this is implemented by adding another anti semi join as below.

The effect of this is shown in [the blog post already linked by Buckley](http://sqlinthewild.co.za/index.php/2010/02/18/not-exists-vs-not-in/). In the example there the number of logical reads increase from around 400 to 500,000.
Additionally the fact that a single `NULL` can reduce the row count to zero makes cardinality estimation very difficult. If SQL Server assumes that this will happen but in fact there were no `NULL` rows in the data the rest of the execution plan may be catastrophically worse, if this is just part of a larger query, [with inappropriate nested loops causing repeated execution of an expensive sub tree for example](https://dba.stackexchange.com/q/117306/3690).
This is not the only possible execution plan for a `NOT IN` on a `NULL`-able column however. [This article shows another one](http://bradsruminations.blogspot.co.uk/2011/10/t-sql-tuesday-023-flip-side-of-join.html) for a query against the `AdventureWorks2008` database.
For the `NOT IN` on a `NOT NULL` column or the `NOT EXISTS` against either a nullable or non nullable column it gives the following plan.

When the column changes to `NULL`-able the `NOT IN` plan now looks like

It adds an extra inner join operator to the plan. This apparatus is [explained here](https://dba.stackexchange.com/a/14812/3690). It is all there to convert the previous single correlated index seek on `Sales.SalesOrderDetail.ProductID = <correlated_product_id>` to two seeks per outer row. The additional one is on `WHERE Sales.SalesOrderDetail.ProductID IS NULL`.
As this is under an anti semi join if that one returns any rows the second seek will not occur. However if `Sales.SalesOrderDetail` does not contain any `NULL` `ProductID`s it will double the number of seek operations required.
|
Also be aware that NOT IN is not equivalent to NOT EXISTS when it comes to null.
This post explains it very well
<http://sqlinthewild.co.za/index.php/2010/02/18/not-exists-vs-not-in/>
> When the subquery returns even one null, NOT IN will not match any
> rows.
>
> The reason for this can be found by looking at the details of what the
> NOT IN operation actually means.
>
> Let’s say, for illustration purposes that there are 4 rows in the
> table called t, there’s a column called ID with values 1..4
>
> ```
> WHERE SomeValue NOT IN (SELECT AVal FROM t)
> ```
>
> is equivalent to
>
> ```
> WHERE SomeValue != (SELECT AVal FROM t WHERE ID=1)
> AND SomeValue != (SELECT AVal FROM t WHERE ID=2)
> AND SomeValue != (SELECT AVal FROM t WHERE ID=3)
> AND SomeValue != (SELECT AVal FROM t WHERE ID=4)
> ```
>
> Let’s further say that AVal is NULL where ID = 4. Hence that !=
> comparison returns UNKNOWN. The logical truth table for AND states
> that UNKNOWN and TRUE is UNKNOWN, UNKNOWN and FALSE is FALSE. There is
> no value that can be AND’d with UNKNOWN to produce the result TRUE
>
> Hence, if any row of that subquery returns NULL, the entire NOT IN
> operator will evaluate to either FALSE or NULL and no records will be
> returned
|
NOT IN vs NOT EXISTS
|
[
"",
"sql",
"sql-server",
"notin",
""
] |
I need to create a custom volume slider for a WMP object. The current slider is complicated to modify, and use, is there a simple way to generate a slider on an HTML page that can have it's value passed to a javascript function?
|
[jQuery UI Slider](http://jqueryui.com/demos/slider/) ([API docs](http://docs.jquery.com/UI/Slider))
|
hey i've just created my own JS slider because I had enough of the heavy Jquery UI one. Interested to hear people's thoughts. Been on it for 5 hours, so really really early stages.
[jsfiddle\_slider](http://jsfiddle.net/LucP/BPdKR/2/)
|
Is there a simple JavaScript slider?
|
[
"",
"javascript",
"slider",
"controls",
"wmp",
""
] |
I have a c# application that runs as a windows service controlling socket connections and other things.
Also, there is another windows forms application to control and configure this service (systray with start, stop, show form with configuration parameters).
I'm using .net remoting to do the IPC and that was fine, but now I want to show some real traffic and other reports and remoting will not meet my performance requirements. So I want to combine both applications in one.
Here is the problem:
When I started the form from the windows service, nothing happened. Googling around I've found that I have to right click the service, go to Log on and check the "Allow service to interact with desktop" option. Since I don't want to ask my users to do that, I got some code googling again to set this option in the user's regedit during installation time. The problem is that even setting this option, it doesn't work. I have to open the Log On options of the service (it is checked), uncheck and check again.
**So, how to solve that? How is the best way to have a windows service with a systray control in the same process, available to any user logging in?**
UPDATE: Thanks for the comments so far, guys. I agree it is better to use IPC and I know that it is bad to mix windows services and user interfaces. Even though, I want to know how to do that.
|
Two separate processes that communicate using your technology of choice. Services with UI is a **bad idea**. Don't go down this road - you'll regret it.
I've had very good results having service communication through a simple socket connection - document your service protocol well, keep it as simple as possible, and it'll be easier than you think.
|
In practice you should not couple your service with the management UI.
|
Windows services with windows forms in the same process
|
[
"",
"c#",
"windows",
"windows-services",
""
] |
What's the best way to break from nested loops in Javascript?
```
//Write the links to the page.
for (var x = 0; x < Args.length; x++)
{
for (var Heading in Navigation.Headings)
{
for (var Item in Navigation.Headings[Heading])
{
if (Args[x] == Navigation.Headings[Heading][Item].Name)
{
document.write("<a href=\""
+ Navigation.Headings[Heading][Item].URL + "\">"
+ Navigation.Headings[Heading][Item].Name + "</a> : ");
break; // <---HERE, I need to break out of two loops.
}
}
}
}
```
|
Just like Perl,
```
loop1:
for (var i in set1) {
loop2:
for (var j in set2) {
loop3:
for (var k in set3) {
break loop2; // breaks out of loop3 and loop2
}
}
}
```
as defined in EMCA-262 section 12.12. [[MDN Docs]](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/label)
Unlike C, these labels can only be used for [`continue`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/continue) and [`break`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/break), as Javascript does not have `goto`.
|
Wrap that up in a function and then just `return`.
|
What's the best way to break from nested loops in JavaScript?
|
[
"",
"javascript",
"loops",
"nested-loops",
"break",
""
] |
I'm having some trouble with plain old JavaScript (no frameworks) in referencing my object in a callback function.
```
function foo(id) {
this.dom = document.getElementById(id);
this.bar = 5;
var self = this;
this.dom.addEventListener("click", self.onclick, false);
}
foo.prototype = {
onclick : function() {
this.bar = 7;
}
};
```
Now when I create a new object (after the DOM has loaded, with a span#test)
```
var x = new foo('test');
```
The 'this' inside the onclick function points to the span#test and not the foo object.
How do I get a reference to my foo object inside the onclick function?
|
*(extracted some explanation that was hidden in comments in other answer)*
The problem lies in the following line:
```
this.dom.addEventListener("click", self.onclick, false);
```
Here, you pass a function object to be used as callback. When the event trigger, the function is called but now it has no association with any object (this).
The problem can be solved by wrapping the function (with it's object reference) in a closure as follows:
```
this.dom.addEventListener(
"click",
function(event) {self.onclick(event)},
false);
```
Since the variable self was assigned *this* when the closure was created, the closure function will remember the value of the self variable when it's called at a later time.
An alternative way to solve this is to make an utility function (and avoid using variables for binding *this*):
```
function bind(scope, fn) {
return function () {
fn.apply(scope, arguments);
};
}
```
The updated code would then look like:
```
this.dom.addEventListener("click", bind(this, this.onclick), false);
```
---
[`Function.prototype.bind`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind) is part of ECMAScript 5 and provides the same functionality. So you can do:
```
this.dom.addEventListener("click", this.onclick.bind(this), false);
```
For browsers which do not support ES5 yet, [MDN provides the following shim](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind):
```
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
```
|
```
this.dom.addEventListener("click", function(event) {
self.onclick(event)
}, false);
```
|
JavaScript Callback Scope
|
[
"",
"javascript",
"events",
"binding",
"scope",
"callback",
""
] |
Is it possible to find the `foreach` index?
in a `for` loop as follows:
```
for ($i = 0; $i < 10; ++$i) {
echo $i . ' ';
}
```
`$i` will give you the index.
Do I have to use the `for` loop or is there some way to get the index in the `foreach` loop?
|
```
foreach($array as $key=>$value) {
// do stuff
}
```
`$key` is the index of each `$array` element
|
You can put a hack in your `foreach`, such as a field incremented on each run-through, which is exactly what the `for` loop gives you in a numerically-indexed array. Such a field would be a pseudo-index that needs manual management (increments, etc).
A `foreach` will give you your index in the form of your `$key` value, so such a hack shouldn't be necessary.
e.g., in a **`foreach`**
```
$index = 0;
foreach($data as $key=>$val) {
// Use $key as an index, or...
// ... manage the index this way..
echo "Index is $index\n";
$index++;
}
```
|
How to find the foreach index?
|
[
"",
"php",
"loops",
"foreach",
""
] |
Mixing the use of primitive data types and their respective wrapper classes, in Java, can lead to a lot of bugs. The following example illustrates the issue:
```
int i = 4;
...
if (i == 10)
doStuff();
```
Later on you figure that you want the variable *i* to be either defined or undefined, so you change the above instantiation to:
```
Integer i = null;
```
Now the equality check fails.
Is it good Java practise to always use the primitive wrapper classes? It obviously would get some bugs out of the way early, but what are the downsides to this? Does it impact performance or the application's memory footprint? Are there any sneaky gotchas?
|
Using the boxed types *does* have both performance and memory issues.
When doing comparisons (eg `(i == 10)` ), java has to unbox the type before doing the comparison. Even using `i.equals(TEN)` uses a method call, which is costlier and (IMO) uglier than the == syntax.
Re memory, the object has to be stored on the heap (which also takes a hit on performance) as well as storing the value itself.
A sneaky gotcha? `i.equals(j)` when i is `null`.
I always use the primitives, except when it *may* be `null`, but always check for `null` before comparison in those cases.
|
Firstly, switching from using a primitive to using an object just to get the ability to set it to null is probably a bad design decision. I often have arguments with my coworkers about whether or not null is a sentinel value, and my opinion is usually that it is not (and thus shouldn't be prohibited like sentinel values should be), but in this particular case you're going out of your way to use it as a sentinel value. Please don't. Create a boolean that indicates whether or not your integer is valid, or create a new type that wraps the boolean and integer together.
Usually, when using newer versions of Java, I find I don't need to explicitly create or cast to the object versions of primitives because of the auto-boxing support that was added some time in 1.5 (maybe 1.5 itself).
|
Should I never use primitive types again?
|
[
"",
"java",
"types",
""
] |
Can someone provide an explanation of variable scope in JS as it applies to objects, functions and closures?
|
### Global variables
Every variable in Javascript is a named attribute of an object. For example:-
```
var x = 1;
```
x is added to the global object. The global object is provided by the script context and may already have a set of attributes. For example in a browser the global object is window. An equivalent to the above line in a browser would be:-
```
window.x = 1;
```
### Local variables
Now what if we change this to:-
```
function fn()
{
var x = 1;
}
```
When `fn` is called a new object is created called the *execution context* also referred to as the *scope* (I use these terms interchangeably). `x` is added as an attribute to this scope object. Hence each call to `fn` will get its own instance of a scope object and therefore its own instance of the x attribute attached to that scope object.
### Closure
Now lets take this further:-
```
function fnSequence()
{
var x = 1;
return function() { return x++; }
}
var fn1 = fnSequence();
var fn2 = fnSequence();
WScript.Echo(fn1())
WScript.Echo(fn2())
WScript.Echo(fn1())
WScript.Echo(fn2())
WScript.Echo(fn1())
WScript.Echo(fn1())
WScript.Echo(fn2())
WScript.Echo(fn2())
```
**Note:** Replace `WScript.Echo` with whatever writes to stdout in your context.
The sequence you should get is :-
1 1 2 2 3 4 3 4
So what has happened here? We have `fnSequence` which initialises a variable `x` to 1 and returns an anonymous function which will return the value of `x` and then increment it.
When this function is first executed a scope object is created and an attribute `x` is added to that scope object with the value of 1. Also created in the same execution object is an anonymous function. Each function object will have a scope attribute which points to the execution context in which it is created. This creates what is know as a *scope chain* which we will come to later. A reference to this function is returned by `fnSequence` and stored in `fn1`.
Note that `fn1` is now pointing at the anonymous function and that the anonymous function has a scope attribute pointing at a scope object that still has an `x` attribute attached. This is known as `closure` where the contents of an execution context is still reachable after the function it was created for has completed execution.
Now this same sequence happens when assigning to `fn2`. `fn2` will be pointing at a different anonymous function that was created in a different execution context that was create when `fnSequence` was called this second time.
### Scope Chain
What happens when the function held by `fn1` is executed the first time? A new execution context is created for the execution of the anonymous function. A return value is to be found from the identifier `x`. The function's scope object is inspected for an `x` attribute but none is found. This is where the *scope chain* comes in. Having failed to find `x` in the current execution context JavaScript takes the object held by the function's scope attribute and looks for `x` there. It finds it since the functions scope was created inside an execution of `fnSequence`, retrieves its value and increments it. Hence 1 is output and the `x` in this scope is incremented to 2.
Now when `fn2` is executed it is ultimately attached to a different execution context whose `x` attribute is still 1. Hence executing `fn2` also results in 1.
As you can see `fn1` and `fn2` each generate their own independent sequence of numbers.
|
Variables not declared with var are global in scope.
Functions introduce a scope, but note that if blocks and other blocks do not introduce a scope.
I could also see much information about this by Googling Javascript scope. That's really what I would recommend.
<http://www.digital-web.com/articles/scope_in_javascript/>
|
OO Javascript : Definitive explanation of variable scope
|
[
"",
"javascript",
"oop",
""
] |
I'm using the document.form.submit() function for a rather large input form (hundreds of fields, it's an inventory application). I'm calling this after the user has been idle for a certain amount of time and I would like to save any data they've typed. When I try this the page reloads (the action is #) but any new text typed in the fields is not passed in the REQUEST, so I don't get to put it in the DB. Is there some fundamental reason why this happens or is my code just not playing nice together (I'm using the EXTJS grid view to show the form and a library for tracking idle time)?
Thanks,
Robert
|
I guess I put the answer here. What I found was that doing this:
setTimeout('frm.submit();', 2000);
caused the page to reload but didn't submit the form. When I did this:
frm.submit();
The form was submitted and the data was passed. I don't know why the first way didn't work, but I don't need to know that:)
|
Might the server be voiding out the input values. Say if your page on the server looks like this:
```
<form action="/page.cgi">
...
<input name="Fieldx" value=""/>
</form>
```
I think it'll void out the field. Or this the server action might be setting it indirectly. In JSF, something like this.
```
<input name="Fieldx" value="#{bean.nullProperty}"/>
```
What do you have on the server and what's your browser?
|
How to submit form with data before logging someone out?
|
[
"",
"javascript",
"forms",
"submit",
""
] |
I was writing some Unit tests last week for a piece of code that generated some SQL statements.
I was trying to figure out a regex to match `SELECT`, `INSERT` and `UPDATE` syntax so I could verify that my methods were generating valid SQL, and after 3-4 hours of searching and messing around with various regex editors I gave up.
I managed to get partial matches but because a section in quotes can contain any characters it quickly expands to match the whole statement.
Any help would be appreciated, I'm not very good with regular expressions but I'd like to learn more about them.
By the way it's C# RegEx that I'm after.
**Clarification**
I don't want to need access to a database as this is part of a Unit test and I don't wan't to have to maintain a database to test my code. which may live longer than the project.
|
Regular expressions can match languages only a finite state automaton can parse, which is very limited, whereas SQL is a syntax. **It can be demonstrated you can't validate SQL with a regex.** So, you can stop trying.
|
SQL is a [type-2 grammar](http://en.wikipedia.org/wiki/Chomsky_hierarchy), it is too powerful to be described by regular expressions. It's the same as if you decided to generate C# code and then validate it without invoking a compiler. Database engine in general is too complex to be easily stubbed.
That said, you may try [ANTLR's SQL grammars](https://github.com/antlr/grammars-v4/wiki).
|
Regular expression to match common SQL syntax?
|
[
"",
"sql",
"regex",
"unit-testing",
""
] |
I'm in the process of writing a Java 2D game. I'm using the built-in Java 2D drawing libraries, drawing on a Graphics2D I acquire from a BufferStrategy from a Canvas in a JFrame (which is sometimes full-screened). The BufferStrategy is double-buffered. Repainting is done actively, via a timer. I'm having some performance issues though, especially on Linux.
And Java2D has so very many ways of creating graphics buffers and drawing graphics that I just don't know if I'm doing the right thing. I've been experimenting with graphics2d.getDeviceConfiguration().createCompatibleVolatileImage, which looks promising, but I have no real proof it it's going to be any faster if I switch the drawing code to that.
In your experience, what is the fastest way to render 2D graphics onto the screen in Java 1.5+? Note that the game is quite far ahead, so I don't want to switch to a completely different method of drawing, like OpenGL or a game engine. I basically want to know how to get the fastest way of using a Graphics2D object to draw stuff to the screen.
|
I'm having the same issues as you are I think. Check out my post here:
[Java2D Performance Issues](https://stackoverflow.com/questions/196890/java2d-performance-issues)
It shows the reason for the performance degradation and how to fix it. It's not guaranteed to work well on all platforms though. You'll see why in the post.
|
A synthesis of the answers to this post, the answers to [Consty's](https://stackoverflow.com/questions/196890/java2d-performance-issues), and my own research:
What works:
* Use `GraphicsConfiguration.createCompatibleImage` to create images compatible with what you're drawing on. This is absolutely essential!
* Use double-buffered drawing via `Canvas.createBufferStrategy`.
* Use `-Dsun.java2d.opengl=True` where available to speed up drawing.
* Avoid using transforms for scaling. Instead, cache scaled versions of the images you are going to use.
* Avoid translucent images! Bitmasked images are fine, but translucency is very expensive in Java2D.
In my tests, using these methods, I got a speed increase of 10x - 15x, making proper Java 2D graphics a possibility.
|
Java 2D Drawing Optimal Performance
|
[
"",
"java",
"performance",
"graphics",
"java-2d",
""
] |
I need to get the actual local network IP address of the computer (e.g. 192.168.0.220) from my program using C# and .NET 3.5. I can't just use 127.0.0.1 in this case.
How can I accomplish this?
|
In [*How to get IP addresses in .NET with a host name*](http://www.devcity.net/Articles/62/1/gethostbyname.aspx "Article by John Spano, Published 1 Dec 2002") by John Spano, it says to add the `System.Net` namespace, and use the following code:
> ```
> //To get the local IP address
> string sHostName = Dns.GetHostName ();
> IPHostEntry ipE = Dns.GetHostByName (sHostName);
> IPAddress [] IpA = ipE.AddressList;
> for (int i = 0; i < IpA.Length; i++)
> {
> Console.WriteLine ("IP Address {0}: {1} ", i, IpA[i].ToString ());
> }
> ```
|
If you are looking for the sort of information that the command line utility, ipconfig, can provide, you should probably be using the System.Net.NetworkInformation namespace.
This sample code will enumerate all of the network interfaces and dump the addresses known for each adapter.
```
using System;
using System.Net;
using System.Net.NetworkInformation;
class Program
{
static void Main(string[] args)
{
foreach ( NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces() )
{
Console.WriteLine("Network Interface: {0}", netif.Name);
IPInterfaceProperties properties = netif.GetIPProperties();
foreach ( IPAddress dns in properties.DnsAddresses )
Console.WriteLine("\tDNS: {0}", dns);
foreach ( IPAddressInformation anycast in properties.AnycastAddresses )
Console.WriteLine("\tAnyCast: {0}", anycast.Address);
foreach ( IPAddressInformation multicast in properties.MulticastAddresses )
Console.WriteLine("\tMultiCast: {0}", multicast.Address);
foreach ( IPAddressInformation unicast in properties.UnicastAddresses )
Console.WriteLine("\tUniCast: {0}", unicast.Address);
}
}
}
```
You are probably most interested in the UnicastAddresses.
|
How do I get the Local Network IP address of a computer programmatically?
|
[
"",
"c#",
".net",
".net-3.5",
"ip-address",
""
] |
In languages like Java and C#, strings are immutable and it can be computationally expensive to build a string one character at a time. In said languages, there are library classes to reduce this cost such as C# `System.Text.StringBuilder` and Java `java.lang.StringBuilder`.
Does php (4 or 5; I'm interested in both) share this limitation? If so, are there similar solutions to the problem available?
|
No, there is no type of stringbuilder class in PHP, since strings are mutable.
That being said, there are different ways of building a string, depending on what you're doing.
echo, for example, will accept comma-separated tokens for output.
```
// This...
echo 'one', 'two';
// Is the same as this
echo 'one';
echo 'two';
```
What this means is that you can output a complex string without actually using concatenation, which would be slower
```
// This...
echo 'one', 'two';
// Is faster than this...
echo 'one' . 'two';
```
If you need to capture this output in a variable, you can do that with the [output buffering functions](https://www.php.net/outcontrol).
Also, PHP's array performance is really good. If you want to do something like a comma-separated list of values, just use implode()
```
$values = array( 'one', 'two', 'three' );
$valueList = implode( ', ', $values );
```
Lastly, make sure you familiarize yourself with [PHP's string type](https://www.php.net/types.string) and it's different delimiters, and the implications of each.
|
I was curious about this, so I ran a test. I used the following code:
```
<?php
ini_set('memory_limit', '1024M');
define ('CORE_PATH', '/Users/foo');
define ('DS', DIRECTORY_SEPARATOR);
$numtests = 1000000;
function test1($numtests)
{
$CORE_PATH = '/Users/foo';
$DS = DIRECTORY_SEPARATOR;
$a = array();
$startmem = memory_get_usage();
$a_start = microtime(true);
for ($i = 0; $i < $numtests; $i++) {
$a[] = sprintf('%s%sDesktop%sjunk.php', $CORE_PATH, $DS, $DS);
}
$a_end = microtime(true);
$a_mem = memory_get_usage();
$timeused = $a_end - $a_start;
$memused = $a_mem - $startmem;
echo "TEST 1: sprintf()\n";
echo "TIME: {$timeused}\nMEMORY: $memused\n\n\n";
}
function test2($numtests)
{
$CORE_PATH = '/Users/shigh';
$DS = DIRECTORY_SEPARATOR;
$a = array();
$startmem = memory_get_usage();
$a_start = microtime(true);
for ($i = 0; $i < $numtests; $i++) {
$a[] = $CORE_PATH . $DS . 'Desktop' . $DS . 'junk.php';
}
$a_end = microtime(true);
$a_mem = memory_get_usage();
$timeused = $a_end - $a_start;
$memused = $a_mem - $startmem;
echo "TEST 2: Concatenation\n";
echo "TIME: {$timeused}\nMEMORY: $memused\n\n\n";
}
function test3($numtests)
{
$CORE_PATH = '/Users/shigh';
$DS = DIRECTORY_SEPARATOR;
$a = array();
$startmem = memory_get_usage();
$a_start = microtime(true);
for ($i = 0; $i < $numtests; $i++) {
ob_start();
echo $CORE_PATH,$DS,'Desktop',$DS,'junk.php';
$aa = ob_get_contents();
ob_end_clean();
$a[] = $aa;
}
$a_end = microtime(true);
$a_mem = memory_get_usage();
$timeused = $a_end - $a_start;
$memused = $a_mem - $startmem;
echo "TEST 3: Buffering Method\n";
echo "TIME: {$timeused}\nMEMORY: $memused\n\n\n";
}
function test4($numtests)
{
$CORE_PATH = '/Users/shigh';
$DS = DIRECTORY_SEPARATOR;
$a = array();
$startmem = memory_get_usage();
$a_start = microtime(true);
for ($i = 0; $i < $numtests; $i++) {
$a[] = "{$CORE_PATH}{$DS}Desktop{$DS}junk.php";
}
$a_end = microtime(true);
$a_mem = memory_get_usage();
$timeused = $a_end - $a_start;
$memused = $a_mem - $startmem;
echo "TEST 4: Braced in-line variables\n";
echo "TIME: {$timeused}\nMEMORY: $memused\n\n\n";
}
function test5($numtests)
{
$a = array();
$startmem = memory_get_usage();
$a_start = microtime(true);
for ($i = 0; $i < $numtests; $i++) {
$CORE_PATH = CORE_PATH;
$DS = DIRECTORY_SEPARATOR;
$a[] = "{$CORE_PATH}{$DS}Desktop{$DS}junk.php";
}
$a_end = microtime(true);
$a_mem = memory_get_usage();
$timeused = $a_end - $a_start;
$memused = $a_mem - $startmem;
echo "TEST 5: Braced inline variables with loop-level assignments\n";
echo "TIME: {$timeused}\nMEMORY: $memused\n\n\n";
}
test1($numtests);
test2($numtests);
test3($numtests);
test4($numtests);
test5($numtests);
```
...
And got the following results. Image attached. Clearly, sprintf is the least efficient way to do it, both in terms of time and memory consumption.
EDIT: view image in another tab unless you have eagle vision.

|
php String Concatenation, Performance
|
[
"",
"php",
"string",
"concatenation",
""
] |
I have a search form with a query builder. The builder is activated by a button. Something like this
```
<h:form id="search_form">
<h:outputLabel for="expression" value="Expression"/>
<h:inputText id="expression" required="true" value="#{searcher.expression}"/>
<button onclick="openBuilder(); return false;">Open Builder</button>
<h:commandButton value="Search" action="#{searcher.search}"/>
</h:form>
```
The result is HTML that has both a `<button/>` and an `<input type="submit"/>` in the form. If the user enters a string into the expression field and hits the enter key rather than clicking the submit button, the query builder is displayed when the expected behavior is that the search be submitted. What gives?
|
A button in an HTML form is assumed to be used to submit the form. Change button to input type="button" and that should fix it.
Alternatively, add type="button" to the button element.
|
as first, give an ID to Search button.
Then,on textbox, you could intercept client event **onkeydown**, with a (javascript) function like this:
```
function KeyDownHandler(event)
{
// process only the Enter key
if (event.keyCode == 13)
{
// cancel the default submit
event.returnValue=false;
event.cancel = true;
// submit the form by programmatically clicking the specified button
document.getElementById('searchButtonId').click();
}
}
```
I hoper i help you.
|
Seam/JSF form submit firing button onclick event
|
[
"",
"java",
"html",
"firefox",
"jsf",
"seam",
""
] |
I have a .net 2.0 ascx control with a start time and end time textboxes. The data is as follows:
txtStart.Text = 09/19/2008 07:00:00
txtEnd.Text = 09/19/2008 05:00:00
I would like to calculate the total time (hours and minutes) in JavaScript then display it in a textbox on the page.
|
Once your textbox date formats are known in advance, you can use [Matt Kruse's Date functions](http://www.mattkruse.com/javascript/date/) in Javascript to convert the two to a timestamp, subtract and then write to the resulting text box.
Equally the [JQuery Date Input](http://jonathanleighton.com/projects/date-input#date-formatting) code for `stringToDate` could be adapted for your purposes - the below takes a string in the format "YYYY-MM-DD" and converts it to a date object. The timestamp (`getTime()`) of these objects could be used for your calculations.
```
stringToDate: function(string) {
var matches;
if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2})$/)) {
return new Date(matches[1], matches[2] - 1, matches[3]);
} else {
return null;
};
}
```
|
```
function stringToDate(string) {
var matches;
if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2}) (\d{2,2}):(\d{2,2}):(\d{2,2})$/)) {
return new Date(matches[1], matches[2] - 1, matches[3], matches[4], matches[5], matches[6]);
} else {
return null;
};
}
function getTimeSpan(ticks) {
var d = new Date(ticks);
return {
hour: d.getUTCHours(),
minute: d.getMinutes(),
second: d.getSeconds()
}
}
var beginDate = stringToDate('2008-09-19 07:14:00');
var endDate = stringToDate('2008-09-19 17:35:00');
var sp = getTimeSpan(endDate - beginDate);
alert("timeuse:" + sp.hour + " hour " + sp.minute + " minute " + sp.second + " second ");
```
you can use getUTCHours() instead Math.floor(n / 3600000);
|
Calculate timespan in JavaScript
|
[
"",
"asp.net",
"javascript",
""
] |
The following method does not work because the inner block declares a variable of the same name as one in the outer block. Apparently variables belong to the method or class in which they are declared, not to the block in which they are declared, so I therefore can't write a short little temporary block for debugging that happens to push a variable in the outer scope off into shadow just for a moment:
```
void methodName() {
int i = 7;
for (int j = 0; j < 10; j++) {
int i = j * 2;
}
}
```
Almost every block-scoped language I've ever used supported this, including trivial little languages that I wrote interpreters and compilers for in school. Perl can do this, as can Scheme, and even C. Even PL/SQL supports this!
What's the rationale for this design decision for Java?
Edit: as somebody pointed out, Java does have block-scoping. What's the name for the concept I'm asking about? I wish I could remember more from those language-design classes. :)
|
I believe the rationale is that most of the time, that isn't intentional, it is a programming or logic flaw.
in an example as trivial as yours, its obvious, but in a large block of code, accidentally redeclaring a variable may not be obvious.
ETA: it might also be related to exception handling in java. i thought part of this question was discussed in a question related to why variables declared in a try section were not available in the catch/finally scopes.
|
Well, strictly speaking, Java *does* have block-scoped variable declarations; so this is an error:
```
void methodName() {
for (int j = 0; j < 10; j++) {
int i = j * 2;
}
System.out.println(i); // error
}
```
Because 'i' doesn't exist outside the for block.
The problem is that Java doesn't allow you to create a variable with the same name of another variable that was declared in an outer block of the same method. As other people have said, supposedly this was done to prevent bugs that are hard to identify.
|
Why does Java not have block-scoped variable declarations?
|
[
"",
"java",
"syntax",
"language-design",
""
] |
I have a c# object with a property called Gender which is declared as a char.
```
private char _Gender;
public char Gender
{
get{ return _Gender; }
set{ _Gender = value; }
}
```
What string is returned/created when I call MyObject.Gender.ToString()?
I ask because I am calling a webservice (which accepts a string rather than a char) so I am doing a ToString on the property as I pass it over. I was expecting it to send an empty string if the char is not set.
However this doesn't appear to be the case, so the question is what is the string?
|
The default value of char is unicode 0, so I'd expect "\u0000" to be returned.
|
Fields are always initialized to their default value; 0/false/null - this this is the 0 character, \0.
If you want an empty string, use strings directly - i.e. "".
You could use a conditional operator:
```
string s = c == 0 ? "" : c.ToString();
```
Alternatively, nullable types might help - i.e.
```
char? c; // a field
...
string s = c.ToString(); // is ""
c = 'a';
s = c.ToString(); // is "a"
```
|
What is returned when I call ToString() on an uninitialized char object property?
|
[
"",
"c#",
""
] |
I heard that you could right-shift a number by .5 instead of using Math.floor(). I decided to check its limits to make sure that it was a suitable replacement, so I checked the following values and got the following results in Google Chrome:
```
2.5 >> .5 == 2;
2.9999 >> .5 == 2;
2.999999999999999 >> .5 == 2; // 15 9s
2.9999999999999999 >> .5 == 3; // 16 9s
```
After some fiddling, I found out that the highest possible value of two which, when right-shifted by .5, would yield 2 is 2.9999999999999997779553950749686919152736663818359374999999¯ (with the 9 repeating) in Chrome and Firefox. The number is 2.9999999999999997779¯ in IE.
My question is: what is the significance of the number .0000000000000007779553950749686919152736663818359374? It's a very strange number and it really piqued my curiosity.
I've been trying to find an answer or at least some kind of pattern, but I think my problem lies in the fact that I really don't understand the bitwise operation. I understand the idea in principle, but shifting a bit sequence by .5 doesn't make any sense at all to me. Any help is appreciated.
For the record, the weird digit sequence changes with 2^x. The highest possible values of the following numbers that still truncate properly:
```
for 0: 0.9999999999999999444888487687421729788184165954589843749¯
for 1: 1.9999999999999999888977697537484345957636833190917968749¯
for 2-3: x+.99999999999999977795539507496869191527366638183593749¯
for 4-7: x+.9999999999999995559107901499373838305473327636718749¯
for 8-15: x+.999999999999999111821580299874767661094665527343749¯
...and so forth
```
|
Actually, you're simply ending up doing a floor() on the first operand, without any floating point operations going on. Since the left shift and right shift bitwise operations only make sense with integer operands, the JavaScript engine is converting the two operands to integers first:
```
2.999999 >> 0.5
```
Becomes:
```
Math.floor(2.999999) >> Math.floor(0.5)
```
Which in turn is:
```
2 >> 0
```
Shifting by 0 bits means "don't do a shift" and therefore you end up with the first operand, simply truncated to an integer.
The SpiderMonkey source code has:
```
switch (op) {
case JSOP_LSH:
case JSOP_RSH:
if (!js_DoubleToECMAInt32(cx, d, &i)) // Same as Math.floor()
return JS_FALSE;
if (!js_DoubleToECMAInt32(cx, d2, &j)) // Same as Math.floor()
return JS_FALSE;
j &= 31;
d = (op == JSOP_LSH) ? i << j : i >> j;
break;
```
Your seeing a "rounding up" with certain numbers is due to the fact the JavaScript engine can't handle decimal digits beyond a certain precision and therefore your number ends up getting rounded up to the next integer. Try this in your browser:
```
alert(2.999999999999999);
```
You'll get 2.999999999999999. Now try adding one more 9:
```
alert(2.9999999999999999);
```
You'll get a 3.
|
This is possibly the single worst idea I have ever seen. Its only possible purpose for existing is for winning an obfusticated code contest. There's no significance to the long numbers you posted -- they're an artifact of the underlying floating-point implementation, filtered through god-knows how many intermediate layers. Bit-shifting by a fractional number of bytes is insane and I'm surprised it doesn't raise an exception -- but that's Javascript, always willing to redefine "insane".
If I were you, I'd avoid ever using this "feature". Its only value is as a possible root cause for an unusual error condition. Use `Math.floor()` and take pity on the next programmer who will maintain the code.
---
Confirming a couple suspicions I had when reading the question:
* Right-shifting any fractional number `x` by any fractional number `y` will simply truncate `x`, giving the same result as `Math.floor()` while thoroughly confusing the reader.
* 2.999999999999999777955395074968691915... is simply the largest number that can be differentiated from "3". Try evaluating it by itself -- if you add anything to it, it will evaluate to 3. This is an artifact of the browser and local system's floating-point implementation.
|
2.9999999999999999 >> .5?
|
[
"",
"javascript",
"bit-manipulation",
"precision",
""
] |
I have a marker interface defined as
```
public interface IExtender<T>
{
}
```
I have a class that implements IExtender
```
public class UserExtender : IExtender<User>
```
At runtime I recieve the UserExtender type as a parameter to my evaluating method
```
public Type Evaluate(Type type) // type == typeof(UserExtender)
```
How do I make my Evaluate method return
```
typeof(User)
```
based on the runtime evaluation. I am sure reflection is involved but I can't seem to crack it.
(I was unsure how to word this question. I hope it is clear enough.)
|
I went this way based on some of the tidbits provided. It could be made more robust to handle multiple generic arguments on the interface.... but I didn't need it to ;)
```
private static Type SafeGetSingleGenericParameter(Type type, Type interfaceType)
{
if (!interfaceType.IsGenericType || interfaceType.GetGenericArguments().Count() != 1)
return type;
foreach (Type baseInterface in type.GetInterfaces())
{
if (baseInterface.IsGenericType &&
baseInterface.GetGenericTypeDefinition() == interfaceType.GetGenericTypeDefinition())
{
return baseInterface.GetGenericArguments().Single();
}
}
return type;
}
```
|
I read your question completely differently than the other answers.
If the evaluate signature can be changed to:
```
public Type Evaluate<T>(IExtender<T> it)
{
return typeof(T);
}
```
This doesn't require the calling code to change, but does require the parameter to be of type `IExtender<T>`, however you can easily get at the type `T` :
```
// ** compiled and tested
UserExtender ue = new UserExtender();
Type t = Evaluate(ue);
```
Certainly it's not as generic as something just taking a `Type` parameter, but this is a different take on the problem. Also note that there are [Security Considerations for Reflection [msdn]](https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/security-considerations-for-reflection)
|
How do I determine the value of a generic parameter on my class instance
|
[
"",
"c#",
"generics",
"reflection",
""
] |
Is there anyway to declare an object of a class before the class is created in C++? I ask because I am trying to use two classes, the first needs to have an instance of the second class within it, but the second class also contains an instance of the first class. I realize that you may think I might get into an infinite loop, but I actually need to create and instance of the second class before the first class.
|
You can't do something like this:
```
class A {
B b;
};
class B {
A a;
};
```
The most obvious problem is the compiler doesn't know how to large it needs to make class A, because the size of B depends on the size of A!
You can, however, do this:
```
class B; // this is a "forward declaration"
class A {
B *b;
};
class B {
A a;
};
```
Declaring class B as a forward declaration allows you to use pointers (and references) to that class without yet having the whole class definition.
|
You can't declare an instance of an undefined class but you can declare a **pointer** to one:
```
class A; // Declare that we have a class A without defining it yet.
class B
{
public:
A *itemA;
};
class A
{
public:
B *itemB;
};
```
|
Declare an object even before that class is created
|
[
"",
"c++",
"class",
"object",
"instantiation",
""
] |
Is it possible to specify a Java `classpath` that includes a JAR file contained within another JAR file?
|
If you're trying to create a single jar that contains your application and its required libraries, there are two ways (that I know of) to do that. The first is [One-Jar](http://one-jar.sourceforge.net/), which uses a special classloader to allow the nesting of jars. The second is [UberJar](http://classworlds.codehaus.org/uberjar.html), (or [Shade](http://maven.apache.org/plugins/maven-shade-plugin/)), which explodes the included libraries and puts all the classes in the top-level jar.
I should also mention that UberJar and Shade are plugins for Maven1 and Maven2 respectively. As mentioned below, you can also use the assembly plugin (which in reality is much more powerful, but much harder to properly configure).
|
You do NOT want to use those "explode JAR contents" solutions. They definitely make it harder to see stuff (since everything is exploded at the same level). Furthermore, there could be naming conflicts (should not happen if people use proper packages, but you cannot always control this).
The feature that you want is one of the [top 25 Sun RFEs](http://bugs.sun.com/bugdatabase/top25_rfes.do): [RFE 4648386](https://bugs.java.com/bugdatabase/view_bug?bug_id=4648386), which Sun, in their infinite wisdom, has designated as being of low priority. We can only hope that Sun wakes up...
In the meanwhile, the best solution that I have come across (which I wish that Sun would copy in the JDK) is to use the custom class loader [JarClassLoader](http://www.jdotsoft.com/JarClassLoader.php).
|
Classpath including JAR within a JAR
|
[
"",
"java",
"classpath",
""
] |
What are some of the new features that can be used in .NET 2.0 that are specific to C# 3.0/3.5 after upgrading to Visual Studio 2008? Also, what are some of the features that aren't available?
**Available**
* Lambdas
* Extension methods (by declaring an empty System.Runtime.CompilerServices.ExtensionAttribute)
* Automatic properties
* Object initializers
* Collection Initializers
* LINQ to Objects (by implementing IEnumerable extension methods, see [LinqBridge](http://www.albahari.com/nutshell/linqbridge.aspx))
**Not Available**
* Expression trees
* WPF/Silverlight Libraries
|
You can use any new C# 3.0 feature that is handled by the compiler by emitting 2.0-compatible IL and doesn't reference any of the new 3.5 assemblies:
* Lambdas (used as `Func<..>`, not `Expression<Func<..>>` )
* Extension methods (by declaring an empty `System.Runtime.CompilerServices.ExtensionAttribute`)
* Automatic properties
* Object Initializers
* Collection Initializers
* LINQ to Objects (by implementing `IEnumerable<T>` extension methods, see [LinqBridge](http://www.albahari.com/nutshell/linqbridge.aspx))
|
Pretty much everything! Daniel Moth covers this [here](http://www.danielmoth.com/Blog/2007/05/using-c-30-from-net-20.html) and [here](http://www.danielmoth.com/Blog/2007/05/using-extension-methods-in-fx-20.html). That only leaves runtime support: LINQ-to-Objects is provided by [LINQBridge](http://www.albahari.com/nutshell/linqbridge.aspx) - which leaves just bigger APIs like Expression support, and tools like LINQ-to-SQL. These are too big to be reasonably ported back to .NET 2.0, so I'd use .NET 3.5 for these.
|
C# .NET 3.0/3.5 features in 2.0 using Visual Studio 2008
|
[
"",
"c#",
".net",
"visual-studio",
""
] |
What is the best way to make a `<div>` fade away after a given amount of time (without using some of the JavaScript libraries available).
I'm looking for a very lightweight solution not requiring a huge JavaScript library to be sent to the browser.
|
Not sure why you'd be so against using something like jQuery, which would make accomplishing this effect all but trivial, but essentially, you need to wrap a series of changes to the -moz-opacity, opacity, and filter:alpha CSS rules in a setTimeout().
Or, use jQuery, and wrap a fadeOut() call in setTimeout. Your choice.
|
Here's some javascript that does it. I found it on a javascript tutorial web site somewhere (which I was unable to find again) and modified it.
```
var TimeToFade = 200.0;
function fade(eid)
{
var element = document.getElementById(eid);
if(element == null) return;
if(element.FadeState == null)
{
if(element.style.opacity == null || element.style.opacity == ''
|| element.style.opacity == '1') {
element.FadeState = 2;
} else {
element.FadeState = -2;
}
}
if(element.FadeState == 1 || element.FadeState == -1) {
element.FadeState = element.FadeState == 1 ? -1 : 1;
element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
} else {
element.FadeState = element.FadeState == 2 ? -1 : 1;
element.FadeTimeLeft = TimeToFade;
setTimeout("animateFade(" + new Date().getTime()
+ ",'" + eid + "')", 33);
}
}
function animateFade(lastTick, eid)
{
var curTick = new Date().getTime();
var elapsedTicks = curTick - lastTick;
var element = document.getElementById(eid);
if(element.FadeTimeLeft <= elapsedTicks) {
element.style.opacity = element.FadeState == 1 ? '1' : '0';
element.style.filter = 'alpha(opacity = '
+ (element.FadeState == 1 ? '100' : '0') + ')';
element.FadeState = element.FadeState == 1 ? 2 : -2;
element.style.display = "none";
return;
}
element.FadeTimeLeft -= elapsedTicks;
var newOpVal = element.FadeTimeLeft/TimeToFade;
if(element.FadeState == 1) {
newOpVal = 1 - newOpVal;
}
element.style.opacity = newOpVal;
element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';
setTimeout("animateFade(" + curTick + ",'" + eid + "')", 33);
}
```
The following html shows how it works:
```
<html><head>
<script type="text/javascript" src="fade.js"></script>
</head><body>
<div id="fademe" onclick="fade( 'fademe' )">
<p>This will fade when you click it</p>
</div>
</body></html>
```
|
Make a div fade away nicely after a given amount of time
|
[
"",
"javascript",
"css",
"html",
"fade",
""
] |
I've been using Xcode for the usual C/C++/ObjC development. I'm wondering what are practical considerations, opinions of Xcode, Eclipse or NetBeans usage on a Mac for Java development?
Please don't include my current usage of Xcode in your analysis.
|
I like [NetBeans](http://netbeans.org/) on OS X for Java.
It seems like I spend more time configuring eclipse to get a decent java programming environment. With NetBeans the setup time is less and I can get down to programming quicker...
|
You missed the Rolls Royce of all IDEs. [IntelliJ Idea](http://www.jetbrains.com/idea/).
If you can afford to buy a personal license, go for it. Edit: There’s a free Community Edition which is a superb way to get started with Java, Scala or Kotlin.
|
Java Development on a Mac - Xcode, Eclipse, or Netbeans
|
[
"",
"java",
"eclipse",
"xcode",
"macos",
"netbeans",
""
] |
Are there any more generic tools that can "compile" or basically merge multiple PHP files into a single file based on includes and autoloading classes? I'm thinking of something similar to Doctrine's compiling functionality or the compiling that many of the major JS frameworks do for "production" sites to lighten the file size and improve performance.
Before writing a script to do it myself, I just want to find out if anything worth looking at already exists (Google hasn't been much help so far).
**Edit:** I've actually written a [blog post](http://www.nickawilliams.com/2008/09/04/the-new-phar-php-package/) about the .phar archive format and am very excited about that. I was actually more concerned about performance, but it sounds like merging files would not yield any benefit.
Does anyone have any real data that might suggest the performance gain (or lack thereof) from merging multiple scripts into a single file?
|
Out of curiosity, why do you want to do this? If it's for performance, don't bother. Just use regular includes instead of auto-loading, and it will have much of the same effect. For performance you're better off looking at one of the run-time caching solutions.
|
I am not a php programmer, but I have seen something called "phar" file. Its like jar for php. maybe u shud look into that
A quick google search reveals
<http://pear.php.net/pepr/pepr-proposal-show.php?id=88>
<http://www.pixelated-dreams.com/archives/78-PHAR-PHPs-Answer-to-.jar.html>
|
PHP Script Compression/"Compilation" Tools
|
[
"",
"php",
"optimization",
"compilation",
"merge",
""
] |
I'm looking for something that will monitor Windows directories for size and file count over time. I'm talking about a handful of servers and a few thousand folders (millions of files).
Requirements:
* Notification on X increase in size over Y time
* Notification on X increase in file count over Y time
* Historical graphing (or at least saving snapshot data over time) of size and file count
* All of this on a set of directories and their child directories
I'd prefer a free solution but would also appreciate getting pointed in the right direction. If we were to write our own, how would we go about doing that? Available languages being Ruby, Groovy, Java, Perl, or PowerShell (since I'd be writing it).
|
You might want to take a look at [PolyMon](http://www.codeplex.com/polymon), which is an open source systems monitoring solution. It allows you to write custom monitors in any .NET language, and allows you to create custom PowerShell monitors.
It stores data on a SQL Server back end and provides graphing. For your purpose, you would just need a script that would get the directory size and file count.
Something like:
```
$size = 0
$count = 0
$path = '\\unc\path\to\directory\to\monitor'
get-childitem -path $path -recurse | Where-Object {$_ -is [System.IO.FileInfo]} | ForEach-Object {$size += $_.length; $count += 1}
```
In reply to Scott's comment:
Sure. you could wrap it in a while loop
```
$ESCkey = 27
Write-Host "Press the ESC key to stop sniffing" -foregroundcolor "CYAN"
$Running=$true
While ($Running)
{
if ($host.ui.RawUi.KeyAvailable) {
$key = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyUp,IncludeKeyDown")
if ($key.VirtualKeyCode -eq $ESCkey) {
$Running=$False
}
#rest of function here
}
```
I would not do that for a PowerShell monitor, which you can schedule to run periodically, but for a script to run in the background, the above would work. You could even add some database access code to log the results to a database, or log it to a file.. what ever you want.
|
There are several solutions out there, including some free ones. Some that I have worked with include:
[Nagios](http://www.nagios.org/)
and
[Big Brother](http://bb4.com/)
A quick google search can probably find more.
|
Monitoring Windows directory size
|
[
"",
"java",
"ruby",
"perl",
"powershell",
"groovy",
""
] |
I thought I'd offer this softball to whomever would like to hit it out of the park. What are generics, what are the advantages of generics, why, where, how should I use them? Please keep it fairly basic. Thanks.
|
* Allows you to write code/use library methods which are type-safe, i.e. a List<string> is guaranteed to be a list of strings.
* As a result of generics being used the compiler can perform compile-time checks on code for type safety, i.e. are you trying to put an int into that list of strings? Using an ArrayList would cause that to be a less transparent runtime error.
* Faster than using objects as it either avoids boxing/unboxing (where .net has to convert [value types to reference types or vice-versa](https://stackoverflow.com/questions/5057267/what-is-the-difference-between-a-reference-type-and-value-type-in-c)) or casting from objects to the required reference type.
* Allows you to write code which is applicable to many types with the same underlying behaviour, i.e. a Dictionary<string, int> uses the same underlying code as a Dictionary<DateTime, double>; using generics, the framework team only had to write one piece of code to achieve both results with the aforementioned advantages too.
|
I really hate to repeat myself. I hate typing the same thing more often than I have to. I don't like restating things multiple times with slight differences.
Instead of creating:
```
class MyObjectList {
MyObject get(int index) {...}
}
class MyOtherObjectList {
MyOtherObject get(int index) {...}
}
class AnotherObjectList {
AnotherObject get(int index) {...}
}
```
I can build one reusable class... (in the case where you don't want to use the raw collection for some reason)
```
class MyList<T> {
T get(int index) { ... }
}
```
I'm now 3x more efficient and I only have to maintain one copy. Why WOULDN'T you want to maintain less code?
This is also true for non-collection classes such as a `Callable<T>` or a `Reference<T>` that has to interact with other classes. Do you really want to extend `Callable<T>` and `Future<T>` and every other associated class to create type-safe versions?
I don't.
|
What is cool about generics, why use them?
|
[
"",
"c#",
"generics",
"types",
""
] |
We have an "engine" that loads dlls dynamically (whatever is located in a certain directory) and calls Workflow classes from them by way of reflection.
We now have some new Workflows that require access to a database, so I figured that I would put a config file in the dll directory.
But for some reason my Workflows just don't see the config file.
```
<configuration>
<appSettings>
<add key="ConnectString" value="Data Source=officeserver;Database=mydatabase;User ID=officeuser;Password=officeuser;" />
</appSettings>
</configuration>
```
Given the above config file, the following code prints an empty string:
```
Console.WriteLine(ConfigurationManager.AppSettings["ConnectString"]);
```
I think what I want is to just specify a config filename, but I'm having problems here. I'm just not getting results.
Anyone have any pointers?
|
If your code sample for reading the AppSettings is in your DLL, then it will attempt to read the config file for the application and not the config file for the DLL. This is because you're using Reflection to execute the code.
|
Funny, where I'm at we're doing something very similar and the config file loads just fine. In our case I think each new config file's name matches that of it's associated assembly. So MyLibrary.dll would have a file named MyLibrary.dll.config with information for that file assembly. Also, the example I have handy is using VB.Net rather than C# (we have some of each) and all the settings in there are for the VB-specific My.Settings namespace, so we don't use the ConfigurationManager class directly to read them.
The settings themselves look like this:
```
<applicationSettings>
<MyLibrary.My.MySettings>
<setting name="SomeSetting" serializeAs="String">
<value>12345</value>
</setting>
</MyLibrary.My.MySettings>
</applicationSettings>
```
|
App.config for dll
|
[
"",
"c#",
"dll",
"app-config",
""
] |
Is it possible to unsubscribe an anonymous method from an event?
If I subscribe to an event like this:
```
void MyMethod()
{
Console.WriteLine("I did it!");
}
MyEvent += MyMethod;
```
I can un-subscribe like this:
```
MyEvent -= MyMethod;
```
But if I subscribe using an anonymous method:
```
MyEvent += delegate(){Console.WriteLine("I did it!");};
```
is it possible to unsubscribe this anonymous method? If so, how?
|
```
Action myDelegate = delegate(){Console.WriteLine("I did it!");};
MyEvent += myDelegate;
// .... later
MyEvent -= myDelegate;
```
Just keep a reference to the delegate around.
|
One technique is to declare a variable to hold the anonymous method which would then be available inside the anonymous method itself. This worked for me because the desired behavior was to unsubscribe after the event was handled.
Example:
```
MyEventHandler foo = null;
foo = delegate(object s, MyEventArgs ev)
{
Console.WriteLine("I did it!");
MyEvent -= foo;
};
MyEvent += foo;
```
|
Unsubscribe anonymous method in C#
|
[
"",
"c#",
"delegates",
"anonymous-methods",
""
] |
I'm looking for a XPath library to query over XML documents in FF, IE, Opera and Safari... and couldn't find one. Have you seen any?
|
Google has just released Wicked Good XPath - A rewrite of Cybozu Lab's famous JavaScript-XPath.
Link: <https://github.com/google/wicked-good-xpath>
The rewritten version is 40% smaller and about 30% faster than the original implementation.
|
[**Google's AJAXSLT**](http://code.google.com/p/ajaxslt/) open source project fits well the stated requirements.
As their own description goes to say:
"AJAXSLT is an implementation of XSLT in **JavaScript**. Because XSLT uses XPath, **it is also an implementation of XPath that can be used independently of XSLT**. This implementation has the advantange that it makes XSLT uniformly available on more browsers than natively provide it, and that it can be extended to yet more browsers if necessary.
**AJAXSLT is interesting for developers who strive aggressively for cross browser compatibility of their advanced web applications**.
"
**UPDATE**: In the end of 2010 Michael Kay has been compiling his Saxon XSLT 2.0 processor to Javascript (thus making it available to all 5 major browsers) using GWT. It is likely there will be a light-weight in-browser Saxon soon.
|
Cross-browser XPath implementation in JavaScript
|
[
"",
"javascript",
"xml",
"xpath",
""
] |
I am trying to use the `Directory.GetFiles()` method to retrieve a list of files of multiple types, such as `mp3`'s and `jpg`'s. I have tried both of the following with no luck:
```
Directory.GetFiles("C:\\path", "*.mp3|*.jpg", SearchOption.AllDirectories);
Directory.GetFiles("C:\\path", "*.mp3;*.jpg", SearchOption.AllDirectories);
```
Is there a way to do this in one call?
|
For .NET 4.0 and later,
```
var files = Directory.EnumerateFiles("C:\\path", "*.*", SearchOption.AllDirectories)
.Where(s => s.EndsWith(".mp3") || s.EndsWith(".jpg"));
```
For earlier versions of .NET,
```
var files = Directory.GetFiles("C:\\path", "*.*", SearchOption.AllDirectories)
.Where(s => s.EndsWith(".mp3") || s.EndsWith(".jpg"));
```
**edit:** *Please read the comments. The improvement that [Paul Farry](https://stackoverflow.com/users/97516/paul-farry) suggests, and the memory/performance issue that [Christian.K](https://stackoverflow.com/users/21567/christian-k) points out are both very important.*
|
How about this:
```
private static string[] GetFiles(string sourceFolder, string filters, System.IO.SearchOption searchOption)
{
return filters.Split('|').SelectMany(filter => System.IO.Directory.GetFiles(sourceFolder, filter, searchOption)).ToArray();
}
```
I found it here (in the comments): <http://msdn.microsoft.com/en-us/library/wz42302f.aspx>
|
Can you call Directory.GetFiles() with multiple filters?
|
[
"",
"c#",
"filesystems",
".net",
""
] |
Let's say I have a java program that makes an HTTP request on a server using HTTP 1.1 and doesn't close the connection. I make one request, and read all data returned from the input stream I have bound to the socket. However, upon making a second request, I get no response from the server (or there's a problem with the stream - it doesn't provide any more input). If I make the requests in order (Request, request, read) it works fine, but (request, read, request, read) doesn't.
Could someone shed some insight onto why this might be happening? (Code snippets follow). No matter what I do, the second read loop's isr\_reader.read() only ever returns -1.
```
try{
connection = new Socket("SomeServer", port);
con_out = connection.getOutputStream();
con_in = connection.getInputStream();
PrintWriter out_writer = new PrintWriter(con_out, false);
out_writer.print("GET http://somesite HTTP/1.1\r\n");
out_writer.print("Host: thehost\r\n");
//out_writer.print("Content-Length: 0\r\n");
out_writer.print("\r\n");
out_writer.flush();
// If we were not interpreting this data as a character stream, we might need to adjust byte ordering here.
InputStreamReader isr_reader = new InputStreamReader(con_in);
char[] streamBuf = new char[8192];
int amountRead;
StringBuilder receivedData = new StringBuilder();
while((amountRead = isr_reader.read(streamBuf)) > 0){
receivedData.append(streamBuf, 0, amountRead);
}
// Response is processed here.
if(connection != null && !connection.isClosed()){
//System.out.println("Connection Still Open...");
out_writer.print("GET http://someSite2\r\n");
out_writer.print("Host: somehost\r\n");
out_writer.print("Connection: close\r\n");
out_writer.print("\r\n");
out_writer.flush();
streamBuf = new char[8192];
amountRead = 0;
receivedData.setLength(0);
while((amountRead = isr_reader.read(streamBuf)) > 0 || amountRead < 1){
if (amountRead > 0)
receivedData.append(streamBuf, 0, amountRead);
}
}
// Process response here
}
```
Responses to questions:
Yes, I'm receiving chunked responses from the server.
I'm using raw sockets because of an outside restriction.
Apologies for the mess of code - I was rewriting it from memory and seem to have introduced a few bugs.
So the consensus is I have to either do (request, request, read) and let the server close the stream once I hit the end, or, if I do (request, read, request, read) stop before I hit the end of the stream so that the stream *isn't* closed.
|
According to your code, the only time you'll even reach the statements dealing with sending the second request is when the server closes the output stream (your input stream) after receiving/responding to the first request.
The reason for that is that your code that is supposed to read only the first response
```
while((amountRead = isr_reader.read(streamBuf)) > 0) {
receivedData.append(streamBuf, 0, amountRead);
}
```
will block until the server closes the output stream (i.e., when `read` returns `-1`) or until the read timeout on the socket elapses. In the case of the read timeout, an exception will be thrown and you won't even get to sending the second request.
The problem with HTTP responses is that they don't tell you how many bytes to read from the stream until the end of the response. This is not a big deal for HTTP 1.0 responses, because the server simply closes the connection after the response thus enabling you to obtain the response (status line + headers + body) by simply reading everything until the end of the stream.
With HTTP 1.1 persistent connections you can no longer simply read everything until the end of the stream. You first need to read the status line and the headers, line by line, and then, based on the status code and the headers (such as Content-Length) decide how many bytes to read to obtain the response body (if it's present at all). If you do the above properly, your read operations will complete before the connection is closed or a timeout happens, and you will have read exactly the response the server sent. This will enable you to send the next request and then read the second response in exactly the same manner as the first one.
P.S. Request, request, read might be "working" in the sense that your server supports request pipelining and thus, receives and processes both request, and you, as a result, read both responses into one buffer as your "first" response.
P.P.S Make sure your `PrintWriter` is using the `US-ASCII` encoding. Otherwise, depending on your system encoding, the request line and headers of your HTTP requests might be malformed (wrong encoding).
|
Writing a simple http/1.1 client respecting the RFC is not such a difficult task.
To solve the problem of the blocking i/o access where reading a socket in java, you must use java.nio classes.
SocketChannels give the possibility to perform a non-blocking i/o access.
This is necessary to send HTTP request on a persistent connection.
Furthermore, nio classes will give better performances.
My stress test give to following results :
* HTTP/1.0 (java.io) -> HTTP/1.0 (java.nio) = +20% faster
* HTTP/1.0 (java.io) -> HTTP/1.1 (java.nio with persistent connection) = +110% faster
|
HTTP 1.1 Persistent Connections using Sockets in Java
|
[
"",
"java",
"http",
"sockets",
""
] |
I'm making a simple scheduler with C# in .Net. All it does is execute a simple select statement on a table in a SQL Server DB once per minute (this does not need to scale or anything... the db does not have a high load). Here is my proposed implementation:
```
static void Main(string[] args)
{
while (true)
{
System.Threading.Thread.Sleep(timeout); // timeout is, say, 60000
CheckTable();
}
}
```
Is this ok? What is a better way?
p.s. Someone suggested using the Windows Forms Timer class... however that seems like overkill.
Cheers!
|
While it is technically legal you are probably better of using a timer. They are not much more code to set up and you can let the runtime take care of spawning new threads. If you ever needed to use this again in another program it would also create a performance bottleneck where a timer would not.
The timer will add more code though since you need to use a timer trigger event.
|
Close.
1. This will run every (1 minute + time to call proc). Maybe that's OK, maybe it isn't. If it isn't OK you need to subtract the amount of time it took to ran.
2. You should have a try-catch block around it. You don't want it to die entirely just because of a temporary database or network issue.
|
Is this an acceptable way to make a simple "scheduler" in C#?
|
[
"",
"c#",
"sql-server",
"scheduling",
""
] |
Is there a Generics Friendly way of using Collection.EMPTY\_LIST in my Java Program.
I know I could just declare one myself, but I'm just curious to know if there's a way in the JDK to do this.
Something like `users = Collections<User>.EMPTY_LIST;`
|
By doing the following:
```
List<User> users = Collections.emptyList();
```
The type of the returned list from `Collections.emptyList();` will be *inferred* as a `String` due to the left-hand-side of the assignment. However, if you prefer to not have this inference, you can define it explicitly by doing the following:
```
List<User> users = Collections.<User>emptyList();
```
In this particular instance, this may appear as redundant to most people (in fact, I've seen very little code out in the wild that makes use of explicit type arguments), however for a method with the signature: `void doStuff(List<String> users)` it would be perfectly clean for one to invoke `doStuff()` with an explicit type argument as follows:
```
doStuff(Collections.<String>emptyList());
```
|
```
List<User> users = Collections.emptyList();
```
|
Can I use Collections.EMPTY_LIST wihout an UncheckedException?
|
[
"",
"generics",
"java",
""
] |
I'm encountering some peculiarities with LINQ to SQL.
With a relatively simple query, I want to select some fields, but have the date fields formatted as strings, which I first achieved like this:
```
var list = dataContext.MyLists.Single(x => x.ID == myId);
var items = from i in list.MyItems
select
new
{
i.ID,
i.Sector,
i.Description,
CompleteDate = i.CompleteDate.HasValue ? i.CompleteDate.Value.ToShortDateString() : "",
DueDate = i.DueDate.HasValue ? i.DueDate.Value.ToShortDateString() : ""
};
```
Later on I tried the following query, which is exactly the same, except I'm querying straight from my dataContext, rather than an element in my first query:
```
var items = from i in dataContext.MyLists
select
new
{
i.ID,
i.Sector,
i.Description,
CompleteDate = i.CompleteDate.HasValue ? i.CompleteDate.Value.ToShortDateString() : "",
DueDate = i.DueDate.HasValue ? i.DueDate.Value.ToShortDateString() : ""
};
```
The first one runs fine, yet the second query yields a:
*Could not translate expression '...' into SQL and could not treat it as a local expression.*
If I remove the lines that Format the date, it works fine. If I remove the .HasValue check it also works fine, until there are null values.
Any ideas?
Anthony
|
I'd do the SQL part without doing the formatting, then do the formatting on the client side:
```
var items = list.MyItems.Select(item => new { item.ID, item.Sector, item.Description,
item.CompleteDate, item.DueDate })
.AsEnumerable() // Don't do the next bit in the DB
.Select(item => new { item.ID, item.Sector, item.Description,
CompleteDate = FormatDate(CompleteDate),
DueDate = FormatDate(DueDate) });
static string FormatDate(DateTime? date)
{
return date.HasValue ? date.Value.ToShortDateString() : ""
}
```
|
In the first query, you have already got the data back from the database by the time the second line runs (var items = ...). This means that the 2nd line runs at the client, where ToShortDateString can run quite happily.
In the second query, because the select runs directly on an IQueryable collection (dataContext.MyLists), it attempts to translate the select into SQL for processing at the server, where ToShortDateString is not understood - hence the "Could Not Translate.." exception.
To understand this a bit better, you really need to understand the difference between IQueryable and IEnumerable, and at which point a Linq To Sql query stops being IQueryable and becomes IEnumerable. There is plenty of stuff on the web about this.
Hope this helps,
Paul
|
LINQ to SQL Peculiarities
|
[
"",
"c#",
"linq",
"linq-to-sql",
""
] |
I'm currently working on the `Tips.js` from `mootools` library and my code breaks on the line that has those `el.$tmp`, and console says it's undefined
Can anybody help me?
|
in 1.11 (haven't checked in 1.2+) $tmp is a reference to the element itself, created and used internally by the garbage collector:
```
var Garbage = {
elements: [],
collect: function(el){
if (!el.$tmp){
Garbage.elements.push(el);
el.$tmp = {'opacity': 1};
}
return el;
},
trash: function(elements){
for (var i = 0, j = elements.length, el; i < j; i++){
if (!(el = elements[i]) || !el.$tmp) continue;
if (el.$events) el.fireEvent('trash').removeEvents();
for (var p in el.$tmp) el.$tmp[p] = null;
for (var d in Element.prototype) el[d] = null;
Garbage.elements[Garbage.elements.indexOf(el)] = null;
el.htmlElement = el.$tmp = el = null;
}
Garbage.elements.remove(null);
},
empty: function(){
Garbage.collect(window);
Garbage.collect(document);
Garbage.trash(Garbage.elements);
}
};
```
the lines `el.$tmp = {'opacity': 1};` (in collect method above) and `el.htmlElement = el.$tmp = el = null;` (in trash method above) are the only places in the source where this property is assigned that i could find, although it's called by various other methods, such as Element.setOpacity and Element.getStyle (specifically, only to return opacity value), as well as methods in the Tips class
1.2 might not have this issue, but in any case, hope that helps and sorry i couldn't help more
|
I'd suggest taking your question and posting it, along with a link to the page to either/or/and:
<http://mooforum.net>
<http://groups.google.com/group/mootools-users/topics>
That's the community that swarms with it.
Now as for answering it here - I'd need a lot more information (code example?)
|
mootools or javascript : what does $tmp stand for or what does it pertain too
|
[
"",
"javascript",
"mootools",
""
] |
I have a helper class pulling a string from an XML file. That string is a file path (so it has backslashes in it). I need to use that string as it is... How can I use it like I would with the literal command?
Instead of this:
```
string filePath = @"C:\somepath\file.txt";
```
I want to do this:
```
string filePath = @helper.getFilePath(); //getFilePath returns a string
```
This isn't how I am actually using it; it is just to make what I mean a little clearer. Is there some sort of .ToLiteral() or something?
|
I don't think you have to worry about it if you already have the value. The @ operator is for when you're specifying the string (like in your first code snippet).
What are you attempting to do with the path string that isn't working?
|
I'm not sure if I understand. In your example: if `helper.getFilePath()` returns `"c:\somepath\file.txt"`, there will be no problem, since the `@` is only needed if you are explicitely specifying a string with "".
When Functions *talk to each other*, you will always get the literal path. If the XML contains `c:\somepath\file.txt` and your function returns `c:\somepath\file.txt`, then string filePath will also contain `c:\somepath\file.txt` as a valid path.
|
Using the literal '@' with a string variable
|
[
"",
"c#",
"string",
""
] |
I want to make sure people can't type the name of a PHP script in the URL and run it. What's the best way of doing this?
I could set a variable in the file that will be including this file, and then check that variable in the file being included, but is there an easier way?
|
You could check the URI and see if that file is being called with `
```
$_SERVER['SCRIPT_FILENAME']
```
or you could move the file outside the public folder, this is a better solution.
|
In a few of the open source applications I've poked around in, including Joomla and PHPBB, they declare a constant in the main includes file, and then verify that constant exists in each of the includes:
```
// index.php
require_once 'includes.php';
// includes.php
define('IN_MY_PROJECT', true);
include 'myInc.php';
// myInc.php
defined('IN_MY_PROJECT') || die("No direct access, plsktnxbai");
```
|
What's the best way to only allow a PHP file to be included?
|
[
"",
"php",
""
] |
Given:
```
interface I
{
}
class B: I
{
}
class C: I
{
}
class A
{
public void Method(B arg)
{
}
public void Method(C arg)
{
}
public void Method(I arg)
{
// THIS is the method I want to simplify.
if (I is B)
{
this.Method(arg as B);
}
else if (I is C)
{
this.Method(arg as C);
}
}
}
```
I know that there are better ways to design this type of interactions, but because of
details which would take too long to explain this is not possible.
Since this pattern will be duplicated MANY times, I would like to replace the
conditional logic with a generic implementation which I could use just one line.
I can't see a simple way to implement this generic method/class, but my instincts tell me it should be possible.
Any help would be appreciated.
|
What you want is [double dispatch](http://en.wikipedia.org/wiki/Double_dispatch), and [visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern) in particular.
|
I would put the method inside the interface and then let polymorphism decide which method to call
```
interface I
{
void Method();
}
class B : I
{
public void Method() { /* previously A.Method(B) */}
}
class C : I
{
public void Method() { /* previously A.Method(C) */ }
}
class A
{
public void Method(I obj)
{
obj.Method();
}
}
```
Now when you need to add a new class, you only need to implement I.Method. You don't need to touch A.Method.
|
conditional logic based on type
|
[
"",
"c#",
".net",
"polymorphism",
""
] |
How do I fix that error once and for all? I just want to be able to do unions in MySQL.
(I'm looking for a shortcut, like an option to make MySQL ignore that issue or take it's best guess, not looking to change collations on 100s of tables ... at least not today)
|
Not sure about mySQL but in MSSQL you can change the collation in the query so for example if you have 2 tables with different collation and you want to join them or as in you situation crate UNION you can do
```
select column1 from tableWithProperCollation
union all
select column1 COLLATE SQL_Latin1_General_CP1_CI_AS from tableWithDifferentCollation
```
Of course SQL\_Latin1\_General\_CP1\_CI\_AS is just an example of collation you want to "convert" to
|
Thanks Kristof. In this case it was being caused by selecting a literal in the first select, and not from any different table collations.
Ironically I got it working by following this [old blog post](http://www.answermysearches.com/mysql-fixing-illegal-mix-of-collations-message/352/) I made for that issue.
|
MySQL - Illegal mix of collations (utf8_general_ci,COERCIBLE) and (latin1_swedish_ci,IMPLICIT) for operation 'UNION'
|
[
"",
"sql",
"mysql",
"unicode",
"union",
"collation",
""
] |
Is there any way to determine a removable drive speed in Windows without actually reading in a file. And if I do have to read in a file, how much needs to be read to get a semi accurate speed (e.g. determine whether a device is USB2 or USB1)?
**EDIT**: Just to clarify, USB2 and USB1 were an example. These could be Compact Flash, could be SSD, could be a removable drive. And I am trying to determine this as fast as possible as it has a real effect on the responsiveness of the application.
**EDIT**: Should also clarify, this has to be done programatically. It will probably be done in C++.
**EDIT**: Boost answer is kind of what I was looking for (though I haven't written any WMI in C++). But I need to know what properties I have to check to determine relative speed. I don't need exact speed (like I said about the difference in speed between USB1 and USB2), but I need to know if it is going to be SLLOOOOWWW.
|
[WMI - Physical Disks Properties](http://www.computerperformance.co.uk/vbscript/wmi_disks_physical.htm) is an article I found which would at least help you figure out what you have connected. I foresee things heading toward tables equating particular manufacturers and models to speeds, which is not as simple a solution as you may have hoped for.
|
You may have better results querying the operating system for information about the hardware rather than trying to reverse engineer it from data transfer timing information.
For example, identical transfer speeds don't necessarily mean the same technology is being used by two devices, although other factors such as seek times would improve the accuracy, if such information is available to your application.
In order to keep the application responsive while this work is done, try doing the calls asynchronously and provide some sort of progress indicator to the user. As an example, take a look at how [WinDirStat](http://windirstat.info/) handles this progress indication (I love the pac-man animation as each directory is analyzed).
|
Any way to determine speed of a removable drive in windows?
|
[
"",
"c++",
"windows",
"removable-storage",
""
] |
Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there is a better way to do this?
Thanks!
```
def unique_filename(file_name):
counter = 1
file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext')
while os.path.isfile(file_name):
file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1]
counter += 1
return file_name
```
I really *do* require the files to be in a single directory, and numbering duplicates is definitely acceptable in my case, so I'm not looking for a more robust method (tho' I suppose any pointers are welcome), but just to make sure that what this accomplishes is getting done the right way.
|
One issue is that there is a race condition in your above code, since there is a gap between testing for existance, and creating the file. There may be security implications to this (think about someone maliciously inserting a symlink to a sensitive file which they wouldn't be able to overwrite, but your program running with a higher privilege could) Attacks like these are why things like os.tempnam() are deprecated.
To get around it, the best approach is to actually try create the file in such a way that you'll get an exception if it fails, and on success, return the actually opened file object. This can be done with the lower level os.open functions, by passing both the os.O\_CREAT and os.O\_EXCL flags. Once opened, return the actual file (and optionally filename) you create. Eg, here's your code modified to use this approach (returning a (file, filename) tuple):
```
def unique_file(file_name):
counter = 1
file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext')
while 1:
try:
fd = os.open(file_name, os.O_CREAT | os.O_EXCL | os.O_RDRW)
return os.fdopen(fd), file_name
except OSError:
pass
file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1]
counter += 1
```
**[Edit]** Actually, a better way, which will handle the above issues for you, is probably to use the tempfile module, though you may lose some control over the naming. Here's an example of using it (keeping a similar interface):
```
def unique_file(file_name):
dirname, filename = os.path.split(file_name)
prefix, suffix = os.path.splitext(filename)
fd, filename = tempfile.mkstemp(suffix, prefix+"_", dirname)
return os.fdopen(fd), filename
>>> f, filename=unique_file('/home/some_dir/foo.txt')
>>> print filename
/home/some_dir/foo_z8f_2Z.txt
```
The only downside with this approach is that you will always get a filename with some random characters in it, as there's no attempt to create an unmodified file (/home/some\_dir/foo.txt) first.
You may also want to look at tempfile.TemporaryFile and NamedTemporaryFile, which will do the above and also automatically delete from disk when closed.
|
Yes, this is a good strategy for readable but unique filenames.
**One important change**: You should replace `os.path.isfile` with `os.path.lexists`! As it is written right now, if there is a directory named /foo/bar.baz, your program will try to overwrite that with the new file (which won't work)... since `isfile` only checks for files and not directories. `lexists` checks for directories, symlinks, etc... basically if there's any reason that filename could not be created.
EDIT: @Brian gave a better answer, which is more secure and robust in terms of race conditions.
|
Is this the best way to get unique version of filename w/ Python?
|
[
"",
"python",
"filenames",
""
] |
In an aspx C#.NET page (I am running framework v3.5), I need to know where the user came from since they cannot view pages without logging in. If I have page `A` (the page the user wants to view) redirect to page `B` (the login page), the Request.UrlReferrer object is null.
Background: If a user isn't logged in, I redirect to the Login page (`B` in this scenario). After login, I would like to return them to the page they were requesting before they were forced to log in.
**UPDATE:**
A nice quick solution seems to be:
`//if user not logged in
Response.Redirect("..MyLoginPage.aspx?returnUrl=" + Request.ServerVariables["SCRIPT_NAME"]);`
Then, just look at QueryString on login page you forced them to and put the user where they were after successful login.
|
If you use the standard Membership provider, and set the Authorization for the directory/page, the code will automatically set a query parameter of ReturnUrl and redirect after a successfull login.
If you don't want to use the Membership provider pattern, I would suggest manually doing the query string parameter thing as well. HTTP referrers are not very reliable.
|
UrlReferrer is based off the [HTTP\_REFERER](http://en.wikipedia.org/wiki/Referer) header that a browser *should* send. But, as with all things left up to the client, it's variable.
I know some "security" suites (like Norton's Internet Security) will strip that header, in the belief that it aids tracking user behavior. Also, I'm sure there's some Firefox extensions to do the same thing.
Bottom line is that you shouldn't trust it. Just append the url to the GET string and redirect based off that.
UPDATE: As mentioned in the comments, it is probably a good idea to restrict the redirect from the GET parameter to only work for domain-less relative links, refuse directory patterns (../), etc. So still sanity check the redirect; if you follow the standard "don't use any user-supplied input blindly" rule you should be safe.
|
Request.UrlReferrer null?
|
[
"",
"c#",
".net",
"visual-studio",
"visual-studio-2008",
""
] |
I'm not sure if this is something I should do in T-SQL or not, and I'm pretty sure using the word 'iterate' was wrong in this context, since you should never iterate anything in sql. It should be a set based operation, correct? Anyway, here's the scenario:
I have a stored proc that returns many uniqueidentifiers (single column results). These ids are the primary keys of records in a another table. I need to set a flag on all the corresponding records in that table.
How do I do this without the use of cursors? Should be an easy one for you sql gurus!
|
This may not be the most efficient, but I would create a temp table to hold the results of the stored proc and then use that in a join against the target table. For example:
```
CREATE TABLE #t (uniqueid int)
INSERT INTO #t EXEC p_YourStoredProc
UPDATE TargetTable
SET a.FlagColumn = 1
FROM TargetTable a JOIN #t b
ON a.uniqueid = b.uniqueid
DROP TABLE #t
```
|
You could also change your stored proc to a user-defined function that returns a table with your uniqueidentifiers. You can joing directly to the UDF and treat it like a table which avoids having to create the extra temp table explicitly. Also, you can pass parameters into the function as you're calling it, making this a very flexible solution.
```
CREATE FUNCTION dbo.udfGetUniqueIDs
()
RETURNS TABLE
AS
RETURN
(
SELECT uniqueid FROM dbo.SomeWhere
)
GO
UPDATE dbo.TargetTable
SET a.FlagColumn = 1
FROM dbo.TargetTable a INNER JOIN dbo.udfGetUniqueIDs() b
ON a.uniqueid = b.uniqueid
```
**Edit:**
This will work on SQL Server 2000 and up...
|
How can one iterate over stored procedure results from within another stored procedure....without cursors?
|
[
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
""
] |
Currently I have this (edited after reading advice):
```
struct Pair<T, K> : IEqualityComparer<Pair<T, K>>
{
readonly private T _first;
readonly private K _second;
public Pair(T first, K second)
{
_first = first;
_second = second;
}
public T First { get { return _first; } }
public K Second { get { return _second; } }
#region IEqualityComparer<Pair<T,K>> Members
public bool Equals(Pair<T, K> x, Pair<T, K> y)
{
return x.GetHashCode(x) == y.GetHashCode(y);
}
public int GetHashCode(Pair<T, K> obj)
{
int hashCode = obj.First == null ? 0 : obj._first.GetHashCode();
hashCode ^= obj.Second == null ? 0 : obj._second.GetHashCode();
return hashCode;
}
#endregion
public override int GetHashCode()
{
return this.GetHashCode(this);
}
public override bool Equals(object obj)
{
return (obj != null) &&
(obj is Pair<T, K>) &&
this.Equals(this, (Pair<T, K>) obj);
}
}
```
The problem is that First and Second may not be reference types (VS actually warns me about this), but the code still compiles. Should I cast them (First and Second) to objects before I compare them, or is there a better way to do this?
Edit:
Note that I *want* this struct to support value and reference types (in other words, constraining by class is not a valid solution)
Edit 2:
As to what I'm trying to achieve, I want this to work in a Dictionary. Secondly, SRP isn't important to me right now because that isn't really the essence of this problem - it can always be refactored later. Thirdly, comparing to default(T) will not work in lieu of comparing to null - try it.
|
It looks like you need IEquatable instead:
```
internal struct Pair<T, K> : IEquatable<Pair<T, K>>
{
private readonly T _first;
private readonly K _second;
public Pair(T first, K second)
{
_first = first;
_second = second;
}
public T First
{
get { return _first; }
}
public K Second
{
get { return _second; }
}
public bool Equals(Pair<T, K> obj)
{
return Equals(obj._first, _first) && Equals(obj._second, _second);
}
public override bool Equals(object obj)
{
return obj is Pair<T, K> && Equals((Pair<T, K>) obj);
}
public override int GetHashCode()
{
unchecked
{
return (_first != null ? _first.GetHashCode() * 397 : 0) ^ (_second != null ? _second.GetHashCode() : 0);
}
}
}
```
|
Your IEqualityComparer implementation should be a different class (and definately not a struct as you want to reuse the reference).
Also, your hashcode should never be cached, as the default GetHashcode implementation for a struct (which you do not override) will take that member into account.
|
How do I implement IEqualityComparer on an immutable generic Pair struct?
|
[
"",
"c#",
"generics",
"struct",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.