Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am using Rational Application Developer v7.0 that ships with an integrated test environment. When I get to debugging my webapp, the server startup time in debug mode is close to 5-6 minutes - enough time to take a coffee break! At times, it so pisses me off that I start cursing IBM for building an operating system instead of an app server! Spawning 20+ processes and useless services with no documented configuration to tuning it, to starting any faster. I am sure there are many java developers out there who would agree with me on this. I tried to disable the default apps and a set of services via my admin console, however that hasn't helped much. I have no webservices, no enterprise beans, no queues, just a simple web app which requires a connection pool. Have you done something in the past to make your integrated test environment, start fast in debug mode and there by consume less RAM? UPDATE: I tried disabling a few services (internationalization, default apps etc...) and now the WebSphere server went from bad to worse. Not only doesn't it take horrifying startup time, it keeps freezing every now and then for up to 2 minutes. :-( Sounds like, optimization is not such a good thing, always!
The best way to debug server code is to use remote debugging. First you need to add the following to the JVM params in the server start script: ``` -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 ``` This will cause the JVM to listen on the specified port, then from your IDE you can start a remote debug session against that port and debug as if the code was running in the same process. Working this way prevent you restarting the server so frequently and hence side-steps your problem with Websphere's start-up time. You can get some odd results if the binaries on the server and the source in the IDE get out of sync but on the whole that's not a problem.
One of the main reasons is that you have a large application with many modules, classes, manifests, XML descriptors so on, and the fact that Websphere application server start up process is single threaded per se (thus each application may be started in a separate thread if they has equal weight). One other reason is that the Eclipse EMF and JST frameworks are very I/O intensive during startup and publish/deploy. One other reason for the tedious start up is the annotation scanning which will occur during publish/deploy. This annotation scanning can be controlled and modified in a various ways. Look at this site: <http://wasdynacache.blogspot.se/2012/05/how-to-speed-up-annotation-processing.html> First of all, examine and evaluate your hardware, both CPU, memory and HDD. Is your processor/s running 100% for a long time during start up? If so, the processor may be too weak. Is paging occur? then you may have to put in some more RAM. The Websphere/eclipse JST and EMF frameworks are very I/O intense so you should consider to invest in a SSD disc. You should also make sure that other processes on your machine (virus protection software etc.) don´t steal hardware resources from the Websphere java processes. So for the hardware: 1. Processor - a pretty fast one, since the publish and the startup is mostly singlethreaded you do not need that many cpu cores 2. Memory - You will at least need 512Mb of physical RAM, this depends of the size of your application of course. 3. Storage - I would definitely go for a fast SSD since the underlying eclipse framework is I/O intensive. Here are some tricks to reduce the footprint of the start up phase. Please before applying these settings make sure that you record a baseline start up so that you can observe the difference in start up, i.e. the reduced start up time. 1. JVM args : -Xverify:none -Xquickstart -Xnoclassgc -XX:+UseNUMA -XtlhPrefetch -Xgcthreads4 (I got 4 virtual processors installed on my machine) 2. Extend the heap size to match the demands of your application. 3. Disable the autostart of the application to reduce publish time. 4. Disable PMI and unnecessary tracing. 5. Profile your application during startup and fix bottlenecks if found any. Other JVM arguments that may gain performance: * com.ibm.cacheLocalHost=true * com.ibm.ws.classloader.zipFileCacheSize=512 * com.ibm.ws.classloader.resourceRequestCacheSize=1024 * com.ibm.ws.management.event.pull\_notification\_timeout =20000 * com.ibm.ws.amm.scan.context.filter.packages=true * org.eclipse.jst.j2ee.commonarchivecore.disableZip=true Jvm arguments that will make the Websphere application server to stop immediately: * com.ibm.ejs.sm.server.quiesceTimeout=0 * com.ibm.ejs.sm.server.quiesceInactiveRequestTime=1000 Webcontainer properties: * com.ibm.wsspi.jsp.disableTldSearch=true * com.ibm.wsspi.jsp.disableResourceInjection=true JVM arguments that may be specified eclipse.ini (Note that the heap parameters is configured according to the conditions of my environment) * -Dcom.ibm.ws.management.event.max\_polling\_interval=5000 * -Xquickstart * -Xverify:none * -Xmxcl25000 * -Xjit:dataTotal=65536 * -Xcodecache64m * -Xscmx48m * -Xnolinenumbers * -Xverify:none * -Xmnx64m * -Xmx1446m * -Xmnx64m * -XX:+UseCompressedOops * -XX:+UseNUMA
Websphere Application Server - What on earth will it take to start any fast?
[ "", "java", "performance", "jakarta-ee", "websphere", "" ]
Using this: ``` Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) ``` I get this output: ``` "C:\\Documents and Settings\\[USER]\\Application Data" ``` How can I get the root directory of all users? i.e.: ``` "C:\\Documents and Settings\\[USER]\\" ```
May be this will be a good solution: taking in account whether this is Vista/Win7 or XP and without using environment variables: ``` string path = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName; if ( Environment.OSVersion.Version.Major >= 6 ) { path = Directory.GetParent(path).ToString(); } ``` Though using the environment variable is much more clear.
Try: ``` System.Environment.GetEnvironmentVariable("USERPROFILE"); ``` Edit: If the version of .NET you are using is 4 or above, you can use the `Environment.SpecialFolder` enumeration: ``` Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); ```
How can I get the current user directory?
[ "", "c#", "windows", "environment", "special-folders", "" ]
I'm trying to use the **C++ STD TechnicalReport1** extensions to generate numbers following a normal distribution, but this code (adapted from [this article](http://www.johndcook.com/cpp_TR1_random.html#normal)): ``` mt19937 eng; eng.seed(SEED); normal_distribution<double> dist; // XXX if I use the one below it exits the for loop // uniform_int<int> dist(1, 52); for (unsigned int i = 0; i < 1000; ++i) { cout << "Generating " << i << "-th value" << endl; cout << dist(eng) << endl; } ``` only prints 1 "Generating..." log message, then *never exits the for loop*! If I use the distribution I commented out instead, it terminates, so I'm wondering what I'm doing wrong. Any idea? Thanks a lot!
This definitely would not hang the program. But, not sure if it really meets your needs. ``` #include <random> #include <iostream> using namespace std; typedef std::tr1::ranlux64_base_01 Myeng; typedef std::tr1::normal_distribution<double> Mydist; int main() { Myeng eng; eng.seed(1000); Mydist dist(1,10); dist.reset(); // discard any cached values for (int i = 0; i < 10; i++) { std::cout << "a random value == " << (int)dist(eng) << std::endl; } return (0); } ```
I have had the same issue with the code originally posted and investigated the GNU implementation of first some observations: with g++-4.4 and using the code hangs, with g++-4.5 and using -std=c++0x (i.e. not TR1 but the real thing) above code **works** IMHO, there was a change between TR1 and c++0x with regard to adaptors between random number generation and consumption of random numbers -- mt19937 produces integers, normal\_distribution consumes doubles the c++0x uses adaption automatically, the g++ TR1 code does not in order to get your code working with g++-4.4 and TR1, do the following ``` std::tr1::mt19937 prng(seed); std::tr1::normal_distribution<double> normal; std::tr1::variate_generator<std::tr1::mt19937, std::tr1::normal_distribution<double> > randn(prng,normal); double r = randn(); ```
C++ TR1: how to use the normal_distribution?
[ "", "c++", "tr1", "normal-distribution", "" ]
**Update**: As @PaulGroke points out below, things have changed with Java 7: there now is [AutoCloseable](http://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html). Which isn't tied to streams and supported by the new [try-with-resources](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) construct. `AutoCloseable` is the direct Java equivalent for .NET's `IDisposable` interface. --- The `Closeable` interface introduced in Java 1.5 is tightly tied to streams, and even has an exception specifier for `IOException`. This suggests that it should only be used for streams or other IO related activities, rather than general purpose cleanup logic. Certainly the description for the `close()` method would make absolutely no sense outside of a stream/IO context: > `void close() throws IOException` > > *Closes this stream and releases any system resources associated with it.* Should I therefore declare my own interface, `Disposable`, with a `Dispose()` method on it, and use that as an analogue to .NET's `IDisposable` interface? Or should I re-use `Closeable` even though it may not be a perfect fit?
Especially given that close() throws an IOException you then have to write exception handling code for, I would advise you write your own interface. This interface can then throw any checked exceptions that are appropriate to the use you want to put the interface to. Interfaces tend to signify intent in the mind of the reader, so having a class implement an IO-associated Closeable interface will make the reader assume the class is also IO-based. Obviously, if the objects you do want to close *are* all IO-related, you should use Closeable. But otherwise go for ``` /** Interface for objects that require cleanup post-use. Call dispose() in finally block! */ public interface Disposable { public void dispose(); } ```
I'm sure most people are aware of it, but since this question is still among the top results when searching for "IDisposable Java" (#2 result for me just now), and it's still not mentioned here... Things have changed with Java 7: there now is [AutoCloseable](http://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html). Which isn't tied to streams and supported by the new [try-with-resources](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) construct.
Should Closeable be used as the Java equivalent for .NET's IDisposable?
[ "", "java", "idisposable", "" ]
I have a Wicket application and my pages expire very quickly. Why is this, and what can I do about it?
I assume that by "My page is Expiring" you mean that the session is expiring? If so, you can increase the session-timeout in the web.xml of your project: ``` <session-config> <session-timeout>30</session-timeout> </session-config> ``` The timeout is specified in minutes.
You can also do this programatically, by getting the HttpSession of the request and setting MaxInactiveInterval. ``` Integer timeoutInMinutes = 20; Request request = RequestCycle.get().getRequest(); if( request instanceof WebRequest ) { WebRequest wr = (WebRequest)request; HttpSession session = wr.getHttpServletRequest().getSession(); if( session != null ) { session.setMaxInactiveInterval(timeoutInMinutes*60); } } ```
Pages expire very quickly in Wicket
[ "", "java", "wicket", "" ]
I have the code below working like a charm: ``` var div = $('#div'); div.html('<div>one line</div><div>another line</div>'); div.slideDown('slow'); ``` But the problem comes when I need to change the content (the number of lines): ``` div.html('<div>one line replacement</div><div>another line replacement</div><div>third line</div>') ``` This transition is too fast. How to animate this?
You can add an invisible span to the html: ``` <span class="foo" style="display: none">some other lines</span> ``` And then fade them in: ``` $("span.foo").fadeIn('slow'); ``` Going by your edit, you may also want to consider: ``` div.slideUp('slow'); // you may want this to be 'fast' div.html('some other lines'); div.slideDown('slow'); ```
A wrinkle on Daniel Sloof's answer: ``` div.fadeOut('fast', function() { div.html(html); div.fadeIn('fast'); } ``` This will ensure your first animation is complete before proceeding. In my current case at least, fading makes a nicer experience than sliding.
jQuery smooth change of innerHTML
[ "", "javascript", "jquery", "html", "slideup", "" ]
I have the following code in a JavaScript file: ``` $(document).ready(function() { detectscreen(); }); $(window).resize(function(){ detectscreen(); }); function windowWidth() { if(!window.innerWidth) { // user is being a git, using ie return document.documentElement.clientWidth; } else { return window.innerWidth; }} function detectscreen() { if (windowWidth()>1280) { $('body').append('<div id="gearsfloat"></div>'); }} ``` Basically, what it does is append an object to the end of the document if the width is less than 1280 pixels, however what this does is append it every single time the page is resized. I don't think I can use the `once` function because it would only run it once and then the next time it is resized, it's dead. Anything I can do? *NOTE*: I, in fact, DO want it to be checked on the resize of the page, but the effect is that it happens over and over again. ``` if (windowWidth()>1280 && !$('gearsfloat')) { $('body').append('<div id="gearsfloat"></div>'); } ``` The above (by Jason) ~~works~~ does *not* work but then it won't delete it when it gets less than 1280. Is there anything I can do?
Keep track of whether the element exists or not, and add/remove it when the condition changes. That way you will only add it once, it will be removed when it shouldn't be there, and you don't do any unneccesary adding or removing: ``` var gearsExists = false; function detectscreen() { var shouldExist = windowWidth() > 1280; if (shouldExist != gearsExists) { if (shouldExist) { $('body').append('<div id="gearsfloat"></div>'); } else { $('#gearsfloat').remove(); } gearsExists = shouldExist; } } ```
``` if (windowWidth()>1280 && !$('gearsfloat')) { $('body').append('<div id="gearsfloat"></div>'); } ``` Check if the element already exists first?
Resize script appends object, does it over and over again
[ "", "javascript", "jquery", "" ]
I have a bunch of sorted lists of objects, and a comparison function ``` class Obj : def __init__(p) : self.points = p def cmp(a, b) : return a.points < b.points a = [Obj(1), Obj(3), Obj(8), ...] b = [Obj(1), Obj(2), Obj(3), ...] c = [Obj(100), Obj(300), Obj(800), ...] result = magic(a, b, c) assert result == [Obj(1), Obj(1), Obj(2), Obj(3), Obj(3), Obj(8), ...] ``` what does `magic` look like? My current implementation is ``` def magic(*args) : r = [] for a in args : r += a return sorted(r, cmp) ``` but that is quite inefficient. Better answers?
Python standard library offers a method for it: [`heapq.merge`](http://docs.python.org/library/heapq.html#heapq.merge). As the documentation says, it is very similar to using [itertools](http://docs.python.org/library/itertools.html#itertools.chain) (but with more limitations); if you cannot live with those limitations (or if you do not use Python 2.6) you can do something like this: ``` sorted(itertools.chain(args), cmp) ``` However, I think it has the same complexity as your own solution, although using iterators should give some quite good optimization and speed increase.
I like Roberto Liffredo's answer. I didn't know about heapq.merge(). Hmmmph. Here's what the complete solution looks like using Roberto's lead: ``` class Obj(object): def __init__(self, p) : self.points = p def __cmp__(self, b) : return cmp(self.points, b.points) def __str__(self): return "%d" % self.points a = [Obj(1), Obj(3), Obj(8)] b = [Obj(1), Obj(2), Obj(3)] c = [Obj(100), Obj(300), Obj(800)] import heapq sorted = [item for item in heapq.merge(a,b,c)] for item in sorted: print item ``` Or: ``` for item in heapq.merge(a,b,c): print item ```
Merge sorted lists in python
[ "", "python", "arrays", "merge", "sorting", "" ]
When i open a form in visual studio 2005 (c#) the designer automaticaly resize the form and move/resize controls without touching the designer at all. The source file is changed and when i close the designer i'm asked to save the \*.cs file. I tried to look into visual studio options without any success. any ideas? visual studio setup or something? thanks, Tal
I found a work around. not sure what happens behind but i changed my display properties. and it works fine. here is the sequence: display propertis->settings tab->advance. in the the advance dialog i changed the "DPI Settings" from Large (120dpi) to Normal (96 dpi)
I have been working on this problem for most of today and found some interesting things: The main source of the problem seems to be relying on anchoring. If I use docking to position my controls, instead of anchoring, my problems seem to go away. I found a couple of blog posts from 2003(!), which detail how you might use docking instead of anchoring, and explain how anchoring can break the Windows Forms designer. It seems like this problem might be over 7 years old! Here are the posts: * <http://weblogs.asp.net/rweigelt/archive/2003/09/24/28984.aspx> * <http://weblogs.asp.net/rweigelt/archive/2003/10/17/32407.aspx> * <http://weblogs.asp.net/rweigelt/archive/2003/10/23/33181.aspx>
visual studio 2005 designer moves controls and resizes Form
[ "", "c#", "visual-studio", "designer", "" ]
I want my application to be able to work with multiple db vendors. In other words, depending on the DB infrastructure of the client, the db schema will be deployed on one of Oracle, MySQL, SQL Server. I am between using ODBC and OleDB, and the following key requirements that must be taken into account for the selection: * the DB schema must be created from within the application (I was told that ODBC may be problematic in this case, is this true?) * it is strongly desirable that the end users are not required to install any additional software (i.e. Oracle Instant Client etc). So, the driver should be preferably either: 1. already bundled with Windows. Does Windows have a generic version of ODBC / OleDB? 2. be able to be bundled in a way with the application. I.E. in Java, I can bundle the JDBC driver for MySQL as a .jar file with my application. Can this be done by including a .dll file? * it is strongly desirable that the end users are not required to make any external configuration, such as creating ODBC datasources Cheers!
Most ODBC/OLEDB drivers are using a "common language" which still requires some kind of native device driver or "client install" provided by the vendor to properly connect to the database. What you want to look for is a proper ADO.NET driver, which will have all the required libraries built into it, or it may only require a second DLL to go with it that doesn't not require a "client install". This will also allow for easy use of the Connectin String in your app.config file and all the goodness that ADO.NET provides. Here are some links to the common ones you need: * MySQL - [MySQL Connector](http://dev.mysql.com/downloads/connector/net/) Oracle - * [Oracle Data Provider](http://www.oracle.com/technology/tech/windows/odpnet/index.html) (ODP) SQL * Server - Already built in (naturally) * SQLite - [SQL.Data.Sqlite](http://sqlite.phxsoftware.com/) (just in case you want that available)
You do need to have an appropriate, database specific driver installed. Once this is installed the connection string will also be, to some degree, database dependent. Using ADO.NET much database interaction in code can be independent by using the common interfaces (e.g. [`IDbCommand`](http://msdn.microsoft.com/library/system.data.idbcommand)) rather than the provider specific subclasses, but a provider specific factory will still be needed. Even then, SQL dialects and datatypes have significant variation. Expect to need to be very familiar with building your own abstracts, inversion of control (IoC) and debugging each different database. The latter would strongly indicate debugging actively across multiple database platforms from the project start to avoid sudden need for significant porting effort.
OleDB vs ODBC: does one of them NOT require driver installation FOR ALL Oracle, MySQL, SQL Server?
[ "", "c#", ".net", "odbc", "oledb", "driver", "" ]
I have a function that receive a type and returns true or false. I need to find out what are all types in a certain namespace that that function will return true for them. Thanks.
Here's a function that gets all the classes in a namespace: ``` using System.Reflection; using System.Collections.Generic; /// <summary> /// Method to populate a list with all the class /// in the namespace provided by the user /// </summary> /// <param name="nameSpace">The namespace the user wants searched</param> /// <returns></returns> static List<string> GetAllClasses(string nameSpace) { //create an Assembly and use its GetExecutingAssembly Method //http://msdn2.microsoft.com/en-us/library/system.reflection.assembly.getexecutingassembly.aspx Assembly asm = Assembly.GetExecutingAssembly(); //create a list for the namespaces List<string> namespaceList = new List<string>(); //create a list that will hold all the classes //the suplied namespace is executing List<string> returnList = new List<string>(); //loop through all the "Types" in the Assembly using //the GetType method: //http://msdn2.microsoft.com/en-us/library/system.reflection.assembly.gettypes.aspx foreach (Type type in asm.GetTypes()) { if (type.Namespace == nameSpace) namespaceList.Add(type.Name); } foreach (String className in namespaceList) returnList.Add(className); return returnList; } ``` **[Update]** Here's a more compact way to do it, but this requires .Net 3.5 (from [here](https://stackoverflow.com/questions/343869/taking-out-all-classes-of-a-specific-namespace)): ``` public static IEnumerable<Type> GetTypesFromNamespace(Assembly assembly, String desiredNamepace) { return assembly.GetTypes() .Where(type => type.Namespace == desiredNamespace); } ```
`System.Reflection.Assembly.GetTypes()` : Gets all types defined in this assembly.\* Should do the job =)
Is there a way to go over all types in a namespace in a foreach loop?
[ "", "c#", "reflection", "" ]
I've got a fairly simple method which recursively removes begining/ending html tags ``` class Program { static void Main(string[] args) { string s = FixHtml("<div><p>this is a <strong>test</strong></p></div>"); Console.WriteLine(s); } private static string FixHtml(string s) { //Remove any outer <div> if (s.ToLower().StartsWith("<div>")) { FixHtml(s.Substring(5, s.Length - 5)); } else if (s.ToLower().StartsWith("<p>")) { FixHtml(s.Substring(3, s.Length - 3)); } else if (s.ToLower().EndsWith("</div>")) { FixHtml(s.Substring(0, s.Length - 6)); } else if (s.ToLower().EndsWith("</p>")) { FixHtml(s.Substring(0, s.Length - 4)); } return s; } } ``` The behaviour is that it can recursively remove the `<div> & <p>` tags, but on the "return s" statement it undo's all the work, by adding back add the tags! Anyone know why this happens? and how do i force it to return the value i want. i.e `this is a <strong>test</strong>`
In .NET, strings are immutable - so your method actually never changes the return value. When you call `s.ToLower().StartsWith("<div>")` you get back a *new string* with the expected differences. The *existing string s* is left unchanged. Also, you never consume the return value from your recursive calls. Off the top of my head, try something like this: ``` private static string FixHtml(string s) { if (s.ToLower().StartsWith("<div>")) { return FixHtml(s.Substring(5, s.Length - 5)); } else if (s.ToLower().StartsWith("<p>")) { return FixHtml(s.Substring(3, s.Length - 3)); } else if (s.ToLower().EndsWith("</div>")) { return FixHtml(s.Substring(0, s.Length - 6)); } else if (s.ToLower().EndsWith("</p>")) { return FixHtml(s.Substring(0, s.Length - 4)); } return s; } ```
Note that raw text manipulation is usually a poor way to treat xml - for example, you aren't handling attributes, namespaces, trailing tag whitespace `(<p >`) etc at the moment. Normally, I'd say load it into a DOM (`XmlDocument`/`XDocument` for xhtml; HTML Agaility Pack for html) - but actually I wonder whether an xslt would be good in this case... For example: ``` static void Main() { string xhtml = @"<div><p>this is a <strong>test</strong></p></div>"; XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load("strip.xslt"); StringWriter sw = new StringWriter(); using(XmlReader xr = XmlReader.Create(new StringReader(xhtml))) { xslt.Transform(xr, null, sw); } string newHtml = sw.ToString(); Console.WriteLine(newHtml); } ``` With strip.xslt: ``` <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="no" omit-xml-declaration="yes"/> <xsl:template match="strong|@*"> <xsl:copy><xsl:apply-templates select="*|text()"/></xsl:copy> </xsl:template> <xsl:template match="*"> <xsl:apply-templates select="*|text()"/> </xsl:template> </xsl:stylesheet> ```
Unexpected results with C# recursion method
[ "", "c#", "html", "string", "text", "recursion", "" ]
I've been wanting to work on this application for about a year now. I want to create a 'Laser Show Simulator/Editor'. I want to be able to place lights in different positions on a stage and I want to be able to script each one of them to do various operations such as turning, go on and off at certain intervals, change color, etc. Being realistic isn't entirely my intention. I have further plans of writing a tool that makes it easy to synchronize and compose a laser show based on an existing audio file (*which will usually be a song of course*) based on certain information that can be detected such as the beats per minute, etc., for example. I was originally thinking of working on this in C# with XNA. The editor will of course contain some 3D viewports (*Maybe in Ortho Projection*), kind of like a 3D Modeling tool I guess, but more like a level design tool for a game, since the amount of things one will be able to do with it will be limited such as light placement and property editing. The thing is that I have never worked on a 3D programming project before. A few years back, I tried to learn OpenGL (*Bought many books and honestly did read them, but back then I was new to programming and things just did not make sense. Also, I didn't understand much of the math that was used*). I also did try to learn Managed DirectX, and although it did seem to make more sense, I guess I wasn't as motivated to learn it so I gave up. Now I actually have a reason to learn it, so I will be motivated, and I am sure that I will understand most of the math now. But I don't know where to start. This is something that I'm sure will take me a while to complete, so I know to be patient. I would like to know where you guys suggest I begin. The audio part I am sure I will leave to later. I guess the basics are the rendering engine and the editing interface, then the actual simulator to play back the created show. Since I can't fit everything into one question, I will ask follow up questions later when I get to that area of the project. However, in the meantime the basic general questions I am asking are: 1. **Where should I begin?** I have never worked on something of this magnitude, so I am overwhelmed with the amount of things going into this project and I don't understand what I should begin on. I know I will plan things out first, but I would appreciate at least a hint as to what one would begin on. I assume it is the rendering engine. 2. **Is it a good idea, or at least OK to use C# and XNA?** I'm pretty familiar with C# and I did try to learn Managed DirectX a couple of years back which I believe is somewhat similar. And I'm familiar with the User Interface creation aspect of .Net with C#. 3. **Should I create my own rendering engine or use an existing one? Which do you recommend?** I'm not entirely interested in creating my own engine so that I can learn. I'm sure I will eventually understand what's going on anyways, and I really don't want the rendering aspect to be a roadblock, especially if there's something out there that already exists that will be better than anything I can create in the immediate future. Still, of course, I will try to learn XNA; I'm not going to try to ignore it. Thanks guys I really appreciate any input you can provide. Sorry if I was very vague. I have ideas for the specifics, but I wanted to ask the general questions for now, to give myself a sense of direction. Thanks again. **EDIT**: I want to emphasize that I have *never* worked on something of this magnitude from scratch. I literally don't know where to begin. I've never worked on 3D programming nor a complicated user interface which an editor would entail. I do have the drive and motivation to learn and do anything programming related, as I have proved to myself in the past, but I would appreciate any details and specifics you guys can provide as to where to begin. For example, some of you say begin with the rendering engine, but can you provide any specifics? Are there any free and/or open source engines out there that will suffice? Are there any 3D topics in particular that I should look into that might be of interest to me considering what I'm pursuing? For example, I've read that some lasers might just be 3D meshes with shaders, or something, I'm not well versed in 3D programming apparently. I'm not looking into buying anything such as the rendering engine, at least in the immediate future. If I do, it will be once I have a core/base down which I can work upon. Thanks guys, I really appreciate any insight you can provide, aside from what some of you have already done.
I'm interested in your project because I used to be a laser show designer and control software developer. First - sketch the design! It's interesting that you are thinking about implementation details like the rendering engine, while still overwhelmed by the scope of the project. Just imaging a rendering engine that will do anything you ask. Then when concepts firm up and you know the capabilities you need you can shop for one that fits your needs. If you are unfamiliar with the system behaviors and use cases that would be associated with laser displays, I can definitely help you - I'll email ya.
C# and XNA is a really good choice for a first 3D project. You won't have to write your own rendering engine, which is good news because it can be very time consuming. However it lacks GUI tools. There is no simple way (yet) to make menus, text boxes, labels, etc. However, there are some libraries out there than can help you. I recommend you to take a look at [Audio support](http://msdn.microsoft.com/en-us/library/bb195055.aspx) to make sure the tools provided (especially XACT) are enough for what you want to do.
Advice for Hobby Application: Laser Show Editor/Simulator
[ "", "c#", "xna", "simulation", "project-planning", "" ]
``` try { String comd ="E:/ior1.txt"; Runtime rt = Runtime.getRuntime(); rt.exec("C:/tes1.bat"+comd+""); System.out.println("Process exitValue: "); } catch (Exception e) { System.out.println("Unexpected exception Trying to Execute Job: " +e); } ``` But when I run I get an exception like this ``` Unexpected exception Trying to Execute Job: java.io.IOException: CreateProcess: C:/tes1.batE:/ior1.txt error=2 Press any key to continue . . . ``` This is the batch file content ``` echo "testing" echo %1 ```
Be aware, that there is a number of issues related to executing an external process from within your Java program if you have to use this in a production environment. You have e.g. to be aware of the fact, that if the output from the process is larger than the buffer used by the JVM<->OS the exec will block forever. I normally use a wrapper with Threads to read from the buffers. Its not perfect, but something like (see main() for details on usage): ``` /** * Executes a given OS dependent command in a given directory with a given environment. * The parameters are given at construction time and the initialized object is immutable. * After the object initialization and execution of the blocking exec() method the state * can't be changed. The result of the execution can be accessed through the get methods * for the exitValue, stdOut, and stdErr properties. Before the exec() method is completed * the excuted property is false and the result of other getters is undefined (null). */ public class CommandExecutor { /** * Specifies the number of times the termination of the process is * waited for if the OS gives interruptions */ public static final int NUMBER_OF_RUNS = 2; /** * Used for testing and as example of usage. */ public static void main(String[] args) { System.out.println("CommandExecutor.main Testing Begin"); String command_01 = "cmd.exe /C dir"; File dir_01 = new File("C:\\"); System.out.println("CommandExecutor.main Testing. Input: "); System.out.println("CommandExecutor.main Testing. command: " + command_01); System.out.println("CommandExecutor.main Testing. dir: " + dir_01); CommandExecutor ce_01 = new CommandExecutor(command_01, null, dir_01); ce_01.exec(); System.out.println("CommandExecutor.main Testing. Output:"); System.out.println(" exitValue: " + ce_01.getExitValue()); System.out.println(" stdout: " + ce_01.getStdout()); System.out.println(" stderr: " + ce_01.getStderr()); String command_02 = "cmd.exe /C dirs"; File dir_02 = new File("C:\\"); System.out.println("CommandExecutor.main Testing. Input: "); System.out.println("CommandExecutor.main Testing. command: " + command_02); System.out.println("CommandExecutor.main Testing. dir: " + dir_02); CommandExecutor ce_02 = new CommandExecutor(command_02, null, dir_02); ce_02.exec(); System.out.println("CommandExecutor.main Testing. Output:"); System.out.println(" exitValue: " + ce_02.getExitValue()); System.out.println(" stdout: " + ce_02.getStdout()); System.out.println(" stderr: " + ce_02.getStderr()); System.out.println("CommandExecutor.main Testing End"); } /* * The command to execute */ protected String command; /* * The environment to execute the command with */ protected String[] env; /* * The directory to execute the command in */ protected File dir; /* * Flag set when the command has been executed */ protected boolean executed = false; /* * Exit value from the OS */ protected int exitValue; /* * Handle to the spawned OS process */ protected Process process; /* * Std error */ protected List<String> stderr; /* * Worker Thread to empty the stderr buffer */ protected Thread stderrReader; /* * Std output */ protected List<String> stdout; /* * Worker Thread to empty the stdout buffer */ protected Thread stdoutReader; /** * Creates a new instance of the CommandExecutor initialized to execute the * specified command in a separate process with the specified environment * and working directory. * * @param env */ public CommandExecutor(String command, String[] env, File dir) { this.command = command; this.env = env; this.dir = dir; } /** * Creates a reader thread for the stderr */ protected void connectStderrReader() { stderr = new ArrayList<String>(); final InputStream stream = process.getErrorStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); stderrReader = new Thread(new Runnable() { public void run() { String nextLine = null; try { while ((nextLine = reader.readLine()) != null) { stderr.add(nextLine); } } catch (IOException e) { System.out.println( "CommandExecutor.connectStderrReader() error in reader thread"); e.printStackTrace(System.out); } } }); stderrReader.start(); } /** * Creates a reader thread for the stdout */ protected void connectStdoutReader() { stdout = new ArrayList<String>(); final InputStream stream = process.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); stdoutReader = new Thread(new Runnable() { public void run() { String nextLine = null; try { while ((nextLine = reader.readLine()) != null) { stdout.add(nextLine); } } catch (IOException e) { System.out.println( "CommandExecutor.connectStdoutReader() error in reader thread"); e.printStackTrace(System.out); } } }); stdoutReader.start(); } /** * Creates the process for the command */ protected void createProcess() { try { process = Runtime.getRuntime().exec(command, env, dir); } catch (IOException e) { System.out.println("CommandExecutor.exec() error in process creation. Exception: " + e); e.printStackTrace(System.out); } } /** * Executes command in a separate process in the specified directory. Method will block until * the process has terminated. Command will only be executed once. */ public synchronized void exec() { // Future enhancement: check for interrupts to make the blocking nature interruptible. if (!executed) { createProcess(); connectStdoutReader(); connectStderrReader(); waitForProcess(); joinThreads(); exitValue = process.exitValue(); executed = true; } } /** * @return the command */ public String getCommand() { return command; } /** * @return the dir */ public File getDir() { return dir; } /** * @return the env */ public String[] getEnv() { return env; } /** * @return the exitValue */ public int getExitValue() { return exitValue; } /** * @return the stderr */ public List<String> getStderr() { return stderr; } /** * @return the stdout */ public List<String> getStdout() { return stdout; } /** * @return the executed */ public boolean isExecuted() { return executed; } /** * Joins on the 2 Reader Thread to empty the buffers */ protected void joinThreads() { try { stderrReader.join(); stdoutReader.join(); } catch (InterruptedException e) { System.out.println("CommandExecutor.joinThreads() error. Exception: "); e.printStackTrace(System.out); } } /** * Creates a String representing the state of the object */ @Override public synchronized String toString() { StringBuilder result = new StringBuilder(); result.append("CommandExecutor:"); result.append(" command: " + command); result.append(" env: " + Arrays.deepToString(env)); result.append(" dir: " + dir); result.append(" executed: " + executed); result.append(" exitValue: " + exitValue); result.append(" stdout: " + stdout); result.append(" stderr: " + stderr); return result.toString(); } /** * Waits for the process to terminate */ protected void waitForProcess() { int numberOfRuns = 0; boolean terminated = false; while ((!terminated) && (numberOfRuns < NUMBER_OF_RUNS)) { try { process.waitFor(); terminated = true; } catch (InterruptedException e) { System.out.println("CommandExecutor.waitForProcess() error"); e.printStackTrace(System.out); numberOfRuns++; } } } } ```
There's a blank missing after .bat (in the rt.exec line) --- ### Edit: You could also try executing: ``` rt.exec("cmd /c c:/tes1.bat "+comd); ```
Java to batch file
[ "", "java", "batch-file", "" ]
I'd like to write a program able to "use" other programs by taking control of the mouse/keyboard and being able to "see" what's on the screen. I used [AutoIt](http://www.autoitscript.com/autoit3/) to do something similar, but I had to cheat sometimes because the language is not that powerful, or maybe it's just that I suck and I'm not able to do that much with it :P So... I need to: * Take screenshots, then I will compare them to make the program "understand", but it needs to "see" * Use the mouse: move, click and release, it's simple, isn't it? * Using the keyboard: pressing some keys, or key combinations, including special keys like `Alt`,`Ctrl` etc... How can I do that in python? Does it works in both linux and windows? (this could be really really cool, but it is not necessary)
I've had some luck with similar tasks using [PyWinAuto](http://pywinauto.openqa.org/). > pywinauto is a set of python modules > to automate the Microsoft Windows GUI. > At it's simplest it allows you to send > mouse and keyboard actions to windows > dialogs and controls. It also has some support for capturing images of dialogs and such using the Python Imaging Library [PIL](http://www.pythonware.com/products/pil/).
AutoIt is completely capable of doing everything you mentioned. When I'm wanting to do some automation but use the features of Python, I find it easiest to use [AutoItX](http://www.google.com/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fwww.autoitscript.com%2Fautoit3%2Fdownloads.shtml&ei=Yk9TSsOsDYnWNfza6fQI&usg=AFQjCNEBCnVe6pRuxIzX_UE4U_3O8SVYOg&sig2=t4kpjNbgspeikHz2SBkIGg) which is a DLL/COM control. Taken from [this answer](https://stackoverflow.com/questions/151846/get-other-running-processes-window-sizes-in-python/155587#155587) of mine: ``` import win32com.client oAutoItX = win32com.client.Dispatch( "AutoItX3.Control" ) oAutoItX.Opt("WinTitleMatchMode", 2) #Match text anywhere in a window title width = oAutoItX.WinGetClientSizeWidth("Firefox") height = oAutoItX.WinGetClientSizeHeight("Firefox") print width, height ```
Make your program USE a gui
[ "", "python", "user-interface", "remote-control", "" ]
I have my `persistence.xml` with the same name using `TopLink` under the `META-INF` directory. Then, I have my code calling it with: ``` EntityManagerFactory emfdb = Persistence.createEntityManagerFactory("agisdb"); ``` Yet, I got the following error message: ``` 2009-07-21 09:22:41,018 [main] ERROR - No Persistence provider for EntityManager named agisdb javax.persistence.PersistenceException: No Persistence provider for EntityManager named agisdb at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:89) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:60) ``` Here is the `persistence.xml`: ``` <?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0"> <persistence-unit name="agisdb"> <class>com.agis.livedb.domain.AddressEntity</class> <class>com.agis.livedb.domain.TrafficCameraEntity</class> <class>com.agis.livedb.domain.TrafficPhotoEntity</class> <class>com.agis.livedb.domain.TrafficReportEntity</class> <properties> <property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/agisdb"/> <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="toplink.jdbc.user" value="root"/> <property name="toplink.jdbc.password" value="password"/> </properties> </persistence-unit> </persistence> ``` It should have been in the classpath. Yet, I got the above error.
After `<persistence-unit name="agisdb">`, define the persistence provider name: ``` <provider>org.hibernate.ejb.HibernatePersistence</provider> ```
Put the `"hibernate-entitymanager.jar"` in the classpath of application. For newer versions, you should use `"hibernate-core.jar"` instead of the deprecated `hibernate-entitymanager` If you are running through some IDE, like **Eclipse**: `Project Properties -> Java Build Path -> Libraries.` Otherwise put it in the `/lib` of your application.
No Persistence provider for EntityManager named
[ "", "java", "jpa", "persistence", "toplink", "" ]
What mechanism do you prefer for building a GUI: from scratch or using GUI-building software?
I actually enjoy building GUIs with the NetBeans GUI Builder; the thing is, it is fairly customizable - it allows you to change the code used for auto-generation and the auto-generated code [no pun intended] (which is necessary for custom components), it also allows "easy" event-handling and binding. And NetBeans GUI Builder is not restricted to GroupLayout but rather allows you to choose which LayoutManager to use (a somewhat hidden setting in the form's properties dialog). But it is not always the best choice; as others already said: MiG Layout is a good choice when you need to have full control of your application, knowing every single JLabel, every JButton etc. I must confess I prefer Netbeans' GUI builder for the ease of use and WYSIWYG view. But I also think that it does not even matter if you have created the GUI-Code by hand or with a GUI-Designer; adding Controls / custom Components dynamically works with both, doing this and that works with both etc.. The only thing that matters is that it works. (From my point of view I do not see a point in coding a GUI manually if it can be done faster with a GUI-Builder, as I do not see why one should bother coding it by hand without some kind of benefit)
If the question is about GUI development using Swing then IMO it is best to code everything manually without a WYSIWIG tool. In order for a manual UI design/coding to be efficient a really good layout manager should be used. MigLayout is one of such layout managers. Since I've started using it I have never looked back at WYSIWIG tools -- a sheet of paper, a pencil, MigLayout and you get a full control over your design and code. Also tools like [Balsamiq](http://www.balsamiq.com/) simplify making GUI mock ups for quick prototyping if the paper and pencil approach is not suitable.
Building a GUI in Java
[ "", "java", "user-interface", "" ]
Is there a quick way to say ``` Where (data.x == (If notempty x = y else x = default)) ``` Assuming the data being compared is both strings ``` Compare listitem.string with passed.string - if passed.string isnotempty, else passed.string equals default value. ``` in a Linq 'where` query. Apologies that the question was really badly written. ... As per the comments updated ...
Ok, with your clarifications to the original post, I think I see what you're getting at now. Try the following clause (where `data.x` is your current element and `y` in the passed argument). ``` where y == (string.IsNullOrEmpty(y) ? "default" : data.x) ``` I do not believe it's possible to use the null coalescing operator here, since the variables you are comparing and returning are different. **Old Post:** If what is empty? I'm guessing you're referring to `y`. For a generic type `T`, you could use the following clause: ``` where data.x == (y ?? DefaultValue<T>()) ``` where `DefaultValue` is a generic function of `T` that returns a so-called "default" value.
It really depends on the data type of x and y, but say they are strings: ``` Where (data.x == (!string.IsNullOrEmpty(y) ? y : "default")) ``` It's called the [conditional operator](http://msdn.microsoft.com/en-us/library/ty67wk28(VS.80).aspx).
Is there a quick way to say If notempty x = y else x = default in a Linq where query
[ "", "c#", "linq", ".net-3.5", "" ]
I'm currently creating blog system, which I hope to turn into a full CMS in the future. There are two classes/objects that would be useful to have global access to (the mysqli database connection and a custom class which checks whether a user is logged in). I am looking for a way to do this without using global objects, and if possible, not passing the objects to each function every time they are called.
You could make the objects Static, then you have access to them anywhere. Example: ``` myClass::myFunction(); ``` That will work anywhere in the script. You might want to read up on static classes however, and possibly using a Singleton class to create a regular class inside of a static object that can be used anywhere. **Expanded** I think what you are trying to do is very similar to what I do with my DB class. ``` class myClass { static $class = false; static function get_connection() { if(self::$class == false) { self::$class = new myClass; } return self::$class; } // Then create regular class functions. } ``` What happens is after you get the connection, using $object = myClass::get\_connection(), you will be able to do anything function regularly. ``` $object = myClass::get_connection(); $object->runClass(); ``` **Expanded** Once you do that static declarations, you just have to call get\_connection and assign the return value to a variable. Then the rest of the functions can have the same behavior as a class you called with $class = new myClass (because that is what we did). All you are doing is storing the class variable inside a static class. ``` class myClass { static $class = false; static function get_connection() { if(self::$class == false) { self::$class = new myClass; } return self::$class; } // Then create regular class functions. public function is_logged_in() { // This will work $this->test = "Hi"; echo $this->test; } } $object = myClass::get_connection(); $object->is_logged_in(); ```
You could pass the currently global objects into the constructor. ``` <?php class Foo { protected $m_db; function __construct($a_db) { $this->m_db = $a_db; } } ?> ```
How to avoid using PHP global objects?
[ "", "php", "global", "" ]
My Java application runs another Java application, by running the process "java -jar j.jar". J.jar is known to use a LOT of memory depending on the dataset it is given, and often gets an OutOfMemoryError heap. So I want to use -Xmx on it, so that I can allocate as much memory as possible (or close to). I was thinking of getting the total memory on the system, then specifying 80-90% of that in -Xmx. Is there any solution to my problem? And, how does my solution sound? Edit: I cant reduce the memory consumption as the memory being used is by Java's built-in pack200 compression, which I am using to pack some JAR files.
Depending on your OS, this might work for getting the free and available memory size: ``` java.lang.management.OperatingSystemMXBean mxbean = java.lang.management.ManagementFactory.getOperatingSystemMXBean(); com.sun.management.OperatingSystemMXBean sunmxbean = (com.sun.management.OperatingSystemMXBean) mxbean; long freeMemory = sunmxbean.getFreePhysicalMemorySize(); long availableMemory = sunmxbean.getTotalPhysicalMemorySize(); ``` From there, you can figure out 80-90% and launch your jar with the max memory size you want. I don't know that this works with all OS's (i.e. Windows), but it worked when I tested it with both OSX and Linux.
The limit for -XmX is -Xmx1500m on 32 bit windows. Shared libraries get in the way of a bigger heap. You'll need about 2Gb of RAM to do this. On non-windows OSes you can go bigger, and 64Bit JVM's are capable of a LOT more. Windows XP will not let you have more than 3Gb of RAM ( doesn't care if you have 4Gb physical, ever since XP SP3) Vista may be different YMMV. I've tried -Xmx4000M on a 64 bit JVM on 64 bit Linux and it was fine. considering I had 6Gb of physical ram, it was not a big request. Your 80% idea is interesting, but my test systems run higher percentages than that without ill effect. (As long as you don't try doing anything else.) And the other commenter is right, paging out your JVM's in-memory image is not quick. Later JVM's are better at doing this less messily ( but they have better garbage collectors too) If you can't reduce your memory consumption – and I know how hard that is – then have lots of physical ram and allocate most of it.
Java -Xmx, Max memory on system
[ "", "java", "memory-management", "" ]
I'm developing an application that is reading and writing a lot (but synchronously, though) to a certain file on disk. However, how larger the file gets, the more often I get the following IOException: > The requested operation cannot be > performed on a file with a user-mapped > section open. occuring from: ``` at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) at System.IO.StreamWriter.CreateFile(String path, Boolean append) at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize) at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding) at System.IO.File.WriteAllText(String path, String contents, Encoding encoding) at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at TestApp.Program.Main() ``` As you can see, the exception is thrown from within `File.WriteAllText`. I suspected the exception had to do with simultaneous reading and writing, so tried to limit access to the file. Both a `lock` and a `Mutex` seemed to increase the number of exceptions instead of preventing them. So what's exactly going on? What does this exception exactly mean and how can it be prevented?
I was writing to a file (open,loop(writes),close) but after a mistake a duplicated the call to the rutine... so I end up with "The requested operation cannot be performed on a file with a user-mapped section open."! Well, I deleted the second call and then the problem solved. It seems that two (open/close) (open/close) rutines over the same file happening too soon one after another causes this... Some developers suggest to call the gc. Check for closing correctly every i/o operation. Not to perform complete (open,loop(writes),close) too soon. It seems that when one operation it is going to be finished while the second request arrives and that throws the problem.
The first solution will be to turn off your antivirus. Better still you can add the folder to the scan exception list of your antivirus.
What's wrong when 'the requested operation cannot be performed on a file with a user-mapped section open?'
[ "", "c#", "exception", "file-io", "" ]
I'm implementing various PHP & ASP.NET web apps for a client. I'd like to install a very low overhead user tracking system. (It has to be on the intranet, this is an internal system only). I'd like to do something like the following: ``` line 1 normal code line 2 normal code line 3 Send Request/Query/Info to http://internal-IP/userTracker.php?Name=UserName&Page=... line 4 Code that proceeds immediately after line 3 without waiting for a reply of any sort. ``` "Fire and Forget" seems to be the best analogy here. Any tips? Thanks!
That's pretty much a textbook case for AJAX. Essentially, you fire off a rqeuest to that URL, and code execution continues as normal. Here's an example in jQuery (assuming you want to post to the URL). Other libraries may vary. As will doing so without any js lirbaries. ``` //some code $.get("http://internal-IP/userTracker.php?Name=UserName", function() { //put something here if you want to verify the request worked. }); //some more code ``` The browser will fire off the request, and "some more code" will continue executing without blocking on the request.
theory one: don't even bother doing the request with server code if you can avoid it. typically, people use invisible "tracking images" where it's just an <img> tag with src="http://internal-IP/userTracker.php?Name=UserName&Page=...". this avoids security headaches trying to get your webserver communicating with the tracking server directly. it's also better than ajax because it works across any combination of domains. the problem with either tracking images or ajax is if you don't want your users hitting the tracking server directly and would rather just ping server-to-server... theory two: avoid AJAX and IMGs and just go server-to-server like you originally suggest. this is probably the better suggestion. are you writing this in .NET and having it fire off to a PHP page? if so, the .NET code above will work great. even though you don't care about the response, i'd still wrap the hell out of it with exception handling. that's all i've got. :) good luck!
I'd like to send a "Fire and Forget" query to a PHP page
[ "", "php", "asp.net", "html", "http", "" ]
I'm trying to update a column in a database, but the column needs to be specified at runtime. For example, given the table: | PKEY | ColumnA | ColumnB | ColumnC | I want to write an stored procedure that will update a given column per PKEY. Such as: updateColumn(pkey, columnName, Value); This could easily be done using java/JDBC etc, but this needs to be a stored procedure. also, its an Oracle database
Converting dave's proc to Oracle PL/SQL with minimal changes: ``` create procedure updateColumn (pkey int, columnName varchar2, value int) as begin execute immediate 'update YOUR_TABLE set ' || columnName || ' = ' || TO_CHAR(value) || ' where KEY = ' || TO_CHAR(pkey); end; ``` I would add a check to ensure that columnName is one of the columns in the table, to reduce the risk of SQL injection.
You should look into dynamic SQL. A good place to start is [Execute Immediate](http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28370/executeimmediate_statement.htm) and [the Oralce Application Developer's Guide](http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96590/adg09dyn.htm)
Update DB column that is specified at runtime
[ "", "sql", "oracle", "stored-procedures", "" ]
I want to toggle a button's visibility in when value of a particular variable changes. Is there a way to attach some kind of delegate to a variable which executes automatically when value changes?
No, you can't do things like overloading assignment operator in C#. The best you could do is to change the variable to a property and call a method or delegate or raise an event in its setter. ``` private string field; public string Field { get { return field; } set { if (field != value) { field = value; Notify(); } } } ``` This is done by many frameworks (like WPF `DependencyProperty` system) to track property changes.
Use **[Observer pattern](http://www.google.co.in/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FObserver_pattern&ei=c_9eStClEciJkQW-z7WoCg&usg=AFQjCNGRWwxlv75N0vj4Ifwc0q4NnXIbrg&sig2=JB4iBKiMPOQLLDhqdAtlDw)**. Here's [another reference](http://www.dofactory.com/Patterns/PatternObserver.aspx).
How can I execute code when value of a variable changes in C#?
[ "", "c#", "delegates", "variables", "" ]
I have a class like this: ``` public class SomeClass { private const string sessionKey = "__Privileges"; public Dictionary<int, Privilege> Privileges { get { if (Session[sessionKey] == null) { Session[sessionKey] = new Dictionary<int, Privilege>(); } return (Dictionary<int, Privilege>)Session[sessionKey]; } } } ``` Now, if Ido this... ``` var someClass = new SomeClass(); var p = someClass.Privileges[13]; ``` ... and there is no key 13, I will get an error like this: `The given key was not present in the dictionary.` I would like to have a property that can be accessed in the same way as above, but will return a default object in case of the absence of the key. I tried creating an indexer property like this... ``` public Privilege Privileges[int key] { get { try { return _privileges[key]; } catch { return new Privilege(); } } } ``` ... but it looks like that's not a C# 2008 language feature. How can I access the property in the same way, but get the default object if the key isn't present?
You'll have to define your own IDictionary-based class with an indexer that has the desired behavior, and return an instance of that, rather than the stock Dictionary class, in your property getter.
C# does not supported named indexers, as you have discovered. Have you considered using a regular method instead of an indexer property? Not every programming problem requires the use fancy syntax to solve. Yes, you could create your own IDictionary implementation with an aggregated dictionary and change the property access behavior - but is that really necessary for something that just fetches a value or returns a default? I would add a method like this to your class: ``` protected Privilege GetPrivilege(int key) { try { return _privileges[key]; } catch { return new Privilege(); } } ``` or better yet, avoid exception handling as a flow control mechanism: ``` protected Privilege GetPrivilge( int key ) { Privilege priv; if( _privileges.TryGetValue( key, out priv ) ) return priv; else return new Privilege(); } ```
C# Indexer Property Question
[ "", "c#", ".net", "dictionary", "properties", "indexer", "" ]
I'd like the destructor of my class to delete the entire object except for one of the members, which is deleted elsewhere. First of all, is this totally unreasonable? Assuming it's not, how do I do this? I thought that created an destructor with an empty body would prevent all the members from being deleted (because the destructor wouldn't do anything), but that doesn't seem to be the case.
**Short answer**: You don't. **Longer answer**: If the "member" is actually a pointer to some other allocation, you can arrange to not delete the other allocation. But usually, if you allocated the other block in the constructor, you want to delete it in the destructor. Anything else will require careful handling of the "ownership" of the block in question. It will be a lot like memory management in plain c. Possible, but fraught with danger. Good luck.
Depends on what you mean by "deleted". If they aren't in a smart pointer, and aren't explicitly deleted, then they aren't deleted. Members that are just part of the class: ``` class Bar { //... private: Foo foo; }; ``` Aren't deleted by the destructor (because they weren't dynamically allocated), they are just destroyed. They "live" inside the class, so once it is destroyed, it's gone. If you are looking the share "ownership" between two locations, what you want is a dynamically allocated shared\_ptr: ``` #include <memory> class Bar { // ... private: std::tr1::shared_ptr<Foo> foo; }; ```
How do I *not* delete a member in a destructor?
[ "", "c++", "destructor", "ownership-semantics", "" ]
*The question is not the same as [What’s the best way to generate a UML diagram from Python source code?](https://stackoverflow.com/questions/260165/whats-the-best-way-to-generate-a-uml-diagram-from-python-source-code), but the other way around.* [Topcoder UML tool](http://www.topcoder.com/tc?module=Static&d1=dev&d2=umltool&d3=description) automatically generates code in only Java or C#. Since I need to create [a very depended data structure](https://stackoverflow.com/questions/1185589/three-dimensional-data-structure-a-problem-in-a-db) at a point, I am hesitant to turn to Java. I want to use Python. So: 1. Is there an UML-like tool that automatically generates Python code from your diagram? 2. If there is, is it possible to generate it from the Topcoder UML tool? 3. Can you shortly compare the tools?
[Enterprise Architect](http://www.sparxsystems.com.au/products/ea/index.html) is able to generate python code code from UML diagrams. It is also able to also perform some reverse engineering, and therefore maintain the two versions (UML and python) synchronized together. However, I have never used it in that way, except for some small tests just to see it in action. I personally find productivity in Python so high, that even if I am really satisfied with EA, I prefer it just to document the design.
* [PyUML](http://sourceforge.net/projects/eclipse-pyuml/) - a Python Roundtrip Tool for Eclipse * [PyIdea](http://sourceforge.net/projects/pyidea/): PyNSource UML & Patterns IDE for Python
Automatically Generated Python Code from an UML diagram?
[ "", "python", "uml", "" ]
Is it possible to detect/reuse those settings ? How ? The exception i'm getting is This is the exception while connecting to <http://www.google.com> ``` System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 66.102.1.99:80 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) --- End of inner exception stack trace --- at System.Net.HttpWebRequest.GetResponse() at mvcTest.MvcApplication.Application_Start() in C:\\home\\test\\Application1\\Application1\\Program.cs:line 33" ```
HttpWebRequest will actually use the IE proxy settings by default. If you *don't* want to use them, you have to specifically override the .Proxy proprty to either null (no proxy), or the proxy settings of you choice. ``` HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://news.bbc.co.uk"); //request.Proxy = null; // uncomment this to bypass the default (IE) proxy settings HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Console.WriteLine("Done - press return"); Console.ReadLine(); ```
I was getting a very similar situation where the HttpWebRequest wasn't picking up the correct proxy details by default and setting the UseDefaultCredentials didn't work either. Forcing the settings in code however worked a treat: ``` IWebProxy proxy = myWebRequest.Proxy; if (proxy != null) { string proxyuri = proxy.GetProxy(myWebRequest.RequestUri).ToString(); myWebRequest.UseDefaultCredentials = true; myWebRequest.Proxy = new WebProxy(proxyuri, false); myWebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials; } ``` and because this uses the default credentials it should not ask the user for their details. Note that this is a duplicate of my answer posted here for a very similar problem: [Proxy Basic Authentication in C#: HTTP 407 error](https://stackoverflow.com/questions/9603093/407-proxy-authentication-required-in-c-sharp/18013423#18013423)
How to AutoDetect/Use IE proxy settings in .net HttpWebRequest
[ "", "c#", "proxy", "httpwebrequest", "detect", "" ]
We have three databases that are physically separated by region, one in LA, SF and NY. All the databases share the same schema but contain data specific to their region. We're looking to merge these databases into one and mirror it. We need to preserve the data for each region but merge them into one db. This presents quite a few issues for us, for example we will certainly have duplicate Primary Keys, and Foreign Keys will be potentially invalid. I'm hoping to find someone who has had experience with a task like this who could provide some tips, strategies and words of experience on how we can accomplish the merge. For example, one idea was to create composite keys and then change our code and sprocs to find the data via the composite key (region/original pk). But this requires us to change all of our code and sprocs. Another idea was to just import the data and let it generate new PK's and then update all the FK references to the new PK. This way we potentially don't have to change any code. Any experience is welcome!
I have no first-hand experience with this, but it seems to me like you ought to be able to uniquely map PK -> New PK for each server. For instance, generate new PKs such that data from LA server has PK % 3 == 2, SF has PK % 3 == 1, and NY has PK % 3 == 0. And since, as I understood your question anyway, each server only stores FK relationships to its own data, you can update the FKs in identical fashion. ``` NewLA = OldLA*3-1 NewSF = OldLA*3-2 NewNY = OldLA*3 ``` You can then merge those and have no duplicate PKs. This is essentially, as you already said, just generating new PKs, but structuring it this way allows you to trivially update your FKs (assuming, as I did, that the data on each server is isolated). Good luck.
**BEST:** add a column for RegionCode, and include it on your PKs, but you don't want to do all the leg work. **HACK:** if your IDs are INTs, a quick fix would be to add a fixed value based on region to each key on import. INTs can be as large as: 2,147,483,647 local server data: ``` LA IDs: 1,2,3,4,5,6 SF IDs: 1,2,3,4,5 NY IDs: 1,2,3,4,5,6,7,9 ``` add 100000000 to LA's IDs add 200000000 to SF's IDs add 300000000 to NY's IDs combined server data: ``` LA IDs: 100000001,100000002,100000003,100000004,100000005,100000006 SF IDs: 200000001,200000002,200000003,200000004,200000005 NY IDs: 300000001,300000002,300000003,300000004,300000005,300000006,300000007,300000009 ```
Merging databases how to handle duplicate PK's
[ "", "sql", "database", "merge", "" ]
Is it possible to uncompress (if that's the right term even) for code like below? ``` var vote=function(){var k={informModerator:-1,undoMod:0,acceptedByOwner:1,upMod:2,downMod:3,offensive:4,favorite:5,close:6,reopen:7,deletion:10,undeletion:11,spam:12};var f=imagePath+"vote-arrow-down.png";var c=imagePath+"vote-arrow-down-on.png";var x=imagePath+"vote-arrow-up.png";var w=imagePath+"vote-arrow-up-on.png";var A=imagePath+"vote-favorite-on.png";var o=imagePath+"vote-favorite-off.png";var l=function(){var C='<a href="/users/login?returnurl='+escape(document.location)+'">login or register</a>';$("div.vote").find("img").not(".vote-accepted").unbind("click").click(function(D){u($(D.target),"Please "+C+" to use voting.")});z().unbind("click").click(function(D){u($(D.target),"Please "+C+" to flag this post.")})};var B=function(C){if(!C){C="div.vote"}$(C).find("img.vote- ``` I did search stackoverflow for this question and found no results
Yes. Copy / paste here: <http://jsbeautifier.org/> That will only **reformat** the layout. You cannot restore variable/function names. **Related on MetaSO**: [Can we get an un-obfuscated version of the vote object?](https://meta.stackexchange.com/questions/9094/can-we-get-an-un-obfuscated-version-of-the-vote-object)
I think something like Eclipse can auto-format it for you. Won't be able to get back any of the original variable names though.
Can compressed javascript be uncompressed
[ "", "javascript", "compression", "" ]
Today I found out about an interface I'd never heard of before: `IGrouping` ``` IEnumerable<IGrouping<YourCategory, YourDataItem>> ``` I am fortunate to have access to some of the best programming books available, but seldom do I come across these kinds of gems in those books. Blogs and podcasts work, but that approach is somewhat scattershot. Is there a better way to learn these things, or do I need to sift through the entire MSDN library to discover them?
[Eric Lippert's blog](http://blogs.msdn.com/ericlippert/). The real guts of C# - why there are some limitations which might seem arbitrary at first sight, how design decisions are made, etc. Alternatively, for more variety, look at the [Visual C# Developer Center](http://msdn.microsoft.com/en-us/vcsharp/default.aspx) - there's a whole range of blogs and articles there. Oh, and read the C# spec. No, I mean it - some bits can be hard to wade through (I'm looking at you, generic type inference!) but there's some very interesting stuff in there.
The best place to start is Jon Skeet's C# Coding blog: <http://msmvps.com/blogs/jon_skeet/> He regularly covers stuff you won't see anywhere else.
Learning about Hidden Features
[ "", "c#", ".net", "" ]
*background:* I've searched around for a reference, or possibly a tool, that helps you theoretically evaluate the efficiency (resource cost) of your JavaScript. This search has turned up a lot of excellent debugging software, but I can't really find something that helps me optimize the code, by utilizing less resource-intensive methods. *question:* **Is there any resource (online guide, list, database, book, anything) or perhaps some software (web-based, browser plugin, IDE extension) that will help you optimize your JavaScript?** *example:* `innerText` in IE / `textContent` in Firefox requires far fewer resources than `innerHTML` in either browser. That one is kinda common sense, because it's less powerful, but there are other comparisons I hear about on a daily basis, and can't really verify if they are in fact better for optimized code or more efficient, and even if I could I have no way to test it! Any ideas?
the usual way to evaluate Javascript is by evaluating the amount of time it takes for a set of code to execute: ``` var begin = new Date().getTime(); //do stuff console.debug( new Date().getTime() - begin ); ``` However, there are some issues with this in IE. if a script takes <15ms to run, IE returns 0ms as the result. Various javascript libraries have testing frameworks to help evaluate your code's speed. Dojo's testing framework is called DOH. John Resig also made a firebug plugin called FireUnit which allows you to easily evaluate the time it takes for a function to execute, and with a little configuring, also outputs the Big O of a function, which is a great piece of data. Check out Resig's video from JSConf on JS performance testing: [Measuring Javascript Performance - John Resig](http://vimeo.com/5284172) [FireUnit rundown](http://ejohn.org/blog/fireunit/)
In the same line as strife25, firebug has a very handy method of measuring time without handling any dates. Just use this: ``` console.time("Your timer name"); //Execute some javascript console.timeEnd("Your timer name"); ``` Then, check the console. [alt text http://aquate.us/u/62232567893647972047.jpg](http://aquate.us/u/62232567893647972047.jpg) Edit -- off by 30 odd seconds. :(
JavaScript Performance Evaluation
[ "", "javascript", "" ]
I need to complete the plan of a [ask-a-question site for my uni.](http://translate.google.com/translate?hl=en&sl=fi&tl=en&u=http%3A%2F%2Fwww.cs.helsinki.fi%2Fu%2Flaine%2Finfoht%2Faiheet%2Fis97je1.html) in a few days. I need to have the first version of the code ready for the next Tuesday, while the end of the project is in about three weeks. **Questions about the project which do not fit here** * [to make efficient tables](https://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data) * [to improve a relation figure](https://stackoverflow.com/questions/1182798/to-improve-a-relation-figure-for-a-database) * [to improve a ERD diagram](https://stackoverflow.com/questions/1182910/to-improve-a-sequence-diagram) * [to SHA1-hash you password in a MySQL database by Python](https://stackoverflow.com/questions/1183161/to-sha1-hash-a-password-in-mysql-database-by-python) * [to have a revision history for the questions](https://stackoverflow.com/questions/1182674/users-text-in-my-database-as-a-separate-table-or-within-other-data) * [to get the right way in designing databases](https://stackoverflow.com/questions/1184634/which-is-the-right-way-of-designing-a-database) * [to get primary and foreign keys right in ERD](https://stackoverflow.com/questions/1184857/to-get-primary-and-foreign-keys-right-in-erd) * [to understand login -variable in cookies/URL](https://stackoverflow.com/questions/1184888/to-understand-a-line-about-a-login-variable-in-a-session) * [to get info about my Uni's servers](https://stackoverflow.com/questions/1187473/to-know-whether-my-uni-can-run-python-web-applications) * [to improve SQL -queries](https://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-postgresql) * [to write SQL queries in DDL correctly](https://stackoverflow.com/questions/1196034/is-there-any-iso-standard-of-how-to-write-sql-queries-in-ddl) * [to prevent to use of duplicate tags in a question](https://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database) * [to improve SQL queries in DDL](https://stackoverflow.com/questions/1195816/to-improve-sql-queries-in-ddl) * [to have no duplicate tags in a table](https://stackoverflow.com/questions/1196873/to-prevent-the-use-of-duplicate-tags-in-a-database) * [to separate answers in a databse](https://stackoverflow.com/questions/1197031/to-separate-answers-in-a-database) --- My [uni. offers little support](http://translate.google.com/translate?prev=hp&hl=en&js=y&u=http%3A%2F%2Fcs.helsinki.fi%2Fu%2Flaine%2Ftikas%2Fmaterial%2Fohjeita.html&sl=fi&tl=en&history_state0=) for tools which I selected: **Tools in building the backend** * **Python** in building the database schema??? *(I am not sure which components I can build by Python)* * **MySQL** to store data * I am not sure **which tool to use in building login and logout -system**. *They do not allow me to use Google's system. This forces me to use some simple open-source code, since it would take more than a week to build a descent login/logout -system.* **Tools in building the frontend** * Django *(if we can use MySQL in Django)* **Tools for Planning** * **Google Docs' Spreadsheet** for illustrating the usecases * **TopCoder UML Tool** to show primary keys and other relations in the database **Tools for coding** * Vim, Screen, Zsh, OS X's Visor: my [dot-files](http://github.com/masi/Sam/tree/master) * [EasyEclipse for Python](http://www.easyeclipse.org/site/distributions/python.html) *(only if I get a difficult error message)* **My focus in the project:** I aim to build a database system only for users and moderators such that I only provide the following features 1. to allow user to add to a database such that I neutralize the input *(I know that there is some tool for that, but I am not sure about its name.)* 2. to arrange questions by time 3. to arrange questions by name 4. to arrange questions by their subject 5. to allow users to remove their questions 6. to send an email to user that the question was successfully asked **Things about which I am uncertain** 1. *how to integrate the login -system to the database* such that the user sees only his data that is his username when he logins successfully, similarly as in Joomla 2. **Which components should I not build by Python** when I use MySQL for databases? 3. My uni. does not give me hardware support for the project. This suggests me that I will be better of in using a host which is specialized in my project. I used Djangohosting.ch the last month, and by their toos, I got started. **Which host would you use such that I can show the final product to my Uni.?** This is my first official database project so my plan apparently has shortcomings, since there must be tools which I do not know. **Please, pinpoint any one of them.**
First, this is all a lot to work with in a week. But here it goes. Tools for the backend: 1. SQLAlchemy - This is an ORM toolkit that is plenty powerful for most smaller tasks when using a MySQL database built with Python. To my knowledge, it is the best for this job. <http://www.sqlalchemy.org/> 2. Django - "...is a high-level Python Web framework..." This might be better for rapid development of a site with login/logout methods included and a minimal learning curve for someone with web/Python understanding. Tools in building the frontend: If you already plan on using Django for the backend, I'd recommend using it for the frontend as well. Things about which you are uncertain: 1. The users can be specified in MySQL and their permissions can be set accordingly. 2. From some of the requirements you listed, most of these sound like they can be contained within the capabilities of Django.
Use the django Model to create the Object-Relational Mapping (ORM) that injects and retrieve your data. For login/logout, django has an AuthenticationMiddleware feature you can probably use, although I am not sure if you can solve your problem with it. In any case, your project, with the given deadlines is totally unrealistic. Be prepared to miss the deadline, and hear the whooshing sound they do as they fly by.
To make a plan for my first MySQL project
[ "", "python", "mysql", "" ]
I have a class with overloaded constructor (C#) It can be initialized in few ways, and some parameters are optional - so in result - there is a confusing bunch of constructors ``` new Object(StrA, StrB, ObjA) new Object(StrA, StgB, ObjB, StrC) new Object(StrA, StrB, ObjA, StrD) new Object(StrA, StrB, ObjB, StrC, StrD) new Object(StrA, StrB, StrE, ObjA) new Object(StrA, StrB, StrE, ObjB) new Object(StrA, StrB, StrE, ObjA, StrC) new Object(StrA, StrB, StrE, ObjB, StrC, StrD) ``` I see a two ways to improve situation a) create a structure to hold optional parameters ``` new Config(StrA, StrB, StrD, StrE) new Object(Config, ObjA) new Object(Config, ObjB, StrC) ``` b) set optional parameters as properties ``` A = new Object(ObjA) A.StrA = some; A.StrB = some; A.StrD = some; A.StrE = some; ``` Which is the best way? And is such code refactoring necessary - the previous code maintainer says that "while intellisense used, complexity of constructor doesn't matter - it always possible to check tips and select the correct one"
Yes, I would refactor this. IntelliSense is only so much helpful, and staring at a 5-argument constructor which takes 3 seemingly random strings trying to figure out which one means what is not going to improve code readability any. In VB (or C# 4.0), I'd still go with constructor, but use named arguments. For C# 3.0, I'd make a separate class to hold the initialization info: ``` class ObjectSettings { public string StrA { get; set; } public string StrB { get; set; } ... public string ObjA { get; set; } public string ObjB { get; set; } } ``` and then take a single argument of that type in constructor: ``` class Object { public Object(ObjectSettings settings); } ``` and use object initializer when invoking it: ``` new Object(new ObjectSettings { StrA = ..., StrB = ..., ObjA = ... }) ``` The main advantage of this compared to just having properties in `Object` is that this pattern guarantees that `Object` will be properly initialized as soon as it is constructed. With properties on object itself, it will be in invalid state until client sets them all correctly, and you'll have to validate that on pretty much every call. This pattern is actually used in .NET FCL - see `XmlReader` / `XmlReaderSettings` for an example of it.
Another option is to hold on for the moment, and then compress it all down when C# 4 comes out with optional parameters and named arguments - so long as you don't need to call the code from any other languages which might not have those features. I'd personally create a type holding *all* the parameters, unless there are different types involved for some overloads (e.g. like `XmlReader.Create` can deal with a `TextReader` or a `Stream`). I wouldn't make it a struct though - just make it a class, it'll be fine. Give it a load of automatically implemented properties, and then you can use object initializers to set the parameters in a readable way.
How to refactor a class with overloaded constructors
[ "", "c#", ".net", "refactoring", "constructor", "" ]
I recently read the IXmlSerializable interface information on MSDN and was a little confused about the whole end tag thing. As I understand it, if you are implementing IXmlSerializable then you do not need to write the end tag, but you do need to read it? E.g. the following would error if my class A does not read the end tag ``` <A> <i>32</i> </A> ``` But what happens if the content is ``` <A i="32"/> ``` If I attempt to read the end tag here I get an InvalidOperationException. But if I read on to determine what I'm supposed to be reading is that not going to much up the position of the reader? I think I'm just getting a little lost, as the code I'm working with gets a bit more complex when I have to deal with IXmlSerializable children (which can be of varying types), and collections of IXmlSerializable elements.
Both [`XmlReader`](http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.isemptyelement.aspx) and [`XPathNavigator`](http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.isemptyelement.aspx) implement a property called `IsEmptyElement`. From the documentation: > When overridden in a derived class, gets a value indicating whether the current node is an empty element without an end element tag. So when you see a start-element event, if `IsEmptyElement` is `true` you should not look for an end-element event. The start-element event acts as both start and end for that case.
I'm recalling `XmlReader.IsEmptyElement`. On the start tag if this is set then you have `<a />`. If it is not set then you have `<a></a>`. The latter you read the end tag, the former you don't.
XmlSerialization - reading the End Element Tag?
[ "", "c#", "xml-serialization", "" ]
I loved the 2005 book "Professional Java Development with the Spring Framework" by Johnson. What would be the 2008-9 equivalent of this in terms of the quality and clarity the book provided? Essentially looking for a book for someone new to Spring, I still think the 2005 book is somewhat relevant, but much has changed in the Spring world since then.
The best of the bunch today seems to be the "Pro Spring" series, and the "Spring an Action" series. I can particularly recommend the former. edit: It seems that Pro Spring covers Spring 2.5, but Spring in Action is still stuck back in the 2.0 days
I'm reading ["Spring Recipes"](https://rads.stackoverflow.com/amzn/click/com/1590599799) right now (~1/3rd of the way done), and I can recommend it. Spring 3.0 isn't out yet, so it's right up to date covering 2.5. UPDATE: Finished it this week. I can highly recommend it, just for the chapter on Spring Security alone.
Book: Modern day equivalent of the Wrox Spring book
[ "", "java", "spring", "" ]
How to use Class Dictionary in java ?
Don't use it, it's profoundly, thoroughly, obsolete and unnecessary. Use a Map implementation such as HashMap.
Look at java.util.HashMap and java.util.Map (I understand you are looking for a dictionary equivalent in Java, and not referring to the abstract Dictionary class which is implemented by HashTable)
Class Dictionary in java (data structure)
[ "", "java", "class", "data-structures", "dictionary", "" ]
I'm trying to design a view to accept donations, sell memberships, or sell tickets to events. I have a dropdown list that displays "Make a donation", "Purchase membership", and the subsequent options are populated from the `IList<Event>` Model passed from the controller. I use javascript to determine which panel (membership, donation, or event) should be displayed based on the selection. The problem I'm having is that once an event is selected, I need to be able to dynamically populate the Event panel with the properties of the selected event (without, of course, having to put the user through a browser refresh). I was told by someone that I should be able to use Ajax to accomplish this. Supposedly I could go to my server/home/GetEventById action to do this. However, I haven't been able to find any examples or any tutorials that would help me accomplish this. Could anybody shed some light on this for me by means of how to go about this, or provide examples or tutorials that would help me?
Here is a code example of fetching some content by calling a controller method through ajax, and then populating a jQuery dialog with it. Hopefully this helps point you in the right direction. The controller method: ``` [AcceptVerbs(HttpVerbs.Get)] public ActionResult GetItemsForJson() { var items = Repository.GetItems(); var result = Json(items); return result; } ``` And the jQuery to make it happen: ``` $('#dialog_link').click(function () { $.getJSON("/Items/GetItemsForJson/", getItems); }); function getItems(items) { $("#itemlist").text(""); $.each(items, function (i, item) { $("#itemlist").append("<li>" + item.Id + item.Name + "</li>"); }); } ```
Your question is a bit too broad. I assume you already implemented your Action in controller so we concentrate only on client side scripting. Following should within $.ready: ``` $("#ddlSelectEvent").change(function() { // this will fire when drop down list is changed var selection = $(this).attr("selected"); // text representation of selected value $(".panels").hide(); $("#panel_" + selection).show(); // Assume the panel naming will be panel_MakeDonation and those... // Now is time for ajax - load html directly $.get("server/home/geteventbyId", {id: "12345"}, function (data) { // callback when data is loaded $("#panel_" + selection).html(data); } ); }); ``` Above codes assume you populate content of panel with html. You might use JSON or other types depending on how you implement it. <http://docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype>
MVC, Jquery, and Ajax to display object based on dropdown
[ "", "c#", "asp.net-mvc", "jquery", "" ]
I wrote a class that lets me pass in a list of variable types, variable names, prompts, and default values. The class creates a wxPython panel, which is displayed in a frame that lets the user set the input values before pressing the calculate button and getting the results back as a plot. I add all of the variables to the class using exec statements. This keeps all of the variables together in one class, and I can refer to them by name. ``` light = Variables( frame , [ ['f','wavelength','Wavelength (nm)',632.8] ,\ ['f','n','Index of Refraction',1.0],]) ``` Inside the class I create and set the variables with statments like: ``` for variable in self.variable_list: var_type,var_text_ctrl,var_name = variable if var_type == 'f' : exec( 'self.' + var_name + ' = ' + var_text_ctrl.GetValue() ) ``` When I need to use the variables, I can just refer to them by name: ``` wl = light.wavelength n = light.n ``` Then I read on SO that there is rarely a need to use exec in Python. Is there a problem with this approach? Is there a better way to create a class that holds variables that should be grouped together, that you want to be able to edit, and also has the code and wxPython calls for displaying, editing, (and also saving all the variables to a file or reading them back again)? Curt
You can use the `setattr` function, which takes three arguments: the object, the name of the attribute, and it's value. For example, ``` setattr(self, 'wavelength', wavelength_val) ``` is equivalent to: ``` self.wavelength = wavelength_val ``` So you could do something like this: ``` for variable in self.variable_list: var_type,var_text_ctrl,var_name = variable if var_type == 'f' : setattr(self, var_name, var_text_ctrl.GetValue()) ```
I agree with mipadi's answer, but wanted to add one more answer, since the Original Post asked if there's a problem using exec. I'd like to address that. Think like a criminal. If your malicious adversary knew you had code that read: ``` exec( 'self.' + var_name + ' = ' + var_text_ctrl.GetValue() ) ``` then he or she may try to inject values for var\_name and var\_text\_ctrl that hacks your code. Imagine if a malicious user could get var\_name to be this value: ``` var_name = """ a = 1 # some bogus assignment to complete "self." statement import os # malicious code starts here os.rmdir('/bin') # do some evil # end it with another var_name # ("a" alone, on the next line) a """ ``` All of the sudden, the malicious adversary was able to get YOU to exec[ute] code to delete your /bin directory (or whatever evil they want). Now your exec statement roughly reads the equivalent of: ``` exec ("self.a=1 \n import os \n os.rmdir('/bin') \n\n " "a" + ' = ' + var_text_ctrl.GetValue() ) ``` Not good!!! As you can imagine, it's possible to construct all sorts of malicious code injections when exec is used. This puts the burden onto the developer to think of any way that the code can be hacked - and adds unnecessary risk, when a risk-free alternative is available.
Using Eval in Python to create class variables
[ "", "python", "wxpython", "scientific-computing", "" ]
I have a string that is randomly generated: ``` polymer_str = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine" ``` I'd like to find the longest sequence of "diNCO diol" and the longest of "diNCO diamine". So in the case above the longest "diNCO diol" sequence is 1 and the longest "diNCO diamine" is 3. How would I go about doing this using python's re module? Thanks in advance. EDIT: I mean the longest number of repeats of a given string. So the longest string with "diNCO diamine" is 3: diol **diNCO diamine diNCO diamine diNCO diamine** diNCO diol diNCO diamine
Expanding on [Ealdwulf](https://stackoverflow.com/users/90354/ealdwulf)'s [answer](https://stackoverflow.com/questions/1155376/python-re-find-longest-sequence/1155508#1155508): Documentation on `re.findall` can be found [here](http://docs.python.org/library/re.html#re.findall). ``` def getLongestSequenceSize(search_str, polymer_str): matches = re.findall(r'(?:\b%s\b\s?)+' % search_str, polymer_str) longest_match = max(matches) return longest_match.count(search_str) ``` This could be written as one line, but it becomes less readable in that form. **Alternative:** If `polymer_str` is huge, it will be more memory efficient to use `re.finditer`. Here's how you might go about it: ``` def getLongestSequenceSize(search_str, polymer_str): longest_match = '' for match in re.finditer(r'(?:\b%s\b\s?)+' % search_str, polymer_str): if len(match.group(0)) > len(longest_match): longest_match = match.group(0) return longest_match.count(search_str) ``` The biggest difference between `findall` and `finditer` is that the first returns a list object, while the second iterates over Match objects. Also, the `finditer` approach will be somewhat slower.
``` import re pat = re.compile("[^|]+") p = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine".replace("diNCO diamine","|").replace(" ","") print max(map(len,pat.split(p))) ```
Python: re.find longest sequence
[ "", "python", "regex", "" ]
I have thought of this idea where you could have a tab control on a form, but instead of defining each tabs controls before runtime, inherit or use another form's controls. Basically a tab control is in place on the main form that has no tabs on it before runtime. When runtime comes along I want to create tabs, but the controls that would be on each tab would be from seperate already created forms. Each form would be a seperate tab that had been created prior to runtime. Is this possible? Is so, how? Thanks in advance EDIT I'm using 3.5
first create a User Control and design it as you would a regular form, then add it to your **TabControl.TabPages** ``` TabPage page = new TabPage("Title"); page.Controls.Add(new CustomUserControl()); //your user control this.tabControl1.TabPages.Add(page); ```
Yes, it is possible. You have to add the [controls](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controls.aspx) onto the TabPage, then add the [TabPage](http://msdn.microsoft.com/en-us/library/system.windows.forms.tabpage_properties.aspx) to the [TabControl.TabPages](http://msdn.microsoft.com/en-us/library/system.windows.forms.tabcontrol.tabpages.aspx)
C# Adding tabs at runtime using Form's controls
[ "", "c#", "inheritance", "controls", "tabs", "" ]
This is in reference to [a problem I had](https://stackoverflow.com/questions/1127264/cannot-find-datacontractjsonserializer-from-an-asp-net-mvc-application/1131227#1131227) which I was able to find the solution to here on Stack Overflow. This wasn't my question, but it was the same exact problem I had. How do I know that I need to import a specific DLL file to use a specific namespace? I saw no reference to this on either the MSDN page or the Object Explorer, and even [ReSharper](http://en.wikipedia.org/wiki/ReSharper) didn't pick up on it. Is this referenced anywhere?
From <http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx>: # DataContractJsonSerializer Class Serializes objects to the JavaScript Object Notation (JSON) and deserializes JSON data to objects. This class cannot be inherited. Namespace: [System.Runtime.Serialization.Json](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.aspx) Assembly: System.ServiceModel.Web (in System.ServiceModel.Web.dll)
Good question. I generally do a quick search for the class on Google, then start typing for the assembly based on the beginning of the namespace it's in.
How do I know what reference to include to import a specific .NET namespace?
[ "", "c#", ".net", "" ]
Does anyone know how to localize date ranges using C#? In particular, I want to generate "smart" date ranges, so that redundant information is eliminated. Here are some examples in US English 1. August - Sept, 2009 2. August 2009 3. August 1 - 9, 2009 4. January 1 - March 3, 2009 5. December 6, 2009 - January 8, 2010 Form what I can tell the .NET Framework has support for localizing dates, but not ranges of dates. Using the information in `System.Globalization.DateTimeFormatInfo` for the Windows locales that `CultureInfo` supports, I was able to figure out (most of the time) how to do items #1 and #2. Item #2 is just `DateTime.ToString(DateTimeFormatInfo.YearMonthFormat)`. Using `YearMonthFormat` I was also able to deduce formats to use for #1 for most languages. For the few that I couldn't I just duplicate the year. Unfortunately, I can't figure out how to do items #3-#5 using the .NET Framework. Outlook formats ranges using those formats, so I was hoping there might be some Win32 APIs that would do it, but a Google search for "Win32 Date Range localization" yielded nothing useful. I like the enhanced usability provided by "smart range formating", and I would like my customers that are not using English versions of Windows to get the same benefits. Does any one know how to do that in a culture-dependent manner?
I ended up defining my own range formats for this. For the most part I derived them from the LongDatePattern. Where possible I verified the formats against Google Calendar, and / or native speakers. I also generated 2 formats for time ranges (within the same day), one for within the same 12 hour period and another for times outside the same 12 hour period (for cultures that use 24 hour time these 2 formats are the same). Those are mostly based on the FullDateTimePattern. In all cases I removed "day names" (monday, tuesday, etc) from all the formats where ever possible. I would love to post them here, but it seems that the Stack Overflow folks have an irrational fear of html tables, because they don't allow table tags. The data is essentially a giant table. I have no interest in trying to simulate tables using CSS, so I just put the table up on my own site. You can access it here if you are interested: <http://www.transactor.com/misc/ranges.html> I do have some detailed notes on how I derived a lot of the formats, including what's been validated and what hasn't, if you are really interested. If you want those notes, just send an email to: contact@transactor.com and I'd be happy to send them to you.
Good question and it does seem to be something that the .NET framework and other languages seem to be missing too. I would guess the presentation of the results depends upon your application. Outlook has very good date understanding as an input (as does Google calenders), but I haven't personally seen this form of expression as an output (e.g. displayed to the user). Some recommendations: 1. Stick with displaying a start date and an end date and don't worry about redundancy 2. Roll your own..... :-( I would guess that from your term 'localize' you plan to internationalize the output, if that is the case you are going to have a hard job catching all of the cases, it doesn't seem to be information stored in most of the typical internationalization data sets. Concentrating on English from your example, you seem to have a number of rules already defined in the code: 1. Year always displayed. 2. Month (at least one of them) is also always displayed. 3. Days are not displayed in case 3, this I would condition to mean that the start date is the 1st and the end is the 31st (e.g. every day of the month) 4. Day and Month are shown if the start/end are different months. 5. Year is additionally shown against the start date if the two dates differ by year. I know the above is only looking at English, but in my view, it doesn't look too hard to roll yourself, too much to write in this editor though! ## EDIT - I know this doesn't answer the original - but if anyone using a search engine finds this question and wants an English version... ``` class Program { static void Main(string[] args) { Console.WriteLine(DateRange.Generate(2009, 08, 01, 2009, 09, 31)); Console.WriteLine(DateRange.Generate(2009, 08, 01, 2009, 08, 31)); Console.WriteLine(DateRange.Generate(2009, 08, 01, 2009, 08, 09)); Console.WriteLine(DateRange.Generate(2009, 01, 01, 2009, 03, 03)); Console.WriteLine(DateRange.Generate(2009, 12, 06, 2010, 01, 08)); // Same dates Console.WriteLine(DateRange.Generate(2009, 08, 01, 2009, 08, 01)); } } static class DateRange { private static string[] Months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; public static string Generate( int startYear, int startMonth, int startDay, int endYear, int endMonth, int endDay) { bool yearsSame = startYear == endYear; bool monthsSame = startMonth == endMonth; bool wholeMonths = (startDay == 1 && IsLastDay(endDay, endMonth)); if ( monthsSame && yearsSame && startDay == endDay) { return string.Format("{0} {1}, {2}", startDay, Month(startMonth), startYear); } if (monthsSame) { if (yearsSame) { return wholeMonths ? string.Format("{0} {1}", Month(startMonth), endYear) : string.Format("{0} {1} - {2}, {3}", Month(endMonth), startDay, endDay, endYear); } return wholeMonths ? string.Format("{0}, {1} - {2}, {3}", Month(startMonth), startYear, Month(endMonth), endYear) : string.Format("{0} {1}, {2} - {3} {4}, {5}", Month(startMonth), startDay, startYear, Month(endMonth), endDay, endYear); } if (yearsSame) { return wholeMonths ? string.Format("{0} - {1}, {2}", Month(startMonth), Month(endMonth), endYear) : string.Format("{0} {1} - {2} {3}, {4}", Month(startMonth), startDay, Month(endMonth), endDay, endYear); } return wholeMonths ? string.Format("{0}, {1} - {2}, {3}", Month(startMonth), startYear, Month(endMonth), endYear) : string.Format("{0} {1}, {2} - {3} {4}, {5}", Month(startMonth), startDay, startYear, Month(endMonth), endDay, endYear); } private static string Month(int month) { return Months[month - 1]; } public static bool IsLastDay(int day, int month) { switch (month+1) { case 2: // Not leap-year aware return (day == 28 || day == 29); case 1: case 3: case 5: case 7: case 8: case 10: case 12: return (day == 31); case 4: case 6: case 9: case 11: return (day == 30); default: return false; } } } ``` This yields the same output (almost, Sept becomes September in mine) as the original question: ``` August - September, 2009 August 1 - 31, 2009 August 1 - 9, 2009 January 1 - March 3, 2009 December 6, 2009 - January 8, 2010 ```
Localizing Date Ranges
[ "", "c#", ".net", "datetime", "date", "globalization", "" ]
What's the best way to store a `key=>value` array in javascript, and how can that be looped through? The key of each element should be a tag, such as `{id}` or just `id` and the value should be the numerical value of the id. It should either be the element of an existing javascript class, or be a global variable which could easily be referenced through the class. jQuery can be used.
That's just what a JavaScript object is: ``` var myArray = {id1: 100, id2: 200, "tag with spaces": 300}; myArray.id3 = 400; myArray["id4"] = 500; ``` You can loop through it using [`for..in` loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in): ``` for (var key in myArray) { console.log("key " + key + " has value " + myArray[key]); } ``` See also: [Working with objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) (MDN). In ECMAScript6 there is also [`Map`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map) (see the browser compatibility table there): > * An Object has a prototype, so there are default keys in the map. This could be bypassed by using map = Object.create(null) since ES5, but was seldomly done. > * The keys of an Object are Strings and Symbols, where they can be any value for a Map. > * You can get the size of a Map easily while you have to manually keep track of size for an Object.
If I understood you correctly: ``` var hash = {}; hash['bob'] = 123; hash['joe'] = 456; var sum = 0; for (var name in hash) { sum += hash[name]; } alert(sum); // 579 ```
Best way to store a key=>value array in JavaScript?
[ "", "javascript", "jquery", "" ]
I was wondering if there was a way to send a referer with a http-request though it is turned of in the browser (e.g. with javascript)? The problem I have when the referrer is not sent: I am trying to minimize the changes of attacks, so whenever a page is loaded I am changing the sessionkey ... the sessionid stays the same, but the key changes ... so basically when a page has some script- or style-files that need to be sent from the server the refer(r)er is the page that needs them to be displayed correctly or has some parts that need the script. When I change into another page on my server the refer(r)er changes. Ok, to explain it, here is a pattern (if it is not understandable, please say so): ``` start: GET test.html --> referrer := null `--> GET style.css --> referrer := test.html ---- CLICK ON LINK TO GO TO: 'form.html' GET form.html --> referrer := test.html `--> GET sendRequest.js --> referrer := form.html `--> GET style.css --> referrer := form.html ---- CALL A PAGE DIRECTLY OVER ADDRESS BAR: http://somedomain.com/someotherpage.html GET someotherpage.html --> referrer := null ``` So, to make the change of sessionkey work: I only change the sessionkey when the refer(r)er is null or I am changing to another page ... BUT that won't work when "Send referer" is turned off, like you could do when using Opera ... b/c then the refer(r)er is always null and I get into trouble when the client sends the request for style.css from the test.html-page b/c then the new sessionkey would be set, but the request for the style.css comes in with the old sessionkey ... so the easiest way (I think ... maybe I am missing something) would be to work with the refer(r)er ...
I think that you've overcomplicated this. They have to have cookies enabled in order for session to work. Add a cookie with a copy of the current session key. Whenever an html file is requested, test to see if the cookie key and the session key's match. If they don't then you probably have a replay attack going on. Go ahead and ignore requests for .css, ., etc. All you really should care about is your html files. Update the key and write it to your session variable and the cookie whenever an html file is requested. With this referrer is immaterial (it can be spoofed anyway) and you are protected against replay; which, I think, is what your ultimately after.
Not sure what JavaScript you were hoping to use here but do keep in mind that if you are using JavaScript to set where the user is going to (e.g. the next page) then [IE won't send the referrer at all](http://webbugtrack.blogspot.com/2008/11/bug-421-ie-fails-to-pass-http-referer.html)! So be weary of what magic you add to your page transitions.
Sending refer(r)er though it's turned off in the browser?
[ "", "javascript", "http-referer", "" ]
I am building a small app which captures mouse clicks. I wrote the prototype in jQuery but, since it is a small app focusing on speed, embedding jQuery to use just one function would be an overkill. I tried to adapt this example from [JavaScriptKit](http://www.javascriptkit.com/jsref/eventkeyboardmouse.shtml): ``` document.getElementById("alphanumeric").onkeypress=function(e){ //blah..blah..blah.. } ``` but it didn't work when I tried this: ``` document.getElementsByTagName("x").onclick ``` What am I doing wrong?
Say you have a list of p tags you would like to capture the click for the `<p>` tag: ``` var p = document.getElementsByTagName("p"); for (var i = 0; i < p.length; i++) { p[i].onclick = function() { alert("p is clicked and the id is " + this.id); } } ``` Check out an example here for more clarity: <http://jsbin.com/onaci/>
In your example you are using [`getElementsByTagName()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName) method, which returns you an *array* of DOM elements. You could iterate that array and assign the `onclick` handler to each element, for example: ``` var clickHandler = function() { alert('clicked!'); } var elements = document.getElementsByTagName('div'); // All divs for (var i = 0; i < elements.length; i++) { elements[i].onclick = clickHandler; } ```
Pure JavaScript equivalent of jQuery click()?
[ "", "javascript", "jquery", "click", "equivalent", "" ]
Notice, this is a remote server, I don't have access to it, only to the FTP. I want to do this using purely PHP, not .htaccess. Is there a way similar to .net, where you put the web.config file and you set who can access it and their password?
I'd say the equivalent of that kind of functionnality from web.config on Apache is with .htaccess files : PHP is used to generate pages, but if you are trying to work at the directory level, the check has to come before PHP is even called. In your PHP scripts, you can access the data of HTTP Authentication ; see [`$_SERVER`](http://php.net/manual/en/reserved.variables.server.php), especially `PHP_AUTH_USER` and `PHP_AUTH_PW` ; but the protection will be at the file's level, and not directory -- and, obviously, it will be enforced only for PHP files (not images in a subdirectory, for instance). For more informations, you can have a look at, for instance : [HTTP Basic and Digest authentication with PHP](http://www.rooftopsolutions.nl/article/223) The right way to do this for an entire directory is definitly with .htpasswd / .htaccess files (or directly in the Apache's configuration file).
Why using PHP? .htaccess files were designed for this purpose. If you're trying to do something like store user logons in a database, look at the something like [Mod\_auth\_mysql](http://modauthmysql.sourceforge.net/) What you can do is place the files outside of your webroot and write a php script to serve those files after passing your authentication logic.
How can I protect a directory using PHP?
[ "", "php", "security", "" ]
In Java, you can create an enum as follows: ``` public enum Letter { A, B, C, D, E, F, G; static { for(Letter letter : values()) { // do something with letter } } } ``` This question concerns the "values()" method. Specifically, how is it implemented? Usually, I could jump to the source for Java classes using F3 or CTRL+Click in Eclipse (even for classes like String, Character, Integer, and even Enum). It is possible to view the source of the other enum methods (e.g., valueOf(String)). Does "values()" create a new array each time it is invoked? If I assign it to a local variable and then modify one of the elements, what happens (clearly this won't affect the value returned by values(), which implies that a new array is allocated each time). Is the code for it native? Or does the JVM / compiler treat it specially, only returning a new instance from values() when it cannot prove that it will not be modified.
Basically, the compiler (javac) translates your enum into a static array containing all of your values at compile time. When you call values(), it gives you a .clone'd() copy of this array. Given this simple enum: ``` public enum Stuff { COW, POTATO, MOUSE; } ``` You can actually look at the code that Java generates: ``` public enum Stuff extends Enum<Stuff> { /*public static final*/ COW /* = new Stuff("COW", 0) */, /*public static final*/ POTATO /* = new Stuff("POTATO", 1) */, /*public static final*/ MOUSE /* = new Stuff("MOUSE", 2) */; /*synthetic*/ private static final Stuff[] $VALUES = new Stuff[]{Stuff.COW, Stuff.POTATO, Stuff.MOUSE}; public static Stuff[] values() { return (Stuff[])$VALUES.clone(); } public static Stuff valueOf(String name) { return (Stuff)Enum.valueOf(Stuff.class, name); } private Stuff(/*synthetic*/ String $enum$name, /*synthetic*/ int $enum$ordinal) { super($enum$name, $enum$ordinal); } } ``` You can look at how javac 'translates' your classes by making a temporary directory and running: ``` javac -d <output directory> -XD-printflat filename.java ```
If you assign it to a local variable the only thing that you can modify is assigning another enum to this variable. This will not change the enum itself because you are only changing the object your variable references. It seems that the enums are in fact singletons so that only one element from each enum can exist in you whole program this makes the == operator legal for enums. So there is no performance problem and you can't accidentally change something in your enum definition.
How is values() implemented for Java 6 enums?
[ "", "java", "enums", "" ]
Should every C++ programmer read the ISO standard to become professional?
No. C++ standard is more like a dictionary - something where you look up specific things that concern you at any given moment. It doesn't make a good (or useful) reading if you treat it as a simple book to read from beginning to end. If the question were whether every professional C++ programmer should *have* an ISO standard at hand, and use it for reference *as needed*, then I'd say "yes".
I think that every professional C++ programmer should have a copy of the standard to refer to. But a sit down and slog through it, cover-to-cover read would be pretty numbing. It's mostly written for implementers (compiler writers), and it has next to no explanation of rationale for why the standard requires certain things. So, I'd say it's more important for a professional C++ programmer to have and read: * Stroustrup's "The C++ Programming Language" * Meyer's "Effective..." series and/or Sutter's "Exceptional..." series * Lippman's "Inside the C++ Object Model" * Stroustrup's "Design and Evolution of C++" Or at least some decent subset of them. If you have a chunk of those books under your belt, you'll only be going to the Standard for minutiae or to settle arguments. By the way, see this answer for pointers on how to get the standard documents: * [Where do I find the current C or C++ standard documents?](https://stackoverflow.com/questions/81656/where-do-i-find-the-current-x-standard/83763#83763)
Should every C++ programmer read the ISO standard to become professional?
[ "", "c++", "" ]
I want to keep only 1000 entries for each clientid. The code below does what I want but does not loop through the clientid, instead keeping 1000 total of any of the clients. Is there a way to do this in sql? I was told I need a cursor, but I am hoping not. ``` DECLARE @ids TABLE ( id int ) DECLARE @clients TABLE ( clientid varchar(20) ) INSERT INTO @clients (clientid) SELECT select distinct clientid FROM tRealtyTrac INSERT INTO @ids (id) SELECT top 1000 id FROM tRealtyTrac WHERE clientid in (select clientid from @clients) DELETE trealtytrac WHERE id NOT IN (select id from @ids) ```
Is this SQL Server 2005 or later? What about something like ``` INSERT INTO @ids (id) SELECT id FROM ( SELECT id, RANK() OVER (PARTITION BY clientid ORDER BY id) AS Rank FROM tRealtyTrac ) t WHERE t.Rank <= 1000 ```
in Oracle: ``` DELETE from CLIENTS where CLIENT_ID = 'xxx' and rownum > 1000 ```
Delete SQL looping
[ "", "sql", "sql-server", "loops", "distinct", "sql-delete", "" ]
I think the topic might not be accurate enough, but I really don't know how to describe it in a very brief way... What I want to do is as follows: I have a process running some analysis (in Java) and trying to give a return value, but the whole analysis has a time constraint, say 10 seconds If the analysis gives a result within 10s, return the result; else, times up when reaching 10s, stop the process and return a dummy value I am a newbie in this field, any suggestions will be welcomed.
You can use [FutureTask](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/FutureTask.html) to create a job and request the result within a particular time (using [get()](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/FutureTask.html#get%28long,%20java.util.concurrent.TimeUnit%29) with a timeout). If that time window is breached, then you'll get an exception. At that point you can then call the [cancel()](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/FutureTask.html#cancel%28boolean%29) method with the parameter set to `true to` force an interruption and cancel the underlying task. ``` Object result = DUMMY; try { result = futureTask.get(5, TimeOut.SECONDS); } catch (TimeoutException e) { futureTask.cancel(true); } ```
You could use a timer (java.util.Timer), which you could notify of the thread, and then when the timer expired it could tell the thread to stop. A better solution would be to spawn the process off into it's own thread, and then tell your main thread to wait on the processing thread and sleep for 10 seconds. When it finishes, you can send the thread a stop signal. Note: I would not use the stop() method, and instead send either a signal or set a value through a synchronized method that gets checked every so often during the execution.
How to stop a process with time constraints
[ "", "java", "time", "event-handling", "constraints", "listener", "" ]
Need to check if **$message** length is 7 characters or less, if so, do action A, if not, do action B. Is this correct syntax? I think im doing something wrong? ``` <?php if (strlen($message) <= 7) { echo $actiona; } else { echo $actionb; } ?> ```
It's fine. For example, let's run the following: ``` <?php $message = "Hello there!"; if (strlen($message) <= 7){ echo "It is less than or equal to 7 characters."; } else { echo "It is greater than 7 characters."; } ?> ``` It will print: "It is greater than 7 characters."
You might also want to use the PHP shorthand if/else using the ternary operators (?:). For example, instead of: ``` <?php if (strlen($message) <= 7) { echo $actiona; } else { echo $actionb; } ?> ``` You can write it as: ``` <?php echo strlen($message) <= 7 ? $actiona : $actionb; ?> ``` See [How do I use shorthand if / else?](https://stackoverflow.com/questions/1506527/how-do-i-use-shorthand-if-else) for information on the ternary operator.
php check if variable length equals a value
[ "", "php", "" ]
I want to create a table that stores values from two different tables; > From table 1: cust\_id (varchar2), invoice\_amt (float) > > From table 2: cust\_id (from table 1), payment\_date My table should have 3 fields: ``` cust_id, invoice_amt, payment_date ``` I tried the following, which is obviously wrong. ``` create table temp1 as ( select table_1.cust_id, table_1.invoice_amt, table_2.payment_date from table_1@dblink, table_2@dblink) ``` Your valuable suggestions will be of great help.
``` create table temp1 as ( select table_1.cust_id, table_1.invoice_amt, table_2.payment_date from table_1@dblink, table_2@dblink where table_1.cust_id = table_2.cust_id ) ``` I'm no oracle guy, but that should do what you want (untested, though).
You were close: ``` create table temp1 as ( select t1.cust_id, t1.invoice_amt, t2.payment_date from table_1@dblink t1, table_2@dblink t2 where t1.cust_id=t2.cust_id) ```
Creating tables with fields from 2 different tables
[ "", "sql", "oracle", "oracle10g", "" ]
I am struggling to read gzipped xml files in php. I did succeed in reading normal xml files, using XMLReader() like this: ``` $xml = new XMLReader(); $xml->open($linkToXmlFile); ``` However, this does not work when the xml file is gzipped. How can I unzip the file and read it with the XMLReader?
As you didn't specify a PHP version, I am going to assume you are using PHP5. I am wondering why people haven't suggested using the built in [PHP compression streams API](https://www.php.net/manual/en/wrappers.compression.php). ``` $linkToXmlFile = "compress.zlib:///path/to/xml/file.gz"; $xml = new XMLReader(); $xml->open($linkToXmlFile); ``` From what I understand, under the covers, it will transparently decompress the file for you and allow you to read it as if were a plain xml file. Now, that may be a gross understatement.
Maybe the function [`gzdecode`](http://php.net/manual/en/function.gzdecode.php) could help you : the manual says (quote) : > Decodes a gzip compressed string So, you'd have to : * download the XML data * get it as a string * decompress it with `gzdecode` * work on it with `XMLReader` That would depend on the right extension *(`zlib` I guess)* beeing installed on your server, though... > [*Mark*](https://stackoverflow.com/users/139812/mark): Expanding on Pascal's post, here is some example code that should work for you ``` $xmlfile = fopen($linkToXmlFile,'rb'); $compressedXml = fread($xmlfile, filesize($linkToXmlFile)); fclose($xmlfile); $uncompressedXml = gzdecode($compressedXml); $xml = new XMLReader(); $xml->xml($uncompressedXml); ```
PHP open gzipped XML
[ "", "php", "xml", "gzip", "xmlreader", "" ]
How do I assign an in-memory `Bitmap` object to an `Image` control in WPF ?
You can use the Source property of the image. Try this code... ``` ImageSource imageSource = new BitmapImage(new Uri("C:\\FileName.gif")); image1.Source = imageSource; ```
According to <http://khason.net/blog/how-to-use-systemdrawingbitmap-hbitmap-in-wpf/> ``` [DllImport("gdi32")] static extern int DeleteObject(IntPtr o); public static BitmapSource loadBitmap(System.Drawing.Bitmap source) { IntPtr ip = source.GetHbitmap(); BitmapSource bs = null; try { bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); } finally { DeleteObject(ip); } return bs; } ``` It gets System.Drawing.Bitmap (from WindowsBased) and converts it into BitmapSource, which can be actually used as image source for your Image control in WPF. ``` image1.Source = YourUtilClass.loadBitmap(SomeBitmap); ```
Using Image control in WPF to display System.Drawing.Bitmap
[ "", "c#", "wpf", "" ]
On my page I am changing some css styles via javascript. When I try and pull a value that has been inherited - it comes up blank. Consider the following: ``` .Sliding { display: none; overflow: hidden; } .Sliding #FilterBox { height: 185px; background-color: Fuchsia; } ``` And the html: ``` <div class="Sliding" id="FilterBox"> <h3>Test Form</h3> This is a test/<br /> 12345 </div> ``` If I look at the element '**document.getElementById(objname).style.display**' its blank? How can I read the display value via via javascript?
You'll want to use [getComputedStyle](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle). The `.style` property is a means of accessing and setting inline style (i.e. like the style attribute). Note, however, that your example has nothing to do with inheritance. Just rule-sets that apply directly to the elements you are interested in. Inheritance is when an element takes on the same style as its parent via the `inherit` keyword. ``` span { color: inherit; } ``` getComputedStyle will give the final computed value though, so it will pick up inherited values too.
Your second CSS rule: ``` .Sliding #FilterBox { height: 185px; background-color: Fuchsia; } ``` will match anything with id "FilterBox" that is a descendant of anything with a class "Sliding", so this rule does not apply to your div. And to get the computed style, you can refer to Fabien's answer, or consider using jQuery, which makes this stuff a lot easier: using jQuery, **$("#FilterBox").css("display")** would return the current value for "display".
Inherited CSS Values via Javascript
[ "", "javascript", "css", "getelementbyid", "" ]
Is there a version of the PHP array class where all the elements must be distinct like, for instance, sets in Python?
Nope. You could fake it by using an associative array where the keys are the elements in the "set" and the values are ignored.
Here's a first-draft of an idea that could eventually work for what you want. ``` <?php class DistinctArray implements IteratorAggregate, Countable, ArrayAccess { protected $store = array(); public function __construct(array $initialValues) { foreach ($initialValues as $key => $value) { $this[$key] = $value; } } final public function offsetSet( $offset, $value ) { if (in_array($value, $this->store, true)) { throw new DomainException('Values must be unique!'); } if (null === $offset) { array_push($this->store, $value); } else { $this->store[$offset] = $value; } } final public function offsetGet($offset) { return $this->store[$offset]; } final public function offsetExists($offset) { return array_key_exists($offset, $this->store); } final public function offsetUnset($offset) { unset( $this->store[$offset] ); } final public function count() { return count($this->store); } final public function getIterator() { return new ArrayIterator($this->store); } } $test = new DistinctArray(array( 'test' => 1, 'foo' => 2, 'bar' => 3, 'baz' => '1', 8 => 4, )); try { $test[] = 5; $test[] = 6; $test['dupe'] = 1; } catch (DomainException $e) { echo "Oops! ", $e->getMessage(), "<hr>"; } foreach ($test as $value) { echo $value, '<br>'; } ```
PHP array with distinct elements (like Python set)
[ "", "php", "arrays", "" ]
Fairly easy, if the BigInteger number is 543 I want it to cut off the last digit so that it is 54. Two easy ways to do this can be : 1. Use strings, get substring and create new biginteger with the new value. 2. Use BigIntegers divide method with number 10. ( 543 / 10 = 54.3 => 54 ) The thing is I will be performing this **a lot** of times with large integers of course. My guess is that playing around with strings will be slower but then again I haven't used Bigintegers so much and have no idea how expensive the "divide" operation is. The speed is essential here, what is the fastest way to implement this (memory is no problem only speed) ? Others solutions are also welcome.
Dividing by 10 is much faster than using a substring operation. Using the following benchmark, I get about 161x times (ratio is proportional to bit count) ``` long divTime = 0; long substrTime = 0; final int bitsCount = 1000; for (int i = 0; i < 1000; ++i) { long t1, t2; BigInteger random = new BigInteger(bitsCount, new Random()); t1 = System.currentTimeMillis(); random.divide(BigInteger.TEN); t2 = System.currentTimeMillis(); divTime += (t2 - t1); t1 = System.currentTimeMillis(); String str = random.toString(); new BigInteger(str.substring(0, str.length() - 1)); t2 = System.currentTimeMillis(); substrTime += (t2 - t1); } System.out.println("Divide: " + divTime); System.out.println("Substr: " + substrTime); System.out.println("Ratio: " + (substrTime / divTime)); ```
Divide by 10 is most likely going to be faster.
Java BigInteger, cut off last digit
[ "", "java", "performance", "optimization", "biginteger", "" ]
Last week i searched for good free or opensource solutions and component for GIS (Geographical Information Systems) I founded some system but no one fill my requirements * SharpMap is very buggy software * Gmap.net is very slow * MapWindow have a very complex structure and is very buggy. I founded uDIG but is in java, i need a solution in vb.net or c#. Anyone know a good solution that fill my requirements or have alternatives, i accept solutions?
You are limiting yourself a lot by insisting on .NET. I don't know of anything other than SharpMap or [MapWinGIS ActiveX](http://www.mapwindow.com) (MapWindow). Here are some free, but not .NET, options for Windows desktop applications. If you'd consider writing your standalone application in Python or C++: * [Mapnik](http://www.mapnik.org/faq/) * [QGIS](http://www.qgis.org/) Or if you'd consider writing a plug-in or a customisation for an existing GIS: * [GRASS](http://grass.osgeo.org/) can be customised in [Python](http://grass.osgeo.org/wiki/GRASS_and_Python), Perl, Ruby... * [QGIS](http://www.qgis.org/) can be customised in [Python](http://desktopgisbook.com/node/19)
I think that you've covered it already. There really aren't any production quality open source GIS project out there using C#. Most of the good work is being done in Java, C/C++ or Python these days. If you must use the .NET Framework then I think the best of the bunch is indeed SharpMap. Failing that you need to look at commercial products from companies like <http://www.esri.com>. Of course, it also depends on what you need: web services, Windows Forms control, WPF, etc. In the past I've managed to whip up some C# that constructed the right XML to send to a Java server-based mapping engine, so you could look at something like GeoServer and build your own client. Obviously not what you want to get in to but I don't see that you have many options beyond the ones you've listed.
Good GIS Software or Components for Windows PC in .NET?
[ "", "c#", "components", "gis", "geography", "" ]
When writing a MVVM WPF app, there's always a point where the view model has to be set to as the data context of the view. For me, usually that's in code. But I realized that if I declare the view model as a static resource inside the xaml and set the binding there, I don't need to do it in code anymore. This means I don't have to coordinate the view and the viewmodel in a third class somewhere, like in the App. Is it acceptable to do this? Thanks!
I'd say so. It sort of implies specific knowledge of the ViewModel from the View, but you have to set it somehow and I like the codebehindless approach here. If you are using dependency injection this would not be appropriate, but if you aren't I'd stick with this approach.
Acceptable, yes, but if you are using PRISM, or DI of any sort, then it would make more sense to resolve it from the container and then set the datacontext either in code, or using a markup extension, depending on your exact solution.
Is it okay to declare the view model as a static resource in a view?
[ "", "c#", "wpf", "mvvm", "" ]
> **Possible Duplicates:** > [What is the correct way to create a single instance application?](https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application) > [Prevent multiple instances of a given app in .NET?](https://stackoverflow.com/questions/93989/prevent-multiple-instances-of-a-given-app-in-net) Do I check whether another process with the same name exists? (What if the user doesn't have permission to do that?) Write a file to disk and delete it before exiting? (what about abnormal termination?) What would be a best practice to do this?
You can use a Mutex. ``` bool firstInstance = true; using (Mutex mutex = new Mutex(true, "MyApplicationName", out firstInstance)) { if (firstInstance) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } else { // Another instance loaded } } ```
You can use the `Process` class's `GetProcessesByName` method to look for another running process with the same name, and exit if you find one.
What is the best way to make a single instance application in .net?
[ "", "c#", ".net", "design-patterns", "" ]
I have the following 3 tables ``` Table1 ID | NAME ----------- 1 | X 2 | Y 3 | Z Table2 ID | NAME ----------- 1 | A 2 | B 3 | C Table3 ID | P (Boolean field) | Other cols 1 | True ... 2 | True.... 1 | False ``` Now I need a query on table3 that has to do the following: To display the name field of table1 and table2. But my problem is that if field P on table3 is true I want it to display the name of table2's field where table2.id = table3.id but if it is false I need it to read the name of table1's name field where table1.id = table3.id. The program which will display the results is a desktop application and i could do it with some procedure or something to display them, but would be nicer if I had a SQL query to do this for me.
This: ``` SELECT CASE WHEN p THEN ( SELECT name FROM table2 t2 WHERE t2.id = t3.id ) ELSE ( SELECT name FROM table1 t1 WHERE t1.id = t3.id ) END FROM table3 t3 ``` , or this: ``` SELECT CASE WHEN p THEN t2.name ELSE t1.name END FROM table3 t3 JOIN table1 t1 ON t1.id = t3.id JOIN table1 t2 ON t2.id = t3.id ``` In systems capable of doing `HASH JOIN` (that is `Oracle`, `SQL Server`, `PostgreSQL`, but not `MySQL`), the second one is better if the boolean values are distributed evenly, i. e. there are lots of both `TRUE`'s and `FALSE`'s, and if `table3` is quite large. The first one is better if there is a skew in distribution, if there are much fewer rows in `table3` then in `table1` or `table2`, or if you are using `MySQL`. **Update:** If the majority of fields are false, the following query will probably be the best: ``` SELECT CASE WHEN p THEN ( SELECT name FROM table2 t2 WHERE t2.id = t3.id ) ELSE t1.name END AS cname FROM table3 t3 JOIN table1 t1 ON t1.id = t3.id ORDER BY cname ``` Subquery here will only be used as a fallback, and will be executed only for the rare `TRUE` values. **Update 2:** I can't check it on Firebird, but on most systems the `ORDER BY` syntax as in query above will work. If it does not, wrap the query into an inline view: ``` SELECT cname FROM ( SELECT CASE WHEN p THEN ( SELECT name FROM table2 t2 WHERE t2.id = t3.id ) ELSE t1.name END AS cname FROM table3 t3 JOIN table1 t1 ON t1.id = t3.id ) q ORDER BY cname ``` , though it may hamper performance (at least in `MySQL` it does).
you can use ``` select if(P, t1.name, t2.name) ... ```
Values from multiple tables on a row
[ "", "sql", "firebird", "" ]
I have a string containing space-delimited words. I want to reverse the letters in every word without reversing the order of the words. I would like `my string` to become `ym gnirts`.
This should work: ``` $words = explode(' ', $string); $words = array_map('strrev', $words); echo implode(' ', $words); ``` Or as a one-liner: ``` echo implode(' ', array_map('strrev', explode(' ', $string))); ```
``` echo implode(' ', array_reverse(explode(' ', strrev('my string')))); ``` This is considerably faster than reversing every string of the array after exploding the original string.
Reverse the letters in each word of a string
[ "", "php", "string", "reverse", "" ]
How can I count the number of objects of a class type within a method of that class? For that matter, how to do it outside of a class without adding the objects to a list? *I should have thought of that! Thanks! I'm gonna leave it unanswered for a little while to see if there is a better way, because I agree. I'm just sortv wrapping my head around OO. If you don't mind let me explain a little more and maybe there is a better way in general?* **I have an object class that i want to add 3 pieces of information to, but first I want to cycle through and make sure there are no other objects with any of the three pieces the same, and if there are, do something different for each case.**
The only way to accomplish what you're looking for is to keep a static list of these objects in the class itself. If you just want to see if there is an instance somewhere that hasn't been garbage collected, then you'll want to use the `WeakReference` class. For example... ``` public class MyClass { private static List<WeakReference> instances = new List<WeakReference>(); public MyClass() { instances.Add(new WeakReference(this)); } public static IList<MyClass> GetInstances() { List<MyClass> realInstances = new List<MyClass>(); List<WeakReference> toDelete = new List<WeakReference>(); foreach(WeakReference reference in instances) { if(reference.IsAlive) { realInstances.Add((MyClass)reference.Target); } else { toDelete.Add(reference); } } foreach(WeakReference reference in toDelete) instances.Remove(reference); return realInstances; } } ``` Since you're new to OO/.NET, don't let the `WeakReference` use scare you. The way garbage collection works is by reference counting. As long as some piece of code or an object has access to a particular instance (meaning it's within scope as a or as part of a local, instance, or static variable) then that object is considered alive. Once that variable falls OUT of scope, at some point after that the garbage collector can/will collect it. However, if you were to maintain a list of all references, they would never fall out of scope since they would exist as references in that list. The `WeakReference` is a special class allows you to maintain a reference to an object that the garbage collector will ignore. The `IsAlive` property indicates whether or not the `WeakReference` is pointing to a valid object that still exists. So what we do here is keep this list of `WeakReference`s that point to every instance of `MyClass` that's been created. When you want to obtain a list of them, we iterate through our `WeakReference`s and snatch out all of them that are alive. Any we find that are no longer alive are placed into another temporary list so that we can delete them from our outer list (so that the `WeakReference` class itself can be collected and our list doesn't grow huge without reason).
I'm not exactly sure what you mean. But it might be this: ``` MethodInfo methodInfo = ...; MethodBody body = methodInfo.GetMethodBody(); int count = body.LocalVariables.Count(variable => variable.LocalType == typeof(DesiredType)); ``` Another possibility: The profiler in Team Suite (and maybe others) can tell you: * The number of objects of type T allocated in every method * The number of *bytes* allocated in each method Edit: Due to the lack of a "`dup` *n*" or "`swap` n, n+1" IL instruction, the compiler is forced to generate locals you might not expect (ones you didn't explicitly declare). The compiler is also free to remove locals where possible when optimization is on.
Count number of objects of class type within class method
[ "", "c#", "class", "object", "count", "methods", "" ]
EDIT: Firefox 2 windows XP **Steps to reproduce problem:** **Firefox 2** and visit: <http://resopollution.com/rentfox/html/property_setup.html> Begin Typing and pressing [enter key] to create new lines After about 10 [enter key] presses you'll notice the screen shaking **How this happened** This began happening after I installed a plugin for jQuery. It's located here: <http://resopollution.com/rentfox/html//js/textarea.js> It makes it so the textarea is expandable as I type, depending on how many lines there are in the text area, up to a max-height value which can be specified in CSS. I tried disabling the 'setHeight' function within this plugin (the only thing that changes height dynamically) but I still saw the screen shaking. **When I think the problem might be** Firefox thinks that the screen just got larger, and compensates by putting in a scrollbar on the right side of the body document. However, it realizes that in fact the page didn't get larger, and removes the scrollbar, causing the shaking. I have no idea where in the code that makes Firefox think this way... Appreciate any help.
You can either force a scrollbar: <http://css-tricks.com/eliminate-jumps-in-horizontal-centering-by-forcing-a-scroll-bar/> or hide the overflow of the div and try to get rid of the scrollbar, try overflow: hidden instead of auto in the div propertySetup
Can't reproduce, works fine here in Mac OSX + Firefox 3.5.
Firefox textarea typing causing screen shaking (firefox2 winXP)
[ "", "javascript", "jquery", "firefox", "textarea", "" ]
I am trying to use a relative path to locate an executable file within a Java class instead of hard-coded lines which worked, but using something like: `final static String directory = "../../../ggla/samples/obj/linux_x86"` fails... what is the proper way of using a relative path in Java?
The most likely explanation is that your current directory is not where you think that it is. You can inspect the system property of user.dir to see what the base path of the application is, or you can do something like this: ``` System.out.println(new File(".").getCanonicalPath()); ``` right before you use that relative path to debug where your relative reference starts.
Use System.out.println(System.getProperty("user.dir")); to see where your current directory is. You can then use relative paths from this address. Alternatively if you dont need to update the file you are trying to read obtain it from the classpath using getResourceAsStream("filename"); Karl
Using relative directory path in Java
[ "", "java", "file", "" ]
I am using VSTS 2008 + C# + .Net 2.0. When executing the following statement, there is FormatException thrown from String.Format statement, any ideas what is wrong? Here is where to get the template.html I am using. I want to format this part m={0} in template.html. ``` string template = String.Empty; using (StreamReader textFile = new StreamReader("template.html")) { template = textFile.ReadToEnd(); String.Format(template, "video.wmv"); } ``` <http://www.mediafire.com/download.php?u4myvhbmmzg> EDIT 1: Here is the content for my template.html, ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <!-- saved from url=(0014)about:internet --> <head> <title>Silverlight Project Test Page </title> <style type="text/css"> html, body { height: 100%; overflow: auto; } body { padding: 0; margin: 0; } #silverlightControlHost { height: 100%; } </style> <script type="text/javascript"> function onSilverlightError(sender, args) { var appSource = ""; if (sender != null && sender != 0) { appSource = sender.getHost().Source; } var errorType = args.ErrorType; var iErrorCode = args.ErrorCode; var errMsg = "Unhandled Error in Silverlight 2 Application " + appSource + "\n" ; errMsg += "Code: "+ iErrorCode + " \n"; errMsg += "Category: " + errorType + " \n"; errMsg += "Message: " + args.ErrorMessage + " \n"; if (errorType == "ParserError") { errMsg += "File: " + args.xamlFile + " \n"; errMsg += "Line: " + args.lineNumber + " \n"; errMsg += "Position: " + args.charPosition + " \n"; } else if (errorType == "RuntimeError") { if (args.lineNumber != 0) { errMsg += "Line: " + args.lineNumber + " \n"; errMsg += "Position: " + args.charPosition + " \n"; } errMsg += "MethodName: " + args.methodName + " \n"; } throw new Error(errMsg); } </script> </head> <body> <!-- Runtime errors from Silverlight will be displayed here. This will contain debugging information and should be removed or hidden when debugging is completed --> <div id='errorLocation' style="font-size: small;color: Gray;"></div> <div id="silverlightControlHost"> <object data="data:application/x-silverlight," type="application/x-silverlight-2" width="500" height="240"> <param name="source" value="ClientBin/VideoPlayer.xap"/> <param name="onerror" value="onSilverlightError" /> <param name="background" value="white" /> <param name="initParams" value="cc=true,markers=true,m={0}" /> <a href="http://go.microsoft.com/fwlink/?LinkID=115261" style="text-decoration: none;"> <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/> </a> </object> <iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe> </div> </body> </html> ``` thanks in avdance, George
At a guess, the html contains javascript or another source of braces (`{` and `}`) which would all need doubling (to `{{` and `}}`) to be usable with `string.Format`. I expect a different (more obvious) token may be in order, i.e. `%%FILENAME%%`. Then use either regex or `string.Replace`. If you have a single tag, `string.Replace` is fine; if you have lots, there are tricks with regex and `MatchEvaluator` that may be helpful - [like so](https://stackoverflow.com/questions/1102300#1102324) but with a different regex pattern. --- Update after the example html added: I would definitely use a different token; at the most basic level: ``` <param name="initParams" value="cc=true,markers=true,m=%%FILENAME%%" /> ``` and ``` template = template.Replace("%%FILENAME%%", "video.wmv"); ```
Your template contains `{` and `}` characters which need to be escaped, otherwise they confuse `String.Format`. Escape them using `{{` and `}}`. Alternatively, use a different mechanism such as `String.Replace`.
String.Format exception when format string contains "{"
[ "", "c#", ".net", "string.format", "" ]
So can you overload operators to handle objects in multiple classes (specifically private members.) For example if I wanted == to check if a private member in Class A is equal to objects in a vector in Class B. For example: ``` bool Book::operator==(const Book& check){ return(((ISBN1 == check.ISBN1) && (ISBN2 == check.ISBN2) && (ISBN3 == check.ISBN3) && (ISBN4 == check.ISBN4)) || (title_ == check.title_));} ``` Everything in that overload is part of the Book class, however what if I wanted to do something like this. ``` if(*this == bookcheckout[i]) ``` with bookcheckout being part of a Library class. The == would fail in trying to compare title\_ to a title\_ stored in a vector of the Library class. It's odd because I have the program doing the exact same thing in two different places, but in one place it's working and in the other it isn't. Answered: had to have the function that the operator was in be a member function of the same class that the operator was a member function of
If you make operator friend or member of one class, it will be able to access its private members. To access privates of both, operator will have to be free standing friend of both. That is a bit unwieldy, so consider making public interface for interesting things instead. (suppressed all puns about accessing private parts of multiple entities) Here is how you can make a very friendly operator, but again, this is not a good solution. (didn't compile the code) ``` class B; class A { friend bool operator==(const A&, const B&); private: int private_; }; class B { friend bool operator==(const A&, const B&); private: int private_; }; bool operator==(const A& a, const B& b) { return a.private_ == b.private_; } class B; ``` This is a better way -- just make public getters and use them in operator. ``` class A { public: int GetPrivate() const { return private_; } private: int private_; }; class B { public: int GetPrivate() const { return private_; } private: int private_; }; bool operator==(const A& a, const B& b) { return a.GetPrivate() == b.GetPrivate(); } ``` You also can make operator to be part of one of the classes, if you need privates from it alone. Read up on operator overloading syntax for more.
You don't specify the type of bookcheckout, so I can't be sure, but I think that your operator== will work without change. For instance, if the code is: ``` class Library { public: const Book & operator[] (int i); }; Library bookcheckout; ``` Then your if statement will call the operator== you have without a problem.
Operator Overloading for Objects in Multiple Classes
[ "", "c++", "" ]
I wrote a simple hello world program to test the JDK installation. I can compile from Vim using: ``` :!javac Desktop\HelloWorld.java ``` That works just fine but when I try to run the program using: ``` :!java Desktop\HelloWorld ``` it gives me this error: > C:\Windows\system32\cmd.exe /c java "Desktop\HelloWorld" > Exception in thread "main" java.lang.NoClassDefFoundError: Desktop\HelloWorld (w > rong name: HelloWorld) > at java.lang.ClassLoader.defineClass1(Native Method) > at java.lang.ClassLoader.defineClass(Unknown Source) > at java.security.SecureClassLoader.defineClass(Unknown Source) > at java.net.URLClassLoader.defineClass(Unknown Source) > at java.net.URLClassLoader.access$000(Unknown Source) > at java.net.URLClassLoader$1.run(Unknown Source) > at java.security.AccessController.doPrivileged(Native Method) > at java.net.URLClassLoader.findClass(Unknown Source) > at java.lang.ClassLoader.loadClass(Unknown Source) > at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) > at java.lang.ClassLoader.loadClass(Unknown Source) > at java.lang.ClassLoader.loadClassInternal(Unknown Source) > Could not find the main class: Desktop\HelloWorld. Program will exit. The program works just fine from the normal command line. ``` C:\Users\Casey\Desktop>java HelloWorld Hello world! ``` How can I execute the program from Vim without having to switch to the standard cmd?
`java` doesn't take a file name as its first non-option argument. Instead it should specify the main class name (with `.`s between package names and class name, if there were any packages other than a default). Use `-classpath` to specify where to load classes from (with directories separated with your OS's directory separator character (`\`)). ``` :!java -classpath Desktop HelloWorld ```
The culprit is this line: java Desktop\HelloWorld The argument that you are passing to the "java" program is a class name, not a path name. If the file is in package "Desktop.HelloWorld" (directory Desktop\HelloWorld), then you need to execute it with: java Desktop.HelloWorld (all of the above assumes that you are in the folder directly above the "Desktop" folder).
Vim: running java from vim command gives error
[ "", "java", "windows", "vim", "command-line", "windows-vista", "" ]
OK I have a static class that has two static members, a string and a boolean. A public static method assigns values to these members based upon the state of parameters passed in. A private static method is then called that processes the static members. The problem is that while the boolean keeps the value it is set to in the public function, the string does not; it defaults back to its initialised value. Why is this? Simplified code is below. ``` static class MessageHandler { private static String m_messageToSend = String.Empty; private static bool m_requiresACK = false; public static void Send(String message) { //formatting etc (actual method sets more fields) m_messageToSend = message; m_requiresACK = true; Send(); } private void static Send() { SendMessageDelegate sendDelegate = DoSend; //At this point m_requiresACK remains true but m_messageToSend does not //hold value of message; it is empty. IAsyncResult ar = sendDelegate.BeginInvoke(m_messageToSend, m_requiresACK); //rest of function } } //some other class MessageHandler.Send("Hello"); ```
The thread "unsafetyness" of this code could be the problem, since other threads could call Send(string) while your thread is currently in the middle of the same method. I would suggest the following rewrite of the Message class: ``` static class Message { public static void Send(String message) { Send(message, true); } private void static Send(string messageToSend, bool requiresACK) { SendMessageDelegate sendDelegate = DoSend; IAsyncResult ar = sendDelegate.BeginInvoke(messageToSend, requiresACK); //rest of function } } ```
This is most likely due to another thread calling ``` Message.Send(""); ``` or your AppDomain is being unloaded. Without more information it is hard to say for sure.
Static member does not keep assigned value
[ "", "c#", "static-members", "" ]
I am creating a conversion class for frequency, and I wanted to allow my team to be able to add additional conversions when they are needed. ``` Frequency myFrequency = new Frequency(100, MHz); double value = myFrequency.InKhz(); ``` The source code for the class will not be include in future projects, so I will either have to have the class be a partial class or the additional conversions will need to be extensions. An example would be adding a conversion to GHz ``` myFrequency.InGHz() ``` Which is the best way to proceed with this? Update: After reading Randolpho's answer I am going with the extension method approach. As time allows the extensions will get rolled into the base code, but I didn't want to make the other team members wait for updated assemblies and this allows them to move on to the next task a little faster.
Partial classes will not work unless you have the original source. If you are denying the developers access to that source, their only alternative is to use extension methods. That said, you probably just want to have a process to update the library with new additions; it looks like they'll be rare.
Extension methods all the way. It will not limit you, and partial methods can only be used within the assembly, while extension methods can be declared anywhere.
Conversion Class Extensiblity (Extension Methods vs Parital Class)
[ "", "c#", "extension-methods", "partial-classes", "" ]
I'm working on getting some legacy code under unit tests and sometimes the only way to sense an existing program behavior is from the console output. I see lots of examples online for how to redirect stdout to another file in C++, but is there a way I can redirect it to an in-memory stream so my tests don't have to rely on the disk? I'd like to get anything that the legacy code sends to stdout into a std::string so I can easily .find on the output. **Edit** The legacy code is so bad that it users a mixture of `cout << ..` and `printf`. Here is what I have so far: ``` void TestSuite::setUp(void) { oldStdoutBuf = std::cout.rdbuf(); std::cout.rdbuf(consoleOutput.rdbuf()); } void TestSuite::tearDown(void) { std::cout.rdbuf(oldStdoutBuf); } ``` The problem is that this does **not** capture output using printf. I would like something that gets both. Any ideas?
[`std::stringstream`](http://en.cppreference.com/w/cpp/io/basic_stringstream) may be what you're looking for. **UPDATE** Alright, this is a bit of hack, but maybe you could do this to grab the printf output: ``` char huge_string_buf[MASSIVE_SIZE]; freopen("NUL", "a", stdout); setbuf(stdout, huge_string_buffer); ``` Note you should use "/dev/null" for linux instead of "NUL". That will rapidly start to fill up huge\_string\_buffer. If you want to be able to continue redirecting output after the buffer is full you'll have to call fflush(), otherwise it will throw an error. See [`std::setbuf`](http://en.cppreference.com/w/cpp/io/c/setbuf) for more info.
You can use `freopen(..., stdout)` and then dump the file into memory or a `std::string`.
Redirect both cout and stdout to a string in C++ for Unit Testing
[ "", "c++", "unit-testing", "stdout", "legacy-code", "" ]
I know it is really annoying to read this topic again. Before you start diggin into the code, one solution could be that I don't get prototypes and objects in JavaScript. But at this point i think, i do. The problem is: **How to clone an JavaScript Class (created with prototypes), so that the “cloned” Class remains untouched when extending and executing afterwards?** ``` function clone(obj){ if(obj == null || typeof(obj) != 'object') return obj; var temp = new obj.constructor(); for(var key in obj) temp[key] = clone(obj[key]); return temp; } var FOO = function() { var myBAR = clone(BAR); myBAR.prototype = jQuery.extend(true, myBAR.prototype, this); // deep cloning twice and extending with this console.log("FOO:", this.name); new myBAR(); }; FOO.prototype = { name: "FOO" }; var BAR = function() { console.log("BAR:", this.name); }; BAR.prototype = { name: "BAR" }; new FOO(); // returns FOO: FOO and BAR: FOO new BAR(); // returns BAR: FOO should return BAR: BAR ``` If i've got it right, the second call of `new BAR()` (after `new FOO()`) should return `BAR: BAR` not `BAR: FOO` as at the moment. One possible solution for this problem is an complete rewrite of the `clone` function in something like this: ``` function clone(obj) { return eval("("+obj.toString()+")"); // the same as eval(uneval(obj)); } ``` But this approach has an BIG downside, you can't pass any dynamically created objects. Any ideas?
I just wanted to show anyone my solution for the problem above. ``` function cloneClass (func) { if(typeof func == 'function') { var prototype = {}; for (var prop in func.prototype) { prototype[prop] = func.prototype[prop]; }; var Class = function() { var _this = this; var constructor = function() { func.apply(_this, arguments); }; constructor.prototype = _this; for (var property in func) { if(property != "prototype") { constructor[property] = func[property]; } }; return constructor; }; Class.prototype = prototype; return new Class(); } return func; }; ``` Try to dig into it to understand how this is working. Does anyone can see any problems with this implementation, memory leaks etc.?
The problem is how you are cloning the 'prototype' The following line ``` myBAR.prototype = jQuery.extend(true, myBAR.prototype, this); // deep cloning ``` You are not only cloning the 'prototype', you are also cloning the 'name' property. If you replace above line with ``` myBAR.prototype = jQuery.extend(true, myBAR.prototype, this.prototype); // deep cloning ``` Your code will now return ``` new FOO(); // returns FOO:FOO and BAR:BAR new BAR(); // returns BAR:BAR ```
Cloning JavaScript Objects. Again :(
[ "", "javascript", "jquery", "clone", "extend", "" ]
I am in the concept phase of an application that is going to have a lot of Audio/Video input and output. I want to do it in Java; but somehow am not fully convinced yet. What do you think? How bad could it be? And any advices? Why I am thinking Java: 1. It's the language I'm most comfortable with. 2. Easier cross platform migration would be a bonus. 3. Cannot afford commercial platforms (like .NET) or not good enough in other free alternatives (like Python) 4. I'm also slightly inclined towards C++/Qt; but that would take more time for me as I'm not great in that and I am a bit worried about maintainability.
C++ would be the first choice because of performance concerns often present in Audio/Video processing as well as the range of available libraries for video/audio. You do make a good point about being familiar with Java. If you are pressed for time, this is even more important. However if you can spare some time for learning, C++ would be well worth it. Regarding .NET: The .NET SDK with everything you need is [freely downloadable](http://www.microsoft.com/downloads/details.aspx?FamilyID=fe6f2099-b7b4-4f47-a244-c96d69c35dec&displaylang=en). Get hold of a free IDE such as [SharpDevelop](http://www.icsharpcode.net/OpenSource/SD/) and you are up and running. It's Visual Studio that costs money, you don't need Visual Studio to do .NET development.
If you're interested, check out [Xuggler](http://www.xuggle.com/xuggler). It exposes all the power of FFmpeg, but as a Java API that runs on Windows, Mac and Linux. The advantage is you get all the power of FFmpeg but from Java. The disadvantage is it requires the FFmpeg native DLLs/shared-libraries to be installed.
Java for a video based application: Good choice?
[ "", "java", "video", "audio", "multimedia", "jmf", "" ]
(Now that Django 1.1 is in release candidate status, it could be a good time to ask this.) I've been searing everywhere for ways to extend Django's comments app to support authenticated comments. After reading through the comments model a few times, I found that a `ForeignKey` to `User` already exists. From `django.contrib.comments.models`: ``` class Comment(BaseCommentAbstractModel): """ A user comment about some object. """ # Who posted this comment? If ``user`` is set then it was an authenticated # user; otherwise at least user_name should have been set and the comment # was posted by a non-authenticated user. user = models.ForeignKey(User, verbose_name=_('user'), blank=True, null=True, related_name="%(class)s_comments") user_name = models.CharField(_("user's name"), max_length=50, blank=True) user_email = models.EmailField(_("user's email address"), blank=True) user_url = models.URLField(_("user's URL"), blank=True) ``` **I can't seem to get my head around setting `user`.** If I use comments as is, even if I'm authenticated, it still seems to require the other fields. I'm guessing I should override the form and do it there? On top of that, if I use `user`, I should ignore the fact that `user_name`, `user_email` and `user_url` will be empty and just pull that information from a related profile model, correct? While the answers could be quite trivial in the end, I'm just surprised that it hasn't been written or even talked about.
Theju wrote an authenticated comments app — <http://thejaswi.info/tech/blog/2009/08/04/reusable-app-authenticated-comments/>
WordPress and other systems make this a no-brainer. If you're logged in, the comment form should just "do the right thing" and remove the name/email/url fields. Isn't this exactly the kind of heavy lifting a framework is supposed to do for you? Rather than dancing around with subclassing models for something that should be trivially easy, I find it simpler to build the form manually in the template and provide the hidden field values it needs. This works perfectly for sites that only accept comments from authenticated users: ``` {% if user.is_authenticated %} {% get_comment_form for [object] as form %} <form action="{% comment_form_target %}" method="POST"> {% csrf_token %} {{ form.comment }} {{ form.honeypot }} {{ form.content_type }} {{ form.object_pk }} {{ form.timestamp }} {{ form.security_hash }} <input type="hidden" name="next" value="{% url [the_view] [object].id %}" /> <input type="submit" value="Add comment" id="id_submit" /> </form> {% else %} <p>Please <a href="{% url auth_login %}">log in</a> to leave a comment.</p> {% endif %} ``` Note that this will leave the honeypot field visible; you'll want to hide it in your CSS: ``` #id_honeypot { visibility:hidden; } ``` If you want to enable comments either for anonymous or authenticated users, replace the auth\_login line above with a standard call to a comment form.
Authenticated commenting in Django 1.1?
[ "", "python", "django", "comments", "" ]
Here is my object literal: ``` var obj = {key1: value1, key2: value2}; ``` How can I add field `key3` with `value3` to the object?
There are two ways to add new **properties** to an object: ``` var obj = { key1: value1, key2: value2 }; ``` ### Using dot notation: ``` obj.key3 = "value3"; ``` ### Using square bracket notation: ``` obj["key3"] = "value3"; ``` The first form is used when you know the name of the property. The second form is used when the name of the property is dynamically determined. Like in this example: ``` var getProperty = function (propertyName) { return obj[propertyName]; }; getProperty("key1"); getProperty("key2"); getProperty("key3"); ``` --- A *real* JavaScript array can be constructed using either: ### The Array literal notation: ``` var arr = []; ``` ### The Array constructor notation: ``` var arr = new Array(); ```
# Year 2017 answer: `Object.assign()` [Object.assign(dest, src1, src2, ...)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) merges objects. It overwrites `dest` with properties and values of (however many) source objects, then returns `dest`. > The `Object.assign()` method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object. ### Live example ``` var obj = {key1: "value1", key2: "value2"}; Object.assign(obj, {key3: "value3"}); document.body.innerHTML = JSON.stringify(obj); ``` # Year 2018 answer: object spread operator `{...}` ``` obj = {...obj, ...pair, scalar}; ``` From [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator#Spread_in_object_literals): > It copies own enumerable properties from a provided object onto a new object. > > Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than [`Object.assign()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign). > > Note that [`Object.assign()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) triggers [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) whereas spread syntax doesn’t. ### Live example It works in current Chrome and current Firefox. They say it doesn’t work in current Edge. ``` var obj = {key1: "value1", key2: "value2"}; var pair = {key3: "value3"}; var scalar = "value4" obj = {...obj, ...pair, scalar}; document.body.innerHTML = JSON.stringify(obj); ``` # Year 2019 answer ~~[Object assignment operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Object_assignment) `+=`:~~ ``` obj += {key3: "value3"}; ``` Oops... I got carried away. Smuggling information from the future is illegal. Duly obscured!
How can I add a key/value pair to a JavaScript object?
[ "", "javascript", "object-literal", "" ]
The radio buttons in Zend Framework are displayed in a column (one option per line). How can I remove the br tag from the markup so that all radio options stay in one line? My decorators are: ``` private $radioDecorators = array( 'Label', 'ViewHelper', array(array('data' => 'HtmlTag'), array('tag' => 'div', 'class' => 'radio')), array(array('row' => 'HtmlTag'), array('tag' => 'li')), ); ```
You need to call the setSeparator method on the Zend\_Form\_Element\_Radio object, passing it ''. Here's an example from [here](http://zendguru.wordpress.com/2009/03/05/zend-framework-form-working-with-radio-buttons/): ``` <?php class CustomForm extends Zend_Form { public function init() { $this->setMethod('post'); $this->setAction('user/process'); $gender = new Zend_Form_Element_Radio('gender'); $gender->setLabel('Gender:') ->addMultiOptions(array( 'male' => 'Male', 'female' => 'Female' )) ->setSeparator(''); } } ```
use options as follows ``` array("listsep" => ' ') ``` This will make radio seperation by ' '
Display Zend_Form_Element_Radio on one line
[ "", "php", "zend-framework", "zend-form", "radio-button", "" ]
Consider this problem: Using Javascript/E4X, in a non-browser usage scenario (a Javascript HL7 integration engine), there is a variable holding an XML snippet that could have multiple repeating nodes. ``` <pets> <pet type="dog">Barney</pet> <pet type="cat">Socks</pet> </pets> ``` **Question**: How to get the count of the number of pet nodes in Javascript/E4X ? EDIT: To clarify, this question should be around [E4X (ECMAScript for XML)](http://en.wikipedia.org/wiki/E4x). Apologies to those who answered without this information. I should have researched & posted this info beforehand.
Use an E4X XML object to build an XMLList of your 'pet' nodes. You can then call the length method on the XMLList. ``` //<pets> // <pet type="dog">Barney</pet> // <pet type="cat">Socks</pet> //</pets> // initialized to some XML resembling your example var petsXML = new XML(""); // build XMLList var petList = petsXML['pet']; // alternative syntax // var petList = petsXML.pet; // how many pet nodes are under a given pets node? var length = petList.length(); ```
I'd say... use jQuery! ``` var count = 0; $(xmlDoc).find("pet").each(function() { count++; // do stuff with attributes here if necessary. // var pet = $(this); // var myPetType = pet.attr("type"); }; }); ``` EDIT: Can't use jquery... ok, let's do it in regular javascript :( ``` var pets= xmlDoc.getElementsByTagName("pet"); for ( var i = 0; i < pets.length ; i++ ) { count++; // var petObj = { // pets[i].getAttribute("type") // }; } ```
Count the number of nodes in an XML snippet using Javascript/E4X
[ "", "javascript", "xml", "e4x", "mirth", "" ]
What is the use of AsyncCallback and why should we use it?
When the `async` method finish the processing, `AsyncCallback` method is automatically called, where post processing statements can be executed. With this technique there is no need to poll or wait for the `async` thread to complete. Here's some more explanation on `Async` Callback usage: **Callback Model:** The callback model requires that we specify a method to callback on and include any state that we need in the callback method to complete the call. The callback model can be seen in the following example: ``` static byte[] buffer = new byte[100]; static void TestCallbackAPM() { string filename = System.IO.Path.Combine (System.Environment.CurrentDirectory, "mfc71.pdb"); FileStream strm = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous); // Make the asynchronous call IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(CompleteRead), strm); } ``` In this model, we are creating a new `AsyncCallback` delegate, specifying a method to call (on another thread) when the operation is complete. Additionally, we are specifying some object that we might need as the state of the call. For this example, we are sending the stream object in because we will need to call `EndRead` and close the stream. The method that we create to be called at the end of the call would look something like this: ``` static void CompleteRead(IAsyncResult result) { Console.WriteLine("Read Completed"); FileStream strm = (FileStream) result.AsyncState; // Finished, so we can call EndRead and it will return without blocking int numBytes = strm.EndRead(result); // Don't forget to close the stream strm.Close(); Console.WriteLine("Read {0} Bytes", numBytes); Console.WriteLine(BitConverter.ToString(buffer)); } ``` Other techniques are **Wait-until-done** and **Polling**. **Wait-Until-Done Model** The wait-until-done model allows you to start the asynchronous call and perform other work. Once the other work is done, you can attempt to end the call and it will block until the asynchronous call is complete. ``` // Make the asynchronous call strm.Read(buffer, 0, buffer.Length); IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length, null, null); // Do some work here while you wait // Calling EndRead will block until the Async work is complete int numBytes = strm.EndRead(result); ``` Or you can use wait handles. ``` result.AsyncWaitHandle.WaitOne(); ``` **Polling Model** The polling method is similar, with the exception that the code will poll the `IAsyncResult` to see whether it has completed. ``` // Make the asynchronous call IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length, null, null); // Poll testing to see if complete while (!result.IsCompleted) { // Do more work here if the call isn't complete Thread.Sleep(100); } ```
Think of it this way. You have some operations that you would like to execute in parallel. You would enable this by using threads which executes asynchronously. This is a fire and forget mechanism. But some situations call for a mechanism where you can fire and forget but need notification when the operation completes. For this, you would use an async callback. The operation is async but calls you back when the operation completes. The advantage of this is that you don't have to wait on the operation till it completes. You are free to execute other operations and hence your thread is not blocked. An example of this would be a background transfer of a large file. While the transfer is in progress, you don't really want to block the user from doing other operations. Once the transfer is complete, the process will call you back on an async method, where you can probably pop up a message box which says 'Transfer complete'.
What is AsyncCallback?
[ "", "c#", "asynchronous", "" ]
in C#,I have a double variable price with value 10215.24. I want to show the price with comma after some digits. My expected output is 10,215.24
``` myPrice.ToString("N2"); ``` depending on what you want, you may also wish to display the currency symbol: ``` myPrice.ToString("C2"); ``` (The number after the C or N indicates how many decimals should be used). (C formats the number as a currency string, which includes a currency symbol) To be completely politically correct, you can also specify the CultureInfo that should be used.
I think this should do it: ``` String.Format("{0:C}", doubleVar); ``` If you don't want the currency symbol, then just do this: ``` String.Format("{0:N2}", doubleVar); ```
C#: Formatting Price value string
[ "", "c#", "string-formatting", "" ]
I had always assumed that AJAX-driven content was invisible to search engines. (i.e. content inserted into the DOM via XMLHTTPRequest) For example, in this site, the main content is loaded via AJAX request by the browser: <http://www.trustedsource.org/query/terra.cl> ...if you view this page with **Javascript disabled**, the main content area is **blank.** However, Google cache shows the full content after the AJAX load: <http://74.125.155.132/search?q=cache:JqcT6EVDHBoJ:www.trustedsource.org/query/terra.cl+http://www.trustedsource.org/query/terra.cl&cd=1&hl=en&ct=clnk&gl=us> So, apparently search engines do index content loaded by AJAX. Questions: * Is this a new feature in search engines? Most postings on the web indicate that you have to publish duplicate static HTML content for search engines to find them. * Are there any tricks to get an AJAX-driven content to be crawled by search engines (besides creating duplicate static HTML content). * Will the AJAX-driven content be indexed if it is loaded from a separate subdomain? How about a separate domain?
Following this guide from Google, AJAX sites may be made crawlable: <http://code.google.com/intl/sv-SE/web/ajaxcrawling/docs/getting-started.html>
AJAX-driven are not crawled by search engines (or at least, not by Google). The reason you can see the page in the google cache is because in the cache, there is the full page, including .js file. So when you see the page, your browser use the google cached .js file. I don't think there is any trick to make it crawled by search engine, except using a static .html. Edit at April, 27th 2010 : Google published a way to [make AJAX crawlable](http://code.google.com/intl/fr-FR/web/ajaxcrawling/index.html "Making AJAX Application crawlable") [Google webmaster toolkit](http://www.google.com/webmasters/) might help.
Are AJAX sites crawlable by search engines?
[ "", "javascript", "ajax", "search", "seo", "xmlhttprequest", "" ]
I have a label containing some text and I want to highlight or change the color of some words in the text of the label and not all of the words. It has to be dynamic. Any suggestions? It's for c# with ASP.NET in a user control in webpart in sharepoint
On the server-side, you could just embed some Html in your Label's text (VB): ``` myLabel.Text="Some normal text <span style='color: red;'>some red text</span>" ``` That's the basic mechanism, but 'dynamic' could mean a lot of things here. If you post some more details about exactly what you're doing, I might be able to help more. One more thought: as Rob Allen pointed out, the Literal control may be a slightly better choice in this situation since it's intended to emit raw Html, whereas the Label wraps the text in a span so that the whole thing can be formatted easily. Check this out for more details: [StackOverflow: Literals versus Labels](https://stackoverflow.com/questions/510998/what-literal-control-is-used-for-in-asp-net-and-difference-between-it-and-label) For the record, depending on the situation I think a Label may actually be okay here.
For ASP.NET, wrap the words you want highlighted in a `<span>`. Then set the `<span>` style `background-color` to the colour of your choice, or use a CSS class to do so. For example, ``` <asp:Label runat="server"> <span style="background-color:Blue;">Hello</span> World </asp:Label> ``` or ``` <asp:Label runat="server" Text="<span style='background-color:Blue;'>Hello</span> World" /> ``` **EDIT:** If setting this in code behind, then you can do something like the following ``` StringBuilder builder = new StringBuilder(); builder.Append([start of text]); builder.Append("<span style=\"background-color:Blue;\">"); builder.Append([text to highlight]); builder.Append("</span>"); builder.Append([rest of text]); Label.Text = builder.ToString(); ``` If you needed to match text already in the label against some specific text then something like the following ``` string theTextToMatch = "[Text to match]"; string theText = Label.Text; int leftIndex = theText.IndexOf(theTextToMatch, StringComparison.OrdinalIgnoreCase); int rightIndex = leftIndex + theTextToMatch.Trim().Length; StringBuilder builder = new StringBuilder(); builder.Append(theText , 0, leftIndex); builder.Append("<span style=\"background-color:Blue;\">"); builder.Append(theText, leftIndex, rightIndex - leftIndex); builder.Append("</span>"); builder.Append(theText, rightIndex, theText.Length - rightIndex); Label.Text = builder.ToString(); ```
How to highlight or change the color of some words in a label dynamically at runtime?
[ "", "c#", ".net", "asp.net", "" ]
How can you detect the country of origin of the users accessing your site? I'm using Google Analytics on my site and can see that I have users coming from different regions of the world. But within my application I would like to provide some additional customization based on the country and perhaps the city. Is it possible to detect this infomation from the browser? This is a Python web application.
Grab and gunzip <http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz>, install the GeoIP-Python package (python-geoip package if you're in Debian or Ubuntu, otherwise install <http://geolite.maxmind.com/download/geoip/api/python/GeoIP-Python-1.2.4.tar.gz>), and do: ``` import GeoIP gi = GeoIP.open("GeoLiteCity.dat", GeoIP.GEOIP_INDEX_CACHE | GeoIP.GEOIP_CHECK_CACHE) print gi.record_by_name("74.125.67.100") # a www.google.com IP ``` `{'city': 'Mountain View', 'region_name': 'California', 'region': 'CA', 'area_code': 650, 'time_zone': 'America/Los_Angeles', 'longitude': -122.05740356445312, 'country_code3': 'USA', 'latitude': 37.419200897216797, 'postal_code': '94043', 'dma_code': 807, 'country_code': 'US', 'country_name': 'United States'}` The database is free (<http://geolite.maxmind.com/download/geoip/database/LICENSE.txt>). They do sell it, too; I think that just gets you more frequent updates.
Get the visitor's IP and check it with a [geolocation](http://en.wikipedia.org/wiki/Geolocation) web service (or purchase a geolocation database if you're keen to host that determination in-house).
How to detect the country and city of a user accessing your site?
[ "", "python", "web-applications", "" ]
I am trying to write a piece of code for fun using C++ templates. ``` #include <iostream> #include <vector> template <class Container> std::ostream& operator<<(std::ostream& o, const Container& container) { typename Container::const_iterator beg = container.begin(); o << "["; // 1 while(beg != container.end()) { o << " " << *beg++; // 2 } o << " ]"; // 3 return o; } int main() { std::vector<int> list; list.push_back(0); list.push_back(0); std::cout << list; return 0; } ``` ***The above code doesn't compile :)*** At 1, 2, 3 the same error is produced : **error C2593: 'operator <<' is ambiguous** All what I am trying to do is overloading the << operator to work with any container. Does that make sense ? How would that be done If possible, if not why ? EDIT :: Thanks for corrections :) 'sth' way is a good solution. I am just curious if this ambiguity -as Neil explained- would go away if we could use C++0x Concepts ?
You can restrict your operator<< to only apply to templated containers by specifying that the Container template parameter is itself templated. Since the C++ std containers also have an allocator template parameter you also have to include this as a template parameter of Container. ``` template < typename T , template<typename ELEM, typename ALLOC=std::allocator<ELEM> > class Container > std::ostream& operator<< (std::ostream& o, const Container<T>& container) { typename Container<T>::const_iterator beg = container.begin(); o << "["; // 1 while(beg != container.end()) { o << " " << *beg++; // 2 } o << " ]"; // 3 return o; } int main() { std::vector<int> list; list.push_back(0); list.push_back(0); std::cout << list; return 0; } ```
Your newly defined `operator<<` does not only match containers, but also any other types like ints and strings. That's why the compiler complains about ambiguities when it needs to find the matching `operator<<` to output `"["`. One way to work around this problem would be to rename your output function: ``` template <class Container> std::ostream& container_out(std::ostream& o, const Container &container) { // ... } ``` You can then add simple wrappers to enable `operator<<` for all the containers you want to print: ``` template<typename T> std::ostream& operator<<(std::ostream& o, const std::vector<T> &container) { return container_out(o, container); } template<typename T> std::ostream& operator<<(std::ostream& o, const std::map<T> &container) { return container_out(o, container); } ```
How could I print the contents of any container in a generic way?
[ "", "c++", "templates", "stl", "operator-overloading", "" ]
I'm trying to make a calendar page where you can click and drag to select multiple calendar days at once. Everything works fine in Google Chrome, but in Firefox, when I try to start dragging, it fails. The reason for this is that each calendar day is contained in a link (`<a></a>`). When you try to drag links in Firefox, it does its own action. Is there any way I can prevent this or work around it?
I ran into this issue, saw your thread. In my case, I handling the lower level mouse events, not click. I found that on jQuery's mousedown (<http://docs.jquery.com/Events/mousedown#fn>) I could suppress Firefox's special behavior calling event.preventDefault (<http://docs.jquery.com/Events/jQuery.Event#event.preventDefault.28.29>) on the incoming mouse event. I was calling it on other event handlers, but I suspect just mousedown() is sufficient to stop browsers from doing their custom drag behavior.
Hmmm well maybe it's kinda late for this. But if you hadn't put this topic maybe I would have never resolved this. I had the same problem so I started to draw in my head how the events is working on. The environment is this: our draggable item: ``` <div id="sender"><a href="http://www.ourlinktodestination.com">my title</a></div> ``` our droppable item: ``` <table><tr><td class="celdarec">&nbsp;</td></tr><table> ``` So here is it: ``` jQuery(document).ready(function($) { var globalEle, globalLink; $(".sender").draggable({ revert:'invalid', start:function(event, ui){ globalEle = $(this); globalLink = $(this).find("a").attr("href"); }, stop:function(event, ui){ globalEle = null; } }); $("#tablareceptora .celdarec").droppable({ accept: '.sender', hoverClass: 'drop_hover', drop: function(event, ui){ $(this).html(globalEle.html()); $(this).find("a").attr("href", globalLink); globalEle.remove(); }, tolerance: 'pointer' }); $(".sender").delegate("a", "mouseup", function(e){ e.target.href ="javascript:void(0)"; }); }); ``` (I'm using jQuery and jQuery ui from the wordpress folder so that's why the first line use "jQuery" statement instead of "$" and put this last on the handler as a parameter). 1. When you click to drag, the event.target.href is reached and filled with our link. For reasons that I can't explain (yet), even if you use preventDefault, on the mouseup event, using delegate statement, on the element passed to the droppable area, the link still redirects to it. 2. We are assuming the event is responding to the click action... "click" and that it means: Mouse down and Mouse up... but here is the thing: I used on the draggable "start" option this: ``` globalLink = $(this).find("a").attr("href"); ``` globalLink is a declared variable externally (at the beginning of the script), so when you start to drag, the link is sent to this variable. Then, on the dragable element (in my case a class called sender) you must use the delegate statement, looking for an "a" marquee on the "mouseup" event and put "#" on the target.href setting of the event passed: ``` $(".sender").delegate("a", "mouseup", function(e){ e.target.href = "javascript:void(0)"; }); ``` This will avoid any behavior that is working over the preventDefault statement (which I'm assuming is happening from the event who is evading this restriction). 3. Finally you drop your link on the "a" marquee. However if we just go and drop on the cell if you use firebug and check the code the href attribute has the "javascript:void(0)" that was passed on the mouseup event. This can answer many things, like how is the redirect behavior is fired in the drop action. Means jquery ui is working over the defaultPrevent because the redirect behavior on the droppable event, is a programmed behavior. So that's why I saved the link on the external variable, so I can reassign it on the drop event in the droppable setting: ``` $(this).find("a").attr("href", globalLink); ``` Hope this can help any another guy or girl who is in the same situation Good vibes for everyone!
JavaScript: Dragging Mouse on Links
[ "", "javascript", "jquery", "firefox", "drag-and-drop", "" ]
I was working on this carousel thing, using the [iCarousel](http://zendold.lojcomm.com.br/icarousel/example6.asp). It works pretty nicely with a few images, using MooTools. However when I added 70 pictures (around 30k each) it stopped working so nicely. Having spent some time poking around in the code of iCarousel it looked pretty decent and stable. So this got me thinking: is the problem inherent to the script (which animates divs inside an `overflow:hidden` div), MooTools, Firefox on Ubuntu or that JavaScript cannot handle too much? If so, how much is too much? I guess it's hard to say, but it would be really decent to know when JavaScript will become sluggish and unusable, preferably before starting to develop.
In addition to the other answers I will point out from hard experience that manipulating dom elements in the browser to animate them is really really slow compared to a direct drawing API like the canvas tag provides. There's a lot of overhead not only in the bridge between the javascript and the dom, but also in the browser running a content reflow routine every time some attribute is changed. There's ways around some of this such as ensuring that your animated eliments have display:absolute set in their css (Thus taking them out of the document flow, eliminating the need to reflow) and ensuring in your code that you only touch the dom when something actually needs to change. A dom document fragment can be manipulated, and then inserted into the dom, and that's much faster than manipulating a part of the dom that is displayed on the screen. And also that event handling stuff other people mentioned. Javascript scaling? Yes, yes it can. The browser DOM scaling? No perhaps not. Maybe future browsers will be better at this.
Looking at the sample code, I noticed something like this being done: ``` $("thumb0").addEvent("click", function(event){new Event(event).stop();ex6Carousel.goTo(0)}); $("thumb1").addEvent("click", function(event){new Event(event).stop();ex6Carousel.goTo(1)}); $("thumb2").addEvent("click", function(event){new Event(event).stop();ex6Carousel.goTo(2)}); $("thumb3").addEvent("click", function(event){new Event(event).stop();ex6Carousel.goTo(3)}); $("thumb4").addEvent("click", function(event){new Event(event).stop();ex6Carousel.goTo(4)}); $("thumb5").addEvent("click", function(event){new Event(event).stop();ex6Carousel.goTo(5)}); $("thumb6").addEvent("click", function(event){new Event(event).stop();ex6Carousel.goTo(6)}); ``` If you have 70 images (and thus 70 thumbnails, I'm assuming) this would be wiring 70 events to the DOM. This is really not necessary and is most likely the cause of the "sluggish" behavior you are observing. I suggest you read up on event delegation and why it is a good thing. :) If you are using jQuery, this is easily done by using the [`live`](http://docs.jquery.com/Events/live) function, I would imagine mootools would have something similar. If it doesn't, though, it is fairly easy to rig up. I have discussed event delegation in the past [here](https://stackoverflow.com/questions/905883/is-binding-events-in-jquery-very-expensive-or-very-inexpensive) and [here](https://stackoverflow.com/questions/663842/jquery-unbinding-events-speed-increases).
How well does JavaScript scale?
[ "", "javascript", "jquery", "browser", "mootools", "performance", "" ]
I'm working on a C# project that uses System.Data.OleDb.OleDbCommand class to create and alter tables in an MS Access DB. I generate the SQL statement, pass it to the object, then call the ExecuteNonQuery function. I was able to figure out the proper MS Access SQL syntax to create columns of the following Access data types: ``` AutoNumber: ALTER TABLE table-name ADD COLUMN column-name COUNTER|AUTOINCREMENT Currency: ALTER TABLE table-name ADD COLUMN column-name MONEY Date/Time: ALTER TABLE table-name ADD COLUMN column-name DATE Memo: ALTER TABLE table-name ADD COLUMN column-name MEMO|TEXT Number: ALTER TABLE table-name ADD COLUMN column-name NUMBER OLE Object: ALTER TABLE table-name ADD COLUMN column-name OLEOBJECT Text: ALTER TABLE table-name ADD COLUMN column-name CHARACTER Yes/No: ALTER TABLE table-name ADD COLUMN column-name BIT ``` The only type I haven't figured out how to create is Hyperlink. Does anyone know the syntax for that one?
There is no real concept in sql of a datatype of hyperlink. You would store the url as you would any text and then when you're using it in your application you would create the hyperlink on that end.
This is a case where you can't use DDL but must use DAO. What you're looking for is the .Attributes property of the DAO Field type. In VBA, this code does the trick (you'll have to figure out how to do this with DAO in C#): ``` Dim tdf As DAO.TableDef Dim fld As DAO.Field Set tdf = CurrentDB.TableDefs("MyTable") Set fld = tdf.CreateField("Hyperlink", dbMemo) ' dbMemo = 12 fld.Attributes = dbHyperlinkField ' 32768 tdf.Fields.Append fld Set fld = Nothing Set tdf = Nothing ``` If you check the data type of this field in Access: ``` CurrentDB.TableDefs("MyTable").Fields("Hyperlink").Type ``` it returns 12, which is equal to the VBA global constant dbMemo (that's how I figured out how to do it, i.e., created a Hyperlink field in the Access UI, then checked its datatype). The value for dbHyperlinkField is 32768, but cannot be assigned directly as a data type -- it is instead a sub-attribute of a memo field. This is a case of Access extending Jet by using a custom attribute for it to work with the data differently than the limited number of Jet data types. It's also clear that the Hyperlink field type is only relevant if you're using the data from Access itself. If you're using some other application to work with the data, you're gaining nothing at all from using a hyperlink data field. Also, I'm with those who recommend *not* using a field of type Hyperlink because I've tried it and it's just a pain in the ass. Also, given that it's really a memo field, it's subject to all the problems that come with memo fields. That is, the data is not actually stored with the data table -- all that's stored in the main record is a pointer to the data page where the real data is stored, and those pointers are one of the frailer parts of Jet. Memos are worth that risk, because when you need to store more than 255 characters, you need to do it. I can't see that there's any significant functionality added by the Access-specific Hyperlink field type that it's worth the trouble in working with it in code or the risk that comes from the fact that it's implemented behind the scenes as a memo field.
What is the MS Access SQL syntax to create a field of type Hyperlink?
[ "", "sql", "ms-access", "types", "" ]
Consider the following example: ``` import string,cgi,time from os import curdir, sep from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class MyHandler(BaseHTTPRequestHandler): def do_GET(self): try: if self.path.endswith(".html"): f = open(curdir + sep + self.path) #self.path has /test.html #note that this potentially makes every file on your computer readable by the internet self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(f.read()) f.close() return except IOError: self.send_error(404,'File Not Found: %s' % self.path) def main(): try: server = HTTPServer(('', 80), MyHandler) print 'started httpserver...' server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down server' server.socket.close() if __name__ == '__main__': main() ``` What if I want to server a ZIP file also... how would I do that? I don't think this line would work right? ``` self.wfile.write(f.read()) ```
Pass binary as a parameter to open(). This: ``` f = open(curdir + sep + self.path, 'rb') ``` Instead of this: ``` f = open(curdir + sep + self.path) ``` UNIX doesn't distinguish between binary and text, but windows does. But if the script executes on UNIX, the "b" will just be ignored so you're safe.
Your line would work just fine. The problem would be setting the `Content-type` appropriately. You'd want to set it to `application/zip` instead of `text/html`.
How to serve any file type with Python's BaseHTTPRequestHandler
[ "", "python", "httpserver", "" ]
My app is working from the web side of things. I'd like to get the CLI working so that I can run unit tests and the such Here's what I have for a test script: ``` $pthRoot = dirname(__FILE__); define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/..')); define('APPLICATION_ENV', 'development'); define('SERVER_ROLE', 'development'); set_include_path(implode(PATH_SEPARATOR, array( realpath(APPLICATION_PATH . '/../library') . PATH_SEPARATOR . realpath($pthRoot . '/../controllers') . PATH_SEPARATOR . get_include_path() ))); date_default_timezone_set('America/Toronto'); require_once('Zend/Loader/Autoloader.php'); $autoloader = Zend_Loader_Autoloader::getInstance(); require '../bootstrap.php'; require_once 'Zend/Application.php'; $application = new Zend_Application( APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini' ); $_SERVER['SERVER_ROLE'] = 'development'; $bootstrap = $application->getBootstrap(); $bootstrap->runScript(); $db = Zend_Registry::get('db'); $sql = "select * from settings"; print_r($db->fetchAll($sql)); ``` Unfortunately, I get an error at the get('db') line. PHP Fatal error: Uncaught exception 'Zend\_Db\_Adapter\_Exception' with message 'The mysql driver is not currently installed' According to phpinfo from the command line, the mysql driver is running. What am I missing? Thanks in advance.
If you are using a MySQL Adapter with Zend Framework, you have two possibilities (I quote [the doc](http://framework.zend.com/manual/en/zend.db.html#zend.db.adapter)) : * MySQL, using the **pdo\_mysql** PHP extension * MySQL, using the **mysqli** PHP extension Which one of those are you trying to use ? If it's the first one, is the extension pdo\_mysql activated for CLI ? (you can use "php -m" to get the list of extensions that are loaded) If it's the second one, is the extension mysqli activated for CLI ? It seems none of the two adapter are using the extension *mysql* (which is quite old) ; so, if this one appears, it's probably not really relevant. With a bit of luck, it'll just be that "the right extension" is loaded in the php.ini file used for Web, and not in the one used for CLI...
You can copy the `pdo_mysql.so` extention of Zend Server to you `php-cli` extension folder and the `pdo_mysql.ini` file of Zend Server to the ini folder of `php-cli`.
Zend CLI not working
[ "", "php", "mysql", "zend-framework", "" ]
I'm trying to loop over distinct values over a dictionary list: So I have a dictionary of key value pairs . How do I get just the distinct values of string keys from the dictionary list?
``` var distinctList = mydict.Values.Distinct().ToList(); ``` Alternatively, you don't need to call ToList(): ``` foreach(var value in mydict.Values.Distinct()) { // deal with it. } ``` **Edit:** I misread your question and thought you wanted distinct values from the dictionary. The above code provides that. Keys are automatically distinct. So just use ``` foreach(var key in mydict.Keys) { // deal with it } ```
Keys are distinct in a dictionary. *By definition*. So **myDict.Keys** is a distinct list of keys.
Distinct Values in Dictionary<TKey,TValue>
[ "", "c#", ".net", "linq", "distinct", "" ]
What does another build tool targeted at Java really get me? If you use Gradle over another tool, why?
I don't use [Gradle](http://www.gradle.org/) in anger myself (just a toy project so far) *[author means they have used Gradle on only a toy project so far, not that Gradle is a toy project - see comments]*, but I'd say that the reasons one would consider using it would be because of the frustrations of Ant and Maven. In my experience Ant is often write-only (yes I know it is possible to write [beautifully modular, elegant build](http://onjava.com/pub/a/onjava/2003/12/17/ant_bestpractices.Html)s, but the fact is most people don't). For any non-trivial projects it becomes mind-bending, and takes great care to ensure that complex builds are truly portable. Its imperative nature can lead to replication of configuration between builds (though macros can help here). Maven takes the opposite approach and expects you to completely integrate with the Maven lifecycle. Experienced Ant users find this particularly jarring as Maven removes many of the freedoms you have in Ant. For example there's a [Sonatype blog](http://www.sonatype.com/people/2009/05/were-used-to-the-axe-grinding/) that enumerates many of the Maven criticisms and their responses. The Maven plugin mechanism allows for very powerful build configurations, and the inheritance model means you can define a small set of parent POMs encapsulating your build configurations for the whole enterprise and individual projects can inherit those configurations, leaving them lightweight. Maven configuration is very verbose (though Maven 3 promises to address this), and if you want to do anything that is "not the Maven way" you have to write a plugin or use the hacky Ant integration. Note I happen to like writing Maven plugins but appreciate that many will object to the effort involved. Gradle promises to hit the sweet spot between Ant and Maven. It uses [Ivy](http://en.wikipedia.org/wiki/Apache_Ivy)'s approach for dependency resolution. It allows for convention over configuration but also includes Ant tasks as first class citizens. It also wisely allows you to use existing Maven/Ivy repositories. So if you've hit and got stuck with any of the Ant/Maven pain points, it is probably worth trying Gradle out, though in my opinion it remains to be seen if you wouldn't just be trading known problems for unknown ones. The proof of the pudding is in the eating though so I would reserve judgment until the product is a little more mature and others have ironed out any kinks (they call it bleeding edge for a reason). I'll still be using it in my toy projects though, It's always good to be aware of the options.
Gradle can be used for many purposes - it's a much better Swiss army knife than Ant - but it's specifically focused on multi-project builds. First of all, Gradle is a dependency programming tool which also means it's a programming tool. With Gradle you can execute any random task in your setup and Gradle will make sure all declared dependecies are properly and timely executed. Your code can be spread across many directories in any kind of layout (tree, flat, scattered, ...). Gradle has two distinct phases: evaluation and execution. Basically, during evaluation Gradle will look for and evaluate build scripts in the directories it is supposed to look. During execution Gradle will execute tasks which have been loaded during evaluation taking into account task inter-dependencies. On top of these dependency programming features Gradle adds project and JAR dependency features by intergration with Apache Ivy. As you know Ivy is a much more powerful and much less opinionated dependency management tool than say Maven. Gradle detects dependencies between projects and between projects and JARs. Gradle works with Maven repositories (download and upload) like the iBiblio one or your own repositories but also supports and other kind of repository infrastructure you might have. In multi-project builds Gradle is both adaptable and adapts to the build's structure and architecture. You don't have to adapt your structure or architecture to your build tool as would be required with Maven. Gradle tries very hard not to get in your way, an effort Maven almost never makes. Convention is good yet so is flexibility. Gradle gives you many more features than Maven does but most importantly in many cases Gradle will offer you a painless transition path away from Maven.
Why use Gradle instead of Ant or Maven?
[ "", "java", "maven", "ant", "build-process", "gradle", "" ]
I have built Boost in Release configuration and have staged it into one folder. Now when I add Boost libraries into project and try to build it in Debug configuration - linker fails because there are no Debug versions libraries. Is there a way to make MSVC 9.0 use Release version of libraries when building Debug configuration? Of course, there is an easy soultion - build Debug version of Boost. But I am just curious.
You can do two things: * Build the debug version for boost (this is the best option). * Add debugging symbols to your release build. You can't use the release version of boost with your debug build because boost depends on the CRT, which is different in debug/release builds.
Exclude debug libs boost tries to link in (or disable with a preprocessor define, look into config.hpp) and manually include release versions. That is, you could try that if not for runtime conflict... (so that's a no)
Is it possible to instruct MSVC to use release version of Boost when compiling Debug project?
[ "", "c++", "boost", "visual-c++", "" ]
I have modified my PHP web app to add events to a Google Calendar. Currently, it adds successfully. However, now I wish to delete and edit events. This seems easy to do, except for the fact that I don't know what event URL is associated with each event. Am I supposed to set this event URL (or ID?) upon adding an event? How am I supposed to figure out what it is? I can't seem to find this information anywhere else... Thanks! EDIT: I have been using the Zend Framework for this (Gdata package)... EDIT: ``` $newIncludePath = array(); $newIncludePath[] = '../ZendGdata-1.8.4PL1/library'; $newIncludePath = implode($newIncludePath); set_include_path($newIncludePath); // load classes require_once 'Zend/Loader.php'; Zend_Loader::loadClass('Zend_Gdata'); Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); Zend_Loader::loadClass('Zend_Gdata_Calendar'); Zend_Loader::loadClass('Zend_Http_Client'); // connect to service $gcal = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; $user = "********@gmail.com"; $pass = "*****"; $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $gcal); $gcal = new Zend_Gdata_Calendar($client); // construct event object // save to server try { $event = $gcal->newEventEntry(); $event->title = $gcal->newTitle($title); $event->content = $gcal->newContent($desc); $when = $gcal->newWhen(); $when->startTime = $date; $when->endTime = $date; $event->when = array($when); $gcal->insertEvent($event); echo $event->getEditLink()->href; } catch (Zend_Gdata_App_Exception $e) { echo "Error: Unable to add event to Google Calendar" . $e->getResponse(); } ```
This is plainly documented in the Zend\_Gdata documentation: <http://framework.zend.com/manual/en/zend.gdata.calendar.html#zend.gdata.calendar.deleting_events> ``` // Option 1: Events can be deleted directly $event->delete(); ``` or ``` // Option 2: Events can be deleted supplying the edit URL of the event // to the calendar service, if known $service->delete($event->getEditLink()->href); ``` It sounds like you need the latter. **Edit:** Get the edit link from your $event. It's shown in the code above: ``` $event->getEditLink()->href; ``` This will be available on a saved event. e.g. ``` $newEvent = $service->insertEvent($event); echo $newEvent->getEditLink()->href; ```
You could have a look at [`Zend_Gdata`](http://framework.zend.com/manual/en/zend.gdata.html) and [`Zend_Gdata_Calendar`](http://framework.zend.com/manual/en/zend.gdata.html) : those would probably help for all the hard work -- and if you don't have to spend code to communicate with Google's API, it gives you more time to develop other things ;-) And it seems it can be used outsid of the Zend FRamework : it's even available as a standalone download : <http://framework.zend.com/download/gdata> (If you really want to do it yourself, you can still try to understand how `Zend_Gdata` does it ^^ )
Google Calendar PHP - Event URL / ID? (Zend_Gdata)
[ "", "php", "events", "zend-framework", "calendar", "" ]
I'm working in a C# web service with a generic static class that takes a type. I was wondering why this does not compile: ``` Type type1 = typeof(MySnazzyType); Assert.AreEqual(0, ConnectionPool_Accessor<type1>._pool.Count); ``` It gives this error: > The type or namespace name 'type1' could not be found (are you missing a using directive or an assembly reference?) And ReSharper, when I hover over `type1` in that second line of code, says "Type or namespace name expected". Well, `type1` *is* a type! It's a variable of type `Type`! It also doesn't work if I do: ``` Type type1 = typeof(MySnazzyType); Assert.AreEqual(0, ConnectionPool_Accessor<typeof(type1)>._pool.Count); ``` I was hoping to assign my types to a couple of different `Type` variables and just use those in testing the different generic static classes, instead of typing out `MySnazzyType` each time. Any ideas, or am I stuck with doing: ``` Assert.AreEqual(0, ConnectionPool_Accessor<MySnazzyType>._pool.Count); ``` *Edit:* to clarify, `MySnazzyType` is *not* a generic class, nor does it inherit from a generic class. The only generic class here is `ConnectionPool_Accessor`. Thanks to Pavel's comment "Essentially, your problem is that C# is a statically typed language", I now know that Ruby has spoiled me. ;)
First of all, ReSharper is actually correct. It isn't a *type*, it's a *variable*. Granted, it's a variable that is holding the reflection object that corresponds to a type, but that isn't enough. Between the <...> brackets, you have to write the name of a type, not the name of any other identifier. You can construct generic objects through reflection, however, and access their properties, even static ones, so you should be able to rewrite the code to do that, however, have you looked at NUnit 2.5? From the latest release notes, it appears that unit test classes can now be generic, and you can specify with an attribute on the test class which types to test it with. This would allow you to write something like this (note, I have not tested this, I only looked up the names of the new attributes in the documentation): ``` [TestFixture(typeof(MySnazzyType))] [TestFixture(typeof(MyOtherSnazzyType))] public class Tests<T> { [Test] public void PoolCount_IsZero() { Assert.AreEqual(0, ConnectionPool_Accessor<T>._pool.Count); } } ```
Generic types are evaluated at *compile time*, not in *runtime*. Since it cannot be determined at runtime time what `type1` will be, this construct is not allowed. This is actually what Resharper says: `type1` is not a Type, it's a variable of the type `Type`, (just as it could be an object of the type `String`).
assign type to variable, use variable with generic static class
[ "", "c#", "generics", "types", "static-typing", "" ]
I don't have any knowledge of Java platform and I wonder which tools (and methodologies) could be used to help developing maintainable code written in Java. I know one can use: 1. Agile methodology in any environment 2. jUnit/jMock for unit testing code (similar to NUnit/Moq in .net world) 3. Checkstyle for coding standards - is this similar to StyleCop or FxCop or both? 4. I suppose you can also write layered applications in Java (like assemblies for different tiers in .net) 5. Are there any automated testing OSS/Licensed tools that are worth mentioning 6. Are there any code generators that are very popular in Java world Are there also any other popular tools/methods that a Java developer/team can use that I don't have access to in .net world? Would you suggest other tools and approaches in Java world?
In java there are a lot of frameworks. For example, you don't have to use JUnit, you could use TestNG with basically just as much tool support. There are several mocking frameworks as well. In terms of coding standards, IDEs come with that built in, as well as there being several others available (I'm most familiar with the IDE ones, so I don't know names off hand). You have Eclipse as an IDE if you want free, as well as NetBeans and for money there is IntelliJ IDEA among others. Then there are some IDEs from big vendors intended to support their specific application servers. In terms of building "assemblies" (jars, wars and ears in the java world), there are some built in tools in IDEs for one-man projects, and there is Ant or Maven for a full fledged build tool. There are many options in automated testing tools. If you mean continuous integration, there is CruiseControl that is free, and TeamCity which has no cost for low usage. In terms of code generators, in general the Java world is kind of trying to move away from them in favor of annotations, but the name that comes to mind is xdoclet. In GUI building there are a bunch of code generators strictly for building the GUI of course. That really barely scratches the surface. For example, application servers (JBoss, Oracle (they now own two with the Sun purchase) and IBM among others) are a big decision point in many Java projects (it depends what kind of project). None of the categories discussed are intended to be exhaustive, just enough to give you a jumping point of what to look into. There are many more in each category. The great thing about Java is that there are so many choices. The bad thing about Java is that there are so many choices ...
Responding to #2: Code coverage tools like [EMMA](http://emma.sourceforge.net/) are often used to evaluate the extent of current tests. Responding to #5: [Findbugs](http://findbugs.sourceforge.net/) and [PMD](http://pmd.sourceforge.net/) are extremely popular static analysis tools.
Java development standards and tools (compared to C#)
[ "", "java", "jakarta-ee", "jboss", "coding-style", "" ]
ASP.NET MVC app, close to completion, then it was decided that it needed a language switcher. It will simply be two languages: English and Japanese. They should be able to switch between the two, but if one is not selected it should choose whichever is the default language of the browser. I'm wondering what the best solution would be in this case. **First thought**, routes! So I change the routes to have a `/{l}` on the end of every route, and defaulted `l = ""`. Then, in my BaseController (every controller is based off of it), I check the l variable in the route. Each action returns a view based on the language. I wanted to simply be able to hack /ja-jp on the end of the url, and it would show the view in Japanese. It didn't quite seem to route correctly. Then, I was real bad in my views and hand coded the links... I couldn't quite get the helper to output the right links at first... and got into a bad habit of hand coding them. So, I'd have to re-code every link again - to hack the language variable on the end. **Second thought**... ok, use jQuery to append the language variable to all anchor's href. That seems overly clumsy and difficult in certain situations where hrefs are hidden until needed, etc... So... at this point I've decided to just do whatever it takes. What is the most elegant way to switch between 2 languages - without using resource files? I simply want the action to choose between 2 views, based on language. Do I rewrite every link I've got to use the Html helper and then get the routes working? Then in the BaseController just set the language to English if their is no value? Any advice is much appreciated, thank you.
I think one of the most easiest and user-friendly method is to use the domain (sub-domain actually) to identify what language it speaks. It doesn't need to change almost anything in the Html helper (those HTML.ActionLink) since it works only relatively to domain. Also, it might looks neat to user that when seeing that domain, they know exactly what language it supposed to be, and without making the url too long. All you need to do is to do something in the language switcher to work. No matter what approach, I strongly discourage using the second thought, since you can't deny (even 0.1%) people not having javascript to work to visit your japanese web site, right?
Dont put the language at the end of your route. Put it at the beginning. That makes it easy to work with different routes that might have optional parameters. The Language setting should realy only change tranlation. If your Japanese users have specific rules (prices, delivery options, etc) then you should implement language and country specifics. A country is something you find under "multi tennant application" it is not detected by the browser language. A japanese user could browse the english site and see english content in a japanes translation ``` routes.MapRoute( // Route name "LocalizedRoute", // URL with parameters ("{language}/{controller}/{action}"), // Parameter defaults new { action = "Index", language = "de" }, //Parameter constraints new { language = @"en-us|ja-jp" } ```
Building a language switcher - 2 languages only - ASP.NET MVC
[ "", "c#", "asp.net-mvc", "switch-statement", "" ]
I'm outputting files in C# and want to handle files being saved with the same name by adding brackets and a number: ``` FooBar.xml FooBar(1).xml FooBar(2).xml ... FooBar(N).xml ``` Is there a simple way to do that in .NET? And is there a special name for the `(#)` construct?
You'll just have to count up and manipulate the file names manually. The (pseudo)code below is dirty, but it's the basic algorithm. Refactor it to your needs. ``` var filenameFormat = "FooBar{0}.xml"; var filename = string.Format(filenameFormat, ""); int i = 1; while(File.Exists(filename)) filename = string.Format(filenameFormat, "(" + (i++) + ")"); return filename; ``` If you can get away with it, you could always just tack on DateTime.Now in a format of your choice. That's what we do for temporary files, anyway.
In the end I utilized the accepted answer to create an extension method that looks like this: ``` public static string GetNextFilename(this string filename) { int i = 1; string dir = Path.GetDirectoryName(filename); string file = Path.GetFileNameWithoutExtension(filename) + "{0}"; string extension = Path.GetExtension(filename); while (File.Exists(filename)) filename = Path.Combine(dir, string.Format(file, "(" + i++ + ")") + extension); return filename; } ```
Is there an easy way to add (#) to a filename when you find a duplicate filename?
[ "", "c#", ".net", "file", "file-io", "" ]
I'm learning *C++* and when I was testing the *Microsoft Visual C++ 2008 Express* and *Eclipse Ganymede*, but with the *g++* compiler as default, I've noted that a same code in *VC++* get some errors and in *g++* compile normally, without errors or warnings and execute normally, but I want to know what is the difference between *VC++* syntax and *g++* syntax? Thanks!
Please add this to Pavel's answer: If you are developing a cross platform product, use g++ ([MingW](http://www.mingw.org/)) and stick to the C++ standard. Use POSIX compliant APIs provided by MingW where the standard facilities does not serve the purpose. An executable built using MingW does not need a special runtime to be installed on the target system, but VC++ 2008 requires that. So deployment is simpler with MingW applications. An advantage of VC++ is its great IDE. The Microsoft compiler seems to perform some Windows specific optimizations as well. Still, MingW complemented with the [CodeBlocks](http://www.codeblocks.org/) IDE can give you a great, free, cross-platform C++ development environment.
Can't comment because I'm new (reputation isn't 50 yet), but here's another Stack Overflow question that deals with a similar topic: [Compiling differences in Visual C++ and \*nix environments](https://stackoverflow.com/questions/1150723/compiling-differences-in-visual-c-and-nix-enviroments)
Difference Betwen Visual C++ 2008 And g++
[ "", "c++", "visual-c++", "gcc", "g++", "eclipse-cdt", "" ]
I got a trivial issue.. and can't solve it. I have this in my view: ``` <% if (!Model.DisplayText) { %> <%= Model.MyText %> <% } %> ``` As you can see, i am using **3x** <% and %>. That just screams like bad code. But I can't seem to get this working in a single line. This throws all kinds of weird errors (such as semicolon missing, and when I add one it throws something else): ``` <% if (!Model.DisplayText) { Model.MyText } %> ``` Any idea?!
Try: ``` <%= Model.DisplayText ? "" : Model.MyText %> ``` or ``` <% if(!Model.DisplayText) Response.Write(Model.MyText); %> ```
This: ``` <%= foo %> ``` is generally equivalent to: ``` <% Response.Write(foo) %> ``` So you can write: ``` <% if (!Model.DisplayText) { Response.Write(Model.MyText); } %> ``` but I don't see what you really get from this. Your original code is fine as it is. Or you might use the ternary operator, as OrbMan suggests.
C# ASP.NET MVC: Single-Line If Clause in View?
[ "", "c#", "asp.net-mvc", "" ]
On a blog I wish to pass all of the text for a blog entry through a PHP script to process quotes and some other items into nice typographic characters. The blog text in question contains HTML, and in particular will highlight code snippets contained within `<pre><code> ... </code></pre>` blocks. The `code` blocks can appear randomly and in multiple places within the text (much like Stack Overflow!) **I do not want those code blocks processed by the typographic scripts I will be using.** *The processing itself is not the point, being able to selectively apply it is.* I have been able to write a regex to find those blocks: ``` preg_match_all('/(<pre><code>(.*?)<\/code><\/pre>)/s', $text, $matches); ``` But I am not sure what the best way is to process the rest of the text and then slot these blocks back into their correct places. Thanks for your help!
The first solution that comes to my mind looks like this : * extract all the codes * remove the codes, replacing them with a special marker, that will not be affected by your string manipulations -- that marker has to be really special (and you could verify it's not present in the input string, btw) * do your manipulations on the string * put back the codes, where there are markers now In code, it could be something like this : *(sorry, it's quite long -- and I didn't include any check ; it's up to you to add those)* ``` $str = <<<A Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sodales lacus et erat accumsan consectetur. Sed lacinia enim vitae erat suscipit fermentum. Quisque lobortis nisi et lacus imperdiet ac malesuada dui imperdiet. <pre><code>ThIs Is CoDe 1</code></pre>Donec vestibulum commodo quam rhoncus luctus. Nam vitae ipsum sed nibh dignissim condimentum. Sed ultrices fermentum dapibus. Vivamus mattis nisi nec enim convallis quis aliquet arcu accumsan. Suspendisse potenti. Nullam eget fringilla nunc. Nulla porta justo justo. Nunc consectetur egestas malesuada. Mauris ac nisi ipsum, et accumsan lorem. Quisque interdum accumsan pellentesque. Sed at felis metus. Nulla gravida tincidunt tortor, <pre><code>AnD cOdE 2</code></pre>nec aliquam tortor ultricies vel. Integer semper libero eu magna congue eget lacinia purus auctor. Nunc volutpat ultricies feugiat. Nullam id mauris eget ipsum ultricies ullamcorper non vel risus. Proin volutpat volutpat interdum. Nulla orci odio, ornare sit amet ullamcorper non, condimentum sagittis libero. <pre><code>aNd CoDe NuMbEr 3 </code></pre>Ut non justo at neque convallis luctus ultricies amet. A; var_dump($str); // Extract the codes $matches = array(); preg_match_all('#<pre><code>(.*?)</code></pre>#s', $str, $matches); var_dump($matches); // Remove the codes $str_nocode = preg_replace('#<pre><code>.*?</code></pre>#s', 'THIS_IS_A_NOCODE_MARKER', $str); var_dump($str_nocode); // Do whaterver you want with $str_nocode $str_nocode = strtoupper($str_nocode); var_dump($str_nocode); // And put back the codes : $str_codes = $str_nocode; foreach ($matches[0] as $code) { $str_codes = preg_replace('#THIS_IS_A_NOCODE_MARKER#', $code, $str_codes, 1); } var_dump($str_codes); ``` I've tried with : * code on one line, * code on 2 lines, * and code on multiple lines Note : you should really test more than I did -- but this could give you a first idea... Hope this helps :-) As a side note : generally, parsing HTML with regexes is considered bad practice, and often leads to troubles... Maybe using something like [`DOMDocument::loadHTML`](http://php.net/manual/en/domdocument.loadhtml.php) could be an idea worth having a look ?
If you're getting everything you need back from `preg_match_all()` then you could leverage `preg_split()` like so: ``` $pattern = '/(<pre><code>(.*?)<\/code><\/pre>)/s'; // get the code blocks preg_match_all($pattern, $text, $matches); $code_blocks = $matches[0]; // split up the text around the code blocks into an array $unprocessed = preg_split($pattern, $text); $processed_text = ''; foreach($unprocessed as $block) { // process the text here $processed_text .= process($block); // add the next code block if(!empty($code_blocks)) $processed_text .= array_shift($code_blocks); } // any remaining $processed_text .= implode('', $code_blocks); ``` This has the unfortunate drawback of having to do multiple `process()` calls so depending on how intensive that is and how often you do it this may not be the best solution. It is pretty clear and safe though and you don't have to add any special markers for replacement later. If your processing is doing white listing and safety type stuff then have a look at [HTMLPurifier](http://htmlpurifier.org) which can do some sophisticated filtering of HTML that may let you avoid this type of stuff altogether (don't quote me on that though).
Process a block of HTML, ignoring content within specific tags
[ "", "php", "regex", "" ]