Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Should methods in a Java interface be declared with or without the `public` access modifier? Technically it doesn't matter, of course. A class method that implements an `interface` is always `public`. But what is a better convention? Java itself is not consistent in this. See for instance `Collection` vs. `Comparable...
The [JLS](http://docs.oracle.com/javase/specs/jls/se7/html/jls-9.html#jls-9.4) makes this clear: > It is permitted, but discouraged as a matter of style, to redundantly specify the `public` and/or `abstract` modifier for a method declared in an interface.
The public modifier should be omitted in Java interfaces (in my opinion). Since it does not add any extra information, it just draws attention away from the important stuff. Most style-guides will recommend that you leave it out, but of course, the most important thing is to be consistent across your codebase, and es...
Should methods in a Java interface be declared with or without a public access modifier?
[ "", "java", "interface", "coding-style", "public-method", "" ]
I'm writing a utility in Python that will attach changed files in Subversion to an email and send it when a subset of folders that are under source control in SVN have been changed. I am using the pysvn library to access the repository. I have a copy of the files on my local file system and I do an update to check if ...
Stay with the slice operator, but do not change the loop variable inside the loop. for fun, try the generator expression (or keep the listcomp). ``` baselen = len(self.basePath) return (path[baselen:].replace("/", "\\") for path in paths) ``` Edit: `lstrip()' is not relevant here. From the [manual](http://docs.python...
Hm... That would do it: ``` baselen = len(self.basePath) for path in paths: path = path[baselen:].replace("/", "\\") newPaths.append(path) return newPaths ``` If you like, you can do it like this: ``` baselen = len(self.basePath) return (path[baselen:].replace("/", "\\") for path in paths) ``` Not calculati...
Translate SVN path to local file system path in Python
[ "", "python", "svn", "" ]
All I need is a way to make a property of one class only 'settable' from one other class (a sort of manager class). Is this even possible in c#? My colleague 'reliably' informs me that I have a design flaw, but I feel I should at least ask the community before I concede defeat!
No, it's not really possible to do this in any clean way in C#. You probably have a design flaw ;-)
You can use the `internal` modifier, which lets all types in the same assembly access the data (or nominated assemblies if using `[InternalsVisibleTo]` - but no: there is no `friend` equivalent in C#. For example: ``` public string Foo {get; internal set;} ```
How can one type access a private setter of another type's property?
[ "", "c#", "access-modifiers", "" ]
I have asp.net form that contains fields. When I access this window, my javascript functions can access the fields via the DOM with the getElementById() method and when I postpack to the server I am receiving the updates made by the client. However, when I launch the form as a child window using Telerik's RadWindow co...
To get the ID of your asp.net control do something like this: ``` <%= theControl.ClientID %> ``` getElementByName is not as commonly used as getElementById. The ID attribute is supposed to be unique for each element on the page whereas the name attribute can be duplicated.
It is quite possible that the element's ID is not what you think it is. Check the rendered page and see if the ID is there. I am guessing that the page is given a different ID since it is rendered inside another control. If that is the case, you can have the form render some script that returns the element ID by acces...
Are hidden fields on child window inaccessible from parent window
[ "", "asp.net", "javascript", "telerik", "" ]
What's the difference between the list methods `append()` and `extend()`?
[`.append()`](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) appends a specified object at the end of the list: ``` >>> x = [1, 2, 3] >>> x.append([4, 5]) >>> print(x) [1, 2, 3, [4, 5]] ``` [`.extend()`](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) extends the list ...
`.append()` adds an element to a list, whereas `.extend()` concatenates the first list with another list/iterable. ``` >>> xs = ['A', 'B'] >>> xs ['A', 'B'] >>> xs.append("D") >>> xs ['A', 'B', 'D'] >>> xs.append(["E", "F"]) >>> xs ['A', 'B', 'D', ['E', 'F']] >>> xs.insert(2, "C") >>> xs ['A', 'B', 'C', 'D', ['E'...
What is the difference between Python's list methods append and extend?
[ "", "python", "list", "data-structures", "append", "extend", "" ]
I came across an issue that makes me think there is bug in the 3.0 framework. When I try to use extension methods I get the following error: ``` Missing compiler required member 'System.Runtime.CompilerServices.ExtensionAttribute..ctor' ``` When using this simple code: ``` public static class StringUtils { stati...
I just ran into this problem myself. In my case, it was because I converted a VS 2005/.Net 2.0 project to a VS 2008/.Net 3.5 project. The conversion tool kept references to System.Core 2.0, and I couldn't find an easy way to change the references to System.Core 3.5. I ended up re-creating the project in VS 2008 from s...
I have the exact same problem. The error `System.Runtime.CompilerServices.ExtensionAttribute..ctor` is rather cryptic, and could mean a number of different things. However, for me It boiled down to the fact that I'm using `Newtonsoft.Json.Net`. I removed the reference to the file `Newtonsoft.Json.Net20.dll`, and the r...
Error when using extension methods in C#
[ "", "c#", ".net-3.5", "extension-methods", "" ]
What is the most efficient way to store large arrays (10000x100) in a database, say, hsqldb? I need to do this for a certain math program that I'm writing in java. Please help. The whole array will be retrieved and stored often (not so much individual elements). Also, some meta-data about the array needs to be stored a...
Great question. Unless you want to translate your arrays into a set of normalized tables, which it sounds like you don't, you might want to contemplate serialization. Serialization is a fancy word for turning objects into some format that you can save to disk or a database. The two major formats for serialization are...
How about storing the data as a BLOB and using Java to decode the BLOB into an actual Java array? It would be much more efficient for storing and retrieving the whole array in one gulp, but would be terrible for twiddling individual elements.
Storing arrays in databases
[ "", "java", "database", "hsqldb", "" ]
I'm trying to figure out how to restrict access to a page unless the page is navigated to from a specific "gate" page. Essentially I want the page to be unaccessible unless you're coming from the page that comes before it in my sitemap. I'm not certain this is even possible. If possible, can you limit your suggestions ...
What if you encrypted a variable (like the current date) and placed that in the "gate" link. When you arrive at the new page, a script decrypts the variable and if it doesn't match or isn't even there, the script redirects to another page. Something like: ``` <a href="restricted.php?pass=eERadWRWE3ad=">Go!</a> ``` *...
> If possible, can you limit your suggestions to using either html or javascript? No. **Because there is no secure way** using only these two techniques. Everything that goes on on the client side may be manipulated (trivially easy). If you want to be sure, you have to enforce this on the server side by checking for t...
Restricting access to page unless coming from a specific page
[ "", "javascript", "html", "" ]
I'm currently working on an application which requires transmission of speech encoded to a specific audio format. ``` System.Speech.AudioFormat.SpeechAudioFormatInfo synthFormat = new System.Speech.AudioFormat.SpeechAudioFormatInfo(System.Speech.AudioFormat.EncodingFormat.Pcm, ...
It's entirely possible that the LH Michael and LH Michelle voices simply don't support 8000 Hz sample rates (because they inherently generate samples > 8000 Hz). SAPI allows engines to reject unsupported rates.
I have created some classes in my [NAudio](http://www.codeplex.com/naudio) library to allow you to convert your audio data to a different sample rate, if you are stuck with 11025 from the synthesizer. Have a look at `WaveFormatConversionStream` (which uses ACM) or `ResamplerDMO` (uses a DirectX Media Object)
Question SpeechSynthesizer.SetOutputToAudioStream audio format problem
[ "", "c#", "audio", "speech-recognition", "text-to-speech", "" ]
I've created a copy utility in c# (.NET 2.0 Framework) that copies files, directories and recursive sub directories etc. The program has a GUI that shows the current file being copied, the current file number (sequence), the total number of files to be copied and the percentage completed for the copy operations. There ...
The FileInfo.CopyTo is basically a wrapper around the Win32 API call "CopyFile" in the kernel32.dll. This method does not support progress callback. However, the CopyFileEx method does, and you can write your own .NET wrapper around it in a few minutes, like it is described here: [http://www.pinvoke.net/default.aspx/k...
I also used the implementation provided in the [marked answer](https://stackoverflow.com/a/187842/73025). However I then created a wrapper to provide a nicer™ API to use from .NET. **Usage:** ``` XCopy.Copy(networkFile.FullPath, temporaryFilename, true, true, (o, pce) => { worker.ReportProgress(pce.ProgressPerce...
Can I show file copy progress using FileInfo.CopyTo() in .NET?
[ "", "c#", ".net", "copy", "fileinfo", "" ]
I have a database called foo and a database called bar. I have a table in foo called tblFoobar that I want to move (data and all) to database bar from database foo. What is the SQL statement to do this?
On SQL Server? and on the same database server? Use three part naming. ``` INSERT INTO bar..tblFoobar( *fieldlist* ) SELECT *fieldlist* FROM foo..tblFoobar ``` This just moves the data. If you want to move the table definition (and other attributes such as permissions and indexes), you'll have to do something else.
SQL Server Management Studio's "Import Data" task (right-click on the DB name, then tasks) will do most of this for you. Run it from the database you want to copy the data into. If the tables don't exist it will create them for you, but you'll probably have to recreate any indexes and such. If the tables do exist, it ...
Copy tables from one database to another in SQL Server
[ "", "sql", "sql-server", "copy", "migrate", "database-table", "" ]
Is there some library for using some sort of cursor over a file? I have to read big files, but can't afford to read them all at once into memory. I'm aware of java.nio, but I want to use a higher level API. A little backgrond: I have a tool written in GWT that analyzes submitted xml documents and then pretty prints th...
Have you taken a look at using FileChannels (i.e., memory mapped files)? Memory mapped files allow you to manipulate large files without bringing the entire file into memory. Here's a link to a good introduction: <http://www.developer.com/java/other/article.php/1548681>
Maybe [java.io.RandomAccessFile](https://docs.oracle.com/javase/1.5.0/docs/api/java/io/RandomAccessFile.html) can be of use to you.
Java File Cursor
[ "", "java", "performance", "file", "file-io", "" ]
How can I get the BSSID / MAC (Media Access Control) address of the wireless access point my system is connected to using C#? Note that I'm interested in the BSSID of the WAP. This is different from the MAC address of the networking portion of the WAP.
The following needs to be executed programmatically: ``` netsh wlan show networks mode=Bssid | findstr "BSSID" ``` The above shows the access point's wireless MAC addresses which is different from: ``` arp -a | findstr 192.168.1.254 ``` This is because the access point has 2 MAC addresses. One for the wireless devi...
``` using System; using System.Diagnostics; class Program { static void Main(string[] args) { Process proc = new Process(); proc.StartInfo.CreateNoWindow = true; proc.StartInfo.FileName = "cmd"; proc.StartInfo.Arguments = @"/C ""netsh wlan show networks mode=bssid | find...
Get BSSID (MAC address) of wireless access point from C#
[ "", "c#", "wifi", "" ]
I've been working on database-driven web applications for a few years now and recently took on a project involving a CMS that is XML-capable. This has led me to think about the usage of XML/XSLT in general and in what situations it would be more useful than the approach I've always used, which is storing all of my data...
To quote [This Book](http://www.amazon.com/exec/obidos/tg/detail/-/0321150406/102-0503816-7711357) (Effective XML: 50 Specific Ways to Improve Your XML): > “XML is not a database. It was never > meant to be a database. It is never > going to be a database. Relational > databases are proven technology with > more than ...
Use XML to create files that need to be sent to other applications. XML is more suited as data interchange format than as data storage format. The following link is not bad to describe when using XML: [Why should I use XML ?](http://xml.silmaril.ie/whyxml.html)
When would I use XML instead of SQL?
[ "", "sql", "xml", "" ]
I am trying to connect to a webservice over ssl with a client certificate. Is there an elegant way of doing this apart from shoving things like "javax.net.ssl.keyStore" into System.properties. Any pointers to code examples would be appreciated.
You could just install the cert into the system keystore. (Location varies across platforms, and you will need admin rights).
Not sure if [this](http://blogs.oracle.com/andreas/entry/no_more_unable_to_find) is fully relevant, but still. This entry describes the way of generating the certificate and installing it on a local system without using the keytool. Probably you could reuse some parts of the (very simple) source code.
Java webservice (soap) client - use certificates
[ "", "java", "web-services", "soap", "certificate", "" ]
I have a form that is sending in sizes of things, and I need to see what the strings are equal to so that I can set the price accordingly. When i try to do this, it says that they are not equal, and i get no prices. This is the code i'm using: ``` if ($_POST['sizes'] == "Small ($30)"){$total = "30";} if ($_POST['sizes...
What [Paul Dixon said](https://stackoverflow.com/questions/184703/compare-strings-given-in-post-with-php/184737#184737) is correct. Might I also recommend using a switch statement instead of that clunky chunk of if statements (which actually has a logic bug in it, I might add - `$total` will always equal `$_POST['price...
That's a good candidate for a switch/case statement, with your 'else' being a default. Also, without using elseif's on Medium and Large, if your $\_POST['sizes'] is not Large, then your $total will always be $\_POST['price']. This could be throwing you off as well.
Compare Strings given in $_POST with php
[ "", "php", "post", "compare", "" ]
In Java, is there an elegant way to detect if an exception occurred prior to running the finally block? When dealing with "close()" statements, it's common to need exception handling within the finally block. Ideally, we'd want to maintain both exceptions and propagate them up (as both of them may contain useful inform...
Your idea about setting a variable outside the scope of the try/catch/finally is correct. There cannot be more than one exception propagating at once.
Instead of using a Boolean flag, I would store a reference to the Exception object. That way, you not only have a way to check whether an exception occurred (the object will be null if no exception occurred), but you'll also have access to the exception object itself in your finally block if an exception did occur. You...
Is it possible to detect if an exception occurred before I entered a finally block?
[ "", "java", "exception", "" ]
Other than using raw XML, is there an easy way in .NET to open and read a config file belonging to another assembly...? I don't need to write to it, just grab a couple of values from it.
[Here's](http://msdn.microsoft.com/en-us/library/ms224437.aspx) MSDN on OpenExeConfiguration. Edit: [link](http://www.eggheadcafe.com/software/aspnet/32181042/using-configurationmanage.aspx) to a how-to on eggheadcafe.com disappeared. Looks like EggheadCafe moved to NullSkull but dropped the article ID's.
Have you tried [`ConfigurationManager`](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx) and [`OpenExeConfiguration(path)`](http://msdn.microsoft.com/en-us/library/ms224437.aspx)? (in System.Configuration.dll)
Easiest way to read a config file belonging to another application
[ "", "c#", "configuration-files", "" ]
The company I work for has a large webapp written in C++ as an ISAPI extension (not a filter). We're currently enhancing our system to integrate with several 3rd party tools that have SOAP interfaces. Rather than roll our own, I think it would probably be best if we used some SOAP library. Ideally, it would be free and...
GSoap is a great open source cross platfrom soap stack. # It is FAST. # Great interop. Many open source soap libraries don't have great interop with java/c#/python/whatever. It parses HUGE payloads while using very little memory. It is open source! Since you are using an IIS extension, you would need to add the g...
Take a look at [ATL Server](http://www.codeplex.com/AtlServer) This library used to be shipped with Visual C++, but now it is a separate open source project
choosing a SOAP library to integrate with ISAPI webapp
[ "", "c++", "soap", "isapi-extension", "" ]
I'm currently using [Magpie RSS](http://magpierss.sourceforge.net/) but it sometimes falls over when the RSS or Atom feed isn't well formed. Are there any other options for parsing RSS and Atom feeds with PHP?
Your other options include: * [SimplePie](http://simplepie.org/) * [Last RSS](http://lastrss.oslab.net/) * [PHP Universal Feed Parser](http://www.phpclasses.org/package/4548-PHP-Parse-RSS-and-ATOM-feeds.html)
I've always used [the SimpleXML functions built in to PHP](https://www.php.net/simplexml) to parse XML documents. It's one of the few generic parsers out there that has an intuitive structure to it, which makes it extremely easy to build a meaningful class for something specific like an RSS feed. Additionally, it will ...
Best way to parse RSS/Atom feeds with PHP
[ "", "php", "parsing", "rss", "atom-feed", "" ]
In one of my projects I need to build an ASP.NET page and some of the controls need to be created dynamically. These controls are added to the page by the code-behind class and they have some event-handlers added to them. Upon the PostBacks these event-handlers have a lot to do with what controls are then shown on the ...
I think that you have to provide the same ID for your buttons every time you add them like this for example (in first line of `AddButtonControl` method): ``` var button = new Button { Text = id , ID = id }; ``` --- **EDIT** - My solution without using session: ``` public partial class _Default : Page { protecte...
You need to make sure that your dynamic controls are being added during the `Pre_Init` event. See here for the ASP.NET Page Lifecycle: <http://msdn.microsoft.com/en-us/library/ms178472.aspx> When adding events you need to do it no later than the `Page_Load` method and they *need to be added every single request*, ie ...
How do I dynamically create/remove controls, with EventHandlers, to/from an ASP.NET page?
[ "", "c#", "asp.net", "" ]
I have some Java code that uses curly braces in two ways ``` // Curly braces attached to an 'if' statement: if(node.getId() != null) { node.getId().apply(this); } // Curly braces by themselves: { List<PExp> copy = new ArrayList<PExp>(node.getArgs()); for(PExp e : copy) { e.apply(this); } }...
The only purpose of the extra braces is to provide scope-limit. The `List<PExp> copy` will only exist within those braces, and will have no scope outside of them. If this is generated code, I assume the code-generator does this so it can insert some code (such as this) without having to worry about how many times it h...
I second what matt b wrote, and I'll add that another use I've seen of anonymous braces is to declare an implicit constructor in anonymous classes. For example: ``` List<String> names = new ArrayList<String>() { // I want to initialize this ArrayList instace in-line, // but I can't define a constructor for a...
What do curly braces in Java mean by themselves?
[ "", "java", "syntax", "scope", "curly-braces", "" ]
How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don't seem to find any obvious ways to do the operation the opposite way.
``` import time, datetime d = datetime.datetime.now() print time.mktime(d.timetuple()) ```
For UTC calculations, `calendar.timegm` is the inverse of `time.gmtime`. ``` import calendar, datetime d = datetime.datetime.utcnow() print calendar.timegm(d.timetuple()) ```
Converting datetime to POSIX time
[ "", "python", "datetime", "posix", "" ]
Is there some way I can define `String[int]` to avoid using `String.CharAt(int)`?
No, there isn't a way to do this. This is a common question from developers who are coming to JavaScript from another language, where **operators can be defined or overridden** for a certain type. In C++, it's not entirely out of the question to overload `operator*` on `MyType`, ending up with a unique asterisk opera...
**Please note:** Before anybody *else* would like to vote my answer down, the question I answered was: > **IE javascript string indexers** > > is there some way I can define string[int] to avoid using string.CharAt(int)?" Nothing about specifically overriding brackets, or syntax, or best-practice, the question just a...
In javascript, can I override the brackets to access characters in a string?
[ "", "javascript", "syntax", "operators", "" ]
Is it possible to use PHP's SimpleXML functions to create an XML object from scratch? Looking through the function list, there's ways to import an existing XML string into an object that you can then manipulate, but if I just want to generate an XML object programmatically from scratch, what's the best way to do that? ...
Sure you can. Eg. ``` <?php $newsXML = new SimpleXMLElement("<news></news>"); $newsXML->addAttribute('newsPagePrefix', 'value goes here'); $newsIntro = $newsXML->addChild('content'); $newsIntro->addAttribute('type', 'latest'); Header('Content-type: text/xml'); echo $newsXML->asXML(); ?> ``` Output ``` <?xml version=...
In PHP5, you should use the [Document Object Model](https://www.php.net/manual/en/book.dom.php "Document Object Model") class instead. Example: ``` $domDoc = new DOMDocument; $rootElt = $domDoc->createElement('root'); $rootNode = $domDoc->appendChild($rootElt); $subElt = $domDoc->createElement('foo'); $attr = $domDoc...
Using SimpleXML to create an XML object from scratch
[ "", "php", "xml", "simplexml", "" ]
I have a standard .NET windows service written in C#. Can it install itself without using InstallUtil? Should I use the service installer class? How should I use it? I want to be able to call the following: ``` MyService.exe -install ``` And it will have the same effect as calling: ``` InstallUtil MyService.exe ``...
Yes, that is fully possible (i.e. I do exactly this); you just need to reference the right dll (System.ServiceProcess.dll) and add an installer class... [Here's an example:](http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/4d45e9ea5471cba4/4519371a77ed4a74) ``` [RunInstal...
Take a look at the [InstallHelper](http://msdn.microsoft.com/en-us/library/system.configuration.install.managedinstallerclass.installhelper.aspx) method of the [ManagedInstaller](http://msdn.microsoft.com/en-us/library/system.configuration.install.managedinstallerclass.aspx) class. You can install a service using: ```...
Install a .NET windows service without InstallUtil.exe
[ "", "c#", ".net", "deployment", "windows-services", "installutil", "" ]
I'd like to have it yell hooray whenever an assert statement succeeds, or at the very least have it display the number of successful assert statements that were encountered. I'm using JUnit4. Any suggestions?
If you want to see some output for each successful assertion, another simple approach which requires no external dependencies or source code, would be to define your own Assert class which delegates all methods to the standard JUnit Assert class, as well as logging successful assertions (failed assertions will be repor...
Adding some info that would have been helpful to me when I wanted JUnit to be more verbose and stumbled on this question. Maybe it will help other testers in the future. If you are running JUnit from Ant, and want to see what tests are being run, you can add the following to your task: ``` <junit showoutput="true" pr...
Can I make JUnit more verbose?
[ "", "java", "junit", "" ]
I've recently decided that I just have to finally learn C/C++, and there is one thing I do not really understand about pointers or more precisely, their definition. How about these examples: 1. `int* test;` 2. `int *test;` 3. `int * test;` 4. `int* test,test2;` 5. `int *test,test2;` 6. `int * test,test2;` Now, to my...
4, 5, and 6 are the same thing, only *test* is a pointer. If you want two pointers, you should use: ``` int *test, *test2; ``` Or, even better (to make everything clear): ``` int* test; int* test2; ```
White space around asterisks have no significance. All three mean the same thing: ``` int* test; int *test; int * test; ``` The "`int *var1, var2`" is an evil syntax that is just meant to confuse people and should be avoided. It expands to: ``` int *var1; int var2; ```
Placement of the asterisk in pointer declarations
[ "", "c++", "c", "pointers", "declaration", "" ]
Notice in the bottom right hand corner of this page it has the SVN revision id? I'm assuming that's dynamic. I'd love to add that to some of my sites, just as a comment in the source to make sure code pushes are going through. NOTE: You can also assume that the working directory of the site in question is an svn chec...
You can use the [`svnversion`](http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.ref.svnversion) CLI utility to get a more specific look at the revision, including the highest number. You could then use regular expressions to parse this. Subversion has no concept of a global revision; rather, you'd have to recursiv...
The keyword subsitution method isn't reliable because it will provide the revision of the file rather than the whole codebase that you're deploying, which I presume is what you're after. Typically I use ANT to deploy from subversion, and in the build script I'd use the replace task to substitue a revision token in a l...
Easy way to embed svn revision number in page in PHP?
[ "", "php", "svn", "versioning", "revision", "" ]
I have the following HTML node structure: ``` <div id="foo"> <div id="bar"></div> <div id="baz"> <div id="biz"></div> </div> <span></span> </div> ``` How do I count the number of immediate children of `foo`, that are of type `div`? In the example above, the result should be two (`bar` and `baz`).
``` $("#foo > div").length ``` Direct children of the element with the id 'foo' which are divs. Then retrieving the size of the wrapped set produced.
I recommend using `$('#foo').children().size()` for better performance. I've created a [jsperf](http://jsperf.com/jquery-child-ele-size) test to see the speed difference and the `children()` method beaten the child selector (#foo > div) approach by at least **60%** in Chrome (canary build v15) **20-30%** in Firefox (v...
Count immediate child div elements using jQuery
[ "", "javascript", "jquery", "dom", "jquery-selectors", "" ]
I'm wondering if a Java library can be called from a VB.net application. (A Google search turns up lots of shady answers, but nothing definitive)
No, you can't. Unless you are willing to use some "J#" libraries (which is not nearly the same as Java) or [IKVM](http://www.ikvm.net/) which is a Java implementation that runs on top of .NET, but as their documentation says: > IKVM.OpenJDK.ClassLibrary.dll: compiled version of the Java class libraries derived from th...
I am author of [jni4net](http://jni4net.sf.net/), open source intraprocess bridge between JVM and CLR. It's build on top of JNI and PInvoke. No C/C++ code needed. I hope it will help you.
Can you use Java libraries in a VB.net program?
[ "", "java", "vb.net", "" ]
I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area. Is something like this possible with jQuery? ``` $("#menuscontainer").clickOutsideThisElement(function() { // Hide the menus }); ```
> Note: Using `stopPropagation` is something that should be avoided as it breaks normal event flow in the DOM. See [this CSS Tricks article](https://css-tricks.com/dangers-stopping-event-propagation/) for more information. Consider using [this method](https://stackoverflow.com/a/3028037/561309) instead. Attach a click...
You can listen for a **click** event on `document` and then make sure `#menucontainer` is not an ancestor or the target of the clicked element by using [`.closest()`](http://api.jquery.com/closest/). If it is not, then the clicked element is outside of the `#menucontainer` and you can safely hide it. ``` $(document)....
How do I detect a click outside an element?
[ "", "javascript", "jquery", "click", "" ]
I feel like I should know this, but I haven't been able to figure it out... I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more...
The answers involving introspection via `inspect` and the like are reasonable. But there may be another option, depending on your situation: If your integration test is written with the [unittest](http://docs.python.org/library/unittest.html) module, then you could use `self.id()` within your TestCase.
This seems to be the simplest way using module `inspect`: ``` import inspect def somefunc(a,b,c): print "My name is: %s" % inspect.stack()[0][3] ``` You could generalise this with: ``` def funcname(): return inspect.stack()[1][3] def somefunc(a,b,c): print "My name is: %s" % funcname() ``` Credit to [S...
How do I get the name of a function or method from within a Python function or method?
[ "", "python", "" ]
I am using [this](http://www.codeproject.com/KB/vb/TabPages.aspx) - otherwise excellent - vb tab control in one of my c# apps. When the app using it is installed on another machine, Windows tells the user in its usual friendly and descriptive manner that "The application encountered a problem and needs to close". I gue...
Since the tab control appears to be managed code as well, your 'crash' is most likely an unhandled .NET exception. Looking at the error details (by expanding the error dialog using the button provided for that purpose...) should give you the exception message, which should give you an idea of what's going on. If it's ...
Click the 'What data does this error report contain?' button and there will be more descriptive info. (i.e. type of the thrown exception, module etc.). For additional info see [Dr. Watson vs. CLR.](http://blogs.msdn.com/vipul/archive/2007/01/22/Dr.-watson-and-the-common-language-runtime.aspx)
VB control crashes my app
[ "", "c#", ".net", "vb.net", "" ]
I have a library A, that I develop. When I deploy it on a machine, the corresponding *libA.so* and *libA-X.Y.Z.so* are put in /usr/lib (X.Y.Z being the version number). Now I develop a library B, which uses A. When I link B, I use the flag -lA. Then "*ldd libB.so*" gives me : ``` (...) libA-X.Y.Z.so => /usr/lib/libA-...
When you create libA.so, pass the -soname option to the linker (if you linking through gcc, use -Wl,-soname). Then, when B gets linked, the linker refers to A through its soname, not through its filename. On the target system, make sure you have a link from the soname to the real file. See <http://www.linux.org/docs/l...
This also works in Windows as "DLL hell" :). If B needs a specific version of A and you would link to libA not libA-X.Y.Z then only substituting libA with newer version might cause B not to load or crash. But of course you can do a symlink from libA-X.Y.Z to libA-X1.Y1.Z1. If no APIs changed and only implementations ...
C++ : how to link against libA.so and not libA-X.Y.Z.so
[ "", "c++", "linker", "versions", "" ]
How do people approach mocking out TcpClient (or things like TcpClient)? I have a service that takes in a TcpClient. Should I wrap that in something else more mockable? How should I approach this?
When coming to mock classes that are not test friendly (i.e. sealed/not implementing any interface/methods are not virtual), you would probably want to use the [Adapter](http://en.wikipedia.org/wiki/Adapter_pattern) design pattern. In this pattern you add a wrapping class that implements an interface. You should then ...
I think @Hitchhiker is on the right track, but I also like to think about abstracting out things like that just a step further. I wouldn't mock out the TcpClient directly, because that would still tie you too closely to the underlying implementation even though you've written tests. That is, your implementation is tie...
TDD and Mocking out TcpClient
[ "", "c#", "networking", "tdd", "mocking", "" ]
I'm looking for a good JavaScript RegEx to convert names to proper cases. For example: ``` John SMITH = John Smith Mary O'SMITH = Mary O'Smith E.t MCHYPHEN-SMITH = E.T McHyphen-Smith John Middlename SMITH = John Middlename SMITH ``` Well you get the idea. Anyone come up with a comprehensive solution?
Something like this? ``` function fix_name(name) { var replacer = function (whole,prefix,word) { ret = []; if (prefix) { ret.push(prefix.charAt(0).toUpperCase()); ret.push(prefix.substr(1).toLowerCase()); } ret.push(word.charAt(0).toUpperCase()); ret....
Wimps!.... Here's my second attempt. Handles "John SMITH", "Mary O'SMITH" "John Middlename SMITH", "E.t MCHYPHEN-SMITH" and "JoHn-JOE MacDoNAld" ``` Regex fixnames = new Regex("(Ma?C)?(\w)(\w*)(\W*)"); string newName = fixnames.Replace(badName, NameFixer); static public string NameFixer(Match match) { string mc...
JS Regex For Human Names
[ "", "javascript", "regex", "string", "text", "" ]
I've got a User table with a bitmask that contains the user's roles. The linq query below returns all the users whose roles include 1, 4 or 16. ``` var users = from u in dc.Users where ((u.UserRolesBitmask & 1) == 1) || ((u.UserRolesBitmask & 4) == 4) || ((u.UserRolesBitmask &...
You can use the [PredicateBuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx) class. PredicateBuilder has been released in the [LINQKit NuGet package](https://www.nuget.org/packages/LinqKit/) > LINQKit is a free set of extensions for LINQ to SQL and Entity Framework power users.
Assuming your UserRoles values are themselves bitmasks, would something like this work? ``` private List<User> GetUsersFromRoles(uint[] UserRoles) { uint roleMask = 0; for (var i = 0; i < UserRoles.Length;i++) roleMask= roleMask| UserRoles[i]; // roleMasknow contains the OR'ed bitfields of the roles we're ...
How do you add dynamic 'where' clauses to a linq query?
[ "", "c#", "linq", "dynamic", "" ]
I am just starting to fiddle with Excel via C# to be able to automate the creation, and addition to an Excel file. I can open the file and update its data and move through the existing worksheets. My problem is how can I add new sheets? I tried: ``` Excel.Worksheet newWorksheet; newWorksheet = (Excel.Worksheet)excel...
You need to add a COM reference in your project to the **"`Microsoft Excel 11.0 Object Library`"** - or whatever version is appropriate. This code works for me: ``` private void AddWorksheetToExcelWorkbook(string fullFilename,string worksheetName) { Microsoft.Office.Interop.Excel.Application xlApp = null; Wor...
Would like to thank you for some excellent replies. @AR., your a star and it works perfectly. I had noticed last night that the `Excel.exe` was not closing; so I did some research and found out about how to release the COM objects. Here is my final code: ``` using System; using System.Collections.Generic; using System...
C# - How to add an Excel Worksheet programmatically - Office XP / 2003
[ "", "c#", "excel", "com", "office-interop", "worksheet", "" ]
I am deciding on a framework to try out for PHP. I have narrowed it down to CakePHP and CodeIgniter. I have a couple of questions for any of you who have used or are familiar with both: 1. I like the fact that CakePHP keeps most of the code outside of the webroot by default. Especially since I may end up using a singl...
You should **try** both frameworks for a week or so, building something trivial (like a blog or wiki) in both, and see which you prefer using. Whatever makes the most sense *to you* will probably sustain you the longest through upgrades an deprecations. CakePHP is in a bit of a volatile state right now, still unearthi...
I have deployed multiple applications on CakePHP and it's been a very, very, nice experience. You can't go wrong either way, as both are solid.
Which framework should I use to ensure better longterm upgrade / maintainability, CakePHP or CodeIgniter?
[ "", "php", "codeigniter", "cakephp", "maintainability", "" ]
When I try to add a HTTP header key/value pair on a `WebRequest` object, I get the following exception: > This header must be modified using the appropriate property I've tried adding new values to the `Headers` collection by using the Add() method but I still get the same exception. ``` webRequest.Headers.Add(HttpR...
If you need the short and technical answer go right to the last section of the answer. If you want to know better, read it all, and i hope you'll enjoy... --- I countered this problem too today, and what i discovered today is that: 1. the above answers are true, as: 1.1 it's telling you that the header you are ...
I ran into this problem with a custom web client. I think people may be getting confused because of multiple ways to do this. When using `WebRequest.Create()` you can cast to an `HttpWebRequest` and use the property to add or modify a header. When using a `WebHeaderCollection` you may use the `.Add("referer","my_url")`...
Cannot set some HTTP headers when using System.Net.WebRequest
[ "", "c#", "header", "webrequest", "" ]
What is the best way to graph scatter plots in C++? Do you write data to a file and use another tool? Is there a library like matplotlib in Python?
I always write out data and then using [gnuplot](http://www.gnuplot.info/) to create my graphs. It is by far the best way I have found of producing graphs in a variety of formats: eps, png, jpeg, xpm, you name it. `gnuplot` will do scatter plot very easily. Provided the `x` and `y` values are in 2 space-separated colu...
If you are looking for a C++ library rather than I independent plotting tool like gnuplot, I would consider the following: * [Koolplot](http://www.codecutter.net/tools/koolplot/byExample.html) * [dislin](http://www.mps.mpg.de/dislin/) ([Wikipedia article on dislin](http://en.wikipedia.org/wiki/DISLIN)) dislin seems t...
Scatter Plots in C++
[ "", "c++", "data-visualization", "scatter-plot", "" ]
I am looking for an addon that can say characters vocally. It is for non-commercial use, and it would be nice if it can vocalize more languages, like asian, english etc... I have googled it, but can't seem to find anything for free use. Update: This is for web use
You could try <http://espeak.sourceforge.net/> and make an mp3 of the word, then stream it to a flash application (you could use darwin for the streaming).
You can convert the text to speech in Java using freetts1.2 API. It is quite simple to use. This link could be useful for you which has an example program. <http://learnsharelive.blogspot.com/2011/01/convert-text-to-speech-java-freetts12.html>
(Vocal code) Need some help finding text-to-speech addon
[ "", "java", "flash", "text-to-speech", "" ]
I am experimenting with calling delegate functions from a delegate array. I've been able to create the array of delegates, but how do I call the delegate? ``` public delegate void pd(); public static class MyClass { static void p1() { //... } static void p2 () { //... } ...
If they're all the same type, why not just combine them into a single multicast delegate? ``` static pd delegateInstance = new pd(MyClass.p1) + new pd(MyClass.p2) ...; ... pd(); ```
``` public class MainClass { static void Main() { pd[0](); pd[1](); } } ```
Delegate Array in C#
[ "", "c#", "arrays", "delegates", "" ]
**EDIT:** See [my working code](https://stackoverflow.com/questions/218909/returning-a-pdf-file-from-a-java-bean-to-a-jsp#221252) in the answers below. --- **In brief:** I have a JSP file which calls a method in a Java Bean. This method creates a PDF file and in theory, returns it to the JSP so that the user can down...
The way I have implemented this type of feature in the past is to make a servlet write the contents of the PDF file out to the response as a stream. I don't have the source code with me any longer (and it's been at least a year since I did any servlet/jsp work), but here is what you might want to try: In a servlet, ge...
Ok, I got this working. Here's how I did it: JSP: ``` <%@ taglib uri="utilTLD" prefix="util" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %> <%@ page language="java" session="false" %> <%@ page contentType="application/pdf" %> <%-- C...
Returning a PDF file from a Java Bean to a JSP
[ "", "java", "jsp", "pdf", "xsl-fo", "apache-fop", "" ]
I'm trying to write a python script that packages our software. This script needs to build our product, and package it. Currently we have other scripts that do each piece individually which include csh, and perl scripts. One such script is run like: ``` sudo mod args ``` where mod is a perl script; so in python I wou...
I would choose to go with Pexpect. ``` import pexpect child = pexpect.spawn ('sudo mod -p -c noresource -u dtt -Q') child.expect ('First question:') child.sendline ('Y') child.expect ('Second question:') child.sendline ('Yup') ```
I think you should remove the `sudo` in your `Popen` call and require the user of *your* script to type `sudo`. This additionally makes more explicit the need for elevated privileges in your script, instead of hiding it inside `Popen`.
Is it possible to communicate with a sub subprocess with subprocess.Popen?
[ "", "python", "subprocess", "" ]
``` Option Explicit On Option Strict On Public Class Class1 Dim l As List(Of A) Public Sub New() l = New List(Of B) End Sub End Class Public Class A End Class Public Class B Inherits A End Class<p> ``` I've run into this problem. I have a list declared of a Generic Type 'A' I want to ...
It's a matter of variance, which C# doesn't support for generics. See [Rick Byer's post on the subject](http://blogs.msdn.com/rmbyers/archive/2005/02/16/375079.aspx).
In C# 4.0 (as announced yesterday) we are [half way there](http://blogs.msdn.com/charlie/archive/2008/10/28/linq-farm-covariance-and-contravariance-in-visual-studio-2010.aspx).
Create Generic List from a subclass
[ "", "c#", "vb.net", "generics", "reflection", "" ]
Suppose we have some named enums: ``` enum MyEnum { FOO, BAR = 0x50 }; ``` What I googled for is a script (any language) that scans all the headers in my project and generates a header with one function per enum. ``` char* enum_to_string(MyEnum t); ``` And a implementation with something like this: ```...
You may want to check out [GCCXML](http://www.gccxml.org/HTML/Index.html). Running GCCXML on your sample code produces: ``` <GCC_XML> <Namespace id="_1" name="::" members="_3 " mangled="_Z2::"/> <Namespace id="_2" name="std" context="_1" members="" mangled="_Z3std"/> <Enumeration id="_3" name="MyEnum" context="...
X-macros are the best solution. Example: ``` #include <iostream> enum Colours { # define X(a) a, # include "colours.def" # undef X ColoursCount }; char const* const colours_str[] = { # define X(a) #a, # include "colours.def" # undef X 0 }; std::ostream& operator<<(std::ostream& os, enum Colours ...
Is there a simple way to convert C++ enum to string?
[ "", "c++", "string", "enums", "scripting", "" ]
I'm refactoring some PHP code and discovered that certain nested combinations of ``` if () : ``` and ``` if () { ``` generate syntax errors. Not that I would normally mix the two, but I like to do frequent syntax checks as I'm writing code and I kept getting a syntax error because of this. Example - generates synt...
This is a wild guess since I am not familiar with the grammar of PHP. But here goes: The problem is the second `else`. The parser can't see if this `else` is belonging to the first or the second if (counting from the beginning). In your second example there is an `endif` making the second `if`-block be terminated so t...
i don't know the exact reason why. here's a related [PHP bug post](http://bugs.php.net/bug.php?id=18413) in which a dev basically says, "just don't do it" :). i haven't poured through the PHP source code lately, but if i had to hazard a guess, it's due to not checking for alternative syntax while recursively going thro...
Mixed syntax for control structures generating syntax errors
[ "", "php", "syntax", "" ]
What are the different types of indexes, what are the benefits of each? I heard of covering and clustered indexes, are there more? Where would you use them?
* Unique - Guarantees unique values for the column(or set of columns) included in the index * Covering - Includes all of the columns that are used in a particular query (or set of queries), allowing the database to use only the index and not actually have to look at the table data to retrieve the results * Clustered - ...
[OdeToCode has a good article covering the basic differences](http://www.odetocode.com/Articles/70.aspx) As it says in the article: > Proper indexes are crucial for good > performance in large databases. > Sometimes you can make up for a poorly > written query with a good index, but > it can be hard to make up for po...
What are the different types of indexes, what are the benefits of each?
[ "", "sql", "database", "database-design", "indexing", "" ]
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." (Donald Knuth). My SQL tables are unlikely to contain more than a few thousand rows each (and those are the big ones!). SQL Server Database Engine Tuning Advisor dismisses the amount of data as irrele...
The value of indexes is in speeding reads. For instance, if you are doing lots of SELECTs based on a range of dates in a date column, it makes sense to put an index on that column. And of course, generally you add indexes on any column you're going to be JOINing on with any significant frequency. The efficiency gain is...
Knuth's wise words are not applicable to the creation (or not) of indexes, since by adding indexes you are **not** optimising anything directly: you are providing an index that the DBMSs optimiser *may* use to optimise some queries. In fact, you could better argue that deciding *not* to index a small table is premature...
No indexes on small tables?
[ "", "sql", "sql-server", "indexing", "performance", "" ]
I have heard from people who have switched either way and who swear by the one or the other. Being a huge Eclipse fan but having not had the time to try out IntelliJ, I am interested in hearing from IntelliJ users who are "ex-Eclipsians" some specific things that you can do with IntelliJ that you can not do with Eclip...
## CTRL-click works anywhere CTRL-click that brings you to where clicked object is defined works everywhere - not only in Java classes and variables in Java code, but in Spring configuration (you can click on class name, or property, or bean name), in Hibernate (you can click on property name or class, or included res...
There is only one reason I use intellij and not eclipse: *Usability* Whether it is debugging, refactoring, auto-completion.. Intellij is much easier to use with consistent key bindings, options available where you look for them etc. Feature-wise, it will be tough for intellij to catch up with Eclipse, as the latter ha...
Things possible in IntelliJ that aren't possible in Eclipse?
[ "", "java", "eclipse", "ide", "intellij-idea", "" ]
I know that IntelliJ has an option to select all the code in a JSP file, right click, and select "format". This nicely formats all HTML, CSS, scriptlets and JSTL tags in a JSP file. Can Eclipse do this? If not, what is the best free Eclipse plugin that does the same?
With the Web Tool Plateform plateform (on eclipse.org website), this is very simple : in the JSP editor tab, right click->source->format (or Shift+Ctrl+F)
I use the EclipseHTMLEditor from [Project Amateras](http://amateras.sourceforge.jp/). Be sure to set "Amateras JSP Editor" as default editor for file type "\*.jsp" in Window > Preferences > General > Editors > File Associations. **UPDATE:** As of today, March 27th 2015, Project Amateras seems stale. However [latest re...
What is the best free plugin for Eclipse that allows for formatting/indenting/cleanup of JSP code?
[ "", "java", "eclipse", "jsp", "intellij-idea", "" ]
Can anybody recommend a good code profiler for C++? I came across Shiny - any good? <http://sourceforge.net/projects/shinyprofiler/>
[Callgrind](http://valgrind.org/info/tools.html) for Unix/Linux [DevPartner](http://www.compuware.com/products/devpartner/default.htm) for Windows
Not C++ specific, but AMD's CodeAnalyst software is free and is feature-packed. <http://developer.amd.com/cpu/codeanalyst/codeanalystwindows/Pages/default.aspx>
C++ Code Profiler
[ "", "c++", "windows", "visual-studio", "profiler", "" ]
I'm developing a SWT/JFace application using the libraries from Eclipse 3.4.1. I encounter the following problem on Windows (Vista 32bit) and Ubuntu 8.10 32bit: I create a menu bar in the createMenuManager method of the JFace ApplicationWindow. I add MenuManagers for file, edit and help. I then add an ExitAction to t...
Update: There is a duplicate bug of mine which also contains a workaround. The bug url is: <https://bugs.eclipse.org/bugs/show_bug.cgi?id=243758> Basically the workaround is to call `create()` on the `ApplicationWindow` and then `getMenuBarManager().updateAll(true);` which will force all menu items to get initialized....
AFAIK `setAccelerator(.)` does nothing else than adding the appropriate text to your `MenuItem`. You are responsible to register for an `KeyUp` event and react on it. You can use `Display.addFilter(SWT.KeyUp, myListener)` to register your `Listener` independently of your widgets.
Menu item accel key works only after menu item has been shown
[ "", "java", "swt", "" ]
In python, if I say ``` print 'h' ``` I get the letter h and a newline. If I say ``` print 'h', ``` I get the letter h and no newline. If I say ``` print 'h', print 'm', ``` I get the letter h, a space, and the letter m. How can I prevent Python from printing the space? The print statements are different iterati...
``` import sys sys.stdout.write('h') sys.stdout.flush() sys.stdout.write('m') sys.stdout.flush() ``` You need to call [`sys.stdout.flush()`](https://docs.python.org/library/io.html#io.IOBase.flush) because otherwise it will hold the text in a buffer and you won't see it.
In [Python 3](https://docs.python.org/whatsnew/3.0.html#print-is-a-function), use ``` print('h', end='') ``` to suppress the endline terminator, and ``` print('a', 'b', 'c', sep='') ``` to suppress the whitespace separator between items. See [the documentation for `print`](https://docs.python.org/library/functions....
How do I keep Python print from adding newlines or spaces?
[ "", "python", "printing", "formatting", "python-2.x", "" ]
Given a Stream as input, how do I safely create an XPathNavigator against an XML data source? The XML data source: * May possibly contain invalid hexadecimal characters that need to be removed. * May contain characters that do not match the declared encoding of the document. As an example, some XML data sources in t...
I had a similar issue when some XML fragments were imported into a CRM system using the wrong encoding (there was no encoding stored along with the XML fragments). In a loop I created a wrapper stream using the current encoding from a list. The encoding was constructed using the DecoderExceptionFallback and EncoderExc...
It's possible to use the [DecoderFallback](http://msdn.microsoft.com/en-us/library/system.text.decoderfallback.aspx) class (and a few related classes) to deal with bad characters, either by skipping them or by doing something else (restarting with a new encoding?).
How do I safely create an XPathNavigator against a Stream in C#?
[ "", "c#", "xml", "encoding", "stream", "" ]
I have the classical table with expandable and collapsible records that if expanded show several subrecords (as new records in the same parent table, not some child div/child table). I am also using tablesorter and absolutely love it. The problem is that tablesorter isn't keeping expanded child records next to the par...
If you want to keep tablesorter, there is a mod which I have used for this purpose **[available here](http://www.pengoworks.com/workshop/jquery/tablesorter/tablesorter.htm)** After including it, you make your second (expandable child) row have the class "expand-child", and tablesorter will know to keep the row paired ...
Actually, that [mod of tablesorter](http://www.pengoworks.com/workshop/jquery/tablesorter/tablesorter.htm) mentioned by @AdamBellaire was added to [tablesorter v2.0.5](http://tablesorter.com/docs/). I've documented [how to use the `ccsChildRow` option](http://wowmotty.blogspot.com/2011/06/jquery-tablesorter-missing-doc...
Getting jQuery tablesorter to work with hidden/grouped table rows
[ "", "javascript", "jquery", "tablesorter", "" ]
Do you know of any tool that would do like Ruby on Rails' Scaffolding (create simple CRUD pages for any particular class to allow quickly populating a database with dummy data), only which used Java classes with Hibernate for database access, and JSP/JSF for the pages? It is a drag when you are programming one part of...
[Grails](http://grails.org/) is a very nice Rails-like framework built on top of Spring MVC. For persistence, they use [GORM](http://grails.org/GORM), which is basically an ActiveRecord-like framework built on top of Hibernate. Pretty slick. If you already have Hibernate entities, they can actually be used immediately...
You can try **Telosys Tools**, an Eclipse plugin for code generation (scaffolding) working from an existing database with customizable Velocity templates. It's very simple and easy to use. The tutorial for code generation with Spring MVC and Spring Data is here : <https://sites.google.com/site/telosystutorial/> See a...
Hibernate CRUD à la Ruby on Rails' Scaffolding
[ "", "java", "ruby-on-rails", "hibernate", "jsp", "jsf", "" ]
What would be the best way to determine if an object equals number zero (0) or string.empty in C#? **EDIT:** The object can equal any built-in System.Value type or reference type. Source Code: ``` public void MyMethod(object input1, object input2) { bool result = false; object compare = new object(); if...
Using Jonathan Holland code sample with a minor modification, here is the solution that worked: ``` static bool IsZeroOrEmpty(object o1) { bool Passed = false; object ZeroValue = 0; if(o1 != null) { if(o1.GetType().IsValueType) { Passed = (o1 as System.ValueType).Equals(Con...
What's wrong with this? ``` public static bool IsZeroOrEmptyString(object obj) { if (obj == null) return false; else if (obj.Equals(0) || obj.Equals("")) return true; else return false; } ```
Determine value of object in C#
[ "", "c#", "casting", "" ]
Checking the HTML source of a question I see for instance: ``` <a id="comments-link-xxxxx" class="comments-link">add comment</a><noscript>&nbsp;JavaScript is needed to access comments.</noscript> ``` And then in the javascript source: ``` // Setup our click events.. $().ready(function() { $("a[id^='comme...
* You don't have to type the same string over and over again in the HTML (which if nothing else would increase the number of typos to debug) * You can hand over the HTML/CSS to a designer who need not have any javascript skills * You have programmatic control over what callbacks are called and when * It's more elegant ...
Attaching events via the events API instead of in the mark-up is the core of unobtrusive javascript. You are welcome to read [this wikipedia article](http://en.wikipedia.org/wiki/Unobtrusive_JavaScript) for a complete overview of why unobtrusive javascripting is important. The same way that you separate styles from ma...
Why Stackoverflow binds user actions dynamically with javascript?
[ "", "javascript", "jquery", "" ]
I used to work with eclipse for nearly all the languages I need. I'm asked to work on a tool developed in C# and so, I would like to stay in the same familiar environment. I've found the [improve's plugin](http://www.improve-technologies.com/alpha/esharp/) but its last release is from 2004 and .NET 1.1 which is quite ...
[Emonic](http://emonic.sourceforge.net/) integrates mono into the eclipse framework, that may be of use.
I fear, that there is no good eclipse plug in. Try <http://www.monodevelop.com/Main_Page> or <http://www.icsharpcode.net/OpenSource/SD/>. And the free visual 2008 express editions are worth a look.
Looking for up-to-date eclipse plugin for C#
[ "", "c#", "eclipse", "eclipse-plugin", "" ]
I'm absolutely in love with the way GWT does RPC. Is there anything similar for Java SE you have experience with that: 1. Is not spring 2. Doesn't require a Java EE/Servlet container to run the server side 3. Is not RMI that comes with Java SE
POJ (Plain Old JSON).
Maybe [Jini](http://www.jini.org/ "Jini"). Not Spring- or EJB-related, doesn't run in a container, and you can pick the transport.
Suggestion on remoting (rpc, rmi) for Java SE client-server app?
[ "", "java", "remoting", "" ]
For the past 2 years-(ish) I've been using [Maven2](http://maven.apache.org) for my build/continuous integration solution. I used [Ant](http://ant.apache.org) a bit before that but really didn't get a lot of experience with it. Now I've taken a new job and the team I'm on now uses Ant. What I'm wondering about is this...
My experience with ant -- which is our primary build tool for Java source, so make of this what you will -- is that there are no such *formal* conventions. Many source projects I've seen organize things in a similar manner; JBoss uses <module>/src/main for sources, etc... Ant just uses whatever conventions you want, wh...
A lot of ANT conventions/best practices are explained in [ANT in Anger](http://ant.apache.org/ant_in_anger.html)
Are there any Ant conventions similar to Maven2 conventions?
[ "", "java", "ant", "automated-tests", "conventions", "" ]
Say i have this PHP code: ``` $FooBar = "a string"; ``` i then need a function like this: ``` print_var_name($FooBar); ``` which prints: ``` FooBar ``` Any Ideas how to achieve this? Is this even possible in PHP?
You could use [get\_defined\_vars()](http://php.net/get_defined_vars) to find the name of a variable that has the same value as the one you're trying to find the name of. Obviously this will not always work, since different variables often have the same values, but it's the only way I can think of to do this. Edit: ge...
I couldn't think of a way to do this efficiently either but I came up with this. It works, for the limited uses below. *shrug* ``` <?php function varName( $v ) { $trace = debug_backtrace(); $vLine = file( __FILE__ ); $fLine = $vLine[ $trace[0]['line'] - 1 ]; preg_match( "#\\$(\w+)#", $fLine, $match )...
How to get a variable name as a string in PHP?
[ "", "php", "" ]
I have an asp.net page with a button. This button generates and inserts a user control into the page, so many controls could exist on one page. I need to validate that a certain dynamically generated control inside the generated control exists. So..Page has 0 to N Control1’s. Each Control 1 can have 0 to N Control2’s....
Hmm i like the Interface idea suggested by digiguru but i would use the interface on the container Control1 instead of the sub controls as it seems like the more logical place for the code to live. Heres my take on it: ``` public interface IValidatableControl { bool IsValidControl(); } ``` then implement this...
If you are adding user controls on the fly, you could make each control implement the same interface with a Validate function. That way you can load the controls into a placeholder in each parent control on the page. When the page is submitted, simply loop through the controls in the placeholder, cast them to the inter...
Validating an ASP.NET user control from its parent page
[ "", "c#", "asp.net", "validation", "user-controls", "custom-controls", "" ]
Using answers to [this question](https://stackoverflow.com/questions/57522/javascript-array-with-a-mix-of-literals-and-arrays), I have been able to populate a select box based on the selection of another select box. ( [I posted my answer here](https://stackoverflow.com/questions/57522/javascript-array-with-a-mix-of-lit...
I prefer data structure like this: ``` var carMakers = [ { name: 'Honda', models: [ { name: 'Accord', features: ['2dr', '4dr'] }, { name: 'CRV', features: ['2dr', 'Hatchback'] }, { name: 'Pilot', features: ['base', 'superDuper'] } ]}, { name: 'Toyota', models: [ ...
Thanks to the answer from @Marko Dunic, I was able to build an array (data) structure that can be referenced to populate 3 select boxes. I didn't use the implementation code only because I didn't completely understand it...it works as posted. I will come back to this code later as I learn jQuery. My code is posted belo...
Using javascript and jquery, to populate related select boxes with array structure
[ "", "javascript", "jquery", "" ]
It's easy to get the value of a key from a .NET generic Dictionary: ``` Dictionary<int, string> greek = new Dictionary<int, string>(); greek.Add(1, "Alpha"); greek.Add(2, "Beta"); string secondGreek = greek[2]; // Beta ``` But trying to get the keys given a value is not as straightforward because there could be mult...
Okay, here's the multiple bidirectional version: ``` using System; using System.Collections.Generic; using System.Text; class BiDictionary<TFirst, TSecond> { IDictionary<TFirst, IList<TSecond>> firstToSecond = new Dictionary<TFirst, IList<TSecond>>(); IDictionary<TSecond, IList<TFirst>> secondToFirst = new Di...
As everyone else has said, there's no mapping within a dictionary from value to key. **I've just noticed you wanted to map to from value to multiple keys - I'm leaving this solution here for the single value version, but I'll then add another answer for a multi-entry bidirectional map.** The normal approach to take h...
Getting multiple keys of specified value of a generic Dictionary?
[ "", "c#", ".net", "" ]
``` "foo" instanceof String //=> false "foo" instanceof Object //=> false true instanceof Boolean //=> false true instanceof Object //=> false false instanceof Boolean //=> false false instanceof Object //=> false 12.21 instanceof Number //=> false /foo/ instanceof RegExp //=> true // the tests against Object really...
Primitives are a different kind of type than objects created from within Javascript. From the [Mozilla API docs](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/instanceof_Operator): ``` var color1 = new String("green"); color1 instanceof String; // returns true var color2 = "...
I use: ``` function isString(s) { return typeof(s) === 'string' || s instanceof String; } ``` Because in JavaScript strings can be literals or objects.
Why does instanceof return false for some literals?
[ "", "javascript", "literals", "instanceof", "" ]
Is there a way to determine how many cores a machine has from C/C++ in a platform-independent way? If no such thing exists, what about determining it per-platform (Windows/\*nix/Mac)?
# C++11 ``` #include <thread> //may return 0 when not able to detect const auto processor_count = std::thread::hardware_concurrency(); ``` Reference: [std::thread::hardware\_concurrency](http://en.cppreference.com/w/cpp/thread/thread/hardware_concurrency) --- In C++ prior to C++11, there's no portable way. Instead...
This functionality is part of the C++11 standard. ``` #include <thread> unsigned int nthreads = std::thread::hardware_concurrency(); ``` For older compilers, you can use the [Boost.Thread](http://www.boost.org/doc/libs/1_46_0/doc/html/thread.html) library. ``` #include <boost/thread.hpp> unsigned int nthreads = bo...
Programmatically find the number of cores on a machine
[ "", "c++", "c", "multithreading", "multiplatform", "" ]
I'm trying to make a page in php that takes rows from a database, displays them, and then give the viewer a chance to upvote or downvote a specific entry. Here is a snippet: ``` echo("<form action=\"vote.php\" method=\"post\"> \n"); echo("<INPUT type=\"hidden\" name=\"idnum\" value=\"".$row[0]."\">"); echo("<INPUT typ...
Your form tag isn't closed properly. You have `<form/>`, but it should be `</form>`. This makes the entire page a form so it sends all the inputs. With a form that is closed properly though, it will only send the inputs within the form tags that the pressed button was in.
While this wouldn't have helped with this particular issue, I would recommend not mixing your markup with your logic wherever possible. This is quite a lot more readable, and quite a lot more editable as well: ``` <form action="vote.php" method="post"> <input type="hidden" name="idnum" value="<?php echo $row[0]; ?...
Are inputs in separate forms sent when a submit button is hit?
[ "", "php", "html", "" ]
There are a couple of questions similar to this on stack overflow but not quite the same. I want to open, or create, a local group on a win xp computer and add members to it, domain, local and well known accounts. I also want to check whether a user is already a member so that I don't add the same account twice, and p...
Okay, it's taken a while, messing around with different solutions but the one that fits best with my original question is given below. I can't get the DirectoryEntry object to access the members of a local group using the 'standard' methods, the only way I could get it to enumerate the members was by using the Invoke m...
Microsoft .NET Framework provides a standard library for working with Active Directory: **[System.DirectoryServices namespace](http://msdn.microsoft.com/en-us/library/ms682458(VS.85).aspx)** in the System.DirectoryServices.dll. Microsoft recommends using two main classes from the System.DirectoryServices namespace: **...
Get a list of members of a WinNT group
[ "", "c#", ".net", "active-directory", "active-directory-group", "windows-security", "" ]
I am writing a program in Python that will act as a server and accept data from a client, is it a good idea to impose a hard limit as to the amount of data, if so why? More info: So certain chat programs limit the amount of text one can send per send (i.e. per time user presses send) so the question comes down to is t...
Most likely you've seen code which protects against "extra" incoming data. This is often due to the possibility of buffer overruns, where the extra data being copied into memory overruns the pre-allocated array and overwrites executable code with attacker code. Code written in languages like C typically has a lot of le...
What is your question exactly? What happens when you do receive on a socket is that the current available data in the socket buffer is immediately returned. If you give receive (or read, I guess), a huge buffer size, such as 40000, it'll likely never return that much data at once. If you give it a tiny buffer size lik...
Receive socket size limits good?
[ "", "python", "sockets", "" ]
I'm pretty sure one would do this using the os.plock(op) function, but I have no idea how. Also, if there's a better way, I'd be grateful to find out. Code snippets are very welcome.
[Subprocess](http://docs.python.org/library/subprocess) replaces os.popen, os.system, os.spawn, popen2 and commands. A [simple example for piping](http://docs.python.org/library/subprocess#replacing-shell-pipe-line) would be: ``` p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PI...
Take a look at the [multiprocessing](http://docs.python.org/dev/library/multiprocessing.html) module new in python 2.6 (also available for earlier versions a [pyprocessing](http://pyprocessing.berlios.de/) Here's an example from the docs illustrating passing information using a pipe for instance: ``` from multiproces...
How do you share data between a parent and forked child process in Python?
[ "", "python", "fork", "share", "" ]
I would like to know if it is possible to determine if a function parameter with a default value was passed in Python. For example, how does dict.pop work? ``` >>> {}.pop('test') Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'pop(): dictionary is empty' >>> {}.pop('test',None) >>> ...
I guess you mean "keyword argument", when you say "named parameter". `dict.pop()` does not accept keyword argument, so this part of the question is moot. ``` >>> {}.pop('test', d=None) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: pop() takes no keyword arguments ``` That said, t...
The convention is often to use `arg=None` and use ``` def foo(arg=None): if arg is None: arg = "default value" # other stuff # ... ``` to check if it was passed or not. Allowing the user to pass `None`, which would be interpreted as if the argument was *not* passed.
Determine if a named parameter was passed
[ "", "python", "default-value", "named-parameters", "" ]
I continually get these errors when I try to update tables based on another table. I end up rewriting the query, change the order of joins, change some groupings and then it eventually works, but I just don't quite get it. What is a 'multi-part identifier'? When is a 'multi-part identifier' not able to be bound? W...
A multipart identifier is any description of a field or table that contains multiple parts - for instance MyTable.SomeRow - if it can't be bound that means there's something wrong with it - either you've got a simple typo, or a confusion between table and column. It can also be caused by using reserved words in your ta...
Actually sometimes when you are updating one table from another table's data, I think one of the common issues that cause this error, is when you use your table abbreviations incorrectly *or when they are not needed*. The correct statement is below: ``` Update Table1 Set SomeField = t2.SomeFieldValue From Table1 t1 ...
What is a 'multi-part identifier' and why can't it be bound?
[ "", "sql", "sql-server", "" ]
We have a C# service that is deployed to a remote customer system. The application writes a substantial amount of "diagnostic" information to the console (i.e. Console.WriteLine()). The service isn't "doing what it should." How can we capture the console output from the service in another application? A WinForm versio...
Are you able to change the service code *at all*? If so, using Console.SetOut to write to a file instead would be the most obvious first port of call. Then change to using a proper logging library for the next release :)
In general, you should avoid writing diagnostic information directly to Console, the Event Log, MSMQ or elsewhere from your application code. Instead call a logging API, and use configuration to redirect the output wherever you want. For example, you could replace all the Console.WriteLine by Trace.WriteLine (\*). The...
How to capture console output from a service C#?
[ "", "c#", "service", "console", "" ]
I have a c# form (let's call it MainForm) with a number of custom controls on it. I'd like to have the MainForm.OnClick() method fire anytime someone clicks on the form regardless of whether the click happened on the form or if the click was on one of the custom controls. I'm looking for behavior similar to the KeyPrev...
In the form's ControlAdded event, add a MouseClick handler to the control, with the Address of the form's click event. I haven't tested this, but it might work. ``` Private Sub Example_ControlAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.ControlEventArgs) Handles Me.ControlAdded AddHandler e.Contr...
I recommend creating a base form for the other forms in your application to inherit. Add this code to your base form to create a new event called GlobalMouseClickEventHandler: ``` namespace Temp { public delegate void GlobalMouseClickEventHander(object sender, MouseEventArgs e); public partial class TestForm ...
How do I set a click event for a form?
[ "", "c#", "winforms", "" ]
What is the best method for applying drop shadows? I'm working on a site right now where we have a good deal of them, however, I've been fighting to find the best method to do it. The site is pretty animation heavy so shadows need to work well with this. I tried a jQuery shadow pulgin. The shadows looked good and were...
[ShadedBorder](http://www.ruzee.com/blog/shadedborder/) is a good looking and easy to use Shadow-Library. check it out
You don't need to wrap those shadow-divs around the other content, just set them a little askew and place them on a lower z-index !-)
What's the best way to apply a drop shadow?
[ "", "javascript", "jquery", "css", "animation", "user-interface", "" ]
How do you change the CLASSPATH of a Java process from within the Java process? --- Before you ask me "Why would you want to do that?" I'll explain it shortly. > When you have a Clojure REPL running it is common to need more jars in your CLASSPATH to load a [Clojure](http://clojure.org) source file, and I'd like to ...
Update 2023: as [commented](https://stackoverflow.com/questions/252893/how-do-you-change-the-classpath-within-java#comment135692001_252967) below by [Holger](https://stackoverflow.com/users/2711488/holger) > The only way to add jar files to the class path working in Java 9 and newer, is through the [Instrumentation AP...
I don't believe you can - the right thing to do (I believe) is create a new classloader with the new path. Alternatively, you could write your own classloader which allows you to change the classpath (for that loader) dynamically.
How do you change the CLASSPATH within Java?
[ "", "java", "clojure", "classpath", "" ]
I have the following intentionally trivial function: ``` void ReplaceSome(ref string text) { StringBuilder sb = new StringBuilder(text); sb[5] = 'a'; text = sb.ToString(); } ``` It appears to be inefficient to convert this to a StringBuilder to index into and replace some of the characters only to copy it...
C# strings are "immutable," which means that they can't be modified. If you have a string, and you want a similar but different string, you must create a new string. Using a StringBuilder as you do above is probably as easy a method as any.
Armed with Reflector and the decompiled IL - On a pure LOC basis then the StringBuilder approach is definitely the most efficient. Eg tracing the IL calls that StringBuilder makes internally vs the IL calls for String::Remove and String::Insert etc. I couldn't be bothered testing the memory overhead of each approach, ...
Indexing into a String in C# as an L-Value
[ "", "c#", ".net", "" ]
Is there any way I can detect when my page has been set as the user's homepage in their browser? I'm most interested in something in javascript, but I'd be happy to hear about other approaches as well. **Edit**: I'm not looking for anything sneaky. I'm wondering if there is anything that is explicitly allowed through...
Mozilla/Firefox has a [`window.home()`](https://developer.mozilla.org/En/DOM/Window.home) method which loads the user's home page. This method could be used (in an iframe, maybe) combined with server access logging, to see if the site's home page is instantly requested loaded by the current user. However, other browse...
There isn't likely to be a foolproof method, as that's an intrusion into the privacy of the user. One thing that comes to mind is checking for a referrer. If the user arrived at your page without following a link, they a) typed the url, b) followed a bookmark, or c) have your page set as their homepage. But that's abo...
How can I tell if my page is set as the user's homepage?
[ "", "javascript", "" ]
What's a simple/easy way to access the system clock using Java, so that I can calculate the elapsed time of an event?
I would avoid using [`System.currentTimeMillis()`](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#currentTimeMillis--) for measuring elapsed time. [`currentTimeMillis()`](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#currentTimeMillis--) returns the 'wall-clock' time, which may change...
This is some sample code. ``` long startTime = System.currentTimeMillis(); // Run some code; long stopTime = System.currentTimeMillis(); System.out.println("Elapsed time was " + (stopTime - startTime) + " miliseconds."); ```
How do I calculate the elapsed time of an event in Java?
[ "", "java", "time", "timer", "clock", "" ]
I've seen some examples of C++ using template template parameters (that is templates which take templates as parameters) to do policy-based class design. What other uses does this technique have?
I think you need to use template template syntax to pass a parameter whose type is a template dependent on another template like this: ``` template <template<class> class H, class S> void f(const H<S> &value) { } ``` Here, `H` is a template, but I wanted this function to deal with all specializations of `H`. **NOTE*...
Actually, usecase for template template parameters is rather obvious. Once you learn that C++ stdlib has gaping hole of not defining stream output operators for standard container types, you would proceed to write something like: ``` template<typename T> static inline std::ostream& operator<<(std::ostream& out, std::l...
What are some uses of template template parameters?
[ "", "c++", "templates", "template-templates", "" ]
If I have the following string: ``` string s = "abcdefghab"; ``` Then how do I get a string (or char[]) that has just the characters that are repeated in the original string using C# and LINQ. In my example I want to end up with "ab". Although not necessary, I was trying to do this in a single line of LINQ and had s...
``` String text = "dssdfsfadafdsaf"; var repeatedChars = text.ToCharArray().GroupBy(x => x).Where(y => y.Count() > 1).Select(z=>z.Key); ```
``` string theString = "abcdefghab"; //C# query syntax var qry = (from c in theString.ToCharArray() group c by c into g where g.Count() > 1 select g.Key); //C# pure methods syntax var qry2 = theString.ToCharArray() .GroupBy(c => c) .Where(g => g.Count() > 1) ...
How do I get an array of repeated characters from a string using LINQ?
[ "", "c#", "linq", "algorithm", "" ]
I have Virtual PC 2007. I am writing a C# program that will run on the Host and Virtual. It needs to communicate both ways. **What is the best way to do this?** **Can it be done in a way that does not require changing Virtual settings?** (the OSs will be XP, Vista, Server 2000 / 2003)
[WCF](http://msdn.microsoft.com/en-us/netframework/aa663324.aspx). .NET Remoting without the calls to the suicide prevention hotline.
Via TCP. Simple client/server setup. or [.NET Remoting](http://msdn.microsoft.com/en-us/library/ms973864.aspx)
What is the best way for a process inside a VirtualPc to talk to a process on the host?
[ "", "c#", "virtual-pc", "" ]
*[This question is related to but not the same as [this one](https://stackoverflow.com/questions/206106/is-a-safe-way-to-convert-to-bool-in-c).]* My compiler warns about implicitly converting or casting certain types to bool whereas explicit conversions do not produce a warning: ``` long t = 0; bool b = false; b = t;...
I was puzzled by this behaviour, until I found this link: <http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99633> Apparently, coming from the Microsoft Developer who "owns" this warning: > *This warning is surprisingly > helpful, and found a bug in my code > just yesterday. I think Ma...
The performance is identical across the board. It involves a couple of instructions on x86, maybe 3 on some other architectures. On x86 / VC++, they all do ``` cmp DWORD PTR [whatever], 0 setne al ``` GCC generates the same thing, but without the warnings (at any warning-level).
What is the performance implication of converting to bool in C++?
[ "", "c++", "visual-c++", "" ]
I have a query that has a list of base values and a list of language values. Each value has a key that matches to the other. The base values are stored in one table and the language values in another. My problem is that I need to get all matching base values removed from the QUERY except for one. Then, I export that qu...
Hey thanks for that update! Looking at that and adding it into a previous post I finally came up with this: ``` <cfquery name="getRows" datasource="XXXX"> SELECT pe.prodtree_element_name_l, MAX(rs.resource_value) AS resource_value FROM prodtree_element pe LEFT JOIN resource_shortstrings rs ON pe.p...
Hrm, still not real clear on what the issue truly is, but let me give it a go. Tables: ``` BASE_VALUES ------------------ BASE_VALUE_RK BASE_VALUE_NAME RESOURCE_VALUES (these are the translations, I'm guessing) ----------------------- RESOURCE_KEY RESOURCE_LANGUAGE_ID RESOURCE_VALUE ``` You want to retrieve one bas...
Matching values in two tables query (SQL and ColdFusion)
[ "", "sql", "excel", "coldfusion", "" ]
I am developing some client side Javascript that is using some JSON web services on a different domain. I have read that some browsers do not allow cross-domain scripting and that I should create a proxy on my local server to serve the data. Can someone please point me to a simple example of how to do this in ASP.Net?
You may be able to avoid a proxy by using a technique like [JSONP](http://remysharp.com/2007/10/08/what-is-jsonp/). Assuming the web service you're talking to supports JSONP (for example, Flickr or Twitter both offer a JSONP API) or you have control over the data the web service sends back, you can send JSON data betwe...
Generally speaking, the proxy runs on your web server - most likely IIS in your case - and 'relays' the requests to another server on a different domain. Here's an example of one implemented in C# .NET [Fast, Streaming AJAX proxy](https://www.codeproject.com/articles/25218/fast-scalable-streaming-ajax-proxy-continuou...
Cross browser scripting proxy
[ "", "asp.net", "javascript", "web-services", "cross-domain", "" ]
I have two PHP scripts, both using the same session by calling `session_name('MySessID')`. When the first script calls the second script using curl, the second script hangs when `session_start()` is called. Why would this happend?
I don't totally understand why this happens, but I got it solved. This [bug](http://bugs.php.net/bug.php?id=44134) describes the same problem I'm having. I have a scripts posting to another script, *both using the same session*, which apparently stalls PHP. So, before I do the whole curl post script, I call the `sess...
From the php manual <http://php.net/manual/en/function.session-write-close.php> Session data is usually stored after your script terminated without the need to call session\_write\_close(), **but as session data is locked to prevent concurrent writes only one script may operate on a session at any time**. When using ...
Why does session_start cause a timeout when one script calls another script using curl
[ "", "php", "post", "curl", "timeout", "" ]
**UPDATE:** Thanks to everyone for the responses. I didn't realize document.write() was deprecated. Add a another notch to the learning column. I'll be taking the advice posted here, but leave the original question so that the answers given make sense in context of the original question. --- I'm in the process of cod...
My gut reaction is: **don't do that**. (Your example is poor, you should not be writing big chunks of content in your behavior layer.) Whenever you *have to* do this, either concat: ``` var longVar = 'asdfasdf asdf asdf asdfasdf asdfasdf asdf asdfasdf' + ' fasdf s9d0af asdf asdf0s,dv z-xcfva-sdfmwaert ' + 'qe...
I would write it however is going to be easiest to read and maintain. Then test the performance. If it is too slow try incrementally improving the algorithm until the speed is acceptable. So ideas to improve the performance: - ensure script is minified. - do as much preprocessing on the server and serve the "processed...
Which is the best way to handle long write() arguments?
[ "", "javascript", "readability", "" ]
I feel that using GetEnumerator() and casting IEnumerator.Current is expensive. Any better suggestions? I'm open to using a different data structure if it offers similiar capabilities with better performance. **After thought:** Would a generic stack be a better idea so that the cast isn't necessary?
Have you done any benchmarks, or are they just gut feelings? If you think that the majority of the processing time is spent looping through stacks you should benchmark it and make sure that that is the case. If it is, you have a few options. 1. Redesign the code so that the looping isn't necessary 2. Find a faster lo...
`Stack<T>` (with foreach) would indeed save the cast, but actually boxing [isn't all *that* bad](https://codeblog.jonskeet.uk/2008/10/08/why-boxing-doesn-t-keep-me-awake-at-nights/) in the grand scheme of things. If you have performance issues, I doubt this is the area where you can add much value. Use a profiler, and ...
Fastest way to iterate over a stack in c#
[ "", "c#", "optimization", "stack", "" ]
Magento shopping cart is built on the Zend Framework in PHP. This is the first time I've dealt with the Zend framework and I'm having the following difficulty... I'm creating a custom module that will allow users to upload images whenever they purchase products. I can overload the addAction() method whenever a user a...
hey this option is given in newer version of magento 1.3.1 to upload the file from frontend enjoy
I thought I'd move to a new answer as I think I've managed to get it working. Here's what I did created the following files; app/code/local/Company/SpecialCheckout/controllers/Checkout/CartController.php app/code/local/Company/SpecialCheckout/etc/config.xml app/etc/modules/Company\_SpecialCheckout.xml First the c...
Magento Custom Module. Redirect to another module and return to checkout
[ "", "php", "magento", "zend-framework", "module", "checkout", "" ]
This is a simple one. I want to replace a sub-string with another sub-string on client-side using Javascript. Original string is `'original READ ONLY'` I want to replace the `'READ ONLY'` with `'READ WRITE'` Any quick answer please? Possibly with a javascript code snippet...
`String.replace()` is regexp-based; if you pass in a string as the first argument, the regexp made from it will not include the **‘g’** (global) flag. This option is essential if you want to replace all occurances of the search string (which is usually what you want). An alternative **non-regexp** idiom for simple glo...
Good [summary](http://www.w3schools.com/jsref/jsref_replace.asp). It is regexp based, if you use regexp notation you can specify the i and g modifiers (case insensitive (i), which will match regardless to case and global (g), which will replace all occurences), if you use string notation it'll get converted to a regex ...
Javascript - how to replace a sub-string?
[ "", "javascript", "regex", "" ]
I have a third-party product, a terminal emulator, which provides a DLL that can be linked to a C program to basically automate the driving of this product (send keystrokes, detect what's on the screen and so forth). I want to drive it from a scripting language (I'm comfortable with Python and slightly less so with Pe...
One way to call C libraries from Python is to use [ctypes](https://docs.python.org/library/ctypes.html): ``` >>> from ctypes import * >>> windll.user32.MessageBoxA(None, "Hello world", "ctypes", 0); ```
In Perl, [Win32::API](http://search.cpan.org/perldoc?Win32::API) is an easy way to some interfacing to DLLs. There is also [Inline::C](http://search.cpan.org/perldoc?Inline::C), if you have access to a compiler and the windows headers. Perl [XSUB](http://search.cpan.org/perldoc?perlxs)s can also create an interface be...
How can I call a DLL from a scripting language?
[ "", "python", "perl", "dll", "" ]
Python's IDLE has 'Check Module' (Alt-X) to check the syntax which can be called without needing to run the code. Is there an equivalent way to do this in Emacs instead of running and executing the code?
You can [use Pyflakes together with Flymake](https://web.archive.org/web/20090503090851/http://www.plope.org/Members/chrism/flymake-mode) in order to get instant notification when your python code is valid (and avoids a few common pitfalls as well).
``` python -m py_compile script.py ```
How can I check the syntax of Python code in Emacs without actually executing it?
[ "", "python", "validation", "emacs", "syntax", "" ]
I am trying the following code: ``` <?php $link = mysql_connect('localhost', 'root', 'geheim'); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; $query = "SELECT * FROM Auctions"; $result = mysql_query($query); while($row = mysql_fetch_...
You haven't selected a database - use [`mysql_select_db()`](http://www.php.net/mysql_select_db) That would be something like: ``` <?php $link = mysql_connect('localhost', 'root', 'geheim'); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; $db_sele...
Your MySQL query possibly does not match any rows in the database. Check the return value of [mysql\_query()](http://nl2.php.net/mysql_query), which returns "resource" on success and "false" on failure. ``` $query = "SELECT * FROM Auctions"; $result = mysql_query($query); if ($result !== false) { while ($row = ...
mysql_fetch_array() returns 'supplied argument is not a valid MySQL result resource'
[ "", "php", "mysql", "" ]
Does anyone have a library or JavaScript snippet to validate the check digit of credit cards before the user hits Submit?
The [jQuery Validation Plugin](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) has a [method](http://jquery.bassistance.de/api-browser/plugins.html#jQueryvalidatormethodscreditcard) for validating credit card numbers. There are other specific scripts: * [JavaScript Credit Card Validation Function](htt...
Probably OP doesn't even follow this thread anymore but this may be helpful for someone else: [http://jquerycreditcardvalidator.com](http://jquerycreditcardvalidator.com/) It checks the card type, validates its length and checks for mod 10 with Luhn algorithm.
Client-side validation of credit cards
[ "", "javascript", "validation", "luhn", "" ]
I'm sure this has been asked before, but I can't find it. What are the benefits/limitations of using a browser-based interface for a stand-alone application vs. using a normal GUI framework? I'm working on a Python program currently implement with wxPython for the GUI. The application is simply user-entry forms and d...
The obvious advantages to browser-based: * you can present the same UI regardless of platform * you can upgrade the application easily, and all users have the same version of the app running * you know the environment that your application will be running in (the server hardware/OS) which makes for easier testing and ...
Let's pretend for a moment that the development/deployment/maintenance effort/cost is equal and we look at it from the application user's perspective: *Which UI is the user going to find more useful?* in terms of * Ease of use * Responsiveness * Familiar navigation/usage patterns * Most like other tools/applications...
Browser-based application or stand-alone GUI app?
[ "", "python", "user-interface", "browser", "" ]
I'm designing some VB based ASP.NET 2.0, and I am trying to make more use of the various ASP tags that visual studio provides, rather than hand writing everything in the code-behind. I want to pass in an outside variable from the Session to identify who the user is for the query. ``` <asp:sqldatasource id="DataStores"...
I believe Oracle uses the colon ":", not the at-symbol "@". --- "user" is probably a reserved word. Change it to "userID", or something similar.
You may want to consider using a [SessionParameter](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sessionparameter(VS.80).aspx) instead of just a Parameter and let the SqlDataSource extract the user id directly from the session without any intervention on your part. Also, the example on the page lin...
ASP.NET : Passing a outside variable into a <asp:sqldatasource> tag ASP.NET 2.0
[ "", "sql", "vb.net", "asp.net-2.0", "selectcommand", "" ]