Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
What is the best practice of Unicode processing in C++?
* Use [ICU](http://www.icu-project.org/) for dealing with your data (or a similar library) * In your own data store, make sure everything is stored in the same encoding * Make sure you are always using your unicode library for mundane tasks like string length, capitalization status, etc. Never use standard library buil...
If you don't care about backwards compatibility with previous C++ standards, the current C++11 standard has built in Unicode support: <http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2011/n3242.pdf> So the truly best practice for Unicode processing in C++ would be to use the built in facilities for it. That isn't a...
Unicode Processing in C++
[ "", "c++", "unicode", "" ]
I'm going to be implementing a `PHP/mySQL` setup to store credit card information. It seems like `AES_ENCRYPT/AES_DECRYPT` is the way to go, **but I'm still confused on one point:** **How do I keep the encryption key secure?** Hardwiring it into my PHP scripts (which will live on the same server as the db) seems li...
You should think long and hard about whether you REALLY need to keep the CC#. If you don't have a great reason, DON'T! Every other week you hear about some company being compromised and CC#'s being stolen. All these companies made a fatal flaw - they kept too much information. Keep the CC# until the transaction clears....
MySQL, there is six easy steps you can do to secure your sensitive data. Step 1: Remove wildcards in the grant tables Step 2: Require the use of secure passwords Note: Use the MySQL “--secure-auth” option to prevent the use of older, less secure MySQL password formats. Step 3: Check the permissions of configuration...
How do I keep a mySQL database secure?
[ "", "php", "mysql", "security", "aes", "" ]
We have some legacy code that needs to identify in the Page\_Load which event caused the postback. At the moment this is implemented by checking the Request data like this... if (Request.Form["\_\_EVENTTARGET"] != null && (Request.Form["\_\_EVENTTARGET"].IndexOf("BaseGrid") > -1 // BaseGrid event ( e.g. sort)     ...
This should get you the control that caused the postback: ``` public static Control GetPostBackControl(Page page) { Control control = null; string ctrlname = page.Request.Params.Get("__EVENTTARGET"); if (ctrlname != null && ctrlname != string.Empty) { control = page.FindControl(ctrlname); ...
In addition to the above code, if control is of type ImageButton then add the below code, ``` if (control == null) { for (int i = 0; i < page.Request.Form.Count; i++) { if ((page.Request.Form.Keys[i].EndsWith(".x")) || (page.Request.Form.Keys[i].EndsWith(".y"))) { control = page.FindContro...
How to Identify Postback event in Page_Load
[ "", "c#", "asp.net", "" ]
Boost is meant to be **the** standard non-standard C++ library that every C++ user can use. Is it reasonable to assume it's available for an open source C++ project, or is it a large dependency too far?
Basically your question boils down to “is it reasonable to have [free library xyz] as a dependency for a C++ open source project.” Now consider the following quote from Stroustrup and the answer is really a no-brainer: > Without a good library, most interesting tasks are hard to do in > C++; but given a good library,...
Take a look at <http://www.boost.org/doc/tools.html>. Specifically the *bcp* utility would come in handy if you would like to embed your boost-dependencies into your project. An excerpt from the web site: > "The bcp utility is a tool for extracting subsets of Boost, it's useful for Boost authors who want to distribute...
Boost dependency for a C++ open source project?
[ "", "c++", "boost", "standard-library", "" ]
Ok, my web application is at **C:\inetpub\wwwroot\website** The files I want to link to are in **S:\someFolder** Can I make a link in the webapp that will direct to the file in **someFolder**?
If its on a different drive on the server, you will need to make a [virtual directory](http://www.zerog.com/ianetmanual/IISVDirs_O.html) in IIS. You would then link to "`/virtdirect/somefolder/`"
You would have to specifically map it to some URL through your web server. Otherwise, all your files would be accessible to anyone who guessed their URL and you don't want that...
How can I hyperlink to a file that is not in my Web Application?
[ "", "c#", "asp.net", "" ]
I have a SQL query (MS Access) and I need to add two columns, either of which may be null. For instance: ``` SELECT Column1, Column2, Column3+Column4 AS [Added Values] FROM Table ``` where Column3 or Column4 may be null. In this case, I want null to be considered zero (so `4 + null = 4, null + null = 0`). Any sugges...
Since ISNULL in Access is a boolean function (one parameter), use it like this: ``` SELECT Column1, Column2, IIF(ISNULL(Column3),0,Column3) + IIF(ISNULL(Column4),0,Column4) AS [Added Values] FROM Table ```
According to [Allen Browne](http://allenbrowne.com/QueryPerfIssue.html), the fastest way is to use `IIF(Column3 is Null; 0; Column3)` because both `NZ()` and `ISNULL()` are VBA functions and calling VBA functions slows down the JET queries. I would also add that if you work with linked SQL Server or Oracle tables, the...
SQL Null set to Zero for adding
[ "", "sql", "ms-access", "database-design", "" ]
I need to determine if a Class object representing an interface extends another interface, ie: ``` package a.b.c.d; public Interface IMyInterface extends a.b.d.c.ISomeOtherInterface{ } ``` according to [the spec](http://web.archive.org/web/20100705124350/http://java.sun.com:80/j2se/1.4.2/docs/api/java/lang/C...
Use Class.getInterfaces such as: ``` Class<?> c; // Your class for(Class<?> i : c.getInterfaces()) { // test if i is your interface } ``` Also the following code might be of help, it will give you a set with all super-classes and interfaces of a certain class: ``` public static Set<Class<?>> getInheritance(Clas...
``` if (interface.isAssignableFrom(extendedInterface)) ``` is what you want i always get the ordering backwards at first but recently realized that it's the exact opposite of using instanceof ``` if (extendedInterfaceA instanceof interfaceB) ``` is the same thing but you have to have instances of the classes rather...
Determining the extended interfaces of a Class
[ "", "java", "reflection", "interface", "" ]
I have the following html code: ``` <h3 id="headerid"><span onclick="expandCollapse('headerid')">&uArr;</span>Header title</h3> ``` I would like to toggle between up arrow and down arrow each time the user clicks the span tag. ``` function expandCollapse(id) { var arrow = $("#"+id+" span").html(); // I have t...
When the HTML is parsed, what JQuery sees in the DOM is a `UPWARDS DOUBLE ARROW` ("⇑"), not the entity reference. Thus, in your Javascript code you should test for `"⇑"` or `"\u21d1"`. Also, you need to change what you're switching to: ``` function expandCollapse(id) { var arrow = $("#"+id+" span").html(); if(...
If you do an alert of `arrow` what does it return? Does it return the exact string that you're matching against? If you are getting the actual characters `'⇓'` and `'⇑'` you may have to match it against `"\u21D1"` and `"\u21D3"`. Also, you may want to try `&#8657;` and `&#8659;` since not all browsers support those en...
How to compare an html entity with jQuery
[ "", "javascript", "jquery", "html-entities", "" ]
I'm creating a small database application to teach myself the following concepts 1. C# programming 2. .Net 3.5 framework 3. WPF 4. LINQ ORM I want to use Microsoft Access as the database but I can't seem to find any mention of whether its possible to use SQLMetal to generate the ORM code from a Microsoft Access datab...
For an embedded database, you can use [SQL Server Compact Edition](http://www.microsoft.com/sql/editions/compact/default.mspx). Unlike SQL Server Express, it is *not* compatible with the LINQ to SQL designer, but it is fully compatible with the command-line SQLMetal. It has a few advantages over SQL Express, like to ab...
I don't think SQL Express would be overkill if you want to learn real-world skills - quite the opposite in fact! That'd be my choice, and whatever I chose, I'd stay clear of Access. Good luck
Can you use LINQ tools such as SQLMetal with an access database?
[ "", "c#", "linq-to-sql", "ms-access", "" ]
I have to load a PDF within a page. Ideally I would like to have a loading animated gif which is replaced once the PDF has loaded.
I'm pretty certain that it cannot be done. Pretty much anything else than PDF works, even Flash. (Tested on Safari, Firefox 3, IE 7) Too bad.
Have you tried: ``` $("#iFrameId").on("load", function () { // do something once the iframe is loaded }); ```
How do I fire an event when a iframe has finished loading in jQuery?
[ "", "javascript", "jquery", "" ]
I am using `setInterval(fname, 10000);` to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event? I want the user to be able to stop the repeated refresh of data.
`setInterval()` returns an interval ID, which you can pass to `clearInterval()`: ``` var refreshIntervalId = setInterval(fname, 10000); /* later */ clearInterval(refreshIntervalId); ``` See the docs for [`setInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) and [`cl...
If you set the return value of `setInterval` to a variable, you can use `clearInterval` to stop it. ``` var myTimer = setInterval(...); clearInterval(myTimer); ```
Stop setInterval call in JavaScript
[ "", "javascript", "dom-events", "setinterval", "" ]
Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code: ``` class hi: def __init__(self): self.ii = "foo" self.kk = "bar" ``` Is there a way for me to do this: ``` >>> mystery_method(hi) ["ii", "kk"] ``` Edit: I originally had asked for cl...
Every object has a `__dict__` variable containing all the variables and its values in it. Try this ``` >>> hi_obj = hi() >>> hi_obj.__dict__.keys() ``` Output ``` dict_keys(['ii', 'kk']) ```
Use [vars()](https://docs.python.org/3/library/functions.html#vars) ``` class Foo(object): def __init__(self): self.a = 1 self.b = 2 vars(Foo()) #==> {'a': 1, 'b': 2} vars(Foo()).keys() #==> ['a', 'b'] ```
How to get instance variables in Python?
[ "", "python", "methods", "instance-variables", "" ]
I saw some code like the following in a JSP ``` <c:if test="<%=request.isUserInRole(RoleEnum.USER.getCode())%>"> <li>user</li> </c:if> ``` My confusion is over the "=" that appears in the value of the `test` attribute. My understanding was that anything included within `<%= %>` is printed to the output, but surel...
All that the `test` attribute looks for to determine if something is true is the string "true" (case in-sensitive). For example, the following code will print "Hello world!" ``` <c:if test="true">Hello world!</c:if> ``` The code within the `<%= %>` returns a boolean, so it will either print the string "true" or "fals...
You can also use something like ``` <c:if test="${ testObject.testPropert == "testValue" }">...</c:if> ```
test attribute in JSTL <c:if> tag
[ "", "java", "jsp", "jstl", "" ]
In C#.Net WPF During UserControl.Load -> What is the best way of showing a whirling circle / 'Loading' Indicator on the UserControl until it has finished gathering data and rendering it's contents?
I generally would create a layout like this: ``` <Grid> <Grid x:Name="MainContent" IsEnabled="False"> ... </Grid> <Grid x:Name="LoadingIndicatorPanel"> ... </Grid> </Grid> ``` Then I load the data on a worker thread, and when it's finished I update the UI under the "MainContent" grid and enab...
This is something that I was working on just recently in order to create a loading animation. This xaml will produce an animated ring of circles. My initial idea was to create an adorner and use this animation as it's content, then to display the loading animation in the adorners layer and grey out the content underne...
What is the best way to display a 'loading' indicator on a WPF control
[ "", "c#", ".net", "wpf", "user-controls", "" ]
I have the following code: ``` String inputFile = "somefile.txt"; FileInputStream in = new FileInputStream(inputFile); FileChannel ch = in.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(BUFSIZE); // BUFSIZE = 256 /* read the file into a buffer, 256 bytes at a time */...
You have to know what the encoding of the file is, and then decode the ByteBuffer into a CharBuffer using that encoding. Assuming the file is ASCII: ``` import java.util.*; import java.io.*; import java.nio.*; import java.nio.channels.*; import java.nio.charset.*; public class Buffer { public static void main(Str...
buf.getChar() is expecting 2 bytes per character but you are only storing 1. Use: ``` System.out.print((char) buf.get()); ```
Reading an ASCII file with FileChannel and ByteArrays
[ "", "java", "file-io", "io", "arrays", "filechannel", "" ]
What is considered as best practice when it comes to assemblies and releases? I would like to be able to reference multiple versions of the same library - solution contains multiple projects that depend on different versions of a commonutils.dll library we build ourselves. As all dependencies are copied to the bin/de...
Here's what I've been living by -- It depends on what you are planning to use the DLL files for. I categorize them in two main groups: 1. Dead-end Assemblies. These are EXE files and DLL files you really aren't planning on referencing from anywhere. Just weakly name these and make sure you have the version numbers yo...
Assemblies can coexist in the GAC (Global Assembly Cache) even if they have the same name given that the version is different. This is how .NET Framework shipped assemblies work. A requirement that must be meet in order for an assembly to be able to be GAC registered is to be signed. Adding version numbers to the name...
Assembly names and versions
[ "", "c#", "assemblies", "naming-conventions", "" ]
Is it possible to use DateTimePicker (Winforms) to pick both date and time (in the dropdown)? How do you change the custom display of the picked value? Also, is it possible to enable the user to type the date/time manually?
Set the Format to Custom and then specify the format: ``` dateTimePicker1.Format = DateTimePickerFormat.Custom; dateTimePicker1.CustomFormat = "MM/dd/yyyy hh:mm:ss"; ``` or however you want to lay it out. You could then type in directly the date/time. If you use MMM, you'll need to use the numeric value for the month...
It is best to use two DateTimePickers for the Job One will be the default for the date section and the second DateTimePicker is for the time portion. Format the second DateTimePicker as follows. ``` timePortionDateTimePicker.Format = DateTimePickerFormat.Time; timePortionDateTimePicker.ShowUpDown = true; `...
DateTimePicker: pick both date and time
[ "", "c#", ".net", "winforms", "datetimepicker", "" ]
I'm trying to determine the best way to truncate or drop extra decimal places in SQL without rounding. For example: ``` declare @value decimal(18,2) set @value = 123.456 ``` This will automatically round `@value` to be `123.46`, which is good in most cases. However, for this project, I don't need that. Is there a si...
You will need to provide 3 numbers to the ROUND function. 1. number **Required. The number to be rounded** 2. decimals **Required. The number of decimal places to round number to operation** 3. *Optional. If 0, it rounds the result to the number of decimal. If another value than 0, it truncates the result to the nu...
``` ROUND ( 123.456 , 2 , 1 ) ``` [When the third parameter **!= 0** it truncates rather than rounds.](https://learn.microsoft.com/sql/t-sql/functions/round-transact-sql#arguments) **Syntax** ``` ROUND ( numeric_expression , length [ ,function ] ) ``` **Arguments** * `numeric_expression` Is an expression of the ...
Truncate (not round) decimal places in SQL Server
[ "", "sql", "sql-server", "t-sql", "rounding", "" ]
Take the following snippet: ``` List<int> distances = new List<int>(); ``` Was the redundancy intended by the language designers? If so, why?
The reason the code appears to be redundant is because, to a novice programmer, it appears to be defining the same thing twice. But this is not what the code is doing. It is defining two separate things that just happen to be of the same type. It is defining the following: 1. A variable named distances of type `List<i...
What's redudant about this? ``` List<int> listOfInts = new List<int>(): ``` Translated to English: (EDIT, cleaned up a little for clarification) * Create a pointer of type List<int> and name it listofInts. * listOfInts is now created but its just a reference pointer pointing to nowhere (null) * Now, create an object...
Redundancy in C#?
[ "", "c#", ".net", "generics", "programming-languages", "" ]
I'm trying to draw a polygon using c# and directx All I get is an ordered list of points from a file and I need to draw the flat polygon in a 3d world. I can load the points and draw a convex shape using a trianglefan and drawuserprimitives. This obviously leads to incorrect results when the polygon is very concave ...
Direct3D can only draw triangles (well, it can draw lines and points as well, but that's besides the point). So if you want to draw any shape that is more complex than a triangle, you have to draw a bunch of touching triangles that equal to that shape. In your case, it's a concave polygon triangulation problem. Given ...
If you are able to use the stencil buffer, it should not be hard to do. Here's a general algorithm: ``` Clear the stencil buffer to 1. Pick an arbitrary vertex v0, probably somewhere near the polygon to reduce floating-point errors. For each vertex v[i] of the polygon in clockwise order: let s be the segment v[i]-...
Is there an efficient\easy way to draw a concave polygon in Direct3d
[ "", "c#", "directx", "polygon", "concave", "" ]
I'm a little confused about how the standard library will behave now that Python (from 3.0) is unicode-based. Will modules such as CGI and urllib use unicode strings or will they use the new 'bytes' type and just provide encoded data?
Logically a lot of things like MIME-encoded mail messages, URLs, XML documents, and so on should be returned as `bytes` not strings. This could cause some consternation as the libraries start to be nailed down for Python 3 and people discover that they have to be more aware of the `bytes`/`string` conversions than they...
One of the great things about this question (and Python in general) is that you can just mess around in the interpreter! [Python 3.0 rc1 is currently available for download](http://www.python.org/download/releases/3.0/). ``` >>> import urllib.request >>> fh = urllib.request.urlopen('http://www.python.org/') >>> print(...
Will everything in the standard library treat strings as unicode in Python 3.0?
[ "", "python", "unicode", "string", "cgi", "python-3.x", "" ]
How can you enumerate an `enum` in C#? E.g. the following code does not compile: ``` public enum Suit { Spades, Hearts, Clubs, Diamonds } public void EnumerateAllSuitsDemoMethod() { foreach (Suit suit in Suit) { DoSomething(suit); } } ``` And it gives the following compile-time e...
**Update:** *If you're using .NET 5 or newer, use [this solution](https://stackoverflow.com/questions/105372/how-to-enumerate-an-enum#65103244).* ``` foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit))) { } ``` **Note**: The cast to `(Suit[])` is not strictly necessary, [but it does make the code 0.5 ns faste...
It looks to me like you really want to print out the names of each enum, rather than the values. In which case `Enum.GetNames()` seems to be the right approach. ``` public enum Suits { Spades, Hearts, Clubs, Diamonds, NumSuits } public void PrintAllSuits() { foreach (string name in Enum.GetNam...
How to enumerate an enum?
[ "", "c#", ".net", "loops", "enums", "enumeration", "" ]
Does somebody know a Java library which serializes a Java object hierarchy into Java code which generates this object hierarchy? Like Object/XML serialization, only that the output format is not binary/XML but Java code.
I am not aware of any libraries that will do this out of the box but you should be able to take one of the many object to XML serialisation libraries and customise the backend code to generate Java. Would probably not be much code. For example a quick google turned up [XStream](http://xstream.codehaus.org/). I've neve...
Serialised data represents the internal data of objects. There isn't enough information to work out what methods you would need to call on the objects to reproduce the internal state. There are two obvious approaches: * Encode the serialised data in a literal String and deserialise that. * Use java.beans XML persiste...
Serialize Java objects into Java code
[ "", "java", "" ]
`mysql_real_escape_string` and `addslashes` are both used to escape data before the database query, so what's the difference? (This question is not about parametrized queries/PDO/mysqli)
> `string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier ] )` > `mysql_real_escape_string()` calls MySQL's library function mysql\_real\_escape\_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a. > `string addslashes ( string $str )` > ...
`mysql_real_escape_string()` has the added benefit of escaping text input correctly with respect to the character set of a database through the optional *link\_identifier* parameter. Character set awareness is a critical distinction. `addslashes()` will add a slash before every eight bit binary representation of each ...
What is the difference between mysql_real_escape_string and addslashes?
[ "", "php", "" ]
I am writing a program which has two panes (via `CSplitter`), however I am having problems figuring out out to resize the controls in each frame. For simplicity, can someone tell me how I would do it for a basic frame with a single `CEdit` control? I'm fairly sure it is to do with the `CEdit::OnSize()` function... But...
When your frame receives an OnSize message it will give you the new width and height - you can simply call the CEdit SetWindowPos method passing it these values. Assume CMyPane is your splitter pane and it contains a CEdit you created in OnCreate called m\_wndEdit: ``` void CMyPane::OnSize(UINT nType, int cx, int cy)...
A window receives WM\_SIZE message (which is processed by OnSize handler in MFC) immediately after it was resized, so CEdit::OnSize is not what you are looking for. You should add OnSize handler in your frame class and inside this handler as Rob [pointed out](https://stackoverflow.com/questions/127514/resizing-control...
Resizing Controls in MFC
[ "", "c++", "mfc", "" ]
Dear Stacktoverflow, can you show me an example of how to use a QScrollBar? Thanks.
It will come down to you using the QScrollArea, it is a widget that implements showing something that is larger than the available space. You will not need to use QScrollBar directly. I don't have a PyQt example but there is a C++ example in the QT distribution it is called the "Image Viewer". The object hierarchy will...
``` >>> import sys >>> from PyQt4 import QtCore, QtGui >>> app = QtGui.QApplication(sys.argv) >>> sb = QtGui.QScrollBar() >>> sb.setMinimum(0) >>> sb.setMaximum(100) >>> def on_slider_moved(value): print "new slider position: %i" % (value, ) >>> sb.connect(sb, QtCore.SIGNAL("sliderMoved(int)"), on_slider_moved) >>> sb....
PyQt - QScrollBar
[ "", "python", "pyqt", "" ]
The [Sun Documentation for DataInput.skipBytes](http://java.sun.com/j2se/1.4.2/docs/api/java/io/DataInput.html#skipBytes(int)) states that it "makes an attempt to skip over n bytes of data from the input stream, discarding the skipped bytes. However, it may skip over some smaller number of bytes, possibly zero. This ma...
1) There might not be that much data available to read (the other end of the pipe might not have sent that much data yet), and the implementing class might be non-blocking (i.e. it will just return what it can, rather than waiting for enough data to fulfil the request). I don't know if any implementations actually beh...
I came across this problem today. It was reading off a network connection on a virtual machine so I imagine there could be a number of reasons for this happening. I solved it by simply forcing the input stream to skip bytes until it had skipped the number of bytes I wanted it to: ``` int byteOffsetX = someNumber; //n ...
When can DataInputStream.skipBytes(n) not skip n bytes?
[ "", "io", "java", "" ]
The following will cause infinite recursion on the == operator overload method ``` Foo foo1 = null; Foo foo2 = new Foo(); Assert.IsFalse(foo1 == foo2); public static bool operator ==(Foo foo1, Foo foo2) { if (foo1 == null) return foo2 == null; return foo1.Equals(foo2); } ``` How d...
Use `ReferenceEquals`: ``` Foo foo1 = null; Foo foo2 = new Foo(); Assert.IsFalse(foo1 == foo2); public static bool operator ==(Foo foo1, Foo foo2) { if (object.ReferenceEquals(null, foo1)) return object.ReferenceEquals(null, foo2); return foo1.Equals(foo2); } ```
Cast to object in the overload method: ``` public static bool operator ==(Foo foo1, Foo foo2) { if ((object) foo1 == null) return (object) foo2 == null; return foo1.Equals(foo2); } ```
How do I check for nulls in an '==' operator overload without infinite recursion?
[ "", "c#", ".net", "operator-overloading", "" ]
So I'm writing a framework on which I want to base a few apps that I'm working on (the framework is there so I have an environment to work with, and a system that will let me, for example, use a single sign-on) I want to make this framework, and the apps it has use a Resource Oriented Architecture. Now, I want to cre...
I prefer to use reg ex over making my own format since it is common knowledge. I wrote a small class that I use which allows me to nest these reg ex routing tables. I use to use something similar that was implemented by inheritance but it didn't need inheritance so I rewrote it. I do a reg ex on a key and map to my ow...
Yet another framework? -- anyway... The trick is with routing is to pass it all over to your routing controller. You'd probably want to use something similar to what I've documented here: <http://www.hm2k.com/posts/friendly-urls> The second solution allows you to use URLs similar to Zend Framework.
PHP Application URL Routing
[ "", "php", "url", "routes", "url-routing", "" ]
Considering "private" is the default access modifier for class Members, why is the keyword even needed?
It's for you (and future maintainers), not the compiler.
There's a certain amount of misinformation here: > "The default access modifier is not private but internal" Well, that depends on what you're talking about. For members of a type, it's private. For top-level types themselves, it's internal. > "Private is only the default for *methods* on a type" No, it's the defau...
What does the "private" modifier do?
[ "", "c#", ".net", "private", "access-modifiers", "private-members", "" ]
We have a couple of developers asking for `allow_url_fopen` to be enabled on our server. What's the norm these days and if `libcurl` is enabled is there really any good reason to allow? Environment is: Windows 2003, PHP 5.2.6, FastCGI
You definitely want `allow_url_include` set to Off, which mitigates many of the risks of `allow_url_fopen` as well. But because not all versions of PHP have `allow_url_include`, best practice for many is to turn off fopen. Like with all features, the reality is that if you don't need it for your application, disable i...
I think the answer comes down to how well you trust your developers to use the feature responsibly? Data from a external URL should be treated like any other untrusted input and as long as that is understood, what's the big deal? The way I see it is that if you treat your developers like children and never let them ha...
Should I allow 'allow_url_fopen' in PHP?
[ "", "php", "configuration", "" ]
Is there any way to edit column names in a DataGridView?
I don't think there is a way to do it without writing custom code. I'd implement a ColumnHeaderDoubleClick event handler, and create a TextBox control right on top of the column header.
You can also change the column name by using: ``` myDataGrid.Columns[0].HeaderText = "My Header" ``` but the `myDataGrid` will need to have been bound to a `DataSource`.
DataGridView Edit Column Names
[ "", "c#", "winforms", "datagridview", "" ]
What is the difference between Views and Materialized Views in Oracle?
Materialized views are disk based and are updated periodically based upon the query definition. Views are virtual only and run the query definition each time they are accessed.
# Views They evaluate the data in the tables underlying the view definition **at the time the view is queried**. It is a logical view of your tables, with no data stored anywhere else. The upside of a view is that it will **always return the latest data to you**. The **downside of a view is that its performance** dep...
What is the difference between Views and Materialized Views in Oracle?
[ "", "sql", "oracle", "view", "relational-database", "materialized-views", "" ]
The purpose of using a Javascript proxy for the Web Service using a service reference with Script Manager is to avoid a page load. If the information being retrieved is potentially sensitive, is there a way to secure this web service call other than using SSL?
If your worried about other people access your web service directly, you could check the calling IP address and host header and make sure it matches expected IP's addresses. If your worried about people stealing information during it's journey from the server to the client, SSL is the only way to go.
I would use ssl it would also depend I suppose on how sensitive your information is.
Is there a good way of securing an ASP.Net web service call made via Javascript on the click event handler of an HTML button?
[ "", "asp.net", "javascript", "service", "security", "" ]
If I have a table in my database called 'Users', there will be a class generated by LINQtoSQL called 'User' with an already declared empty constructor. What is the best practice if I want to override this constructor and add my own logic to it?
The default constructor which is generated by the O/R-Designer, calls a partial function called `OnCreated` - so the best practice is not to override the default constructor, but instead implement the partial function `OnCreated` in `MyDataClasses.cs` to initialize items: ``` partial void OnCreated() { Name = ""; } ...
It doesn't look like you can override the empty constructor. Instead, I would create a method that performs the functionality that you need in the empty constructor and returns the new object. ``` // Add new partial class to extend functionality public partial class User { // Add additional constructor public Use...
Is there a way to override the empty constructor in a class generated by LINQtoSQL?
[ "", "c#", ".net", "linq", "linq-to-sql", "" ]
Newer ARM processors include the PLD and PLI instructions. I'm writing tight inner loops (in C++) which have a non-sequential memory access pattern, but a pattern that naturally my code fully understands. I would anticipate a substantial speedup if I could prefetch the next location whilst processing the current memor...
There should be some Compiler-specific Features. There is no standard way to do it for C/C++. Check out you compiler Compiler Reference Guide. For RealView Compiler see [this](http://www.keil.com/support/man/docs/armccref/armccref_cjagadac.htm) or [this](http://www.keil.com/support/man/docs/armccref/armccref_cjacagfi.h...
If you are trying to extract truly maximum performance from these loops, than I would recommend writing the entire looping construct in assembler. You should be able to use inline assembly depending on the data structures involved in your loop. Even better if you can unroll any piece of your loop (like the parts involv...
Prefetch instructions on ARM
[ "", "c++", "arm", "assembly", "" ]
I'd like my application to have a full-screen mode. What is the easiest way to do this, do I need a third party library for this or is there something in the JDK that already offers this?
Try the [Full-Screen Exclusive Mode API](http://java.sun.com/docs/books/tutorial/extra/fullscreen/index.html). It was introduced in the JDK in release 1.4. Some of the features include: > * **Full-Screen Exclusive Mode** - allows you to suspend the windowing system so that drawing can be done directly to the screen. >...
JFrame `setUndecorated(true)` method
How to program a full-screen mode in Java?
[ "", "java", "graphics", "fullscreen", "" ]
I have an installation program (just a regular C++ MFC program, not Windows Installer based) that needs to set some registry values based on the type of Internet connection: broadband, dialup, and/or wireless. Right now this information is being determined by asking a series of yes or no questions. The problem is that ...
Use InternetGetConnectedState API to retrieve internet connection state. I tested it and it works fine. I found this document which can help: <http://www.pcausa.com/resources/InetActive.txt>
[I have no idea how to get exactly the information you asked for, but...] Maybe you could rephrase (for yourself) what you try to accomplish? Like, instead of asking "does the user have broadband or dialup", ask "how much bandwidth does the user's internet connection have" - and then you can try to answer the rephrased...
How do you detect dialup, broadband or wireless Internet connections in C++ for Windows?
[ "", "c++", "mfc", "windows-xp", "broadband", "" ]
For example, if I declare a long variable, can I assume it will always be aligned on a "sizeof(long)" boundary? Microsoft Visual C++ online help says so, but is it standard behavior? some more info: a. It is possible to explicitely create a misaligned integer (\*bar): > char foo[5] > > int \* bar = (int \*)(&foo[1])...
As others have mentioned, this isn't part of the standard and is left up to the compiler to implement as it sees fit for the processor in question. For example, VC could easily implement different alignment requirements for an ARM processor than it does for x86 processors. Microsoft VC implements what is basically cal...
By default, yes. However, it can be changed via the pack() #pragma. I don't believe the C++ Standard make any requirement in this regard, and leaves it up to the implementation.
Are POD types always aligned?
[ "", "c++", "c", "visual-c++", "" ]
I'm looking for a way to set the default language for visitors comming to a site built in EPiServer for the first time. Not just administrators/editors in the backend, people comming to the public site.
Depends on your setup. If the site languages is to change under different domains you can do this. Add to configuration -> configSections nodes in web.config: ``` <sectionGroup name="episerver"> <section name="domainLanguageMappings" allowDefinition="MachineToApplication" allowLocation="false" type="EPiServer.Util....
I have this on EPiServer CMS5: ``` <globalization culture="sv-SE" uiCulture="sv" requestEncoding="utf-8" responseEncoding="utf-8" resourceProviderFactoryType="EPiServer.Resources.XmlResourceProviderFactory, EPiServer" /> ```
Setting default language in EPiServer?
[ "", "c#", ".net", "episerver", "" ]
Is there a quick & dirty way of obtaining a list of all the classes within a Visual Studio 2008 (c#) project? There are quite a lot of them and Im just lazy enough not to want to do it manually.
If you open the "Class View" dialogue (View -> Class View or Ctrl+W, C) you can get a list of all of the classes in your project which you can then select and copy to the clipboard. The copy will send the fully qualified (i.e. with complete namespace) names of all classes that you have selected.
I've had success using **[doxygen](http://www.doxygen.nl/)** to generate documentation from the XML comments in my projects - a byproduct of this is a nice, hyperlinked list of classes.
List the names of all the classes within a VS2008 project
[ "", "c#", "visual-studio-2008", "class", "list", "" ]
I'm no crypto expert, but as I understand it, 3DES is a symmetric encryption algorithm, which means it doesnt use public/private keys. Nevertheless, I have been tasked with encrypting data using a public key, (specifically, a .CER file). If you ignore the whole symmetric/asymmetric thang, I should just be able to use ...
cryptoProvider.Key = cert.GetPublicKey()?
It's not a good idea to use keys generated for asymmetric cryptography for symmetric cryptography. There's nothing preventing you from coming up with a way of using a public key as an encryption key for 3DES, but the end result will be that anyone having access to the public key (and this means everyone!) will be able ...
3DES with .cer public key?
[ "", "c#", "encryption", "" ]
Suppose I attach an `blur` function to an HTML input box like this: ``` <input id="myInput" onblur="function() { ... }"></input> ``` Is there a way to get the ID of the element which caused the `blur` event to fire (the element which was clicked) inside the function? How? For example, suppose I have a span like this...
Hmm... In Firefox, you can use `explicitOriginalTarget` to pull the element that was clicked on. I expected `toElement` to do the same for IE, but it does not appear to work... However, you can pull the newly-focused element from the document: ``` function showBlur(ev) { var target = ev.explicitOriginalTarget||docu...
**2015 answer**: according to [UI Events](http://www.w3.org/TR/uievents), you can use the [`relatedTarget`](http://www.w3.org/TR/uievents/#widl-FocusEvent-relatedTarget) property of the event: > Used to identify a secondary [`EventTarget`](http://www.w3.org/TR/uievents/#interface-EventTarget) related to a Focus > even...
When a 'blur' event occurs, how can I find out which element focus went *to*?
[ "", "javascript", "events", "" ]
I have inherited a poorly written web application that seems to have errors when it tries to read in an xml document stored in the database that has an "&" in it. For example there will be a tag with the contents: "Prepaid & Charge". Is there some secret simple thing to do to have it not get an error parsing that chara...
The problem is the xml is not well-formed. Properly generated xml would list the data like this: > `Prepaid &amp; Charge` I've fixed the same problem before, and I did it with this regex: ``` Regex badAmpersand = new Regex("&(?![a-zA-Z]{2,6};|#[0-9]{2,4};)"); ``` Combine that with a string constant defined like thi...
The web application isn't at fault, the XML document is. Ampersands in XML should be encoded as `&amp;`. Failure to do so is a syntax error. **Edit:** in answer to the followup question, yes there are all kinds of similar errors. For example, unbalanced tags, unencoded less-than signs, unquoted attribute values, octet...
Reading XML with an "&" into C# XMLDocument Object
[ "", "c#", ".net", "asp.net", "xml", "xmldocument", "" ]
I am told that good developers can spot/utilize the difference between `Null` and `False` and `0` and all the other good "nothing" entities. What *is* the difference, specifically in PHP? Does it have something to do with `===`?
## It's language specific, but in PHP : **`Null`** means "**nothing**". The var has not been initialized. **`False`** means "**not true in a boolean context**". Used to explicitly show you are dealing with logical issues. **`0`** is an **`int`**. Nothing to do with the rest above, used for mathematics. Now, what is...
`null` is `null`. `false` is `false`. Sad but true. there's not much consistency in PHP (though it is improving on latest releases, there's too much backward compatibility). Despite the design wishing some consistency (outlined in the selected answer here), it all get confusing when you consider method returns that us...
Null vs. False vs. 0 in PHP
[ "", "php", "null", "" ]
Is there a cheap way to get the dimensions of an image (jpg, png, ...)? Preferably, I would like to achieve this using only the standard class library (because of hosting restrictions). I know that it should be relatively easy to read the image header and parse it myself, but it seems that something like this should be...
Your best bet as always is to find a well tested library. However, you said that is difficult, so here is some dodgy largely untested code that should work for a fair number of cases: ``` using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; namespace ImageDimension...
``` using (FileStream file = new FileStream(this.ImageFileName, FileMode.Open, FileAccess.Read)) { using (Image tif = Image.FromStream(stream: file, useEmbeddedColorManagement: false, validateImageData: false)) { float widt...
Getting image dimensions without reading the entire file
[ "", "c#", ".net", "image", "image-manipulation", "" ]
I'm planning on creating a game that contains a landscape with objects on it. The landscape will be defined using a heightfield, and the objects will move about on top of, and fly over the terrain. If you've ever played the old games [Marble Madness](http://en.wikipedia.org/wiki/Marble_Madness) and [Virus/Zarch](http:/...
Here is a more complete list, Xbox, Zune and Windows... * [Farseer](http://www.codeplex.com/FarseerPhysics) - 2d only. * [JigLibX](http://www.codeplex.com/JigLibX) * [Bullet](http://bulletphysics.com/) + [BulletX](http://www.codeplex.com/xnadevru/Wiki/View.aspx?title=Managed%20Bullet%20Physics%20Library&referringTit...
If you're looking for more of a tutorial rather than a full-blown solution, have you checked the collision series at [the XNA creators site](http://creators.xna.com)? Specifically, [Collision Series 5: Heightmap Collision with Normals](http://creators.xna.com/en-us/sample/collision3dheightmapnormals) sounds like exact...
What XNA based 3D terrain and physics libraries exist?
[ "", "c#", "xna", "physics", "" ]
When building some of my PHP apps, a lot of the functionality could be coded using PEAR/PECL modules, however, the fact that some people using it may not have the access to install things, It poses a puzzler for me. Should I forsake some users to use PEAR/PECL for functionality, where these will allow me to have a sys...
It partly depends on how much time you have, and the purpose of the project. If you're just trying to make something that works, go with PEAR/PECL. If you're trying to learn to be a better programmer, and you have the time, then I'd recommend taking the effort to write your own versions. Once you understand the innards...
Save on development time by developing with the pear libraries, and provide the libraries bundled in what you distribute (though you'll have to make sure it obeys licensing requirements) I would not depend on certain PECL extensions being installed unless you're doing something particularly related to one (say an XDeb...
PHP: Use Pecl/Pear, or build my own systems?
[ "", "php", "pear", "pecl", "" ]
Does anyone know how I can check to see if a directory is writeable in PHP? The function [`is_writable`](http://php.net/manual/en/function.is-writable.php) doesn't work for folders. > Edit: It does work. See the accepted answer.
Yes, it does work for folders.... > Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writable.
this is the code :) ``` <?php $newFileName = '/var/www/your/file.txt'; if ( ! is_writable(dirname($newFileName))) { echo dirname($newFileName) . ' must writable!!!'; } else { // blah blah blah } ```
How do I check if a directory is writeable in PHP?
[ "", "php", "permissions", "directory", "" ]
First, yes I know about [this question](https://stackoverflow.com/questions/50182/linuxx11-input-library-without-creating-a-window), but I'm looking for a bit more information that that. I have actually, a fairly similar problem, in that I need to be able to capture input for mouse/keyboard/joystick, and I'd also like ...
Using the link below look at the function void kGUISystemX::Loop(void) This is my main loop for getting input via keyboard and mouse using X Windows on Linux. <http://code.google.com/p/kgui/source/browse/trunk/kguilinux.cpp> Here is a snippet: ``` if(XPending(m_display)) { XNextEvent(m_display, &m_e...
If you know your project will only be run under Linux (not Windows or even one of the BSDs), you should look into the Linux kernel's input system. Download the [kernel source](http://kernel.org/pub/linux/kernel/v2.6/linux-2.6.26.5.tar.bz2) and read `Documentation/input/input.txt`, particularly the description of the `e...
Capturing Input in Linux
[ "", "c++", "linux", "" ]
I am investigating the design of a work queue processor where the QueueProcessor retrieves a Command Pattern object from the Queue and executes it in a new thread. I am trying to get my head around a potential Queue lockup scenario where nested Commands may result in a deadlock. E.G. A FooCommand object is placed on...
For simple cases like this an additional monitoring thread that can spin off more threads on demand is helpful. Basically every N seconds check to see if any jobs have been finished, if not, add another thread. This won't necessarily handle even more complex deadlock problems, but it will solve this one. My recommen...
You could redesign things so that FooCommand doesn't use the queue to run BarCommand but runs it directly, or you could split FooCommand into two, and have the first half stop immediately after queueing BarCommand, and have BarCommand queue the second have of FooCommand after it's done its work.
Managing ThreadPool starvation within a multithreaded work queue processor?
[ "", "c#", ".net", "multithreading", "" ]
How can I tell in JavaScript what path separator is used in the OS where the script is running?
Afair you can always use / as a path separator, even on Windows. Quote from <http://bytes.com/forum/thread23123.html>: > So, the situation can be summed up > rather simply: > > * All DOS services since DOS 2.0 and all Windows APIs accept either forward > slash or backslash. Always have. > * None of the standard com...
Use [`path`](http://nodejs.org/docs/latest/api/path.html) module in `node.js` returns the platform-specific file separator. example ``` path.sep // on *nix evaluates to a string equal to "/" ``` Edit: As per Sebas's comment below, to use this, you need to add this at the top of your js file: ``` const path = req...
How to determine the OS path separator in JavaScript?
[ "", "javascript", "file", "directory", "" ]
What is the best way (performance wise) to paginate results in SQL Server 2000, 2005, 2008, 2012 if you also want to get the total number of results (before paginating)?
Getting the total number of results and paginating are two different operations. For the sake of this example, let's assume that the query you're dealing with is ``` SELECT * FROM Orders WHERE OrderDate >= '1980-01-01' ORDER BY OrderDate ``` In this case, you would determine the total number of results using: ``` SE...
Finally, **Microsoft SQL Server 2012** was released, I really like its simplicity for a pagination, you don't have to use complex queries like answered here. For getting the next 10 rows just run this query: ``` SELECT * FROM TableName ORDER BY id OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY; ``` <https://learn.microsoft....
What is the best way to paginate results in SQL Server
[ "", "sql", "sql-server", "performance", "pagination", "" ]
I'm trying to generate customized xml files from a template xml file in python. Conceptually, I want to read in the template xml, remove some elements, change some text attributes, and write the new xml out to a file. I wanted it to work something like this: ``` conf_base = ConvertXmlToDict('config-template.xml') con...
For easy manipulation of XML in python, I like the [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) library. It works something like this: Sample XML File: ``` <root> <level1>leaf1</level1> <level2>leaf2</level2> </root> ``` Python code: ``` from BeautifulSoup import BeautifulStoneSoup, Tag, Navi...
This'll get you a dict minus attributes. I don't know, if this is useful to anyone. I was looking for an xml to dict solution myself, when I came up with this. ``` import xml.etree.ElementTree as etree tree = etree.parse('test.xml') root = tree.getroot() def xml_to_dict(el): d={} if el.text: d[el.tag] = el.t...
Editing XML as a dictionary in python?
[ "", "python", "xml", "dictionary", "" ]
We are running part of our app as a windows service and it needs to b able to access DSNs in order to import through ODBC. However there seem to be a lot of restrictions found through trial and error on what DSNs it can access. For example it seems that it cannot 1. access a system DSN unless the account that is runnin...
This is somewhere between your #1 and #2: sometimes correct file permissions are also necessary. I once had troubles on a Vista machine connecting to a DB2 DSN because, for whatever reason (maybe to write out temp files; although I don't know why it would do such a thing in this location instead of a user-specific one)...
I think you've already discovered the three main rules yourself. :-) Except that you probably don't need admin privileges for your service account. IANANA (I am not a network administrator), but your service account probably just needs read access to one of the ODBC files or directories.
What are the access restrictions on accessing a DSN
[ "", "c++", "windows-services", "odbc", "dsn", "" ]
Having a problem getting a TreeView control to display node images. The code below works sometimes but fails to show any image at other times. ``` private TreeNode AddNodeForCore(TreeNode root, Core c) { string key = GetImageKey(c); TreeNode t = root.Nodes.Add(c.Name, c.Name, key, key); t.Tag = c; retu...
The helpful bit of the googled posts above is in fact: "This is a known bug in the Windows XP visual styles implementation. Certain controls, like ImageList, do not get properly initialized when they've been created before the app calls Application.EnableVisualStyles(). The normal Main() implementation in a C#'s Progr...
A quick google search found this answer: <http://forums.microsoft.com/MSDN/ShowPost.aspx?siteid=1&PostID=965968> **Quote** from that page: > If the Form containing the TreeView is instantiated in the add-in startup function as below, the icons appear! ``` public partial class ThisApplication { Form1 frm; pr...
.NET TreeView won't show images
[ "", "c#", ".net", "winforms", "" ]
My model layer is being used by a handful of different projects and I'd like to use a single XML Spring Configuration file for the model regardless of which project is using it. My question is: Since not all beans are used in all projects am I wasting resources to any significant amount if there not being instantiated...
Taken from the [Spring Reference Manual](http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-lazy-init): > The default behavior for ApplicationContext implementations is to eagerly pre-instantiate all singleton beans at startup. Pre-instantiation means that an ApplicationContext will...
In addition to the other comments: it's also possible to specify a whole configuration file to be lazily initialized, by using the 'default-lazy-init' attribute on the `<beans/>` element; for example: ``` <beans default-lazy-init="true"> <!-- no beans will be pre-instantiated... --> </beans> ``` This is much easi...
Does having many unused beans in a Spring Bean Context waste significant resources?
[ "", "java", "spring", "" ]
Maps are great to get things done easily, but they are memory hogs and suffer from caching issues. And when you have a map in a critical loop that can be bad. So I was wondering if anyone can recommend another container that has the same API but uses lets say a vector or hash implementation instead of a tree implement...
See [Loki::AssocVector](http://loki-lib.sourceforge.net/) and/or hash\_map (most of STL implementations have this one).
You can use std::tr1::unordered\_map, which is already present in most STL implementations, and is part of the C++0x standard. Here is it's current signature : ``` template <class Key, class T, class Hash = std::tr1::hash<Key>, class Pred = std::equal_to<Key>, class Alloc = std...
Can anyone recommend a C++ std::map replacement container?
[ "", "c++", "stdmap", "" ]
I'm working on a fairly complex project, a custom encryption routine if you will (just for fun) and I've run into this issue in designing my code layout. I have a number of functions that I want to be able to call by index. Specifically, I need to be able to call one randomly for the encrypt process, but then address ...
You could write something like: ``` class EncryptionFunction { public: virtual Foo Run(Bar input) = 0; virtual ~MyFunction() {} }; class SomeSpecificEncryptionFunction : public EncryptionFunction { // override the Run function }; // ... std::vector<EncryptionFunction*> functions; // ... functions[2]->...
What's wrong with function array? You need to call functions by index. So they must be put into some "indexable by index" structure *somehow*. Array is probably the simplest structure that suits this need. Example (typing out of my head, might not compile): ``` struct FunctionPair { EncodeFunction encode; Deco...
C++ Function List
[ "", "c++", "function", "maintainability", "" ]
I was reading about output buffering in JavaScript **[here](http://www.webreference.com/programming/javascript/jkm3/4.html),** and was trying to get my head around the script the author says was the fastest at printing 1 to 1,000,000 to a web page. (Scroll down to the header "The winning one million number script".) Af...
## What makes this script so efficient compared to other approaches? There are several optimizations that the author is making to this algorithm. Each of these requires a fairly deep understanding of how the are underlying mechanisms utilized (e.g. Javascript, CPU, registers, cache, video card, etc.). I think there ar...
I would bet the slowest thing in printing 1m numbers is the browser redrawing the page, so the fewer times you call document.write(), the better. Of course this needs to be balanced against large string concatenations (because they involve allocating and copying). Determining the right buffer size is found through exp...
What makes this the fastest JavaScript for printing 1 to 1,000,000 (separated by spaces) in a web browser?
[ "", "javascript", "optimization", "buffer", "" ]
Is there a way to prevent someone from faking a mime type on a file upload and then running a php/exe/etc... I have to make the file upload directory writeable and executable so that the files can be stored, but this allows anyone to run a script after. One thing I can do is add random data to the file name so they ca...
The file upload directory should not be accessible to the web browser. I.e. don't allow somebody to upload a file, say "`remove_all_my_files.php`", and then execute it on your system by giving the url to it, say "`http://xample.com/uploads/remove_all_my_files.php`".
The information in `$_FILES` always comes from the client, so what you want to do is accept the file and scan it on the server. I'd either recommend using [finfo](http://php.net/manual/en/ref.fileinfo.php), which is a PHP extension and it makes it easy: ``` <?php // example :-) $finfo = finfo_open(FILEINFO_MIME); echo...
prevent mime faking on php uploads
[ "", "php", "security", "" ]
Mending a bug in our SAP BW web application, I need to call two javascript functions from the web framework library upon page load. The problem is that each of these functions reloads the page as a side-effect. In addition, I don't have access to modify these functions. Any great ideas on how to execute a piece of cod...
A cookie would work just fine. Or you could modify the query string each time with a "mode=x" or "load=x" parameter. This would present a problem if the user tries to bookmark the final page, though. If that's an option, the cookie solution is fine. I would guess they need cookies enabled to get that far in the app an...
A cookie, or pass a query string parameter indicating which javascript function has been run. We had to do something along these lines to trip out a piece of our software. That's really the best I got.
Executing JavaScript on page load selectively
[ "", "javascript", "" ]
Is there such a thing as an x86 assembler that I can call through C#? I want to be able to pass x86 instructions as a string and get a byte array back. If one doesn't exist, how can I make my own? To be clear - I don't want to *call* assembly code from C# - I just want to be able to assemble code from instructions and...
As part of some early prototyping I did on a personal project, I wrote quite a bit of code to do something like this. It doesn't take strings -- x86 opcodes are methods on an X86Writer class. Its not documented at all, and has nowhere near complete coverage, but if it would be of interest, I would be willing to open-so...
See this project: <https://github.com/ZenLulz/MemorySharp> This project wraps the FASM assembler, which is written in assembly and as a compiled as Microsoft coff object, wrapped by a C++ project, and then again wrapped in C#. This can do exactly what you want: given a string of x86/x64 assembly, this will produce th...
Assembler library for .NET, assembling runtime-variable strings into machine code for injection
[ "", "c#", "assembly", "x86", "" ]
Is there any good reason to use C strings in C++ nowadays? My textbook uses them in examples at some points, and I really feel like it would be easier just to use a std::string.
The only reasons I've had to use them is when interfacing with 3rd party libraries that use C style strings. There might also be esoteric situations where you would use C style strings for performance reasons, but more often than not, using methods on C++ strings is probably faster due to inlining and specialization, e...
A couple more memory control notes: C strings are POD types, so they can be allocated in your application's read-only data segment. If you declare and define `std::string` constants at namespace scope, the compiler will generate additional code that runs before `main()` that calls the `std::string` constructor for eac...
Why use C strings in C++?
[ "", "c++", "c", "stl", "string", "c-strings", "" ]
I'm writing an application to start and monitor other applications in C#. I'm using the System.Diagnostics.Process class to start applications and then monitor the applications using the Process.Responding property to poll the state of the application every 100 milisecs. I use Process.CloseMainWindow to stop the applic...
Now, I need to check this out later, but I am sure there is a method that tells the thread to wait until it is ready for input. Are you monitoring GUI processes only? Isn't [Process.WaitForInputIdle](http://msdn.microsoft.com/en-us/library/kcdbkyt4.aspx) of any help to you? Or am I missing the point? :) ## Update Fo...
I think it may be better to enhance the check for \_process.Responding so that you only try to stop/kill the process if the Responding property returns false for more than 5 seconds (for example). I think you may find that quite often, applications may be "not responding" for a split second whilst they are doing more ...
System.Diagnostics.Process.Start weird behaviour
[ "", "c#", ".net", "asynchronous", "" ]
Is there an easier way to step through the code than to start the service through the Windows Service Control Manager and then attaching the debugger to the thread? It's kind of cumbersome and I'm wondering if there is a more straightforward approach.
If I want to quickly debug the service, I just drop in a `Debugger.Break()` in there. When that line is reached, it will drop me back to VS. Don't forget to remove that line when you are done. **UPDATE:** As an alternative to `#if DEBUG` pragmas, you can also use `Conditional("DEBUG_SERVICE")` attribute. ``` [Conditi...
I also think having a separate "version" for normal execution and as a service is the way to go, but is it really required to dedicate a separate command line switch for that purpose? Couldn't you just do: ``` public static int Main(string[] args) { if (!Environment.UserInteractive) { // Startup as service. ...
Easier way to debug a Windows service
[ "", "c#", ".net", "windows", "debugging", "windows-services", "" ]
Specifically I have a PHP command-line script that at a certain point requires input from the user. I would like to be able to execute an external editor (such as vi), and wait for the editor to finish execution before resuming the script. My basic idea was to use a temporary file to do the editing in, and to retrieve...
You can redirect the editor's output to the terminal: ``` system("vim > `tty`"); ```
I just tried this and it works fine in windows, so you can probably replicate with vi or whatever app you want on Linux. The key is that `exec()` hangs the php process while notepad (in this case) is running. ``` <?php exec('notepad c:\test'); echo file_get_contents('c:\test'); ?> $ php -r test.php ``` Edit: As ...
How do I escape a PHP script to an external editor and return afterwards?
[ "", "php", "shell", "command-line", "user-input", "" ]
I want to maintain a list of global messages that will be displayed to all users of a web app. I want each user to be able to mark these messages as read individually. I've created 2 tables; `messages (id, body)` and `messages_read (user_id, message_id)`. Can you provide an sql statement that selects the unread messag...
If the table definitions you mentioned are complete, you might want to include a date for each message, so you can order them by date. Also, this might be a slightly more efficient way to do the select: ``` SELECT id, message FROM messages LEFT JOIN messages_read ON messages_read.message_id = messages.id AND ...
Well, you could use ``` SELECT id FROM messages m WHERE m.id NOT IN( SELECT message_id FROM messages_read WHERE user_id = ?) ``` Where ? is passed in by your app.
Fetch unread messages, by user
[ "", "sql", "mysql", "database", "" ]
I'm starting to learn Python and I've come across generator functions, those that have a yield statement in them. I want to know what types of problems that these functions are really good at solving.
Generators give you lazy evaluation. You use them by iterating over them, either explicitly with 'for' or implicitly by passing it to any function or construct that iterates. You can think of generators as returning multiple items, as if they return a list, but instead of returning them all at once they return them one...
One of the reasons to use generator is to make the solution clearer for some kind of solutions. The other is to treat results one at a time, avoiding building huge lists of results that you would process separated anyway. If you have a fibonacci-up-to-n function like this: ``` # function version def fibon(n): a ...
What can you use generator functions for?
[ "", "python", "generator", "" ]
I need to allow other Python applications to register callback functions for events in my application. These need to have priorities associated with them (so a callback with a priority of 10 runs before a callback with a priority of 1) and callback functions need to be able to signal errors to the dispatcher. These ar...
Are these other applications running in another address space? If so, you'll need to use an interprocess communication library like [D-BUS](http://www.freedesktop.org/wiki/Software/dbus). If you're just sending signals in the same process, try [PyDispatcher](http://pypi.python.org/pypi/PyDispatcher/2.0.1)
What platform are you running under? GObject is the basis of the GTK GUI that's widely-used under Linux, and it supports event loops with prioritizable events like this.
What's the best dispatcher/callback library in Python?
[ "", "python", "" ]
Why does the following method hang? ``` public void pipe(Reader in, Writer out) { CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE); while( in.read(buf) >= 0 ) { out.append(buf.flip()); } } ```
Answering my own question: you have to call `buf.clear()` between `read`s. Presumably, `read` is hanging because the buffer is full. The correct code is ``` public void pipe(Reader in, Writer out) { CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE); while( in.read(buf) >= 0 ) { out.append(buf.fli...
I would assume that it is a deadlock. The in.read(buf) locks the CharBuffer and prevents the out.append(buf) call. That is assuming that CharBuffer uses locks (of some kind)in the implementation. What does the API say about the class CharBuffer? Edit: Sorry, some kind of short circuit in my brain... I confused it wit...
Why does "piping" a CharBuffer hang?
[ "", "java", "io", "pipe", "" ]
I have a stored procedure in SQL 2005. The Stored Procedure is actually creating temporary tables in the beginning of SP and deleting it in the end. I am now debugging the SP in VS 2005. In between the SP i would want to know the contents into the temporary table. Can anybody help in in viewing the contents of the temp...
There are several kinds of temporary tables, I think you could use the table which is not dropped after SP used it. Just make sure you don't call the same SP twice or you'll get an error trying to create an existing table. Or just drop the temp table after you see it's content. So instead of using a table variable (`@t...
Edit the stored procedure to temporarily select \* from the temp tables (possibly into another table or file, or just to the output pane) as it runs..? You can then change it back afterwards. If you can't mess with the original procedure, copy it and edit the copy.
View Temporary Table Created from Stored Procedure
[ "", "sql", "sql-server", "stored-procedures", "" ]
I was wondering if there was a way to use "find\_by\_sql" within a named\_scope. I'd like to treat custom sql as named\_scope so I can chain it to my existing named\_scopes. It would also be good for optimizing a sql snippet I use frequently.
While you can put any SQL you like in the conditions of a named scope, if you then call `find_by_sql` then the 'scopes' get thrown away. Given: ``` class Item # Anything you can put in an sql WHERE you can put here named_scope :mine, :conditions=>'user_id = 12345 and IS_A_NINJA() = 1' end ``` This works (it just...
This doesn't address exactly what you asked about, but you might investigate 'contruct\_finder\_sql'. It lets you can get the SQL of a named scope. ``` named_scope :mine, :conditions=>'user_id = 12345 and IS_A_NINJA() = 1' named_scope :additional { :condtions => mine.send(:construct_finder_sql,{}) + " additional = '...
Encapsulating SQL in a named_scope
[ "", "sql", "ruby-on-rails", "named-scope", "" ]
When java was young, people were excited about writing applets. They were cool and popular, for a little while. Now, I never see them anymore. Instead we have flash, javascript, and a plethora of other web app-building technologies. Why don't sites use java applets anymore? I'm also curious: historically, why do you ...
I think Java applets were overshadowed by Flash and ActionScript (pun unintended), being much easier to use for what Java Applets were being used at the time (animations + stateful applications). Flash's success in this respect in turn owes to its much smaller file sizes, as well as benefiting from the Sun vs. Microso...
1) AWT made for horrid UIs. Swing improved on that but it was too late, because... 2) Microsoft dropped support for Java in the browser (its propietary MSJVM), and before it did, it would only support the last version it released, which was roughly JDK 1.1 compatible. 3) So today you cannot be sure that an applet w...
Where did all the java applets go?
[ "", "java", "applet", "" ]
In JavaScript, the "this" operator can refer to different things under different scenarios. Typically in a method within a JavaScript "object", it refers to the current object. But when used as a callback, it becomes a reference to the calling object. I have found that this causes problems in code, because if you us...
In JavaScript, `this` always refers to the object invoking the function that is being executed. So if the function is being used as an event handler, `this` will refer to the node that fired the event. But if you have an object and call a function on it like: ``` myObject.myFunction(); ``` Then `this` inside `myFunct...
Quick advice on best practices before I babble on about the magic *this* variable. If you want Object-oriented programming (OOP) in Javascript that closely mirrors more traditional/classical inheritance patterns, pick a framework, learn its quirks, and don't try to get clever. If you want to get clever, learn javascrip...
In Javascript, why is the "this" operator inconsistent?
[ "", "javascript", "" ]
Is there some way to do multi-threading in JavaScript?
See <http://caniuse.com/#search=worker> for the most up-to-date support info. The following was the state of support circa 2009. --- The words you want to google for are [JavaScript Worker Threads](http://www.google.com/search?q=JavaScript+worker+threads) Apart from from [Gears](http://gears.google.com/) there's no...
# Different way to do multi-threading and Asynchronous in JavaScript Before HTML5 JavaScript only allowed the execution of one thread per page. There was some hacky way to simulate an asynchronous execution with *Yield*, `setTimeout()`, `setInterval()`, `XMLHttpRequest` or *event handlers* (see the end of this post f...
JavaScript and Threads
[ "", "javascript", "multithreading", "" ]
I've run into a problem where I make changes to a few JavaScript files that are referenced in an HTML file, but the browser doesn't see the changes. It holds onto the copy cached in the browser, even though the web server has a newer version. Not until I force the browser to clear the cache do I see the changes. Is t...
We append a product build number to the end of all Javascript (and CSS etc.) like so: ``` <script src="MyScript.js?4.0.8243"> ``` Browsers ignore everything after the question mark but upgrades cause a new URL which means cache-reload. This has the additional benefit that you can set HTTP headers that mean "never ca...
> It holds onto the copy cached in the browser, even though the web server has a newer version. This is probably because the HTTP Expires / Cache-Control headers are set. <http://developer.yahoo.com/performance/rules.html#expires> I wrote about this here: <http://www.codinghorror.com/blog/archives/000932.html> > T...
Aggressive JavaScript caching
[ "", "javascript", "caching", "" ]
I'd sort of like to use SQLite from within C#.Net, but I can't seem to find an appropriate library. Is there one? An official one? Are there other ways to use SQLite than with a wrapper?
From [https://system.data.sqlite.org](https://system.data.sqlite.org/): > System.Data.SQLite is an ADO.NET adapter for SQLite. > > System.Data.SQLite was started by Robert Simpson. Robert still has commit privileges on this repository but is no longer an active contributor. Development and maintenance work is now most...
Here are the ones I can find: * [managed-sqlite](http://code.google.com/p/managed-sqlite/) * SQLite.NET wrapper * [System.Data.SQLite](http://system.data.sqlite.org/) Sources: * [sqlite.org](http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers) * other posters
Is there a .NET/C# wrapper for SQLite?
[ "", "c#", ".net", "database", "sqlite", "" ]
I have an XML file that's the output from a database. I'm using the Java SAX parser to parse the XML and output it in a different format. The XML contains some invalid characters and the parser is throwing errors like 'Invalid Unicode character (0x5)' Is there a good way to strip all these characters out besides pre-p...
I haven't used this personally but Atlassian made a command line XML cleaner that may suit your needs (it was made mainly for JIRA but XML is XML): > Download [atlassian-xml-cleaner-0.1.jar](http://repository.atlassian.com/atlassian-xml-cleaner/jars/atlassian-xml-cleaner-0.1.jar) > > Open a DOS console or shell, and l...
I used Xalan `org.apache.xml.utils.XMLChar` class: ``` public static String stripInvalidXmlCharacters(String input) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (XMLChar.isValid(c)) { sb.append(c); } } ...
Stripping Invalid XML characters in Java
[ "", "java", "xml", "" ]
I'm writing a small tool in C# which will need to send and receive data to/from a website using POST and json formatting. I've never done anything like this before in C# (or any language really) so I'm struggling to find some useful information to get me started. I've found some information on the WebRequest class in ...
WebRequest and more specifically the HttpWebRequest class is a good starting point for what you want to achieve. To create the request you will use the WebRequest.Create and cast the created request to an HttpWebRequest to actually use it. You will then create your post data and send it to the stream like: ``` HttpWeb...
[WebClient](http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx) is sometimes easier to use than [WebRequest](http://msdn.microsoft.com/en-us/library/system.net.webrequest.aspx). You may want to take a look at it. For JSON deserialization you are going to want to look at the [JavaScriptSerializer]...
Is WebRequest The Right C# Tool For Interacting With Websites?
[ "", "c#", ".net", "webrequest", "" ]
Do you know any easy or simple way to make a map object (from the STL library) persistent (i.e. write it to a file) so that you can recover its state later when the program in run later ?? Thanks for your help
I believe the [Boost Serialization](http://www.boost.org/doc/libs/1_36_0/libs/serialization/doc/index.html) library is capable of serializing std::map, but the standard library itself provides no means. Serialization is a great library with a lot of features and is easy to use and to extend to your own types.
If you want to do it manually, the same way you'd persist any other container structure, write out the individual parts to disk: ``` outputFile.Write(thisMap.size()); for (map<...>::const_iterator i = thisMap.begin(); i != thisMap.end(); ++iMap) { outputFile.Write(i->first); outputFile.Write(i->second); } ``` ...
Persistence of std::map in C++
[ "", "c++", "dictionary", "persistence", "" ]
In C#, I can do this: ``` class Program { static void Main(string[] args) { List<Animal> animals = new List<Animal>(); animals.Add(new Dog()); animals.Add(new Cat()); foreach (Animal a in animals) { Console.WriteLine(a.MakeNoise()); a.Sleep(); ...
edit: added more code for your updated question disclaimer: I haven't used Ruby in a year or so, and don't have it installed on this machine, so the syntax might be entirely wrong. But the concepts are correct. --- The exact same way, with classes and overridden methods: ``` class Animal def MakeNoise r...
All the answers so far look pretty good to me. I thought I'd just mention that the whole inheritance thing is not entirely necessary. Excluding the "sleep" behaviour for a moment, we can achieve the whole desired outcome using duck-typing and omitting the need to create an Animal base class at all. Googling for "duck-t...
How do you do polymorphism in Ruby?
[ "", "c#", "ruby", "polymorphism", "" ]
What is an efficient way to implement a singleton design pattern in Java?
Use an enum: ``` public enum Foo { INSTANCE; } ``` Joshua Bloch explained this approach in his [Effective Java Reloaded](http://sites.google.com/site/io/effective-java-reloaded) talk at Google I/O 2008: [link to video](http://www.youtube.com/watch?v=pi_I7oD_uGI#t=28m50s). Also see slides 30-32 of his presentation...
Depending on the usage, there are several "correct" answers. Since Java 5, the best way to do it is to use an enum: ``` public enum Foo { INSTANCE; } ``` Pre Java 5, the most simple case is: ``` public final class Foo { private static final Foo INSTANCE = new Foo(); private Foo() { if (INSTANCE...
What is an efficient way to implement a singleton pattern in Java?
[ "", "java", "singleton", "design-patterns", "" ]
I've been looking into [OSGi](http://www.osgi.org/Main/HomePage) recently and think it looks like a really good idea for modular Java apps. However, I was wondering how OSGi would work in a web application, where you don't just have code to worry about - also HTML, images, CSS, that sort of thing. At work we're build...
You are very right in thinking there are synergies here, we have a modular web app where the app itself is assembled automatically from independent components (OSGi bundles) where each bundle contributes its own pages, resources, css and optionally javascript. We don't use JSF (Spring MVC here) so I can't comment on t...
Check out [SpringSource dm Server](http://www.springsource.org/dmserver) - an application server built entirely in terms of OSGi and supporting modular web applications. It is available in free, open source, and commercial versions. You can start by deploying a standard WAR file and then gradually break your applicati...
Modular web apps
[ "", "java", "web-applications", "jsf", "modularity", "" ]
``` $a = '{ "tag": "<b></b>" }'; echo json_encode( json_decode($a) ); ``` This outputs: ``` {"tag":"<b><\/b>"} ``` when you would think it would output exactly the input. For some reason json\_encode adds an extra slash.
Because it's part of the JSON standard <http://json.org/> > char > > ``` > any-Unicode-character- > except-"-or-\-or- > control-character > \" > \\ > \/ <---- see here? > \b > \f > \n > \r > \t > \u four-hex-digits > ```
use this: ``` echo json_encode($a,JSON_HEX_TAG) ``` Result will be: ``` ["\u003C\u003E"] ``` You can read this article to improve your knowledge about JSON\_ENCODE <http://php.net/manual/en/function.json-encode.php>
Can anyone explain this PHP code using json_encode and json_decode?
[ "", "php", "json", "" ]
Is there a more concise/standard idiom (e.g., a JDK method) for "piping" an input to an output in Java than the following? ``` public void pipe(Reader in, Writer out) { CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE); while (in.read(buf) >= 0 ) { out.append(buf.flip()); buf.clear(); ...
[IOUtils](http://commons.apache.org/io/) from the Apache Commons project has a number of [utilily methods](http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html) that do exactly what you need. `IOUtils.copy(in, out)` will perform a buffered copy of all input to the output. If there is more than one s...
Take a look at [java.io.PipedInputStream](http://java.sun.com/javase/6/docs/api/java/io/PipedInputStream.html) and [PipedOutputStream](http://java.sun.com/javase/6/docs/api/java/io/PipedOutputStream.html), or [PipedReader](http://java.sun.com/javase/6/docs/api/java/io/PipedReader.html)/[PipedWriter](http://java.sun.com...
Java idiom for "piping"
[ "", "java", "io", "pipe", "" ]
I need to enumerate all the user defined types created in a `SQL Server` database with `CREATE TYPE`, and/or find out whether they have already been defined. With tables or stored procedures I'd do something like this: ``` if exists (select * from dbo.sysobjects where name='foobar' and xtype='U') drop table fooba...
Types and UDTs don't appear in sys.objects. You should be able to get what you're looking for with the following: ``` select * from sys.types where is_user_defined = 1 ```
Although the post is old, I found it useful to use a query similar to this. You may not find some of the formatting useful, but I wanted the fully qualified type name and I wanted to see the columns listed in order. You can just remove all of the SUBSTRING stuff to just get the column name by itself. ``` SELECT USER_N...
How do I list user defined types in a SQL Server database?
[ "", "sql", "sql-server", "t-sql", "" ]
How can I format Floats in Java so that the float component is displayed only if it's not zero? For example: ``` 123.45 -> 123.45 99.0 -> 99 23.2 -> 23.2 45.0 -> 45 ``` Edit: I forgot to mention - I'm still on Java 1.4 - sorry!
If you use [DecimalFormat](http://java.sun.com/j2se/1.4.2/docs/api/java/text/DecimalFormat.html) and specify # in the pattern it only displays the value if it is not zero. See my question [How do I format a number in java?](https://stackoverflow.com/questions/50532/how-do-i-format-a-number-in-java) Sample Code ``` ...
Check out the [DecimalFormat](http://java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormat.html) class, e.g. new DecimalFormat("0.##").format(99.0) will return "99".
Conditional Number Formatting In Java
[ "", "java", "java1.4", "" ]
We would like to give access to some of our EJBs from Excel. The goal is to give an API usable from VBA. Our EJBs are mostly Stateless Session Beans that do simple CRUD operations with POJOs. Some possible solutions: * Exposing the EJBs as WebServices and create a VB/C# dll wrapping them, * Using Corba to access the...
You could take a look at [IIOP.NET](http://www.codeproject.com/KB/cs/iiop_net_and_ejb.aspx), which addresses this issue.
If you have a fairly recent ejb container, the cheapest and easiest should be to expose your beans as web services and call it from VB/C#. This doesn't require any extra tool or library.
Best solution for using EJBs from Excel
[ "", "java", "excel", "ejb", "corba", "vba", "" ]
I'm in the process of designing a PHP-based content management system for personal use and eventually to be distributed. I know there are a lot of CMS's already out there, but I really haven't found one that meets my all of my needs and I also would like to have the learning experience. Security is a large focus, as ar...
Well, building your own CMS actually implies that it is not an enterprise-level product. What this means is that you will not be able to actually implement all features that make CMS users happy. Not even most features. I want to clarify that by CMS I actually mean a platform for creating web applications or web sites,...
In building a few iterations of CMSs, some of the key things turned out to be: * Having a good rich text editor - end-users really don't want to do HTML. Consensus seems to be that FCKEditor is the best - there have been a couple of questions on this here recently * Allowing people to add new pages and easily create a...
Advice on building a distributed CMS?
[ "", "php", "content-management-system", "" ]
What's the fastest way to count the number of keys/properties of an object? Is it possible to do this without iterating over the object? I.e., without doing: ``` var count = 0; for (k in myobj) if (myobj.hasOwnProperty(k)) ++count; ``` (Firefox did provide a magic `__count__` property, but this was removed somewhere ...
To do this in any *[ES5](https://en.wikipedia.org/wiki/ECMAScript#5th_Edition)-compatible environment*, such as [Node.js](http://nodejs.org), Chrome, [Internet Explorer 9+](https://en.wikipedia.org/wiki/Internet_Explorer_9), Firefox 4+, or Safari 5+: ``` Object.keys(obj).length ``` * [Browser compatibility](https://k...
You could use this code: ``` if (!Object.keys) { Object.keys = function (obj) { var keys = [], k; for (k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) { keys.push(k); } } return keys; }; } ``` Then you can use th...
How to efficiently count the number of keys/properties of an object in JavaScript
[ "", "javascript", "performance", "properties", "count", "key", "" ]
Have you managed to get Aptana Studio debugging to work? I tried following this, but I don't see `Windows -> Preferences -> Aptana -> Editors -> PHP -> PHP Interpreters` in my menu (I have `PHP plugin` installed) and any attempt to set up the servers menu gives me "socket error" when I try to debug. `Xdebug` is install...
I've been using ZendDebugger with Eclipse (on OS X) for a while now and it works great! Here's the recipe that's worked well for me. 1. install Eclipse PDT via "All in one" package at: <http://www.zend.com/en/community/pdt> 2. install ZendDebugger.so (<http://www.zend.com/en/community/pdt>) 3. configure your php.ini ...
This is not related to Aptana Studio, but if you are looking for a PHP XDebug debugger client on OS X, you can try [MacGDBp](http://www.bluestatic.org/software/macgdbp/) (Free/GPL).
Php debugging with Aptana Studio and Xdebug or Zend debugger on OS X
[ "", "php", "debugging", "macos", "aptana", "xdebug", "" ]
There are a lot of new features that came with the .Net Framework 3.5. Most of the posts and info on the subject list stuff about new 3.5 features and C# 3 changes at the same time. But C# 3 can be used without .Net 3.5. Does anyone know of a good post describing the changes to the language? (Besides the boring, explic...
Update: I can certainly understand. Eric Lippert has some more indepth posts..[Check them out](http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/Lambda+Expressions/default.aspx). --- I liked the series of posts by [scottgu](http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic...
There's a ["quick and dirty" list on my C# in Depth site](http://csharpindepth.com/Articles/General/BluffersGuide3.aspx) (which is also slightly tongue in cheek): To respond somewhat to Charles Graham's post, I have an [article](http://csharpindepth.com/Articles/Chapter1/Versions.aspx) about how applicable the languag...
C# 3 new feature posts (and not about .Net 3.5 features)
[ "", "c#", ".net", ".net-3.5", "c#-3.0", "" ]
**Problem**. I need a way to find Starteam server time through Starteam Java SDK 8.0. Version of server is 8.0.172 so method `Server.getCurrentTime()` is not available since it was added only in server version 9.0. **Motivation**. My application needs to use views at specific dates. So if there's some difference in sy...
After some investigation I haven't found any cleaner solution than using a temporary item. My app requests the item's time of creation and compares it with local time. Here's the method I use to get server time: ``` public Date getCurrentServerTime() { Folder rootFolder = project.getDefaultView().getRootFolder(); ...
If your StarTeam server is on a Windows box and your code will be executing on a Windows box, you could shell out and execute the **NET time** command to fetch the time on that machine and then compare it to the local time. ``` net time \\my_starteam_server_machine_name ``` which should return: ``` "Current time at ...
Calculate client-server time difference in Borland Starteam server 8
[ "", "java", "time", "starteam", "" ]
Is it possbile to execute linux commands with java? I am trying to create a web servlet to allow ftp users to change their passwords without ssh login access. I would like to execute the next commands: ``` # adduser -s /sbin/nologin clientA -d /home/mainclient/clientA # passwd clientA # cd /home/mainclient; chgrp -R m...
Check out [this](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html). However, doing what you are talking about is way outside spec, and I wouldnt reccommend it. To get it to work you are going to either run your app server as root, or use some other mechanism to give the user the app server is runn...
Use: ``` Runtime.getRuntim().exec("Command"); ``` where Command is the command string you want to execute.
Linux commands from Java
[ "", "java", "linux", "" ]
Where can I find the specifications for the various C# languages? *(EDIT: it appears people voted down because you could 'google' this, however, my original intent was to put an answer with information not found on google. I've accepted the answer with the best google results, as they are relevant to people who haven'...
[Microsoft's version](http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx) (probably what you want) [The formal standardised versions](http://www.ecma-international.org/publications/standards/Ecma-334.htm) (via ECMA, created just so they could say it was "standardised" by some external body. Even though ECMA "standa...
If you have Visual Studio 2005 or 2008, they are already on your machine! For 2005 (English): ``` .\Microsoft Visual Studio 8\VC#\Specifications\1033 ``` For 2008 (English): ``` .\Microsoft Visual Studio 9.0\VC#\Specifications\1033 ``` For 2010 (English): ``` .\Microsoft Visual Studio 10.0\VC#\Specifications\1033...
Where can you find the C# Language Specifications?
[ "", "c#", "visual-studio", "" ]
I want to setup a mechanism for tracking DB schema changes, such the one described in [this answer](https://stackoverflow.com/questions/1607/mechanisms-for-tracking-db-schema-changes#1666): > For every change you make to the > database, you write a new migration. > Migrations typically have two methods: > an "up" meth...
in sql server every DDL command that i know of is an up/down pair.
Other than loss of data, every migration I've ever done is reversible. That said, Rails offers a way to mark a migration as "destructive": > Some transformations are destructive > in a manner that cannot be reversed. > Migrations of that kind should raise > an ActiveRecord::IrreversibleMigration > exception in their d...
Is every DDL SQL command reversible? [database version control]
[ "", "sql", "version-control", "migration", "ddl", "" ]
Assume the following class: ``` public class MyEnum: IEnumerator { private List<SomeObject> _myList = new List<SomeObject>(); ... } ``` It is necessary to implement the IEnumerator methods in MyEnum. But is it possible to 'delegate' or redirect the implementation for IEnumerator directly to \_myList without needi...
**Method 1:** Continue to use encapsulation and forward calls to the List implementation. ``` class SomeObject { } class MyEnum : IEnumerable<SomeObject> { private List<SomeObject> _myList = new List<SomeObject>(); public void Add(SomeObject o) { _myList.Add(o); } public IEnumerator<Some...
You can do this: ``` public class MyEnum : IEnumerator { private List<SomeObject> _myList = new List<SomeObject>(); public IEnumerator GetEnumerator() { return this._myList.GetEnumerator(); } } ``` The reason is simple. Your class can contains several fields which are collections, so compiler/enviroment can't...
How to delegate interface implementation to other class in C#
[ "", "c#", "interface", "" ]
What are the consequences of running a Java class file compiled in JDK 1.4.2 on JRE 1.6 or 1.5?
The [Java SE 6 Compatibility](http://java.sun.com/javase/6/webnotes/compatibility.html) page lists the compatibility of Jave SE 6 to Java SE 5.0. Furthermore, there is a link to [Incompatibilities in J2SE 5.0 (since 1.4.2)](http://java.sun.com/j2se/1.5.0/compatibility.html) as well. By looking at the two documents, it ...
Java classes are **forward** compatible , e.g. classes generated using 1.5 compiler will be loaded and executed successfully **without any problems** on JRE 1.6. Generally your classes genereated by today java compilers will be compatible with future JREs (for example Java7) The inverse does not hold : you can not run...
Consequences of running a Java Class file on different JREs?
[ "", "java", "java1.4", "" ]
C++ is all about memory ownership - aka **ownership semantics**. It is the responsibility of the owner of a chunk of dynamically allocated memory to release that memory. So the question really becomes who owns the memory. In C++ ownership is documented by the type a *raw* pointer is wrapped inside thus in a good (IMO...
For me, these 3 kinds cover most of my needs: `shared_ptr` - reference-counted, deallocation when the counter reaches zero `weak_ptr` - same as above, but it's a 'slave' for a `shared_ptr`, can't deallocate `auto_ptr` - when the creation and deallocation happen inside the same function, or when the object has to be ...
## Simple C++ Model In most modules I saw, by default, it was assumed that receiving pointers was **not** receiving ownership. In fact, functions/methods abandoning ownership of a pointer were both very rare and explicitly expressed that fact in their documentation. **This model assumes that the user is owner only of...
Smart pointers: who owns the object?
[ "", "c++", "memory-management", "smart-pointers", "ownership-semantics", "" ]