Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
What is a use case for using a dynamic proxy? How do they relate to bytecode generation and reflection? Any recommended reading?
I highly recommend this [resource](https://web.archive.org/web/20150226062232/http://userpages.umbc.edu/~tarr/dp/lectures/DynProxies-2pp.pdf). First of all, you must understand what the proxy pattern use case. Remember that the main intent of a proxy is to control access to the target object, rather than to enhance the functionality of the target object. The access control includes synchronization, authentication, remote access (RPC), lazy instantiation (Hibernate, Mybatis), AOP (transaction). In contrast with static proxy, the dynamic proxy generates bytecode which requires Java reflection at runtime. With the dynamic approach you don't need to create the proxy class, which can lead to more convenience.
> A *dynamic proxy class* is a class that implements a list of > interfaces specified at runtime such that a method invocation through > one of the interfaces on an instance of the class will be encoded and > dispatched to another object through a uniform interface. It can be > used to create a type-safe proxy object for a list of interfaces > without requiring pre-generation of the proxy class. Dynamic proxy > classes are useful to an application or library that needs to provide > type-safe reflective dispatch of invocations on objects that present > interface APIs. [Dynamic Proxy Classes](http://docs.oracle.com/javase/8/docs/technotes/guides/reflection/proxy.html)
What are Dynamic Proxy classes and why would I use one?
[ "", "java", "design-patterns", "dynamic-proxy", "" ]
I have two executables that reference the same Class Library. In the class library I have a static variable. How can that static variable persists on the two different executables? This is how it looks: ``` public class MyClass { public static string MyVar; } ``` App 1: ``` public class MyApp1 { public void SomeMethod() { MyClass.MyVar = "hello"; } } ``` App 2: ``` public class MyApp2 { public void SomeOtherMethod() { if(MyClass.MyVar == "hello") DoSomething(); } } ```
There's nothing built-in to do this. Would you want the static variables to be persistent across invocations of the executable as well, or just while both were running at the same time? Basically you're looking at "normal" persistence mechanisms (and thinking about liveness - detecting when one process needs to reload its state). I would personally try to design around this to avoid even wanting to do it. Consider having a separate service which both apps talk to instead.
This will sound stupid. But write it to a text file on a common location & read from it when needed.
static variables of a class used in different AppDomains
[ "", "c#", "appdomain", "" ]
I am receiving the next JSON response ``` { "timetables":[ {"id":87,"content":"B","language":"English","code":"en"}, {"id":87,"content":"a","language":"Castellano","code":"es"}], "id":6, "address":"C/Maestro José" } ``` I would like to achieve the next pseudo code functionality ``` for(var i in json) { if(json[i] is Array) { // Iterate the array and do stuff } else { // Do another thing } } ``` Any idea?
There are other methods but, to my knowledge, this is the most reliable: ``` function isArray(what) { return Object.prototype.toString.call(what) === '[object Array]'; } ``` So, to apply it to your code: ``` for(var i in json) { if(isArray(json[i])) { // Iterate the array and do stuff } else { // Do another thing } } ```
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray> ``` if(Array.isArray(json[i])){ // true ... } ```
How to check if a JSON response element is an array?
[ "", "javascript", "json", "" ]
I'm using the Apache Derby embedded database for unit testing in a Maven project. Unfortunately whenever I run the test I end up with the `derby.log` file in the root of the project. The database itself is created in the `target` directory (`jdbc:derby:target/unittest-db;create=true`) so that is not a problem. After consulting the [reference guide](http://db.apache.org/derby/docs/10.2/ref/rrefattrib24612.html#rrefattrib24612) I tried setting the `logDevice` parameter on the JDBC url (`jdbc:derby:target/unittest-db;create=true;logDevice=/mylogs`) but that seems to be for a different log, hence `derby.log` still appears. Any help is much appreciated.
You can get rid of [`derby.log`](http://db.apache.org/derby/docs/dev/devguide/cdevdvlp25889.html) file by creating the following class ``` public class DerbyUtil { public static final OutputStream DEV_NULL = new OutputStream() { public void write(int b) {} }; } ``` and setting the JVM system property [`derby.stream.error.field`](http://db.apache.org/derby/docs/10.8/ref/rrefproper33027.html), for example, using the following JVM command-line argument: ``` -Dderby.stream.error.field=DerbyUtil.DEV_NULL ``` [Credit to whom it is due.](http://davidvancouvering.blogspot.com/2007/10/quiet-time-and-how-to-suppress-derbylog.html)
Derby lets you specify the name of the file to which the error log messages are written using the Java system property [`derby.stream.error.file`](http://db.apache.org/derby/docs/10.8/ref/rrefproper33027.html). The default value is 'derby.log'. To get rid of `derby.log` during the Maven surefire testing phase, I just add the property definition in the plugin configuration as follows: ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <systemProperties> <property> <name>derby.stream.error.file</name> <value>target/derby.log</value> </property> </systemProperties> </configuration> </plugin> ```
Getting rid of derby.log
[ "", "java", "maven-2", "derby", "" ]
I want to write a function that parses a (theoretically) unknown XML data structure into an equivalent PHP array. Here is my sample XML: ``` <?xml version="1.0" encoding="UTF-8"?> <content> <title>Sample Text</title> <introduction> <paragraph>This is some rudimentary text</paragraph> </introduction> <description> <paragraph>Here is some more text</paragraph> <paragraph>Even MORE text</paragraph> <sub_section> <sub_para>This is a smaller, sub paragraph</sub_para> <sub_para>This is another smaller, sub paragraph</sub_para> </sub_section> </description> </content> ``` I modified this DOM iterating function from devarticles: ``` $data = 'path/to/xmldoc.xml'; $xmlDoc = new DOMDocument(); #create a DOM element $xmlDoc->load( $data ); #load data into the element $xmlRoot = $xmlDoc->firstChild; #establish root function xml2array($node) { if ($node->hasChildNodes()) { $subNodes = $node->childNodes; foreach ($subNodes as $subNode) { #filter node types if (($subNode->nodeType != 3) || (($subNode->nodeType == 3))) { $arraydata[$subNode->nodeName]=$subNode->nodeValue; } xml2array($subNode); } } return $arraydata; } //The getNodesInfo function call $xmlarray = xml2array($xmlRoot); // print the output - with a little bit of formatting for ease of use... foreach($xmlarray as $xkey) { echo"$xkey<br/><br/>"; } ``` Now, because of the way I'm passing the elements to the array I'm overwriting any elements that share a node name (since I ideally want to give the keys the same names as their originating nodes). My recursion isn't great... However, even if I empty the brackets - the second tier of nodes are still coming in as *values* on the first tier (see the text of the description node). Anyone got any ideas how I can better construct this?
You might also want to check out XML Unserializer <http://pear.php.net/package/XML_Serializer/redirected>
You might be better off just snagging some code off the net <http://www.bin-co.com/php/scripts/xml2array/> ``` /** * xml2array() will convert the given XML text to an array in the XML structure. * Link: http://www.bin-co.com/php/scripts/xml2array/ * Arguments : $contents - The XML text * $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value. * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance. * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure. * Examples: $array = xml2array(file_get_contents('feed.xml')); * $array = xml2array(file_get_contents('feed.xml', 1, 'attribute')); */ function xml2array($contents, $get_attributes=1, $priority = 'tag') { ```
iterating over unknown XML structure with PHP (DOM)
[ "", "php", "xml", "arrays", "parsing", "loops", "" ]
In my HTML file I have linked to the JS with: ``` src="myscript.js?config=true" ``` Can my JS directly read the value of this var like this? ``` alert (config); ``` This does not work, and the FireFox Error Console says "config is not defined". How do I read the vars passed via the src attribute in the JS file? Is it this simple?
``` <script> var config=true; </script> <script src="myscript.js"></script> ``` You can't pass variables to JS the way you tried. SCRIPT tag does not create a Window object (which has a query string), and it is not server side code.
Yes, you can, but you need to know the exact script file name in the script : ``` var libFileName = 'myscript.js', scripts = document.head.getElementsByTagName("script"), i, j, src, parts, basePath, options = {}; for (i = 0; i < scripts.length; i++) { src = scripts[i].src; if (src.indexOf(libFileName) != -1) { parts = src.split('?'); basePath = parts[0].replace(libFileName, ''); if (parts[1]) { var opt = parts[1].split('&'); for (j = opt.length-1; j >= 0; --j) { var pair = opt[j].split('='); options[pair[0]] = pair[1]; } } break; } } ``` You have now an 'options' variable which has the arguments passed. I didn't test it, I changed it a little from <http://code.google.com/p/canvas-text/source/browse/trunk/canvas.text.js> where it works.
Pass vars to JavaScript via the SRC attribute
[ "", "javascript", "html", "url", "variables", "src", "" ]
My main purpose is to execute processes one by one in a round-robin fashion until one calls receive() and is blocked, so that the execution switches to the next process in the queue. There is a controller application which is coded in Java and it executes these processes(which are also Java applications) using Runtime.getRuntime().exec() and keeps the return values which are Process objects. To achieve this purpose, I need to capture the receive() calls(or their states, which is blocked) and tell them to the controller(master) application. I can go as low-level as you want if this is possible.. My first thought was to get this information from the driver and then tell it to my controller Java application. I have written a linux kernel network module which captures the send and receive operations, but AFAIK the socket.receive() function does not tell anything to the network driver. So, I think the options are to get this information from either the JVM, somehow get it from a linux command or so, or possibly through the linux kernel module? What are your suggestions?
If you want to know if your threads are blocked, or exactly what they are blocked on, you can either take a thread dump or use a tool like [jvisualvm](http://java.sun.com/javase/6/docs/technotes/tools/share/jvisualvm.html) to attach to the process and take a look (in jvisualvm you would attach to the process, take a thread dump, and then look at the activity of each thread).
Have you looked at [systemtap](http://sourceware.org/systemtap/wiki/HomePage)? Should be readily available on recent Fedora systems. Best Anders
Is it possible to know if a process is waiting in Blocked state on a Receive() call on Linux?
[ "", "java", "linux-kernel", "jvm", "blocking", "" ]
I want to start coding in Python or Ruby. Since I own a [Lego Midstorms](http://en.wikipedia.org/wiki/Lego_Robotics) kit I thought it would be nice to program against it. Are there any good translators / interpeters for the Mindstorms brick?
The nxt-python and ruby-nxt projects are remote control interfaces to the NXT. They both run on a PC and remotely control the NXT via Bluetooth or USB. If you are looking for running alternative firmware on the NXT, there are several different alternatives. Steve Hassenplug has a webpage with a comprehensive list of all of the known alternative firmware and remote control options. [NXT Software](http://www.teamhassenplug.org/NXT/NXTSoftware.html)
With python you can use [jaraco.nxt](http://pypi.python.org/pypi/jaraco.nxt) or [nxt-python](http://code.google.com/p/nxt-python/) to control the NXT robot. I don't own one so I've never used any of those. Found this example using nxt-python: ``` #!/usr/bin/env python import nxt.locator from nxt.motor import Motor, PORT_B, PORT_C def spin_around(b): m_left = Motor(b, PORT_B) m_left.update(100, 360) m_right = Motor(b, PORT_C) m_right.update(-100, 360) sock = nxt.locator.find_one_brick() if sock: spin_around(sock.connect()) sock.close() else: print 'No NXT bricks found' ``` Seems nice.
Is there any Ruby or Python interpreter for Lego Mindstorm?
[ "", "python", "ruby", "interpreter", "robotics", "lego-mindstorms", "" ]
Looking for something simple (like Smarty for PHP or erb in Rails), but that will allow nesting templates inside each other. Does App Engine have anything built-in, or will I need to look into something separate (like Velocity?)? Thanks.
If you need the templating engine for creating HTML pages (or other content that you are sending to the user directly), you could use JSP, I suppose. JSP support comes built-in with App Engine.
If you're looking at Velocity, you may also want to consider [Freemarker](http://freemarker.org/). It has a more complex, but correspondingly richer, markup language than Apache Velocity.
Is there a HTML templating engine for Google App Engine (in Java)?
[ "", "java", "html", "google-app-engine", "template-engine", "templating", "" ]
I have a .swf file I am including in my html document. I'd like to be able to play it in full screen mode. (No browser showing). Is it possible to do this using html / javascript or is this a component of the flash movie itself?
> The ActionScript that initiates full-screen mode can be called only in response to a mouse click or keypress. If it is called in other situations, it will be ignored (in ActionScript 2.0) or throw an exception (in ActionScript 3.0). <http://www.adobe.com/devnet/flashplayer/articles/full_screen_mode.html> So you cannot do this using Javascript.
No, you can't. I understand that preventing people from making annoying auto-fullscreen movies and the like sounds good, but this is really crippling... You have a whole navigation bar (standard across the site) in HTML and then for this one flash component, there's one button that's not in the bar because... because other people might do something scurrilous with it? What's the real harm in a video taking full screen unprompted? Will a user lose files? Will the computer shut down? Sometimes I think Adobe's too paranoid for their own good...
How do you make a flash movie to play full screen mode using javascript?
[ "", "javascript", "html", "flash", "" ]
Could you help me solve the following incompatibility issue between Python 2.5 and 2.6? logger.conf: ``` [loggers] keys=root,aLogger,bLogger [handlers] keys=consoleHandler [formatters] keys= [logger_root] level=NOTSET handlers=consoleHandler [logger_aLogger] level=DEBUG handlers=consoleHandler propagate=0 qualname=a [logger_bLogger] level=INFO handlers=consoleHandler propagate=0 qualname=b [handler_consoleHandler] class=StreamHandler args=(sys.stderr,) ``` module\_one.py: ``` import logging import logging.config logging.config.fileConfig('logger.conf') a_log = logging.getLogger('a.submod') b_log = logging.getLogger('b.submod') def function_one(): b_log.info("function_one() called.") ``` module\_two.py: ``` import logging import logging.config logging.config.fileConfig('logger.conf') a_log = logging.getLogger('a.submod') b_log = logging.getLogger('b.submod') def function_two(): a_log.info("function_two() called.") ``` logger.py: ``` from module_one import function_one from module_two import function_two function_one() function_two() ``` Output of calling logger.py under Ubuntu 9.04: ``` $ python2.5 logger.py $ $ python2.6 logger.py function_one() called. function_two() called. $ ```
This is a bug which was fixed between 2.5 and 2.6. The fileConfig() function is intended for one-off configuration and so should not be called more than once - however you choose to arrange this. The intended behaviour of fileConfig is to disable any loggers which are not explicitly mentioned in the configuration, and leave enabled the mentioned loggers and their children; the bug was causing the children to be disabled when they shouldn't have been. The example logger configuration mentions loggers 'a' and 'b'; after calling getLogger('a.submod') a child logger is created. The second fileConfig call wrongly disables this in Python 2.5 - in Python 2.6 the logger is not disabled as it is a child of a logger explicitly mentioned in the configuration.
I don't understand the reasons of this behavior myself but as you well stated in 2.6 it works differently. We can assume this is a bug affecting 2.5 As a workaround I suggest the following: extra\_module.py: ``` import logging import logging.config logging.config.fileConfig('logger.conf') a_log = logging.getLogger('a.submod') b_log = logging.getLogger('b.submod') ``` module\_one.py: ``` from extra_module import a_log def function_one(): a_log.info("function_one() called.") ``` module\_two.py: ``` from extra_module import b_log def function_two(): b_log.info("function_two() called.") ``` by using this scheme I was able to run logger.py on python2.5.4 with the same behavior as of 2.6
Python logging incompatibilty between 2.5 and 2.6
[ "", "python", "logging", "python-logging", "incompatibility", "" ]
I don't really understand attributes. I've read all kinds of books & posts on them, but I just don't get it. Since I don't understand them, I also don't understand how to effectively use them. 1) Can you give me a good definition of what an attribute is & what it's used for? 2) Can you give me a good code example in C# of how to make and consume a custom attribute?
Say you've got a class with a series of properties that you are going to walk through using reflection. Any that are strings may need to be validated to check they are not longer than a certain amount. You could then create a `TextLength` attribute, with a default integer constructor and integer property/field. You could then read your attribute on each string property in your class and compare the length of the property value to the number specified in the attribute. Code: ``` public class TextLengthAttribute : Attribute { private int length; public int Length { get { return length; } set { length = value; } } public TextLengthAttribute(int num) { this.length = num; } } public class MyClass { [TextLength(10)] public string Property1; [TextLength(20)] public string Property2; } public class ClassReader { public static void Main() { MyClass example = MyClass.GetTestData(); PropertyInfo[] props = typeof(MyClass).GetProperties(); foreach (PropertyInfo prop in props) { if (prop.ValueType == typeof(String) { TextLengthAttribute[] atts = (TextLengthAttribute)[]prop.GetCustomAttributes( typeof(TextLengthAttribute), false); if (prop.GetValue(example, null).ToString().Length > atts[0].Length) throw new Exception(prop.name + " was too long"); } } } } ``` Note: untested
I could give you an example but it would pale in comparison to this fine article: [Defining and Using Custom Attribute Classes in C#](http://www.devx.com/codemag/Article/16706) > The complex, component-style > development that businesses expect out > of modern software developers requires > greater design flexibility than the > design methodologies of the past. > Microsoft's .NET Framework makes > extensive use of attributes to provide > added functionality through what is > known as "declarative" programming. > Attributes enhance flexibility in > software systems because they promote > loose coupling of functionality. > Because you can create your own custom > attribute classes and then act upon > them, you can leverage the loose > coupling power of attributes for your > own purposes.
What's the best way to implement custom attributes in dotnet/.NET?
[ "", "c#", ".net", "attributes", "" ]
Using the function from: <http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx> ``` public static byte[] encryptStringToBytes_AES(string plainText, byte[] Key, byte[] IV) ``` As you can see it returns a byte array, I want to convert the byte array to a string. How can I convert it from a byte array to string and visa versa?
If you don't care how it's stored, an easy way is to use: Convert byte array into string: `Convert.ToBase64String(YourByteArray)` and Convert string into byte array: `Convert.FromBase64String(YourString)`. This will give a concise, printable ASCII representation of the byte array.
This can help you a lot, is about to converting into Hex format but can be very usefull [How do you convert Byte Array to Hexadecimal String, and vice versa?](https://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa-in-c)
How to convert a byte array to a string?
[ "", "c#", "encryption", "arrays", "aes", "rijndaelmanaged", "" ]
I want to implement a chat site with following features: 1. Direct one-on-one chat with a randomly picked stranger 2. If my conversation partner gets disconnected, I should be shifted to different stranger In short, I want to imitate <http://omegle.com/> Which language is best suited to this task? Jsp and Java? PHP? ASP? Others? Should all of the messages go through the web server, or is there a better approach?
You may want to look into [Google Web Toolkit (GWT)](http://code.google.com/webtoolkit/). Ryan Dewsbury's book ["Google Web Toolkit Applications"](http://www.gwtapps.com/) actually runs you through the process of writing a basic chat application. GWT lets you write Java code that is compiled into Javascript for AJAX applications.
I wrote an AJAX Chat tutorial years ago at: <http://www.dynamicajax.com/fr/AJAX_Driven_Web_Chat-271_290_291.html> I also did a JSON version of it too: <http://www.dynamicajax.com/fr/JSON_AJAX_Web_Chat-271_290_324.html> Those are written in PHP but the back end is really simple so you can port it to whatever language you want easily. Here's a version that I converted to ASP.NET <http://www.dynamicajax.com/fr/AJAX_Web_Chat_ASP_NET-271_290_328.html> It works pretty much like Omegle, all you need to do is setup the code to randomly select a stranger.
implementing a AJAX chat site
[ "", "java", "asp.net", "ajax", "jsp", "chat", "" ]
Suppose I have some Ant task - say javac or junit - if either task fails, I want to execute a task, but if they succeed I don't. Any idea how to do this?
In your [junit](http://ant.apache.org/manual/Tasks/junit.html) target, for example, you can set the `failureProperty`: ``` <target name="junit" depends="compile-tests" description="Runs JUnit tests"> <mkdir dir="${junit.report}"/> <junit printsummary="true" failureProperty="test.failed"> <classpath refid="test.classpath"/> <formatter type="xml"/> <test name="${test.class}" todir="${junit.report}" if="test.class"/> <batchtest fork="true" todir="${junit.report}" unless="test.class"> <fileset dir="${test.src.dir}"> <include name="**/*Test.java"/> <exclude name="**/AllTests.java"/> </fileset> </batchtest> </junit> </target> ``` Then, create a target that only runs if the `test.failed` property is set, but fails at the end: ``` <target name="otherStuff" if="test.failed"> <echo message="I'm here. Now what?"/> <fail message="JUnit test or tests failed."/> </target> ``` Finally, tie them together: ``` <target name="test" depends="junit,otherStuff"/> ``` Then just call the `test` target to run your JUnit tests. The `junit` target will run. If it fails (failure or error) the `test.failed` property will be set, and the body of the `otherStuff` target will execute. The [javac](http://ant.apache.org/manual/Tasks/javac.html) task supports `failonerror` and `errorProperty` attributes, which can be used to get similar behavior.
as mentioned from Kai: > [ant-contrib](http://ant-contrib.sourceforge.net/tasks/tasks/index.html) has a trycatch task. But you need the recent version 1.0b3. And then use ``` <trycatch> <try> ... <!-- your executions which may fail --> </try> <catch> ... <!-- execute on failure --> <throw message="xy failed" /> </catch> </trycatch> ``` The trick is to throw an error again to indicate a broken build.
How do I execute an Ant command if a task fails?
[ "", "java", "ant", "" ]
``` Callback* p = new Callback; function(p); ``` If I want to delete the callback object, when and how to delete that? If it gets deleted early, then the callback might fail with segmentation fault.
The best solution for this is to used a smart pointer. You initialize the pointer with the callback and pass it to the function. when the function or whatever process is done, the callback will be deleted automatically by the smart pointer. A good smart pointer implementation is [`boost::shared_ptr<>`](http://www.boost.org/doc/libs/1%5F39%5F0/libs/smart%5Fptr/shared%5Fptr.htm)
If the code is as trivial as you put it, meaning there's only one reference to the Callback pointer after func() is executed, I believe an auto\_ptr will suffice: ``` std::auto_ptr<Callback> p(new Callback); func(p.get()); ``` This also assures that should func() throw an exception the memory will still be freed.
When to make a object delete itself?
[ "", "c++", "oop", "memory-management", "" ]
Okay, the question might seem dumb, but I'm asking it anyways. After struggling for hours to get a Spring + BlazeDS project up and running, I discovered that I was having problems with my project as a result of not including the right dependencies for Spring etc. There were .jars missing from my WEB-INF/lib folder, yes, silly me. After a while, I managed to get all the .jar files where they belong, and it comes at a whopping 12.5MB at that, and there's more than **30** of them! Which concerns me, but it probably and hopefully shouldn't be concerned. How does Java operate in terms of these JAR files, they do take up quite a bit of hard drive space, taking into account that it's compressed and compiled source code. So that can really quickly populate a lot of RAM and in an instant. My questions are: Does Java load an entire .jar file into memory when say for instance a class in that .jar is instantiated? What about stuff that's in the .jar that never gets used. Do .jars get cached somehow, for optimized application performance? When a single .jar is loaded, I understand that the thing sits in memory and is available across multiple HTTP requests (i.e. for the lifetime of the server instance running), unlike PHP where objects are created on the fly with each request, is this assumption correct? When using Spring, I'm thinking, I had to include all those fiddly .jars, wouldn't I just be better off just using native Java, with say at least and ORM solution like Hibernate? So far, Spring just took extra time configuring, extra hard drive space, extra memory, cpu consumption, so I'm concerned that the framework is going to cost too much application performance just to get for example, IoC implemented with my BlazeDS server. There still has to come ORM, a unit testing framework and bits and pieces here and there. It's just so easy to bloat up a project quickly and irresponsibly easily. Where do I draw the line?
> "Does Java load an entire .jar file > into memory when say for instance a > class in that .jar is instantiated? > What about stuff that's in the .jar > that never gets used." No, the class loader loads each .class file as it is needed. > "Do .jars get cached somehow, for > optimized application performance?" JARs are just like DLLs (except for the details about linking versus class loading): They're just compressed libraries of .class files. They aren't cached: .class files are loaded into perm space as needed. > "When a single .jar is loaded, I > understand that the thing sits in > memory and is available across > multiple HTTP requests (i.e. for the > lifetime of the server instance > running), unlike PHP where objects are > created on the fly with each request, > is this assumption correct?" When your app server loads a .class into perm space, it's available as long as the server is up and running. > "When using Spring, I'm thinking, I > had to include all those fiddly .jars, > wouldn't I just be better off just > using native Java, with say at least > and ORM solution like Hibernate?" Not if you think that using Spring is buying you something. If you don't think the cost/benefit analysis favors you, by all means don't use Spring. But it doesn't sound like you're doing a good analysis if dependencies are deterring you. > "So far, Spring just took extra time > configuring, extra hard drive space, > extra memory, cpu consumption, so I'm > concerned that the framework is going > to cost too much application > performance just to get for example, > IoC implemented with my BlazeDS > server." You have no idea what the performance penalty is for using Spring. Measure it if you think it's a problem. My bet is that your application code or database schema will be the biggest problem. > "There still has to come ORM, a unit > testing framework and bits and pieces > here and there. It's just so easy to > bloat up a project quickly and > irresponsibly easily." Why irresponsibly? > "Where do I draw the line?" By all means, write your own. Do it all from scratch. You'll have a better idea of what a framework is buying for you and what the real costs are when you're done. I'll add this: The folks at Spring write some of the best code around. Better than anything that you or I will write. You choose any framework because you believe that you'll get a lift from using code that has been rigorously engineered, has a wider audience, has been tested more thoroughly. and is better by virtually every measure than what you'd write yourself. I would not let the (admittedly) large number of dependencies deter me from using it. When I deploy on an app server and allocate 256 MB of RAM to that JVM, I certainly don't care much if the perm space consumes 10% of that total - until I measure that it's a problem. I think what's really going on is that you'd rather write PHP instead of Java. It's a fair thought, because a lot of people think that using dynamic languages can offer value over Java. The majority of sites are still written in PHP, so your skepticism is justified. I'd recommend prototyping a use case or two with and without Spring and using PHP. You'll have a better sense of what works for you after that.
The classloader should only load the classes it needs and they stay memory-resident. Don't worry about 12 MB. RAM is cheap. The objects you create (in a large application) will use far more memory than the classes that get loaded. So in short, don't worry about it. :) There is a good article on IBM DeveloperWorks with the title "Demystifying class loading problems, Part 1: An introduction to class loading and debugging tools" Additional point -- When it comes down to cost, Developer Time costs way more than the hardware does, so if Spring/Hibernate/WhateverTool helps you the developer build the application faster and easier, it is well worth the cost of whatever RAM is being used.
JAR files, don't they just bloat and slow Java down?
[ "", "java", "spring", "" ]
I'm working on an app which takes in a raw binary message (very simple, first byte is the message type, rest is payload), and then does something with it. The thing I'm trying to accomplish is making sure that the networking service is abstracted away from the rest of the app, to allow for modifying the protocol now and then without affecting the rest of the application too much. The context of the application is a very simple client-server game, for which I am doing the client work now. I'm kinda struggling now though. I need to find an elegant way to just throw a connection into some sort of translator/adapter service, which returns pretty objects (I think). Those objects will be thrown in a queue awaiting consumption by the rest of the app. The problem I'm facing is more or less this construct (pseudo code): Let's assume each message is the 20 bytes, so I can deal with calling this function for each 20 bytes: ``` public Message GetMessage(byte[] buffer) { switch(buffer[0]) { case 1: return Message1(...); case 2: return Message2(...); ..... case n: return MessageN(...); } } ``` Obviously, I'll use an enum or constants for the case, but that's not the thing that's bugging me. Here's the thing. I think I've got about 50 message types, which would mean I'll get a switch statement with 50 cases. I can't really think of a proper way to cut this up into smaller pieces, which will result in a huge, error prone method. I was wondering if there's any patterns to make this easier, as I couldn't find any. Thanks for the input in advance!
Well, there are certainly many ways. The standard one is to store functions in a dictionary. In functional languages you would write something like ``` import MyProtocol handler = { mListFirmware : listFirmwareVersions, mLoadFirmware : startLoadingFirmwareVersion, mLoadFirmwareBl: loadFirmwareVersionBlock, ... } ... try { handler[message[0]](message[1:]) } catch (NotInTheDictionary e) { # complain ... } ``` I'm not sure what's your version of C/C++/C#. If you can't put functions there, then put pointers to functions. If some of your functions are very small, in some languages you can put then right there with `lambda`: ``` ... mLoadFirmware : (lambda (m): start_load(m[1:3]); do_threads()), ... ``` There are more optimizations that I would do. See, for every message you have a constant and a function name. You don't have to repeat, though: ``` Messages = new Array() def listFirmwareVersions(m): ... Messages.add(Name_Of_This_Method(), This_Method) # it's possible to get name of current function in Python or C# ... # how to send send_message(Messages.lookup(listFirmwareVersions), ...) ... # how to receive try { Messages[message[0]](message[1:]) ... ``` But if you want to be philosophically correct, you can have separate classes for handlers: ``` class MessageHandler: static int message_handlers = [] int msg Array data void handler Message(a_handler): msg = message_handlers.add(this) handler = a_handler write(Stream s): s.write(msg, data) listFirmwareVersions = new MessageHandler(do_firmware) startLoadingFirmwareVersion = new MessageHandler(load_firmware) ... ... # how to send listFirmwareVersions.send(...) ... # how to receive try { message_handlers[message[0]](message[1:]) ... ```
I have some Java code which does this. Hopefully you can easily translate to C#. Essentially, I have a `messageMap` collection: ``` private final Map<Byte, Class<? extends Message>> messageMap; ``` This is a map from message IDs to their corresponding `Message` classes. I call `addMessage` once for each different message type: ``` public void addMessage(int id, Class<? extends Message> messageClass) { messageMap.put((byte) id, messageClass); } ``` Then when a message arrives I read the message ID off the wire, look up the `Message` class I need to instantiate in `messageMap`, and then use reflection to create an instance of that class. ``` Class<? extends Message> messageClass = messageMap.get(id); Message message = messageClass.newInstance(); ``` Here `newInstance()` calls the default constructor. I've used this generic message-handling code across multiple applications with different messages. Each one just has a nice, simple block of code registering the different messages like so: ``` // Messages that we can send to the client. addOutgoingMessage(0, HeartbeatMessage.class); addOutgoingMessage(1, BeginMessage .class); addOutgoingMessage(2, CancelMessage .class); // Messages that the client can send. addIgnoredMessage (0, HeartbeatMessage.class); addIncomingMessage(1, StatusMessage .class, statusMessageHandler); addIncomingMessage(2, ProgressMessage .class, progressMessageHandler); addIncomingMessage(3, OutputMessage .class, outputMessageHandler); addIncomingMessage(4, FinishedMessage .class, finishedMessageHandler); addIncomingMessage(5, CancelledMessage.class, cancelledMessageHandler); addIncomingMessage(6, ErrorMessage .class, errorMessageHandler); ```
Encapsulating a network protocol
[ "", "c#", "networking", "" ]
What is the fastest way of checking the condition ``` l + 1 < r ``` for `int l,r` in Java? `l` and `r` are not constant and I know that `l <= r`. The comparison is a stopping condition for a `while` loop in a binary search implementation. I am of course benchmarking my code, both in a separate test (searching a large array) and in the code which uses it. What I am looking for, I imagine, is some sort of a bit operation which would be faster than the present condition. But I don't know.
I think that's probably as fast as it's going to get. That'll reduce to very simple bytecode, and the JIT (just-in-time compiler) will probably reduce that to a very simple native implementation. (Unrelated: interesting to see a 'quant dev' use Java btw. Doesn't happen that often)
This kind of micro-optimization is almost always a bad idea; your performance for such a small bit will be entirely dependent on how the hotspot compiler optimizes your code, and subtle cache effects having to do with the surrounding code.
Fastest way of checking the condition l+1<r for int l,r in Java
[ "", "java", "performance", "integer", "" ]
I've tried to pass an initialization list {...} to a constructor and it didn't work. When I instead declared it in a method local variable (int[]) it worked flawlessly. Why is that? ``` public class QuickSort { int[] a; public QuickSort(int[] a) { this.a = a; } public static void main(String[] args) { // ################### // ### WORKS ## // ################### int[] a = {8,12,79,12,50,44,8,0,7,289,1}; QuickSort sort = new QuickSort(a); // ################### // ### DOESN'T WORK ## // ################### //QuickSort sort = new QuickSort({8,12,79,12,50,44,8,0,7,289,1}); } } ```
When declaring an `int[]` and assigning `{1, 2, 3}` the compiler knows you want to create an `int[]` as it's spelled out right there. In the latter case where you stick the array directly into the method call you would have to use ``` QuickSort sort = new QuickSort(new int[] {8,12,79,12,50,44,8,0,7,289,1}); ``` to tell the compiler what your array is.
The `{}` construct is called an array initializer, and it is used to initialize an array in Java. (Reference: [Section 10.6: Array Initializers](http://java.sun.com/docs/books/jls/third_edition/html/arrays.html#10.6) from [The Java Language Specification, Third Edition](http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html).) The reason why passing `{1, 2, 3}` itself is not valid is because there is no type information associated with the initializer. Therefore, one must let the compiler know the type of the array is by writing `new Type[]`, where the `Type` is the type for which the array is made for. The following are all valid use of the array initializer: * `new String[] {"Hello, "World"}` * `new Character[] {'A', 'B'}` * `new Runnable[] {new Runnable() {public void run() {}}, new Runnable() {public void run() {}}` As can be seen, this notation can be used for many data types, so it's not something that is specific for integers. As for: ``` int[] a = {1, 2, 3}; ``` The reason why the above is valid is because the type information is provided to the compiler in the variable type declaration, which in this case is `int[]`. What the above is implying is the following: ``` int[] a = new int[] {1, 2, 3}; ``` Now, if we have `new int[] {1, 2, 3}`, we are able to create a new `int[]` array in place, so that can be handled as any other `int[]` array would -- it's just that it doesn't have a variable name associated with it. Therefore, the array created by `new int[] {1, 2, 3}` can be sent into an method or constructor that takes a `int[]` as its argument: ``` new Quicksort(new int[] {1, 2, 3}); // This will work. ```
Why passing {a, b, c} to a method doesn't work?
[ "", "java", "arrays", "syntax", "array-initialization", "" ]
I'm trying to run a process as a different user that has Administrator privilege in 2 different computers running Vista and their UAC enabled but in one of them I get a Win32Exception that says "The directory name is invalid" Can anyone tell me what is wrong with my code? ``` var myFile = "D:\\SomeFolder\\MyExecutable.exe"; var workingFolder = "D:\\SomeFolder"; var pInfo = new System.Diagnostics.ProcessStartInfo(); pInfo.FileName = myFile; pInfo.WorkingDirectory = workingFolder; pInfo.Arguments = myArgs; pInfo.LoadUserProfile = true; pInfo.UseShellExecute = false; pInfo.UserName = {UserAccount}; pInfo.Password = {SecureStringPassword}; pInfo.Domain = "."; System.Diagnostics.Process.Start(pInfo); ``` **UPDATE** The application that executes the above code has requireAdministrator execution level. I even set the working folder to **"Path.GetDirectoryName(myFile)"** and **"New System.IO.FileInfo(myFile).DirectoryName"**
It is because the path length of the file exceeds 255 characters.
You need to specify the `WorkingDirectory` property of ProcessStartInfo`. From [Win32Exception error code 267 "The directory name is invalid"](http://bitterolives.blogspot.tw/2008/08/win32exception-error-code-267-directory.html): > I'm currently working on an "Automated Run As" tool. Its goal is > helping admins which, like me, have to give users a means to execute > one or two programs as Administrator and would like to do so without > having to surrender an admin's password. > > So, I'm developing on Vista and I just whipped up a small proof of > concept prototype, that'd run calc.exe as a different user, using > ProcessStartInfo and Process. This worked fine when I executed it as > myself (a rather pointless exercise, I must admit), but when I created > a new user and tried to run it as him, I stumbled upon a > Win32Exception complaining that the directory name is invalid, native > error code 267. I was instsantly baffled, as I knew of no supplied > directory name that could be invalid. I then tested the code on an XP > machine and it worked! > > I started googling on it to no avail, many reports of that error but > no conclusive solution, or on different contexts. Finally, after a > while it dawned on me, I wasn't specifying the WorkingDirectory > property of the ProcessStartInfo class, as soon as I added the lines > > FileInfo fileInfo = new FileInfo(path); startInfo.WorkingDirectory = > fileInfo.DirectoryName; > > To my code, it was allowed to run code as different than logged in > user. ...
Win32Exception: The directory name is invalid
[ "", "c#", "processstartinfo", "win32exception", "" ]
i am creating an empty div in the javascript DOM. but when i call some function on it, for example, ``` var hover = document.createElement("div"); hover.className = "hover"; overlay.appendChild(hover); hover.onClick = alert("hi"); ``` the onClick function isn't working. Instead it displays an alert as soon as it reaches the div creation part of the script. What am i doing wrong?
Try [addEventHandler & attachEvent](http://www.quirksmode.org/js/events_advanced.html) to attach event to an element : ``` if (hover.addEventListener) { // addEventHandler Sample : hover.addEventListener('click',function () { alert("hi"); },false); } else if (hover.attachEvent) { // attachEvent sample : hover.attachEvent('onclick',function () { alert("hi"); }); } else { hover.onclick = function () { alert("hi"); }; } ```
You need to put the onclick in a function, something like this: ``` hover.onclick = function() { alert('hi!'); } ```
empty div not getting recognised in javascript
[ "", "javascript", "dom", "" ]
I know this does not work, however does anyone have a way of making it work? ``` object obj = new object(); MyType typObj = new MyType(); obj = typObj; Type objType = typObj.GetType(); List<objType> list = new List<objType>(); list.add((objType) obj); ``` EDIT: Here is the current code: [http://github.com/vimae/Nisme/blob/4aa18943214a7fd4ec6585384d167b10f0f81029/Lala.API/XmlParser.cs](http://github.com/vimae/Nisme/blob/4aa18943214a7fd4ec6585384d167b10f0f81029/Lala.API/XmlParser.cs "Github.com") The method I'm attempting to streamline is SingleNodeCollection As you can see, it currently uses so hacked together reflection methods.
It seems you're missing an obvious solution: ``` object obj = new object(); MyType typObj = new MyType(); obj = typObj; List<MyType> list = new List<MyType>(); list.Add((MyType) obj); ``` If you really need the dynamic route, then you could do something like this: ``` object obj = new object(); MyType typObj = new MyType(); obj = typObj; Type objType = typObj.GetType(); Type listType = typeof(List<>); Type creatableList = listType.MakeGenericType(objType); object list = Activator.CreateInstance(creatableList); MethodInfo mi = creatableList.GetMethod("Add"); mi.Invoke(list, new object[] {obj}); ```
You need reflection: ``` constructor = typeof (MyType).GetConstructor () // doing this from memory, the typeof might be wrong, I'm sure someone will edit it typObj = (MyType) constructor.Invoke () ``` It can also be done for generics but that is a bit trickier.
Dynamic typing in C#
[ "", "c#", "dynamic-typing", "" ]
I am developing a script in php to manage my rapidshare accounts (for learning purposes), i wanted to know how can we login remotely and get accounts details on my site, something that api does, the details like traffic left, expiry date, etc.
Uncertain what exactly your question is, but it probably helps to take a look at the [Rapidshare](http://rapidshare.com/dev.html) API. Additionally you probably want to make yourself familiar with the following functions/ components: fopen and curl to use the api/load the site. To get specific parameters out of the content I suggest using ereg or the xml functionality.
With PHP you could use either [Curl](https://www.php.net/curl), [PHPSimpleHTMLDomParser](http://simplehtmldom.sourceforge.net/), [Snoopy](http://sourceforge.net/projects/snoopy/), or [phpQuery](http://code.google.com/p/phpquery/) to grab the contents from the remote page. Be mindful that some websites require a user\_agent, in which case you could setup one through ini\_set prior to running your script.
get values of elements from another site (rapidshare)
[ "", "php", "" ]
I get the following error when going through the WCF tutorial. HTTP could not register URL <http://+:8000/ServiceModelSamples/Service/>. Your process does not have access rights to this namespace (see <http://go.microsoft.com/fwlink/?LinkId=70353> for details). Is this something caused by a restriction on Windows 7?
The issue is that the URL is being blocked from being created by Windows. Steps to fix: Run command prompt as an administrator. Add the URL to the ACL ``` netsh http add urlacl url=http://+:8000/ServiceModelSamples/Service user=mylocaluser ```
If you are running via the IDE, running as administrator should help. To do this locate the Visual Studio 2008/10 application icon, right click it and select "Run as administrator"
WCF ServiceHost access rights
[ "", "c#", "wcf", "windows-7", "" ]
**Situation:** a user clicks on a link, the server gets the request and starts processing it. In the meanwhile, the user clicks on another link, the server gets the new request while processing the 1st one. What happens? On the client side we only see the webpage from the 2nd request, but is the process from the 1st request killed on the server when receiving the 2nd one? And is it managed by the server or the language (Apache or PHP)?
Depends. If the browser does not drop the connection to server, it'll have absolutely no idea that the client has navigated elsewhere. If it does drop the connection, it's up to the Web server to choose to detect it and abort the processing thread or not. Either case, this is the nature of statelessness of HTTP. You shouldn't rely on anything in this regard.
Both requests get served (if the browser did send the second one). You would only see the second page, but if you'll look into access\_log you'll surely notice two requests. That's how HTTP works.
Handling web requests on server side
[ "", "php", "apache", "http", "" ]
OK, I've tried but I just don't get it. I have two classes `logger` and `class1`. I have a method called `logger.Write(string)` and method called `class1.Execute()`. Now in my application I want to have `logger.Write(class1.ToString())` run when `class1.Execute()` is called. I presume you need to add delegates and events, but I just can't get my head around this, been scratching it for a couple hours. One thing, is that the logger and the class are in different namespaces and I don't want to update the class code for either of them if possible.
Well you certainly can't do it without changing code in either class (assuming you also don't want to change everywhere that calls `class1.Execute`) - at least not without some deep code-weaving/instrumentation magic. However, you can fairly easily add an event in `Class1`: ``` public class Class1 { // TODO: Think of a better name :) public event EventHandler ExecuteCalled = delegate {}; public void Execute() { ExecuteCalled(this, EventArgs.Empty); // Do your normal stuff } } ``` The `delegate{}` bit is just to make sure that there's always at least a no-op event handler registered - it means you don't need to check for nullity. You'd then hook it up by writing: ``` Class1 class1 = new Class1(); Logger logger = new Logger(); class1.ExecuteCalled += (sender, args) => logger.Write(sender.ToString()); ``` (This is assuming you're using C# 3 so you have lambda expressions available to you - let me know if that's not the case.) If `Class1` implements an interface (say `IFoo`), you might want to write an implementation of the interface which wraps another implementation, and just logs before each call: ``` public sealed class LoggingFoo : IFoo { private readonly IFoo original; private readonly IFoo logger; public LoggingFoo(IFoo original, Logger logger) { // TODO: Check arguments for nullity this.original = original; this.logger = logger; } // Implement IFoo public void Execute() { logger.Write("Calling Execute on {0}", original); original.Execute(); } } ``` Then just use that wrapper around a "real" implementation wherever you currently just use the implementation.
Can you pass an object parameter for logger and then just call the ToString on that? The proper ToString method will be called. If you don't want to change anything in logger or class1, then you could write an extension method and call that instead of calling class1.Execute. This method would make the call to logger and then the call to class1.Execute. ``` public static ExecuteAndLog(this class1 obj) { logger.Write(obj.ToString()); obj.Execute(); } ``` And then you'd simply call obj.ExecuteAndLog();
Add an event to a class method?
[ "", "c#", "events", "delegates", "methods", "" ]
I've been working on a WPF application for a while, and the time has come to attach the CHM format help document to it. But alas! HelpProvider, the standard way to show CHM files in Winforms, has magically vanished and has no counterpart in WPF. I've been trying to use WindowsFormsHost to spawn a new control so I can actually display the help, but essentially it just grabs control of the entire UI. A little more detail: I've got a menu item that I want to, when clicked, open up the CHM file. First I set up the WindowsFormsHost... ``` host = new System.Windows.Forms.Integration.WindowsFormsHost(); helpForm = new System.Windows.Forms.Control(); host.Child = helpForm; host.Visibility = System.Windows.Visibility.Hidden; this.grid1.Children.Add(host); hp = new System.Windows.Forms.HelpProvider(); hp.HelpNamespace = "Somehelpfile.chm"; hp.SetHelpNavigator(helpForm, System.Windows.Forms.HelpNavigator.TableOfContents); ``` And then I say, voila, reveal yourself. ``` private void Help_Click(object sender, RoutedEventArgs e) { host.Visibility = Visibility.Visible; helpForm.Show(); hp.SetShowHelp(helpForm, true); } ``` I'm not really sure of where to proceed from here. When I show the helpForm, it obscures / overrides the existing UI and all I get is a gray, empty WPF window with no help file. Any takers?
Call me crazy, but couldn't you just do: ``` System.Diagnostics.Process.Start(@"C:\path-to-chm-file.chm"); ```
If you include System.Windows.Forms.dll you can also do: ``` System.Windows.Forms.Help.ShowHelp(null, @"help.chm"); ``` Also, there's an article [here](http://blogs.msdn.com/mikehillberg/archive/2007/07/26/a-context-sensitive-help-provider-in-wpf.aspx) about adding a context sensitive help system to WPF.
Using F1 Help (CHM format) With WPF
[ "", "c#", "wpf", "winforms", "interop", "chm", "" ]
I'm attempting to remove accents from characters in PHP string as the first step to making the string usable in a URL. I'm using the following code: ``` $input = "Fóø Bår"; setlocale(LC_ALL, "en_US.utf8"); $output = iconv("utf-8", "ascii//TRANSLIT", $input); print($output); ``` The output I would expect would be something like this: ``` F'oo Bar ``` However, instead of the accented characters being transliterated they are replaced with question marks: ``` F?? B?r ``` Everything I can find online indicates that setting the locale will fix this problem, however I'm already doing this. I've already checked the following details: 1. The locale I am setting is supported by the server (included in the list produced by `locale -a`) 2. The source and target encodings (UTF-8 and ASCII) are supported by the server's version of iconv (included in the list produced by `iconv -l`) 3. The input string is UTF-8 encoded (verified using PHP's `mb_check_encoding` function, as suggested in the [answer by mercator](https://stackoverflow.com/questions/1017599/how-do-i-remove-accents-from-characters-in-a-php-string/1018160#1018160)) 4. The call to `setlocale` is successful (it returns `'en_US.utf8'` rather than `FALSE`) --- ## The cause of the problem: The server is using the wrong implementation of iconv. It has the **glibc** version instead of the required **libiconv** version. > Note that the iconv function on some systems may not work as you expect. In such case, it'd be a good idea to install the GNU libiconv library. It will most likely end up with more consistent results. > *– [PHP manual's introduction to iconv](http://www.php.net/manual/en/intro.iconv.php)* Details about the iconv implementation that is used by PHP are included in the output of the `phpinfo` function. (I'm not able to re-compile PHP with the correct iconv library on the server I'm working with for this project so the answer I've accepted below is the one that was most useful for removing accents without iconv support.)
I think the problem here is that your encodings consider ä and å different symbols to 'a'. In fact, the PHP documentation for strtr offers a sample for removing accents the ugly way :( <https://www.php.net/strtr>
What about the [WordPress implementation](https://github.com/WordPress/WordPress/blob/a2693fd8602e3263b5925b9d799ddd577202167d/wp-includes/formatting.php#L1528)? ``` function remove_accents($string) { if ( !preg_match('/[\x80-\xff]/', $string) ) return $string; $chars = array( // Decompositions for Latin-1 Supplement chr(195).chr(128) => 'A', chr(195).chr(129) => 'A', chr(195).chr(130) => 'A', chr(195).chr(131) => 'A', chr(195).chr(132) => 'A', chr(195).chr(133) => 'A', chr(195).chr(135) => 'C', chr(195).chr(136) => 'E', chr(195).chr(137) => 'E', chr(195).chr(138) => 'E', chr(195).chr(139) => 'E', chr(195).chr(140) => 'I', chr(195).chr(141) => 'I', chr(195).chr(142) => 'I', chr(195).chr(143) => 'I', chr(195).chr(145) => 'N', chr(195).chr(146) => 'O', chr(195).chr(147) => 'O', chr(195).chr(148) => 'O', chr(195).chr(149) => 'O', chr(195).chr(150) => 'O', chr(195).chr(153) => 'U', chr(195).chr(154) => 'U', chr(195).chr(155) => 'U', chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y', chr(195).chr(159) => 's', chr(195).chr(160) => 'a', chr(195).chr(161) => 'a', chr(195).chr(162) => 'a', chr(195).chr(163) => 'a', chr(195).chr(164) => 'a', chr(195).chr(165) => 'a', chr(195).chr(167) => 'c', chr(195).chr(168) => 'e', chr(195).chr(169) => 'e', chr(195).chr(170) => 'e', chr(195).chr(171) => 'e', chr(195).chr(172) => 'i', chr(195).chr(173) => 'i', chr(195).chr(174) => 'i', chr(195).chr(175) => 'i', chr(195).chr(177) => 'n', chr(195).chr(178) => 'o', chr(195).chr(179) => 'o', chr(195).chr(180) => 'o', chr(195).chr(181) => 'o', chr(195).chr(182) => 'o', chr(195).chr(182) => 'o', chr(195).chr(185) => 'u', chr(195).chr(186) => 'u', chr(195).chr(187) => 'u', chr(195).chr(188) => 'u', chr(195).chr(189) => 'y', chr(195).chr(191) => 'y', // Decompositions for Latin Extended-A chr(196).chr(128) => 'A', chr(196).chr(129) => 'a', chr(196).chr(130) => 'A', chr(196).chr(131) => 'a', chr(196).chr(132) => 'A', chr(196).chr(133) => 'a', chr(196).chr(134) => 'C', chr(196).chr(135) => 'c', chr(196).chr(136) => 'C', chr(196).chr(137) => 'c', chr(196).chr(138) => 'C', chr(196).chr(139) => 'c', chr(196).chr(140) => 'C', chr(196).chr(141) => 'c', chr(196).chr(142) => 'D', chr(196).chr(143) => 'd', chr(196).chr(144) => 'D', chr(196).chr(145) => 'd', chr(196).chr(146) => 'E', chr(196).chr(147) => 'e', chr(196).chr(148) => 'E', chr(196).chr(149) => 'e', chr(196).chr(150) => 'E', chr(196).chr(151) => 'e', chr(196).chr(152) => 'E', chr(196).chr(153) => 'e', chr(196).chr(154) => 'E', chr(196).chr(155) => 'e', chr(196).chr(156) => 'G', chr(196).chr(157) => 'g', chr(196).chr(158) => 'G', chr(196).chr(159) => 'g', chr(196).chr(160) => 'G', chr(196).chr(161) => 'g', chr(196).chr(162) => 'G', chr(196).chr(163) => 'g', chr(196).chr(164) => 'H', chr(196).chr(165) => 'h', chr(196).chr(166) => 'H', chr(196).chr(167) => 'h', chr(196).chr(168) => 'I', chr(196).chr(169) => 'i', chr(196).chr(170) => 'I', chr(196).chr(171) => 'i', chr(196).chr(172) => 'I', chr(196).chr(173) => 'i', chr(196).chr(174) => 'I', chr(196).chr(175) => 'i', chr(196).chr(176) => 'I', chr(196).chr(177) => 'i', chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij', chr(196).chr(180) => 'J', chr(196).chr(181) => 'j', chr(196).chr(182) => 'K', chr(196).chr(183) => 'k', chr(196).chr(184) => 'k', chr(196).chr(185) => 'L', chr(196).chr(186) => 'l', chr(196).chr(187) => 'L', chr(196).chr(188) => 'l', chr(196).chr(189) => 'L', chr(196).chr(190) => 'l', chr(196).chr(191) => 'L', chr(197).chr(128) => 'l', chr(197).chr(129) => 'L', chr(197).chr(130) => 'l', chr(197).chr(131) => 'N', chr(197).chr(132) => 'n', chr(197).chr(133) => 'N', chr(197).chr(134) => 'n', chr(197).chr(135) => 'N', chr(197).chr(136) => 'n', chr(197).chr(137) => 'N', chr(197).chr(138) => 'n', chr(197).chr(139) => 'N', chr(197).chr(140) => 'O', chr(197).chr(141) => 'o', chr(197).chr(142) => 'O', chr(197).chr(143) => 'o', chr(197).chr(144) => 'O', chr(197).chr(145) => 'o', chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe', chr(197).chr(148) => 'R',chr(197).chr(149) => 'r', chr(197).chr(150) => 'R',chr(197).chr(151) => 'r', chr(197).chr(152) => 'R',chr(197).chr(153) => 'r', chr(197).chr(154) => 'S',chr(197).chr(155) => 's', chr(197).chr(156) => 'S',chr(197).chr(157) => 's', chr(197).chr(158) => 'S',chr(197).chr(159) => 's', chr(197).chr(160) => 'S', chr(197).chr(161) => 's', chr(197).chr(162) => 'T', chr(197).chr(163) => 't', chr(197).chr(164) => 'T', chr(197).chr(165) => 't', chr(197).chr(166) => 'T', chr(197).chr(167) => 't', chr(197).chr(168) => 'U', chr(197).chr(169) => 'u', chr(197).chr(170) => 'U', chr(197).chr(171) => 'u', chr(197).chr(172) => 'U', chr(197).chr(173) => 'u', chr(197).chr(174) => 'U', chr(197).chr(175) => 'u', chr(197).chr(176) => 'U', chr(197).chr(177) => 'u', chr(197).chr(178) => 'U', chr(197).chr(179) => 'u', chr(197).chr(180) => 'W', chr(197).chr(181) => 'w', chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y', chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z', chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z', chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z', chr(197).chr(190) => 'z', chr(197).chr(191) => 's' ); $string = strtr($string, $chars); return $string; } ``` To understand what this function does, check the conversion table: ``` À => A Á => A  => A à => A Ä => A Å => A Ç => C È => E É => E Ê => E Ë => E Ì => I Í => I Î => I Ï => I Ñ => N Ò => O Ó => O Ô => O Õ => O Ö => O Ù => U Ú => U Û => U Ü => U Ý => Y ß => s à => a á => a â => a ã => a ä => a å => a ç => c è => e é => e ê => e ë => e ì => i í => i î => i ï => i ñ => n ò => o ó => o ô => o õ => o ö => o ù => u ú => u û => u ü => u ý => y ÿ => y Ā => A ā => a Ă => A ă => a Ą => A ą => a Ć => C ć => c Ĉ => C ĉ => c Ċ => C ċ => c Č => C č => c Ď => D ď => d Đ => D đ => d Ē => E ē => e Ĕ => E ĕ => e Ė => E ė => e Ę => E ę => e Ě => E ě => e Ĝ => G ĝ => g Ğ => G ğ => g Ġ => G ġ => g Ģ => G ģ => g Ĥ => H ĥ => h Ħ => H ħ => h Ĩ => I ĩ => i Ī => I ī => i Ĭ => I ĭ => i Į => I į => i İ => I ı => i IJ => IJ ij => ij Ĵ => J ĵ => j Ķ => K ķ => k ĸ => k Ĺ => L ĺ => l Ļ => L ļ => l Ľ => L ľ => l Ŀ => L ŀ => l Ł => L ł => l Ń => N ń => n Ņ => N ņ => n Ň => N ň => n ʼn => N Ŋ => n ŋ => N Ō => O ō => o Ŏ => O ŏ => o Ő => O ő => o Œ => OE œ => oe Ŕ => R ŕ => r Ŗ => R ŗ => r Ř => R ř => r Ś => S ś => s Ŝ => S ŝ => s Ş => S ş => s Š => S š => s Ţ => T ţ => t Ť => T ť => t Ŧ => T ŧ => t Ũ => U ũ => u Ū => U ū => u Ŭ => U ŭ => u Ů => U ů => u Ű => U ű => u Ų => U ų => u Ŵ => W ŵ => w Ŷ => Y ŷ => y Ÿ => Y Ź => Z ź => z Ż => Z ż => z Ž => Z ž => z ſ => s ``` You can generate the conversion table yourself by simply iterating over the `$chars` array of the function: ``` foreach($chars as $k=>$v) { printf("%s -> %s", $k, $v); } ```
How do I remove accents from characters in a PHP string?
[ "", "php", "iconv", "" ]
On startup JGroups 2.7.0. GA writes to *System.out* a message along the lines of: ``` --------------------------------------------------------- GMS: address is 10.0.3.35:48641 (cluster=blabla) --------------------------------------------------------- ``` I want to either suppress it or redirect it using Log4j ( which the rest of the framework uses ). Ideas? --- I don't want to redirect System.out by itself since that usually causes more trouble than it's worth.
You can suppress the printing of the GMS address by setting in your XML > <pbcast.GMS print\_local\_addr="false" ...> Works on JGroups 2.5.1 as well.
This is how i managed to do print GMS string to logs. First disable ``` <pbcast.GMS print_local_addr="false"> ``` then, ``` String clusterName = channel.getClusterName(); String clusterAddress = channel.getAddressAsString(); String localAddress = channel.getProtocolStack() .dumpStats() .get("UDP") .get("local_physical_address") .toString(); StringBuilder border = new StringBuilder(); String GMS = String.format("GMS: address=%s, cluster=%s, physical address=%s", clusterAddress, clusterName, localAddress ); logger.info("{}", GMS); ``` Works with **4.2.3.Final** version.
Removing JGroups startup message : GMS
[ "", "java", "jgroups", "" ]
Is there an equivalent function to [SendMessage](http://msdn.microsoft.com/en-us/library/ms644950(VS.85).aspx) in the Mac OS?
Ironically, every method call in Objective-C is the equivalent of SendMessage. Objective-C is at heart a message passing system. So you just say: ``` [window myMessage] ``` and the myMessage routine will be executed by passing myMessage to the Window object and having it process that method... It's also possible the closer thing to what you really want to do would be to use Notifications to message between components. If you don't have the Window object around at compile time, the compiler may complain it doesn't know if Window can handle the message you are sending. For those cases you can use: ``` [window performSelector:@selector(myMessage)] ``` There are alternate versions of this call that allow passing objects as parameters.
It depends on what message you'd be sending with SendMessage(). Most events in Cocoa go through `-[NSApplication sendEvent:]` for example, or `SendEventToEventTarget()` if you wanted a lower-level version. For other messages, such as resizing, movement, etc. you would need to look at the appropriate methods of NSWindow (such as `-setFrame:animated:`) or NSApplication. Generally speaking, instead of using a funnel routine and function constants as SendMessage() does, in Cocoa you just get hold of the relevant object and call its methods.
What is the equivalent (if any) to the C++/Windows SendMessage() on the Mac?
[ "", "c++", "objective-c", "windows", "macos", "" ]
I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in [this](https://stackoverflow.com/questions/1015606/mixing-object-oriented-and-functional-programming) question, and when it was mentioned, it normally wasn't very positive. However, not many reasons were given for this (lack of pattern matching and algebraic data types were mentioned). So my question is: why isn't Python very good for functional programming? Are there more reasons than its lack of pattern matching and algebraic data types? Or are these concepts so important to functional programming that a language that doesn't support them can only be classed as a second rate functional programming language? (Keep in mind that my experience with functional programming is quite limited.)
The question you reference asks which languages promote both OO and functional programming. Python does not *promote* functional programming even though it *works* fairly well. The best argument *against* functional programming in Python is that imperative/OO use cases are carefully considered by Guido, while functional programming use cases are not. When I write imperative Python, it's one of the prettiest languages I know. When I write functional Python, it becomes as ugly and unpleasant as your average language that doesn't have a [BDFL](http://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life). Which is not to say that it's bad, just that you have to work harder than you would if you switched to a language that promotes functional programming or switched to writing OO Python. Here are the functional things I miss in Python: * [Pattern matching](http://learnyouahaskell.com/syntax-in-functions#pattern-matching) * [Tail recursion](http://book.realworldhaskell.org/read/functional-programming.html#fp.loop) * [Large library of list functions](https://hackage.haskell.org/package/base/docs/Data-List.html) * [Functional dictionary class](https://hackage.haskell.org/package/containers/docs/Data-Map.html) * [Automatic currying](http://learnyouahaskell.com/higher-order-functions#curried-functions) * [Concise way to compose functions](http://learnyouahaskell.com/higher-order-functions#composition) * Lazy lists * Simple, powerful expression syntax (Python's simple block syntax prevents Guido from adding it) --- * No pattern matching and no tail recursion mean your basic algorithms have to be written imperatively. Recursion is ugly and slow in Python. * A small list library and no functional dictionaries mean that you have to write a lot of stuff yourself. * No syntax for currying or composition means that point-free style is about as full of punctuation as explicitly passing arguments. * Iterators instead of lazy lists means that you have to know whether you want efficiency or persistence, and to scatter calls to `list` around if you want persistence. (Iterators are use-once) * Python's simple imperative syntax, along with its simple LL1 parser, mean that a better syntax for if-expressions and lambda-expressions is basically impossible. Guido likes it this way, and I think he's right.
Guido has a good explanation of this [here](http://python-history.blogspot.com/2009/04/origins-of-pythons-functional-features.html). Here's the most relevant part: > I have never considered Python to be > heavily influenced by functional > languages, no matter what people say > or think. I was much more familiar > with imperative languages such as C > and Algol 68 and although I had made > functions first-class objects, I > didn't view Python as a functional > programming language. However, earlier > on, it was clear that users wanted to > do much more with lists and functions. > > ... > > It is also worth noting that even > though I didn't envision Python as a > functional language, the introduction > of closures has been useful in the > development of many other advanced > programming features. For example, > certain aspects of new-style classes, > decorators, and other modern features > rely upon this capability. > > Lastly, even though a number of > functional programming features have > been introduced over the years, Python > still lacks certain features found in > “real” functional programming > languages. For instance, Python does > not perform certain kinds of > optimizations (e.g., tail recursion). > In general, because Python's extremely > dynamic nature, it is impossible to do > the kind of compile-time optimization > known from functional languages like > Haskell or ML. And that's fine. I pull two things out of this: 1. The language's creator doesn't really consider Python to be a functional language. Therefore, it's possible to see "functional-esque" features, but you're unlikely to see anything that is definitively functional. 2. Python's dynamic nature inhibits some of the optimizations you see in other functional languages. Granted, Lisp is just as dynamic (if not more dynamic) as Python, so this is only a partial explanation.
Why isn't Python very good for functional programming?
[ "", "python", "functional-programming", "" ]
This question is as a result of trying [Jon Skeet's](https://stackoverflow.com/users/22656/jon-skeet) answer to [this question](https://stackoverflow.com/questions/944296/). So I have the following code based in the question and answer from the above question link. ``` public abstract class DeliveryStrategy { } public class ParcelDelivery : DeliveryStrategy { } public class ShippingContainer : DeliveryStrategy { } public abstract class Order<TDelivery> where TDelivery : DeliveryStrategy { private TDelivery delivery; protected Order(TDelivery delivery) { this.delivery = delivery; } public TDelivery Delivery { get { return delivery; } set { delivery = value; } } } public class CustomerOrder : Order<ParcelDelivery> { public CustomerOrder() : base(new ParcelDelivery()) { } } public class OverseasOrder : Order<ShippingContainer> { public OverseasOrder() : base(new ShippingContainer()) { } } ``` I'm trying understand generics more to improve my skill set, so I have the question of: Now how can I use foreach to loop through a collection of "Orders"? I'm using C#2.0. Code Example of what I'm trying to do (does not compile). ``` List<Order> orders = new List<Order>(); orders.Add(new CustomerOrder()); orders.Add(new CustomerOrder()); orders.Add(new OverseasOrder()); orders.Add(new OverseasOrder()); foreach (Order order in orders) { order.Delivery.ToString(); } ``` **EDIT: Added OverseasOrder to give a better example.**
The problem here is that Order is a generic class, so `Order<T>` and `Order` is basically two distinct types. You can do this: ``` public abstract class Order { public abstract String GetDeliveryMethod(); } public abstract class Order<TDelivery> : Order where TDelivery : DeliveryStrategy { .... the rest of your class public override String GetDeliveryMethod() { return Delivery.ToString(); } } ``` Or... you can redefine Order to be non-generic, in which case you'll loose some strong typing.
The generic is where you're going wrong here. Since the types for generics are cooked up at compile time, you need to indicate what kind of Order you're making the list for with a type. It will compile if you add types as such: ``` List<Order<ParcelDelivery>> orders = new List<Order<ParcelDelivery>>(); orders.Add(new CustomerOrder()); orders.Add(new CustomerOrder()); orders.Add(new CustomerOrder()); orders.Add(new CustomerOrder()); orders.Add(new CustomerOrder()); foreach (Order<ParcelDelivery> order in orders) { order.Delivery.ToString(); } ``` Maybe this is no longer what you intended, but you're have to go about it a different way if you need to be able to set this up without predetermined types.
How do you use foreach on a base class using generics?
[ "", "c#", "generics", "inheritance", "foreach", "" ]
I saw in WCF they have the `[OperationContract(IsOneWay = true)]` attribute. But WCF seems kind of slow and heavy just to do create a nonblocking function. Ideally there would be something like static void nonblocking `MethodFoo(){}`, but I don't think that exists. What is the quickest way to create a nonblocking method call in C#? E.g. ``` class Foo { static void Main() { FireAway(); //No callback, just go away Console.WriteLine("Happens immediately"); } static void FireAway() { System.Threading.Thread.Sleep(5000); Console.WriteLine("5 seconds later"); } } ``` **NB**: Everyone reading this should think about if they actually want the method to finish. (See #2 top answer) If the method has to finish, then in some places, like an ASP.NET application, you will need to do something to block and keep the thread alive. Otherwise, this could lead to "fire-forget-but-never-actually-execute", in which case,of course, it would be simpler to write no code at all. ([A good description of how this works in ASP.NET](https://github.com/StephenCleary/AspNetBackgroundTasks))
``` ThreadPool.QueueUserWorkItem(o => FireAway()); ``` (five years later...) ``` Task.Run(() => FireAway()); ``` as pointed out by [luisperezphd](https://stackoverflow.com/users/984780/luisperezphd).
For C# 4.0 and newer, it strikes me that the best answer is now given here by Ade Miller: [Simplest way to do a fire and forget method in c# 4.0](https://stackoverflow.com/questions/5613951/simplest-way-to-do-a-fire-and-forget-method-in-c-sharp-4-0) > ``` > Task.Factory.StartNew(() => FireAway()); > ``` > > Or even... > > ``` > Task.Factory.StartNew(FireAway); > ``` > > Or... > > ``` > new Task(FireAway).Start(); > ``` > > Where `FireAway` is > > ``` > public static void FireAway() > { > // Blah... > } > ``` > > So by virtue of class and method name terseness this beats the > threadpool version by between six and nineteen characters depending on > the one you choose :) > > ``` > ThreadPool.QueueUserWorkItem(o => FireAway()); > ```
Simplest way to do a fire and forget method in C#?
[ "", "c#", ".net", "nonblocking", "" ]
Recently I posted a answer to a question that I thought was quite an easy one, The question was about issues with the lifecyle of the page in asp.net where items would only reflect the changes made after the first postback, so I suggested using ``` Response.Redirect(Request.RawUrl) ``` And almost instantly got voted down for this as (Why cause another round trip) Well I want your suggestion, is this type of thing good practise, simply practical or should never be used, please back up your answer with a little motivation its something I do from time to time and now question if I should rethink it. This is the original post [Dynamically Change User Control in ASP.Net](https://stackoverflow.com/questions/987680/dynamically-change-user-control-in-asp-net/987727#987727)
There is nothing inherently wrong with Reponse.Redirect, just in most cases it isn't required in that kind of situation. You can change the way the page is constructed by working with the lifecycle rather than against it. Then there shouldbe no need for another postback.
The ASP.Net page lifecycle provides plenty of opportunities to step in and set things up, so I don't see that it would be necessary to use `Response.Redirect` to make the client load the page twice. As an aside, using Response.Redirect with just the one argument can throw a `ThreadAbortException`, so it's often best to use the overload `Response.Redirect(string url, bool endResponse)` with the second argument set to false. This definitely applies to ASP.Net 1.0 and 1.1 (see [here](http://support.microsoft.com/kb/312629)), not sure about 2.0.
Response.Redirect bad seed or just misunderstood
[ "", "c#", "asp.net", "vb.net", "" ]
I'm evaluating some potential implementations of a complex object hierarchy model for my current project. I'm wondering if there is an xpath-style meta-language or something like this that would allow me to query these object linkages. Furthermore, I'm sure there is some very specific jargon used for the problem I am asking about - I just don't know it. The requirements: * Must be done in Java (or at least compiled to Java bytecode). * Objects will be hierarchically related to each other with n possible links. obj1->obj2->obj3->... * We need to be able to look up any object in the hierarchy based on an objects properties or its relationship to other objects. * Objects will be of the same type. * Hierarchical lookups should be able to happen at runtime. I think I could roll my own solution here, but I'm curious if someone smarter than me has already come up with something. After seeing some answers come in, I think I might need to clarify my question a bit more. Specifically, this tool would be used to traverse a set of Objects that are different versions of a parent object. For example: [Object 1 prop1="foo" prop2="bar" prop3="zoop"] ↓ Inherits from above object ↓ [Object 2 prop1="foo and something" prop2="bar" prop3="zoop"] ↓ Inherits from above object ↓ [Object 3 prop1="foo and something" prop2="bar" prop3="zoop 24"]
I believe [JXPath](http://commons.apache.org/jxpath/) should do what you want.
Are you after something like [OGNL](http://www.opensymphony.com/ognl/), [SPEL](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/ch07.html) or [Unified EL](http://java.sun.com/products/jsp/reference/techart/unifiedEL.html)?
Is there a meta-language available for Java that allows you to access object complex hierarchies?
[ "", "java", "oop", "" ]
I'm using BlazeDS to remote some Java objects that I'm consuming in a Flex application. I'm getting a type coercion error with one of my classes that I can't for the life of me figure out. I have other classes that are working fine using the same data types, and I've gone over my mapping a dozen times. I'm following all of the necessary conventions for getters and setters as far as I know... **Anyhow, my question is: how can I debug this problem?** Running the Flex app in debug mode spits out some generic errors to the console that don't really help much (TypeError: Error #1034: Type Coercion failed: cannot convert Object@5d1d809 to valueObjects.SomeClass.). I'm new to this whole AMF / Flex + Java thing, so any tips would be greatly appreciated.
These are two of the tools I use when working with BlazeDS, AMF, etc.: * **Use an HTTP proxy tool** that shows the calls between your client and server, like ***[Charles](http://www.charlesproxy.com/)*** > Charles is an HTTP proxy / HTTP > monitor / Reverse Proxy that enables a > developer to view all of the HTTP and > SSL / HTTPS traffic between their > machine and the Internet. This > includes requests, responses and the > HTTP headers (which contain the > cookies and caching information). * **Turn on the logging for BlazeDS**. Within `WEB-INF/conf/services-conf.xml`, lower the debugging level to '`debug`' like in the below snippit. The output, which is fairly detailed, will appear in `{tomcat-home}/logs/localhost.yyyy-mm-dd.log` <`target class="flex.messaging.log.ConsoleTarget" level="debug"`>
The easiest way to check on the communication between service-clients AMF messages is to use FireFox, install **FireBug** extension and add the **[AMF Explorer](https://addons.mozilla.org/en-US/firefox/addon/amf-explorer/)**. You can see the structured requests and responses.
How can I debug AMF (BlazeDS) serialization of Java objects to Actionscript?
[ "", "java", "apache-flex", "blazeds", "amf", "livecycle", "" ]
I am trying to create a file with PHP here is my code: ``` $file_to_send = 'ftp_test_from_created_file.txt'; chmod($file_to_send, 0777); $fh = fopen($file_to_send,'w'); $tsv_line = 'Hey\tThese\tAre\tTab\tSeperated\tValues'; fwrite($fh, $tsv_line); fwrite($fh, '\n'); $tsv_line = 'Hey\tThese\tAre\tToo'; fwrite($fh, $tsv_line); fclose($fh); ``` This clearly gives me an error because I am trying to set permissions on a file that does not exist yet. Although if I skip the chmod call I get an another error telling me I do not have permissions set. So either I am in a sick chicken vs egg cycle or I need to set the permissions on the containing directory...but how? it tried all of the folling: ``` chmod('../containingfolder/', 0777); chmod('../', 0777); chmod('', 0777); ``` None of which work... what should I do? Oh and by the way once I am done do I need to change the permissions back? Thanks! **UPDATE** I tried **chmod('.', 0777)** and this is the error I got: ``` Warning: chmod(): Operation not permitted ``` The only reason I am trying to make this file is so I can FTP it somewhere else, then I planned to unlink() it. So if there is a better way? Like maybe storing the file in memory to send it(don't know if thats possible)? Also I am using PHP4. Thanks!
Create a directory outside your document root which we will call `$tmpFolder` make sure that the user that the webserver is running as has read/write permissions to it. Then the following: ``` $file_to_send = $tmpFolder . '/ftp_test_from_created_file.txt'; chmod($file_to_send, 0777); $fh = fopen($file_to_send,'w'); $tsv_line = 'Hey\tThese\tAre\tTab\tSeperated\tValues'; fwrite($fh, $tsv_line); fwrite($fh, '\n'); $tsv_line = 'Hey\tThese\tAre\tToo'; fwrite($fh, $tsv_line); fclose($fh); ```
It could also be that the apache server running (if it is apache) does not have access to change the permissions on that directory. It could have root / root as user / group and apache runs on apache group or wwwuser or something else. Do a `ls -l` on the parent directory and see what user and group has access to this folder.
PHP: Setting permissions so I can write a file?
[ "", "php", "chmod", "" ]
A relation table is the common solution to representing a many-to-many (m:n) relationship. In the simplest form, it combines foreign keys referencing the two relating tables to a new composite primary key: ``` A AtoB B ---- ---- ---- *id *Aid *id data *Bid data ``` How should it be indexed to provide optimal performance in every JOIN situation? 1. clustered index over (`Aid ASC, Bid ASC`) (this is mandatory anyway, I guess) 2. option #1 plus an additional index over (`Bid ASC, Aid ASC`) 3. or option #1 plus an additional index over (`Bid ASC`) 4. any other options? Vendor-specific stuff, maybe?
I made some tests, and here is the **update:** To cover all possible cases, you'll need to have: ``` CLUSTERED INDEX (a, b) INDEX (b) ``` This will cover all `JOIN` sutiations AND `ORDER BY` Note that an index on `B` is actually sorted on `(B, A)` since it references clustered rows. As long as your `a` and `b` tables have `PRIMARY KEY`'s on id's, you **don't** need to create additional indexes to handle `ORDER BY ASC, DESC`. See the entry in my blog for more details: * [**Indexing a link table**](http://explainextended.com/2009/05/12/indexing-a-link-table)
I guess solution 2 is optimal. I'd choose the order of the clustered index by looking at the values and expecting which one has more distinct rows. That one goes first. Also it's important to have `unique` or `primary key` indexes on parent tables. Depending on DBMS, number 3 might work as good as number 2. It might or might not be smart enough to consider the values (key of clustered index) in the nonclustered index for anything other than refering the the actual row. If it can use it, then number 3 would be better.
What is the optimal indexing strategy for a relation table?
[ "", "sql", "database-design", "indexing", "" ]
I am trying to use a Maven 2 repository via SSL secured with a self-signed certificate. I followed the instructions at [HTTPS and Self-Signed Certificates in Java](http://cvs.peopleware.be/training/maven/maven2/selfSignedSslCertificates.html) but I doesn't to work. I think its because the certificate is a wild-card certificate. So I wonder if I should be doing something different to import the wild-card certificate?
The issue was not the use of a wild-card certificate after all. I had to import the CA certificate I used to sign the server certificate into the **jssecacerts** keystore rather than **cacerts**: ``` keytool -keystore %JAVA_HOME%\jre\lib\security\jssecacerts -import -file cacert.pem ```
Rather the tampering with the certificates for all java applications, generate a separate certificate file that only maven uses, and then use MAVEN\_OPTS to set the -D parameter. -Djavax.net.ssl.trustStore=/private/${ACCOUNT}/java/keystore.pks -Djavax.net.ssl.trustStorePassword=${PASSWORD} See: <https://developer.cloudbees.com/bin/view/DEV/Maven+with+untrusted+SSL+Certificates>
How do I use a Maven 2 repository protected using SSL and a wildcard/self-signed certificate?
[ "", "java", "maven-2", "ssl", "keytool", "" ]
What's the difference between using "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED" and NOLOCK? Is one better than the other?
They're the same thing, just scoped differently. NOLOCK is placed on a per table basis and `SET Transaction...` can be placed as a block.
NOLOCK is a query hint and as such only applies to the specifc table within the query in which it is specified. Setting the transaction isolation level applies to all code executed hence forth within the current connection or until it is explicitly modified. To clarify, functionally the isoloation level at work is the same however the scope which is covered may not be.
NOLOCK vs. Transaction Isolation Level
[ "", "sql", "sql-server", "transaction-isolation", "" ]
I am using the following ``` var validLogin = from P in this.DataContext.Persons where P.UserName.Equals(login) && P.Password.Equals(password) select new { P.FirstName, P.LastName, P.EmailAddress }; ``` In this now i want to know, is there any result returned by this query? How to do this.
Don't use `Count()` - use `Any()` unless you actually care about the count. You can actually simplify this a lot, because you don't use the rest of the results either: ``` bool validLogin = DataContext.Persons.Any(p => p.UserName == login && p.Password == password); ``` The nice thing about `Any()` is that whatever's processing the query can stop as soon as it's found *any* matching results - it doesn't need to keep looking for other potential matches. (`Count()` will *work* of course, it's just not as efficient, mostly because the operator itself isn't describing what you really care about as accurately.)
This should work: ``` if (validLogin.Count() > 0) { //do work } ```
Counting the result LINQ
[ "", "c#", "linq", "linq-to-sql", "" ]
I'm trying to rewrite method `paintEvent` in my programm and change it. ``` void MainWindow::paintEvent(QPaintEvent *event) { QRegion reg = this->bgPixmapHandle->rect(); QPainter painter(this); painter.setClipRegion(reg); painter.drawImage(bgPixmapHandle->rect(), bgPixmapHandle); painter.end(); } ``` Here I try to change my `bg` image. But I got an error on line: `QPainter painter(this);` > Error: Variable 'QPainter painter' is > initialized, though the type is > incomplete
Include QPainter header file. QPainter class is only forward declared in one of the Qt headers you're including in that translation unit.
``` #include <QPainter> ```
Qt - creating QPainter
[ "", "c++", "qt", "qpainter", "paintevent", "" ]
I love the abstract database API that comes with Django, I was wondering if I could use this (or something similar) to model, access, and manage my (postgres) database for my non-Django Python projects.
What you're looking for is an [object-relational mapper](http://en.wikipedia.org/wiki/Object-relational_mapping) (ORM). Django has its own, built-in. To use Django's ORM by itself: * [Using the Django ORM as a standalone component](http://jystewart.net/process/2008/02/using-the-django-orm-as-a-standalone-component/) * [Use Django ORM as standalone](http://pascal.nextrem.ch/2008/08/17/use-django-orm-as-standalone/) * [Using settings without setting DJANGO\_SETTINGS\_MODULE](http://docs.djangoproject.com/en/dev/topics/settings/#using-settings-without-setting-django-settings-module) If you want to use something else: * [What are some good Python ORM solutions?](https://stackoverflow.com/questions/53428/what-are-some-good-python-orm-solutions)
Popular stand-alone ORMs for Python: * [SQLAlchemy](http://www.sqlalchemy.org/) * [SQLObject](http://www.sqlobject.org/) * [Storm](https://storm.canonical.com/) They all support MySQL and PostgreSQL (among others).
Django-like abstract database API for non-Django projects
[ "", "python", "database", "django", "orm", "django-models", "" ]
I'm working on implementing a reflection mechanism in C++. All objects within my code are a subclass of Object(my own generic type) that contain a static member datum of type Class. ``` class Class{ public: Class(const std::string &n, Object *(*c)()); protected: std::string name; // Name for subclass Object *(*create)(); // Pointer to creation function for subclass }; ``` For any subclass of Object with a static Class member datum, I want to be able to initialize 'create' with a pointer to the constructor of that subclass.
You cannot take the address of a constructor (C++98 Standard 12.1/12 Constructors - "12.1-12 Constructors - "The address of a constructor shall not be taken.") Your best bet is to have a factory function/method that creates the `Object` and pass the address of the factory: ``` class Object; class Class{ public: Class(const std::string &n, Object *(*c)()) : name(n), create(c) {}; protected: std::string name; // Name for subclass Object *(*create)(); // Pointer to creation function for subclass }; class Object {}; Object* ObjectFactory() { return new Object; } int main(int argc, char**argv) { Class foo( "myFoo", ObjectFactory); return 0; } ```
I encountered this same problem. My solution was a template function which called the constructor. ``` template<class T> MyClass* create() { return new T; } ``` To use this as a function pointer is simple: ``` MyClass* (*createMyClass)(void) = create<MyClass>; ``` And to get an instance of MyClass: ``` MyClass* myClass = createMyClass(); ```
How to pass a function pointer that points to constructor?
[ "", "c++", "reflection", "constructor", "function-pointers", "" ]
I'm having a problem trying to serve a zip file in a JSP. The zip file is always corrupt after it has finished downloading. I've tried a few different methods for reading and writing, and none of them seem to do the trick. I figure it is probably adding in ascii characters somewhere as the file will open and display all the filenames, but I can't extract any files. Here's my latest code: ``` <%@ page import= "java.io.*" %> <% BufferedReader bufferedReader = null; String zipLocation = "C:\\zipfile.zip"; try { bufferedReader = new BufferedReader(new FileReader(zipLocation)); response.setContentType("application/zip"); response.setHeader( "Content-Disposition", "attachment; filename=zipfile.zip" ); int anInt = 0; while((anInt = bufferedReader.read()) != -1) { out.write(anInt); } } catch(Exception e) { e.printStackTrace(); } %> ``` EDIT: I moved the code to a servlet and it still didn't work. I changed a bunch more stuff around, so here's the latest non-working code: ``` public void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { try { String templateLocation = Config.getInstance().getString("Site.templateDirectory"); response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=output.zip;"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(baos); FileInputStream fis = new FileInputStream(templateLocation); int len; byte[] buf = new byte[1024]; while ((len = fis.read(buf)) > 0) { bos.write(buf, 0, len); } bos.close(); PrintWriter pr = response.getWriter(); pr.write(baos.toString()); pr.close(); } catch (Exception e) { e.printStackTrace(); } } ``` EDIT2: This is the servlet code that I actually works. Thank you to everyone! ``` public void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { try { String templateLocation = Config.getInstance().getString("Site.templateDirectory"); response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=output.zip;"); BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream()); FileInputStream fis = new FileInputStream(templateLocation); int len; byte[] buf = new byte[1024]; while ((len = fis.read(buf)) > 0) { bos.write(buf, 0, len); } bos.close(); } catch (Exception e) { e.printStackTrace(); } } ```
Zips are binary files, and therefore not suitable for being transferred as character data. Also text outside the code may corrupt the file. Use a plain, vanilla servlet instead of the JSP.
The JSP adds whitespace to the output. I suggest you move this to a servlet. Alternatively, you can take a look at [Strip whitespace from jsp output](https://stackoverflow.com/questions/208736/strip-whitespace-from-jsp-output) , but I'm not sure that it would not affect the ZIP output itself.
JSP to serve a zip corrupts the file
[ "", "java", "jsp", "servlets", "zip", "" ]
Do you place separators (commas, and, or operators) at the front of the line? ``` Select Field1 , Field2 --, Field3 From [some_table] as ST Inner Join [other_table] as OT ON ST.PKID = OT.FKID Where [this] = [that] and [one_other] > 53; ``` I think the best feature is to help expose important operators (AND/OR). As a secondary advantage it seems easier to comment out. Not sure where I picked it up initially, but Andrew Novick mentions it in "Transact-SQL User-Defined Function" (Heard him speak; got the book for free and highly recommend.)
At my workplace (small consultancy company with about 10 developers, specialising in Oracle) that is what our convention is, as so: ``` SELECT p.id pd_id , p.var_no , p.status , o.name operator , o.r_id , o.r_type , o.start_datetime , o.end_datetime --, p.id rd_id --, p.s_control , p.xml_data last_d_res_xml FROM schema_a.table_x p JOIN schema_b.table_y o ON p.id = o.pd_id WHERE p.some_id = 11 ORDER BY pd_id DESC, end_datetime DESC NULLS FIRST ``` We find it is quite clear and allows easy commenting of columns when debugging. It took a while to get used to but I prefer this style now - and it is consistently used by our whole team.
It's easier to comment out, but I'd rather go for readability - Using a column layout like the one below is a bit awkward while the code is changing a lot, but it's very comfortable to get an overview: ``` select foo.bar, baz.ban, foobar.bazban from foomatic foo join bartastic bar on bar.id = foo.id join anemone anem on anem.id = bar.id where foo.bar <> 1 and baz.ban = 'foo' and ( anem.bear in ('a', 'b') or anem.zoo is null ) ; ```
Is Separator First Formating (SFF) with SQL Code Formating easier to read/maintain?
[ "", "sql", "formatting", "" ]
I have encountered a strange behavior with a simple C++ class. classA.h ``` class A { public: A(); ~A(); static const std::string CONST_STR; }; ``` classA.cpp ``` #include "classA.h" #include <cassert> const std::string A::CONST_STR("some text"); A::A() { assert(!CONST_STR.empty()); //OK } A::~A() { assert(!CONST_STR.empty()); //fails } ``` main.cpp ``` #include <memory> #include <classA.h> std::auto_ptr<A> g_aStuff; int main() { //do something ... g_aStuff = std::auto_ptr<A>(new A()); //do something ... return 0; } ``` I'd expect access violations or anything similar, but I'd never expect that the content of the static const string could change. Does anyone here have a good explanation what happens in that code? thanks, Norbert
> I'd expect access violations or > anything similar, but I'd never expect > that the content of the static const > string could change. Undefined behaviour: it is undefined. If CONST\_STR has been destroyed, then you are not guaranteed a hardware exception if you access it. It might crash, but then again its address might end up containing data which looks like an empty string: its destructor might clear pointers or whatever. In this case, you say that the A instance is also stored in a global smart pointer, which is assigned in main(). So the CONST\_STR has been constructed when it is accessed in the A constructor, but quite possibly is destroyed before the smart pointer is destroyed. We'd need the whole program to say for sure. [Edit: you've done that. Since CONST\_STR and g\_aStuff are defined in different compilation units, their relative order of construction is not defined by the standard. I'm guessing that CONST\_STR is being destroyed first.]
**Edit:** Apparently the missing `A::` was a typo in the original post of the code. **Original Answer:** Do you mean to have ``` const std::string A::CONST_STR("some text"); ``` so that the CONST\_STR is part of class `A`? Otherwise you are declaring it separately and *not* initializing the static member of `A`.
C++ static const variable and destruction
[ "", "c++", "constants", "static-members", "" ]
What is the need of private constructor in C#? I got it as a question for a C# test.
For example if you have a class that should only be created through factory methods. Or if you have overloads of the constructor, and some of them should only be used by the other constructors. Probably other reasons as well =)
If you know some design pattern, it's obvious: a class could create a new instance of itself internally, and not let others do it. An example in Java (I don't know C# well enough, sorry) with a singleton-class: ``` class Meh { private Meh() { } private static Meh theMeh = new Meh(); public static Meh getInstance() { return theMeh; } } ```
What is the need of private constructor in C#?
[ "", "c#", "" ]
I am trying to create a text button using simple span and formatting the text and providing onclick behaviour. The problem is when a user clicks on the button, it sometimes highlights the text of the button. I want to avoid such behaviour, because it looks damn ugly when the text is selected. Is there any CSS/JavaScript/(jQuery) content I can use to avoid this?
``` spanid.onselectstart = function() {return false;} // ie spanid.onmousedown = function() {return false;} // mozilla ``` First result on Google by the way... **extra** ``` $('#spanid').selectstart(function(event) { event.preventDefault(); }); ```
For a CSS solution: ``` .unselectable { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; /* Isn't Konquerour dead? */ -moz-user-select: -moz-none; -moz-user-select: none; -ms-user-select: none; user-select: none; } ``` But, [looking here](https://developer.mozilla.org/en-US/docs/Web/CSS/user-select), CSS solution is not enough in late 2013, so you should add some javascript. There are good answers around.
Disable text select with JavaScript and/or CSS
[ "", "javascript", "css", "" ]
Can a class be protected in.NET? Why is / isn't this possible?
Yes, you just cannot make them top level classes, they must be inner classes ``` public class Outer { protected class Foo { } } ``` This is fine, it means that the only classes allowed to see Foo are sub classes of Outer ``` class X { // 'Outer.Foo' is inaccessible due to its protection level private void Flibble(Outer.Foo foo) { } } class X : Outer { // fine private void Flibble(Outer.Foo foo) { } } ``` Note that you cannot declare any outer class as private, protected (or protected internal) in c# since the access modifier for outer level classes defines their visibility in relation to other assemblies. Specifically visible within the assembly only (or to friends via InternalsVisibleTo) or outside the assembly. Thus whilst the public/internal identifiers are used here for consistency really the state in IL is simply 'Public' or 'NonPublic' (as the [Reflection.Emit flags show](http://msdn.microsoft.com/en-us/library/5kyyyeh2.aspx))
`protected` visibility is used to indicate 'visible to derived classes'. This makes sense on things inside a class, but normally has no meaning at the class level. The only exception to this is an inner class, where protected visibility means that derived classes will have access to the inner class.
Protected Classes in .NET
[ "", "c#", ".net", "access-modifiers", "" ]
What is a simple jQuery statement that states an operation proceeds only if A and B are true? If A isn't true, stop. If A and B are true, then continue. `
jQuery is just a library which enhances the capabilities of the DOM within a web browser; the underlying language is JavaScript, which has, as you might hope to expect from a programming language, the ability to perform conditional logic, i.e. ``` if( condition ) { // do something } ``` Testing two conditions is straightforward, too: ``` if( A && B ) { // do something } ``` *Dear God, I hope this isn't a troll...*
You can wrap jQuery calls inside normal JavaScript code. So, for example: ``` $(document).ready(function() { if (someCondition && someOtherCondition) { // Make some jQuery call. } }); ```
jQuery if statement, syntax
[ "", "javascript", "if-statement", "" ]
I want to do something along the lines of the following but when I use it like this I get a parse error telling me an entity needs to directly follow the '&' character: ``` <ice:selectManyCheckbox rendered="#{!bean1.condition1 && bean2.condition2}" value="#{bean1.selected}"> <f:selectItems value="#{bean2.items}" /> </ice:selectManyCheckbox> ``` How can I get rendered to check conditions from 2 different beans?
Use 'and' instead: ``` <ice:selectManyCheckbox rendered="#{!bean1.condition1 and bean2.condition2}" value="#{bean1.selected}"> ```
karim79 is right, you can just use the `and` operator. In addition to that, you can have a look to this [page](http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPIntro7.html), which explains the Expression Language (EL) with several examples...
How do I specify conditions from 2 different beans in a jsf rendered attribute?
[ "", "java", "jsf", "rendered-attribute", "" ]
I am getting #error WINDOWS.H already included. MFC apps must not #include windows.h But i dont know how do i find out because of which file this is happening Thanks
Try turning on "Show Includes" in the projects settings (C/C++ -> Advanced). This show give you an indication of what header files are included and in what order - you should be able to trace back from there
Change the include order, and include afx < headers > before the others
#error WINDOWS.H already included. MFC apps must not #include <windows.h>
[ "", "c++", "windows", "mfc", "" ]
I have a GUI C# application that has a single button Start/Stop. Originally this GUI was creating a single instance of a class that queries a database and performs some actions if there are results and gets a single "task" at a time from the database. I was then asked to try to utilize all the computing power on some of the 8 core systems. Using the number of processors I figure I can create that number of instances of my class and run them all and come pretty close to using a fair ammount of the computing power. ``` Environment.ProccessorCount; ``` Using this value, in the GUI form, I have been trying to go through a loop ProccessorCount number of times and start a new thread that calls a "doWork" type method in the class. Then Sleep for 1 second (to ensure the initial query gets through) and then proceed to the next part of the loop. I kept on having issues with this however because it seemed to wait until the loop was completed to start the queries leading to a collision of some sort (getting the same value from the MySQL database). In the main form, once it starts the "workers" it then changes the button text to STOP and if the button is hit again, it should execute on each "worker" a "stopWork" method. Does what I am trying to accomplish make sense? Is there a better way to do this (that doesn't involve restructuring the worker class)?
Restructure your design so you have one thread running in the background checking your database for work to do. When it finds work to do, spawn a new thread for each work item. Don't forget to use synchronization tools, such as semaphores and mutexes, for the key limited resources. Fine tuning the synchronization is worth your time. You could also experiment with the maximum number of worker threads - my guess is that it would be a few over your current number of processors.
While an exhaustive answer on the best practices of multithreaded development is a little beyond what I can write here, a couple of things: 1. Don't use `Sleep()` to wait for something to continue unless ABSOLUTELY necessary. If you have another code process that you need to wait for completion, you can either `Join()` that thread or use either a `ManualResetEvent` or `AutoResetEvent`. There is a lot of information on MSDN about their usage. Take some time to read over it. 2. You can't really guarantee that your threads will each run on their own core. While it's entirely likely that the OS thread scheduler will do this, just be aware that it isn't guaranteed.
C# creating as many instances of a class as there are processors
[ "", "c#", "multithreading", "" ]
I have a class with a few basic properties... ``` [XmlAttribute("MyFirstProperty")] public string FirstProperty { get; set; } [XmlAttribute("MySecondProperty")] public string SecondProperty { get; set; } ``` Using Reflection, I can enumerate through the public properties and get PropertyInfo objects for each of the properties above... the only thing I need now is a way to: 1. Detect whether or not the property has a XmlAttribute (I'm thinking this works via PropertyInfo.IsDefined(typeof(XmlAttribute), true) but would like to make sure) 2. Get the string value of the XmlAttribute How is this done?
``` object[] attribs = myPropertyInfo.GetCustomAttributes(typeof(XmlAttribute),false); bool doesPropertyHaveAttrib =attribs.Length > 0; string name = (XmlAttribute)(attribs[0].AttributeName); ``` Good point by Joel in the comments. My bad. Fixed.
I realise this is an old question. Stumbling upon the very same problem today, none of the solutions provided here worked. Especially seeing how the proposed solution `Attribute.GetCustomAttributes(typeof(XmlAttribute),false)` throws an exception, because XmlAttribute isn't derived from System.Attribute. Instead you should check for `XmlAttributeAttribute`. For future reference, this is the correct and working way to check for XmlAttribute using reflection: ``` PropertyInfo[] objProperties = obj.GetProperties(); foreach (var prop in objProperties) { Attribute[] propXmlAttr = Attribute.GetCustomAttributes(prop, typeof(XmlAttributeAttribute), false); if (propXmlAttr.Length > 0) string myAttribute = propValue.ToString()); } ```
Using Reflection to find [XmlAttribute("IWantThisValueRightHere")]
[ "", "c#", "reflection", "" ]
What are the differences of an Array and a Hash PHP? An array: `array(1,2,3...)` A hash: `array(key1=value1, key2=value2, ...)` are they different or the same? ※ For example, will the function arguments allows array be effective for the hash? Because I distinguish it by the conventional language and used it, I am puzzled.
Both the things you are describing are arrays. The only difference between the two is that you are explicitly setting the keys for the second one, and as such they are known as [associative arrays](http://www.php.net/manual/en/language.types.array.php). I do not know where you got the Hash terminology from (Perl?) but that's not what they are referred as in PHP. So, for example, if you were to do this: ``` $foo = array(1,2,3,4,5); print_r($foo); ``` The output would be: ``` Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) ``` As you can see, the keys to access the individual values you put in were created for you, but are there nonetheless. So this array is, essentially, associative as well. The other "type" of array is exactly the same way, except you are explcitily saying "I want to access *this* value with *this* key" instead of automatic numeric indexes (although the key you provide could also be numeric). ``` $bar = array('uno' => 'one', 'dos' => 'two'); print_r($bar); ``` Would output: ``` Array ( [uno] => one [dos] => two ) ``` As you might then expect, doing `print $bar['one']` would output `uno`, and doing `$foo[0]` from the first example would output `1`. As far as functions go, PHP functions will most of the time take either one of these "types" of array and do what you want them to, but there are distinctions to be aware of, as some functions will do funky stuff to your indexes and some won't. It is usually best to read the documentation before using an array function, as it will note what the output will be depending on the keys of the array. You should [read the manual](http://www.php.net/manual/en/language.types.array.php) for more information.
In actuality, there are no arrays in php - there are only associative arrays (which is basically a hash table) Try doing ``` $ar=array("zero","one","two","three","four"); unset($ar[3]); ``` doing so will remove "three" from the array, but you'll notice that the array keys (the array is not associative) will remain the same (0,1,2,4) - in any normal language it would renumber the key for "four" to 3.
What are the differences of Array and Hash in PHP?
[ "", "php", "arrays", "hash", "language-comparisons", "" ]
I searched here for the answer. I'm sorry if this has been asked before (as I suspect it has). **Summary:** How can I have strongly typed calls into my web.config without duplicating the property names? --- **Details:** In my code, I try to minimize string usage, and I don't like defining something twice. Complementing both of these wonts is my restriction of AppSettings usage (and its strings) to one class, which I reference throughout the project. The AppSettings class exposes public properties: ``` 12 public static string DateFormatString { 13 get { 14 return ConfigurationManager.AppSettings["DateFormatString"]; 15 } 16 } ``` How can I keep this class and prevent the duplication (lines 12 & 14) of the property name? Alternatively, what other solution might you recommend?
I like using Custom Configuration Handlers. <http://haacked.com/archive/2007/03/12/custom-configuration-sections-in-3-easy-steps.aspx>
There's no duplication in your example: One DateFormatString is a property name and the other is a string. You're just following a convention which names the property identically to the lookup key for the value. I do see one possible improvement. You should read the config file once in a static constructor and store the values instead of reading them from AppSettings every time a property is accessed.
Strongly typed calls into web.config without duplicating the property names?
[ "", "c#", "asp.net", "refactoring", "string", "strong-typing", "" ]
I have some (potentially) long-running ajax calls that I would like to abort if the user navigates to another page. The following jQuery code calls abort on all pending XMLHttpRequest objects upon navigating away from the page: ``` $.ajaxSetup({ beforeSend: function(xhr) { $(window).bind('beforeunload', function() { xhr.abort(); }); } }); ``` In a test case, I force a 10-second wait on the server-side operation being called. Using Firebug, I confirmed that the above code does indeed cause all pending ajax calls to halt immediately when I click any link on the page. However, the browser still waits the full 10 seconds before moving on to the next page. IE appears to exhibit the same behavior. Is this a known browser behavior? Is there anything I can do allow the user to navigate away from the page immediately in this situation? Thanks in advance.
Thank you for your replies! It turns out I was completely wrong about this being a browser issue - the problem was on the server. ASP.NET serializes requests of the same session that require session state, so in this case, the next page didn't begin processing on the server until those ajax-initiated requests completed. Unfortunately, in this case, session state is required in the http handler that responded to the ajax calls. But read-only access is good enough, so by marking the handler with IReadOnlySessionState instead of IRequiresSessionState, session locks are not held and the problem is fixed. Hope this information proves useful to others.
Regarding Todd's own answer to this question... I just had this issue with PHP and the same solution would have worked. However I needed the information in the session. For PHP developers you can call [`session_write_close()`](http://php.net/session_write_close) to close and write out your session in the middle of the request. This will free up the session for the other requests.
Browser waits for ajax call to complete even after abort has been called (jQuery)
[ "", "javascript", "jquery", "xmlhttprequest", "onbeforeunload", "abort", "" ]
First off, I read all of the suggested questions that sounded halfway relevant and didn't find anything that addressed my issue. Second, if this is already addressed somewhere, I didn't search well enough for it. Finally, on to the problem. :D I have a page that has a 'line item' on it. A 'line item', for our purposes, is simply a bunch of HTML elements in a horizontal row that form a line of HTML inputs (for example, imagine columns such as Pieces, Description, Weight, Unit Rate, Total Rate). One of the HTML controls in our line item is actually a custom server control that emits some Javascript. Among other things, the Javascript news up an object of type X like so: `var whatever = new X(constructor values);` Now, the user can add line items with an Add button. Currently, I'm simply cloning a clean copy of the HTML that forms the line item. This also clones the Javascript code so that now, every line item has the `var whatever = new X(constructor values);`. This presents a problem in that there are several lines all referencing the same Javascript variable (namely, `whatever`). This, of course, ruins everything b/c I need to reference each of the `whatever`'s as separate instances, not the same instance. I'm wondering if there are approaches to handling this situation. How do I use the custom server control but still reference the Javascript that each row emits? Or how do I create a new line item in a way that avoids this issue? I'm new to the whole modify-the-DOM-using-Javascript arena, and I can't seem to find any best practices or examples that are helpful so I'm at a bit of a loss. Does all this make sense? If not, please let me know what doesn't and I'll try to clear it up as best I can. **EDIT:** Here's a small code sample. This is exactly what the JavaScript object declaration looks like: `var example = new SmartDropDown('uomSDD','75','1','7','','','','',2);` The first parameter is the HTML ID of one of the elements that renders and because of that reason I couldn't *just* use an array (as mentioned in one of the answers; awesome answer, though, until I realized I'd forgotten to mention that detail). I'd need to come up with a way to change the ID *and* use the array. Some of the methods on the SmartDropDown object are `ShowOptions`, `HideOptions`, `BindOptions`. As for the code that's called when the button is clicked, here it is: ``` function AddLineItem() { var lineItemsParent = $("lineItems"); var newRow = lineItemTemplateNode.cloneNode(true); lineItemsParent.appendChild(newRow); } ``` So, to summarize, the line item HTML contains the usual stuff: inputs, selects, spans, etc and then the JS declaration listed above. And because of the way I'm adding a new line item (using the code above), the JS variable gets cloned, too. And I need a way to 1) change the ID of the element and 2) keep track of all the JS references (an array has already suggested).
Use an array? ``` var lineItems = []; ... // when the button is clicked lineItems[lineItems.length] = new X(constructor values); ``` If you need to generate a new id at the same time, you can prepend a string to the array index. ``` var lineItems = []; ... // when the button is clicked var id = 'item_' + lineItems.length.toString() lineItems[lineItems.length] = new X(id, ...); ```
This is where JavaScript frameworks are really handy. Many have good constructors that make this type of thing easy. For example, using [Prototype](http://prototypejs.org), I can do this: ``` function buildMe(counter) { var tempHTML = new Element('div',{'id':'bleh'+counter,className:'product'}) tempHTML.insert(new Element('a',{className:'prodTitleLinkA',href:'/here'}) $('someDiv').insert(tempHTML) Event.observe('bleh'+count, 'click', function(event) { alert(element.id) }); } ``` This creates a few elements, and connects an event to them. I can keep shoving as many as I want into "someDiv", each with its own ID and event.
How do you handle HTML element IDs and Javascript references when adding line items using Javascript?
[ "", "javascript", "html", "dom", "dhtml", "" ]
imagine a transactional, multithreaded java application using spring, jdbc and aop with n classes in m packages all taking part in database transations. Now let's say there is the need to scope an arbitrary set of classes within one transaction. Furthermore there is always one class T within the scope that commits the transaction when called. Let me give an example for clarity: Given the packages A,B,Z and classes A.Foo, B.Bar and Z.T. The following instances of the respective classes are called (possibly by different callers with other classes in between): A.Foo,B.Bar,A.Foo,Z.T The transactions will be committed only after Z.T is called. Should the application shut down for whatever reason the transaction will never be committed unless Z.T gets involved. Instances can call each other and, as already mentioned, there is no common entry point calling all instances from a single point of entry (like a service layer) which would make an easy target for spring's transactional tag. Now the question: can this problem be solved using aspects ? If so, what could be the basic approach ? Thanks.
You don't need a single point of entry, but you do need the ability to apply the transactional interceptor to all entry points so that re-entrant calls can participate in the same transaction. Assuming that you can do that, you could accomplish this with a ThreadLocal flag and a custom `org.springframework.transaction.support.TransactionSynchronization` implementation. You'd modify Z.T to set the ThreadLocal flag when a commit is safe to proceed. In your `TransactionSynchronization.beforeCommit()` implementation, which is invoked from the `PlatformTransactionManager`, you can check the flag and use that to determine whether to allow the commit to proceed. You can force a rollback by throwing a `RuntimeException` if the flag is not present. One caveat would be if you have other types of transactions (that don't involve the 3 co-ordinating classes you've described), you'll need to ensure that they don't get rolled back inadvertently. To do this, you could flag this "special transaction" in A.Foo, B.Bar and Z.T via another ThreadLocal flag, then check that flag in a guard clause in the `beforeCommit()` method mentioned above. Pseudocode: ``` void beforeCommit() { if in special transaction if commit flag not set throw new RuntimeException("cancel transaction") end if end if end ``` And, obviously, this is a hack and I wouldn't advocate doing in a greenfield system :).
Spring's idiom would recommend having a service interface that knows about units of work and a persistence interface that deals with relational databases. The methods in the service interface should map closely to your use cases. The service implementation knows about all the model and persistence packages and classes it needs to accomplish the goals of the use case. "Instances can call each other and, as already mentioned, there is no common entry point calling all instances from a single point of entry (like a service layer) which would make an easy target for spring's transactional tag." This sentence tells me that you're doing things in a manner that doesn't lend itself so easily to Spring's idiom. It's hard to tell exactly what you want, but it sounds like you're tossing aside two of the most important layers that Spring recommends. If it seems difficult to go against the grain, perhaps it's your design that needs reworking. "...different callers with other classes in between..." - maybe you need to declare transactions individually on these callers. You can declare transactions in XML config using aspects, either with Spring AOP or AspectJ. Spring 2.5 and higher now give you the option of using annotations if you prefer them to XML configuration. Your description is terribly confusing to me. Maybe that's part of the reason you're having difficulty with it as well. I'd rethink or clarify.
AOP, Spring and transaction scoping
[ "", "java", "spring", "transactions", "aop", "" ]
Given an array: `[dog, cat, mouse]` what is the most elegant way to create: ``` [,,] [,,mouse] [,cat,] [,cat,mouse] [dog,,] [dog,,mouse] [dog,cat,] [dog,cat,mouse] ``` I need this to work for any sized array. This is essentially a binary counter, where array indices represent bits. This presumably lets me use some bitwise operation to count, but I can't see a nice way of translating this to array indices though.
``` string[] source = new string[] { "dog", "cat", "mouse" }; for (int i = 0; i < Math.Pow(2, source.Length); i++) { string[] combination = new string[source.Length]; for (int j = 0; j < source.Length; j++) { if ((i & (1 << (source.Length - j - 1))) != 0) { combination[j] = source[j]; } } Console.WriteLine("[{0}, {1}, {2}]", combination[0], combination[1], combination[2]); } ```
Elegant? Why not Linq it. ``` public static IEnumerable<IEnumerable<T>> SubSetsOf<T>(IEnumerable<T> source) { if (!source.Any()) return Enumerable.Repeat(Enumerable.Empty<T>(), 1); var element = source.Take(1); var haveNots = SubSetsOf(source.Skip(1)); var haves = haveNots.Select(set => element.Concat(set)); return haves.Concat(haveNots); } ```
How to get all subsets of an array?
[ "", "c#", "arrays", "" ]
Lets say I have this amputated `Person` class: ``` class Person { public int Age { get; set; } public string Country { get; set; } public int SOReputation { get; set; } public TimeSpan TimeSpentOnSO { get; set; } ... } ``` I can then group on `Age` and `Country` like this: ``` var groups = aListOfPeople.GroupBy(x => new { x.Country, x.Age }); ``` Then I can output all the groups with their reputation totals like this: ``` foreach(var g in groups) Console.WriteLine("{0}, {1}:{2}", g.Key.Country, g.Key.Age, g.Sum(x => x.SOReputation)); ``` My question is, how can I get a sum of the `TimeSpentOnSO` property? The `Sum` method won't work in this case since it is only for `int` and such. I thought I could use the `Aggregate` method, but just seriously can't figure out how to use it... I'm trying all kinds properties and types in various combinations but the compiler just won't recognize it. ``` foreach(var g in groups) Console.WriteLine("{0}, {1}:{2}", g.Key.Country, g.Key.Age, g.Aggregate( what goes here?? )); ``` Have I completely missunderstood the Aggregate method? Or what is going on? Is it some other method I should use instead? Or do I have to write my own `Sum` variant for `TimeSpan`s? And to add to the mess, what if Person is an anonymous class, a result from for example a `Select` or a `GroupJoin` statement? --- Just figured out that I could make the `Aggregate` method work if I did a `Select` on the `TimeSpan` property first... but I find that kind of annoying... Still don't feel I understand this method at all... ``` foreach(var g in groups) Console.WriteLine("{0}, {1}:{2}", g.Key.Country, g.Key.Age, g.Select(x => x.TimeSpentOnSO) g.Aggregate((sum, x) => sum + y)); ```
A combination of Chris and Daniels answers solved it for me. I needed to initialize the TimeSpan, and I did things in the wrong order. The solution is: ``` foreach(var g in groups) Console.WriteLine("{0}, {1}:{2}", g.Key.Country, g.Key.Age, g.Aggregate(TimeSpan.Zero, (sum, x) => sum + x.TimeSpentOnSO)); ``` Thanks! And also... [D'oh!](http://en.wikipedia.org/wiki/D'oh!)
``` List<TimeSpan> list = new List<TimeSpan> { new TimeSpan(1), new TimeSpan(2), new TimeSpan(3) }; TimeSpan total = list.Aggregate(TimeSpan.Zero, (sum, value) => sum.Add(value)); Debug.Assert(total.Ticks == 6); ```
C#: How to use the Enumerable.Aggregate method
[ "", "c#", "time", "aggregate", "" ]
I want to use the URLEncoder/URLDecoder class (java.net.URLEncoder/URLDecoder) in an application and the methods : encode(String s, String enc)/decode(String s, String enc), but I don't know what can be the value of the String argument enc? I want to encode/decode in the "x-www-form-urlencoded" MIME content type. Thank you for your help.
The encoding parameter is the character encoding you're using. `For example "UTF-8"`.
First you need to set the content-type as a 'x-www-form-urlencoded'. Then whatever content you would like to encode, encode it using "UTF-8". For example: **For setting content to 'x-www-form-urlencoded':** ``` URL url = new URL("http://www.xyz.com/SomeContext/SomeAction"); <br> URLConnection urlConnection = url.openConnection();<br> ....<br> ....<br> urlConnection.setRequestProperty("Content-type","application/x-www-form-urlencoded"); ``` Or if you are using some JSP then you can write the following on top of it. ``` <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %><br> < META http-equiv="Content-Type" content="text/html; charset=UTF-8"> < FORM action="someaction.jsp" enctype="application/x-www-form-urlencoded" name="InputForm" method="POST"> ``` **And to use URLEncoder:** ``` String encodedString = URLEncoder.encode("hello","UTF-8"); ```
URLEncoder encode / URLDecoder decode in java (Android)
[ "", "java", "android", "" ]
I use the following code to convert an Object array to a String array : ``` Object Object_Array[]=new Object[100]; // ... get values in the Object_Array String String_Array[]=new String[Object_Array.length]; for (int i=0;i<String_Array.length;i++) String_Array[i]=Object_Array[i].toString(); ``` But I wonder if there is another way to do this, something like : ``` String_Array=(String[])Object_Array; ``` But this would cause a runtime error: `Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;` What's the correct way to do it ?
Another alternative to `System.arraycopy`: ``` String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class); ```
In Java 8: ``` String[] strings = Arrays.stream(objects).toArray(String[]::new); ``` To convert an array of other types: ``` String[] strings = Arrays.stream(obj).map(Object::toString). toArray(String[]::new); ```
How to convert object array to string array in Java
[ "", "java", "arrays", "string", "" ]
I am using LINQ like ``` from a in b.Descendants("SomeNode") select new MyClass { isfirst= false, islast = false, }; ``` How can I get the position of the element here? I basically want to know which one is first and which one is last element.
Something like ... ``` var res = b.Select((l, i) => new MyClass { IsFirst = (i == 0), IsLast = (i == b.Count-1) }); ``` ... should work. Per comment: Changed anonymous class to concrete class. This assumes that IsFirst and IsLast are boolean properties with a setter on a class called MyClass.
You've to use lambda syntax. ``` b.Descendants("SomeNode").Select((pArg, pId) => new { Position = pId}); ```
How to get position inside a select statement
[ "", "c#", "linq", "" ]
how hard is adding a basic web services interface to an existing java server application without having to turn it into a .war, or embedding a small web server like jetty? say, xml-rpc instead of more modern approaches, if it helps. if not too hard, can you suggest a starting point? thank you in advance :)
It sounds like you're asking for the impossible: expose an HTTP service without plugging into or embedding an HTTP server! Unless you want to reimplement what Jetty already does, I'd reccommend using Jetty as a library. That way you don't need to conform to the more awkward aspects of the Servlet spec. E.g. your servlets can have real constructors with parameters. There is also a simple HTTP server implementation in JDK 6, but it's in the com.sun namespace so I'd avoid it for production code.
Check out the [Restlet API](http://www.restlet.org/) which provides a painless way to implement RESTful web services that can run inside a web container or standalone.
java: basic web service interface without a web server
[ "", "java", "web-services", "interface", "jetty", "xml-rpc", "" ]
Is there a simple way to add a web part page to a Sharepoint site programmatically, using either the object model or web services? It seems straight-forward to create lists and add web parts in this manner, but I can't find an example of how to create a content page. Edit: For a plain WSS installation (not MOSS).
I'm going to take the route that this isn't a collaboration/publishing site as this isn't mentioned and wss is in the tag list. Pretty clunky in comparison to using a publishing site... First choose the web part page template you'd like to use from: > C:\Program Files\Common > Files\Microsoft Shared\web server > extensions\12\TEMPLATE\1033\STS\DOCTEMP\SMARTPGS Then set up a stream to the template and use SPFileCollection.Add() to add it to your document library. For example: ``` string newFilename = "newpage.aspx"; string templateFilename = "spstd1.aspx"; string hive = SPUtility.GetGenericSetupPath("TEMPLATE\\1033\\STS\\DOCTEMP\\SMARTPGS\\"); FileStream stream = new FileStream(hive + templateFilename, FileMode.Open); using (SPSite site = new SPSite("http://sharepoint")) using (SPWeb web = site.OpenWeb()) { SPFolder libraryFolder = web.GetFolder("Document Library"); SPFileCollection files = libraryFolder.Files; SPFile newFile = files.Add(newFilename, stream); } ``` Note: This solution assumes you have the US SharePoint version installed that uses the 1033 language code. Just change the path if different.
Is it a collaboration/publishing site? If so you can the following blog articles should help: * [Create and Publish web pages in Publishing SharePoint sites programmatically](http://blogs.msdn.com/sridhara/archive/2008/06/21/create-and-publish-web-pages-in-publishing-sharepoint-sites-programmatically.aspx) * [Programmatically create pages - and Add Web Parts](http://www.novolocus.com/2009/04/02/programmatically-create-pages-and-add-web-parts/) * [Programmatically adding pages to a MOSS Publishing site](http://www.andrewconnell.com/blog/archive/2006/11/15/5168.aspx)
Programmatically instantiate a web part page in Sharepoint
[ "", "c#", "sharepoint", "wss-3.0", "" ]
i want to learn C++; and i already have a compiler. i already know a few programming languages including: * BASIC (yes, the dos version) * visualBasic (using VisualBasic Express 2006 or 8 i'm not quite sure) * Java * PHP * HTML (if we count that) so it doesn't need to be for absolute beginners; although if you find one post it too.
[www.cplusplus.com](http://www.cplusplus.com/) is a great website with tons of documentation for experts and beginners. Tutorials for beginners: <http://www.cplusplus.com/doc/tutorial/> An additional website I heartily reccomend once you have a little more expertise is the [C++ FAQ Lite.](http://www.parashift.com/c++-faq-lite/)
The text of a good book is online here: [Thinking in C++](http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html)
i need a good website to learn c++
[ "", "c++", "" ]
After enabling strict warnings in PHP 5.2, I saw a load of strict standards warnings from a project that was originally written without strict warnings: > **Strict Standards**: **Static function** Program::getSelectSQL() **should not be abstract** in Program.class.inc The function in question belongs to an abstract parent class Program and is declared abstract static because it should be implemented in its child classes, such as TVProgram. I did find references to this change [here](http://php.net/manual/migration52.incompatible.php): > Dropped abstract static class functions. Due to an oversight, PHP 5.0.x and 5.1.x allowed abstract static functions in classes. As of PHP 5.2.x, only interfaces can have them. My question is: can someone explain in a clear way why there shouldn't be an abstract static function in PHP?
static methods belong to the class that declared them. When extending the class, you may create a static method of the same name, but you are not in fact implementing a static abstract method. Same goes for extending any class with static methods. If you extend that class and create a static method of the same signature, you are not actually overriding the superclass's static method *EDIT* (Sept. 16th, 2009) Update on this. Running PHP 5.3, I see abstract static is back, for good or ill. (see <http://php.net/lsb> for more info) *CORRECTION* (by philfreo) `abstract static` is still not allowed in PHP 5.3, [LSB](http://php.net/lsb) is related but different.
It's a long, sad story. When PHP 5.2 first introduced this warning, [late static bindings](http://php.net/manual/en/language.oop5.late-static-bindings.php) weren't yet in the language. In case you're not familiar with late static bindings, note that code like this doesn't work the way you might expect: ``` <?php abstract class ParentClass { static function foo() { echo "I'm gonna do bar()"; self::bar(); } abstract static function bar(); } class ChildClass extends ParentClass { static function bar() { echo "Hello, World!"; } } ChildClass::foo(); ``` Leaving aside the strict mode warning, the code above doesn't work. The `self::bar()` call in `foo()` explicitly refers to the `bar()` method of `ParentClass`, even when `foo()` is called as a method of `ChildClass`. If you try to run this code with strict mode off, you'll see "*PHP Fatal error: Cannot call abstract method ParentClass::bar()*". Given this, abstract static methods in PHP 5.2 were useless. The *entire point* of using an abstract method is that you can write code that calls the method without knowing what implementation it's going to be calling - and then provide different implementations on different child classes. But since PHP 5.2 offers no clean way to write a method of a parent class that calls a static method of the child class on which it is called, this usage of abstract static methods isn't possible. Hence any usage of `abstract static` in PHP 5.2 is bad code, probably inspired by a misunderstanding of how the `self` keyword works. It was entirely reasonable to throw a warning over this. But then PHP 5.3 came along added in the ability to refer to the class on which a method was called via the `static` keyword (unlike the `self` keyword, which always refers to the class in which the method was *defined*). If you change `self::bar()` to `static::bar()` in my example above, it works fine in PHP 5.3 and above. You can read more about `self` vs `static` at [New self vs. new static](https://stackoverflow.com/questions/5197300/new-self-vs-new-static). With the static keyword added, the clear argument for having `abstract static` throw a warning was gone. Late static bindings' main purpose was to allow methods defined in a parent class to call static methods that would be defined in child classes; allowing abstract static methods seems reasonable and consistent given the existence late static bindings. You could still, I guess, make a case for keeping the warning. For instance, you could argue that since PHP lets you call static methods of abstract classes, in my example above (even after fixing it by replacing `self` with `static`) you're exposing a public method `ParentClass::foo()` which is *broken* and that you don't really want to expose. Using a non-static class - that is, making all the methods instance methods and making the children of `ParentClass` all be singletons or something - would solve this problem, since `ParentClass`, being abstract, can't be instantiated and so its instance methods can't be called. I think this argument is weak (because I think exposing `ParentClass::foo()` isn't a big deal and using singletons instead of static classes is often needlessly verbose and ugly), but you might reasonably disagree - it's a somewhat subjective call. So based upon this argument, the PHP devs kept the warning in the language, right? Uh, [not exactly](https://bugs.php.net/bug.php?id=53081). PHP bug report 53081, linked above, called for the warning to be dropped since the addition of the `static::foo()` construct had made abstract static methods reasonable and useful. Rasmus Lerdorf (creator of PHP) starts off by labelling the request as bogus and goes through a long chain of bad reasoning to try to justify the warning. Then, finally, this exchange takes place: > ### Giorgio > > i know, but: > > ``` > abstract class cA > { > //static function A(){self::B();} error, undefined method > static function A(){static::B();} // good > abstract static function B(); > } > > class cB extends cA > { > static function B(){echo "ok";} > } > > cB::A(); > ``` > > ### Rasmus > > Right, that is exactly how it should work. > > ### Giorgio > > but it is not allowed :( > > ### Rasmus > > What's not allowed? > > ``` > abstract class cA { > static function A(){static::B();} > abstract static function B(); > } > > class cB extends cA { > static function B(){echo "ok";} > } > > cB::A(); > ``` > > This works fine. You obviously can't call self::B(), but static::B() > is fine. The claim by Rasmus that the code in his example "works fine" is false; as you know, it throws a strict mode warning. I guess he was testing without strict mode turned on. Regardless, a confused Rasmus left the request erroneously closed as "bogus". And that's why the warning is still in the language. This may not be an entirely satisfying explanation - you probably came here hoping there was a rational justification of the warning. Unfortunately, in the real world, sometimes choices are born from mundane mistakes and bad reasoning rather than from rational decision-making. This is simply one of those times. Luckily, the estimable Nikita Popov has removed the warning from the language in PHP 7 as part of [PHP RFC: Reclassify E\_STRICT notices](https://wiki.php.net/rfc/reclassify_e_strict). Ultimately, sanity has prevailed, and once PHP 7 is released we can all happily use `abstract static` without receiving this silly warning.
Why does PHP 5.2+ disallow abstract static class methods?
[ "", "php", "oop", "static", "abstract", "" ]
I would suspect the code below to output: > (I am a SmartForm object and using the method in SmartForm).xml instead, however, it outputs: > (I am a SmartForm object and using the method in Item).xml **Why is that? How can I force C# to take the value from the *overriding* property?** That is why I am *overriding* the property. ``` using System; namespace TestInhersdk234 { public class Program { static void Main(string[] args) { SmartForm smartForm = new SmartForm(); Console.ReadLine(); } } public class SmartForm : Item { public SmartForm() { Console.WriteLine(FullXmlDataStorePathAndFileName); } public new string GetItemTypeIdCode { get { return String.Format("(I am a {0} object and using the method in SmartForm)", this.GetType().Name); } } } public class Item { public string FullXmlDataStorePathAndFileName { get { return GetItemTypeIdCode + ".xml"; } } public string GetItemTypeIdCode { get { return String.Format("(I am a {0} object and using the method in Item)", this.GetType().Name); } } } } ```
You need to add the **override** keyword to the overriding method?
You're not actually overriding. You're hiding. To override: ``` class MyBase { public virtual void foo() {} } class MyClass : MyBase { public override void foo() {} } ```
Why does C# take value from overridden property instead of the overriding property?
[ "", "c#", "oop", "inheritance", "" ]
Is there an elegant way to know when a worker thread is done executing so I can access resources it produced? For example if the worker thread queried a list of SQL Servers using `ServersSqlDataSourceEnumerator.Instance.GetDataSources();` and saved the result in a DataTable variable, what mechanism can I use to know when this DataTable variable has been populated/is available. I don't want to poll ThreadState; it would be ideal to fire an event when it's done so I can perform actions with the result. Thanks!
You can use a callback mechanism or block on an event to know of completion of an Async operation. See this page for the [Asychronous Programming Model in .net](http://msdn.microsoft.com/en-us/library/2e08f6yc%28VS.71%29.aspx) - you can call BeginInvoke on any delegate to perform the action in an Async manner. If you're using the BackgroundWorker type, you can subscribe to the [RunWorkerCompleted event](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.runworkercompleted.aspx).
So fire an event :-P You could also look at using an AutoResetEvent: <http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx>
How can I tell if a thread is finished executing without polling ThreadState?
[ "", "c#", ".net", "multithreading", "worker-thread", "" ]
How do I create a loading overlay(with loading gif) while php script runs and returns data
PHP is a server-side language and what you're looking for is something that interacts with the browser on the clientside. You're probably best of using a solution involving AJAX - for example using Jquery: When the user loads the page, make an AJAX call that runs your script. Show a div that displays your 'loading' gif. When the AJAX call finishes, hide the div with your 'loading' gif.
You need to provide more information as to what to show and when to show the image. but to start with here is [post](http://techxplorer.com/2007/10/06/using-jquery-for-an-ajax-loading-message/) about hot you can show a "loading" message (gif) using php and JQuery.
How to create a Loading/Splash Screen in PHP?
[ "", "php", "css", "" ]
I understand that in IE 5.5, 6, and 7, when you modify a DOM element before it is 'closed', it throws an "operation aborted" error (this article has more information: <http://www.clientcide.com/code-snippets/manipulating-the-dom/ie-and-operation-aborted/>) In my ASP.Net application, I am registering a client script block on the page during the page\_load event. (I tried moving this code to the page\_loadcomplete event or page\_prerender event with no luck). Here is my code (pretty basic): ``` // Checks if the handler is a Page and that the script isn't already on the Page if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("blockUIAlert")) { ScriptManager.RegisterClientScriptBlock(page, typeof(ScriptUtilities), "blockUIAlert", script, true); } ``` I'm using this same code from other AJAX postbacks in my page without a problem. This error only occurs if this code is called when the page is being loaded. What can I do to have this code be called after the DOM elements are closed? I don't want the user to have to initiate this action manually -- I want this code to be executed as soon as the page is loaded, provided certain server-side conditions are met.
If you are using YUI, or jQuery they have js event listening functions that will run code when the DOM is done loading. I am betting that MS Ajax library has a similar function. [jQuery Examples](http://docs.jquery.com/Events)
Maybe this is the answer you're looking for. I was having the operation aborted error and like you I also knew why it happens, but I was 100% certain that I was not modifying a DOM element before it was 'closed'. Turns out the bug was in the ASP.NET AJAX client-side framework. I had to modify the client-side framework. Please see the question I posted, [Internet Explorer's Operation Aborted and Latency Issue](https://stackoverflow.com/questions/757758/internet-explorers-operation-aborted-and-latency-issue) I also just noticed that your are using RegisterClientScriptBlock. Try ScriptManager.RegisterStartupScript(...).
In my ASP.NET app, registering a script from code-behind before a page has loaded throws an "operation aborted" error in IE
[ "", "asp.net", "javascript", "ajax", "asp.net-ajax", "internet-explorer-7", "" ]
for a project i'm currently working on, im trying to pass a set of objects all somehow linked to one object. I'm currently blacked out and can't seem to find a proper solution. The situation is like this. I have a product object, on which a few insurance packages apply. I need to pass this information to the view, but I have to be able to retrieve the proper packages for the proper products. so it looks like this... Product 1 has package 1, 2, 3 Product 2 has package 2,3,5,6 Product 3 has package 2,4,6,7 The problem is that there can be a different number of products and a different number of packages Any ideas? The answer is probably simple, but I'm a little bit too tired to find it out...
How about this: * Create a container class, as Simon suggested * Inside the class, have these members: + List Products { get; set; } + List Packages { get; set; } + List GetPackages(Product product); The GetPackages method can query the internal dictionary to determine which packages to return. ``` public class ProductsPackages { private Dictionary<int, int> _map; public ProductsPackages(List<Product> products, List<Package> packages, Dictionary<int, int> map) { _map = map; } public List<Product> Products { get; private set; } public List<Package> Packages { get; private set; } public List<Package> GetPackages(Product product) { return (from p in Packages join kvp in _map on p.ID == kvp.Value where kvp.Key == product.ID select p).ToList(); } } ```
A dictionary of lists? ``` Dictionary<Product, List<Package>> products = new Dictionary<Product, List<Package>>(); products.Add(product1, new List<Package>()); products.Add(product2, new List<Package>()); products.Add(product3, new List<Package>()); products[product1].Add(package1); products[product1].Add(package2); products[product2].Add(package2); products[product2].Add(package3); products[product2].Add(package5); products[product2].Add(package6); products[product3].Add(package2); products[product3].Add(package4); products[product3].Add(package6); products[product3].Add(package7); ``` I do this often enough I wrote my own container `IndexedLists<K,V>` which is really a `Dictionary<K, List<V>>` that automatically handles creation of the lists.
Preferred way to pass multiple objects, all applying to one other object
[ "", "c#", "data-structures", "" ]
I have some methods in my app that make http requests. Is there a good way to simulate network failures and bad responses for the unit tests?
Suitable [Mock Objects](http://www.mockobjects.com/) should let you perform such simulations easily; if you're unfamiliar with the concept, there's a good [tutorial](http://javaboutique.internet.com/tutorials/mock_objects/) here.
For network failures nothing beats first unplugging your computers ethernet cable (or d/c it's wireless) and then unplugging whatever cable gives you access to the cloud. If by bad responses you mean HTTP errors you can write ASP scripts that will always throw specific errors. If you want to test malformed HTTP packets you'll have to write a simple socket app to do that.
Testing methods that make http requests
[ "", "java", "unit-testing", "http", "" ]
Here's the situation. The company I work for has quite a bit of existing Tcl code, but some of them want to start using python. It would nice to be able to reuse some of the existing Tcl code, because that's money already spent. Besides, some of the test equipment only has Tcl API's. So, one of the ways I thought of was using the subprocess module to call into some Tcl scripts. * Is subprocess my best bet? * Has anyone used this fairly new piece of code: [Plumage](http://code.google.com/p/plumage/)? If so what is your experience (not just for Tk)? * Any other possible ways that I have not considered?
I hope you're ready for this. Standard Python ``` import Tkinter tclsh = Tkinter.Tcl() tclsh.eval(""" proc unknown args {puts "Hello World!"} }"!dlroW olleH" stup{ sgra nwonknu corp """) ``` *Edit in Re to comment*: Python's tcl interpreter is not aware of other installed tcl components. You can deal with that by adding extensions in the usual way to the tcl python actually uses. Here's a link with some detail * [How Tkinter can exploit Tcl/Tk extensions](http://wiki.python.org/moin/How%20Tkinter%20can%20exploit%20Tcl/Tk%20extensions)
This can be done. <http://wiki.tcl.tk/13312> Specificly look at the typcl extension. > Typcl is a bit weird... It's a an extension to use Tcl *from* Python. > It doesn't really require CriTcl and could have been done in standard C. > > This code demonstrates using Tcl as shared library, and hooking into it > at run time (Tcl's stubs architecture makes this delightfully simple). > Furthermore, Typcl avoids string conversions where possible (both ways).
Know any creative ways to interface Python with Tcl?
[ "", "python", "tcl", "" ]
I have a webapp where users can create their account and use the service. Now I want to give them a custom domain facility where app.customer1web.com points\_to myservice.com with userid customer1 once he sets up the custom domain, for the world it looks like my service is running on his machine. Many services like blogger, wp.com, tumblr give this feature. how do i do that? I am using java to write my web app. How do i map domain name to userid when request comes in?
> How do i map domain name to userid when request comes in? Obviously, you'll have to store that information somewhere, most likely in a database. 1. Add a database table `domains` with columns: * customerId * name * active (1 or NULL) * challenge Add unique key for (name, active) to ensure a domain name is mapped only once. 2. When a customer attempts to add a domain, add a row with active=NULL and challenge set to a random string. Show the random string to the customer and ask them to put up a web page with it on the site or create a dummy DNS record with it to verify domain ownership (this is how Google Apps do it). You could verify ownership by sending an email to the administrative contact or in some other way. 3. When the customer says he did what you instructed them to do in step #2, verify it and set active=1, challenge=NULL. If the domain was previously active for some other customer, delete those records or set active=0. 4. Ask the customer to add a CNAME record for their domain and forward it to your domain, e.g. `hosted.myservice.com` (Google uses `ghs.google.com` for Google Apps). 5. When a request comes in, do ``` SELECT customerId FROM domains WHERE name=:requestDomain AND active=1 ``` A better way may be to automatically offer your customers a domain in the format of `<customername>.myservice.com`, *in addition to* custom domains. This gives you two benefits: * Customers who don't wan't to use their own domain can still customize their login page, e.g. with a company logo. * For custom domains, you can ask your customer to forward them to `<customername>.myservice.com` instead of to a generic `hosted.myservice.com`. This enables you to horizontally partition customers among multiple servers without having to ask customers to change anything on their end. For example, you could give customers an option to choose whether they want their account hosted in EU or US. When they change it, just transfer their data and update `<customername>.myservice.com`. Their custom domain will work automatically. To do this, you'd have to set up a wildcard DNS record for `*.myservice.com` (unless you also need the latter feature, in which case you'll have to manage individual records).
One solution you could use is setting up a [WildCard DNS Record](http://en.wikipedia.org/wiki/Wildcard_DNS_record) for your application, and have the application itself check the RequestURI to see what host name the users are coming in on. I know this is a very vague answer, but it sounds like having the WildCard record set up, with a single function checking the hostname is your best bet. This way, you do not have to set up a DNS record every time a customer signs up, and you have more time to yourself to do other things... like adding new features to your application!
How to give cname forward support to saas software
[ "", "java", "dns", "saas", "cname", "" ]
I'm trying to implement a WikiLink template filter in Django that queries the database model to give different responses depending on Page existence, identical to Wikipedia's red links. The filter does not raise an Error but instead doesn't do anything to the input. **WikiLink** is defined as: `[[ThisIsAWikiLink | This is the alt text]]` Here's a working example that does not query the database: ``` from django import template from django.template.defaultfilters import stringfilter from sites.wiki.models import Page import re register = template.Library() @register.filter @stringfilter def wikilink(value): return re.sub(r'\[\[ ?(.*?) ?\| ?(.*?) ?\]\]', r'<a href="/Sites/wiki/\1">\2</a>', value) wikilink.is_safe = True ``` The **input** (`value`) is a multi-line string, containing HTML and many WikiLinks. The expected **output** is substituting `[[ThisIsAWikiLink | This is the alt text]]` with * `<a href="/Sites/wiki/ThisIsAWikiLink">This is the alt text</a>` **or** if "ThisIsAWikiLink" doesn't exist in the database: * `<a href="/Sites/wiki/ThisIsAWikiLink/edit" class="redlink">This is the alt text</a>` and returning value. Here's the non-working code (edited in response to comments/answers): ``` from django import template from django.template.defaultfilters import stringfilter from sites.wiki.models import Page import re register = template.Library() @register.filter @stringfilter def wikilink(value): m = re.match(r'\[\[ ?(.*?) ?\| ?(.*?) ?\]\]', value) if(m): page_alias = m.group(2) page_title = m.group(3) try: page = Page.objects.get(alias=page_alias) return re.sub(r'(\[\[)(.*)\|(.*)(\]\])', r'<a href="Sites\/wiki\/\2">\3</a>', value) except Page.DoesNotExist: return re.sub(r'(\[\[)(.*)\|(.*)(\]\])', r'<a href="Sites\/wiki\/\2\/edit" class="redlink">\3</a>', value) else: return value wikilink.is_safe = True ``` What the code needs to do is: * extract all the WikiLinks in *value* * query the *Page* model to see if the page exists * substitute all the WikiLinks with normal links, styled dependent on each wikipage existence. * return the altered *value* The updated question is: What regular expression (method) can return a python List of WikiLinks, which can be altered and used to substitute the original matches (after being altered). Edit: I'd like to do something like this: ``` def wikilink(value): regex = re.magic_method(r'\[\[ ?(.*?) ?\| ?(.*?) ?\]\]', value) foreach wikilink in regex: alias = wikilink.group(0) text = wikilink.group(1) if(alias exists in Page): regex.sub("<a href="+alias+">"+ text +"</a>") else: regex.sub("<a href="+alias+" class='redlink'>"+ text +"</a>") return value ```
If your string contains other text in addition to the wiki-link, your filter won't work because you are using `re.match` instead of `re.search`. `re.match` matches at the beginning of the string. `re.search` matches anywhere in the string. See [matching vs. searching](http://docs.python.org/library/re.html#matching-vs-searching). Also, your regex uses the greedy `*`, so it won't work if one line contains multiple wiki-links. Use `*?` instead to make it non-greedy: ``` re.search(r'\[\[(.*?)\|(.*?)\]\]', value) ``` Edit: As for tips on how to fix your code, I suggest that you use [`re.sub` with a callback](http://docs.python.org/library/re.html#re.sub). The advantages are: * It works correctly if you have multiple wiki-links in the same line. * One pass over the string is enough. You don't need a pass to find wiki-links, and another one to do the replacement. Here is a sketch of the implmentation: ``` import re WIKILINK_RE = re.compile(r'\[\[(.*?)\|(.*?)\]\]') def wikilink(value): def wikilink_sub_callback(match_obj): alias = match_obj.group(1).strip() text = match_obj.group(2).strip() if(alias exists in Page): class_attr = '' else: class_attr = ' class="redlink"' return '<a href="%s"%s>%s</a>' % (alias, class_attr, text) return WIKILINK_RE.sub(wikilink_sub_callback, value) ```
This is the type of problem that falls quickly to a small set of unit tests. Pieces of the filter that can be tested in isolation (with a bit of code restructuring): * Determining whether or not value contains the pattern you're looking for * What string gets generated if there is a matching Page * What string gets generated is there isn't a matching Page That would help you isolate where things are going wrong. You'll probably find that you'll need to rewire the regexps to account for optional spaces around the |. Also, on first glance it looks like your filter is exploitable. You're claiming the result is safe, but you haven't filtered the alt text for nasties like script tags.
Django, custom template filters - regex problems
[ "", "python", "regex", "django", "django-templates", "" ]
Is there some way to use `@Autowired` with static fields. If not, are there some other ways to do this?
In short, no. You cannot autowire or manually wire static fields in Spring. You'll have to write your own logic to do this.
``` @Component("NewClass") public class NewClass{ private static SomeThing someThing; @Autowired public void setSomeThing(SomeThing someThing){ NewClass.someThing = someThing; } } ```
Can you use @Autowired with static fields?
[ "", "java", "spring", "autowired", "" ]
What are the performance implications of throwing exceptions in C++0x? How much is this compiler dependent? This is not the same as asking [what is the cost of entering a `try` block, even if no exception is thrown](https://stackoverflow.com/questions/1897940/in-what-ways-do-c-exceptions-slow-down-code-when-there-are-no-exceptions-thown). Should we expect to use exceptions more for general logic handling like in Java?
``` #include <iostream> #include <stdexcept> struct SpaceWaster { SpaceWaster(int l, SpaceWaster *p) : level(l), prev(p) {} // we want the destructor to do something ~SpaceWaster() { prev = 0; } bool checkLevel() { return level == 0; } int level; SpaceWaster *prev; }; void thrower(SpaceWaster *current) { if (current->checkLevel()) throw std::logic_error("some error message goes here\n"); SpaceWaster next(current->level - 1, current); // typical exception-using code doesn't need error return values thrower(&next); return; } int returner(SpaceWaster *current) { if (current->checkLevel()) return -1; SpaceWaster next(current->level - 1, current); // typical exception-free code requires that return values be handled if (returner(&next) == -1) return -1; return 0; } int main() { const int repeats = 1001; int returns = 0; SpaceWaster first(1000, 0); for (int i = 0; i < repeats; ++i) { #ifdef THROW try { thrower(&first); } catch (std::exception &e) { ++returns; } #else returner(&first); ++returns; #endif } #ifdef THROW std::cout << returns << " exceptions\n"; #else std::cout << returns << " returns\n"; #endif } ``` Mickey Mouse benchmarking results: ``` $ make throw -B && time ./throw g++ throw.cpp -o throw 1001 returns real 0m0.547s user 0m0.421s sys 0m0.046s $ make throw CPPFLAGS=-DTHROW -B && time ./throw g++ -DTHROW throw.cpp -o throw 1001 exceptions real 0m2.047s user 0m1.905s sys 0m0.030s ``` So in this case, throwing an exception up 1000 stack levels, rather than returning normally, takes about 1.5ms. That includes entering the try block, which I believe on some systems is free at execution time, on others incurs a cost each time you enter try, and on others only incurs a cost each time you enter the function which contains the try. For a more likely 100 stack levels, I upped the repeats to 10k because everything was 10 times faster. So the exception cost 0.1ms. For 10 000 stack levels, it was 18.7s vs 4.1s, so about 14ms additional cost for the exception. So for this example we're looking at a pretty consistent overhead of 1.5us per level of stack (where each level is destructing one object). Obviously C++0x doesn't specify performance for exceptions (or anything else, other than big-O complexity for algorithms and data structures). I don't think it changes exceptions in a way which will seriously impact many implementations, either positively or negatively.
Exception performance is very compiler dependent. You'll have to profile your application to see if it is a problem. In general, it should not be. You really should use exceptions for "exceptional conditions", not general logic handling. Exceptions are ideal for separating normal paths through your code and error paths.
Cost of throwing C++0x exceptions
[ "", "c++", "performance", "exception", "" ]
I have a unit test to check whether a method returns the correct `IEnumerable`. The method builds the enumerable using `yield return`. The class that it is an enumerable of is below: ``` enum TokenType { NUMBER, COMMAND, ARITHMETIC, } internal class Token { public TokenType type { get; set; } public string text { get; set; } public static bool operator == (Token lh, Token rh) { return (lh.type == rh.type) && (lh.text == rh.text); } public static bool operator != (Token lh, Token rh) { return !(lh == rh); } public override int GetHashCode() { return text.GetHashCode() % type.GetHashCode(); } public override bool Equals(object obj) { return this == (Token)obj; } } ``` This is the relevant part of the method: ``` foreach (var lookup in REGEX_MAPPING) { if (lookup.re.IsMatch(s)) { yield return new Token { type = lookup.type, text = s }; break; } } ``` If I store the result of this method in `actual`, make another enumerable `expected`, and compare them like this... ``` Assert.AreEqual(expected, actual); ``` ..., the assertion fails. I wrote an extension method for `IEnumerable` that is similar to [Python's `zip` function](https://docs.python.org/2/library/functions.html?highlight=zip#zip) (it combines two IEnumerables into a set of pairs) and tried this: ``` foreach(Token[] t in expected.zip(actual)) { Assert.AreEqual(t[0], t[1]); } ``` It worked! So what is the difference between these two `Assert.AreEqual`s?
`Assert.AreEqual` is going to compare the two objects at hand. `IEnumerable`s are types in and of themselves, and provide a mechanism to iterate over some collection...but they are not actually that collection. Your original comparison compared two `IEnumerable`s, which is a valid comparison...but not what you needed. You needed to compare *what the two `IEnumerable`s were intended to enumerate*. Here is how I compare two enumerables: ``` Assert.AreEqual(t1.Count(), t2.Count()); IEnumerator<Token> e1 = t1.GetEnumerator(); IEnumerator<Token> e2 = t2.GetEnumerator(); while (e1.MoveNext() && e2.MoveNext()) { Assert.AreEqual(e1.Current, e2.Current); } ``` I am not sure whether the above is less code than your `.Zip` method, but it is about as simple as it gets.
Found it: ``` Assert.IsTrue(expected.SequenceEqual(actual)); ```
How does Assert.AreEqual determine equality between two generic IEnumerables?
[ "", "c#", "unit-testing", "ienumerable", "mstest", "assert", "" ]
I wanna do a application with C# ; it will count correct words and wrong words in a text and show me it ... there is a feature in MS Word .. So how can i use this feature in C# if its possible ? (in Turkish language).
You can add a reference to Microsoft Word x.0 Object Library. Check out this MSDN article for information: <http://msdn.microsoft.com/en-us/library/15s06t57(VS.80).aspx>. Once you have added the reference you should then be able to use the Word.Application object. It would look something like this (untested code!!). ``` using Word; public void checkspelling(string text) { Word.Application app = new Word.Application(); object template=Missing.Value; object newTemplate=Missing.Value; object documentType=Missing.Value; object visible=true; object optional = Missing.Value; _Document doc = app.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible); doc.Words.First.InsertBefore(text); Word.ProofreadingErrors errors = doc.SpellingErrors; ecount = errors.Count; doc.CheckSpelling( ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional, ref optional); if (ecount == 0) { // no errors } else { // errros } } ```
I don't thing it is a good idea to use the MS Office spell checkers. There are several open source libraries out there you can use. One of them is NHunspell, the .NET Version of the open office spell checker Hunspell. It works with the open office directories and yo got support for a lot of languages.
Using MS Office's Spellchecking feature with C#
[ "", "c#", "spell-checking", "" ]
I have a DataSet with a QueriesTableAdapter. In order to control the SqlCommand.CommandTimeout I've added a partial class called QueriesTableAdapter with a public method called ChangeTimeout. ``` partial class QueriesTableAdapter { public void ChangeTimeout(int timeout) { foreach (System.Data.SqlClient.SqlCommand cmd in CommandCollection) { cmd.CommandTimeout = timeout; } } } ``` For every DataSet I have that has a QueriesTableAdapter, I can set the CommandTimeout prior to executing. ``` using (NameSpace.DataSet.DataSetTableAdapters.QueriesTableAdapter ta = new NameSpace.DataSet.DataSetTableAdapters.QueriesTableAdapter()) { ta.ChangeTimeout(3600); ta.DoSomething(); } ``` This works well is most cases because the "QueriesTableAdapter" is named for you in the DataSet designer. The problem I'm running into is the TableAdapters that are uniquely named. For example, if I have a DataTable called Person and a TableAdaper called PersonTableAdapter, I have to write a PersonTableAdapter partial class in the same way I wrote the QueriesTableAdaper class. I have hundreds of DataTables with unique TableAdapter names. I don't want to create a partial class for each of those. How can I get to the underlying SqlCommand objects of a partial class in a global way?
for some reason, my adapter's .selectcommand was null so i ended up having to go through the CommandCollection object instead, so i thought i'd post my small change based on the previous answer above. includes: ``` using System.ComponentModel; using System.Reflection; ``` code: ``` private void ChangeTimeout(Component component, int timeout) { if (!component.GetType().Name.Contains("TableAdapter")) { return; } PropertyInfo adapterProp = component.GetType().GetProperty("CommandCollection", BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.Instance); if (adapterProp == null) { return; } SqlCommand[] command = adapterProp.GetValue(component, null) as SqlCommand[]; if (command == null) { return; } command[0].CommandTimeout = timeout; } ```
All generated TableAdapters inherit from Component. Therefore, you could write a method like this that uses reflection to extract the adapter property: ``` private void ChangeTimeout(Component component, int timeout) { if (!component.GetType().Name.Contains("TableAdapter")) { return; } PropertyInfo adapterProp = component.GetType().GetProperty("Adapter", BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.Instance); if (adapterProp == null) { return; } SqlDataAdapter adapter = adapterProp.GetValue(component, null) as SqlDataAdapter; if (adapter == null) { return; } adapter.SelectCommand.CommandTimeout = timeout; } ``` You then can call it like this: ``` MyTableAdapter ta = new MyTableAdapter(); this.ChangeTimeout(ta,1000); ``` I'm assuming that since you're using typed DataSet's that you're still in .NET 2.0 which is why I didn't bother making this an extension method.
Control TableAdapter Command Timeout Globally
[ "", "c#", "tableadapter", "" ]
For simplicity, assume all relevant fields are `NOT NULL`. You can do: ``` SELECT table1.this, table2.that, table2.somethingelse FROM table1, table2 WHERE table1.foreignkey = table2.primarykey AND (some other conditions) ``` Or else: ``` SELECT table1.this, table2.that, table2.somethingelse FROM table1 INNER JOIN table2 ON table1.foreignkey = table2.primarykey WHERE (some other conditions) ``` Do these two work on the same way in `MySQL`?
`INNER JOIN` is ANSI syntax that you should use. It is generally considered more readable, especially when you join lots of tables. It can also be easily replaced with an `OUTER JOIN` whenever a need arises. The `WHERE` syntax is more relational model oriented. A result of two tables `JOIN`ed is a cartesian product of the tables to which a filter is applied which selects only those rows with joining columns matching. It's easier to see this with the `WHERE` syntax. As for your example, in MySQL (and in SQL generally) these two queries are synonyms. Also, note that MySQL also has a `STRAIGHT_JOIN` clause. Using this clause, you can control the `JOIN` order: which table is scanned in the outer loop and which one is in the inner loop. You cannot control this in MySQL using `WHERE` syntax.
Others have pointed out that `INNER JOIN` helps human readability, and that's a top priority, I agree. Let me try to explain *why* the join syntax is more readable. A basic `SELECT` query is this: ``` SELECT stuff FROM tables WHERE conditions ``` The `SELECT` clause tells us **what** we're getting back; the `FROM` clause tells us **where** we're getting it from, and the `WHERE` clause tells us **which** ones we're getting. `JOIN` is a statement about the tables, how they are bound together (conceptually, actually, into a single table). Any query elements that control the tables - where we're getting stuff from - semantically belong to the `FROM` clause (and of course, that's where `JOIN` elements go). Putting joining-elements into the `WHERE` clause conflates the **which** and the **where-from**, that's why the `JOIN` syntax is preferred.
INNER JOIN ON vs WHERE clause
[ "", "sql", "mysql", "join", "inner-join", "" ]
I am new to unit testing and I am trying to test some of my .NET membership stuff I been writing. So I am trying to check my `VerifyUser` method that checks if the users credentials are valid or not. So this is what it looks like: ``` public bool VerifyUser(string userName, string password) { bool valid = Membership.ValidateUser(userName, password); return valid; } ``` And now every time I run my unit test it fails. I know I am passing in the right credentials and stuff. Then it dawned on me that maybe my Test Project(that is under the same Solution as my real project) might need its own `web.config` file with the connection string and stuff. Or an app config file maybe since it is a Application Library project. So do I just copy the `web.config` file from my real project and call it a day? Or should I only be taking parts from it? Or am I just way off. My database is using a custom database with the .net membership merged with my database. So in my config file I had to specify a ManagerProvider and a roleProvider. This is how my unit test looks like ``` [Test] public void TestVerifyUser() { AuthenticateUser authenitcate = new AuthenticateUser(); bool vaild = authenitcate.VerifyUser("chobo3", "1234567"); Assert.That(vaild, Is.True); } ``` Also later on I have in one of my asp.net mvc ActionResult Methods(the Login View to be exact) I have this: FormsAuthentication.RedirectFromLoginPage(loginValidation.UserName, rememberMe); So now how can I write a unit test that would do what a user would do. Say they start at the Home page then click on the login page and log in successfully. I want them to be redirect to the home page. I am not sure how to represent that in code. I am pretty sure that the `RedirectFromLoginPage` works and thats now what I am really testing. I am testing the fact that I have 3 things that can happen in the login `ActionResult` method. 1. User logs in and gets sent back where they came from. 2. User fails to login and gets sent back to the `LoginView` and sees error messages. 3. User has tried to go to a secure and has been redirect to the login page. If the login successfully the will be redirect back to the secure page via the ReturnUrl. So I want to do a test to see if these work as they should. So thats why I need to have the user coming from like the home page to see if they get redirected back to it later and if they come from a secure page they get redirect back to that later on. I am also by the way using NUnit 2.5 and VS2008 Pro. --- This is what I am trying to test. I am at the part where I am trying to see if the user is valid or not(the if statement). I have no clue how to test it. ``` public ActionResult Login(string returnUrl, FormCollection form, bool rememberMe) { LoginValidation loginValidation = new LoginValidation(); try { UpdateModel(loginValidation, form.ToValueProvider()); } catch { return View("Login"); } if (ModelState.IsValid == true) { bool valid = authenticate.VerifyUser(loginValidation.UserName, loginValidation.Password); if (valid == false) { ModelState.AddModelError("frm_Login", "Either the Password or UserName is invalid"); } else if (string.IsNullOrEmpty(returnUrl) == false) { /* if the user has been sent away from a page that requires them to login and they do * login then redirect them back to this area*/ return Redirect(returnUrl); } else { FormsAuthentication.RedirectFromLoginPage(loginValidation.UserName, rememberMe); } } return View("Login"); } ```
You can test your controllers and much of your custom provider by refactoring your custom membership code into a two layers: a data access repository that only interacts with the database, and a service layer that uses repository components to provide the Membership API. The service layer is where you would validate arguments, hold and enforce parameters like EnablePasswordReset and translate any database exceptions or status codes into a form suitable for controller consumption. When you specify each layer with its own interface, consumers can write to that interface regardless of how its implemented. When your app is running your provider is of course talking to the database through these interfaces but for testing you can mock the repository or service interfaces. You can test your service layer by mocking the repository level without have to mess with the database or the web.config file, and you can test your controllers by mocking the service layer. If you don't want to refactor the whole provider, you can still test your controllers if you only create the service interface and have your controllers use it. To be specific, if a little verbose, your repository and service interfaces might look something like: ``` namespace Domain.Abstract { public interface IRepository { string ConnectionString { get; } } } namespace Domain.Abstract { public interface IUserRepository : IRepository { MembershipUser CreateUser(Guid userId, string userName, string password, PasswordFormat passwordFormat, string passwordSalt, string email, string passwordQuestion, string passwordAnswer, bool isApproved, DateTime currentTimeUtc, bool uniqueEmail); MembershipUser GetUser(Guid userId, bool updateLastActivity, DateTime currentTimeUtc); PasswordData GetPasswordData(Guid userId, bool updateLastLoginActivity, DateTime currentTimeUtc); void UpdatePasswordStatus(Guid userId, bool isAuthenticated, int maxInvalidPasswordAttempts, int passwordAttemptWindow, DateTime currentTimeUtc, bool updateLastLoginActivity, DateTime lastLoginDate, DateTime lastActivityDate); //.... } } namespace Domain.Abstract { public interface IUserService { bool EnablePasswordRetrieval { get; } bool EnablePasswordReset { get; } bool RequiresQuestionAndAnswer { get; } bool RequiresUniqueEmail { get; } //.... MembershipUser CreateUser(string applicationName, string userName, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved); MembershipUser GetUser(Guid userId, bool userIsOnline); bool ValidateUser(Guid userId, string password); //... } } namespace Domain.Concrete { public class UserService : IUserService { private IUserRepository _userRepository; public UserService(IUserRepository userRepository) { _userRepository = userRepository; } //... public bool ValidateUser(Guid userId, string password) { // validate applicationName and password here bool ret = false; try { PasswordData passwordData; ret = CheckPassword(userId, true, true, DateTime.UtcNow, out passwordData); } catch (ObjectLockedException e) { throw new RulesException("userName", Resource.User_AccountLockOut); } return ret; } private bool CheckPassword(Guid userId, string password, bool updateLastLoginActivityDate, bool failIfNotApproved, DateTime currentTimeUtc, out PasswordData passwordData) { passwordData = _userRepository.GetPasswordData(userId, updateLastLoginActivityDate, currentTimeUtc); if (!passwordData.IsApproved && failIfNotApproved) return false; string encodedPassword = EncodePassword(password, passwordData.PasswordFormat, passwordData.PasswordSalt); bool isAuthenticated = passwordData.Password.Equals(encodedPassword); if (isAuthenticated && passwordData.FailedPasswordAttemptCount == 0 && passwordData.FailedPasswordAnswerAttemptCount == 0) return true; _userRepository.UpdatePasswordStatus(userId, isAuthenticated, _maxInvalidPasswordAttempts, _passwordAttemptWindow, currentTimeUtc, updateLastLoginActivityDate, isAuthenticated ? currentTimeUtc : passwordData.LastLoginDate, isAuthenticated ? currentTimeUtc : passwordData.LastActivityDate); return isAuthenticated; } } ```
The Asp.Net Membership system is designed to work in the context of an Asp.Net request. So, you have three options here. 1. Most people when faced with such a dependency would write a thin wrapper around it. The wrapper doesn't do anything, just redirects all calls to the underlying dependency. So, they just don't test it. Your AuthenticateUser is such a wrapper. You should probably make all methods virtual or extract an interface in order to make it mockable, but that's another story. 2. Use TypeMock Isolator and mock Membership. 3. Use the [Ivonna framework](http://sm-art.biz/Ivonna.aspx) and run your test in the Asp.Net context (that would be an integration test).
How to Unit Test Asp.net Membership?
[ "", "c#", ".net", "asp.net-mvc", "unit-testing", "nunit", "" ]
Is there a straightforward way to enumerate all visible network printers in .NET? Currently, I'm showing the PrintDialog to allow the user to select a printer. The problem with that is, local printers are displayed as well (along with XPS Document Writer and the like). If I can enumerate network printers myself, I can show a custom dialog with just those printers. Thanks!!
found this code [here](http://www.dotnetcurry.com/ShowArticle.aspx?ID=148&AspxAutoDetectCookieSupport=1) ``` private void btnGetPrinters_Click(object sender, EventArgs e) { // Use the ObjectQuery to get the list of configured printers System.Management.ObjectQuery oquery = new System.Management.ObjectQuery("SELECT * FROM Win32_Printer"); System.Management.ManagementObjectSearcher mosearcher = new System.Management.ManagementObjectSearcher(oquery); System.Management.ManagementObjectCollection moc = mosearcher.Get(); foreach (ManagementObject mo in moc) { System.Management.PropertyDataCollection pdc = mo.Properties; foreach (System.Management.PropertyData pd in pdc) { if ((bool)mo["Network"]) { cmbPrinters.Items.Add(mo[pd.Name]); } } } } ``` Update: "This API function can enumerate all network resources, including servers, workstations, printers, shares, remote directories etc." <http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=741&lngWId=10>
* Get the default printer from `LocalPrintServer.DefaultPrintQueue` * Get the installed printers (from user's perspective) from `PrinterSettings.InstalledPrinters` * Enumerate through the list: * Any printer beginning with `\\` is a network printer - so get the queue with `new PrintServer("\\UNCPATH").GetPrintQueue("QueueName")` * Any printer not beginning with `\\` is a local printer so get it with `LocalPrintServer.GetQueue("Name")` * You can see which is default by comparing `FullName` property. Note: a network printer can be the default printer from `LocalPrintServer.DefaultPrintQueue`, but not appear in `LocalPrintServer.GetPrintQueues()` ``` // get available printers LocalPrintServer printServer = new LocalPrintServer(); PrintQueue defaultPrintQueue = printServer.DefaultPrintQueue; // get all printers installed (from the users perspective)he t var printerNames = PrinterSettings.InstalledPrinters; var availablePrinters = printerNames.Cast<string>().Select(printerName => { var match = Regex.Match(printerName, @"(?<machine>\\\\.*?)\\(?<queue>.*)"); PrintQueue queue; if (match.Success) { queue = new PrintServer(match.Groups["machine"].Value).GetPrintQueue(match.Groups["queue"].Value); } else { queue = printServer.GetPrintQueue(printerName); } var capabilities = queue.GetPrintCapabilities(); return new AvailablePrinterInfo() { Name = printerName, Default = queue.FullName == defaultPrintQueue.FullName, Duplex = capabilities.DuplexingCapability.Contains(Duplexing.TwoSidedLongEdge), Color = capabilities.OutputColorCapability.Contains(OutputColor.Color) }; }).ToArray(); DefaultPrinter = AvailablePrinters.SingleOrDefault(x => x.Default); ```
Is there a .NET way to enumerate all available network printers?
[ "", "c#", ".net", "network-printers", "" ]
I'm looking for a way using jQuery to return an object of computed styles for the 1st matched element. I could then pass this object to another call of jQuery's css method. For example, with [width](http://docs.jquery.com/CSS/width), I can do the following to make the 2 divs have the same width: ``` $('#div2').width($('#div1').width()); ``` It would be nice if I could **make a text input look like an existing span**: ``` $('#input1').css($('#span1').css()); ``` where .css() with no argument returns an object that can be passed to [.css(obj)](http://docs.jquery.com/CSS/css#properties). (I can't find a jQuery plugin for this, but it seems like it should exist. If it doesn't exist, I'll turn mine below into a plugin and post it with all the properties that I use.) Basically, I want to pseudo clone certain elements **but use a different tag**. For example, I have an li element that I want to hide and put an input element over it that looks the same. When the user types, **it looks like they are editing the element inline**. **I'm also open to other approaches for this pseudo cloning problem for editing.** Any suggestions? Here's what I currently have. The only problem is just getting all the possible styles. This could be a ridiculously long list. --- ``` jQuery.fn.css2 = jQuery.fn.css; jQuery.fn.css = function() { if (arguments.length) return jQuery.fn.css2.apply(this, arguments); var attr = ['font-family','font-size','font-weight','font-style','color', 'text-transform','text-decoration','letter-spacing','word-spacing', 'line-height','text-align','vertical-align','direction','background-color', 'background-image','background-repeat','background-position', 'background-attachment','opacity','width','height','top','right','bottom', 'left','margin-top','margin-right','margin-bottom','margin-left', 'padding-top','padding-right','padding-bottom','padding-left', 'border-top-width','border-right-width','border-bottom-width', 'border-left-width','border-top-color','border-right-color', 'border-bottom-color','border-left-color','border-top-style', 'border-right-style','border-bottom-style','border-left-style','position', 'display','visibility','z-index','overflow-x','overflow-y','white-space', 'clip','float','clear','cursor','list-style-image','list-style-position', 'list-style-type','marker-offset']; var len = attr.length, obj = {}; for (var i = 0; i < len; i++) obj[attr[i]] = jQuery.fn.css2.call(this, attr[i]); return obj; } ``` Edit: I've now been using the code above for awhile. It works well and behaves exactly like the original css method with one exception: if 0 args are passed, it returns the computed style object. As you can see, it immediately calls the original css method if that's the case that applies. Otherwise, it gets the computed styles of all the listed properties (gathered from Firebug's computed style list). Although it's getting a long list of values, it's quite fast. Hope it's useful to others.
Two years late, but I have the solution you're looking for. Here's a plugin I wrote (by wrapping another guy's function in plugin format) which does exactly what you want, but gets **all** possible styles in all browsers, even IE. `jquery.getStyleObject.js:` ``` /* * getStyleObject Plugin for jQuery JavaScript Library * From: http://upshots.org/?p=112 * * Copyright: Unknown, see source link * Plugin version by Dakota Schneider (http://hackthetruth.org) */ (function($){ $.fn.getStyleObject = function(){ var dom = this.get(0); var style; var returns = {}; if(window.getComputedStyle){ var camelize = function(a,b){ return b.toUpperCase(); } style = window.getComputedStyle(dom, null); for(var i=0;i<style.length;i++){ var prop = style[i]; var camel = prop.replace(/\-([a-z])/g, camelize); var val = style.getPropertyValue(prop); returns[camel] = val; } return returns; } if(dom.currentStyle){ style = dom.currentStyle; for(var prop in style){ returns[prop] = style[prop]; } return returns; } return this.css(); } })(jQuery); ``` Basic usage is pretty simple: ``` var style = $("#original").getStyleObject(); // copy all computed CSS properties $("#original").clone() // clone the object .parent() // select it's parent .appendTo() // append the cloned object to the parent, after the original // (though this could really be anywhere and ought to be somewhere // else to show that the styles aren't just inherited again .css(style); // apply cloned styles ```
It's not jQuery but, in Firefox, Opera and Safari you can use `window.getComputedStyle(element)` to get the computed styles for an element and in IE<=8 you can use `element.currentStyle`. The returned objects are different in each case, and I'm not sure how well either work with elements and styles created using Javascript, but perhaps they'll be useful. In Safari you can do the following which is kind of neat: ``` document.getElementById('b').style.cssText = window.getComputedStyle(document.getElementById('a')).cssText; ```
jQuery CSS plugin that returns computed style of element to pseudo clone that element?
[ "", "javascript", "jquery", "css", "web-applications", "" ]
In the spirit of the [c#](https://stackoverflow.com/questions/282459/what-is-the-c-equivalent-to-javas-instanceof-and-isinstance) question.. What is the equivalent statements to compare class types in VB.NET?
Are you looking for something like `TypeOf`? This only works with reference types, not int/etc. ``` If TypeOf "value" Is String Then Console.WriteLine("'tis a string, m'lord!") ``` Or do you want to compare two different instances of variables? Also works for ref types: ``` Dim one As Object = "not an object" Dim two As Object = "also not an object, exactly" Dim three as Object = 3D If one.GetType.Equals( two.GetType ) Then WL("They are the same, man") If one.GetType Is two.GetType then WL("Also the same") If one.GetType IsNot three.GetType Then WL("but these aren't") ``` You could also use `gettype()` like thus, if you aren't using two objects: ``` If three.GetType Is gettype(integer) then WL("is int") ``` If you want to see if something is a subclass of another type (and are in .net 3.5): ``` If three.GetType.IsSubclassOf(gettype(Object)) then WL("it is") ``` But if you want to do that in the earlier versions, you have to flip it (weird to look at) and use: ``` If gettype(Object).IsAssignableFrom(three.GetType) Then WL("it is") ``` All of these compile in [SnippetCompiler](http://www.sliver.com/dotnet/SnippetCompiler/), so go DL if you don't have it.
``` TypeOf obj Is MyClass ```
What is the VB equivalent of Java's instanceof and isInstance()?
[ "", "java", "vb.net", "reflection", "introspection", "instanceof", "" ]
I have a large PDF file that is a floor map for a building. It has layers for all the office furniture including text boxes of seat location. My goal is to read this file with PHP, search the document for text layers, get their contents and coordinates in the file. This way I can map out seat locations -> x/y coordinates. Is there any way to do this via PHP? (Or even Ruby or Python if that's what's necessary)
Check out FPDF (with FPDI): <http://www.fpdf.org/> <http://www.setasign.de/products/pdf-php-solutions/fpdi/> These will let you open an pdf and add content to it in PHP. I'm guessing you can also use their functionality to search through the existing content for the values you need. Another possible library is TCPDF: <https://tcpdf.org/> Update to add a more modern library: [PDF Parser](http://www.pdfparser.org/documentation)
There is a php library (pdfparser) that does exactly what you want. **project website** <http://www.pdfparser.org/> **github** <https://github.com/smalot/pdfparser> **Demo page/api** <http://www.pdfparser.org/demo> After including pdfparser in your project you can get all text from `mypdf.pdf` like so: ``` <?php $parser = new \installpath\PdfParser\Parser(); $pdf = $parser->parseFile('mypdf.pdf'); $text = $pdf->getText(); echo $text;//all text from mypdf.pdf ?> ``` Simular you can get the metadata from the pdf as wel as getting the pdf objects (for example images).
Read pdf files with php
[ "", "php", "pdf", "" ]
Following SQL command ``` select TO_CHAR(NVL(arg1 - arg2, TO_DSINTERVAL('0 00:00:00'))) from table1 ``` produces a result of the format: +000000000 00:03:01.954000. Is it possible to enter a special format in the to\_char function in order to get a result of format: +00 00:00:00.000?
I realize it's not clever at all, nor is it the special format string you're looking for, but this answer does work, given that the output is fixed length: ``` SELECT SUBSTR(TO_CHAR(NVL(arg1 - arg2, TO_DSINTERVAL('0 00:00:00'))), 1, 1) || SUBSTR(TO_CHAR(NVL(arg1 - arg2, TO_DSINTERVAL('0 00:00:00'))), 9, 2) || ' ' || SUBSTR(TO_CHAR(NVL(arg1 - arg2, TO_DSINTERVAL('0 00:00:00'))), 12, 12) FROM table1; ``` It also just truncs the fractional seconds instead of rounding, but I assume from your example they're all just zeros anyway. This is an even greater embarrassment, but I couldn't resist: ``` SELECT SUBSTR(REPLACE(TO_CHAR(NVL(arg1 - arg2, TO_DSINTERVAL('0 00:00:00'))) , '0000000', '') , 1, 16) FROM table1; ```
you could cast the result if you want less precision: ``` SQL> SELECT TO_DSINTERVAL('10 10:00:00') t_interval FROM dual; T_INTERVAL ----------------------------------------------------------- +000000010 10:00:00.000000000 SQL> SELECT CAST(TO_DSINTERVAL('10 10:00:00') 2 AS INTERVAL DAY(2) TO SECOND(3)) t_interval 3 FROM dual; T_INTERVAL ----------------------------------------------------------- +10 10:00:00.000 ``` Edit following OP comment: From The [Oracle Documentation (11gr1)](http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/sql_elements001.htm#i48042): > Interval datatypes do not have format models. Therefore, to adjust their presentation, you must combine character functions such as EXTRACT and concatenate the components. It seems you will have to manually use EXTRACT to achieve the desired output: ``` SQL> SELECT to_char(extract(DAY FROM t_interval), 'fmS99999') || ' ' || 2 to_char(extract(HOUR FROM t_interval), 'fm00') || ':' || 3 to_char(extract(MINUTE FROM t_interval), 'fm00') || ':' || 4 to_char(extract(SECOND FROM t_interval), 'fm00.000') 5 FROM (SELECT TO_DSINTERVAL('10 01:02:55.895') t_interval FROM dual) 6 ; TO_CHAR(EXTRACT(DAYFROMT_INTER ------------------------------ +10 01:02:55.895 ``` This is not very elegant but it seems it is the only way to deal with microseconds precision.
format interval with to_char
[ "", "sql", "oracle", "intervals", "" ]
I have a slightly unique requirement with the Java-JDBC API along with Oracle Database. I have autoCommit to be default which is true for Oracle and I am using the example similar to this [link](http://www.exampledepot.com/egs/java.sql/BatchUpdate.html). However, when I add say 1000 batches and lets say each of them are inserts. And Let us assume that about 20 records violated some constraints, I want the remaining 980 to go COMMITTED (and henceforth visible to any other queries using any other connection) to the database and ignore the 20 records. In the above example, when one row violates any transaction then **even when I commit in the catch block the transaction only commits until the first failure**. I know batch updates are to be done ONLY when you are fairly sure all rows will go through and exception processing is not one, but am planning to PATCH an existing database so some kind of "bad practices" is okay :) Any code samples will be highly appreciated. \*\*\*\* MORE DETAILS \*\*\*\* Using Simple insert/update is not okay since I am processing close to 3M rows so am batching every 1000 records. Simply adding 1000 inserts in loop (ignoring exceptions) takes way more time (about 5 seconds for every 1000 records) as opposed to the batch update < 300ms. Problem: With Oracle database the Driver seems to stop at the first FAILURE, ie when 1000 rows are batched and 100th failed, I want it to go ahead till the 1000th row. Me thinks this cannot be done in JDBC (with Oracle) Like the [link](http://www.exampledepot.com/egs/java.sql/BatchUpdate.html) indicates only few databases support such feature and probably Oracle is not one
I was looking some solution on the line of "With Oracle database the Driver seems to stop at the first FAILURE, ie when 1000 rows are batched and 100th failed, I want it to go ahead till the 1000th row." Basically I wanted to know if this can be done with Oracle JDBC driver. However a variety of answers have been proposed (most/all of which I had already considered) 1) Disabling the constraints/load data/remove offending rows/repeat this many times 2) Do all the checking before loading data 3) Decrease the batch size to 50 - 100. Unfortunately my checking cannot be done before loading and making batch size to be 50 or 100 means taking more time to do the 5M rows I have (infact the total time increased to a few hours instead of 40 mins with a batch size of 1000). I have resorted to keeping the batch size of 1000 **ACCEPTING THE problem as is** and put the code under a "while" loop and do the job until we fill up all rows. Like I said, since there is **NO WAY WITH ORACLE BATCH JDBC** to proceed after first failure, the answer to this question will be "NOT DOABLE" and just accept the constraints and document the fact that this tool takes about 40 mins to complete :)
You can use a PL/SQL stored procedure using the SAVE EXCEPTIONS clause which will allow you to issue a bulk update and then return those rows which could not be updated. Here is a couple of example links: <http://rwijk.blogspot.com/2007/11/save-exceptions.html> <http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:8912264456901>
JDBC Batch Update Problem
[ "", "java", "jdbc", "batch-file", "" ]
**update: Got a beautiful app with exclusive shortcuts for every view, all javascript. I'm gonna look into Fogbugz, i like the hovering shortcut-codes, thanks for the reference.** --- i want to make my site accessible and more usable for visitors. **Which keyCodes can I safely use to handle certain javascript actions?** With safely I mean: * keyCodes that don't interrupt with default browser actions + No direct functionality (like pressing `F1` for Help) + No indirect functionality (like pressing `Ctrl` + `C` for Copy) **Or should I prevent default actions from executing?**
I personally avoid using these keycodes or AccessKeys for a public-facing site, as there is no way to know whether you are conflicting with some predefined shortcuts in users' software like screenreading software, etc.
Maybe you should take a look at those questions: [Key Shortcuts in Web Application](https://stackoverflow.com/questions/912018/key-shortcuts-in-web-application) [Building a keyboard-accessible web application](https://stackoverflow.com/questions/362727/building-a-keyboard-accessible-web-application)
Which keyCodes can I safely use to make my website accessible?
[ "", "javascript", "keyboard-shortcuts", "usability", "accessibility", "" ]
When somebody clicks on my google adwords link like this: <http://www.myshoppingsite.com/product/rubberball.aspx?promo=promo123> I want my aspx page to read the "promo" parameter, hit the database to pull back some data, then display to the user a nice jquery type popup window over top of the product page. The user can read all about the promotion, then close that pop up and be at the product page they wanted to go to. I'm not sure how to do this...Do I read the parameter and get the data from the client side (via webservice or page method), or do I get the data and call the javascript from server side? I have created jquery popups before, but the data has always been on the client side already. I want to display a popup but get the data from a database. any ideas?
If you really think about it, there's no reason to do a trip back to the server in this kind of situation. You can simply check server-side if the `promo` GET parameter was passed, and if so display a hidden `<div>` with the promotion information: ``` <div style='display: none;' id='promo'> .... </div> ``` Once you do that, you can simply have some jQuery code to check whether this hidden `<div>` exists, and if so display the modal: ``` $(function() { if($('#promo').length > 0) { showModal($('#promo').html()); } }); ``` If you insist on querying the server through AJAX, this is fairly simple to do as well: ``` function gup( name ) { name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexS = "[\\?&]"+name+"=([^&#]*)"; var regex = new RegExp( regexS ); var results = regex.exec( window.location.href ); if( results == null ) return ""; else return results[1]; } $(function() { var promo = $.trim(gup('promo')); if(promo != '') { $.get('my/url/whatever.php', {promo: promo}, function(data) { showModal(data); }); } }); ``` Since you said you have experience with showing modal windows with jQuery I won't go into much detail as to what `showModal` should do; suffice it to say it should simply activate whatever your jQuery plugin uses to show the modal window.
So you want the popup on load? Render the page with the pop-up in place, with a means of closing the pop-up. Read the querystring at the server and render whatever content you want into it in a single operation. The only JS required is to hide the popup.
Want to use a jquery pop up, but get the data from server side
[ "", "asp.net", "javascript", "jquery", "html", "" ]
What I'm trying to do is take a 'input' video file (I can make it whatever file type will make this the easiest) and then, through my code, add text to the video file. So, for example, it would take 'Sample1.mpg' and output 'Sample2.mpg'. It wouldn't *show* the video (I've found some tutorials that talk about overlaying text as the video plays; but not actually modifying the video file. Basically, I'd like to be able to say, 'From seconds 1 to 200, draw 'Hi Mom' at position 0,0 with this font' and have that saved in the outputed video. Whenever you run the outputted video, with any player, you'd end up seeing the text; because it'd be part of the video file. I've heard claims like, 'DirectShow!' but I'd really welcome anything slightly more specific.
You can use an extremely powerful scripting language called avisynth link: <http://avisynth.org/> It works with ***ANY*** file you can play, it uses directshow. Just install it, it's basically installing a VFW codec, but very easy. Open notepad and type ``` DirectShowSource("C:\dir\filename.extension") Subtitle("Put Your text here") ``` Save it as "any name.**avs**" And ***THAT'S IT***. Now open it with any avi-capable application (you can even name it avi if you want!) and re-encode the video, or do processing. very easy and automatic. it works for pictures too. For a full reference of the Subtitle() capabilities go here: <http://avisynth.org/mediawiki/Subtitle> of course, avisynth can do wonders if you master it, like printing the system date on every frame of a recording (useful for security cams) or even complex processing like top-line noise reduction, sharpening and many, many other tasks, through external pugins. External Pugin reference: <http://avisynth.org/mediawiki/External_plugins> Easily downloadable plugins: <http://avisynth.org/warpenterprises/> It's as simple as it gets. 2 lines of code and you have a openable, seekable, processable, convertable fully-compatible and less than 1 KB AVI (the subtitles are added on-the-fly when you open the AVS on your app)
I'd suggest reading more into this: [Options for predictable frame capture in .NET application](https://stackoverflow.com/questions/378107/options-for-predictable-frame-capture-in-net-application) And then using ``` Graphics g = Graphics.FromImage(bitmap); ``` To get the frame into .NET and then look at a using this: ``` GraphicsPath path = new GraphicsPath(); path.AddString("Yadda", font.FontFamily, (int)font.Style, font.Size, rect, format); ``` Then use ``` g.FillPath(..path..) ``` to add the drawing to the frame. How to stick it back into the MPG??? I guess you're then back to using the code/project referenced in the link at the top. It just seems to me to be a case of extract BMP frame, use .NET drawing to add stuff to it, then reinsert. Looking at how CAPTCHAs are made in .NET is probably helpful. Good luck!!
Adding Text Into a Video and Saving the Output
[ "", "c#", "vb.net", "video", "" ]
I have an InputStream of a file and i use apache poi components to read from it like this: ``` POIFSFileSystem fileSystem = new POIFSFileSystem(inputStream); ``` The problem is that i need to use the same stream multiple times and the POIFSFileSystem closes the stream after use. What is the best way to cache the data from the input stream and then serve more input streams to different POIFSFileSystem ? EDIT 1: By cache i meant store for later use, not as a way to speedup the application. Also is it better to just read up the input stream into an array or string and then create input streams for each use ? EDIT 2: Sorry to reopen the question, but the conditions are somewhat different when working inside desktop and web application. First of all, the InputStream i get from the org.apache.commons.fileupload.FileItem in my tomcat web app doesn't support markings thus cannot reset. Second, I'd like to be able to keep the file in memory for faster acces and less io problems when dealing with files.
you can decorate InputStream being passed to *POIFSFileSystem* with a version that when close() is called it respond with reset(): ``` class ResetOnCloseInputStream extends InputStream { private final InputStream decorated; public ResetOnCloseInputStream(InputStream anInputStream) { if (!anInputStream.markSupported()) { throw new IllegalArgumentException("marking not supported"); } anInputStream.mark( 1 << 24); // magic constant: BEWARE decorated = anInputStream; } @Override public void close() throws IOException { decorated.reset(); } @Override public int read() throws IOException { return decorated.read(); } } ``` ## testcase ``` static void closeAfterInputStreamIsConsumed(InputStream is) throws IOException { int r; while ((r = is.read()) != -1) { System.out.println(r); } is.close(); System.out.println("========="); } public static void main(String[] args) throws IOException { InputStream is = new ByteArrayInputStream("sample".getBytes()); ResetOnCloseInputStream decoratedIs = new ResetOnCloseInputStream(is); closeAfterInputStreamIsConsumed(decoratedIs); closeAfterInputStreamIsConsumed(decoratedIs); closeAfterInputStreamIsConsumed(is); } ``` ## EDIT 2 you can read the entire file in a byte[] (slurp mode) then passing it to a ByteArrayInputStream
Try BufferedInputStream, which adds mark and reset functionality to another input stream, and just override its close method: ``` public class UnclosableBufferedInputStream extends BufferedInputStream { public UnclosableBufferedInputStream(InputStream in) { super(in); super.mark(Integer.MAX_VALUE); } @Override public void close() throws IOException { super.reset(); } } ``` So: ``` UnclosableBufferedInputStream bis = new UnclosableBufferedInputStream (inputStream); ``` and use `bis` wherever inputStream was used before.
How to Cache InputStream for Multiple Use
[ "", "java", "caching", "inputstream", "apache-poi", "" ]
In a lot of frameworks/AMS/CMS I see folders of "helper" scripts and classes. What exactly do helper scripts and classes do? What is their specific purpose. Is that defined by the developer or is their a standard for their function?
Helper classes/scripts, in general, are utilities that are used by an application to perform certain tasks. Usually, these classes are created to centralize common task logic that is performed again and again throughout the application. These utilities are often very specific, and perform 'actions' on data or objects within the application. Common examples would be string manipulation, input parsing, encryption/decryption utilities, or mathematical calculations.
I know that it means **classes that help you in performing your tasks**. It may be parsing a String in a specific way or some general purpose calculation one needs in various parts of its code. Usually in Java (don't know php) they take the form of a bunch of static methods in a class named Util, or at least that's how I've always seen it. From wikipedia > Helper classes are a term given to classes that are used to assist in providing some functionality, though that functionality isn't the main goal of the application.
What are helper classes and scripts?
[ "", "php", "frameworks", "content-management-system", "helper", "" ]
I've got a situation where I need to generate a class with a large string const. Code outside of my control causes my generated CodeDom tree to be emitted to C# source and then later compiled as part of a larger Assembly. Unfortunately, I've run into a situation whereby if the length of this string exceeds 335440 chars in Win2K8 x64 (926240 in Win2K3 x86), the C# compiler exits with a fatal error: > [fatal error CS1647: An expression is too long or complex to compile near 'int'](http://msdn.microsoft.com/en-us/library/92855ayd.aspx) MSDN says CS1647 is "a stack overflow in the compiler" (no pun intended!). Looking more closely I've determined that the CodeDom "nicely" wraps my string const at 80 chars.This causes the compiler to concatenate over 4193 string chunks which apparently is the stack depth of the C# compiler in x64 NetFx. CSC.exe must internally recursively evaluate this expression to "rehydrate" my single string. My initial question is this: "**does anyone know of a work-around to change how the code generator emits strings?**" I cannot control the fact that the external system uses C# source as an intermediate and I want this to be a constant (rather than a runtime concatenation of strings). Alternatively, **how can I formulate this expression such that after a certain number of chars, I am still able to create a constant but it is composed of multiple *large* chunks?** Full repro is here: ``` // this string breaks CSC: 335440 is Win2K8 x64 max, 926240 is Win2K3 x86 max string HugeString = new String('X', 926300); CodeDomProvider provider = CodeDomProvider.CreateProvider("C#"); CodeCompileUnit code = new CodeCompileUnit(); // namespace Foo {} CodeNamespace ns = new CodeNamespace("Foo"); code.Namespaces.Add(ns); // public class Bar {} CodeTypeDeclaration type = new CodeTypeDeclaration(); type.IsClass = true; type.Name = "Bar"; type.Attributes = MemberAttributes.Public; ns.Types.Add(type); // public const string HugeString = "XXXX..."; CodeMemberField field = new CodeMemberField(); field.Name = "HugeString"; field.Type = new CodeTypeReference(typeof(String)); field.Attributes = MemberAttributes.Public|MemberAttributes.Const; field.InitExpression = new CodePrimitiveExpression(HugeString); type.Members.Add(field); // generate class file using (TextWriter writer = File.CreateText("FooBar.cs")) { provider.GenerateCodeFromCompileUnit(code, writer, new CodeGeneratorOptions()); } // compile class file CompilerResults results = provider.CompileAssemblyFromFile(new CompilerParameters(), "FooBar.cs"); // output reults foreach (string msg in results.Output) { Console.WriteLine(msg); } // output errors foreach (CompilerError error in results.Errors) { Console.WriteLine(error); } ```
Using a CodeSnippetExpression and a manually quoted string, I was able to emit the source that I would have liked to have seen from Microsoft.CSharp.CSharpCodeGenerator. So to answer the question above, replace this line: ``` field.InitExpression = new CodePrimitiveExpression(HugeString); ``` with this: ``` field.InitExpression = new CodeSnippetExpression(QuoteSnippetStringCStyle(HugeString)); ``` And finally modify the private string quoting Microsoft.CSharp.CSharpCodeGenerator.QuoteSnippetStringCStyle method to not wrap after 80 chars: ``` private static string QuoteSnippetStringCStyle(string value) { // CS1647: An expression is too long or complex to compile near '...' // happens if number of line wraps is too many (335440 is max for x64, 926240 is max for x86) // CS1034: Compiler limit exceeded: Line cannot exceed 16777214 characters // theoretically every character could be escaped unicode (6 chars), plus quotes, etc. const int LineWrapWidth = (16777214/6) - 4; StringBuilder b = new StringBuilder(value.Length+5); b.Append("\r\n\""); for (int i=0; i<value.Length; i++) { switch (value[i]) { case '\u2028': case '\u2029': { int ch = (int)value[i]; b.Append(@"\u"); b.Append(ch.ToString("X4", CultureInfo.InvariantCulture)); break; } case '\\': { b.Append(@"\\"); break; } case '\'': { b.Append(@"\'"); break; } case '\t': { b.Append(@"\t"); break; } case '\n': { b.Append(@"\n"); break; } case '\r': { b.Append(@"\r"); break; } case '"': { b.Append("\\\""); break; } case '\0': { b.Append(@"\0"); break; } default: { b.Append(value[i]); break; } } if ((i > 0) && ((i % LineWrapWidth) == 0)) { if ((Char.IsHighSurrogate(value[i]) && (i < (value.Length - 1))) && Char.IsLowSurrogate(value[i + 1])) { b.Append(value[++i]); } b.Append("\"+\r\n"); b.Append('"'); } } b.Append("\""); return b.ToString(); } ```
So am I right in saying you've got the C# source file with something like: ``` public const HugeString = "xxxxxxxxxxxx...." + "yyyyy....." + "zzzzz....."; ``` and you *then* try to compile it? If so, I would try to edit the text file (in code, of course) before compiling. That should be relatively straightforward to do, as presumably they'll follow a rigidly-defined pattern (compared with human-generated source code). Convert it to have a single massive line for each constant. Let me know if you'd like some sample code to try this. By the way, your repro succeeds with no errors on my box - which version of the framework are you using? (My box has the beta of 4.0 on, which may affect things.) EDIT: How about changing it to not be a string constant? You'd need to break it up yourself, and emit it as a public static readonly field like this: ``` public static readonly HugeString = "xxxxxxxxxxxxxxxx" + string.Empty + "yyyyyyyyyyyyyyyyyyy" + string.Empty + "zzzzzzzzzzzzzzzzzzz"; ``` Crucially, `string.Empty` is a `public static readonly` field, *not* a constant. That means the C# compiler will just emit a call to `string.Concat` which may well be okay. It'll only happen once at execution time of course - slower than doing it at compile-time, but it may be an easier workaround than anything else.
Work-around for C# CodeDom causing stack-overflow (CS1647) in csc.exe?
[ "", "c#", "compiler-construction", "codedom", "csc", "" ]
I have two JSPs and a JavaBean that aren't working. I'm using Tomcat 6.0. The first JSP is GetName.jsp, located at C:\Tomcat\webapps\app1\GetName.jsp: ``` <HTML> <BODY> <FORM METHOD=POST ACTION="NextPage.jsp"> What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR> What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR> What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4> <P><INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML> ``` The second JSP is NextPage.jsp, located at C:\Tomcat\webapps\app1\NextPage.jsp: ``` <jsp:useBean id="user" class="classes.UserData" scope="session"/> <HTML> <BODY> You entered<BR> Name: <jsp:getProperty name="user" property="username" /><BR> Email: <jsp:getProperty name="user" property="email" /><BR> Age: <jsp:getProperty name="user" property="age" /><BR> </BODY> </HTML> ``` My JavaBean, UserData, compiles correcty, and the class file is located at C:\Tomcat\webapps\app1\WEB-INF\classes: ``` package classes; import java.io.Serializable; public class UserData implements Serializable { String username; String email; int age; public UserData() { } public void setUsername( String value ) { username = value; } public void setEmail( String value ) { email = value; } public void setAge( int value ) { age = value; } public String getUsername() { return username; } public String getEmail() { return email; } public int getAge() { return age; } } ``` I also have the following in my web.xml file, located at C:\Tomcat\webapps\app1\WEB-INF: ``` <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app> </web-app> ``` My Google searches have suggested something to do with the classpath. My classpath is currently .;C:\Tomcat\lib\servlet-api.jar. When I enter information in GetName.jsp and click on the button, Tomcat gives me the following for NextPage.jsp: ``` org.apache.jasper.JasperException: /NextPage.jsp(1,1) The value for the useBean class attribute classes.UserData is invalid. org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40) org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407) org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:148) org.apache.jasper.compiler.Generator$GenerateVisitor.visit(Generator.java:1203) org.apache.jasper.compiler.Node$UseBean.accept(Node.java:1160) org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2343) org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2393) org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2399) org.apache.jasper.compiler.Node$Root.accept(Node.java:489) org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2343) org.apache.jasper.compiler.Generator.generate(Generator.java:3365) org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:199) org.apache.jasper.compiler.Compiler.compile(Compiler.java:315) org.apache.jasper.compiler.Compiler.compile(Compiler.java:295) org.apache.jasper.compiler.Compiler.compile(Compiler.java:282) org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:586) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267) javax.servlet.http.HttpServlet.service(HttpServlet.java:717) ``` I could swear I'm doing everything right, but apparently I'm not. Could someone please tell me what's wrong before I tear all my hair out? Thanks in advance.
You need to set the bean properties in your NextPage.jsp file. Add the following line after your useBean statement like this. ``` <jsp:useBean id="user" class="UserData" scope="session"/> <jsp:setProperty name="user" property="*" /> ```
The problem is that your `UserData.class` file is in wrong directory, which means `UserData.class` should actually be in `webapps/app1/WEB-INF/classes/classes/UserData.class`.
JavaBean 'value for the useBean class attribute classes.UserData is invalid'
[ "", "java", "attributes", "javabeans", "" ]
One thing that always bugged me, is that I do not see the base type in Visual Studio. I just stumbled on this, because I tried to cast a System.Windows.Forms.MenuItem to a System.Windows.Forms.Control In eclipse the "intellisense" (or whatever it is called) shows me while exploring the members of a class for each member from which base class it is inherited. In Visual Studio I cannot see the base class, even if I use the Objectbrowser or the help. The only solution I found is to use at runtime: ``` Console.WriteLine(obj.GetType.BaseType) Console.WriteLine(obj.GetType.BaseType.BaseType) Console.WriteLine(obj.GetType.BaseType.BaseType.BaseType) ... ``` until I reach System.Object(). Is there a way to query the base type tree of a class at Design Time?
You can see this in the Object Browser; if you click the (+) sign in front of the type, there should be a folder called "Base Types" where you can explore what type the type inherits from, and any interfaces that it implements. There is a setting that controls this; in the tool bar of the Object Browser there is a Settings tool menu; make sure that "Show base types" is checked. ![alt text](https://i612.photobucket.com/albums/tt209/fredrikmork/objectbrowserbasetypes.png)
View -> Class View Usually I just do the "Go to Definition" in the context menu though.
Where to find base type of a class
[ "", "c#", "vb.net", "visual-studio-2008", "" ]