Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
What are the established coding standards for JavaScript?
Not exactly what you're looking for, but (like Doug Crockford's vids) I think everybody who writes/edits/reviews JS should look at Chris Heilmann's [slides](http://www.slideshare.net/cheilmann/fronteers-maintainability-presentation) and [videos](http://ajaxian.com/archives/maintainable-javascript-videos-are-now-availab...
Another reason why [Crockford's JavaScript](http://javascript.crockford.com/code.html) coding guidelines are a good idea to follow: This code (below) actually returns undefined because of JavaScript's semicolon injection - which is a damn good reason to get the whole team of developers singing from the same song sheet...
Are there any coding standards for JavaScript?
[ "", "javascript", "coding-style", "" ]
I was wondering if the C# project setting "Allow unsafe code" applies only to unsafe C# code in the project itself, or is it necessary to set this option when linking in a native C++ DLL? What about linking in a managed DLL that itself links to a native DLL? What does this option really do, under the hood?
It has to do with the "unsafe" keyword in C#. "unsafe" turns off all the checks that would normally happen and allow you to directly access the memory. it doesn't refer to calling native C++ DLL's or interfaces.
It allows you to use the "unsafe" block. ``` unsafe(...) { } ```
What is the actual function of the C# project setting "Allow unsafe code"
[ "", "c#", "dll", "interop", "native", "unsafe", "" ]
I am currently in a course that is using OpenGL and I have been using C for all the programs so far. I have Python installed on Fedora as well as OpenGL, however the minute I call an OpenGL command in my Python code, I get a **segmentation fault**. I have no idea why this is. Just to avoid the "just use C" comments, h...
You may also want to consider using [Pyglet](http://www.pyglet.org/) instead of PyOpenGL. It's a ctypes-wrapper around the native OpenGL libs on the local platform, along with windowing support (should handle most of the stuff you want to use GLUT for.) The [pyglet-users](http://groups.google.com/group/pyglet-users) li...
Well, I don't know if these are the libs the original poster are using but I saw identical issues in a pet project I'm working on (Graphics Engine using C++ and Python) using PyOpenGL. PyOpenGL didn't correctly pick up the rendering context if it was created after the python script had been loaded (I was loading the s...
OpenGl with Python
[ "", "python", "opengl", "fedora", "" ]
I have over the course of a few projects developed a pattern for creating immutable (readonly) objects and immutable object graphs. Immutable objects carry the benefit of being 100% thread safe and can therefore be reused across threads. In my work I very often use this pattern in Web applications for configuration set...
For info, the second approach is called "popsicle immutability". Eric Lippert has a series of blog entries on immutability starting [here](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-one-kinds-of-immutability). I'm still getting to grips with the CTP (C# 4.0), but it looks intere...
Another option would be to create some kind of Builder class. For an example, in Java (and C# and many other languages) String is immutable. If you want to do multiple operations to create a String you use a StringBuilder. This is mutable, and then once you're done you have it return to you the final String object. Fr...
Immutable object pattern in C# - what do you think?
[ "", "c#", "functional-programming", "design-patterns", "immutability", "" ]
I'm writing an implementation of a virtual machine in C#, and I need to implement the VM's stack, which can contain two types of entry - return entries or backtrack entries. What is the best way of implementing this? I'm currently using a base type, as follows: ``` class StackEntry { } class Return : StackEntry { uin...
I'm having a hard time imagining how you're going to use this, but the basic answer is that you use a single type with a default operation for post-pop processing ``` StackEntry { protected virtual void PostPop(); } Return : StackEntry { protected override void PostPop(); } Backtrack : StackEntry { protected override ...
What's wrong with putting the BackTrack object in anyway and have it be null if there is no back track? You can add a helpful property like bool IsBacktrack { get { return \_backTrack != null; } } Can the backtrack be validly null? If yes, then use a bool flag for it.
What is the best way of implementing a stack of more than one type of object in C#?
[ "", "c#", "oop", "" ]
My new boss went to a speech where Deliverance, a kind of proxy allowing to add skin to any html output on the fly, was presented. He decided to use it right after that, no matter how young it is. More here : <http://www.openplans.org/projects/deliverance/introduction> In theory, the system sounds great when you wan...
Having used Plone professionally for the last 4 years or so, and Deliverance on 4 commercial sites, I would advise all new front end developers (and old hands alike) to use Deliverance to theme Plone sites. It is *much* easier to learn (a couple of weeks Vs couple of months) and potentially much more powerful than the...
Note, plone.org uses xdv, a version of deliverance that compiles down to xslt. The simplest way to try it is with <http://pypi.python.org/pypi/collective.xdv> though plone.org runs the xslt in a (patched) Nginx.
Any experience with the Deliverance system?
[ "", "python", "html", "deliverance", "" ]
I took a wsp file, and did my **stsadm -o addsolution** like usual. Then I went into *central administration->solution management* and it showed up just fine. Then I deployed the web part, no problems so far. The problem is when I go to add it to the webpart gallery (*Web Part Gallery: New Web Parts*) usually the web ...
wow... turns out that all I was missing was a 'public' declaration on my class!?! I feel like an idiot. But also, I did have to manually delete it to get it recognized. Thanks everyone!
Check that the .webpart file deployed to the wpcatalog folder of your web site. Depending on what directory was specified when provisioning the web application, you should find it in a location similar to this: c:\Inetpub\wwwroot\wss\VirtualDirectories\80\wpcatalog
Deployed Web Part not showing up in 'Web Part Gallery: New Web Parts'
[ "", "c#", "sharepoint", "moss", "web-parts", "" ]
Is there a way to colorize parts of logs in the eclipse console. I know I could send to error and standard streams and color them differently but I'm more looking someting in the lines of ANSI escape codes (or anyother, HTML ?) where I could embed the colors in the string to have it colored in the logs. It sure would ...
Have a try with this Eclipse Plugin: [Grep Console](http://marketplace.eclipse.org/content/grep-console) **[Update]**: As pointed out by commenters: When installing Grep Console in the currently last version of Eclipse, you need to uncheck 'Group items by category' in the Install dialog to see the available items. ...
Actually the [ANSI Console plugin](https://github.com/mihnita/ansi-econsole) adds ANSI escape code support to Eclipse console. At present it does have a limitation though, whereby escape codes that span multiple lines leak incorrectly to other lines when scrolling, see [issue #3](https://github.com/mihnita/ansi-econsol...
Colorize logs in eclipse console
[ "", "java", "eclipse", "console", "escaping", "metadata", "" ]
I'm looking to setup a lightweight, developer only web stack on Windows (and possible OSX). Ideally, I'd be working with Zend framework, MySQL. But I'm open to other APIs to facilitate creating RESTFul (or pseudo-Restful) web services. I've seen some tools, like QuickPHP, but it might have been too lightweight as I cou...
The thing is, you want your development environment to behave the same way as your production environment, so I would suggest installing whatever you are going to deploy to. I run a LAMP stack on my server, so I run [WAMP](http://www.wampserver.com/en/) on Windows for development. It is very easy to install and I don't...
For my local OSX development I've used [MAMP](http://www.mamp.info/en/download.html). I highly recommend it. For Windows I'm sure you already know about a [WAMP](http://en.wikipedia.org/wiki/Comparison_of_WAMPs) and I haven't used anything else.
Looking for lightweight PHP stack for development on Windows
[ "", "php", "windows", "rest", "" ]
As many do I have a config.php file in the root of a web app that I want to include in almost every other php file. So most of them have a line like: ``` require_once("config.php"); ``` or sometimes ``` require_once("../config.php"); ``` or even ``` require_once("../../config.php"); ``` But I never get it right t...
The current working directory for PHP is the directory in which the called script file is located. If your files looked like this: ``` /A foo.php tar.php B/ bar.php ``` If you call foo.php (ex: <http://example.com/foo.php>), the working directory will be /A/. If you call bar.php (ex: <http://example.c...
I like to do this: ``` require_once(dirname(__FILE__)."/../_include/header.inc"); ``` That way your paths can always be relative to the current file location.
How do you know the correct path to use in a PHP require_once() statement
[ "", "php", "" ]
I think most C++ programmers here would agree that polluting the global namespace is a bad idea, but are there times when this rule can be ignored? For example, I have a type that I need to use all over a particular application - should I define it thus: ``` mytypes.h typedef int MY_TYPE; foo.cpp MY_TYPE myType; `...
I use namespaces for partitioning library code from application-specific code, and in a big project to partition the various modules that make up the project. The global namespace is thus useful for application-specific types and functions that are used across multiple modules in the application. So, if your `MY_TYPE...
You can define your type in a separate namespace, and use ``` using ns::MY_TYPE; ```
Polluting the global namespace
[ "", "c++", "namespaces", "typedef", "" ]
When using XmlDocument.Load , I am finding that if the document refers to a DTD, a connection is made to the provided URI. Is there any way to prevent this from happening?
After some more digging, maybe you should set the [XmlResolver](http://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings.xmlresolver.aspx) property of the XmlReaderSettings object to null. > 'The XmlResolver is used to locate and > open an XML instance document, or to > locate and open any external resourc...
The document being loaded HAS a DTD. With: ``` settings.ProhibitDtd = true; ``` I see the following exception: > Service cannot be started. System.Xml.XmlException: For security reasons DTD is prohibited in this XML document. To enable DTD processing set the ProhibitDtd property on XmlReaderSettings to false and pa...
Prevent DTD download when parsing XML
[ "", "c#", ".net", "xml", "" ]
I have a bunch of JUnit 3 classes which extend TestCase and would like to automatically migrate them to be JUnit4 tests with annotations such as `@Before`, `@After`, `@Test`, etc. Any tool out there to do this in a big batch run?
In my opinion, it cannot be that hard. So let's try it: ## 0. Imports You need to import three annotations: ``` import org.junit.After; import org.junit.Before; import org.junit.Test;` ``` After you've made the next few changes, you won't need `import junit.framework.TestCase;`. ## 1. Annotate `test*` Methods All...
Here are the actual regular expressions I used to execute furtelwart's suggestions: ``` // Add @Test Replace: ^[ \t]+(public +void +test) With: @Test\n $1 Regular Expression: on Case sensitive: on File name filter: *Test.java // Remove double @Test's on already @Test annotated files Replace: ^[ \t]+@Test\n[ \t...
Best way to automagically migrate tests from JUnit 3 to JUnit 4?
[ "", "java", "junit", "migration", "" ]
We have a Java program run as **root** on Unix, that therefore can read for example the content of the folders `/home/user1` and `/home/user2`. However, if the Unix user "user1" is logged in in our application, he should not be able to access "/home/user2" data. We would like to use directly the Unix rights and not rec...
**Use SecurityManager!** 1. Put current unix user id into ThreadLocal 2. Create your own SecurityManager that checks unix user permissions on checkRead() and checkWrite() 3. System.setSecurityManager(new MySecurityManager()) 4. Enjoy **Update** There is no, of course, standard library to read unix file permissions. ...
The simplest and most portable way would be to spawn a child process, have it exec a wrapper written in C which changes the UID, drops all the privileges (be careful, writting a wrapper to do that is tricky - it is as hard as writing a setuid wrapper), and execs another java instance to which you talk via RMI. That jav...
In a Java thread running as root, how can we apply Unix rights specific to a logged-in user?
[ "", "java", "unix", "permissions", "" ]
Some background info; * LanguageResource is the base class * LanguageTranslatorResource and LanguageEditorResource inherit from LanguageResource * LanguageEditorResource defines an IsDirty property * LanguageResourceCollection is a collection of LanguageResource * LanguageResourceCollection internally holds LanguageRe...
It sounds like your collection implements `IEnumerable`, not `IEnumerable<T>`, hence you need: ``` _resources.Cast<LanguageEditorResource>().Where(r => r.IsDirty) ``` Note that `Enumerable.Where` is defined on `IEnumerable<T>`, not `IEnumerable` - if you have the non-generic type, you need to use `Cast<T>` (or `OfTyp...
> How can I dig into what LINQ generates to try and see what the problem is? Linq isn't generating anything here. You can step through with the debugger. > to try and improve my understanding of LINQ and learn how I can improve the design of my classes to work better with LINQ. System.Linq.Enumerable methods rely he...
Having some confusion with LINQ
[ "", "c#", ".net", "linq", "linq-to-objects", "" ]
I am just getting started with expression trees so I hope this makes sense. I am trying to create an expression tree to represent: ``` t => t.SomeProperty.Contains("stringValue"); ``` So far I have got: ``` private static Expression.Lambda<Func<string, bool>> GetContainsExpression<T>(string propertyName, string ...
Something like: ``` class Foo { public string Bar { get; set; } } static void Main() { var lambda = GetExpression<Foo>("Bar", "abc"); Foo foo = new Foo { Bar = "aabca" }; bool test = lambda.Compile()(foo); } static Expression<Func<T, bool>> GetExpression<T>(string propertyName, string propertyValue) { ...
To perform a search like: ``` ef.Entities.Where(entity => arr.Contains(entity.Name)).ToArray(); ``` which the trace string will be: ``` SELECT .... From Entities ... Where Name In ("abc", "def", "qaz") ``` I use the method I created below: ``` ef.Entities.Where(ContainsPredicate<Entity, string>(arr, "Name")).ToArr...
How do I create an expression tree to represent 'String.Contains("term")' in C#?
[ "", "c#", ".net", "lambda", "expression-trees", "" ]
Have you ever tried this before? ``` static void Main(string[] args) { int x = 10; x = x++; Console.WriteLine(x); } ``` Output: 10. but for ``` static void Main(string[] args) { int x = 10; x++; Console.WriteLine(x); } ``` Output: 11. Could anyone explain why this?
X++ will increment the value, but then return its old value. So in this case: ``` static void Main(string[] args) { int x = 10; x = x++; Console.WriteLine(x); } ``` You have X at 11 just for a moment, then it gets back to 10 because 10 is the return value of (x++). You could instead do this for the same...
In the assignment `x = x++` you *first* extract the old value of `x` to use in evaluating the right-hand side expression, in this case 'x'; then, you increment `x` by 1. Last, you assign the results of the expression evaluation (10) to `x` via the assignment statement. Perhaps an equivalent code would make the predica...
What's the difference between X = X++; vs X++;?
[ "", "c#", "" ]
In my current 32-bit application, I check (very occasionally) for overflow by doing operations on 64-bit integers. However, on 64-bit systems there does not seem to be a standard 128-bit integer. Is there a simple way of checking for overflow, or a way of getting 128-bit integers, which works on all OSes and compilers...
Much of the discussion in this question applies: [How to detect integer overflow?](https://stackoverflow.com/questions/199333/best-way-to-detect-integer-overflow-in-cc) Many of the techniques used for 32-bit overflow chacking apply to 64-bits as well (not all of the techniques discussed use the next larger integer ty...
[this document](http://www.fefe.de/intof.html) talks about catching overflows (in c) in detail. I don't know if there are better ways of doing this in C++.
Undefined behavior when exceed 64 bits
[ "", "c++", "64-bit", "" ]
I am building a multithreaded system that works like this: While there are entities: 1. Gets an entity from nHibernate (using the current session) 2. Starts a new thread that will work with this entity\* When I start this new thread, it is required to have a new Session, because nHibernate is not thread-safe. I crea...
If you're working with detached objects, you will have to reattach them to the session. You can do that if you have the correct Hibernate ids of the objects you're working with, calling a get, and then merging your copy with the one Hibernate just put into session. Make sure you use merge, though, because saveOrUpdate(...
Besides Evict + Lock you could make use of 2:nd level cache to reconstruct entities without going to the database. I don't know if it fits your application but I also think it's possible to pass the session to the other tread as long as the first thread stops making changes to it.
How to maintain an object for two nHibernate sessions?
[ "", "c#", "multithreading", "nhibernate", "" ]
What is a `StackOverflowError`, what causes it, and how should I deal with them?
Parameters and local variables are allocated on the **stack** (with reference types, the object lives on the **heap** and a variable in the stack references that object on the heap). The stack typically lives at the **upper** end of your address space and as it is used up it heads towards the **bottom** of the address ...
If you have a function like: ``` int foo() { // more stuff foo(); } ``` Then foo() will keep calling itself, getting deeper and deeper, and when the space used to keep track of what functions you're in is filled up, you get the stack overflow error.
What is a StackOverflowError?
[ "", "java", "exception", "memory-leaks", "out-of-memory", "stack-overflow", "" ]
I'd like to remove all "unchecked" warnings from this general utility method (part of a larger class with a number of similar methods). In a pinch, I can use @SuppressWarnings("unchecked") but I'm wondering if I can use generics properly to avoid the warning. The method is intended to be allow callers to compare two o...
I just tried this: ``` public static <T extends Comparable> int compareObject(T o1, T o2) { if ((o1 instanceof String) && (o2 instanceof String)) return ((String) o1).toUpperCase().compareTo(((String) o2).toUpperCase()); else return o1.compareTo(o2); } ``` It compiles, but gives a unchecked ca...
I hope you are aware that many of the approaches here do change the semantics of the method. With the original method you could compare objects of different types if they allow this, but with ``` public static <T extends Comparable<T>> int compareObject(T o1, T o2) ``` you cannot do this comparison anymore. A variant...
Using generic parameters with static compareObject method
[ "", "java", "generics", "" ]
I have a string column in a database table which maps to an Enum in code. In my dbml file when I set the "Type" to `MyTypes.EnumType` I get the following error: > Error 1 DBML1005: Mapping between DbType 'VarChar(50) NOT NULL' and > Type 'MyTypes.EnumType' in Column 'EnumCol' of Type 'Table1' is not > supported. This...
Curious - it should work IIRC; I'll see if I can do a quick example - however, you might want to check that you have the fully-qualified enum name (i.e. including the namespace). [update] From [here](http://blog.rolpdog.com/2007/07/linq-to-sql-enum-mapping.html) it seems that the RTM version shipped with a bug when re...
I know this has been answered, but i'm still getting this error also. Very weird. Anyway, I found a solution. You need to *PREPEND* the full namespace of the enum with `global::`. I know it sounds very weird. Anyway, I didn't figure this out. Some dude called [Matt](http://blog.rolpdog.com/2007/07/linq-to-sql-enum-ma...
Mapping Enum from String
[ "", "c#", "linq-to-sql", "" ]
When a script runs under Apache, I insert `$_SERVER['SERVER_NAME']` value into an error reporting e-mail message. However, if a Web script forks a "worker" job with `nohup php ...`, `$_SERVER['SERVER_NAME']` appears to be empty there. Thus, if an error occurs, it's reported without a host name. Can I reliably get the...
[php\_uname("n")](http://uk.php.net/manual/en/function.php-uname.php) > (PHP 4 >= 4.0.2, PHP 5) > php\_uname — Returns information about the > operating system PHP is running on > > php\_uname() returns a description of the operating system PHP is > running on. This is the same string you see at the very top of the ...
For [PHP >= 5.3.0 use this](http://www.php.net/manual/en/function.gethostname.php): `$hostname = gethostname();` For [PHP < 5.3.0 but >= 4.2.0 use this](http://www.php.net/manual/en/function.php-uname.php): `$hostname = php_uname('n');` For PHP < 4.2.0 you can try one of these: ``` $hostname = getenv('HOSTNAME'); ...
Is there a PHP function or variable giving the local host name?
[ "", "php", "hostname", "" ]
We need to write unit tests for a *wxWidgets* application using *Google Test Framework*. The problem is that *wxWidgets* uses the macro **IMPLEMENT\_APP(MyApp)** to initialize and enter the application main loop. This macro creates several functions including **int main()**. The google test framework also uses macro de...
You want to use the function: ``` bool wxEntryStart(int& argc, wxChar **argv) ``` instead of wxEntry. It doesn't call your app's OnInit() or run the main loop. You can call `wxTheApp->CallOnInit()` to invoke OnInit() when needed in your tests. You'll need to use ``` void wxEntryCleanup() ``` when you're done.
Just been through this myself with 2.8.10. The magic is this: ``` // MyWxApp derives from wxApp wxApp::SetInstance( new MyWxApp() ); wxEntryStart( argc, argv ); wxTheApp->CallOnInit(); // you can create top level-windows here or in OnInit() ... // do your testing here wxTheApp->OnRun(); wxTheApp->OnExit(); wxEntryCl...
wxWidgets: How to initialize wxApp without using macros and without entering the main application loop?
[ "", "c++", "unit-testing", "wxwidgets", "googletest", "" ]
What is the difference between ***anonymous methods*** of C# 2.0 and ***lambda expressions*** of C# 3.0.?
[The MSDN page on anonymous methods explains it](http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx) > In versions of C# before 2.0, the only > way to declare a delegate was to use > named methods. C# 2.0 introduced > anonymous methods and in C# 3.0 and > later, lambda expressions supersede > anonymous methods as t...
1. Lambda expressions can be converted to delegates or expression trees (with some restrictions); anonymous methods can only be converted to delegates 2. Lambda expressions allow type inference on parameters: 3. Lambda expressions allow the body to be truncated to just an expression (to return a value) or single statem...
What's the difference between anonymous methods (C# 2.0) and lambda expressions (C# 3.0)?
[ "", "c#", "methods", "expression", "" ]
How do I embed a tag within a [url templatetag](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url "url templatetag") in a django template? Django 1.0 , Python 2.5.2 In views.py ``` def home_page_view(request): NUP={"HOMEPAGE": "named-url-pattern-string-for-my-home-page-view"} variables = R...
Maybe you could try passing the final URL to the template, instead? Something like this: ``` from django.core.urlresolvers import reverse def home_page_view(request): NUP={"HOMEPAGE": reverse('named-url-pattern-string-for-my-home-page-view')} variables = RequestContext(request, {'NUP':NUP}) return re...
That's seems way too dynamic. You're supposed to do ``` {% url named-url-pattern-string-for-my-home-page-view %} ``` And leave it at that. Dynamically filling in the name of the URL tag is -- frankly -- a little odd. If you want to use any of a large number of different URL tags, you'd have to do something like this...
How to embed a tag within a url templatetag in a django template?
[ "", "python", "django", "url", "templates", "templatetag", "" ]
In any (non-web) .net project, the compiler automatically declares the DEBUG and TRACE constants, so I can use conditional compiling to, for example, handle exceptions differently in debug vs release mode. For example: ``` #if DEBUG /* re-throw the exception... */ #else /* write something in the event log... ...
Look at [ConfigurationManager.GetSection()](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.getsection.aspx) - this should get you most of the way there.. however, I think you're better off just changing between debug and release modes and letting the compiler determine to execute the ...
To add ontop of Andrews answer, you could wrap it in a method as well ``` public bool IsDebugMode { get { #if DEBUG return true; #else return false; #endif } } ```
How can I check whether I am in a debug or release build in a web app?
[ "", "c#", "asp.net", "debugging", "" ]
Is it possible to modify/write data to an XML file without any server-side proxy(e.g. a php or asp script)? Can this be done via javascript? XSLT?
You can load and modify xml in browser, but writing the file back is a different thing. I don't know of any feasible way of writing data back to a server without some kind of server side mechanism to write the data to disk.
Using the XMLHTTPRequest object you can modify an XML document using XSLT. Here's a [sample](http://aspalliance.com/1067_Creating_a_Menu_Using_XSLT_XML_and_JavaScript) article for getting started.
Modify XML document inside the browser
[ "", "javascript", "xml", "" ]
Here's something I know is probably possible but I've never managed to do In VS2005(C++), While debugging, to be able to invoke a function from the code which I'm debugging. This feature is sometimes essential when debugging complex data structures which can't be explored easily using just the normal capabilities o...
Ok, Here's what I found CXX0040 means that "`The C expression evaluator does not support implicit conversions involving constructor calls.`" CXX0047 means that "`Overloaded functions can be called only if there is an exact parameter match or a match that does not require the construction of an object.`" So combine...
The watch window is limited by the context wherein your current code is, e.g., when your code enters a function and you try to access another function that is hidden from the scope of your current function, it won't work. If you invoke a function in the watch window, make sure that it is visible and accessible from th...
invoking functions while debugging with Visual Studio 2005?
[ "", "c++", "visual-studio", "debugging", "visual-c++-2005", "watch", "" ]
Is there any way in JavaScript to create a "weak reference" to another object? [Here is the wiki page describing what a weak reference is.](http://en.wikipedia.org/wiki/Weak_reference) [Here is another article that describes them in Java.](https://community.oracle.com/blogs/enicholas/2006/05/04/understanding-weak-refer...
**Update: Since July, 2020 some implementations (Chrome, Edge, Firefox and Node.js) has had support for [`WeakRef`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef)s as defined in the [WeakRefs proposal](https://tc39.es/proposal-weakrefs/#sec-weak-ref-objects), which is a "Stage...
When running JS on NodeJS, you may consider <https://github.com/TooTallNate/node-weak>.
Is it possible to create a "weak reference" in JavaScript?
[ "", "javascript", "weak-references", "" ]
In Java, we can always use an array to store object reference. Then we have an ArrayList or HashTable which is automatically expandable to store objects. But does anyone know a native way to have an auto-expandable array of object references? Edit: What I mean is I want to know if the Java API has some class with the ...
Java arrays are, by their definition, fixed size. If you need auto-growth, you use XXXList classes. EDIT - question has been clarified a bit When I was first starting to learn Java (coming from a C and C++ background), this was probably one of the first things that tripped me up. Hopefully I can shed some light. Unl...
All the classes implementing Collection are expandable and store only references: you don't store objects, you create them in some data space and only manipulate references to them, until they go out of scope without reference on them. You can put a reference to an object in two or more Collections. That's how you can...
Is there an expandable list of object references in Java?
[ "", "java", "arrays", "object-reference", "" ]
I'm using jQuery to post a form to a php file, simple script to verify user details. ``` var emailval = $("#email").val(); var invoiceIdval = $("#invoiceId").val(); $.post("includes/verify.php", {invoiceId:invoiceIdval , email:emailval }, function(data) { //stuff here. }); ``` PHP Code: ``...
`$.post()` passes data to the underlying `$.ajax()` call, which sets `application/x-www-form-urlencoded` by default, so i don't think it's that. can you try this: ``` var post = $('#myForm').serialize(); $.post("includes/verify.php", post, function(data) { alert(data); }); ``` the `serialize()` call will g...
I got bitten by the same issue, and I find the solution Owen gives not appropriate. You're serializing the object yourself, while jQuery should do that for you. You might as well do a $.get() in that case. I found out that in my case it was actually a server redirect from /mydir to /mydir/ (with slash) that invalidate...
jquery $.post empty array
[ "", "php", "jquery", "ajax", "post", "" ]
I've been a C# programmer for about 2 years total, and professionally for a little more than 1. I work at a company as a developer on an application that began before the days of .NET 2. My question is this: What is the benefit to use databinding from sql queries directly to a control over querying and manually adding...
I personally find that using the ``` control.DataSource = YourSource; control.DataBind(); ``` process is much easier, you don't have to do the iteration, and overall reduces LOC. If working with DropDownLists and other controls you will most likely set the DataValueField and DataTextField properties as well.
Data binding is much easier to set up, less error prone overall, reduces LOC significantly (as Mitchel Sellers said), and, a few minor glitches aside, works fairly reliably. In my experience, you only actually need full manual control if you need to specify the exact update order or timing for data bound controls.
Benefits of DataBinding over Manually Querying / Adding to Control
[ "", "c#", ".net", "sql-server", "model-view-controller", "data-binding", "" ]
``` $array = explode(".", $row[copy]); $a = $array.length -1; ``` I want to return the last element of this array but all i get from this is -1.
You can also use: ``` $a = end($array); ``` This also sets the arrays internal pointer to the end of the array, but it does get you the last element easily.
Try [count](http://php.net/count): ``` $array = explode(".", $row[copy]); $a = count($array) - 1; $array[$a]; // last element ```
How to access the last element in an array?
[ "", "php", "arrays", "element", "" ]
I am trying to get Silverlight to work with a quick sample application and am calling a rest service on a another computer. The server that has the rest service has a clientaccesspolicy.xml which looks like: ``` <access-policy> <cross-domain-access> <policy> <allow-from http-request-headers="*"...
If you haven't already done so, I'd first try changing the restUrl to something simpler like a static HTML page on the same server (or if need be on your own server) just to verify your main code works. Assuming the security exception is specific to that REST URL (or site), you might take a look at the [URL Access Res...
I couldn't do cross domain REST HTTP deletes without adding http-methods="\*" to the allow-from element in the clientaccesspolicy.xml. When I added the http-methods attribute, then everything worked and the SecurityException stopped happening.
Silverlight Rest Service, Security Exception
[ "", "c#", "silverlight", "rest", "" ]
does anybody know how could I get the TWO most largest values from the third column on the following array? ``` $ar = array(array(1, 1, 7.50, 'Hello'), array(1, 2, 18.90, 'Hello'), array(3, 5, 11.50, 'Hello'), array(2, 4, 15.90, 'Hello')); ``` Output should be: `...
If you're sure that the value (two) will never change, just iterate over the array and keep track of the two largest numbers. If not, sort the arrays using [`usort`()](http://www.php.net/manual/en/function.usort.php) and providing an appropriate callback. Then take the first two values: ``` function cmp($a, $b) { ...
Sorting is O(n log n), but you can actually accomplish this in O(n) (that is, *faster*, if the array is big). Pseudocode follows: ``` first = array[0][2] second = array[1][2] if second > first first, second = second, first for tuple in array[2:n] if tuple[2] > second second = tuple[2] if second > first...
Largest values on array
[ "", "php", "arrays", "" ]
Into some view data i have put the result of an anonymous type: ``` var projectData = from p in db.Projects orderby p.title select new { Title = p.title, DevURL = p.devU...
In your case it would be much simpler to create a model to hold your data rather than using an anonymous type. The issue you're having is that your anonymous type is cast to an object when its stored within the ViewData. On the UI side, when you get that object out, the only way to access its properties is to use refl...
Not tried this with an anonymous type but this is how i do it by passing a `List<T>` object to `ViewData` ``` <% foreach (Project p in (IEnumerable<Project>)ViewData["ProjectSummary"]) { %> <%= Html.Encode(p.Title) %> <% } %> ``` Hope this is what your looking for. Mark
Iterating through anonymous typed data in MVC view
[ "", "c#", "asp.net-mvc", "anonymous-types", "" ]
I know the statement: ``` create table xyz_new as select * from xyz; ``` Which copies the structure and the data, but what if I just want the structure?
Just use a where clause that won't select any rows: ``` create table xyz_new as select * from xyz where 1=0; ``` ### Limitations The following things will not be copied to the new table: * sequences * triggers * indexes * some constraints may not be copied * materialized view logs This also does not handle partiti...
I used the method that you accepted a lot, but as someone pointed out it doesn't duplicate constraints (except for NOT NULL, I think). A more advanced method if you want to duplicate the full structure is: ``` SET LONG 5000 SELECT dbms_metadata.get_ddl( 'TABLE', 'MY_TABLE_NAME' ) FROM DUAL; ``` This will give you th...
How can I create a copy of an Oracle table without copying the data?
[ "", "sql", "oracle", "copy", "database-table", "" ]
Just about every piece of example code everywhere omits error handling (because it "confuses the issue" that the example code is addressing). My programming knowledge comes primarily from books and web sites, and you seldom see any error handling in use at all there, let alone good stuff. Where are some places to see ...
Herb Sutter's and Andrei Alexandrescu's book [C++ Coding Standards](http://www.gotw.ca/publications/c++cs.htm) comes with a whole chapter on *Error Handling and Exceptions* including * Assert liberally to document internal assumptions and invariants * Establish a rational error handling policy, and follow it strictly ...
*"Use exceptions"* vs. *"Use error codes"* is never as clear-cut as examples suggest. Use error codes for program flow. If you have an error that is expected, do not throw an exception. E.g. you're reading a file, you may throw an exception for *"file not found"*, *"file locked"*; but never throw one for *"end of file...
C++ Error Handling -- Good Sources of Example Code?
[ "", "c++", "error-handling", "" ]
I want to write an Add-In for Visual Studio that provides instant search for the solution explorer. So you press a key combination and while you are typing a list first containing all files of the solution explorer gets narrowed down. But how can I get access to the solution explorer using C#? Does anyone have some go...
[Sonic File Finder](http://jens-schaller.de/sonictools/sonicfilefinder/index.htm) it's free When you hit the shortcut you have a search box with autocomplete: [alt text http://jens-schaller.de/files/images/SonicFileFinder/sonicFileFinderToolWindow.png](http://jens-schaller.de/files/images/SonicFileFinder/sonicFileFind...
Visual Studio is already perfectly capable of doing that; just drag the "Edit.GoToFindCombo" to the toolbar, if it's not already there. (Press Ctrl+D if it is, to activate) and type ">of s" for all files starting with the letter 's'. [![Example of the GoToFindCombo with the 'open' command](https://i.stack.imgur.com/nV...
Plug-in for Visual Studio for quick-searching files in solution
[ "", "c#", "visual-studio", "resources", "solution-explorer", "" ]
Correct me if I am wrong, int is 4 bytes, with a range of values from -2,147,483,648 to 2,147,483,647 (2^31) long is 4 bytes, with a range of values from -2,147,483,648 to 2,147,483,647 (2^31) What is the difference in C++? Can they be used interchangeably?
It is implementation dependent. For example, under Windows they are the same, but for example on Alpha systems a long was 64 bits whereas an int was 32 bits. This [article](http://software.intel.com/en-us/articles/size-of-long-integer-type-on-different-architecture-and-os) covers the rules for the Intel C++ compiler o...
The only guarantee you have are: ``` sizeof(char) == 1 sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long) // FROM @KTC. The C++ standard also has: sizeof(signed char) == 1 sizeof(unsigned char) == 1 // NOTE: These size are not specified explicitly in the standard. // They are i...
What is the difference between an int and a long in C++?
[ "", "c++", "variables", "" ]
In my views.py, I'm building a list of two-tuples, where the second item in the tuple is another list, like this: ``` [ Product_Type_1, [ product_1, product_2 ], Product_Type_2, [ product_3, product_4 ]] ``` In plain old Python, I could iteration the list like this: ``` for product_type, products in list: prin...
it would be best if you construct your data like {note the '(' and ')' can be exchanged for '[' and ']' repectively, one being for tuples, one for lists} ``` [ (Product_Type_1, ( product_1, product_2 )), (Product_Type_2, ( product_3, product_4 )) ] ``` and have the template do this: ``` {% for product_type, produ...
Another way is as follows. If one has a list of tuples say: ``` mylst = [(a, b, c), (x, y, z), (l, m, n)] ``` then one can unpack this list in the template file in the following manner. In my case I had a list of tuples which contained the URL, title, and summary of a document. ``` {% for item in mylst %} ...
Django - How to do tuple unpacking in a template 'for' loop
[ "", "python", "django", "templates", "tuples", "iterable-unpacking", "" ]
The [MSDN documentation](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2012/c5kehkcz(v=vs.110)) says that ``` public class SomeObject { public void SomeOperation() { lock(this) { //Access instance variables } } } ``` is "a problem if the instance can be accesse...
It is bad form to use `this` in lock statements because it is generally out of your control who else might be locking on that object. In order to properly plan parallel operations, special care should be taken to consider possible deadlock situations, and having an unknown number of lock entry points hinders this. For...
Because if people can get at your object instance (ie: your `this`) pointer, then they can also try to lock that same object. Now they might not be aware that you're locking on `this` internally, so this may cause problems (possibly a deadlock) In addition to this, it's also bad practice, because it's locking "too muc...
Why is lock(this) {...} bad?
[ "", "c#", "multithreading", "locking", "" ]
Given that these two examples are equivalent, which do you think is preferrable? **Without explicit modifier** ``` public class MyClass { string name = "james"; public string Name { get { return name; } set { name = value; } } void SomeMethod() { ... } } ``` **With explicit modifi...
I think explicity stating private helps in readability. It won't allow for a programmer to interpret its visibility differently.
It looks that we are the only one, but personally, **I support** the let's remove private campaign. My concern is that public and private are so similar, 6-7 chars length, blue, starting with 'p', so it's much harder to point a public method between 10 explicit private ones than between 10 that have no access attribut...
Should you use the private access modifier if it's redundant?
[ "", "c#", "coding-style", "" ]
Are C# enums typesafe? If not what are the implications?
To give a slightly different answer... while the values are type-safe from the casting perspective, they are still unchecked once they have been cast - i.e. ``` enum Foo { A = 1, B = 2, C = 3 } static void Main() { Foo foo = (Foo)500; // works fine Console.WriteLine(foo); // also fine - shows 500 } ``` Fo...
Yes they are. The following is from <http://www.csharp-station.com/Tutorials/Lesson17.aspx> Enums are strongly typed constants. They are essentially unique types that allow you to assign symbolic names to integral values. In the C# tradition, they are strongly typed, meaning that an enum of one type may not be implic...
Are C# enums typesafe?
[ "", "c#", "enums", "" ]
The `java.net.InetAddress.GetByName(String host)` method can only return `A` records so to lookup other record types I need to be able to send DNS queries using the `dnsjava` library. However that normally relies on being able to parse `/etc/resolv.conf` or similar to find the DNS server addresses and that doesn't wor...
The [DNS protocol](http://tools.ietf.org/rfc/rfc882.txt) is not that complex - can't you just do the DNS accesses using raw sockets (either TCP or UDP)? After a quick look at the dnsjava doco it seems to provide low level DNS support to assist with this. The other possible direction is, starting with dnsjava, to remov...
I don't think it's possible for general case. For WiFi I found this: ``` WiFiManager wifi = (WifiManager) getSystemService(WIFI_SERVICE); DhcpInfo info = wifi.getDhcpInfo(); ```
How do I find the DNS servers in Android from a Java program?
[ "", "android", "dns", "java", "" ]
I'm trying to change user input in wildcard form `("*word*")` to a regular expression format. To that end, I'm using the code below to strip off the `'*'` at the beginning and end of the input so that I can add the regular expression characters on either end: ``` string::iterator iter_begin = expressionBuilder.begi...
Try erasing them in the opposite order: ``` expressionBuilder.erase(iter_end); expressionBuilder.erase(iter_begin); ``` After erasing the first \*, iter\_end refers to one character past the end of the string in your example. The [STL documentation](http://www.sgi.com/tech/stl/basic_string.html) indicates that iterat...
Your original code and the proposed solutions so far have a couple of problems in addition to the obvious problem you posted about: * use of invalidated iterators after the string is modified * dereferencing possibly invalid iterators even before the string is modified (if the string is empty, for example) * a bug if ...
std::string erase last character fails?
[ "", "c++", "string", "" ]
I have a simple question. Is there a way ( using reflections I suppose ) to iterate all the static values of a class? For instance ``` class Any { static int one = 1; static int two = 2; static int three = 3; public static void main( String [] args ) { for( int i : magicMethod( Any.class ) ...
``` import java.util.*; import java.lang.reflect.*; class Any { static int one = 1; static int two = 2; static int three = 3; public static void main( String [] args ) { for( int i : magicMethod( Any.class ) ){ System.out.println( i ); } } public static Integ...
Hey.. it was very easy. :P ``` Field [] constants = Main.class.getFields(); Object some = new Main(); for( Field field : constants ){ if(Modifier.isStatic(field.getModifiers() ) && field.getType() == int.class ) { System.out.println( field.getInt( some ) ...
iterate static int values in java
[ "", "java", "reflection", "static", "" ]
I've just wasted the past two hours of my life trying to create a table with an auto incrementing primary key bases on [this tutorial](http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment-columns-in-oracle/), The tutorial is great the issue I've been encountering is that the Create Target fails if I h...
There is a note on metalink about this (227615.1) extract below: ``` # symptom: Creating Trigger fails # symptom: Compiling a procedure fails # symptom: ORA-06552: PL/SQL: %s # symptom: ORA-06553: PLS-%s: %s # symptom: PLS-320: the declaration of the type of this expression is incomplete or malformed # cause:...
TIMESTAMP is not listed in the Oracle docs as a reserved word (which is surprising). It is listed in the V$RESERVED\_WORDS data dictionary view, but its RESERVED flag is set to 'N'. It might be a bug in the trigger processing. I would say this is a good one for Oracle support.
Oracle why does creating trigger fail when there is a field called timestamp?
[ "", "sql", "oracle", "ora-06553", "" ]
If I create a recursive list of of lists: ``` class myList { List<myList> childLists; List<string> things; //... } List<myList> tempList = new List<myList>(); ``` And then later call tempList.Clear(), will it destroy all the childLists in memory, or should I create a recursive method to clear all the childLis...
If no *other* references exist to the child lists, they will be garbage collected as normal. The trick is to watch for any dangling references to the child items (databinding especially tends to go unnoticed once done).
You seem to have come from a C++ background. A read on [.NET's Garbage Collection](http://msdn.microsoft.com/en-us/library/0xy59wtx.aspx) should clear a lot of things up for you. In your case, you do not need to "destroy" all the child lists. In fact, you can't even destroy or dispose a generic List object yourself i...
Does the List Clear() method destroy children [C#.NET]?
[ "", "c#", ".net", "memory-management", "recursion", "" ]
I know the standard way of using the [null coalescing operator](https://en.wikipedia.org/wiki/Null_coalescing_operator) in C# is to set default values. ``` string nobody = null; string somebody = "Bob Saget"; string anybody = ""; anybody = nobody ?? "Mr. T"; // Returns Mr. T anybody = somebody ?? "Mr. T"; // Return...
Well, first of all, it's much easier to chain than the standard ternary operator: ``` string anybody = parm1 ?? localDefault ?? globalDefault; ``` vs. ``` string anyboby = (parm1 != null) ? parm1 : ((localDefault != null) ? localDefault : globalDefault); ``` It also works well if a nul...
I've used it as a lazy load one-liner: ``` public MyClass LazyProp { get { return lazyField ?? (lazyField = new MyClass()); } } ``` Readable? Decide for yourself.
Unique ways to use the null coalescing operator
[ "", "c#", "coding-style", "null", "conditional-operator", "null-coalescing-operator", "" ]
What's a more elegant way of having the code below where i want to return a derived class based on the type of another class. ``` if (option_ is Rectangle) { modelInputs = new Foo(); } else if (option_ is Circle) { modelInputs ...
Have Rectangle, Circle and Triangle implement IHasModelInput: ``` interface IHasModelInput { IModelInput GetModelInput(); } ``` then you can do ``` IModelInput modelInputs = option_.GetModelInput(); ```
My opinion: your "inelegant" way is fine. It's simple, readable and does the job. Having the Rectangle, Circle and Triangle implement the necessary factory function via *IHasModelInput* would work, but it has a design cost: you've now coupled this set of classes with the IModelInput set of classes (Foo, Bar and Bar2)....
Factory based on Typeof or is a
[ "", "c#", "factory", "" ]
How can I have a view render a partial (user control) from a different folder? With preview 3 I used to call RenderUserControl with the complete path, but whith upgrading to preview 5 this is not possible anymore. Instead we got the RenderPartial method, but it's not offering me the functionality I'm looking for.
Just include the path to the view, with the file extension. Razor: ``` @Html.Partial("~/Views/AnotherFolder/Messages.cshtml", ViewData.Model.Successes) ``` ASP.NET engine: ``` <% Html.RenderPartial("~/Views/AnotherFolder/Messages.ascx", ViewData.Model.Successes); %> ``` If that isn't your issue, could you please i...
In my case I was using MvcMailer (https://github.com/smsohan/MvcMailer) and wanted to access a partial view from another folder, that wasn't in "Shared." The above solutions didn't work, but using a relative path did. ``` @Html.Partial("../MyViewFolder/Partials/_PartialView", Model.MyObject) ```
Render partial from different folder (not shared)
[ "", "c#", "asp.net-mvc", "renderpartial", "" ]
Please bear with me here, I'm a student and new to Java Server Pages. If I'm being a complete idiot, can someone give me a good link to a tutorial on JSP, since I've been unable to find info on this anywhere. Okay, here goes... I'm using Netbeans and trying to pass an object that connects to a database between the pa...
You can put it in a session [JSP tutorial, Sessions](http://www.jsptut.com/Sessions.jsp). But frankly, you don't put database connections in a session. They're a scarce resource. You'd be better off using some pooling mechanism like in [Tomcat JNDI database pooling example](http://www.informit.com/articles/article.asp...
<http://java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html> is a J2EE tutorial with parts of it talking about JSP as well one more JSP tutorial from sun : <http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPIntro.html>
Passing parameters between JSPs
[ "", "java", "database", "jsp", "jsf", "netbeans", "" ]
A cross join performs a cartesian product on the tuples of the two sets. ``` SELECT * FROM Table1 CROSS JOIN Table2 ``` Which circumstances render such an SQL operation particularly useful?
If you have a "grid" that you want to populate completely, like size and color information for a particular article of clothing: ``` select size, color from sizes CROSS JOIN colors ``` Maybe you want a table that contains a row for every minute in the day, and you want to use it to verify that a procedur...
Generate data for testing.
What are the uses for Cross Join?
[ "", "sql", "database", "join", "relational-database", "" ]
You launch a java program from a console (maybe using a .bat script). I don't want the console to remain visible, I want to hide it. Is there a simple way to do this ? Without JNI ?
Use javaw. <http://java.sun.com/javase/6/docs/tooldocs/windows/java.html> > The javaw command is identical to java, except that with javaw there is no associated console window. Use javaw when you don't want a command prompt window to appear. The javaw launcher will, however, display a dialog box with error informati...
You can start a java application with `start javaw`. It will hide the black console window.
Is there a way to the hide win32 launch console from a Java program (if possible without JNI)
[ "", "java", "winapi", "console", "" ]
So I want to trigger an event (pausing/unpausing some media) whenever the user presses spacebar anywhere in the my Swing app. Since there are so many controls and panels that could have focus, its not really possible to add keyevents to them all(not to mention gross). So I found ``` KeyboardFocusManager.getCurrentKe...
I think you answered that yourself - yes I think you can find out the current element that has focus, and if it is an instanceof a certain field class, you ignore the space for the purpose of pause event. If it seams heavy handed, don't worry, instanceof is VERY fast for the JVM (and in any cause you are talking human ...
I'm rusty on my Swing, but I think you should try registering a global listener using [Toolkit.addAWTEventListener](http://java.sun.com/javase/6/docs/api/java/awt/Toolkit.html#addAWTEventListener(java.awt.event.AWTEventListener,%20long)) with a `KEY_EVENT_MASK`. You can then filter the AWTEvent processing based on its ...
capturing global keypresses in Java
[ "", "java", "global", "keypress", "" ]
I'm trying to start using LINQ and specifically LINQ to SQL but I'm having some difficulties I've tried this with SqlMetal and now using the database table designer in Visual Studio and I keep getting similar errors, like in this code, using the data context I created with the database layout designer in VS2008. ``` ...
Try ``` var user = from u in dc.User where u.UserName == usn select u; ```
Try changing `User` to `dc.User`: ``` var user = from u in dc.User where u.UserName == usn select u; ``` The `User` is the property [System.Web.UI.Page.User](http://msdn.microsoft.com/en-us/library/system.web.ui.page.user.aspx).
LINQ to SQL error message: 'Where' not found
[ "", "c#", "linq", "linq-to-sql", "" ]
How to calculate the length (in pixels) of a string in Java? Preferable without using Swing. EDIT: I would like to draw the string using the drawString() in Java2D and use the length for word wrapping.
If you just want to use AWT, then use [`Graphics.getFontMetrics`](http://docs.oracle.com/javase/6/docs/api/java/awt/Graphics.html#getFontMetrics()) (optionally specifying the font, for a non-default one) to get a `FontMetrics` and then [`FontMetrics.stringWidth`](http://docs.oracle.com/javase/6/docs/api/java/awt/FontMe...
It doesn't always need to be toolkit-dependent or one doesn't always need use the FontMetrics approach since it requires one to first obtain a graphics object which is absent in a web container or in a headless enviroment. I have tested this in a web servlet and it does calculate the text width. ``` import java.awt.F...
Calculate the display width of a string in Java
[ "", "java", "string-length", "" ]
In my Java development I have had great benefit from the [Jad/JadClipse](http://en.wikipedia.org/wiki/JAD_%28JAva_Decompiler%29) decompiler. It made it possible to *know* why a third-party library failed rather than the usual guesswork. I am looking for a similar setup for C# and Visual Studio. That is, a setup where ...
Here is a good article about [Reflector and how to integrate Reflector into Visual Studio](http://en.csharp-online.net/Visual_Studio_Hacks%E2%80%94Hack_64:_Examine_the_Innards_of_Assemblies). > Of particular interest is the Reflector.VisualStudio Add-In. This > add-in, created by Jaime Cansdale, allows for Reflector t...
Try the open-source software <http://ilspy.net/>
Best (free?) decompiler for C# with Visual Studio integration?
[ "", "c#", "visual-studio", "decompiling", "" ]
I'm not sure why I'm getting this error, but shouldn't this code compile, since I'm already checking to see if queue is getting initialized? ``` public static void Main(String[] args) { Byte maxSize; Queue queue; if(args.Length != 0) { if(Byte.TryParse(args[0], out maxSize)) queue ...
The compiler doesn't know that the Environment.Exit() is going to terminate the program; it just sees you executing a static method on a class. Just initialize `queue` to null when you declare it. ``` Queue queue = null; ```
The compiler doesn't know that Environment.Exit() does not return. Why not just "return" from Main()?
C# error: Use of unassigned local variable
[ "", "c#", "initialization", "" ]
What is the right way to perform some static finallization? There is no static destructor. The `AppDomain.DomainUnload` event is not raised in the default domain. The `AppDomain.ProcessExit` event shares the total time of the three seconds (default settings) between all event handlers, so it's not really usable.
Basically, you can't. Design your way around it to the fullest extent possible. Don't forget that a program can *always* terminate abruptly anyway - someone pulling out the power being the obvious example. So anything you do has to be "best effort" - in which case I'd certainly *hope* that `AppDomain.ProcessExit` woul...
> Herfried Wagner has written an [excellent article](http://dotnet.mvps.org/dotnet/articles/sharedfinalizer/) explaining how to implement this – alas, in German (and VB). Still, the code should be understandable. I've tried it: ``` static readonly Finalizer finalizer = new Finalizer(); sealed class Finalizer { ~Fi...
Static Finalizer
[ "", "c#", ".net", "static", "destructor", "finalizer", "" ]
For work I have to code with an external company's API to deal with their proprietary database solution. Unfortunately the documentation they provide is more of an example guide then proper API docs, so it is very light on nitty gritty details like error codes, method returns, and exceptions. So for instance, a class ...
A nasty scenario. I hate to suggest it, but maybe [reflector](http://www.red-gate.com/products/reflector/) is your friend if it isn't obfuscated. There may be some IP issues, but in this case reversing it seems the only viable way of finding out what the API is. However, I suspect (from methods like .GetErrorCode()) th...
If I can't get code samples or talk to an original developer, I usually resort to [Reflector](http://www.red-gate.com/products/reflector/) to look at the underlying code. It's slow and inefficient, but sometimes that's all you can do.
How to deal with an Undocumented API/Framework under .NET?
[ "", "c#", ".net", "api", "documentation", "frameworks", "" ]
I'm sure this problem has been solved before and I'm curious how its done. I have code in which, when run, I want to scan the contents of a directory and load in functionality. Specifically, I am working with a scripting engine that I want to be able to add function calls to. I want the core engine to provide very lim...
It depends on the platform. On win32, you call `LoadLibrary` to load a DLL, then get functions from it with `GetProcAddress`. On Unixy platforms, the equivalents are `dlopen` and `dlsym`.
You can use the POSIX dlopen/dlsym/dlerror/dlclose functions in Linux/UNIX to dynamically open shared libraries and access the symbols (including functions) they provide, see the [man page](http://linux.die.net/man/3/dlopen) for details.
Dynamically Loading External Modules in a C Program?
[ "", "c++", "c", "dynamic", "modularity", "" ]
For example, I'm trying to convert 2008-09-26T01:51:42.000Z to 09/26/2008. What's the simplest way of accomplishing this?
The easiest way is to use [dateutil](http://labix.org/python-dateutil).parser.parse() to parse the date string into a timezone aware datetime object, then use strftime() to get the format you want. ``` import dateutil.parser d = dateutil.parser.parse('2008-09-26T01:51:42.000Z') print(d.strftime('%m/%d/%Y')) #==> '09...
I know this is really old question, but you can do it with python datetime.strptime() ``` >>> from datetime import datetime >>> date_format = "%Y-%m-%dT%H:%M:%S.%fZ" >>> datetime.strptime('2008-09-26T01:51:42.000Z', date_format) datetime.datetime(2008, 9, 26, 1, 51, 42) ```
How do you convert YYYY-MM-DDTHH:mm:ss.000Z time format to MM/DD/YYYY time format in Python?
[ "", "python", "datetime", "" ]
To preface I am using Borland C++ and the VCL. I need some sort of structured storage object which can be saved to disk as a single file and can contain multiple named blobs of binary data which I can programatically enumerate, access and manipulate. The [IStorage](http://msdn.microsoft.com/en-us/library/aa380015(VS....
A zip file is de facto a standard container, and it seems you can get a TStream interface to them: <http://www.tek-tips.com/faqs.cfm?fid=6734>
SolFS (Solid File System) from Eldos. <http://www.eldos.com/solfs/> Very reliable, but might not be the cheapest solution ($372 for one developer).
VCL alternative to IStorage
[ "", "c++", "vcl", "istorage", "structured-storage", "" ]
I'm refactoring a number of classes in an application to use interfaces instead of base classes. Here's the interfaces I created so far: * ICarryable implemented by all Item objects * IActable implemented by all Actor objects * IUseable implemented by some Item sub-classes * IWieldable implemented by some Item sub-cla...
Sounds like an ILocateable. Something whose location you can discover and track.
* ILocatable * IGeo * IAmSomewhere * IIsSomewhere Edit: * INoun
Need help choosing a name for an interface
[ "", "c#", ".net", "naming", "" ]
**EDIT: I missed a crucial point: .NET 2.0** Consider the case where I have a list of unsorted items, for the sake of simplicity of a type like this: ``` class TestClass { DateTime SomeTime; decimal SomePrice; // constructor } ``` I need to create a report-like output, where the total prices for each da...
[edit] Since you are using .NET 2.0 with C# 3.0, you can use [LINQBridge](http://www.albahari.com/nutshell/linqbridge.aspx) to enable this. LINQ; something like: ``` var groups = from row in testList group row by row.SomeTime; foreach (var group in groups.OrderBy(group => group.Key))...
Okay, so if you can't use LINQ: (I'm using var to save space, but it's easy to translate to C# 2.0 if necessary...) ``` var grouped = new SortedDictionary<DateTime, List<TestClass>>(); foreach (TestClass entry in testList) { DateTime date = entry.SomeTime.Date; if (!grouped.ContainsKey(date)) { grouped[date] ...
Iterating through list and creating summary lines on the fly
[ "", "c#", "loops", "" ]
There are **two different** ways to create an empty object in JavaScript: ``` var objectA = {} var objectB = new Object() ``` Is there any difference in how the script engine handles them? Is there any reason to use one over the other? Similarly it is also possible to create an empty array using different syntax: `...
## Objects There is no benefit to using `new Object()`, whereas `{}` can make your code more compact, and more readable. For defining empty objects they're technically the same. The `{}` syntax is shorter, neater (less Java-ish), and allows you to instantly populate the object inline - like so: ``` var myObject = { ...
Yes, There is a difference, they're not the same. It's true that you'll get the same results but the engine works in a different way for both of them. One of them is an object literal, and the other one is a constructor, two different ways of creating an object in javascript. ``` var objectA = {} //This is an object l...
Create an empty object in JavaScript with {} or new Object()?
[ "", "javascript", "arrays", "object", "javascript-objects", "new-operator", "" ]
I want to have a map that has a homogeneous key type but heterogeneous data types. I want to be able to do something like (pseudo-code): ``` boost::map<std::string, magic_goes_here> m; m.add<int>("a", 2); m.add<std::string>("b", "black sheep"); int i = m.get<int>("a"); int j = m.get<int>("b"); // error! ``` I could...
``` #include <map> #include <string> #include <iostream> #include <boost/any.hpp> int main() { try { std::map<std::string, boost::any> m; m["a"] = 2; m["b"] = static_cast<char const *>("black sheep"); int i = boost::any_cast<int>(m["a"]); std::cout << "I(" << i << ")\...
[How can I build a <favorite container> of objects of different types?](http://www.parashift.com/c++-faq/heterogeneous-list.html) > You can't, but you can fake it pretty well. In C/C++ all arrays are homogeneous (i.e., the elements are all the same type). However, with an extra layer of indirection you can give the ap...
how do you make a heterogeneous boost::map?
[ "", "c++", "boost", "dictionary", "" ]
A Java version of this question was just answered, and, well, I don't know how to do this in .net. So how do you calculate the display width of a string in C# / .net?
You've got the same problem in this question as was present in the Java question - not enough information! It will differ between WinForms and WPF. For WinForms: [Graphics.MeasureString](http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx) For WPF I'm not sure, but I suspect it will depend on the exact way you're d...
An alternative for Windows Forms is the static TextRenderer.MeasureText method. Although restricted to integer sizes, this (in tandem with TextRenderer.DrawText) renders more accurate and much higher quality ClearType text than the Graphics.MeasureString/DrawString duo.
Calculate the display width of a string in C#?
[ "", "c#", ".net", "" ]
Is there any Ruby equivalent for Python's builtin `zip` function? If not, what is a concise way of doing the same thing? A bit of context: this came up when I was trying to find a clean way of doing a check involving two arrays. If I had `zip`, I could have written something like: ``` zip(a, b).all? {|pair| pair[0] =...
Ruby has a zip function: ``` [1,2].zip([3,4]) => [[1,3],[2,4]] ``` so your code example is actually: ``` a.zip(b).all? {|pair| pair[0] === pair[1]} ``` or perhaps more succinctly: ``` a.zip(b).all? {|a,b| a === b } ```
Could you not do: ``` a.eql?(b) ``` Edited to add an example: ``` a = %w[a b c] b = %w[1 2 3] c = ['a', 'b', 'c'] a.eql?(b) # => false a.eql?(c) # => true a.eql?(c.reverse) # => false ```
What is a Ruby equivalent for Python's "zip" builtin?
[ "", "python", "ruby", "translation", "" ]
Is is better to do a joined query like this: ``` var employer = (from person in db.People join employer in db.Employers on person.EmployerID equals employer.EmployerID where person.PersonID == idPerson select employer).FirstOrDefault(); ``` Or i...
I'd use this: ``` var employer = (from person in db.People where person.PersonID == idPerson select person.Employer).FirstOrDefault(); ``` It's got the simplicity of the first version but still only fetches the data for the employer (rather than the person *and* the employer).
The second one could evaluate to null which would result in an error. I like the first one better because if it is null then you can deal with it without an exception being thrown.
Query with a join or use LINQ magic?
[ "", "c#", ".net", ".net-3.5", "" ]
I am writing an application which blocks on input from two `istreams`. Reading from either `istream` is a synchronous (blocking) call, so, I decided to create two `Boost::thread`s to do the reading. Either one of these threads can get to the "end" (based on some input received), and once the "end" is reached, both in...
I don't think there is a way to do it cross platform, but pthread\_cancel should be what you are looking for. With a boost thread you can get the [native\_handle](http://www.boost.org/doc/libs/1_37_0/doc/html/thread/thread_management.html#thread.thread_management.thread.nativehandle) from a thread, and call pthread\_ca...
Yes there is! `boost::thread::terminate()` will do the job to your specifications. It will cause the targeted thread to throw an exception. Assuming it's uncaught, the stack will unwind properly destroying all resources and terminating thread execution. The termination isn't instant. (The wrong thread is running at ...
Kill a blocked Boost::Thread
[ "", "c++", "iostream", "boost-thread", "" ]
In developing search for a site I am building, I decided to go the cheap and quick way and use Microsoft Sql Server's Full Text Search engine instead of something more robust like Lucene.Net. One of the features I would like to have, though, is google-esque relevant document snippets. I quickly found determining "rele...
Although it is implemented in Java, you can see one approach for that problem here: <http://rcrezende.blogspot.com/2010/08/smallest-relevant-text-snippet-for.html>
I know this thread is way old, but I gave this a try last week and it was a pain in the back side. This is far from perfect, but this is what I came up with. The snippet generator: ``` public static string SelectKeywordSnippets(string StringToSnip, string[] Keywords, int SnippetLength) { string snippedStr...
C# Finding relevant document snippets for search result display
[ "", "c#", "algorithm", "search", "relevance", "significance", "" ]
I'm writing a custom blog engine and would like to have trackbacks similar to Wordpress. I could look at the Wordpress source, but I'd really prefer a tutorial of some sort and so far I haven't been able to find one. Are there any good tutorials for implementing trackbacks or pingbacks in PHP5?
Trackbacks are fine, but they're very prone to spam, since there's no verification of their origin. You use a simple discovery method to find the trackpack entrypoint; look for RDF in the target site's source. Then it's simply a RESTful POST request to the destination site's trackback entrypoint passing the requisite t...
Implementing trackbacks isn't that hard at all. [Here](http://www.sixapart.com/pronet/docs/trackback_spec) you can find the official specification and an example at the bottom.
Trackbacks in PHP
[ "", "php", "trackback", "pingback", "" ]
Any python libs for parsing Bind zone files? Basically something that will aid in adding/removing zones and records. This needs to work even if someone modifies the zone file by hand so overwriting the zone files every time is not a solution.
I was unable to use bicop for classical zone files like these: ``` $TTL 86400 @ IN SOA ns1.first-ns.de. postmaster.robot.first-ns.de. ( 2006040800 ; serial 14400 ; refresh 1800 ; retry 604800 ; expire 86400 ) ; minimum @ IN NS ns1.first-n...
[easyzone](http://pypi.python.org/pypi/easyzone) is a nice layer over dnspython [Zoner](http://pypi.python.org/pypi/zoner/1.4.1) provides a web-interface for editing zone files and makes use of easyzone.
Any python libs for parsing Bind zone files?
[ "", "python", "bind", "" ]
I have a method that creates a MessageDigest (a hash) from a file, and I need to do this to a lot of files (>= 100,000). How big should I make the buffer used to read from the files to maximize performance? Most everyone is familiar with the basic code (which I'll repeat here just in case): ``` MessageDigest md = Mes...
Optimum buffer size is related to a number of things: file system block size, CPU cache size and cache latency. Most file systems are configured to use block sizes of 4096 or 8192. In theory, if you configure your buffer size so you are reading a few bytes more than the disk block, the operations with the file system ...
Yes, it's probably dependent on various things - but I doubt it will make very much difference. I tend to opt for 16K or 32K as a good balance between memory usage and performance. Note that you should have a try/finally block in the code to make sure the stream is closed even if an exception is thrown.
How do you determine the ideal buffer size when using FileInputStream?
[ "", "java", "performance", "file-io", "filesystems", "buffer", "" ]
Im currently using ie as an active x com thing on wxWidgets and was wanting to know if there is any easy way to change the user agent that will always work. Atm im changing the header but this only works when i manually load the link (i.e. call setUrl)
The only way that will "always work," so far as I've been able to find, is [changing the user-agent string in the registry](http://www.walkernews.net/2007/07/05/how-to-change-user-agent-string/). That will, of course, affect *every* web browser instance running on that machine. You might also try a Google search on `D...
I did a bit of googling today with the hint you provided head geek and i worked out how to do it. wxWidgets uses an activex rapper class called FrameSite that handles the invoke requests. What i did was make a new class that inherits from this, handles the DISPID\_AMBIENT\_USERAGENT event and passes all others on. Thu...
ie useragent wxWidgets
[ "", "c++", "internet-explorer", "com", "wxwidgets", "user-agent", "" ]
If you provide `0` as the `dayValue` in `Date.setFullYear` you get the last day of the previous month: ``` d = new Date(); d.setFullYear(2008, 11, 0); // Sun Nov 30 2008 ``` There is reference to this behaviour at [mozilla](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/setFullYear...
``` var month = 0; // January var d = new Date(2008, month + 1, 0); console.log(d.toString()); // last day in January ``` ``` IE 6: Thu Jan 31 00:00:00 CST 2008 IE 7: Thu Jan 31 00:00:00 CST 2008 IE 8: Beta 2: Thu Jan 31 00:00:00 CST 2008 Opera 8.54: Th...
I find this to be the best solution for me. Let the Date object calculate it for you. ``` var today = new Date(); var lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0); ``` Setting day parameter to 0 means one day less than first day of the month which is last day of the previous month.
Calculate last day of month
[ "", "javascript", "date", "" ]
So my code is below. I'm not getting any errors and it places everything in the node just fine. But based on my debug statements Everytime anything is inserted it's finding the root. I'm not sure if that is right. But according to output file for the assignment, my answers are different when it comes to the height of t...
You need to change the wording of your debug statements Really it should read (not Root node) ``` cout << "Leaf Node Found" << newNode->data << endl; ``` It is only the root when it is first called after that any call with node->left or node->right makes it an intermediate node. To write height() I would do this: ...
You need to start off with your root init'd to null. Also, you are passing \*&node in; it should be \*node. Else you're passing a pointer to the address(or reference, I'm not sure which in this context, but both aren't going to be right). You should be passing a pointer to Node in, not a reference. ``` template <class...
C++ Binary Search Tree Insert via Recursion
[ "", "c++", "insert", "binary-tree", "" ]
I have been working with T-SQL in MS SQL for some time now and somehow whenever I have to insert data into a table I tend to use syntax: ``` INSERT INTO myTable <something here> ``` I understand that keyword `INTO` is optional here and I do not have to use it but somehow it grew into habit in my case. My question is...
`INSERT INTO` is the standard. Even though `INTO` is optional in most implementations, it's required in a few, so it's a good idea to include it if you want your code to be portable. You can find links to several versions of the SQL standard [here](http://en.wikipedia.org/wiki/SQL#Standardization). I found an HTML ver...
They are the same thing, `INTO` is completely optional in T-SQL (other SQL dialects may differ). Contrary to the other answers, I think it impairs readability to use `INTO`. I think it is a conceptional thing: In my perception, I am not inserting a *row* into a table named "Customer", but I am inserting a *Customer*....
INSERT vs INSERT INTO
[ "", "sql", "sql-server", "database", "t-sql", "sql-insert", "" ]
Eclipse issues warnings when a `serialVersionUID` is missing. > The serializable class Foo does not declare a static final > serialVersionUID field of type long What is `serialVersionUID` and why is it important? Please show an example where missing `serialVersionUID` will cause a problem.
The docs for [`java.io.Serializable`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/Serializable.html) are probably about as good an explanation as you'll get: > The serialization runtime associates with each serializable class a version number, called a `serialVersionUID`, which is used during ...
If you're serializing just because you have to serialize for the implementation's sake (who cares if you serialize for an `HTTPSession`, for instance...if it's stored or not, you probably don't care about `de-serializing` a form object), then you can ignore this. If you're actually using serialization, it only matters...
What is a serialVersionUID and why should I use it?
[ "", "java", "serialization", "serialversionuid", "" ]
In Visual Studio, I often use objects only for RAII purposes. For example: ``` ScopeGuard close_guard = MakeGuard( &close_file, file ); ``` The whole purpose of *close\_guard* is to make sure that the file will be close on function exit, it is not used anywhere else. However, Visual Studio gives me a warning that a "...
**Method 1:** Use the `#pragma warning` directive. `#pragma warning` allows selective modification of the behavior of compiler warning messages. ``` #pragma warning( push ) #pragma warning( disable : 4705 ) // replace 4705 with warning number ScopeGuard close_guard = MakeGuard( &close_file, file ); #pragma warning(...
If your object has a non-trivial destructor, Visual Studio should *not* be giving you that warning. The following code does not generate any warnings in VS2005 with warnings turned all the way up (/W4): ``` class Test { public: ~Test(void) { printf("destructor\n"); } }; Test foo(void) { return Test(); } int main...
Dealing with C++ "initialized but not referenced" warning for destruction of scope helpers?
[ "", "c++", "visual-studio-2005", "warnings", "" ]
I'm teaching Java EE at the university, and this was a question a student asked. I said "no", but I wasn't really sure, so I thought I might ask you mighty developers. :) Basically, what I'd like to do is to use entities if they were in my context: cat getters, setters, etc, so like normal POJOs. if I use an EJB using...
In a basic modern world Java EE application, it is broken into various layers, where you have 4 basic layers ``` +--------------------+ | Presentation | +--------------------+ | Controller/Actions | +--------------------+ | Business Delegate | | (Service) | +--------------------+ | Data Access Layer |...
I've never tried it, but JSF is supposed to work better with [Facelets](https://facelets.dev.java.net/) than with JSP. IBM has [an article](http://www.ibm.com/developerworks/java/library/j-facelets/) about it.
Is there any other strongly-integrated presentation layer tool other than JSF/JSP for Java EE?
[ "", "java", "jakarta-ee", "presentation-layer", "" ]
Very basic question: how do I write a `short` literal in C++? I know the following: * `2` is an `int` * `2U` is an `unsigned int` * `2L` is a `long` * `2LL` is a `long long` * `2.0f` is a `float` * `2.0` is a `double` * `'\2'` is a `char`. But how would I write a `short` literal? I tried `2S` but that gives a compil...
``` ((short)2) ``` Yeah, it's not strictly a short literal, more of a casted-int, but the behaviour is the same and I think there isn't a direct way of doing it. > That's what I've been doing because I couldn't find anything about it. I would guess that the compiler would be smart enough to compile this as if it's a ...
C++11 gives you pretty close to what you want. *(Search for "user-defined literals" to learn more.)* ``` #include <cstdint> inline std::uint16_t operator "" _u(unsigned long long value) { return static_cast<std::uint16_t>(value); } void func(std::uint32_t value); // 1 void func(std::uint16_t value); // 2 func(0...
How do I write a short literal in C++?
[ "", "c++", "literals", "" ]
I'm writing a PHP script and the script outputs a simple text file log of the operations it performs. How would I use PHP to delete the first several lines from this file when it reaches a certain file size? Ideally, I would like it to keep the first two lines (date/time created and blank) and start deleting from line...
``` $x_amount_of_lines = 30; $log = 'path/to/log.txt'; if (filesize($log) >= $max_size)) { $file = file($log); $line = $file[0]; $file = array_splice($file, 2, $x_amount_of_lines); $file = array_splice($file, 0, 0, array($line, "\n")); // put the first line back in ... } ``` edit: with correction from by rca...
## Use the SPL, Luke PHP 5 comes with plenty of iterators goodness : ``` <?php $line_to_strip = 5; $new_file = new SplFileObject('test2.log', 'w'); foreach (new LimitIterator(new SplFileObject('test.log'), $line_to_strip) as $line) $new_file->fwrite($line); ?> ``` It's cleaner that what you can do while m...
How to use PHP to delete X number of lines from the beginning of a text file?
[ "", "php", "file", "logging", "" ]
I am looking to set full trust for a single web part, is this possible? manifest.xml maybe?
Have you tried registering the assembly in the GAC? This is the preferred approach to giving any assembly full trust on your machine: ``` gacutil.exe \i C:\Path\To\Dll.dll ``` Hope that helps. Let me know if I misunderstood your question.
As far as I recall manifest.xml is correct, and you specify the CodeAccessSecurity. This article has a detailed description about it <http://www.dotnetmafia.com/blogs/dotnettipoftheday/archive/2007/07/05/how-to-configure-code-access-security-for-a-web-part.aspx> when you deploy your solution then you deploy it with t...
How do I set full trust for a single Web Part in SharePoint?
[ "", "c#", "sharepoint", "web-parts", "full-trust", "" ]
I have an importer process which is running as a windows service (debug mode as an application) and it processes various xml documents and csv's and imports into an SQL database. All has been well until I have have had to process a large amount of data (120k rows) from another table (as I do the xml documents). I am n...
I found out that it was nHibernate creating the cursor on the large table. I am yet to understand why, but in the mean time I have replaced the large table data access model with straight forward ado.net calls
When are you `COMMIT`ting the data? Are there any locks or deadlocks (sp\_who)? If 120,000 rows is considered large, how much RAM is SQL Server using? When the application hangs, is there anything about the point where it hangs (is it an `INSERT`, a lookup `SELECT`, or what?)? It seems to me that that commit size is w...
Import Process maxing SQL memory
[ "", "c#", "sql-server-2005", "nhibernate", "" ]
I've seen some very good questions on Stack Overflow concerning delegates, events, and the .NET implementation of these two features. One question in particular, "[How do C# Events work behind the scenes?](https://stackoverflow.com/questions/213638/how-do-c-events-work-behind-the-scenes#213651)", produced a great answe...
I'm not sure that is surprising... compare to the same for properties vs fields (since properties before the same function as events: encapsulation via accessors): ``` .field public string Foo // public field .property instance string Bar // public property { .get instance string MyType::get_Bar() .set instanc...
Events aren't the same as delegates. Events encapsulate adding/removing a handler for an event. The handler is represented with a delegate. You *could* just write AddClickHandler/RemoveClickHandler etc for every event - but it would be relatively painful, and wouldn't make it easy for tools like VS to separate out eve...
If events are implemented as delegates in .NET, what is the point of the .event IL section?
[ "", "c#", ".net", "events", "delegates", "cil", "" ]
I am trying to fill a form in a php application from a C# client (Outlook addin). I used Fiddler to see the original request from within the php application and the form is transmitted as a multipart/form. Unfortunately .Net does not come with native support for this type of forms (WebClient has only a method for uploa...
This is cut and pasted from some sample code I wrote, hopefully it should give the basics. It only supports File data and form-data at the moment. ``` public class PostData { private List<PostDataParam> m_Params; public List<PostDataParam> Params { get { return m_Params; } set { m_Params ...
Thanks for the answers, everybody! I recently had to get this to work, and used your suggestions heavily. However, there were a couple of tricky parts that did not work as expected, mostly having to do with actually including the file (which was an important part of the question). There are a lot of answers here alread...
Multipart forms from C# client
[ "", "c#", "http", "multipartform-data", "" ]
Does anyone have a simple, efficient way of checking that a string doesn't contain HTML? Basically, I want to check that certain fields only contain plain text. I thought about looking for the < character, but that can easily be used in plain text. Another way might be to create a new System.Xml.Linq.XElement using: `...
I just tried my XElement.Parse solution. I created an extension method on the string class so I can reuse the code easily: ``` public static bool ContainsXHTML(this string input) { try { XElement x = XElement.Parse("<wrapper>" + input + "</wrapper>"); return !(x.DescendantNodes().Count() == 1 &...
The following will match any matching set of tags. i.e. <b>this</b> ``` Regex tagRegex = new Regex(@"<\s*([^ >]+)[^>]*>.*?<\s*/\s*\1\s*>"); ``` The following will match any single tag. i.e. <b> (it doesn't have to be closed). ``` Regex tagRegex = new Regex(@"<[^>]+>"); ``` You can then use it like so ``` bool hasT...
How to validate that a string doesn't contain HTML using C#
[ "", "c#", "html", "validation", "" ]
I'm [listening to a talk](http://channel9.msdn.com/shows/Going+Deep/Inside-C-40-dynamic-type-optional-parameters-more-COM-friendly/) about **C#4**'s `dynamic` keyword and I'm wondering... Will this feature be orthogonal to other .NET features, for example will it support extension methods? ``` public static class StrE...
From the ["New Features in C# 4" word doc](http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=csharpfuture&DownloadId=3550): > Dynamic lookup will not be able to > find extension methods. Whether > extension methods apply or not depends > on the static context of the call > (i.e. which using...
This works which I find interesting at least... ``` public static class StrExtension { public static string twice(this string str) { return str + str; } } ... dynamic x = "Yo"; StrExtension.twice(x); ``` Still, if the compiler can find the correct extension method at compile time then I don't see why it can't pac...
Will the dynamic keyword in C#4 support extension methods?
[ "", "c#", "dynamic", "extension-methods", "c#-4.0", "" ]
I have some code doing this : ``` var changes = document.getElementsByName(from); for (var c=0; c<changes.length; c++) { var ch = changes[c]; var current = new String(ch.innerHTML); etc. } ``` This works fine in FF and Chrome but not in IE7. Presumably because getElementsByName isn't working in IE. What's...
In case you don't know why this isn't working in IE, here is [the MSDN documentation on that function](http://msdn.microsoft.com/en-us/library/ms536438(VS.85).aspx): > When you use the getElementsByName method, all elements in the document that have the specified NAME attribute or ID attribute value are returned. > > ...
There are a couple of problems: 1. IE is indeed confusing `id=""` with `name=""` 2. `name=""` isn't allowed on `<span>` To fix, I suggest: 1. Change all the `name=""` to `class=""` 2. Change your code like this: - ``` var changes = document.getElementById('text').getElementsByTagName('span'); for (var c=0; c<chang...
getElementsByName in IE7
[ "", "javascript", "dom", "internet-explorer-7", "" ]
> **Edit:** The code here still has some bugs in it, and it could do better in the performance department, but instead of trying to fix this, for the record I took the problem over to the Intel discussion groups and got lots of great feedback, and if all goes well a polished version of Atomic float will be included in ...
I would seriously advise against public inheritance. I don't know what the atomic implementation is like, but im assuming it has overloaded operators that use it as the integral type, which means that those promotions will be used instead of your float in many (maybe most?) cases. I don't see any reason why that would...
It looks like your implementation assumes that `sizeof(size_t) == sizeof(float)`. Will that always be true for your target platforms? And I wouldn't say *threading* heresy so much as *casting* heresy. :)
Is this C++ implementation for an Atomic float safe?
[ "", "c++", "thread-safety", "atomic", "tbb", "" ]
this is a question that when programming I always wonder: What to use when we are writing code: ``` var myFiles = Directory.GetFiles(fullPath); ``` or ``` string[] myFiles = Directory.GetFiles(fullPath); ``` ***var*** is new and is a *Implicitly Typed Local Variables*, so we can only use locally and it has rules li...
Beyond the obvious use of `var` with LINQ, I also use it to abbreviate hairy variable declarations for readability, e.g.: ``` var d = new Dictionary<string, Dictionary<string, Queue<SomeClass>>>(); ``` In general, I get a kind of comfort (for want of a better word) from static typing that makes me reluctant to give i...
You'll get a huge variety of opinions on this one - from "use var everywhere" to "only use var with anonymous types, where you basically have to." I like [Eric Lippert's take on it](http://csharpindepth.com/ViewNote.aspx?NoteID=61): > All code is an abstraction. Is what > the code is “really” doing is > manipulating d...
What to use: var or object name type?
[ "", "c#", ".net-3.5", "c#-3.0", "anonymous-objects", "" ]
I'm looking for a PHP library/function/class which can create [Identicon](http://en.wikipedia.org/wiki/Identicon)s.
how about [this](http://scott.sherrillmix.com/blog/blogger/wp_identicon/) it's how Scott did the identicons for Wordpress, you can download the code and see for yourself. Hope it helps.
i use this: ``` class Gravatar { static public function GetGravatarUrl( $email, $size = 128, $type = 'identicon', $rating = 'pg' ) { $gravatar = sprintf( 'http://www.gravatar.com/avatar/%s?d=%s&s=%d&r=%s', md5( $email ), $type, $size, $rating ); return $gravatar; ...
Is there identicon library for PHP
[ "", "php", "identicon", "" ]
I met an interesting issue about C#. I have code like below. ``` List<Func<int>> actions = new List<Func<int>>(); int variable = 0; while (variable < 5) { actions.Add(() => variable * 2); ++ variable; } foreach (var act in actions) { Console.WriteLine(act.Invoke()); } ``` I expect it to output 0, 2, 4, ...
Yes - take a copy of the variable inside the loop: ``` while (variable < 5) { int copy = variable; actions.Add(() => copy * 2); ++ variable; } ``` You can think of it as if the C# compiler creates a "new" local variable every time it hits the variable declaration. In fact it'll create appropriate new clos...
I believe what you are experiencing is something known as Closure <http://en.wikipedia.org/wiki/Closure_(computer_science)>. Your lamba has a reference to a variable which is scoped outside the function itself. Your lamba is not interpreted until you invoke it and once it is it will get the value the variable has at ex...
Captured variable in a loop in C#
[ "", "c#", "closures", "captured-variable", "" ]
I've noticed that plenty of opensource project doesn't use BITWISE flags anymore, even if it's fully supported by programming enviroment common for web ( php/Mysql). It's that a "lost practise" for some effective problem, or is just that a lot of php programmers don't know how to handle this type of implementation? No...
I'll stick my neck out and say that every technical position requires a sound understanding of bitwise operations. And I have an anecdote that indirectly addresses the topic. January 2007 I was in Cochin, India, recruiting for permanent development staff. Since I wasn't involved in the preliminary screening of candid...
A lot of programmers these days seem to just have their heads filled with just enough knowledge to brute-force code out and then sent into the workforce without being taught what words like "bitwise" even mean. It's a dying art I tell you...
Bitwise Flags abandoned?
[ "", "php", "mysql", "open-source", "" ]
I'm trying to figure out how to pass arguments to an anonymous function in JavaScript. Check out this sample code and I think you will see what I mean: ``` <input type="button" value="Click me" id="myButton" /> <script type="text/javascript"> var myButton = document.getElementById("myButton"); var myMessage ...
Your specific case can simply be corrected to be working: ``` <script type="text/javascript"> var myButton = document.getElementById("myButton"); var myMessage = "it's working"; myButton.onclick = function() { alert(myMessage); }; </script> ``` This example will work because the anonymous function created and a...
What you've done doesn't work because you're binding an event to a function. As such, it's the event which defines the parameters that will be called when the event is raised (i.e. JavaScript doesn't know about your parameter in the function you've bound to onclick so can't pass anything into it). You could do this ho...
How can I pass arguments to anonymous functions in JavaScript?
[ "", "javascript", "jquery", "" ]