Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am a newbie and just learned that if I define say ``` package my.first.group.here; ... ``` then the Java files that are in this package will be placed under `my/first/group/here` directory. What is the main purpose of putting some Java files in a package? Also, if I choose to adopt this, how should I group them? Thank you --- EDIT: For anyone who might have the same question again, I just found [this tutorial on packages](http://java.sun.com/docs/books/tutorial/java/package/index.html) from Sun.
Let's start with the definition of a "Java package", as described in the [Wikipedia article](http://en.wikipedia.org/wiki/Java_package): > A Java package is a mechanism for > organizing Java classes into > namespaces similar to the modules of > Modula. Java packages can be stored in > compressed files called JAR files, > allowing classes to download faster as > a group rather than one at a time. > Programmers also typically use > packages to organize classes belonging > to the same category or providing > similar functionality. So based on that, **packages in Java are simply a mechanism used to organize classes and prevent class name collisions**. You can name them anything you wish, but Sun has published some [naming conventions](http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html#367) that you *should* use when naming packages: > **Packages** > > The prefix of a unique package name is > always written in all-lowercase ASCII > letters and should be one of the > top-level domain names, currently com, > edu, gov, mil, net, org, or one of the > English two-letter codes identifying > countries as specified in ISO Standard > 3166, 1981. > > Subsequent components of the package > name vary according to an > organization's own internal naming > conventions. Such conventions might > specify that certain directory name > components be division, department, > project, machine, or login names. > > **Examples:** > > * com.sun.eng > * com.apple.quicktime.v2 > * edu.cmu.cs.bovik.cheese
I a large application, you are bound to have two files named exactly the same (java.util.Date and java.sql.Date), especially when you start bringing in third party jars. So basically, you can use packages to ensure uniqueness. Most importantly, in my opinion, packaging breaks down projects into meaningful segments. So my SQL package has sql-related code, and my logger package handles logging.
What is the purpose of defining a package in a Java file?
[ "", "java", "package", "" ]
Really simple problem: I want to split a connection string into its keyword / value pairs, so for example the following connection string: ``` Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=vm-jp-dev2;Data Source=scsql\sql2005;Auto Translate=False ``` Would become: ``` Provider=SQLOLEDB.1 Integrated Security=SSPI Persist Security Info=False Initial Catalog=vm-jp-dev2 Data Source=scsql\sql2005 Auto Translate=False ``` The trouble is that the [MSDN documentation](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx) states that connection string values are allowed to contain semicolons if the value is enclosed in single or double quote characters, (so if I understand it the following would be valid): ``` Provider="Some;Provider";Initial Catalog='Some;Catalog';... ``` Whats the best way of splitting this string (in C#)?
There is a DBConnectionStringBuilder class that will do what you want... ``` System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder(); builder.ConnectionString = "Provider=\"Some;Provider\";Initial Catalog='Some;Catalog';"; foreach (string key in builder.Keys) { Response.Write(String.Format("{0}: {1}<br>", key , builder[key])); } ```
You should implement some sort of simple string parsing respecing quotes. Something like that: ``` public static IEnumerable<string> SplitString(string str) { int StartIndex = 0; bool IsQuoted = false; for (int I = 0; I < str.Length; I++) { if (str[I] == '"') IsQuoted = !IsQuoted; if ((str[I] == ';') && !IsQuoted) { yield return str.Substring(StartIndex, I - StartIndex); StartIndex = I + 1; } } if (StartIndex < str.Length) yield return str.Substring(StartIndex); } ```
Split a string by semicolons while accounting for escaped characters
[ "", "c#", "string", "connection-string", "" ]
I followed this tutorial: <https://github.com/EllisLab/CodeIgniter/wiki/PDF-generation-using-dompdf> However, I can't seem to set the path right. On the config file of dompdf (`config_dompdf.inc.php`) I did the following: ``` define("DOMPDF_DIR", realpath(dirname('./system/plugins/dompdf/'))); ``` I get this error: ``` Message: require_once(/var/www/myApp/system/plugins/include/functions.inc.php) [function.require-once]: failed to open stream: No such file or directory Filename: dompdf/dompdf_config.inc.php Line Number: 233 ``` As per the tutorial, I placed the dompdf directory under `system/plugins`. But you can see above that on line 233, there is an error because of an incorrect path. How do I fix the path? ``` (define("DOMPDF_DIR", realpath(dirname('./system/plugins/dompdf/')));) ``` Thanks!
A custom loader that is on autoload is conflicting with DOMPDF, that's the reason it doesn't work. Switched to TCPDF since the custom loader is used by all controllers of the app.
this file take `$_GET['input_file']` as the name of the file that should be converted to pdf ``` http://localhost/dompdf/dompdf.php?input_file=[nameofyourfile] ```
dompdf with codeigniter
[ "", "php", "codeigniter", "dompdf", "" ]
I am trying to write a php function to stop MySQL injection attempts. What I am doing is using str\_replace() to remove symbols and replace them with with their HTML character code. My issue is that the codes all contain &#; but I also want to replace those symbols with their codes. How can I do this without changing the code into something like: ``` &#38&#59;&338&#59;#35&#59;32&#59; ``` Here is my function: ``` function replaceSymbols( $text ) { $text = str_replace( '#', '&#35', $text ); $text = str_replace( '&', '&#38;' $text ); $text = str_replace( ';', '&#59', $text ); $text = str_replace( ' ', '&#32;' $text ); $text = str_replace( '!', '&#33;' $text ); $text = str_replace( '"', '&#34;' $text ); $text = str_replace( '$', '&#36;' $text ); $text = str_replace( '%', '&#37;' $text ); $text = str_replace( "'" '&#39', $text ); $text = str_replace( '(', '&#40;' $text ); $text = str_replace( ')', '&#41;' $text ); $text = str_replace( '*', '&#42;' $text ); $text = str_replace( '+', '&#43', $text ); $text = str_replace( ',', '&#44;' $text ); $text = str_replace( '-', '&#45;' $text ); $text = str_replace( '.', '&#46;' $text ); $text = str_replace( '/', '&#47', $text ); $text = str_replace( ':', '&#58;' $text ); $text = str_replace( '<', '&#60;' $text ); $text = str_replace( '=', '&#61;' $text ); $text = str_replace( '>', '&#62;' $text ); $text = str_replace( '?', '&#63', $text ); $text = str_replace( '[', '&#91', $text ); $text = str_replace( '\\', '&#92;' $text ); $text = str_replace( ']', '&#93;' $text ); $text = str_replace( '^', '&#94;' $text ); $text = str_replace( '_', '&#95', $text ); $text = str_replace( '`', '&#96', $text ); $text = str_replace( '{', '&#123;' $text ); $text = str_replace( '|', '&#124;' $text ); $text = str_replace( '}', '&#125', $text ); $text = str_replace( '~', '&#126', $text ); return $text; } ```
Have you looked at [`mysql_real_escape_string`](http://www.php.net/mysql_real_escape_string)? > Escapes special characters in the > unescaped string, taking into account > the current character set of the > connection so that it is safe to place > it in a mysql\_query().
Is there any reason that [mysql\_real\_escape\_string](https://www.php.net/mysql_real_escape_string)($text) doesn't fulfill your needs?
PHP Function to replace symbols with character codes to stop SQL Injection
[ "", "php", "mysql", "character-encoding", "sql-injection", "symbols", "" ]
How can I check whether a particular element is inside an array? **I don't want to manually write a loop for this**; instead I want to use a JavaScript built-in function, maybe something equivalent to ``` new Array(0,1,2,3,6,9,12,15,18).Contains(5) //return false new Array(0,1,2,3,6,9,12,15,18).Contains(1) //return true ```
Looks like a job for [jQuery.inArray](http://docs.jquery.com/Utilities/jQuery.inArray) ``` inArray: function( elem, array ) { for ( var i = 0, length = array.length; i < length; i++ ) // Use === because on IE, window == document if ( array[ i ] === elem ) return i; return -1; } ```
The Array object does have an [indexOf](https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/IndexOf) function, that will return -1 if the object does not exist. However, IE does not support this function. Regardless, how do you think it is going to locate the item under the scenes? It will have to loop! Just because there's a built-in function does not mean that it is magical.
How can I determine if an element is contained in an Array without looping?
[ "", "javascript", "arrays", "" ]
What is an **efficient** way of determining whether a `BigDecimal` is an integer value in the mathematical sense? At present I have the following code: ``` private boolean isIntegerValue(BigDecimal bd) { boolean ret; try { bd.toBigIntegerExact(); ret = true; } catch (ArithmeticException ex) { ret = false; } return ret; } ``` ... but would like to avoid the object creation overhead if possible. Previously I was using `bd.longValueExact()` which would avoid creating an object if the `BigDecimal` was using its compact representation internally, but obviously would fail if the value was too big to fit into a long.
Depending on the source/usage of your `BigDecimal` values it might be faster to check if the scale <= 0 first. If it is, then it's definitely an integer value in the mathematical sense. If it is >0, then it *could* still be an integer value and the more expensive test would be needed.
EDIT: As of Java 8, stripTrailingZeroes() now accounts for zero [BigDecimal stripTrailingZeros doesn't work for zero](https://stackoverflow.com/questions/34414785/bigdecimal-striptrailingzeros-doesnt-work-for-zero) So ``` private boolean isIntegerValue(BigDecimal bd) { return bd.stripTrailingZeros().scale() <= 0; } ``` Is perfectly fine now. --- If you use the `scale()` and `stripTrailingZeros()` solution mentioned in some of the answers you should pay attention to zero. Zero always is an integer no matter what scale it has, and `stripTrailingZeros()` does not alter the scale of a zero BigDecimal. So you could do something like this: ``` private boolean isIntegerValue(BigDecimal bd) { return bd.signum() == 0 || bd.scale() <= 0 || bd.stripTrailingZeros().scale() <= 0; } ```
Check if BigDecimal is an integer in Java
[ "", "java", "bigdecimal", "" ]
I'm working on a C++ project on GNU/Linux and I'm looking for a way to test the existence and usability of IBM Informix's library with the Autotools - namely, editing a `configure.in`. I don't have experience with Autotools, so basically I'm picking up from the project's `configure.in` *et al.* scripts and copying&changing where I feel needs to be changed. IOW, I've been adapting from the existing text in `configure.in`. So far I've been using successfully the `AC_CHECK_LIB` in `configure.in` to test whether a certain library both exists and is usable. But this only seems to work with libraries with *functions*, not e.g. classes. Namely, this fails when testing Informix's `libifc++.so` library: ``` AC_CHECK_LIB(ifc++, ITString, INFORMIX_LIB="-L$INFORMIX_LIB_LOCATION/c++ -lifc++ -L$INFORMIX_LIB_LOCATION -L$INFORMIX_LIB_LOCATION/dmi -L$INFORMIX_LIB_LOCATION/esql -lifdmi -lifsql -lifasf -lifgen -lifos -lifgls -lifglx $INFORMIX_LIB_LOCATION/esql/checkapi.o -lm -ldl -lcrypt -lnsl", echo "* WARNING: libifc++.so not found!" INFORMIX_INC="" INFORMIX_LIB="" ) ``` I've also tried using other combinations, like `ITString::ITString`, etc. I haven't found a "pure" function in Informix's API (i.e., one that isn't contexted in a C++ class). So I'm hoping that either there's a way to use `AC_CHECK_LIB` in this context, or there's another `autoconf`/`configure.in` "command" for this specific use. Thanks in advance for your feedback.
There might be a cleaner way of achieving this, but I think your problem is that C++ methods get "mangled" to allow additional information about the method (argument & return types etc) to be encoded. For example; the method `int A::foo(void)` will get mangled to something like `__ZN1A3fooEv`. So you need to find the mangled name of a method in the library. You can do this by using the [`nm` command](https://en.wikipedia.org/wiki/Nm_(Unix)) on Unix-like OSs: ``` $ nm libifc++.so | grep ITString ``` It's worth mentioning that the exact mangling format varies across different compilers; and so by embedding a certain compiler's mangled symbol in your `configure.in` it may not work on other platforms - YMMV. Note: you can use the [`c++filt`](https://sourceware.org/binutils/docs/binutils/c_002b_002bfilt.html "c++filt (GNU Binary Utilities)") utility to demangle a name back to it's human-readable form; so for the example I gave previously: ``` $ c++filt __ZN1A3fooEv A::foo() ``` See [Name Mangling in C++](http://en.wikipedia.org/wiki/Name_mangling#Name_mangling_in_C.2B.2B) on Wikipedia for more information.
You've discovered a shortcoming of autotools, but one that can't really be helped. Autotools checks for symbol names in the library binary, and unlike C where symbol names of functions are identical to the function names, C++ "mangles" function's symbol names to accomplish things like function overloading. What's worse is that C++ doesn't really even have a "standard" mangling convention, so different C++ compilers may produce different symbol names for the same function. Thus, autotools can't check for C++ symbol names in a reliable manner. Does the library you are trying to use have any functions that are declared with `extern "C"`? This causes the C++ compiler to generate standardized C-style symbol names, and autotools will be able to find them. I ran into this issue trying to detect [gtest](http://code.google.com/p/googletest/) and [gmock](http://code.google.com/p/googlemock/) (the Google unit testing and object mocking frameworks) with Autotools, and here's what I came up with: ``` # gtest has a main function in the gtest_main library with C linkage, we can test for that. AC_CHECK_LIB([gtest_main], [main], [HAVE_GTEST=1] [TEST_LIBS="$TEST_LIBS -lgtest_main"], AC_MSG_WARN([libgtest (Google C++ Unit Testing Framework) is not installed. Will not be able to make check.])) # gmock has no functions with C linkage, so this is a roundabout way of testing for it. We create a small test # program that tries to instantiate one of gmock's objects, and try to link it with -lgmock and see if it works. if test "$HAVE_GTEST" then saved_ldflags="${LDFLAGS}" LDFLAGS="${LDFLAGS} -lgtest -lgmock" AC_LINK_IFELSE([AC_LANG_PROGRAM([#include <gmock/gmock.h>], [testing::Cardinality dummy])], [TEST_LIBS="$TEST_LIBS -lgmock"] [HAVE_GMOCK=1], [AC_MSG_WARN([libgmock (Google C++ Object Mocking Framework) is not installed. Will not be able to make check.])]) LDFLAGS="${saved_ldflags}" fi ```
How to test a C++ library usability in configure.in?
[ "", "c++", "autotools", "configure", "usability", "autoconf", "" ]
What is the proper way to set the Company Name and Application Name in a ClickOnce application? I have a set of projects in a solution called RecordNavigator. The GUI project is called RecordNavigator.Gui. When I publish the application - I want the Start menu to have a folder called *Tyndall Software* and the application shortcut to be called *Record Navigator*. Right now the folder says *Organization* and the shortcut says *RecordNavigator.Gui*. The AssemblyInfo.cs file seems to have no effect. Is that normal?
If you open your project's properties in Visual Studio and click on the 'Publish' tab, there should be an 'Options...' button under 'Install Mode and Settings'. There you can define the Publisher name ('Tyndall Software'), Product name ('Record Navigator'), and other such options.
You need to change the ClickOnce manifest, not the assemblyinfo.cs... There is an [MSBuild](http://en.wikipedia.org/wiki/MSBuild) task for this: [GenerateDeploymentManifest](http://msdn.microsoft.com/en-us/library/3k2t34e7.aspx) ``` <GenerateDeploymentManifest AssemblyName="$(ApplicationIdentity)" AssemblyVersion="$(PublishVersion)" Description="$(ApplicationDescription)" EntryPoint="@(ApplicationManifest)" DeploymentUrl="$(PublishURL)/$(App).application" MapFileExtensions="true" OutputManifest="$(App).application" Product="$(ApplicationDescription)" Publisher="$(Publisher)" SupportUrl="$(SupportURL)" > <Output ItemName="DeploymentManifest" TaskParameter="OutputManifest" /> </GenerateDeploymentManifest> ``` Set your $(Description) to the Application Name you want, $(Publisher) value to the Company Name, and the $(SupportURL) to the URL you want to publish.
.NET - ClickOnce Install - Company Name and Application Name
[ "", "c#", ".net", "deployment", "clickonce", "smartclient", "" ]
I have seen uses of `@` in front of certain functions, like the following: ``` $fileHandle = @fopen($fileName, $writeAttributes); ``` What is the use of this symbol?
The `@` symbol is the [error control ***operator***](https://www.php.net/manual/en/language.operators.errorcontrol.php) (aka the "silence" or "shut-up" operator). It makes PHP suppress any diagnostic error messages generated by the expression associated with it. Like unary operators, it has a precedence and associativity. Below are some examples: ``` @echo 1 / 0; // displays "Parse error: syntax error, unexpected T_ECHO" // this is because "echo" is not an expression // the script terminates because of parse error echo @(1 / 0); // suppressed "Warning: Division by zero" @$i / 0; // suppressed "Notice: Undefined variable: i" // displays "Warning: Division by zero" @($i / 0); // suppressed "Notice: Undefined variable: i" // suppressed "Warning: Division by zero" $c = @$_POST["a"] + @$_POST["b"]; // suppressed "Notice: Undefined index: a" // suppressed "Notice: Undefined index: b" $c = @foobar(); echo "Script was not terminated"; // displays "Fatal error: Call to undefined function foobar()" // fatal errors are displayed even with the shut-up operator // the script terminates because of fatal error ```
It suppresses error messages — see [Error Control Operators](http://php.net/manual/language.operators.errorcontrol.php) in the PHP manual.
What is the use of the @ symbol in PHP?
[ "", "php", "operators", "error-suppression", "" ]
I wanted to see that a dynamically loaded library (loaded with dlopen etc.) really uses its own new an delete operators and not these ones defined in the calling program. So I wrote the following library.cpp ``` #include <exception> #include <new> #include <cstdlib> #include <cstdio> #include "base.hpp" void* operator new(size_t size) { std::printf("New of library called\n"); void *p=std::malloc(size); if (p == 0) // did malloc succeed? throw std::bad_alloc(); // ANSI/ISO compliant behavior return p; } void operator delete(void* p) { std::printf("Delete of library called\n"); std::free(p); } class Derived : public Base { public: Derived() : Base(10) { } }; extern "C" { Base* create() { return new Derived; } void destroy(Base* p) { delete p; } } ``` and compiled it with ``` g++ -g -Wall -fPIC -shared library.cpp -o library.so ``` or as Employed Russian suggested to try (but in the end nothing changed) ``` g++ -g -Wall -fPIC -shared -Wl,-Bsymbolic library.cpp -o library.so ``` The class Base is only holding an int value and a function get\_value() to get this value. After that I wrote client.cpp like this ``` #include <exception> #include <new> #include <iostream> #include <cstdlib> #include <cstdio> #include <dlfcn.h> #include "base.hpp" void* operator new(size_t size) { std::printf("New of client called\n"); void *p=std::malloc(size); if (p == 0) // did malloc succeed? throw std::bad_alloc(); // ANSI/ISO compliant behavior return p; } void operator delete(void* p) { std::printf("Delete of client called\n"); std::free(p); } typedef Base* create_module_t(); typedef void destroy_module_t(Base *); int main() { void* handle = dlopen("./library.so", RTLD_LAZY); if (handle == NULL) { std::cout << dlerror() << std::endl; return 1; } create_module_t* create_module = NULL; void* func = dlsym(handle, "create"); if (func == NULL) { std::cout << dlerror() << std::endl; return 1; } else create_module = (create_module_t *)func; destroy_module_t* destroy_module = NULL; func = dlsym(handle, "destroy"); if (func == NULL) { std::cout << dlerror() << std::endl; return 1; } else destroy_module = (destroy_module_t *)func; Base* a = create_module(); std::cout << "Value: " << a->get_value() << std::endl; destroy_module(a); return 0; } ``` and compiled it with ``` g++ -Wall -g -o client -ldl client.cpp ``` Executing client I only get a "New of client called" and a "Delete of client called". Even if I use the compiler switch -Bsymbolic for the library like Employed Russian suggested. Now: What went wrong? I thought shared library are using their own new/delete and therefore you have to provide next to the factory create a destructor destroy in the library code. Supplementary question: Why do I need the destroy(Base\* p) function? If this function only calls the delete-operator of the client I could also do it by myself, i.e "delete a" instead of destroy\_module(a) in the next to last line. Answer I found: The library can also provide a new/delete-operator pair. So if I use first the library's new and later the client's delete I can probably step into a pitfall. Sadly until now I never saw my library using it's own new or delete... So the original question still isn't answered. Supplement: I'm only referring to the Linux platform. Edit: The important parts are in the comments to Employed Russian's Answer. So I'm giving the main clue in a nutshell: If one calls the gcc this way ``` g++ -Wall -g -fPIC -shared library.cpp -o library.so -Wl,-Bsymbolic ``` the library will use it's own new/delete operators. Otherwise results ``` g++ -Wall -g -fPIC -shared library.cpp -o library.so ``` in a library that's using the new/delete operators of the calling program. Thanks to Employed Russian!
The problem is that on most `UNIX` platforms (unlike on `Win32` and `AIX`) all symbol references by default bind to the *first* definition of the symbol visible to the runtime loader. If you define `'operator new'` in the main `a.out`, everything will bind to that definition (as Neil Butterworth's example shows), because `a.out` is the very first image runtime loader searches. If you define it in a library which is loaded after `libC.so` (or `libstdc++.so` in case you are using `GCC`), then your definition will never be used. Since you are `dlopen()`ing your library after the program has started, `libC` is already loaded by that point, and your library is the very last one the runtime loader will search; so you lose. On `ELF` platforms, you may be able to change the default behavior by using `-Bsymbolic`. From `man ld` on Linux: ``` -Bsymbolic When creating a shared library, bind references to global symbols to the definition within the shared library, if any. Normally, it is possible for a program linked against a shared library to override the definition within the shared library. This option is only meaningful on ELF platforms which support shared libraries. ``` Note that `-Bsymbolic` is a linker flag, not a compiler flag. If using `g++`, you must pass the flag to the linker like this: ``` g++ -fPIC -shared library.cpp -o library.so -Wl,-Bsymbolic ```
The following code works as expected. Are you expecting your dynamic library code to use the new/delete you provide? I think you will be disappointed. ``` #include <memory> #include <cstdio> #include <cstdlib> using namespace std;; void* operator new(size_t size) { std::printf("New...\n"); void *p=std::malloc(size); if (p == 0) // did malloc succeed? throw std::bad_alloc(); // ANSI/ISO compliant behavior return p; } void operator delete(void* p) { std::printf("Delete...\n"); std::free(p); } int main() { int * p = new int(42); delete p; } ```
Why isn't my new operator called
[ "", "c++", "g++", "overriding", "allocation", "" ]
Specifically how can I: * Show a button which will let the user browse through his computer and select a file * Show a progress bar as the files are uploaded * And store the files to a location on the server of the website on which the applet is being run Any ideas? And yes, I must do this in an applet, and I will make it a trusted/signed applet, have looked into all that.
I've had to do just this, with very large (4Gb+) files. The piece of code at the bottom of this Google Answers post helped me out a LOT: <http://answers.google.com/answers/threadview?id=193780> It showed a way of uploading files chunked into smaller bits, so you can easily use a JProgressBar.
There is no need to sign the applet since 6u10. Instead you can use the [FileOpenService](http://java.sun.com/javase/6/docs/jre/api/javaws/jnlp/javax/jnlp/FileOpenService.html) to read the file through a standard Swing file chooser (technically implementation dependent). Then it is just a matter of sending the file back as a browser would with a [multipart MIME HTTP POST](http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2).
How to do file uploads via a Java applet?
[ "", "java", "swing", "applet", "" ]
The majority of material I have found regarding DLR is related to IronPython. Can you parse and execute C# using DLR? If so is there over head that would prevent you from attempting this on a web server with about 30 users? More specifically I would like to script the configuration of my workflow objects when a user first initiates a workflow. Depending on conditions that change through out the year workflows may start at different steps, hence running configuration scripts seems like a good way to handle the variation.
Although Marc offered an alternative for me, I read this related [SO question](https://stackoverflow.com/questions/297624/vbx-language-hosting-via-dlr) and C# and VB are not supported as of yet.
It sounds like you're really talking about the C# "compiler as a service" (at the end of [this video](http://channel9.msdn.com/pdc2008/TL16/)), which will hopefully be in the 5.0 timescale for .NET (although Mono [has it now](http://www.go-mono.com/docs/index.aspx?link=N:Mono.CSharp)). For now, [CSharpCodeProvider](http://msdn.microsoft.com/en-us/library/microsoft.csharp.csharpcodeprovider.aspx) is the best we have (which works largely like "csc").
Is it possible to load and execute C# snippets using DLR?
[ "", "c#", "dynamic-language-runtime", "embedded-language", "" ]
I'm busy experimenting with [TiddlyWiki](http://tiddlywiki.com/) and trying to get it to run on my Nokia E51, which uses S60v3. The browser is [based on webkit](http://opensource.nokia.com/projects/S60browser/), which **should** mean that I'd be able to get it to work, but no luck so far. Does anyone have any experience with saving files locally on this platform?
I skimmed through the source of TiddlyWiki. For its file operations it is using the [jQuery.twFile plugin](http://jquery.tiddlywiki.org/twFile.html) which in turn uses a custom Java applet on Webkit-based browsers. The S60 browser does not support java applets so I'm afraid you're out of luck.
I may be wrong here but a quick look at the widget training course on forum Nokia makes it seem like file system access from JavaScript isn't available on S60. <http://www.forum.nokia.com/Tools_Docs_and_Code/Documentation/Web_Technologies/> It really look like you're supposed to retrieve persistent data from the network. I would hope the web browser cache allows you to query remote data several times while only transfering it once.
Saving a file with Javascript in S60v3 mobile browser
[ "", "javascript", "mobile", "symbian", "s60", "" ]
Would you consider it bad practice to store various user data in a database as serialized binary? Is it a good, bad or really ugly idea? I'm talking about pretty much arbitrary things, like the last splitter distance on a form, the last value in a search text box, prevously selected checkbox indexes, et cetera. Things that should be remembered that is not critical if it is forgotten. I kind of like it since I would then only need one table with for example four columns: userid, source, key and value. And if I create a nice wrapper class to save and load values to this table things could work pretty nicely. For example I wouldn't have to fix the database whenever a new kind of setting comes in to play. It would of course not work with searching and ordering and things like that, but that wouldn't be needed anyways since you would only access those key value pairs directly from their index (user id + source + key). The columns would also not be human readable, but again that wouldn't really be a problem. The data would be data that could be cleared out without much problems. Any feedback on this idea? Is it an awful one? Is it a good one? Have you done something similar?
Since you are not searching, it would not be a bad idea - it is a opaque container for miscelaneous user data, and as you said it doesn't contain any critical information. And you are correct, you don't need to change the database to support a new configuration of settings.
I use this all the time, because our objects are very customized per client / installation. This way I can add & remove properties without having to update the database. I need about 200-300 properties per row. I have found that this approach gives me good flexibility. I always include version number in my binary structure. So I know what data I can retrieve from it. On some sub-object I also include the typename, so I can store objects from an inheritance tree. (I hope you understand what I mean).
C#, SQL: Storing arbitrary user data in a database as serialized binary
[ "", "c#", "sql-server", "database-design", "settings", "" ]
If I write the following code: ``` session_start(); $_SESSION['user_id']='daniel'; ``` the variable stays fine as long as I'm on the page on which it was created, and the second I try to call `$_SESSION['user_id']` from another page, I don't get a response. Can anyone tell me what mistake I'm making?
You should be using `session_start()` on **every** page you want to use sessions on.
As long as: * You are doing [`session_start()`](https://www.php.net/function.session-start) on the other page. **Note:** you don't make this call once. You do it on every page that wants to access the session information; * The other page can see your cookie from this site (ie sufficiently similar domain); and * The other page is running on the same server. then it can see it. Construct a simple test case and verify this and then work out why what you're doing is different.
$_SESSION variables not transferring from page to page
[ "", "php", "session", "" ]
does anyone know how you edit/maintain regions in magento - specifically adding ones for the uk.
1. In the Magento admin console, go to System->Configuration 2. Click on the "Manage Stores" link (In the upper left hand corner there's a section named "Current Configuration Scope".) 3. From here you should see all the configured websites, stores, and store views in the Magento system. Explaining how all these related to one another is beyond the scope of any single StackOverflow article, but this [wiki article](http://www.magentocommerce.com/design_guide/articles/magento-design-terminologies4) has the basics and this [wiki article](http://www.magentocommerce.com/wiki/general/multiple-website-setup) may also be useful. 4. You'll need to setup either a seperate website or a seperate store or a seperate store view for your UK store, depending on your needs (sorry to be so vague) 5. Return to System->Configuration 6. Click on the Current Configuration Scope drop down You should now see a nested view of all your configured websites, stores and store views. Selecting "Default Config" will allow you to set config values for all stores. Selecting a specific website, store or store view from this menu will allow you to set config values for a specific website, store or store view. This will allow you to set specific config values for your UK store.
Regions are stored inside 'directory\_country\_region' and 'directory\_country\_region\_name' tables in database. Unfortunately there is no editor for them. You can inspect Mage\_Directory module and look at sql installation scripts.
changing / maintaining regions in magento
[ "", "php", "magento", "region", "" ]
Lets put it in parts. I got a socket receiving data OK and I got it in the `\x31\x31\x31` format. I know that I can get the same number, ripping the `\x` with something like ``` for i in data: print hex(ord(i)) ``` so I got `31` in each case. But if I want to add 1 to the data (so it shall be "`32 32 32`")to send it as response, how can I get it in `\x32\x32\x32` again?
The "\x31" is not a format but the text representation of the binary data. As you mention ord() will convert one byte of binary data into an int, so you can do maths on it. To convert it back to binary data in a string, you can use chr() if it's on just one integer. If it's many, you can use the %c formatting character of a string: ``` >>> "Return value: %c%c%c" % (5,6,7) 'Return value: \x05\x06\x07' ``` However, a better way is probably to use struct. ``` >>> import struct >>> foo, bar, kaka = struct.unpack("BBB", '\x06\x06\x06') >>> struct.pack("BBB", foo, bar+1, kaka+5) '\x06\x07\x0b' ``` You may even want to take a look at ctypes.
use the struct module unpack and get the 3 values in abc `(a, b, c) = struct.unpack(">BBB", your_string)` then `a, b, c = a+1, b+1, c+1` and pack into the response `response = struct.pack(">BBB", a, b, c)` see the struct module in python documentation for more details
Hex data from socket, process and response
[ "", "python", "sockets", "hex", "" ]
Why linq is trying to check second expression anyway? ``` .Where(t => String.IsNullOrEmpty(someNullString) || t.SomeProperty >= Convert.ToDecimal(someNullstring)) ``` What is usual workaround? **Update:** It is about LINQ to SQL, of course. It cannot translate to SQL.
Is the `.Where` being used on a `Table<>`? If so, then before any data can be grabbed, it must convert the LINQ to SQL and to do that it must convert the `string` into a `decimal`. It's not trying to actually perform the comparisons yet, it's trying to build the constructs necessary to retrieve data.
Do you have a variable **t** in any scope that may be evaluated? Did you try with parenthesis like this: ``` .Where(t => (String.IsNullOrEmpty(someNullString) || t.SomeProperty >= Convert.ToDecimal(someNullstring))) ``` ?
Why isn't this short circuit in lambda working?
[ "", "c#", "linq", "linq-to-sql", "" ]
I've a directory outside the webroot with images, css and javascripts. These files often change. I could write a script which locates the file, figures out the mime type and outputs it to the browser. *Or* i could locate the file, copy it to a webaccessable directory and redirect to that file using header location. When the file is requested again, there first will be a check if the file is modified, and again a redirect. What would be a better performance wise? Every request a readfile, or every request a timestamp check and redirect ( so 2 requests instead of one )
First rule of performance: benchmark, don't speculate. I'll promptly break that first rule and speculate that the readfile will be faster, because it eliminates a network round-trip. How much performance do you need? The very fastest way to do this would be to setup a separate static-content web server under a subdomain (e.g. <http://static.mysite.com/foo.jpg> ) on a completely different machine, and then let that web server there handle the often-changing image/css/javascript files.
Another suggestion: if you have control of the filesystem, you could perhaps create a [symbolic link](http://en.wikipedia.org/wiki/Symbolic_link) in the web-accessable directory to the image file? Either using exec() to invoke the 'ln' command or *maybe* the PHP [symlink()](https://www.php.net/manual/en/function.symlink.php) function might work.
Use php's readfile() or redirect to display a image file?
[ "", "php", "performance", "" ]
For example I have a filename like this - проба.xml and I am unable to open it from PHP script. If I setup php script to be in utf-8 than all the text in script is utf-8 thus when I pass this to file\_get\_contents: ``` $fname = "проба.xml"; file_get_contents($fname); ``` I get error that file does not exist. The reason for this is that in Windows (XP) all file names with non-latin characters are unicode (UTF-16). OK so I tried this: ``` $fname = "проба.xml"; $res = mb_convert_encoding($fname,'UTF-8','UTF-16'); file_get_contents($res); ``` But the error persists since file\_get\_contents can not accept unicode strings... Any suggestions?
These are conclusions so far: 1. PHP 5 can not open filename with unicode characters unless the source filename is unicode. 2. PHP 5 (at least on windows XP) is not able to process PHP source in unicode. Thus the conclusion this not doable in PHP 5.
# UPDATE (July 13 '17) Although the docs do not seem to mention it, PHP 7.0 and above finally supports Unicode filenames on Windows out of the box. PHP's Filesystem APIs accept and return filenames according to `default_charset`, which is `UTF-8` by default. Refer to bug fix here: <https://github.com/php/php-src/commit/3d3f11ede4cc7c83d64cc5edaae7c29ce9c6986f> --- # UPDATE (Jan 29 '15) If you have access to the PHP extensions directory, you can try installing `php-wfio.dll` at <https://github.com/kenjiuno/php-wfio>, and refer to files via the `wfio://` protocol. ``` file_get_contents("wfio://你好.xml"); ``` --- # Original Answer PHP on Windows uses the Legacy "ANSI APIs" exclusively for local file access, which means PHP uses the *System Locale* instead of Unicode. To access files whose filenames contain Unicode, you must convert the filename to the specified encoding for the current System Locale. ~~If the filename contains characters that are not representable in the specified encoding, you're out of luck~~ **(Update: See section above for a solution)**. `scandir` will return gibberish for these files and passing the string back in `fopen` and equivalents will fail. To find the right encoding to use, you can get the system locale by calling `<?=setlocale(LC_TYPE,0)?>`, and looking up the *Code Page Identifier* (the number after the `.`) at the MSDN Article <https://msdn.microsoft.com/en-us/library/dd317756(VS.85).aspx>. For example, if the function returns `Chinese (Traditional)_HKG.950`, this means that the 950 codepage is in use and the filename should be converted to the big-5 encoding. In that case, your code will have to be as follows, if your file is saved in UTF-8 (preferrably without BOM): ``` $fname = iconv('UTF-8','big-5',"你好.xml"); file_get_contents($fname); ``` or as follows if you directly save the file as Big-5: ``` $fname = "你好.xml"; file_get_contents($fname); ```
How to open file in PHP that has unicode characters in its name?
[ "", "php", "string", "unicode", "" ]
I'm working through some tutorials and examples of java.util.concurrent package. Usually example authors put a placeholder marked with a comment 'long running task'. Since these examples are about concurrent programming I'm not keen of using Thread.sleep(long), surrounded by try-catch blocks. What do you use in these circumstances? To open an url, do some complicated float math, i/o... Optimally these long running tasks do not have any side effects. These methods can be seen as Loren Ipsums on the timescale. --- I'll add here concrete implementations: ``` import java.math.BigInteger; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.SecureRandom; import java.util.Random; public class LongRunningTasks { public void triggerKeyGeneration(int iterations) { try { long start = System.currentTimeMillis(); for (int i = 0; i < iterations; i++) { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); keyGen.initialize(1024, random); keyGen.generateKeyPair(); } System.out.println("triggerKeyGeneration: " + (System.currentTimeMillis() - start)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } } private static final int SCALE = 10000; private static final int ARRINIT = 2000; /** * http://www.codecodex.com/wiki/index.php?title=Digits_of_pi_calculation#Java * * @param digits - returns good results up to 12500 digits * @return */ public String piDigits(int digits){ StringBuffer pi = new StringBuffer(); int[] arr = new int[digits + 1]; int carry = 0; for (int i = 0; i <= digits; ++i) arr[i] = ARRINIT; for (int i = digits; i > 0; i-= 14) { int sum = 0; for (int j = i; j > 0; --j) { sum = sum * j + SCALE * arr[j]; arr[j] = sum % (j * 2 - 1); sum /= j * 2 - 1; } pi.append(String.format("%04d", carry + sum / SCALE)); carry = sum % SCALE; } return pi.toString(); } private static final Random rand = new Random(); private static final BigInteger veryBig = new BigInteger(1200, rand); public BigInteger nextProbablePrime() { return veryBig.nextProbablePrime(); } } ```
I've once used a public-private key generator to do something similar. This is a CPU intensive task. Doing it hundreds or thousands of times should give you a considerable delay.
``` BigInteger veryBig = new BigInteger(10000, new Random()); veryBig.nextProbablePrime(); ```
Long running methods from Java SDK for testing purposes
[ "", "java", "algorithm", "concurrency", "" ]
I have a table in Oracle containing two columns that I'd like to query for records containing a unique combination of values, regardless of the order of those values. For example, if I have the following table: ``` create table RELATIONSHIPS ( PERSON_1 number not null, PERSON_2 number not null, RELATIONSHIP number not null, constraint PK_RELATIONSHIPS primary key (PERSON_1, PERSON_2) ); ``` I'd like to query for all unique relationships. So if I have a record PERSON\_1 = John and PERSON\_2 = Jill, I don't want to see another record where PERSON\_1 = Jill and PERSON\_2 = John. Is there an easy way to do this?
There's some uncertainty as to whether you want to *prevent* duplicates from being inserted into the database. You might just want to fetch unique pairs, while preserving the duplicates. So here's an alternative solution for the latter case, querying unique pairs even if duplicates exist: ``` SELECT r1.* FROM Relationships r1 LEFT OUTER JOIN Relationships r2 ON (r1.person_1 = r2.person_2 AND r1.person_2 = r2.person_1) WHERE r1.person_1 < r1.person_2 OR r2.person_1 IS NULL; ``` So if there is a matching row with the id's reversed, there's a rule for which one the query should prefer (the one with id's in numerical order). If there is no matching row, then r2 will be NULL (this is the way outer join works), so just use whatever is found in r1 in that case. No need to use `GROUP BY` or `DISTINCT`, because there can only be zero or one matching rows. Trying this in MySQL, I get the following optimization plan: ``` +----+-------------+-------+--------+---------------+---------+---------+-----------------------------------+------+--------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+--------+---------------+---------+---------+-----------------------------------+------+--------------------------+ | 1 | SIMPLE | r1 | ALL | NULL | NULL | NULL | NULL | 2 | | | 1 | SIMPLE | r2 | eq_ref | PRIMARY | PRIMARY | 8 | test.r1.person_2,test.r1.person_1 | 1 | Using where; Using index | +----+-------------+-------+--------+---------------+---------+---------+-----------------------------------+------+--------------------------+ ``` This seems to be a reasonably good use of indexes.
Is the relationship always there in both directions? i.e. if John and Jill are related, then is there *always* a {John,Jill} and {Jill,John} ? If so, just limit to those where Person\_1 < Person\_2 and take the distinct set.
Filter SQL query by a unique set of column values, regardless of their order
[ "", "sql", "oracle", "" ]
I am wondering about how to approach inheritance with View Models in the MVVM pattern. In my application I have a Data Model that resembles the following: ``` class CustomObject { public string Title { get; set; } } class CustomItem : CustomObject { public string Description { get; set; } } class CustomProduct : CustomItem { public double Price { get; set; } } ``` In my application I have a ViewModelBase class and then was going to have the following View Models: * CustomObjectViewModel * CustomItemViewModel * CustomProductViewModel A rough implementation of the CustomObjectViewModel would resemble the following: ``` class CustomObjectViewModel : ViewModelBase { private readonly CustomObject _customObject; public CustomObjectViewModel( CustomObject customObject ) { _customObject = customObject; } public string Title { // implementation excluded for brevity } } ``` It seems logical to me that my View Models would extend themselves in the same manner as my Model did (CustomItemViewModel extends CustomObjectViewModel and so on). However, I have noticed that as I go down the inheritance tree I'll be adding additional references to the same object. This seems rather excessive to me and was wondering how to approach this problem and if it were possible to make it much cleaner.
Generally I would recommend you **not to have inheritance between different ViewModel classes**, but instead having them inherit directly from a common abstract base class. This is to avoid introducing unnecessary complexity by **polluting the ViewModel classes' interfaces** with members that come from higher up in the hierarchy, but **are not fully cohesive** to the class's main purpose. The coupling that comes with inheritance will also likely make it hard to change a ViewModel class without affecting any of its derived classes. If your ViewModel classes always will reference a single Model object, you could use generics to encapsulate this rule into the base class: ``` public abstract class ViewModelBase<TModel> { private readonly TModel _dataObject; public CustomObjectViewModel(TModel dataObject) { _dataObject = dataObject; } protected TModel DataObject { get; } } public class CustomObjectViewModel : ViewModelBase<CustomObject> { public string Title { // implementation excluded for brevity } } public class CustomItemViewModel : ViewModelBase<CustomItem> { public string Title { // implementation excluded for brevity } public string Description { // implementation excluded for brevity } } ```
Related to the comment above of Enrico. ViewModels should not be tightly coupled with views, it should be the other way around. Views should be loosely coupled to ViewModels. A ViewModel should not know about a view, this allows you to unit test a ViewModel easily.All interactions between Views with the ViewModel should be implemented via properties in the ViewModel(ICommand properties for actions and other properties for databinding). The one thing that is true is that the ViewModel is tightly coupled with the Model, so the use of generics above allows alot of extensibility. It is the pattern that I would recommend. By providing a ViewModel class that basically just exposes Properties it should allow you to plop that into any kind of presentation framework and leverage all the code you've used previously. In other words, if properly implemented you could drop your ViewModels assembly into a ASP.NET MVC app and tie the view to the properties and have no code change. A good article on MVVM basics is : [this one.](http://msdn.microsoft.com/en-us/magazine/dd419663.aspx) I really think that MVVM is the best thing out there for UI development. Obviously we can't all use it because it requires building an app from the ground up using the MVVM approach, but when you're building a new app that is not an issue. The one gripe I have with ICommand is that it is in the PresentationCore Assembly which is basically for WPF. If Microsoft wanted loose coupling it should be in another assembly altogether.
MVVM Inheritance With View Models
[ "", "c#", "wpf", "design-patterns", "mvvm", "" ]
What is the difference between aligned and unaligned memory access? I work on an TMS320C64x DSP, and I want to use the intrinsic functions (C functions for assembly instructions) and it has ``` ushort & _amem2(void *ptr); ushort & _mem2(void *ptr); ``` where `_amem2` does an aligned access of 2 bytes and `_mem2` does unaligned access. When should I use which?
An aligned memory access means that the pointer (as an integer) is a multiple of a type-specific value called the alignment. The alignment is the natural address multiple where the type must be, or should be stored (e.g. for performance reasons) on a CPU. For example, a CPU might require that all two-byte loads or stores are done through addresses that are multiples of two. For small primitive types (under 4 bytes), the alignment is almost always the size of the type. For structs, the alignment is usually the maximum alignment of any member. The C compiler always puts variables that you declare at addresses which satisfy the "correct" alignment. So if ptr points to e.g. a uint16\_t variable, it will be aligned and you can use \_amem2. You need to use \_mem2 only if you are accessing e.g. a packed byte array received via I/O, or bytes in the middle of a string.
Many computer architectures store memory in "words" of several bytes each. For example, the Intel 32-bit architecture stores words of 32 bits, each of 4 bytes. Memory is addressed at the single byte level, however; therefore an address can be "aligned", meaning it starts at a word boundary, or "unaligned", meaning it doesn't. On certain architectures certain memory operations may be slower or even completely not allowed on unaligned addresses. So, if you know your addresses are aligned on the right addresses, you can use \_amem2(), for speed. Otherwise, you should use \_mem2().
Aligned and unaligned memory accesses?
[ "", "c++", "c", "memory", "memory-alignment", "omap", "" ]
I have a C# program that uses System.Data.OracleClient to access an oracle database. The code uses OracleCommand, OracleDataReader objects. And it uses the TNS names to refer to specific oracle servers (as defined in the tnsnames.ora file). It runs fine on my computer. And then I copied the binary to another computer, and upon running it encounters the error: TNS:could not resolve the connect identifier specified. The other computer has the same version of oracle client installed, and the identical copy of tnsnames.ora dropped in the oracle network/admin folder. And the other computer also has SQLDeveloper installed, and I am able to connect to the oracle servers by using those TNS names from inside its SQLDeveloper. Why then is the c# program complaining about not able to resolve TNS identifier? The connection string I use (as hardcoded into my c# program) is ; "Data Source=TNS Name; User ID=user; Password=pass;" Thanks
Open a command window, type `tnsping yourdbname` and hit enter, you should get back a bunch of info, but what you want to look for is > Used parameter files: > > C:\Oracle\product\10.1.0\Client\_1\network\admin\sqlnet.ora Or something similar, this is the "Default" Oracle client on the system, make sure that this is the same path that you have the tnsnames.ora in (in my case we use sqlnet.ora) Sometimes multiple Oracle product installs make multiple potential ORA\_HOMEs, you can at least confirm the "active" client, so that way you are certain the files are in the right spot. Also, can you connect to the db using SQLPlus?
Is it failing to locate or load the tnsnames.ora file? Try running ProcessMonitor (<http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx>) and then running your c# program. You can see if it fails to locate the .ora file.
Accessing Oracle Database from C#
[ "", "c#", "database", "oracle", "" ]
I have a problem with a javascript set of functions that I made. This functions walk the entire Html page and then add the onclick event to every anchor it finds. It do some check on the anchor href and redirect to it (using window.location.href) My problem is that the cronology don't work properly this way, and the :visited selector don't work anymore. How I can preserve the chronology and let the :visited selector work properly? Regards
There's no need to set `location.href` manually: The link will be followed properly if you don't prevent it explicitly via returning `false` or calling `event.preventDefault()` (`event.returnValue = false` in IE) in the `onclick` handler.
Are you tracking their visits for that session? If so, what about a *server side* solution instead of using Javascript. Each time you serve up a page request, you log that Url, Page Title, etc, into their session - That way you can keep track of where they have been. In that regard, the :visited tags will still work and you'll have a somewhat more reliable source for page history.
Lost chronology using window.location.href
[ "", "javascript", "css", "" ]
Consider this snippet: ``` globalVar = 25 def myfunc(paramVar): localVar = 30 print "Vars: {globalVar}, {paramVar}, {localVar}!".format(**VARS_IN_SCOPE) myfunc(123) ``` Where `VARS_IN_SCOPE` is the dict I'm after that would contain `globalVar`, `paramVar` and `localVar`, among other things. I'd like to basically be able to reference all the variables that are currently in scope inside the string. Hence the expected output would be: `Vars: 25, 123, 30` I can achieve this by passing `**dict(globals().items() + locals().items())` to `format()`. Is this always correct or are there some corner cases that this expression would handle incorrectly? *Rewritten to clarify the question.*
Best way to merge two dicts as you're doing (with locals overriding globals) is `dict(globals(), **locals())`. What the approach of merging globals and locals is missing is (a) builtins (I imagine that's deliberate, i.e. you don't think of builtins as "variables"... but, they COULD be, if you so choose!-), and (b) if you're in a *nested* function, any variables that are local to enclosing functions (no really good way to get a dict with all of *those*, plus -- only those explicitly accessed in the nested function, i.e. "free variables" thereof, survive as cells in a closure, anyway). I imagine these issues are no big deal for your intended use, but you did mention "corner cases";-). If you need to cover them, there are ways to get the built-ins (that's easy) and (not so easy) all the cells (variables from enclosing functions that you explicitly mention in the nested function -- `thefunction.func_code.co_freevars` to get the names, `thefunction.func_closure` to get the cells, `cell_contents` on each cell to get its value). (But, remember, those will only be variables from enclosing functions that are *explicitly accessed* in your nested function's code!).
Does this do what you intended? ``` d = dict(globals()) d.update(locals()) ``` If I read the documentation correctly, you create a copy of the `globals()` dict, then you overwrite any duplicates *and* insert new entries from the `locals()` dict (since the `locals()` should have preference within your scope, anyway). --- I haven't had *any* luck in getting a proper function to return the full dictionary of variables in scope of the **calling** function. Here's the code (I only used pprint to format the output nicely for SO): ``` from pprint import * def allvars_bad(): fake_temp_var = 1 d = dict(globals()) d.update(locals()) return d def foo_bad(): x = 5 return allvars_bad() def foo_good(): x = 5 fake_temp_var = "good" d = dict(globals()) d.update(locals()) return d pprint (foo_bad(), width=50) pprint (foo_good(), width=50) ``` and the output: ``` {'PrettyPrinter': <class pprint.PrettyPrinter at 0xb7d316ec>, '__builtins__': <module '__builtin__' (built-in)>, '__doc__': None, '__file__': 'temp.py', '__name__': '__main__', '__package__': None, 'allvars_bad': <function allvars_bad at 0xb7d32b1c>, 'd': <Recursion on dict with id=3084093748>, 'fake_temp_var': 1, 'foo_bad': <function foo_bad at 0xb7d329cc>, 'foo_good': <function foo_good at 0xb7d32f0c>, 'isreadable': <function isreadable at 0xb7d32c34>, 'isrecursive': <function isrecursive at 0xb7d32c6c>, 'pformat': <function pformat at 0xb7d32bc4>, 'pprint': <function pprint at 0xb7d32b8c>, 'saferepr': <function saferepr at 0xb7d32bfc>} {'PrettyPrinter': <class pprint.PrettyPrinter at 0xb7d316ec>, '__builtins__': <module '__builtin__' (built-in)>, '__doc__': None, '__file__': 'temp.py', '__name__': '__main__', '__package__': None, 'allvars_bad': <function allvars_bad at 0xb7d32b1c>, 'd': <Recursion on dict with id=3084093884>, 'fake_temp_var': 'good', 'foo_bad': <function foo_bad at 0xb7d329cc>, 'foo_good': <function foo_good at 0xb7d32f0c>, 'isreadable': <function isreadable at 0xb7d32c34>, 'isrecursive': <function isrecursive at 0xb7d32c6c>, 'pformat': <function pformat at 0xb7d32bc4>, 'pprint': <function pprint at 0xb7d32b8c>, 'saferepr': <function saferepr at 0xb7d32bfc>, 'x': 5} ``` Note that in the second output, we have overwritten `fake_temp_var`, and x is present; the first output only included the local vars within the scope of `allvars_bad`. So if you want to access the full variable scope, you cannot put locals() inside another function. ---
Get a dict of all variables currently in scope and their values
[ "", "python", "" ]
I'm trying to abort a socket connection such that the client at the other end will get a "WSAECONNABORTED (10053) Software caused connection abort." error message when it polls the connection. Close() and Shutdown() will disconnect gracefully. I don't want a graceful disconnection. I want to do an Abort so that the client senses something really went wrong. Thanks, EDIT: I'm coding a Server and I want to abort sockets to connecting clients
I've managed to simulate this situation: To do a normal graceful disconnection: you do: ``` socket.Shutdown(SocketShutdown.Both); socket.Close(); ``` However, to do an Abort, you do: ``` socket.Shutdown(SocketShutdown.Send); socket.Close(); ``` I think the difference is that the client will not receive any ACK packets and thinks the computer reset or something.
The underlying details, including when it is actually appropriate to forcibly abort a connection are described in great detail here (<https://stackoverflow.com/a/13088864/1280848>). The C# way of doing this is: ``` socket.LingerState = new LingerOption(true, 0); socket.Close(); ``` That is, use `SO_LINGER` with `TIME_WAIT = 0`
How to Abort a Socket in C#
[ "", "c#", ".net", "sockets", "" ]
My program uses Swing JPanel, JList, JScrollPane ... It runs fine, but generated the following error message, and yet in the message it didn't say which line of my program caused the error, what can I do ? ========================================================================= ``` Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 3 at javax.swing.plaf.basic.BasicListUI.updateLayoutState(BasicListUI.java:1356) at javax.swing.plaf.basic.BasicListUI.maybeUpdateLayoutState(BasicListUI.java:1299) at javax.swing.plaf.basic.BasicListUI.getPreferredSize(BasicListUI.java:566) at javax.swing.JComponent.getPreferredSize(JComponent.java:1632) at javax.swing.ScrollPaneLayout.layoutContainer(ScrollPaneLayout.java:769) at java.awt.Container.layout(Container.java:1398) at java.awt.Container.doLayout(Container.java:1387) at java.awt.Container.validateTree(Container.java:1485) at java.awt.Container.validate(Container.java:1457) at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:670) at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:127) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209) at java.awt.EventQueue.dispatchEvent(EventQueue.java:597) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) ``` ===================================================================================== I do have various .validate() and .repaint() statements in my program to make sure it runs correctly. Because my program looks fine, does that mean I can ignore the error ? Anything I can do to avoid the error message ? ===================================================================================== Here is more details: <1> Java version jdk1.6.0\_11 <2> How I init the list: ``` for (int Selector_Id=0;Selector_Id<6;Selector_Id++) { Stock_Symbol_Data[Selector_Id]=new DefaultListModel(); Stock_Symbol_List[Selector_Id]=new JList(Stock_Symbol_Data[Selector_Id]); Stock_Symbol_ScrollPane[Selector_Id]=new JScrollPane(Stock_Symbol_List[Selector_Id]); } ... Stock_Symbol_Data[A_Selector_Id].clear(); if (Selected_Symbols_Vector.size()>0) for (int i=0;i<Selected_Symbols_Vector.size();i++) Stock_Symbol_Data[A_Selector_Id].addElement(Selected_Symbols_Vector.elementAt(i)); ``` Yishai is right, since my program needs to init a very long list, which requires about a minute. I can't wait to see the UI before the init is finished, so I put it in a "SwingWorker" class and let it do the init after the app UI window opens; that way I can see the progress from within the UI rather then wait for the first window to open. It seems to me it's the PC's slowness that's messing up the UI update process; if I later on move to a faster machine, Swing should straighten this out, or am I right about this? I tried to use the "(wrap the change in a Runnable and call SwingUtilities.invokeLater)" approach, but it didn't work as I expected. It waits till all the list is filled in, then opens the first window; that means I have to look at empty screen for one minute before the first UI shows up. With SwingWorker, it now shows the error message randomly--sometimes here, sometimes there, other times not at all. My SwingWorker looks like this : ``` class Update_Selection_Worker extends SwingWorker<Integer,Integer> // Look into SwingWorkerDemo in Fit for details { int Selector_Id; boolean Update_Only_This_Selector; Stock_Image_Scanner Stock_image_scanner; public Update_Selection_Worker(int Selector_Id,boolean Update_Only_This_Selector,Stock_Image_Scanner Stock_image_scanner) { this.Selector_Id=Selector_Id; this.Update_Only_This_Selector=Update_Only_This_Selector; this.Stock_image_scanner=Stock_image_scanner; } @Override protected Integer doInBackground() throws Exception { // Out(" In Update_Selection_Worker Selector_Id="+Selector_Id); if (Update_Only_This_Selector) // Only need to update from Rules_Panel_Id, eariler ones haven't changed { Stock_image_scanner.Update_Selector_List(Selector_Id); Thread.sleep(5); publish(Selector_Id); } else for (int i=Selector_Id;i<Stock_image_scanner.Rules_Panel_Count;i++) { Stock_image_scanner.Update_Selector_List(i); Thread.sleep(5); publish(i); } return 1; } @Override protected void process(java.util.List<Integer> chunks) // As the worker thread executes, it can publish results of V type. Override the process method to work with intermediate results. { for (final int i : chunks) { SwingUtilities.invokeLater(new Runnable() { public void run() { Stock_image_scanner.Selector_Total_Label[i].setText(Stock_image_scanner.Stock_Symbol_Data[i].getSize()+""); Stock_image_scanner.Stock_Symbol_List[i].revalidate(); Stock_image_scanner.Stock_Symbol_List[i].repaint(); Stock_image_scanner.Stock_Symbol_ScrollPane[i].revalidate(); Stock_image_scanner.Stock_Symbol_ScrollPane[i].repaint(); Stock_image_scanner.Selector_Panel[i].revalidate(); Stock_image_scanner.Selector_Panel[i].repaint(); } }); } } @Override protected void done() { } public static void out(String message) { System.out.print(message); } public static void Out(String message) { System.out.println(message); } } ```
I guess too the exception is because the concurrent modification of some swing object array. SwingWorker has the option for 'in progress events'. You need to override `process(List<V> chunks)` protected method and use the `void publish(V... chunks)` method to send status update to the UI. In your processing case this means submit your partial results periodically so the user doesn't get bored.
I think Yishai is right. I had a similar behaviour and wrapping it into ...EventQueue.invokeLater... solved my problem. ``` java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { listModel.addElement(book); jListBooks = new JList(listModel); jListBooks.setCellRenderer(new RobotBookListRenderer()); jScrollPane1.setViewportView(jListBooks); jListBooks.updateUI(); } }); ```
Java Swing BasicUI update error, what can I do?
[ "", "java", "multithreading", "swing", "swingworker", "" ]
Is there any overhead using partial classes in case of memory, performance etc? If we create a partial class can we **identify whether the class was partial or not using reflector**??
No. They are compiled to the same IL as if they weren't partial. It's a *purely* compile-time thing - the CLR doesn't even know that they were ever partial. Note that with *[partial methods](http://msdn.microsoft.com/en-us/library/vstudio/6b0scde8.aspx)* introduced into C# 3, the method doesn't even get emitted in the IL unless it's implemented in one of the files. Both the calls and the declaration get stripped out by the compiler. It's possible that it'll slow down the compiler an imperceptible fraction of a millisecond, of course :)
No, all class files will get consolidated at compile time. Here's the [msdn article](http://msdn.microsoft.com/en-us/library/wa80x488.aspx) on partial types. > Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.
Using partial classes
[ "", "c#", "partial-classes", "" ]
I feed a textbox a string value showing me a balance that need to be formatted like this: ``` ###,###,###,##0.00 ``` I could use the value.ToString("c"), but this would put the currency sign in front of it. Any idea how I would manipulate the string before feeding the textbox to achieve the above formatting? I tried this, without success: ``` String.Format("###,###,###,##0.00", currentBalance); ``` Many Thanks,
``` string forDisplay = currentBalance.ToString("N2"); ```
If the currency formatting gives you exactly what you want, clone a `NumberFormatInfo` with and set the `CurrencySymbol` property to "". You should check that it handles negative numbers in the way that you want as well, of course. For example: ``` using System; using System.Globalization; class Test { static void Main() { NumberFormatInfo nfi = CultureInfo.CurrentCulture.NumberFormat; nfi = (NumberFormatInfo) nfi.Clone(); Console.WriteLine(string.Format(nfi, "{0:c}", 123.45m)); nfi.CurrencySymbol = ""; Console.WriteLine(string.Format(nfi, "{0:c}", 123.45m)); } } ``` The other option is to use a custom numeric format string of course - it depends whether you really want to mirror exactly how a currency would look, just without the symbol, or control the exact positioning of digits.
Format a double value like currency but without the currency sign (C#)
[ "", "c#", "string", "format", "currency", "" ]
Going through Javascript documentation, I found the following two functions on a Javascript object looks interesting: [`.watch`](https://developer.mozilla.org/en-US/docs/Archive/Web/JavaScript/Object.watch) - Watches for a property to be assigned a value and runs a function when that occurs. `.unwatch` - Removes a watchpoint set with the watch method. --- > **UPDATE**: **Deprecation warning** > Do not use `watch()` and `unwatch()`! These two > methods were implemented only in *Firefox* prior to version `58`, they're > deprecated and removed in *Firefox* `58+` --- Sample usage: ``` o = { p: 1 }; o.watch("p", function (id,oldval,newval) { console.log("o." + id + " changed from " + oldval + " to " + newval) return newval; }); ``` Whenever we change the property value of "p", this function gets triggered. ``` o.p = 2; //logs: "o.p changed from 1 to 2" ``` I am working on Javascript for the past few years and never used these functions. Can someone please throw some good use cases where these functions will come in handy?
What watch is really designed for is validation of property values. For example you could validate that something is an integer: ``` obj.watch('count', function(id, oldval, newval) { var val = parseInt(newval, 10); if(isNaN(val)) return oldval; return val; }); ``` You could use it to validate string length: ``` obj.watch('name', function(id, oldval, newval) { return newval.substr(0, 20); }); ``` **However, these are only available in the latest versions of the SpiderMonkey javascript engine.** Great if you are using Jaxer or embedding the SpiderMonkey engine, but not really available in your browser yet (unless you are using FF3).
It's now 2018 and the answers to this question are a bit outdated: * [Object.watch](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch) and [Object.observe](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe) are both deprecated and should not be used. * [onPropertyChange](https://msdn.microsoft.com/en-us/ie/ms536956(v=vs.94)) is a DOM element event handler that only works in some versions of IE. * [Object.defineProperty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty) allows you to make an object property immutable, which would allow you to detect attempted changes, but it would also block any changes. * [Defining setters and getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters) works, but it requires a lot of setup code and it does not work well when you need to delete or create new properties. Today, **you can now use the [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) object** to monitor (and intercept) changes made to an object. It is purpose built for what the OP is trying to do. Here's a basic example: ``` var targetObj = {}; var targetProxy = new Proxy(targetObj, { set: function (target, key, value) { console.log(`${key} set to ${value}`); target[key] = value; return true; } }); targetProxy.hello_world = "test"; // console: 'hello_world set to test' ``` The only drawbacks of the `Proxy` object are: 1. The `Proxy` object is not available in older browsers (such as IE11) and the [polyfill](https://github.com/GoogleChrome/proxy-polyfill) cannot fully replicate `Proxy` functionality. 2. Proxy objects do not always behave as expected with special objects (e.g., `Date`) -- the `Proxy` object is best paired with plain Objects or Arrays. If you need to observe changes made to a **nested object**, then you need to use a specialized library such as **[Observable Slim](https://github.com/ElliotNB/observable-slim)** (which I authored). It works like this: ``` var test = {testing:{}}; var p = ObservableSlim.create(test, true, function(changes) { console.log(JSON.stringify(changes)); }); p.testing.blah = 42; // console: [{"type":"add","target":{"blah":42},"property":"blah","newValue":42,"currentPath":"testing.blah",jsonPointer:"/testing/blah","proxy":{"blah":42}}] ```
Listener for property value changes in a Javascript object
[ "", "javascript", "browser", "dom-events", "" ]
I've come across a switch statement in the codebase I'm working on and I'm trying to figure out how to replace it with something better since [switch statements are considered a code smell](http://c2.com/cgi/wiki?SwitchStatementsSmell). However, having read through [several](https://stackoverflow.com/questions/126409/ways-to-eliminate-switch-in-code) posts on stackoverflow about [replacing](https://stackoverflow.com/questions/374239/why-doesnt-python-have-a-switch-statement#374290) [switch](https://stackoverflow.com/questions/561401/refactor-my-c-code-switch-statement) [statements](https://stackoverflow.com/questions/338206/switch-statement-with-strings-in-java) I can't seem to think of an effective way to replace this particular switch statement. Its left me wondering if this particular switch statement is ok and if there are particular circumstances where switch statements are considered appropriate. In my case the code (slightly obfuscated naturally) that I'm struggling with is like this: ``` private MyType DoSomething(IDataRecord reader) { var p = new MyType { Id = (int)reader[idIndex], Name = (string)reader[nameIndex] } switch ((string) reader[discountTypeIndex]) { case "A": p.DiscountType = DiscountType.Discountable; break; case "B": p.DiscountType = DiscountType.Loss; break; case "O": p.DiscountType = DiscountType.Other; break; } return p; } ``` Can anyone suggest a way to eliminate this switch? Or is this an appropriate use of a switch? And if it is, are there other appropriate uses for switch statements? I'd really like to know where they are appropriate so I don't waste too much time trying to eliminate every switch statement I come across just because they are considered a smell in some circumstances. **Update:** At the suggestion of [Michael](https://stackoverflow.com/questions/1071856/when-should-one-try-to-eliminate-a-switch-statement/1071879#1071879) I did a bit of searching for duplication of this logic and discovered that someone had created logic in another class that effectively made the whole switch statement redundant. So in the context of this particular bit of code the switch statement was unnecessary. However, my question is more about the appropriateness of switch statements in code and whether we should always try to replace them whenever they are found so in this case I'm inclined to accept the answer that this switch statement is appropriate.
This is an appropriate use for a switch statment, as it makes the choices readable, and easy to add or subtract one. [See this link.](https://stackoverflow.com/questions/449273/why-the-switch-statement-and-not-if-else)
Switch statements (especially long ones) are considered bad, not because they are switch statements, but because their presence suggests a need to refactor. The problem with switch statements is they create a bifurcation in your code (just like an if statement does). Each branch must be tested individually, and each branch within each branch and... well, you get the idea. That said, the following article has some good practices on using switch statements: <http://elegantcode.com/2009/01/10/refactoring-a-switch-statement/> In the case of your code, the article in the above link suggests that, if you're performing this type of conversion from one enumeration to another, you should put your switch in its own method, and use return statements instead of the break statements. I've done this before, and the code looks much cleaner: ``` private DiscountType GetDiscountType(string discount) { switch (discount) { case "A": return DiscountType.Discountable; case "B": return DiscountType.Loss; case "O": return DiscountType.Other; } } ```
When should one try to eliminate a switch statement?
[ "", "c#", "refactoring", "switch-statement", "" ]
Consider the following classes in Java ``` class A { protected void methodA() { System.out.println("methodA() in A"); } } class B extends A { protected void methodA() // overrides methodA() { System.out.println("methodA() in B"); } protected void methodB() { } } public class C extends B // needs the functionality of methodB() { public void methodC() { methodA(); // prints "methodA() in B" } } ``` How do I call the methodA() in a from methodC() in class C? Is that possible?
It's not possible. See <http://forums.java.net/jive/thread.jspa?messageID=5194&tstart=0> and <http://michaelscharf.blogspot.com/2006/07/why-is-supersuper-illegal.html>
You have a few options. If the source code for class B is available, then modify class B. If you don't have the source code, consider injecting code into class B's methodA(). [AspectJ](http://www.eclipse.org/aspectj/doc/next/progguide/starting-aspectj.html) can insert code into an existing Java binary. **Change Class B** ``` package com.wms.test; public class A { public A() { } protected void methodA() { System.out.println( "A::methodA" ); } } package com.wms.test; public class B extends A { public B() { } protected void methodA() { if( superA() ) { super.methodA(); } else { System.out.println( "B::methodA" ); } } protected void methodB() { System.out.println( "B::methodB" ); } protected boolean superA() { return false; } } package com.wms.test; public class C extends B { public C() { } protected void methodC() { methodA(); } protected boolean superA() { return true; } public static void main( String args[] ) { C c = new C(); c.methodC(); } } ``` Then: ``` $ javac com/wms/test/*.java $ java com.wms.test.C A::methodA ``` The following does not work: ``` protected void methodC() { ((A)this).methodA(); } ```
Calling the overridden protected method of a class higher up in the hierarchy
[ "", "oop", "java", "" ]
I have been reading up to try to make sense of memory leaks in browsers, esp. IE. I understand that the leaks are caused by a mismatch in garbage collection algorithms between the Javascript engine and the DOM object tree, and will persist past. What I don't understand is why (according to some statements in the articles I'm reading) the memory is not reclaimed after the page is unloaded by the browser. Navigating away from a webpage should put all the DOM and javascript objects out of scope at that point, shouldn't it?
Here's the problem. IE has a separate garbage collector for the DOM and for javascript. They can't detect circular references between the two. What we used to was to clean up all event handlers from all nodes at page unload. This could, however, halt the browser while unloading. This only addressed the case where the circular reference was caused by event handlers. It could also be caused by adding direct references from DOM nodes to js objects which had a reference to the DOM node itself. Another good thing to remember is that if you are deleting nodes, it's a good idea to remove the handlers yourself first. Ext-js has a Ext.destroy method that does just that (if you've set the handlers using ext). Example ``` // Leaky code to wrap HTML elements that allows you to find the custom js object by adding //a reference as an "expando" property function El(node) { this.dom = node; node.el = this; } ``` Then Microsoft hacked IE so it removed all event handlers and expando properties when unloading internally, therefore it's much faster than doing it with js. This fix seemed to fix our memory problems, but not all problems as there are people still having the problem. [MS's description of the problem](http://msdn.microsoft.com/en-us/library/bb250448(VS.85).aspx) [MS releases patch that "fixes" memory leaks:](http://support.microsoft.com/kb/929874/) [Blog about fixed memory leaks](http://novemberborn.net/javascript/memory-leaks-gone) [IE still has some problems](http://ajaxian.com/archives/ies-memory-leak-fix-greatly-exaggerated) At our company, we use ext-js. By always setting event handlers using ext-js, which has a an internal clean up routine, we have not experienced memory leaks. In reality, memory usage grows but stops at about 250Mb for a machine with 4Gb of RAM. We don't think that's too bad since we load about 2Mb(uncompressed) of js files and all the elements on the page are dynamic. There's a lot to be said about this and we've researched this extensively where I work. Feel free to ask a more specific question. I may be able to help you.
The best thing I ever read about [Javascript memory leaks](http://javascript.crockford.com/memory/leak.html) was written by Doulgas Crockford. To answer your question, yes, the browser absolutely *should* unload all the objects (and most importantly, event handlers) at the appropriate time. If it did, it wouldnt have leaks :)
Javascript memory leaks after unloading a web page
[ "", "javascript", "internet-explorer", "dom", "memory", "memory-leaks", "" ]
Is there a way to say "this method returns `this`" using Generics? Of course, I want to override this method in subclasses, so the declaration should work well with `@Override`. Here is an example: ``` class Base { public Base copyTo (Base dest) { ... copy all fields to dest ... return this; } } class X extends Base { @Override public X copyTo (X dest) { super.copyTo (dest); ... copy all fields to dest ... return this; } } ``` `public <T extends Base> T copyTo (Base dest)` doesn't work at all: I get "Type mismatch: Can't convert from Base to T". If I force it with a cast, the override fails.
No, there's no way of expressing that. Just declare the method to return the type of the class. Java has covariant return types, so you can override a method to return a more specific type anyway. If you wanted to have some marker for this, you could always introduce your own annotation - but don't expect any other tools to take any particular notice of it. EDIT: the answer from oxbow\_lakes does indeed give something which will work in most cases, but I believe there are ways of fooling it such that you're actually dealing with a different type. (From memories of experimentation, anyway.) Note that this is similar to how Java enums work.
You can do something very clever (and akin to what they have done in Scala with the [2.8 collection framework](http://scaladocs.jcraft.com/2.8.0/)). Declare some interface method that should return "itself" (**Note:** `This` is a type parameter, not a keyword!) ``` public interface Addable<T, This extends Addable<T, This>> { public This add(T t); } ``` Now declare a level of indirection - a "template" class ``` public interface ListTemplate<A, This extends ListTemplate<A, This>> extends Addable<A, This>{ } public interface List<A> extends ListTemplate<A, List<A>> { } ``` Then an implementation of `List` has to return a `List` from the `add` method (I'll let you fill in the impl details) ``` public class ListImpl<A> implements List<A> { public List<A> add(A a) { return ... } } ``` Similarly you could have declard a `SetTemplate` and a `Set` to extend the `Addable` interface - the `add` method of which would have returned a `Set`. Cool, huh?
Is there a way to say "method returns this" in Java?
[ "", "java", "generics", "" ]
I need to make a proxy script that can access a page hidden behind a login screen. I do not need the proxy to "simulate" logging in, instead the login page HTML should be displayed to the user normally, and all the cookies and HTTP GET/POST data to flow through the proxy to the server, so the login should be authentic. I don't want the login/password, I only need access to the HTML source code of the pages generated *after* logging in. Does anybody here know how this can be accomplished? Is it easy? If not, where do I begin?\* (I'm currently using PHP)\*
What you are talking about is accessing pages for which you need to authenticate yourself. Here are a few things that must be laid down: * you can't view those pages without authenticating yourself. * if the website (whose HTML code you want to see) only supports web login as an authentication method, you will need to simulate login by sending a (username,password) via POST/GET, as the case may be * if the website will let you authenticate yourself in other ways (like LDAP, Kerberos etc), then you should do that The key point is that you cannot gain access without authenticating yourself first. As for language, it is pretty doable in PHP. And as the tags on the question suggest, you are using the right tools to do that job already. One thing I would like to know is, why are you calling it a "proxy"? do you want to serve the content to other users? **EDIT:** [update after comment] In that case, use phproxy. It does what you want, along with a host of other features.
Have your PHP script request the URL you want, and rewrite all links and form actions to point back to your php script. When receiving requests to the script that have a URL parameter, forward that to the remote server and repeat. You won't be able to catch all JavaScript requests, (unless you implemented a JavaScript portion of your "proxy") Eg: User types <http://example.com/login.php> into your proxy form. send the user to <http://yoursite.com/proxy.php?url=http://example.com/login.php> make sure to urlencode the parameter "<http://example.com/login.php>" In <http://yoursite.com/proxy.php>, you make an HTTP request to <http://example.com/login.php> ``` $url = $_REQUEST['url']; // make sure we have a valid URL and not file path if (!preg_match("`https?\://`i", $url)) { die('Not a URL'); } // make the HTTP request to the requested URL $content = file_get_contents($url); // parse all links and forms actions and redirect back to this script $content = preg_replace("/some-smart-regex-here/i", "$1 or $2 smart replaces", $content); echo $content; ``` Note that **/some-smart-regex-here/i** is actually a regex expression you should write to parse links, and such. The example just proxies the HTTP Body, you may want to proxy the HTTP Headers. You can use fsockopen() or PHP stream functions in PHP5+ (stream\_socket\_client() etc.)
How do I write a simple PHP transparent proxy?
[ "", "php", "proxy", "curl", "libcurl", "" ]
When,i try to assign null value to my pointer,it sometimes crashes on that line. The code is something like this : ``` if(s_counter != NULL) { delete s_counter; s_counter = NULL; // it sometimes crashes here. } ``` This is not reproducable,100%,but it occurs frequently. Can anybody help in this?
Note that although it is OK to delete a NULL pointer, it is not necessarily OK to delete a a non-NULL pointer. The pointer must have been allocated with new and must not already have been deleted. Note also that allocating NULL to deleted pointers can add to a false sense of security - simply checking for NULL is not enough, your programs memory allocation semantics need to be correct too.
Probably the line is off by one and it crashes in the delete.
Crash on assigning NULL to a pointer in C++(Qtopia-Core-4.3.3) on Linux
[ "", "c++", "" ]
There is a Locator in SAX, and it keep track of the current location. However, when I call it in my startElement(), it always returns me the ending location of the xml tag. How can I get the starting location of the tag? Is there any way to gracefully solve this problem?
Unfortunately, the `Locator` interface provided by the Java system library in the `org.xml.sax` package does not allow for more detailed information about the documentation location by definition. To quote from the [documentation](http://java.sun.com/j2se/1.5.0/docs/api/org/xml/sax/Locator.html) of the `getColumnNumber` method (highlights added by me): > The return value from the method is intended **only as an approximation** for the sake of diagnostics; it is not intended to provide sufficient information to edit the character content of the original XML document. For example, when lines contain combining character sequences, wide characters, surrogate pairs, or bi-directional text, **the value may not correspond to the column in a text editor's display**. According to that specification, you will always get the position "*of the first character after the text associated with the document event*" based on best effort by the SAX driver. So the short answer to the first part of your question is: **No, the `Locator` does not provide information about the start location of a tag**. Also, if you are dealing with multi-byte characters in your documents, e.g., Chinese or Japanese text, the position you get from the SAX driver is probably not what you want. If you are after exact positions for tags, or want even more fine grained information about attributes, attribute content etc., you'd have to implement your own location provider. With all the potential encoding issues, Unicode characters etc. involved, I guess this is too big of a project to post here, the implementation will also depend on your specific requirements. Just a quick warning from personal experience: Writing a wrapper around the `InputStream` you pass into the SAX parser is dangerous as you don't know when the SAX parser will report it's events based on what it has already read from the stream. You could start by doing some counting of your own in the `characters(char[], int, int)` method of your `ContentHandler` by checking for line breaks, tabs etc. in addition to using the `Locator` information, which should give you a better picture of where in the document you actually are. By remembering the positions of the last event you could calculate the start position of the current one. Take into account though, that you might not see all line breaks, as those could appear inside tags which you would not see in `characters`, but you could deduce those from the `Locator` information.
Here comes a solution that I finally figured out. (But I was too lazy to put it up, sorry.) Here characters(), endElement() and ignorableWhitespace() methods are crucial, with a locator they point to possible starting point of your tags. The locator in characters() points to the closest ending point of the non-tag information, the locator in endElement() points to the ending position of the last tag, which will possibly be the starting point of this tag if they stick together, and the locator in ignorableWhitespace() points to the end of a series of white space and tab. As long as we keep track of the ending position of these three methods, we can find the starting point for this tag, and we can already get the ending position of this tag with the locator in endElement(). Therefore, the starting point and the ending point of a xml can be found successfully. ``` class Example extends DefaultHandler{ private Locator locator; private SourcePosition startElePoint = new SourcePosition(); public void setDocumentLocator(Locator locator) { this.locator = locator; } /** * <a> <- the locator points to here * <b> * </a> */ public void startElement(String uri, String localName, String qName, Attributes attributes) { } /** * <a> * <b> * </a> <- the locator points to here */ public void endElement(String uri, String localName, String qName) { /* here we can get our source position */ SourcePosition tag_source_starting_position = this.startElePoint; SourcePosition tag_source_ending_position = new SourcePosition(this.locator.getLineNumber(), this.locator.getColumnNumber()); // do your things here //update the starting point for the next tag this.updateElePoint(this.locator); } /** * some other words <- the locator points to here * <a> * <b> * </a> */ public void characters(char[] ch, int start, int length) { this.updateElePoint(this.locator);//update the starting point } /** *the locator points to here-> <a> * <b> * </a> */ public void ignorableWhitespace(char[] ch, int start, int length) { this.updateElePoint(this.locator);//update the starting point } private void updateElePoint(Locator lo){ SourcePosition item = new SourcePosition(lo.getLineNumber(), lo.getColumnNumber()); if(this.startElePoint.compareTo(item)<0){ this.startElePoint = item; } } class SourcePosition<SourcePosition> implements Comparable<SourcePosition>{ private int line; private int column; public SourcePosition(){ this.line = 1; this.column = 1; } public SourcePosition(int line, int col){ this.line = line; this.column = col; } public int getLine(){ return this.line; } public int getColumn(){ return this.column; } public void setLine(int line){ this.line = line; } public void setColumn(int col){ this.column = col; } public int compareTo(SourcePosition o) { if(o.getLine() > this.getLine() || (o.getLine() == this.getLine() && o.getColumn() > this.getColumn()) ){ return -1; }else if(o.getLine() == this.getLine() && o.getColumn() == this.getColumn()){ return 0; }else{ return 1; } } } } ```
How do I get the correct starting/ending locations of a xml tag with SAX?
[ "", "java", "sax", "" ]
I have a c++ console application which I would like to publish using clickonce. When I run the mageui.exe tool and import the executable and dependent files to make an application manifest, it won't let me set the app.exe as the entry point. I can set the entry point, but when I click off the line and go to save, it clears the dialog and complains that I do not have a valid entry point. If I save anyway, the entryPoint is empty on the resultant manifest. That makes clickonce fail because there is no valid entrypoint. I've tried manually creating an entry point as follows: ``` <entryPoint> <assemblyIdentity type='win32' name='My App' version='0.9.1.0' processorArchitecture='msil' language='en-US'/> <commandLine file="app.exe" parameters="run"/> </entryPoint> ``` That doesn't work either.
Between the "assembly identity" and setting the processor architecture to MSIL, it seems like you're telling it that the entry point is into a .NET assembly of some kind. Unfortunately, from cursory searching it seems you cannot deploy an unmanaged/native application with clickonce. The entry point must be managed. You can create a shim as described [here](https://stackoverflow.com/questions/51686/is-it-possible-to-deploy-a-native-delphi-application-with-clickonce).
The app has to be managed. ClickOnce uses the security system built into the CLR for restricting what the app can do. Native code has nothing like that.
Is clickonce possible with regular c++ executable
[ "", "c++", "deployment", "code-signing", "" ]
I have to audit a large web Java/J2ee application that has evolved over several years. It's been written by some other company, not the one I'm working for. In it's current state it has become hard to evolve and maintain, new functionalities are hard to add and often lead to bugs that sometime show up in production. There seem to be some copy/pasted code which resulted in code duplication. The current app is some kind of online shopping with some cms-like content here and there. It's mostly Struts and some Spring in newer parts of the code, maybe some ejbs thrown in for good measure. There are some unit tests available, but not a lot of them. These are things I've been told, I haven't seen yet the actual code. My company will make a proposition to rewrite parts of this app in order to reduce complexity, improve quality and modularity, and make it possible to add easier new functionalities without regressions. Before making any commitement, they would like to have some kind of appreciation of the quality of the existing code and to asses how much of it can be reused, in order to have more than a guess in what there will have to be done - full rewrite or partial rewrite. The catch is that I'll have to do this in a very short period ( a couple of days ) so I'm trying to work out a plan for what can be done in such a short time. What I'm thiking is : * check out "basic" things - exceptions treatment, logging * check out the level of layering ( views, controllers, dao layer ) * measure the actual coverage of the unit tests * maybe run some Checkstyle, Findbugs and PMD over the projects * ... So the actual question is what other things should I take into account/check/measure/etc ? I'm not sure what kind of numbers I could get out of this and if it would really mean something, I have the feeling that what the management is asking is kind of the wrong approach, so the second question would be : does anyone has a better idea ? I'll appreciate any idea, suggestion, comment on this. Edit: I'll be adding two dead code detectors to the mix : [UCD](http://www.ucdetector.org/) and [DCD](https://dcd.dev.java.net/)
I had two web applications with similar settings as you. I stopped using FindBugs and Checkstyle as they showed more than 10.000 problematic points. The applications used JDBC level data access, JSP for presentation and a custom framework for request dispatching. Luckily for me, these low level settings allowed me to do the extensions and fixes on medium difficulty. During the 3 year project, only about 20% of the original code remained as it were. Sooner or later everything else needed to be either changed, replaced or removed (and finally I was able to use FindBugs and Checkstyle). We too faced the dilemma of complete rewrite. However, there were several factors against it: * Not sure customer will pay for a complete rewrite. * The lack of functional and technical documentation makes it risky to do the complete rewrite. * Manhours to fully understand the complete application was too high. Customer wanted the requested changes sooner. * The users where customed to the presentation and page behavior. It seemed hard to convince users to use a new interface for old functions. * If we do a complete rewrite, we need to provide complete documentation. For update, we needed to document only our part. * It is hard to convince the management (own and the customer's) of a rewrite if the program works (more or less) * The company had its own PMD rules and the code didn't pass. It was simpler to argue that it is enough the new parts pass the test. It boils down what you want to do actually. Do you want to rewrite, despite the complexity? * Put emphasis on the code bugs. Large pie charts with lots of red is convincing. * Explain the program properties and how they don't fit into the corporate vision. * Show enhancement options beyond the current requirements and describe how the current version is not up to the challenge. * Do interviews with the real users. They might point out important problems with the current version. * Be cheap but a good estimator. You might delay some costs till the maintenance phase. You don't want to rewrite? * Put emphasis on the cost, especially the manhours required from the customer to re-test everything. * Point out the potential trouble of breaking functionality. * Ask for a full-time document writer. If you want to taste the code, try to add the Hello World! function/screen to the application. That tells how hard and how fast you can implement new things.
In fact they won't pay for a full rewrite, because : * It's recession, the cost of you rewriting it from scratch will be high * They might be trying to sell the company ASAP * The management doesn't understand anything about software development I would first go with some simple facts : * Use a tool to display the SLOC of the project * Run as you planned FindBugs and eventually PMD, just to estimate the defects * Do a quick profiling session * Check the different layers * See if resources are generally closed (Streams, Hibernate or JDBC connections, etc.) * See if technologies are used where they don't apply (EJBs, Web Services, etc.) * See how they handle exceptions and logging * See if there's too much or not enough abstraction * See if you could add some base classes to reduce code duplication Try to draw a quick diagram of the architecture of the application, if they don't give you a document about it. Gather some statistics and some facts, write a report and send them to the company. They'll want to minimize the costs and they'll ask you to avoid fixing code which is not broken. You start with the statistics, then to the facts and a proposition with time/approximate percentage of code affected/pricing. Usually legacy Struts applications are a pita to maintain, been there done that. If it wasn't part of your job, I would say let it go. If you come across "standalone" pages which don't involve many templates and are subject to many changes, propose to rewrite them with some other technology.
What's the best approach in auditing a big java/j2ee web application
[ "", "java", "jakarta-ee", "audit", "" ]
Is there a way to get the C++ pre-processor to expand a #define'ed value into a string literal? for example: ``` #define NEW_LINE '\n' Printf("OutputNEW_LINE"); //or whatever ``` This looks to me like it should be possible as it's before compilation? Or is there a better design pattern to achieve this kind of behaviour (without resorting to runtime fixes like sprintf)? **EDIT** I understand that #define's can be evil, but for arguments sake... **ADDITIONAL** Does anyone have any criticism of this approach?
This will do it: ``` #define NEW_LINE "\n" // Note double quotes Printf("Output" NEW_LINE); ``` (Technically it's the compiler joining the strings rather than the preprocessor, but the end result is the same.)
If I remember correctly it is ``` Printf("Output" NEW_LINE); ```
Can you expand #define's into string literals?
[ "", "c++", "c-preprocessor", "" ]
I have a process where an incoming user request to our system is being handled. I also want to add some metadata about the request to a database table without impacting the responsiveness of the main process. To achieve this I added a call to an asynchronous method like this: ``` public static ReturnObject ResponsiveMethod(string ip, string code) { // ... some reasonably quick code IPDetail.InsertAsync(ip); // <-- call to the async method return new ReturnObject(code); } ``` The InsertAsync() method looks like this: ``` public static void InsertAsync(string ipAddress) { Action action = () => IPDetail.Insert(ipAddress); action.BeginInvoke(aResult => Log.Debug("Completed Insert"), null); } ``` And finally, the normally non-asynchronous method called Insert(): ``` private static void Insert(string ipAddress) { ApplicationContextHelper.LoadApplicationContext(); var helper = new GeoLocationHelper(); var result = helper.GetDetailsFromIP(ipAddress); Log.InfoFormat("Succesfully retreived IP data {0}.", ipAddress); result.Save(); } ``` In my unit tests the InsertAsync() call works perfectly. Inside the method calls in Insert() there are many operations occuring which are detailed by logging, and all the expected log messages are there, as well as the final result of the result.Save() method. However, we have a webservice which utilizes something like the ResponsiveMethod() method above and for some reason the asynchronous calls do not complete. All of the logging in the LoadApplicationContext() method gets fired, but after that there is no log activity related to the Insert() and the result.Save() is never getting executed. ***Revised summary question to be more concise*** My current thinking is that the webservice has completed its task and the thread which called the asynchronous no longer exists. Would this stop the async call from completing?
I've never used BeginInvoke before, but usually where there's a Begin\*, you also need the coresponding End\*. Please add one, along with correct exception handling.
My first thought is that you may be throwing an exception on your async call in the web service scenario for some reason. I know you've probably pared it down to post it on the web, but is there any "more-or-less unfailable" error handling code in there?
Asynchronous method appears to not be fully executing
[ "", "c#", ".net", "web-services", "asynchronous", "" ]
How to clear browser cache with php?
``` header("Cache-Control: no-cache, must-revalidate"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Content-Type: application/xml; charset=utf-8"); ```
You can delete the browser cache by setting these headers: ``` <?php header("Expires: Tue, 01 Jan 2000 00:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); ?> ```
How to clear browser cache with php?
[ "", "php", "browser", "caching", "" ]
I have a winforms `ImageList` which contains 200 256x256 images. When I add the images, 1 by one, half of the programs time spent on the `Add` method according to ANTS .NET profiler. So the program takes 10 secs to launch and 5 is spent there. That is very slow in my opinion. I implemented the same thing using `ImageList.Images.AddRange`. The result did not change. Does anyone know any alternatives or optimizations to solve this? Is the WPF `ImageList` any faster? Is there a faster winforms `ImageList`? --- ### EDIT: ``` foreach (string imageFile in images) { imageList.Images.Add(Image.FromFile(imageFile)); // takes pretty much all of program's execution time. } ```
Have a look at the album and list views in [PhotoSuru](http://www.photosuru.com/), one of Microsoft's WPF sample applications. They have a couple different thumbnail view screens that load pretty quickly (all the images are loaded asynchronously, and only the images necessary are loaded). And there's full source code to get you started if it's what you are looking for. It not precisely like Picasa (they decided only to show full rows of photos instead of a partially covered row like Picasa), but by implementing your own virtualizing IScrollInfo panel (reasonably straightforward, and Ben Constable has a great [series of posts on it](http://blogs.msdn.com/bencon/archive/2006/01/05/509991.aspx)), you should be able to get the performance you're looking for and the behaviour you want. A final note: You might be doing this already (are your images stored as 256x256 pixel images?), but whenever you're trying to display image thumbnails, you'll want to avoid loading the full image. Reading 2 MB+ image files off of the disk just to render an entire screenful of 256x256 pixel thumbnails always has a bigger performance hit than reading an appropriately sized small thumbnail image instead. If you can, cache the thumbnails somewhere (like Windows and Picasa do), or at the very least, try to use the embedded thumbnails in any JPEG files you encounter.
Are you using a ListView for the UI part using that ImageList? The general solution to these kind of problems is to only load some of the images, because only some of them are shown at a time, and then load the other as needed. ListView has a [VirtualMode](http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.virtualmode.aspx) property for this kind of scenarios. Loading and adding 200 images at once may be too much to do, you could load the first shown images and then use a background thread to load the others. Have a look at how Win7 display images, it shows some placeholder when you scroll and then, when the image is loaded it shows the real picture. Be warned that this **is not a simple thing** to do.
Is there a more performant alternative to ImageList.Images.Add?
[ "", "c#", ".net", "wpf", "winforms", "performance", "" ]
What does the `>>` sign mean in Java? I had never seen it used before but came across it today. I tried searching for it on Google, but didn't find anything useful.
This is the bit shift operator. [Documentation](http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op3.html) > The signed left shift operator "<<" > shifts a bit pattern to the left, and > the signed right shift operator ">>" > shifts a bit pattern to the right. The > bit pattern is given by the left-hand > operand, and the number of positions > to shift by the right-hand operand. > The unsigned right shift operator > ">>>" shifts a zero into the leftmost > position, while the leftmost position > after ">>" depends on sign extension.
The `>>` operator is the bitwise right shift operator. Simple example: ``` int i = 4; System.out.println(i >> 1); // prints 2 - since shift right is equal to divide by 2 System.out.println(i << 1); // prints 8 - since shift left is equal to multiply by 2 ``` Negative numbers behave the same: ``` int i = -4; System.out.println(i >> 1); // prints -2 System.out.println(i << 1); // prints -8 ``` Generally speaking - `i << k` is equivalent to `i*(2^k)`, while `i >> k` is equivalent to `i/(2^k)`. In all cases (just as with any other arithmetic operator), you should always make sure you do not overflow your data type.
Double Greater Than Sign (>>) in Java?
[ "", "java", "" ]
i have an issue i could use some help with, i have python list that looks like this: ``` fail = [ ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\b\\include', 'Test.java'] ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\c', 'apa1.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'] ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\d', 'Sourcecheck.py'] ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\a\\include', 'svin.txt'] ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'apa2.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'] sha1 value, directory, filename ``` What i want is to separate this content in two different lists based on the sha1 value and directory. For example. ``` ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'] ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'] ``` i want to add to the list `duplicate = []`, because it's in the same directory with the same sha1 value (and only that directory). The rest of the entries i want to add to another list, say `diff = []`, because the sha1 value is the same but the directories differ. I'm kinda lost with the logic here so all that help i could get would be thankful! EDIT: Fixed a typo, last value (filename) was in some cases a 1-list element, which was 100% incorrect, thansk to SilentGhost to become aware of this issue.
``` duplicate = [] # Sort the list so we can compare adjacent values fail.sort() #if you didn't want to modify the list in place you can use: #sortedFail = sorted(fail) # and then use sortedFail in the rest of the code instead of fail for i, x in enumerate(fail): if i+1 == len(fail): #end of the list break if x[:2] == fail[i+1][:2]: if x not in duplicate: duplicate.add(x) if fail[i+1] not in duplicate: duplicate.add(fail[i+1]) # diff is just anything not in duplicate as far as I can tell from the explanation diff = [d for d in fail if d not in duplicate] ``` With your example input ``` duplicate: [ ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', ['apa.txt']], ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'] ] diff: [ ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', ['apa2.txt']], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\c', 'apa1.txt'], ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\a\\include', ['svin.txt']], ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\b\\include', 'Test.java'], ['da39a3ee5e6b4b0d3255bfef95601890afd80709', 'ron\\d', 'Sourcecheck.py'] ] ``` So perhaps I missed something, but I think this is what you were asking for.
you could simply loop through all the values then use an inner loop to compare directories, then if the directory is the same compare values, then assign lists. this would give you a decent n^2 algorithm to sort it out. maybe like this untested code: ``` >>>for i in range(len(fail)-1): ... dir = fail[i][1] ... sha1 = fail[i][0] ... for j in range(i+1,len(fail)): ... if dir == fail[j][1]: #is this how you compare strings? ... if sha1 == fail[j][0]: ... #remove from fail and add to duplicate and add other to diff ``` again the code is untested.
Python List Question
[ "", "python", "list", "" ]
I'm writing some example code where an embedded Jetty server is started. The server must load exactly one servlet, send all requests to the servlet and listen on localhost:80 My code so far: ``` static void startJetty() { try { Server server = new Server(); Connector con = new SelectChannelConnector(); con.setPort(80); server.addConnector(con); Context context = new Context(server, "/", Context.SESSIONS); ServletHolder holder = new ServletHolder(new MyApp()); context.addServlet(holder, "/*"); server.start(); } catch (Exception ex) { System.err.println(ex); } } ``` Can i do the same with less code/lines ? (Jetty 6.1.0 used).
``` static void startJetty() { try { Server server = new Server(); Connector con = new SelectChannelConnector(); con.setPort(80); server.addConnector(con); Context context = new Context(server, "/", Context.SESSIONS); context.addServlet(new ServletHolder(new MyApp()), "/*"); server.start(); } catch (Exception ex) { System.err.println(ex); } } ``` Removed unnecessary whitespace and moved ServletHolder creation inline. That's removed 5 lines.
You could configure Jetty declaratively in a Spring applicationcontext.xml, e.g: <http://roopindersingh.com/2008/12/10/spring-and-jetty-integration/> then simply retrieve the server bean from the applicationcontext.xml and call start... I believe that makes it one line of code then... :) ``` ((Server)appContext.getBean("jettyServer")).start(); ``` It's useful for integration tests involving Jetty.
Shortest code to start embedded Jetty server
[ "", "java", "jetty", "embedded-jetty", "" ]
I feel like this is easy but I am missing something... Using jQuery, I am trying to fetch a remote page (on a different server), capture the HTML contents, and inject that content into a hidden DIV. However, using either $.ajax or $.get results in a cross-site scripting error in FireFox. Any suggestions? Code: ``` $.ajax({ type: 'GET', url: "http://www.remote-url.com", dataType: 'html', success: function(data) { $('#put_here').empty().append(data); } }); ``` Thanks! Chad
You can't do that - the [Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy) prevents it for security reasons (as you've found). You need to [run a proxy script](http://ajaxpatterns.org/Cross-Domain_Proxy) on your own server that your JavaScript uses to fetch the content from the remote server on its behalf.
Alternatively you could use already-existing APIs like YQL or Pipes to access the data you're after... and then return results using JSONP (cross-domain operable).
jQuery Cross Site Fetch
[ "", "javascript", "jquery", "ajax", "" ]
I have two tables, the structure of the first partially recapitulates, iterates the structure of the second: ``` table1 (id, i, j, k, a, b, c, x, y, z) -- requests table2 (id, a, b, c, d) -- essential elements / bank subjects ``` I need to insert into `table1` a record from `table2` with given ID. What is the best approach to do that? I have two ideas: 1: ``` DECLARE @a type, @b type, @c type SELECT @a = a, @b = b, @c = c, FROM table2 WHERE id = @id INSERT INTO table1 (i, j, k, a, b, c, x, y, z) VALUES (@i, @j, @k, @a, @b, @c, @x, @y, @z) ``` 2: ``` CREATE TABLE #result (a type, b type, c type) SELECT a, b, c INTO #result FROM table2 WHERE id = @id INSERT INTO table1 (i, j, k, a, b, c, x, y, z) VALUES (@i, @j, @k, (SELECT a FROM #result), (SELECT b FROM #result), (SELECT c FROM #result), @x, @y, @z) ``` What another approach does exists? Which one is the best-practice?
I would do it like this: ``` INSERT INTO table1 (i, j, k, a, b, c, d, x, y ,z) Select @i, @j @k, a, b, c, d, @x, @y, @z From table2 Where id = @id ``` This saves you from getting the data in to local variables and/or temp tables. The performance should be better. The important part to realize is that you can hard code values in the select. The order in which you list the columns (insert line) must match the order in which you list the columns in the select line.
You can do it with a single insert query: ``` insert into table1 (a, b, c, d, x, y, z) select a, b, c, d, @x, @y, @z from table2 where id = @id ``` Edit: With the extra fields that you added it would be: ``` insert into table1 (i, j, k, a, b, c, x, y, z) select @i, @j, @k, a, b, c, @x, @y, @z from table2 where id = @id ```
Insert into a table a part of another table
[ "", "sql", "sql-server", "temp-tables", "" ]
I have a problem: I used py2exe for my program, and it worked on my computer. I packaged it with Inno Setup (still worked on my computer), but when I sent it to a different computer, I got the following error when trying to run the application: "CreateProcess failed; code 14001." The app won't run. (Note: I am using wxPython and the multiprocessing module in my program.) I googled for it a bit and found that the the user should install some MS redistributable something, but I don't want to make life complicated for my users. Is there a solution? Versions: Python 2.6.2c1, py2exe 0.6.9, Windows XP Pro
You need to include msvcr90.dll, Microsoft.VC90.CRT.manifest, and python.exe.manifest (renamed to [yourappname].exe.manifest) in your install directory. These files will be in the Python26 directory on your system if you installed Python with the "Just for me" option. Instructions for doing this [can be found here](http://www.devpicayune.com/entry/building-python-26-executables-for-windows). Don't forget to call [multiprocessing.freeze\_support()](http://docs.python.org/dev/library/multiprocessing.html#multiprocessing.freeze_support) in your main function also, or you will have problems when you start a new process. While others have discussed including the MSVC runtime in your install package, the above solution works when you only want to distribute a single .zip file containing all your files. It avoids having to create a separate install package when you don't want that additional complication.
You should be able to install that MS redistributable thingy as a part of your InnoSetup setup exe.
Problem deploying Python program (packaged with py2exe)
[ "", "python", "deployment", "wxpython", "multiprocessing", "py2exe", "" ]
I know this is a subjective question, but I'm always curious about best-practices in coding style. ReSharper 4.5 is giving me a warning for the keyword "base" before base method calls in implementation classes, i.e., ``` base.DoCommonBaseBehaviorThing(); ``` While I appreciate the "less is better" mentality, I also have spent a lot of time debugging/maintaining highly-chained applications, and feel like it might help to know that a member call is to a base object just by looking at it. It's simple enough to change ReSharper's rules, of course, but what do y'all think? Should "base" be used when calling base members?
The only time you should use `base.MethodCall();` is when you have an overridden method of the same name in the child class, but you actually want to call the method in the parent. For all other cases, just use `MethodCall();`. Keywords like `this` and `base` do not make the code more readable and should be avoided for all cases *unless* they are necessary--such as in the case I described above.
I am not really sure using *this* is a bad practice or not. *base*, however **is not a matter of good or bad practice, but a matter of semantics**. Whereas *this* is polymorphic, meaning that even if the method using it belongs to a base class, it will use the overriden method, *base* is not. *base* will always refer to the method defined at the base class of the method calling it, hence it is **not polymorphic**. This is a huge semantic difference. *base* should then be used accordingly. If you want *that* method, use *base*. If you want the call to remain polymorphic, don't use *base*.
Is using "base" bad practice even though it might be good for readability?
[ "", "c#", "coding-style", "resharper", "" ]
I'm using the Win32 function GetEnvironmentVariable to retrieve the value of a variable that I just created. I'm running Windows XP and VC++ 2005. If I run the program from within Visual Studio, it can't find the new variable. If I run it from a command-prompt, it does. I restarted VC++ but same result. I even restarted all instances of Visual Studio but still the same problem. It might get resolved if I reboot the PC but I'm curious why this is so. Here's the code that I'm using: ``` #define BUFSIZE 4096 #define VARNAME TEXT("MY_ENV_NAME") int _tmain(int argc, _TCHAR* argv[]) { TCHAR chNewEnv[BUFSIZE]; DWORD dwEnv = ::GetEnvironmentVariable(VARNAME, chNewEnv, BUFSIZE); if (dwEnv == 0) { DWORD dwErr = GetLastError(); if(dwErr == ERROR_ENVVAR_NOT_FOUND) { printf("Environment variable does not exist.\n"); return -1; } } else { printf(chNewEnv); } return 0; } ``` If I replace MY\_ENV\_NAME with something that must exist, such as TEMP, it works as expected. Any ideas? Thanks.
Thanks for all the responses. As I mentioned in my question, I tried restarting everything, short of rebooting the PC. It turns out that because my environment variable was a SYSTEM variable, VS doesn't recognize it without rebooting the PC. When I moved the env variable from SYSTEM to USER and restarted VS, it worked fine.
Expanding on what Anders and Martin said, environment variables are one thing that is inherited when starting an application. The new program basically gets a copy of the environment **at the time it was started**. When debugging, your exe is generally started by Visual Studio, so your application will have the same environment as Visual Studio. Visual Studio, is generally started by explorer. If you change the environment variables by going to System Properties->Advanced->Envronment Variables then you will have to restart Visual Studio to see the changes. If you need to see the envronment variables that Visual Studio is seeing you can (at least for VS2005/2008) go to Tools...->options...->Projects and Solutions->VC++ Project Settings and set Show Environment in Log to 'Yes.' This will print out all the environment variables to the build log (ctrl+click on the link in your build output). You have to build to get this info, but this is the best way I know of seeing the VS environment. If you really need to change environment variables then run and are having a hard time debugging, you can build your debug exe and have a call to DebugBreak() somewhere near where you want to start debugging from. Then you can set your environment how you want, start the exe from explorer or the command prompt. Then (assuming you have JIT debugging enabled) you will get a popup when your code gets to the DebugBreak() call and you can attach to it with VS and debug normally from there.
VC++ doesn't detect newly created env variable using GetEnvironmentVariable
[ "", "c++", "environment-variables", "" ]
I'm having this problem on posting a page. The page have a jquery ajax load called by the onchange of a dropdownlist, if I disable the onchange, the post works. **"The state information is invalid for this page and might be corrupted"** ``` [FormatException: Invalid character in a Base-64 string.] System.Convert.FromBase64String(String s) +0 System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +72 System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) +4 System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) +37 System.Web.UI.HiddenFieldPageStatePersister.Load() +113 [ViewStateException: invalid Viewstate. Client IP: 127.0.0.1 Port: User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729) ViewState: /wEPDwULLTE1NjAwNjAwNDMPZBYCZg9kFgRmD2QWAgIOD2QWCAIBDxYCHgRUZXh0BSpTcGVyaW5kZSBJbcOzdmVpcyAmcnNhcXVvOyBQw6FnaW5hIEluaWNpYWxkAgMPFgIfAAUOdmVuZGFyLCBhbHVnYXJkAgUPFgIfAGVkAgcPFgIfAAUaaHR0cDovL3d3dy5zcGVyaW5kZS5jb20uYnJkAgEPZBYQAgMPEGQQFQEPVGlwbyBkZSBJbcOzdmVsFQEAFCsDAWdkZAIEDxBkEBUBBkNpZGFkZRUBABQrAwFnZGQCBg8QZA8WAWYWARAFD1RpcG8gZGUgSW3Ds3ZlbGVnZGQCBw8QD2QWAh4Ib25jaGFuZ2UFGSQuY2hhbmdlQ2l0eSh0aGlzLnZhbHVlKTsPFgFmFgEQBQZDaWRhZGVlZ2RkAggPZBYQAgEPFgIfAAUMTE9GVCBWSVNDQVlBZAIDDxYCHwAFKUNhc2EgMyBkb3JtaXTDs3Jpb3Mgbm8gYmFpcnJvIEJlbGEgVmlzdGEuZAIHDxYCHwAFHjxzdHJvbmc+UiQgMjUwLjAwMCwwMDwvc3Ryb25nPmQCCQ8WAh8ABRUxNTYwLjQ0IG08c3VwPjI8L3N1cD5kAgsPFgIfAAUJMyBlIDQgIEQuZAINDw8WBh8ABRBFeGNsdWlyIGRhIGxpc3RhHgdUb29sVGlwBRBFeGNsdWlyIGRhIGxpc3RhHgtOYXZpZ2F0ZVVybAUUI3JlbW92ZUxpbmsgMjEwMDM3NzlkZAIPDw8WBh8DBUB+L3ZlbmRhL2xhbmNhbWVudG...] [HttpException (0x80004005): As informações sobre estado são inválidas para esta página e podem estar corrompidas.] System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) +106 System.Web.UI.ViewStateException.ThrowViewStateError(Exception inner, String persistedState) +14 System.Web.UI.HiddenFieldPageStatePersister.Load() +217 System.Web.UI.Page.LoadPageStateFromPersistenceMedium() +105 System.Web.UI.Page.LoadAllState() +43 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +6785 System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +242 System.Web.UI.Page.ProcessRequest() +80 System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +21 System.Web.UI.Page.ProcessRequest(HttpContext context) +49 ASP.content_search_default_aspx.ProcessRequest(HttpContext context) in c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\web-site-2009\e4bfc9d6\d5d6c855\App_Web_zcb1qfmu.0.cs:0 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75 ``` what could be the reason for that? Anyone seen it before? Thank you **EDIT:** So, I've found out why this is happenning. At the end of Page\_Load, I write a javascript line that calls a jquery function that loads new fields into a div. So, as I see, this is causing to create a inconsistence on the viewstate. Disabling ViewState is not a option for this case. It works on FF, and it bugs on IE. Anyone? Thank you
Just ran into this. Remove the form tag from the page you are loading via jquery.
Had the same problem, the reason why I got the error was because I sent a complete form as string into a javascript method, which then posted the form. That was a bit heavy, and my fix was to send only the form data as serialized json, and then create and post the form through javascript, like in this post. <http://weblogs.asp.net/hajan/archive/2011/03/16/posting-from-asp-net-webforms-page-to-another-url.aspx>
"Invalid Character in Base-64 String" using ASP.NET and C#
[ "", "c#", "asp.net-ajax", "" ]
I have a winforms image list which contains say like 200 images 256x256. I use the method `Images.FromFile` to load the images and then add them to the image list. According to ANTS .NET profiler, half of the program's time is spent in `Images.FromFile`. Is there a better way to load an image to add to an image list? Another thing that might be optimized is, the images that are loaded are larger than 256x256. So is there a way to load them by resizing them first or something? I just want to uniform scale them if they their height is larger than 256 pixels. Any idea to optimize this? EDIT: They are JPEGs.
If you are trying to make thumbnails then try this code [here](http://www.vbforums.com/showthread.php?t=342386) it will let you extract thumbnails without completely loading the image.
You don't say how much bigger than 256x256 the images actually are - modern digital cameras images are *much* bigger than this. Disk I/O can be *very* slow, and I would suggest you first get a rough idea how many megabytes of data you're actually reading. Then you can decide if there's a subtle 'Image.FromFile' problem or a simple 'this is how slow my computer/drives/anti-virus scanner/network actually is' problem. A simple test of the basic file I/O performance would be do to File.ReadAllBytes() for each image instead of Image.FromFile() - that will tell you what proportion of the time was spent with the disk and what with the image handling - I suspect you'll find it's largely disk, at which point your only chance to speed it up might be one of the techniques for getting JFIF thumbnails out of files. Or perhaps one can imagine clever stuff with partial reads of progressive JPEGs, though I don't know if anyone does that, nor if your files are progressive (they're probably not). I don't really know how fast you need these to load, but if the problem is that an interactive application is hanging while you load the files, then think of ways to make that better for the user - perhaps use a BackgroundWorker to load them asynchronously, perhaps sort the images by ascending file-size and load the small ones first for a better subjective performance.
Image.FromFile is very SLOW. Any alternatives, optimizations?
[ "", "c#", ".net", "winforms", "performance", "image", "" ]
I have a directory full of images that I would like to resize to around 60% of their original size. How would I go about doing this? Can be in either Python or Perl Cheers Eef
How about using mogrify, part of [ImageMagick](http://www.imagemagick.org/)? If you really need to control this from Perl, then you could use [Image::Magick](http://search.cpan.org/dist/Image-Magick), [Image::Resize](http://search.cpan.org/dist/Image-Resize) or [Imager](http://search.cpan.org/dist/Imager).
If you want to do it programatically, which I assume is the case, use PIL to resize e.g. ``` newIm = im.resize((newW, newH) ``` then save it to same file or a new location. Go through the folder recursively and apply resize function to all images. I have come up with a sample script which I think will work for you. You can improve on it: Maybe make it graphical, add more options e.g. same extension or may be all png, resize sampling linear/bilinear etc ``` import os import sys from PIL import Image def resize(folder, fileName, factor): filePath = os.path.join(folder, fileName) im = Image.open(filePath) w, h = im.size newIm = im.resize((int(w*factor), int(h*factor))) # i am saving a copy, you can overrider orginal, or save to other folder newIm.save(filePath+"copy.png") def bulkResize(imageFolder, factor): imgExts = ["png", "bmp", "jpg"] for path, dirs, files in os.walk(imageFolder): for fileName in files: ext = fileName[-3:].lower() if ext not in imgExts: continue resize(path, fileName, factor) if __name__ == "__main__": imageFolder=sys.argv[1] # first arg is path to image folder resizeFactor=float(sys.argv[2])/100.0# 2nd is resize in % bulkResize(imageFolder, resizeFactor) ```
Resize images in directory
[ "", "python", "perl", "image", "resize", "image-scaling", "" ]
What is the best/foolproof way to get the values of environment variables in Windows when using J2SE 1.4 ?
You have definitely no way to access environment variables straigthly from java API. The only way to achieve that with Runtime.exec with such a code : ``` Process p = null; Runtime r = Runtime.getRuntime(); String OS = System.getProperty("os.name").toLowerCase(); // System.out.println(OS); if (OS.indexOf("windows 9") > -1) { p = r.exec( "command.com /c set" ); } else if ( (OS.indexOf("nt") > -1) || (OS.indexOf("windows 2000") > -1 ) || (OS.indexOf("windows xp") > -1) ) { // thanks to JuanFran for the xp fix! p = r.exec( "cmd.exe /c set" ); } ``` Although you can access Java variables thanks to System.getProperties(); But you would only get some env variables mapped by JVM itself, and additional data you could provide on java command line with "-Dkey=value" For more information see <http://www.rgagnon.com/javadetails/java-0150.html>
You can use getEnv() to get environment variables: ``` String variable = System.getenv("WINDIR"); System.out.println(variable); ``` I believe the getEnv() function was deprecated at some point but then "undeprecated" later in java 1.5 ETA: I see the question now refers specifically to java 1.4, so this wouldn't work for you (or at least you might end up with a deprecation warning). I'll leave the answer here though in case someone else stumbles across this question and is using a later version.
Accessing Windows system variables in Java 1.4
[ "", "java", "windows", "environment-variables", "java1.4", "" ]
I'm solving Sphere's Online Judge [Prime Generator](https://www.spoj.pl/problems/PRIME1/) using the Sieve of Eratosthenes. My code works for the test case provided. But.. as the problem clearly states: > The input begins with the number t of > test cases in a single line (t<=10). > In each of the next t lines there are > two numbers m and n (**1 <= m <= n <= > 1000000000, n-m<=100000)** separated by > a space. I know that the method `Integer.parseInt()` throws an Exception when handling really big numbers and the online judge was indicating that an Exception was being thrown, so I changed every case of `parseInt` to `parseLong` in my code. Well, the thing is running fine on Netbeans 6.5 with small values for m and n. ``` package sphere; import java.io.BufferedReader; import java.io.InputStreamReader; public class Main{ public static void runEratosthenesSieve(long lowerBound, long upperBound) { long upperBoundSquareRoot = (long) Math.sqrt(upperBound); boolean[] isComposite = new boolean[(int)upperBound + 1]; for (int m = 2 /*int m = lowerBound*/; m <= upperBoundSquareRoot; m++) { if (!isComposite[m]) { if (m>=lowerBound) {System.out.println(m);} for (int k = m * m; k <= upperBound; k += m) isComposite[k] = true; } } for (int m = (int)upperBoundSquareRoot; m <= upperBound; m++) if (!isComposite[m]) if (m>=lowerBound){ System.out.println(m);} } public static void main(String args[]) throws java.lang.Exception{ BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String l = r.readLine(); int testCases = Integer.parseInt(l); for (int i =0; i<testCases; i++){ String s =r.readLine(); String []splitted=s.split(" "); long lowerBound = Long.parseLong (splitted[0]); long upperBound = Long.parseLong(splitted[1]); runEratosthenesSieve (lowerBound,upperBound); System.out.println(""); } } } ``` Input+Output: ``` run: 2 1 10 2 3 3 5 7 3 5 3 5 BUILD SUCCESSFUL (total time: 11 seconds) ``` But JCreator LE is saying this: ``` 2 1 10 Exception in thread "main" java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Long.parseLong(Long.java:424) at java.lang.Long.parseLong(Long.java:461) at sphere.Main.main(Main.java:51) Process completed. ``` Here I don't have an integer overflow, but why would jcreator complain? Considering the borderline testcase, the program implodes on Netbeans too: ``` run: 2 999900000 1000000000 Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at sphere.Main.runEratosthenesSieve(Main.java:13) at sphere.Main.main(Main.java:55) Java Result: 1 ``` How can I deal with those huge-ish integers of the problem statement? **Edit:** By suggestion I have changed the boolean array for a BitSet, but I'm still getting an `OutOFMemoryError`: ``` package sphere; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.BitSet; public class Main{ public static void runEratosthenesSieve(long lowerBound, long upperBound) { long upperBoundSquareRoot = (long) Math.sqrt(upperBound); //boolean[] isComposite = new boolean[(int)upperBound + 1]; BitSet isComposite = new BitSet((int)upperBound+1); for (int m = 2 /*int m = lowerBound*/; m <= upperBoundSquareRoot; m++) { if (!isComposite.get(m)) { if (m>=lowerBound) {System.out.println(m);} for (int k = m * m; k <= upperBound; k += m) isComposite.set(m); } } for (int m = (int)upperBoundSquareRoot; m <= upperBound; m++) if (!isComposite.get(m)) if (m>=lowerBound){ System.out.println(m);} } public static void main(String args[]) throws java.lang.Exception{ BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String l = r.readLine(); int testCases = Integer.parseInt(l); for (int i =0; i<testCases; i++){ String s =r.readLine(); String []splitted=s.split(" "); long lowerBound = Long.parseLong (splitted[0]); long upperBound = Long.parseLong(splitted[1]); runEratosthenesSieve (lowerBound,upperBound); System.out.println(""); } } } ``` Input-Output: ``` run: 1 999900000 1000000000 Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.BitSet.initWords(BitSet.java:144) at java.util.BitSet.<init>(BitSet.java:139) at sphere.Main.runEratosthenesSieve(Main.java:16) at sphere.Main.main(Main.java:58) Java Result: 1 BUILD SUCCESSFUL (total time: 14 seconds) ```
Here's your problem: ``` boolean[] isComposite = new boolean[(int)upperBound + 1]; ``` This will use a HUGE amount of space since it allocates 4 bytes per boolean in order to allow faster access. Use a [java.lang.BitSet](http://java.sun.com/javase/6/docs/api/java/util/BitSet.html) to avoid that. Eventually, your numbers might get too big for long as well and you'll have to use BigInteger. But at that point, the sieve of Eratosthenes will probably not cut it anymore as well.
You're using a lot of space to store your booleans. You might try to squeeze every boolean into one bit. And think about it, do you realy need a boolean for every number between lowerbound and upperbound? The even numbers for instance are never prime (except for 2), nor are all multiples of 3 (except for 3) etc. [This page](http://www.qsl.net/w2gl/blackkey.html) might give you some good ideas.
Sieve of Eratosthenes problem: handling really big numbers
[ "", "java", "bignum", "sieve-of-eratosthenes", "" ]
I am creating a custom ASP.NET AJAX server control in which multiple instances of the control may be placed on the page. That control wraps JavaScript objects, which I need access to those objects for each individual control. For example, the JavaScript object may have a property called "x" and control1 might have x set to 5 and control2 might x set to 10. How do I get access to each individual control's JavaScript objects? Here is a bit of a code snippet that might help: **HTML** ``` <CustomControl:MyControl ID="MyControl1" runat="server" x="5"/> <CustomControl:MyControl ID="MyControl2" runat="server" x="10"/> ``` **JavaScript** ``` alert(MyControl1.x); //result 5 alert(MyControl2.x); //result 10 ```
Chris's suggested articles led me to the right solution. In order to get access to the JavaScript properties of a custom control, you must use the ScriptControl's library to execute the $find function to locate your control. For example: **JavaScript in ASP.NET page implementing control** ``` var ctrl1 = $find("<%=MyControl1.ClientID%>"); var ctrl2 = $find("<%=MyControl2.ClientID%>"); ctrl.set_x(5); alert(ctrl1.x); //result 5 ctrl2.set_x(10); alert(ctrl2.x); //result 10 ``` **JavaScript in Control** ``` CustomControl.MyControl = function(element) { CustomControl.MyControl.initializeBase (this, [element]); this.x = null; } CustomControl.MyControl.prototype = { set_x: function(value) { this.x = value; } } ``` --- Note: I'm not sure of etiquitte for answering your own question. I will up-vote Chris's answer for helping me get to the right article. If there are other etiquiite rules I am happy to oblige.
Here's some links that should help you with building custom server controls using ASP.NET AJAX: Article: [ASP.NET AJAX: Create AJAX Server Controls using the ScriptControl base class](http://pietschsoft.com/post.aspx?id=e78fc882-c172-46bd-ac8c-3a8d5ea56b14) [ASP.NET 3.5: Create AJAX Extender Controls using the ExtenderControl base class](http://pietschsoft.com/post.aspx?id=ba924765-2328-4995-a254-6a88d4e4ac11) Video: [[How Do I:] Build a Custom ASP.NET AJAX Server Control?](http://www.asp.net/Learn/ajax-videos/video-170.aspx)
Accessing JavaScript Properties in Custom ASP.NET AJAX Server Control
[ "", "asp.net", "javascript", "" ]
I have the following in a java file (MyRtmpClient.java): ``` import org.apache.mina.common.ByteBuffer; ``` and `ByteBuffer` is inside a JAR file (with the proper directory structure of course). That jar file and others I need are in the same directory as the .java file. Then I compile with the line: ``` javac -cp ".;*.jar" MyRtmpClient.java ``` But I get the error: > `MyRtmpClient.java:3: package org.apache.mina.common does not exist > import org.apache.mina.common.ByteBuffer;` How can I include jar files in my project?
your command line is correct, but there are some considerations: * you must have javac >= 1.6, because only in that version the compiler parses the "\*" as various JAR files. * you must be running Windows, because ";" is the path separator for that operating system only (it doesn't work on Unix, the path separator on Unix is ":"). I'm assuming that the JAR file has the proper directory structure as you stated.
javac does not understand \*.jar in the classpath argument. You need to explicitly specify each jar. e.g. ``` javac -cp ".;mina.jar" MyRtmpClient.java ```
How to wildcard include JAR files when compiling?
[ "", "java", "jar", "compilation", "package", "" ]
I'm getting the NRE error that says: "Object reference not set to an instance of an object." From the following code: ``` select new { ICAO = station.Element("icao").Value, }; ``` The entire script is: ``` XDocument xmlDoc = XDocument.Load(@"http://api.wunderground.com/auto/wui/geo/GeoLookupXML/index.xml?query=94107"); var stations = from station in xmlDoc.Descendants("station") select new { ICAO = station.Element("icao").Value, }; lblXml.Text = ""; foreach (var station in stations) { lblXml.Text = lblXml.Text + "ICAO: " + station.ICAO + "<br />"; } if (lblXml.Text == "") lblXml.Text = "No Results."; } ``` I don't understand why it isn't creating the station object and setting the ICAO value. Any ideas/tips for future XML and C# reference?
It appears that only the airport stations have the icao element. This should work for you: ``` var stations = from airport in xmlDoc.Descendants("airport") from station in airport.Elements("station") select new { ICAO = station.Element("icao").Value, }; ``` You could instead add a where condition to get around the exception: ``` var stations = from station in xmlDoc.Descendants("station") where station.Element("icao") != null select new { ICAO = station.Element("icao").Value, }; ``` Also, you can pull a value like this to prevent an exception, though it will return numerous null records you may or may not want: ``` ICAO = (string)station.Element("icao") ``` You can do that for various other types, not only for strings.
The XML file in your sample returns some `station` elements with no `icao` descendant so sometimes `station.Element("icao")` will return null.
NullReferenceException in C# Dealing with XML
[ "", "c#", "xml", "" ]
Hi I've been working with Django for a few months and find it really helpful. Is there a similar framework for other programming languages such as Java or C#? The problem I have with Django is finding a server to host the project because supporting servers are more expensive and harder to find. In Django I find the following items useful: the object-relational mapper, admin interface and url management. Thanks!
If you're only looking for an alternative because of the hosting aspect of it, I suggest you simply find suitable hosting as opposed to throwing away the framework you like. If you are looking for a good Django host, I HIGHLY recommend [Webfaction](http://www.webfaction.com). If they're not your cup of tea, check out [djangofriendly.com](http://www.djangofriendly.com), which has a huge list of good Django hosts.
If you're looking for the cheapest hosting then PHP is probably your choice. The downside is that PHP is a horrible cobbled together language, and a lot of the PHP code out there is equally terrible (par for the course, I suppose).
django-like frameworks?
[ "", "java", ".net", "django", "frameworks", "" ]
How do I implement dependancy injection in C++ explicitly without using frameworks or reflection? I could use a factory to return a auto\_ptr or a shared\_ptr. Is this a good way to do it?
Just use a shared\_ptr to the service you need, and make a setter to it. E.g.: ``` class Engine; class Car { public: void setEngine(shared_ptr<Engine> p_engine) { this->m_engine = p_engine; } int onAcceleratorPedalStep(int p_gas_pedal_pressure) { this->m_engine->setFuelValveIntake(p_gas_pedal_pressure); int torque = this->m_engine->getTorque(); int speed = ... //math to get the car speed from the engine torque return speed; } protected: shared_ptr<Engine> m_engine; } // (now must create an engine and use setEngine when constructing a Car on a factory) ``` Avoid using auto\_ptr, because you can't share it through more than one object (it transfers ownership when assigning).
AFAIK dependency injection just means, that there is an interface to an component needed by another one. ``` namespace ifc { struct service { virtual ~service() {} virtual do_stuff(/*..*/) = 0; }; } // ns ifc class ServiceProviderA : public ifc::service { public; do_stuff(/*..*/) { /*...*/ } }; class ServiceProviderB : public ifc::service {/*...*/}; class Client { public; client(ifc::service*); private: ifc::service* m_service; }; ``` I can only guess, but is your question how to manage the lifetime of the injected Object?
Dependency Injection in C++
[ "", "c++", "refactoring", "dependency-injection", "" ]
It is possible in plain Java to override a method of a class programmatically at runtime (or even create a new method)? I want to be able to do this even if I **don't** know the classes at compile time. What I mean exactly by overriding at runtime: ``` abstract class MyClass{ public void myMethod(); } class Overrider extends MyClass{ @Override public void myMethod(){} } class Injector{ public static void myMethod(){ // STATIC !!! // do actual stuff } } // some magic code goes here Overrider altered = doMagic( MyClass.class, Overrider.class, Injector.class); ``` Now, this invocation... ``` altered.myMethod(); ``` ...would call **Injector.myMethod()** instead of **Overrider.myMethod()**. Injector.myMethod() is **static**, because, after doing "magic" it is invoked from different class instance (it's the Overrider), (so we prevent it from accessing local fields).
You can use something like [cglib](http://cglib.sourceforge.net/) for generating code on-the-fly
In java6 has been added the possibility to transform any already loaded class. Take a look at the [changes](http://java.sun.com/javase/6/docs/technotes/guides/instrumentation/changes6.html) in the java.lang.instrument package
Java reflection: How do I override or generate methods at runtime?
[ "", "java", "reflection", "code-generation", "runtime", "" ]
I have a table with two decimal(18,0) fields. I am inserting into this table, two decimal values. For example, 1.11 When I select from the table (with no casts), I get 1. I'm losing all percision and I have no clue why. insert into TEST values (153, 'test', 'test', 1, 1, 1.11, 1.11) Select \* from TEST and they are 1 and 1 instead of 1.11,1.11 Any Ideas?
When you declare a field as decimal(18,0), you are saying that you want 0 digits of precision after the decimal point. You're going to want to define those columns as decimal(18,2) (or however many digits of precision you desire) in order to maintain a value of 1.11. Refer to the [MSDN page on decimal and numeric types](http://msdn.microsoft.com/en-us/library/aa258832(SQL.80).aspx) for the grisly details.
Define the Precision to Decimal every time else it stores only int values not Decimal values
SQL Server Inserting Decimal, but selecting Int
[ "", "sql", "sql-server", "types", "decimal", "" ]
What is the difference between `type(obj)` and `obj.__class__`? Is there ever a possibility of `type(obj) is not obj.__class__`? I want to write a function that works generically on the supplied objects, using a default value of 1 in the same type as another parameter. Which variation, #1 or #2 below, is going to do the right thing? ``` def f(a, b=None): if b is None: b = type(a)(1) # #1 b = a.__class__(1) # #2 ```
`type(obj)` and `type.__class__` do not behave the same for old style classes in Python 2: ``` >>> class a(object): ... pass ... >>> class b(a): ... pass ... >>> class c: ... pass ... >>> ai = a() >>> bi = b() >>> ci = c() >>> type(ai) is ai.__class__ True >>> type(bi) is bi.__class__ True >>> type(ci) is ci.__class__ False >>> type(ci) <type 'instance'> >>> ci.__class__ <class __main__.c at 0x7f437cee8600> ``` This is explained [in the documentation](https://docs.python.org/2.7/reference/datamodel.html#newstyle): > For an old-style class, the statement `x.__class__` provides the class of *x*, but `type(x)` is always `<type 'instance'>`. This reflects the fact that all old-style instances, independent of their class, are implemented with a single built-in type, called `instance`.
This is an old question, but none of the answers seems to mention that. in the general case, it **IS** possible for a new-style class to have different values for `type(instance)` and `instance.__class__`: ``` class ClassA(object): def display(self): print("ClassA") class ClassB(object): __class__ = ClassA def display(self): print("ClassB") instance = ClassB() print(type(instance)) print(instance.__class__) instance.display() ``` Output: ``` <class '__main__.ClassB'> <class '__main__.ClassA'> ClassB ``` The reason is that `ClassB` is overriding the `__class__` descriptor, however the internal type field in the object is not changed. `type(instance)` reads directly from that type field, so it returns the correct value, whereas `instance.__class__` refers to the new descriptor replacing the original descriptor provided by Python, which reads the internal type field. Instead of reading that internal type field, it returns a hardcoded value.
Difference between type(obj) and obj.__class__
[ "", "python", "new-style-class", "" ]
My website is being hacked. iframes and JS is being added even after I have been manually searching for and removing them for the past couple of days. Why is this happening and what can I do to prevent it? I have set all index files to permission 444 and most other files to 644. There are a few pages that have flash content being added to them and these files seem to need a more relaxed permission setting(755). The files are mostly PHP files. I am reviewing the PHP code right now for any vulnerabilities. Is there anything specific I should be looking for and what should I be doing on the permissions front?
There are so many things that could have happened. Someone somehow sneaked in something that was eval()ed via a parameter, an external script that was executed. Maybe while transferring something to your site via ftp someone sniffed your password and this list goes on forever... I would suggest taking the website offline, checking the logs and compare them with the timestamp of the files that were changed/last created. If he had access to your php files, most certainly he took a mysql dump with him. I think you need to change all user passwords and maybe inform the users. In a shared environment with bad security checks he could have even used a security hole in another site. In any case you should check with your sysadmin. By the way changing permissions will often not alter anything. The attacker can simply change them back, if he has already snaked in something. Which software are you using, something self made?
Do you allow user submitted content (such as comments to a blog)? Check to make sure the data submitted is properly cleaned of dangerous content such as script tags and the like. Ideally, you will use a format like MarkDown that is converted to HTML for display but contains no dangerous tags itself.
Scripts(iframes and javascript) being added to site
[ "", "php", "permissions", "" ]
I'm building an application that uses an elaborate API to fetch data from Youtube, and the data files are saved with the name of the corresponding video as the file name. However, my program is crashing because quite a lot of the videos on YouTube have characters in their titles that are illegal to use in file names under Windows. Would URLEncoding the title of the video fix this problem? If so, is this the best method to use, and what would be the best way to implement a URLEncode? Thanks! :)
Well if you want to do url encoding, you could use [`HttpUtility.UrlEncode`](http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx). I'm not sure I would though. It *may* strip out all the characters you want it to, but it'll do others as well. I think I'd probably use [`Path.GetInvalidFilenameChars`](http://msdn.microsoft.com/en-us/library/system.io.path.GetInvalidFilenameChars.aspx) and just replace anything invalid in the name with an underscore. That's not a reversible encoding, of course, but I think it'll produce filenames which are easier to understand. You might want to create an index file which maps from original title to filename as well.
Url Encoding should fix the problem, as it should replace any invalid char (and a few valid ones) with a '%' followed by a set of hex; to my knowledge that is valid for file system names. This begs two questions though: 1. Is being able to cleanly read a filename important for the user? If not, it might be better to use a unique file name (1.file, 2.file, 3.file) and a mapping from file name -> title 2. What happens if two videos have the same name? Sort of an extension of the first question, I think. 3. What if the title (when url encoded) is longer then the max filename length? If I recall correctly, max length for a filename is 255 characters on NTFS; if each char in a title expands to 3 chars for url encoding, then the 255 char limit could be met with an 85 char title. EDIT/Update: There are some characters that UrlEncode considers valid which are invalid file system chars; the one I've specifically come across is '\'. So, no, Url Encoding would not be safe.
Will URLEncode fix this problem with illegal characters in file names (C#)?
[ "", "c#", "urlencode", "illegal-characters", "" ]
I need to know the position of the caret in a TextBox so I can pop up a context menu near it. How do I find its placement (not character index)?
Found [this article](http://www.codeproject.com/KB/WPF/Intellisense_popup.aspx) describing how to do what I need done. Turns out you can set both the PlacementTarget of the textbox *and* the PlacementRectangle from GetRectFromCharacterIndex and it will work.
Check out [this example](http://msdn.microsoft.com/en-us/library/ms750420.aspx).
Finding the position of the caret in a TextBox
[ "", "c#", ".net", "wpf", "" ]
How do you get a `<div>` from within an `<iframe>`?
``` var iframe = document.getElementById('iframeId'); var innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document; ``` You could more simply write: ``` var iframe = document.getElementById('iframeId'); var innerDoc = iframe.contentDocument || iframe.contentWindow.document; ``` and the first valid inner doc will be returned. Once you get the inner doc, you can just access its internals the same way as you would access any element on your current page. (`innerDoc.getElementById`...etc.) **IMPORTANT:** Make sure that the iframe is on the same domain, otherwise you can't get access to its internals. That would be cross-site scripting. Reference: * [MDN: `<iframe>` Scripting](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#scripting) * [MDN: Same-Origin Policy: Cross-Origin Script API Access](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy#cross-origin_script_api_access)
Do not forget to access iframe **after it is loaded**. Old but reliable way without jQuery: ``` <iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe> <script> function access() { var iframe = document.getElementById("iframe"); var innerDoc = iframe.contentDocument || iframe.contentWindow.document; console.log(innerDoc.body); } </script> ```
Get element from within an iFrame
[ "", "javascript", "iframe", "html", "" ]
I'm trying to profile a C++ application with gprof on a machine running OSX 10.5.7. I compile with g++ in the usual way, but using -pg flags, run the application and try to view the call graph with gprof. Unfortunately my call graph contains all zeroes for all time columns. The values in the "called" columns have reasonable values so it looks like something was profiled but I'm mystified about the lack of other data. All my source files are compiled in a similar way: ``` g++ -pg -O2 -DNDEBUG -I./ -ansi -c -o ScenarioLoader.o ScenarioLoader.cpp ``` I then run 'ar' to bundle all the object files into a library. Later, I link and run gprof as so: ``` g++ -pg -lm -o vrpalone vrpalone.o ../src/atomicprof.a lastbuild.o ./vrpalone gprof gmon.out | less ``` Any ideas?
I thought I might share [this Apple mailing list discussion](http://lists.apple.com/archives/PerfOptimization-dev/2006/Apr/msg00014.html) which I recently ran across. The behaviour described here is exactly what I am experiencing. It looks like gprof has been broken on OSX for quite some time. I've resorted to Shark which has been helpfully suggested by Dave Rigby. Thanks!
If your program terminates in a non-clean manner then the profile data won't get written correctly - how is your program exiting? Regardless, I'd strongly recommend using [Shark](http://developer.apple.com/tools/sharkoptimize.html) instead of gprof - it's very easy to use and superior in pretty much every way to gprof - and doesn't require you to recompile your program.
gprof reports no time accumulated
[ "", "c++", "macos", "unix", "gprof", "" ]
On my Wordpress blog, I want to show additional content to people from Finland on all pages. Very much like the Feedback button at the left edge of the screen on [printfriendly.com](http://www.printfriendly.com/). How can I achieve this most reliably using PHP?
My suggestion would be to use the PHP GeoIP functions to determine the users location based on IP, and serve appropriate content based on that. More information on GeoIP can be found [here.](https://www.php.net/manual/en/ref.geoip.php)
In addition to the other answers (GeoIP), you may try to analyze the `Accept-Language` header field and serve the content to users that accept finnish language. You can modify the following function to parse `Accept-Language` header in PHP: * [How to select content type from HTTP Accept header in PHP](https://stackoverflow.com/questions/1049401/how-to-select-content-type-from-http-accept-header-in-php/1087498#1087498)
How can I show different content to website visitors from a specific country in PHP?
[ "", "php", "blogs", "selection", "" ]
I have a program, and in that program there is some variables (username and "privilege-level") that are only changed when the user logs on. Is there a way to "secure" these varaibles from memory-editing etc while the program runs, but the program is still able to change them if the user logs on with an other username. I thought it would work (haven't tested) to use either const or readonly, but is it still possible to change them when the user relogs? Also, is it possible to hash/encrypt strings used in the program, so that the user isn't able to find them by searching the memory (i.e. using Cheat Engine)?
If the software and user credentials are running on the user's machine, **it is impossible** to stop the user from changing values. If credentials and access are stored on a remote server, you can use that server and have the user only store a hashed token that expires after an arbitrary period of time. Use that token as a lookup to retrieve the user's profile information from the server. You'll still run into issues because anything that is done client-side can be manipulated/hacked. If you keep all of your logic on a central server, you can be more confident that things won't be cracked, however your system's performance will suffer. You need to weigh the pros and cons of a central server for security and performance and choose a balance that fits best for you.
You can't modify a const (ever) or readonly (after initialization) variable, so that will not work. The best option would probably be to wrap the logic that creates/initializes/sets those variables into a clean method and/or property that is set during the logon process. This will isolate that code, so it's at least easy to follow. As for encrypting strings - you can use [SecureString](http://msdn.microsoft.com/en-us/library/system.security.securestring.aspx) for handling that purpose at runtime. At compile time, you can obfuscate your code (many obfuscators support string encryption).
const/readonly vs. programs like Cheat Engine
[ "", "c#", "memory", "constants", "readonly", "" ]
I just read this: **<http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx>** I was under the impression that overwriting **`Object`** or **`Array`** only had an effect if you chose to use the constructor functions when creating **`arrays`**/**`objects`**, but, according to that article, it also has an effect on literal creation (**`{}`** and **`[]`**)... My logic: ``` Array = function(){ alert('Hi'); }; [1,2,3,4,5]; ([1,2,3,4,5]); var a = [1,2,3,4,5]; // ... // ... Nothing is alerted ``` So, am I going crazy or are there some implementation-specific quirks I'm not aware of?
As far as I know this is an issue with the ECMAScript specification and was fixed in all major browsers over a year ago. [Here](http://ejohn.org/blog/re-securing-json/) is a link that links you to the most relevant links ;) But to actually answer your question, yes, the `Object` and `Array` constructors are also invoked for literal creations. The *fix* browsers implemented just made these (and others) constant so they can't be overridden by custom scripts.
The EcmaScript 5 draft standardizes this fix Josef mentions. It specifies the behavior of the array constructor in terms of the value of the Array global at the time the context was created as described in section 11.1.4. > Semantics > > The production `ArrayLiteral : [ Elisionopt ]` is evaluated as follows: > > 1. Let array be the result of creating a new object as if by the expression > `new Array()` where `Array` is the standard built-in constructor with that name. Instead of the old ES 262 behavior which allowed for replacing the Array constructor: > Semantics > > The production `ArrayLiteral : [ Elisionopt ]` is evaluated as follows: > > 1. Create a new array as if by the expression `new Array()`. That said, do not rely on `[]` working sensibly on older interpreters.
Overwriting the Array constructor does not affect [], right?
[ "", "javascript", "security", "arrays", "xss", "" ]
I am currently attempting to use Lucene to search data populated in an index. I can match on exact phrases by enclosing it in brackets (i.e. "Processing Documents"), but cannot get Lucene to find that phrase by doing any sort of "Processing Document\*". The obvious difference being the wildcard at the end. I am currently attempting to use Luke to view and search the index. (it drops the asterisk at the end of the phrase when parsing) Adding the quotes around the data seems to be the main culprit as searching for document\* will work, but "document\*" does not Any assistance would be greatly appreciated
Not only does the QueryParser not support wildcards in phrases, PhraseQuery itself only supports Terms. [MultiPhraseQuery](http://lucene.apache.org/java/2_4_1/api/core/org/apache/lucene/search/MultiPhraseQuery.html) comes closer, but as its summary says, you still need to enumerate the IndexReader.terms yourself to match the wildcard.
Lucene 2.9 has [ComplexPhraseQueryParser](http://lucene.apache.org/java/2_9_0/api/all/org/apache/lucene/queryParser/complexPhrase/ComplexPhraseQueryParser.html) which can handle wildcards in phrases.
Lucene - Wildcards in phrases
[ "", "c#", ".net", "lucene", "lucene.net", "" ]
I have a DataTable object. Every column is of type string. Using LINQ, how can I get the maximum string length for every column?
The maximum string length for the whole table: ``` int? maxStringLength = dataTable.AsEnumerable() .SelectMany(row => row.ItemArray.OfType<string>()) .Max(str => str?.Length); ``` If you want maximum string length for **each** column, you could do: ``` List<int?> maximumLengthForColumns = Enumerable.Range(0, dataTable.Columns.Count) .Select(col => dataTable.AsEnumerable() .Select(row => row[col]).OfType<string>() .Max(val => val?.Length) ).ToList(); ```
With c# 6, you can prevent the exception by adding val?.Length ``` var maximumLengthForColumns = Enumerable.Range(0, dt.Columns.Count) .Select(col => dt.AsEnumerable() .Select(row => row[col]).OfType<string>() .Max(val => val?.Length )).ToList(); ```
How to get Max String Length in every Column of a Datatable
[ "", "c#", ".net", "linq", "datatable", "max", "" ]
I'm trying to use `std::string` instead of `char*` whenever possible, but I worry I may be degrading performance too much. Is this a good way of returning strings (no error checking for brevity)? ``` std::string linux_settings_provider::get_home_folder() { return std::string(getenv("HOME")); } ``` Also, a related question: when accepting strings as parameters, should I receive them as `const std::string&` or `const char*`?
Return the string. I think the better abstraction is worth it. Until you can measure a meaningful performance difference, I'd argue that it's a micro-optimization that only exists in your imagination. It took many years to get a good string abstraction into C++. I don't believe that Bjarne Stroustroup, so famous for his conservative "only pay for what you use" dictum, would have permitted an obvious performance killer into the language. Higher abstraction is good.
Return the string, like everyone says. *when accepting strings as parameters, should I receive them as `const std::string&` or `const char*`?* I'd say take any const parameters by reference, unless either they're lightweight enough to take by value, or in those rare cases where you need a null pointer to be a valid input meaning "none of the above". This policy isn't specific to strings. Non-const reference parameters are debatable, because from the calling code (without a good IDE), you can't immediately see whether they're passed by value or by reference, and the difference is important. So the code may be unclear. For const params, that doesn't apply. People reading the calling code can usually just assume that it's not their problem, so they'll only occasionally need to check the signature. In the case where you're going to take a copy of the argument in the function, your general policy should be to take the argument by value. Then you already have a copy you can use, and if you would have copied it into some specific location (like a data member) then you can move it (in C++11) or swap it (in C++03) to get it there. This gives the compiler the best opportunity to optimize cases where the caller passes a temporary object. For `string` in particular, this covers the case where your function takes a `std::string` by value, and the caller specifies as the argument expression a string literal or a `char*` pointing to a nul-terminated string. If you took a `const std::string&` and copied it in the function, that would result in the construction of two strings.
Should I return std::string or const char* from a getter?
[ "", "c++", "string", "return-value", "" ]
how can i select the current link via jquery if I have a div like this: ``` <div id='navigation'> <a href='users/home'>home</a> | <a href='projects/browse'>home</a> <a href='discussions/browse'>home</a> <a href='search/dosearch'>home</a> </div> ``` Note I've tried: ``` $(document).ready(function(){ $("#navigation a").click( function(event) { var clicked = $(this); // jQuery wrapper for clicked element // ... click-specific code goes here ... clicked.addClass('selected'); }); }); ``` But when I click on a link it selects a link and adds the class .selected but it reloads the page in order to navigate to a page and then it all disappears. Any tips? Thanks
This should work: ``` $(document).ready(function() { var loc = window.location.href; // The URL of the page we're looking at $('#navigation a').each(function() { if (loc.indexOf(this.href) !== -1) { // If the URL contains the href of the anchor $(this).addClass('selected'); // Mark it as selected } }); }); ``` It basically loops over the navigation items, and if the URL of the current page contains the href of the anchor, it adds the class `selected` to the anchor.
Yep, take the event from your `click()` callback arguments and use `e.preventDefault();` (see [there](http://docs.jquery.com/Events/click#fn)). Or `return false`. Or add a `target='_blank'` attribute to your links so that they open the link in some other page or tab, if you still want the link to be opened by the browser somewhere.
select current link
[ "", "javascript", "jquery", "" ]
How do I convert the string: `"Microsoft Windows XP Professional x64 Edition|C:\\WINDOWS|\\Device\\Harddisk4\\Partition1"` to `"Microsoft Windows XP Professional x64 Edition"` ...using regular expressions? I want to cut out all after `|` symbol. Is it easy to realise it via `Regex.Replace`? Where could I found syntax description for `Regex.Replace` patterns?
``` string str = @"Microsoft Windows XP Professional x64 Edition|C:\WINDOWS|\Device\Harddisk4\Partition1"; string str2 = str.Split('|')[0]; ``` str2 = "Microsoft Windows XP Professional x64 Edition"
You don't need a Regex for that. You can use substring: ``` var text = @"Microsoft Windows XP Professional x64 Edition|C:\WINDOWS|\Device\Harddisk4\Partition1"; text = text.Substring(0,text.IndexOf("|")); ```
How do I parse a string using C# and regular expressions?
[ "", "c#", "regex", "string", "parsing", "" ]
How do I check how much resources a java program uses? In java it is quite easy to create a big nice program that does practically everything you want it to, but a little side effect is that is also very easy to indirectly allocate to much memory and cpu cycles by mistake (i.e. let's just use "new" a couple of times in the wrong place). And if the program are supposed to run in a environment with very limited amount of resources, let's say something embedded or maybe a mobile phone (J2ME, Android etc etc), it is crucial to know how resource hungry your program is. Note: Since my main focus has been c the last years I could be missing something very simple here, so please don't assume to much ;) Thanks Johan
``` maxMemory(); totalMemory(); freeMemory(); ```
You appear to be somewhat confused about what you really need. In your question I sense some uneasiness about "how many resources will Java gobbly up behind my back to bite me later?". The answer to this is, to paraphrase Douglas Adams: "Dont' panic!" :-). Seriously, Java does not necessarily use much more resources than a "native" application, so you probably need not worry. A quick rundown: * Java programs will have a fixed memory overhead because of the JVM, i.e. even a trivial program will eat a few MB of memory. This however is will not grow for more complex software, so it's not usually a problem in practice. Also, several Java VMs running in parallel will share much of the RAM. * CPU: In general, a Java program will use the same CPU time as an equivalent native program. There's not fundamental reason why Java would need more. Garbage collection does have some overhead, but it's not usually significant (and manual memory management also has an overhead). * That said, things like accidental object retention or unneccessarily large objects can cause memory problems. But that's a problem you tackle when it arises. Short version: Don't worry, just do as you always do: Make it run, make it run correctly, make it run fast (by profiling).
How to check how much resources a java program uses?
[ "", "java", "optimization", "embedded", "" ]
``` java -Djava.library.path=../lib -classpath ../lib/wrappertest.jar:../lib/wrapper.jar:Service.jar:../lib/mysql-connector-java-3.0.17-ga-bin.jar -Dwrapper.key=Ksxtsmvr7iAmVJ-T -Dwrapper.port=32001 -Dwrapper.jvm.port.min=31000 -Dwrapper.jvm.port.max=31999 -Dwrapper.pid=1731 -Dwrapper.version=3.3.0 -Dwrapper.native_library=wrapper -Dwrapper.service=TRUE -Dwrapper.cpu.timeout=10 -Dwrapper.jvmid=1 org.tanukisoftware.wrapper.WrapperSimpleApp com.jobirn.Service ```
`-classpath` tells the VM how to find classes `-Dx=y` sets the system property `x` to value `y`; the exact effect depends on the property: * `java.library.path` is used to find native libraries * The rest (`wrapper.*`) looks like it's read by a third party library.
`-classpath` sets the class path for the JVM, i.e. the path where it will look for classes. The others (starting with `-D` ) all set [System properties](http://java.sun.com/javase/6/docs/api/java/lang/System.html#getProperties()). Of these, `java.library.path` sets the path where the JVM will look for native libraries. The other system properties are used to configure the [Java Service Wrapper](http://wrapper.tanukisoftware.org/doc/english/props-jvm.html) product.
what does each of these options mean?
[ "", "java", "" ]
In my form I have a set of input boxes where a user can input a value. On change of one of these boxes, the form automatically gets submitted. The problem now is however that a user stays in the last field, takes the mouse and presses the OK button (of another form) without leaving the textbox first. The change event doesn't get triggered and the old, incorrect values get passed to the next page. I want to trigger the onchange event after a few miliseconds of inactive keyboard. Just like most autocomplete plugins do. I think I could implement a timer that starts timing the moment you enter an input field and gets resetted everytime a keystroke is handled and then when it reaches zero the onchange event gets triggered. I'm not up for re-inventing the wheel and was wondering if such a function is available somewhere. Suggestions?
I had a similar problem and created a jQuery plugin currently in use in an internal application. It should trigger the change event after the user is done typing. If you are not using jQuery, the code is still adaptable to anything else. ``` jQuery.fn.handleKeyboardChange = function(nDelay) { // Utility function to test if a keyboard event should be ignored function shouldIgnore(event) { var mapIgnoredKeys = { 9:true, // Tab 16:true, 17:true, 18:true, // Shift, Alt, Ctrl 37:true, 38:true, 39:true, 40:true, // Arrows 91:true, 92:true, 93:true // Windows keys }; return mapIgnoredKeys[event.which]; } // Utility function to fire OUR change event if the value was actually changed function fireChange($element) { if( $element.val() != jQuery.data($element[0], "valueLast") ) { jQuery.data($element[0], "valueLast", $element.val()) $element.trigger("change"); } } // The currently running timeout, // will be accessed with closures var timeout = 0; // Utility function to cancel a previously set timeout function clearPreviousTimeout() { if( timeout ) { clearTimeout(timeout); } } return this .keydown(function(event) { if( shouldIgnore(event) ) return; // User pressed a key, stop the timeout for now clearPreviousTimeout(); return null; }) .keyup(function(event) { if( shouldIgnore(event) ) return; // Start a timeout to fire our event after some time of inactivity // Eventually cancel a previously running timeout clearPreviousTimeout(); var $self = $(this); timeout = setTimeout(function(){ fireChange($self) }, nDelay); }) .change(function() { // Fire a change // Use our function instead of just firing the event // Because we want to check if value really changed since // our previous event. // This is for when the browser fires the change event // though we already fired the event because of the timeout fireChange($(this)); }) ; } ``` Usage: ``` $("#my_input").handleKeyboardChange(300).change(function() { // value has changed! }); ```
I don't know that such a solution would be considered "re-inventing" anything. As you said, it sounds to be nothing more than a simple setTimeout once the page loads. After about 3,000 milliseconds, it runs form.submit(). I would probably restart the count-down with each keystroke too, to give the user enough time to make their entry.
Auto submit form after x mili seconds of inactive keyboard
[ "", "javascript", "jquery", "html", "timer", "onchange", "" ]
i can't understand one thing. In code, for example: ``` $filePath = 'http://wwww.server.com/file.flv'; if( file_exist($filePath) ) { echo 'yes'; } else { echo 'no'; } ``` Why does script return 'no', but when i copy that link to the browser it downloads?
The file\_exists() function is looking for a file or directory that exists from the point of view of the server's file system. If <http://www.server.com/> equates to /home/username/public\_html/ then you need to make your code: ``` $filename = '/home/username/public_html/file.flv'; if(file_exists($filename)) { //true branch } else { //false brach } ``` See <http://php.net/file_exists> for more info.
use ``` $_SERVER["DOCUMENT_ROOT"] ``` to assure the right filesystem path, not dependent by development or production system for example. in this case, it will be ``` $filePath = $_SERVER["DOCUMENT_ROOT"].'/file.flv'; ```
Php - troubles with files paths
[ "", "php", "file", "path", "" ]
I have installed on my computer C++Test only with UnitTest license (only Unit Test license) as a Visual Studio 2005 plugin ( cpptest\_7.2.11.35\_win32\_vs2005\_plugin.exe ). I have a sample similar to the following: ``` bool MyFunction(... parameters... ) { bool bRet = true; // do something if( some_condition ) { // do something bRet = CallToAFunctionThatCanReturnBothTrueAndFalse.... } else { bRet = false; // do something } if(bRet == false) { // do something } return bRet; } ``` In my case after running the coverage tool I have the following results (for a function similar to the previously mentioned): ``` [LC=100 BC=100 PC=75 DC=100 SCC=100 MCDC=50 (%)] ``` I really don't understand why I don't have 100% coverage when it comes to PathCoverage (PC). Also if someone who has experience with C++Test Parasoft could explain the low MCDC coverage for me that would be great. What should I do to increase coverage? as I'm out of ideas in this case. Directions to (some parts of) the documentation are welcome. Thank you, Iulian
This is a good reference on the various types of code coverage: <http://www.bullseye.com/coverage.html>. **MCDC**: To improve MCDC coverage you'll need to look at `some_condition`. Assuming it's a complex boolean expression, you'll need to look at whether you're exercising the necessary combinations of values. Specifically, each boolean sub-expression needs to be exercised true and false. **Path**: One of the things mentioned in the link above as being a disadvantage of path coverage is that many paths are impossible to exercise. That may be the case with your example.
I can't help with the specific tool you're using, but the general idea with path coverage is that each possible path through the code should be executed. If you draw a flowchart through the program, branching at each if/break/continue, etc. you should see which paths your tests are taking through the program. To get 100% (which isn't totally necessary, nor does it assure a perfect test) your test will have to go down every branch of the code, executing every line. Hope that helps.
Code coverage percentage not good
[ "", "c++", "c", "code-coverage", "" ]
...and that's wrong. Here's the error I get: **BUILD FAILED C:\_TraderPlatform\Clients\Open\Open\Java\Applets\PPDataTransporter\nbproject\build-impl.xml:338: The following error occurred while executing this line: C:\_TraderPlatform\Clients\Open\Open\Java\Applets\PPDataTransporter\nbproject\build-impl.xml:158: Unable to find a javac compiler; com.sun.tools.javac.Main is not on the classpath. Perhaps JAVA\_HOME does not point to the JDK. It is currently set to "C:\Program Files\Java\jre6"** I've set an environment variable called JAVA\_Home to point to: "C:\Program Files\Java\jdk1.6.0\_12" Javac.exe is definitely in **C:\Program Files\Java\jdk1.6.0\_12\bin** I've got %JAVA\_HOME%\Bin in my PATH variable. I've mucked around with the various 'JavaHome' settings under HKLM\SOFTWARE\JavaSoft and I'm now utterly stuck. All I wanted to do was build a Java applet from the command line using the build.xml that netbeans had knocked up for the project. Any ideas anybody?
Well ANT now works. What did I do? I removed it from c:\program files and 'reinstalled' it into "c:\ant" Seems like it doesn't like non 8.3 filenames or directories. Funnily enough I did this only because I misread the part of the manual that suggested ANT shouldn't be in non 8.3 style locations on 95/98/ME. I didn't spot the OS reference and gave it a go. I'm running Vista. Oh well... Thanks for your help guys.
In eclipse set the installed JRE setting to the JDK - in the project (project properties -> Java Build Path-> Libraries), or global default in preferences (Java->Installed JREs). The eclispe setting is stronger than the system variable.
Ant can't find Javac. No matter what I do it always claims JAVA_HOME is "C:\Program Files\Java\jre6"
[ "", "java", "ant", "java-home", "" ]
I need to work with some old C++ code that was developed in Visual C++ 6.0. Right now it's giving me compile errors galore. (For instance, "cannot open include file: 'iostream.h'"... because now it should say *#include <iostream>* rather than *#include <iostream.h>*). How can I work with this code without having to change it all over the place?
Unfortunately, there isn't a targetting feature in VS2008 that lets you do this. You'll just need to clean up your code. Luckily, VS2008 is far more standards-compliant than older versions of Visual C++ (in particular, VC 6). Getting the code clean should help in the future (you're less likely to have to worry about this later), as well as help if you ever decide to port to other platforms.
Problem is, VC6 was very very broken. You only got away with those compiler errors in vc6 because vc6 was so loose. Fix the errors, you'll be glad that you did-- I've done that conversion twice, and it makes the code much safer.
Can I make C++ in Visual Studio 2008 behave like an earlier version?
[ "", "c++", "visual-studio", "visual-c++", "" ]
I've got a video camera that I'm using to capture video; the camera records in H.264 at 720p resolution. I'd like to transcode this stuff to a simpler, smaller format; something that will work properly on digital photo frames that support video, for example. As well, I'd like to transcode to DVD format where possible, so I can burn DVDs for family members. And I'd like this process to be accessible from within Java, so I can set up a server at home to do the transcoding and I can manage the process over the Web from work. What's the best way to programmatically do transcoding from within Java? What libraries exist for H.264 support, and how do I access them?
You could try **ffmpeg for Java** <http://fmj-sf.net/ffmpeg-java/getting_started.php> ffmpeg is used for all kinds of transcoding/recoding ... it powers VLC!
Or you can use [Xuggler](http://www.xuggle.com/xuggler). It automatically integrates with the latest FFmpeg.
Automated transcoding H.264 video on Linux
[ "", "java", "video", "transcoding", "h.264", "" ]
Is there a really easy way I can take an array of JSON objects and turn it into an HTML table, excluding a few fields? Or am I going to have to do this manually?
I'm not sure if is this that you want but there is [jqGrid](http://www.trirand.com/blog/). It can receive JSON and make a grid.
Using jQuery will make this simpler. The following code will take an array of arrays and store convert them into rows and cells. ``` $.getJSON(url , function(data) { var tbl_body = ""; var odd_even = false; $.each(data, function() { var tbl_row = ""; $.each(this, function(k , v) { tbl_row += "<td>"+v+"</td>"; }); tbl_body += "<tr class=\""+( odd_even ? "odd" : "even")+"\">"+tbl_row+"</tr>"; odd_even = !odd_even; }); $("#target_table_id tbody").html(tbl_body); }); ``` You could add a check for the keys you want to exclude by adding something like ``` var expected_keys = { key_1 : true, key_2 : true, key_3 : false, key_4 : true }; ``` at the start of the getJSON callback function and adding: ``` if ( ( k in expected_keys ) && expected_keys[k] ) { ... } ``` around the tbl\_row += line. Edit: Was assigning a null variable previously Edit: Version based on [Timmmm](https://stackoverflow.com/users/265521/timmmm)'s [injection-free](https://stackoverflow.com/a/27821863/1272141) contribution. ``` $.getJSON(url , function(data) { var tbl_body = document.createElement("tbody"); var odd_even = false; $.each(data, function() { var tbl_row = tbl_body.insertRow(); tbl_row.className = odd_even ? "odd" : "even"; $.each(this, function(k , v) { var cell = tbl_row.insertCell(); cell.appendChild(document.createTextNode(v.toString())); }); odd_even = !odd_even; }); $("#target_table_id").append(tbl_body); //DOM table doesn't have .appendChild }); ```
Convert JSON array to an HTML table in jQuery
[ "", "javascript", "jquery", "json", "ajax", "html-table", "" ]
I would like my two applications to be able to send strings to each other and depending on the string "*do something*". This is for a *pre-proof-of-concept-mockup* type of thing so no security precautions needed and as inefficient as you want. So how do I do this with a minimum of work on my part. (You my dear fellow so user can work as hard as you please on the problem)
To what extent do they *really, really* need to be different applications? Could you have two separate projects which you launch from a third project, on different threads? ``` static void Main() { new Thread(Project1.Program.Main).Start(); new Thread(Project2.Program.Main).Start(); } ``` At that point you could use static variables (in a fourth project, referenced by both of the first two projects) to set up a shared communication channel between the two of them. You could have two [producer/consumer queues](http://pobox.com/~skeet/csharp/threads/deadlocks.shtml) (look half way down the page), one for each direction, for example. (You'd want to make the queue just use strings, or make a generic one and then use `ProducerConsumer<string>` for example. If you can use the .NET 4.0 beta, you could use a [`BlockingCollection<string>`](http://msdn.microsoft.com/en-us/library/dd267312(VS.100).aspx).) That would be *extremely hacky* - and without the isolation of even different `AppDomain`s you could see some interesting effects in terms of static variables accessed from both "applications" but that's effectively what you're trying to achieve. You should in no way take this implementation idea *anywhere* near production code - but for the situation you're describing, it sounds like "simple to implement" is the most important point. Just in case the project hierarchy doesn't make sense, here's a graphical representation ``` Launcher / \ / \ App 1 App 2 \ / \ / \ / Shared stuff ``` (To make it *even simpler* you could actually just use one project, and make its main method launch two different threads using methods within the same project. The idea of it being two applications is all smoke and mirrors by this point anyway. On the other hand, it might make it easier to *think* about the different apps by separating the projects.)
There are several mechanisms for this - probably the easiest to use is named pipes. I have not used it, but I understand the Windows Communication Foundation (WCF) is easy to use as well. There are a bunch of [articles on CodePoject](http://www.codeproject.com/KB/WCF/?cat=3) about WCF :) An advantage of using WCF is that it would let easily move your processes to different systems. (should that be practical for your scenario).
What is the easiest way for two separate C# .Net apps to talk to each other on the same computer
[ "", "c#", ".net", "" ]
I'm just starting my first Java Swing project(doing mainly web-based apps before) and try to understand how to build a proper architecture with separation of concerns between the MVC components. Just about any documentation I find goes very deep into the details of how each and every Swing UI widget works and can be used, but all examples just directly call program logic from a Class that extends, for example, JPanel - which seems odd and no good architecure. It would be best if that would be IDE-independent, but if such things come into play, it should be said that in the overall project, we have already Eclipse, JFormdesigner and JGoodies in use. I also see that JSR296 defines a framework that seems to address my concerns. Should I just use something that implements it?
This is an area of Java programming that is highly under-documented. As you mention, extending from JFrame or JDialog to develop a GUI is not a good design practice, yet you see it all over the place in sample code. JSR 296 is a useful starting place, but it's architecture has some serious problems. I do use JSR 296, but I have my own flavor of it, and consistently have to work around issues introduced by the framework design. I've long thought that there should be a discussion group/wiki/something focused on this topic. So far, I've found the listserv for various rich client libraries to be useful, but not comprehensive. Something to think about starting maybe, in my free time :-) So I can't provide any definitive resources for best practices in building swing applications. But I can give you some pointers to the toolkits and concepts that I've found that I use over and over again. Maybe these will be useful to you as you get going. Also, if enough people are interested in having a discussion about best practices, sharing code, etc... I'd be interested in being part of it. First, some absolutely critical libraries if you are going to do Swing development: 1. Binding - there are a number of libraries that do this (JGoodies, JSR295 which has spun off into an open source project called Better Beans Binding (BBB), Eclipse binding framework). I started years ago using JGoodies, but I have moved over to using BBB because I find it's approach to be more intuitive. I can't stress the advantages of the declarative coding approach that binding allows for - it will truly revolutionize your code 2. AppFramework (or some flavor thereof) - JSR 296 is the place to start here. As I mentioned above, it has some problems - if you do use JSR296, I strongly, strongly recommend that you try to avoid using the singleton that is at the core of the framework (other than as a source for injection of the framework components that you actually need). **EDIT** - since I wrote this, I've started using [GUTS](http://kenai.com/projects/guts/pages/Home) in our projects (this is a Guice based app framework - it started life as JSR 296, but has very little in common with it now). GUTS is still a young project, but it's worth taking a look at if you are considering frameworks. 3. GlazedLists - if you are doing anything in the UI that involves lists, tables or trees, you should take a hard look at GlazedLists. It's an incredible project (not just for Swing apps, but it really shines in that arena) 4. Validation - JGoodies has a very good validation library. Learn it, use it, be one with it. Real time validation is an incredibly important part of a modern Swing app. 5. MigLayout - The Mig layout manager is the best around. I strongly advise against the temptation of using an IDE GUI builder - learn MigLayout (it will take a couple of hours, tops), and code things up by hand. So those are the key, absolutely must-have libraries in my book. Now some concepts: A. Presentation Model - Martin Fowler has a lot of info on this design pattern. Long and short, it separates behavior from presentation at the GUI level. IF you are used to MVC, Presentation Model adds another layer of separation that is quite important to 'live' UIs. All of my views are backed by a corresponding presentation model. The end result is that the view code is really, really simple - focusing on two things: 1. Layout, and 2. Binding view components to the presentation model. That's it. B. Views are NOT subclasses of JPanel. Instead, I follow the JGoodies inspired technique of treating the View as a builder that creates JPanels. The basic pattern is: ``` public class MyView{ private MyPresentationModel model; private JButton okButton; private JButton cancelButton; ... public MyView(MyPresentationModel model){ this.model = model; } public JPanel buildView(){ initComponents(); // this method actually creates the okButton and cancelButton objects bindComponentsToModel(); // this method binds those objects to the PresentationModel JPanel p = new JPanel(new MigLayout()); p.add(...); ... return p; } } ``` This approach, followed religiously, allows incredibly rapid development of UIs that are easy to maintain. Note that we can use a given View to construct multiple JPanels that are all backed by the same PresentationModel - changes in one panel generated by the view will immediately be visible in another panel generated by the same view. C. Use Actions not event handlers. JSR 296 actually does a good job of making Actions easy to create and work with. D. Do long running operations (even something that takes 100ms) off of the EDT. JSR 296 makes this fairly easy with it's Task support - but there are a number of gotchas in 296's Task system when it comes to exception handling. If you have property changes that in turn result in long running events, be sure you think carefully about which thread those changes are going to occur on. Using Tasks is a big change to how you do development, but it's a really important area for any real Swing application - take the time to learn about it. E. Resource injection is important. Use it from the beginning (instead of telling yourself that you'll add it later) - if you find yourself calling setText() on a JLabel, it's time to sit back and call setName() instead, and add an entry to the resources file. JSR 296 makes this pretty easy to do if you are disciplined about it. I think that's enough for now - this is a highly complex subject with lot's of nuance. I've spent the past 7 or 8 years banging my head into things that don't work - and I'm continually finding better ways to do even the things that work well for me.
The Java Tutorial has a Swing trail that is very good for getting the concepts straight. If you are used to web apps, you will find the GUI-model rather confusing until you have this straight. <http://java.sun.com/docs/books/tutorial/uiswing/>
Where do I find a good, short, architecture-oriented introduction to Java Swing GUI for web developerrs?
[ "", "java", "swing", "architecture", "" ]
Is there any way that I could enjoy a `decodeValue()` function in PHP, too? I am posting those encodedValue values to a PHP file and I need to work with them in PHP as an array. How can I end up with a PHP array or something from the encoded state in Ext? Or, is there any other way that I could work the encoded values to be able to easily read them in PHP? Here is the function code: ``` decodeValue : function(cookie){ var re = /^(a|n|d|b|s|o)\:(.*)$/; var matches = re.exec(unescape(cookie)); if(!matches || !matches[1]) return; // non state cookie var type = matches[1]; var v = matches[2]; switch(type){ case "n": return parseFloat(v); case "d": return new Date(Date.parse(v)); case "b": return (v == "1"); case "a": var all = []; var values = v.split("^"); for(var i = 0, len = values.length; i < len; i++){ all.push(this.decodeValue(values[i])); } return all; case "o": var all = {}; var values = v.split("^"); for(var i = 0, len = values.length; i < len; i++){ var kv = values[i].split("="); all[kv[0]] = this.decodeValue(kv[1]); } return all; default: return v; } } ``` Thank you.
Below is my port to PHP. I used the DateTime class in lieu of Date as it is the closest PHP equivalent, but you could also use strftime() to get a Unix timestamp, or whatever method you prefer. Also, for type 'o' I return an array rather than an object, keyed by the object's parameter names. Here's the code: ``` function decodeValue($cookie) { $cookie = urldecode($cookie); $re = '/^(a|n|d|b|s|o)\:(.*)$/'; $matches = array(); preg_match($re, $cookie, $matches); if(!$matches || !$matches[1]) return; // non state cookie $type = $matches[1]; $v = $matches[2]; switch ($type){ case "n": return floatval($v); case "d": return new DateTime($v); case "b": return ($v == "1" ? true : false); case "a": $all = array(); $values = explode('^', $v); $len = count($values); for ($i = 0; $i < $len; $i++) { $all.push(decodeValue($values[$i])); } return $all; case "o": $all = array(); $values = explode('^', $v); $len = count($values); for($i = 0; $i < $len; $i++){ $kv = explode('=', $values[$i]); $all[$kv[0]] = decodeValue($kv[1]); } return $all; default: return $v; } } ```
Fixed a bug in the code. Now second level/third level array should work correctly. ``` function decodeValue($cookie) { $cookie = urldecode($cookie); $re = '/^(a|n|d|b|s|o)\:(.*)$/'; $matches = array(); preg_match($re, $cookie, $matches); if(!$matches || !$matches[1]) return $cookie; // non state cookie $type = $matches[1]; $v = $matches[2]; switch ($type){ case "n": return floatval($v); case "d": return new DateTime($v); case "b": return ($v == "1" ? true : false); case "a": $all = array(); $values = explode('^', $v); $len = count($values); for ($i = 0; $i < $len; $i++) { $all.array_push(decodeValue($values[$i])); } return $all; case "o": $all = array(); $values = explode('^', $v); $len = count($values); for($i = 0; $i < $len; $i++){ $kv = explode('=', $values[$i],2); if(count($kv)==1){ $all[] = decodeValue($kv[0]); }else{ $all[$kv[0]] = decodeValue($kv[1]); } } return $all; default: return $v; } } ```
ExtJS: DecodeValue in PHP
[ "", "php", "extjs", "decode", "" ]
I'd like to create an internal auto-property: ``` internal bool IP { get; protected internal set; } ``` I thought it would be possible to make the setter `protected` or `protected internal` - but I always get the error **accessibility modifier must be more restrictive than the property**. Isn't that the case? `Private` does not help me, here. **EDIT:** The question is: How do I implement an auto-property with a internal getter and a protected setter?
It's effectively `protected` or `internal`, not **and**. It's accessible **both** by derived classes and types in the same assembly. It's a common misconception to think `protected internal` means accessible only to derived classes in the same assembly.
At the .NET level, there are two similar but distinct access levels: * FamilyAndAssembly: more restrictive than either protected or internal * FamilyOrAssembly: less restrictive than either protected or internal "protected internal" in C# means FamilyOrAssembly; there's no modifier for FamilyAndAssembly. So, your `protected internal` setter is less restrictive than the `internal` overall property. What you could do is: ``` protected internal bool IP { internal get; set; } ``` But then your setter is less restricted than your getter, which is odd... Another (somewhat equivalent) alternative is: ``` internal bool IP { get; set; } protected void SetIP(bool ip) { this.IP = ip; } ```
Why is internal protected not more restrictive than internal?
[ "", "c#", "access-modifiers", "" ]
I have the following within an XHTML document: ``` <script type="text/javascript" id="JSBALLOONS"> function() { this.init = function() { this.wAPI = new widgetAPI('__BALLOONS__'); this.getRssFeed(); }; } </script> ``` I'm trying to select everything in between the two script tags. The `id` will always be JSBALLOONS if that helps. I know how to select that including the script tags, but I don't know how to select the contents excluding the script tags. The result of the regular expression should be: ``` function() { this.init = function() { this.wAPI = new widgetAPI('__BALLOONS__'); this.getRssFeed(); }; } ```
*(Updated post specifically for a Javascript solution.)* In Javascript, your code might look like this: ``` if (data.match(/<script[^>]+id="JSBALLOONS">([\S\s]*?)<\/script>/)) { inner_script = RegExp.$1; } ``` That part between parentheses `([\S\s]*?)` is saved by the regex engine and is accessible to you after a match is found. In Javascript, you can use `RegExp.$1` to reference to the matched part inside the script tags. If you have more than one of such a group, surrounded by `()`, you can refer to them with `RegExp.$2`, and so on, up to `RegExp.$9`. Javascript will not match newline characters by default, so that is why we have to use `([\S\s]*?)` rather than `(.*?)`, which may make more sense. Just to be complete, in other languages this is not necessary if you use the `s` modifier (`/.../s`). *(I have to add that regexes are typically very fragile when scraping content from HTML pages like this. You may be better off using the [jQuery](http://jquery.com/) framework to extract the contents.)*
What the gentleman means by $1 is "the value of the first capture group". When you enclose part of your regular expression in parentheses, it defines capture groups. You count them from the left to the right. Each opening parenthesis starts a new capture group. They can be nested. (There are ways to define sub expressions without defining capture groups - I forget the syntax.) In Perl, $1 is the magic variable holding the string matched by the first capture group, $2 is the string matched by the second, etc. Other languages may require you to call a method on the returned match object to get the Nth capture group. But back to molf's solution. Suppose he said to use this pattern instead: ``` /<script[^>]+id="JSBALLOONS">(.*)<\/script>/ ``` In this case, if you have more than one script element, this incorrect pattern will gobble them all up because it is greedy, a point worth explaining. This pattern will start with the first opening tag, match to its closing tag, keep going, and finally match the last . The magic in molf's solution is the question mark in (.\*?) which makes it non-greedy. It will return the shortest string that matches the pattern, hence not gobble up extra script elements.
What regular expression would match this data?
[ "", "javascript", "regex", "parsing", "xhtml", "html-parsing", "" ]
Hi I am trying to write a windows virtual com port driver which will divert the data to a IP address. any pointers, best practice will be of help?
I know of a Open source project called com0com which is virtual com port redirector. there is a subproject called com2tcp in that which you can look at[com0com](http://com0com.sourceforge.net/). otherwise for windows I am not sure you have any open source available Between there are commercially available software such as the one from Eltima and tactical software. there are few freewares too, you can search by the name comport redirector.
Check out this example of a User Mode Driver from Microsoft: Archive.org -> Microsoft.com: ~~[Virtual serial driver sample (FakeModem)](http://wayback.archive.org/web/20140824094640/http://code.msdn.microsoft.com/windowshardware/Virtual-serial-driver-8383ea42)~~ Github.com/Microsoft : [Virtual serial driver sample (FakeModem)](https://github.com/Microsoft/Windows-driver-samples/tree/master/serial/VirtualSerial)
how to write a virtual com port to TCP driver?
[ "", "c++", "serial-port", "tcp", "driver", "" ]
I would like to create a method which takes either a filename as a `string` or a `FileInfo` and adds an incremented number to the filename if the file exists. But can't quite wrap my head around how to do this in a good way. For example, if I have this FileInfo ``` var file = new FileInfo(@"C:\file.ext"); ``` I would like the method to give me a new FileInfo with *C:\file 1.ext* if *C:\file.ext* existed, and *C:\file 2.ext* if *C:\file 1.ext* existed and so on. Something like this: ``` public FileInfo MakeUnique(FileInfo fileInfo) { if(fileInfo == null) throw new ArgumentNullException("fileInfo"); if(!fileInfo.Exists) return fileInfo; // Somehow construct new filename from the one we have, test it, // then do it again if necessary. } ```
Lots of good advice here. I ended up using a method written by [Marc](https://stackoverflow.com/users/23354/marc-gravell) in [an answer to a different question](https://stackoverflow.com/questions/909521/how-to-solve-this-problem-storing-values-persistenly-of-files-in-a-directory/909545#909545). Reformatted it a tiny bit and added another method to make it a bit easier to use "from the outside". Here is the result: ``` private static string numberPattern = " ({0})"; public static string NextAvailableFilename(string path) { // Short-cut if already available if (!File.Exists(path)) return path; // If path has extension then insert the number pattern just before the extension and return next filename if (Path.HasExtension(path)) return GetNextFilename(path.Insert(path.LastIndexOf(Path.GetExtension(path)), numberPattern)); // Otherwise just append the pattern to the path and return next filename return GetNextFilename(path + numberPattern); } private static string GetNextFilename(string pattern) { string tmp = string.Format(pattern, 1); if (tmp == pattern) throw new ArgumentException("The pattern must include an index place-holder", "pattern"); if (!File.Exists(tmp)) return tmp; // short-circuit if no matches int min = 1, max = 2; // min is inclusive, max is exclusive/untested while (File.Exists(string.Format(pattern, max))) { min = max; max *= 2; } while (max != min + 1) { int pivot = (max + min) / 2; if (File.Exists(string.Format(pattern, pivot))) min = pivot; else max = pivot; } return string.Format(pattern, max); } ``` Only partially tested it so far, but will update if I find any bugs with it. ([Marc](https://stackoverflow.com/users/23354/marc-gravell)s code works nicely!) If you find any problems with it, please comment or edit or something :)
``` public FileInfo MakeUnique(string path) { string dir = Path.GetDirectoryName(path); string fileName = Path.GetFileNameWithoutExtension(path); string fileExt = Path.GetExtension(path); for (int i = 1; ;++i) { if (!File.Exists(path)) return new FileInfo(path); path = Path.Combine(dir, fileName + " " + i + fileExt); } } ``` Obviously, this is vulnerable to race conditions as noted in other answers.
How would you make a unique filename by adding a number?
[ "", "c#", "unique", "filenames", "" ]
I have a large system that I have coded and I wish to make the code (dare I say) more simple and easy to read. Unfortunately before this, I haven't used functions much. I have many different MySQL Queries that are run in my code, I feel that if I make the various displays into functions and store them in a separate file it would make the code much easier to maintain (actually, I know it would). The only thing I am wondering is, if this is a common practice and if you think that it is going to hurt me in the long run in terms of performance and other factors. Here is an example of what I currently am using: ``` $result = mysql_query("SELECT * FROM table"); while($row = mysql_fetch_array($result)){ /* Display code will go here */ } ``` As you can imagine this can get lengthy. I am thinking of making a function that will take the result variable, and accomplish this, and then return the results, as so: ``` $result = mysql_query("SELECT * FROM table"); dsiplayinfo($result); ``` Do you think this is the right way to go? **[Edit]** The functions would be very different because each of them needs to display the data in different ways. There are different fields of the database that need to be shown in each scenario. Do you feel that this approach is still a good one even with that factor? AKA Modular design is not being fully accomplished, but easy maintenance is.
Using more functions can be helpful, and it can be hurtful. In theory it moves you more towards modular design, meaning you can use a function over and over in multiple apps without having to re-write it. I would honestly encourage you to more toward larger conventions, like the [MVC Frameworks](http://en.wikipedia.org/wiki/Model_view_controller#PHP) out there. [Kohana](http://www.kohanaphp.com) is a great one. It uses things like Helpers for additional outside functionality, Models to query the database, and Controllers to perform all of your logic - and the end-result is passed on to the View to be formatted with HTML/CSS and spiced up with Javascript.
One thing you want to keep in mind is the principle of DRY: Don't Repeat Yourself. If you are finding there is a block of code that you are using multiple times, or is very similar that can be made the same, then it is a ideal candidate for being moved into a function.
PHP Function Abuse?
[ "", "php", "mysql", "coding-style", "" ]
**Hello!** I'm not even sure if this is possible, but hopefully it is in Java. I know I've done it in PHP by using variable variables and accessing a variable dynamically, but I read this isn't possible in Java in a different question. I have an array of strings which contains the state of checkboxes in my JSF GUI. If all checkboxes are set the array will then be filled with strings containing the value of different checkboxes. The labels and values of the checkboxes are built by looping through an array that looks like this: ``` private static final String[][] OVERVIEW_FIELDS = {{"ID", "requestid"}, {"Date added", "dob"}, {"Title", "requestTitle"}, {"Process", "processId"}, ..., ..., ...}; ``` Then I iterate through the array and make JSF SelectItems out of it: ``` for (int i = 0; i < OVERVIEW_FIELDS.length; i++) { SelectItem item = new SelectItem(OVERVIEW_FIELDS[i][0], OVERVIEW_FIELDS[i][1]); getFields().add(item); } ``` **The problem and current solution (hopefully someone can help me refactor it into something better:** ``` for (String item : getVisibleFields()) { if (item.equals("dob")) { setDob(true); } if (item.equals("requestTitle")) { setRequestTitle(true); } if (item.equals("processId")) { setProcessId(true); } if (...) { } } ``` And so on it continues for 11 booleans. I don't like this solution, and I see similar patterns in other beans in my system. Does anyone know if there's a better solution to this? The booleans control columns where I set their rendered field to true/false according to what the checkbox array contains. I was hoping in the JSF EL I could access the visibleFields variable and the contains method, thus returning either true or false if the object exist in array. This doesn't seem to work though and the EL doesn't give me access to the contains method. I'm currently using: ``` rendered="#{overviewFilterBean.dob}" ``` And I tried with this code: ``` rendered="#{overviewFilterBean.visibleFields.contains['dob']}"> ``` Now this led me to try to use my final array and set the booleans according to `getFields().contains(OVERVIEW_FIELDS[i][1])`, but how can I make this possible? Part real and part pseudo code follows (the solution I was aiming for now): ``` for (int i = 0; i < OVERVIEW_FIELDS.length; i++) { if (item.equals(OVERVIEW_FIELDS[i][1])) { setOVERVIEW_FIELDS[i][1](true); } } ``` **The big question:** Is there a way for me to use the value from `OVERVIEW_FIELDS[i][1]` to set the correct boolean variable or can I turn this into a Map maybe and use the JSF EL to check if key exists in the map? Thank you for your time, and sorry for writing such a lengthy question to get to a small point :/ **EDIT:** The reflection method resulted in 5 exceptions, big block of code handling them and also people said that its an expensive method. This leads me to believe that either my old solution or by using maps is the best way of doing it. Im gonna try the map solution =)
You could always store the values in a map rather. However if you want to invoke methods based on the methodname as a string, use reflection. See <http://java.sun.com/developer/technicalArticles/ALT/Reflection/>
With [reflection](http://java.sun.com/docs/books/tutorial/reflect/index.html), you can do: ``` for (String item : getVisibleFields()) { getClass().getMethod("get" + capitalize(item)).invoke(this, true); } ``` Exception handling and the `capitalize` method are left as an exercise to the reader ([`invoke`](http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object,%20java.lang.Object...)) throws a *lot* of exceptions).
How can I access methods based on strings in an array?
[ "", "java", "jsf", "variable-variables", "" ]
I'm having issues with a bit of code that I am writing in C#. I am sending a document using the MailMessage and SMTP components. I copy the files that I wish to send to a temp directory such as c:\temp, loop through the documents and attach them to the email. The email sends fine, however when I try to delete the files from the temp directory, I get the following error: > *The process can not access the file because it is being used by another process* I can't understand why this is happening. Below is the code that processes the documents ``` public void sendDocument(String email, string barcode, int requestid) { string tempDir = @"c:\temp"; //first we get the document information from the database. Database db = new Database(dbServer, dbName, dbUser, dbPwd); List<Document> documents = db.getDocumentByID(barcode); int count = 0; foreach (Document doc in documents) { string tempPath = tempDir + "\\" + doc.getBarcode() + ".pdf"; string sourcePath = doc.getMachineName() + "\\" + doc.getFilePath() + "\\" + doc.getFileName(); //we now copy the file from the source location to the new target location try { //this copies the file to the folder File.Copy(sourcePath, tempPath, false); } catch (IOException ioe) { count++; //the file has failed to copy so we add a number to the file to make it unique and try //to copy it again. tempPath = tempDir + "\\" + doc.getBarcode() + "-" + count + ".pdf"; File.Copy(sourcePath, tempPath, false); } //we now need to update the filename in the to match the new location doc.setFileName(doc.getBarcode() + ".pdf"); } //we now email the document to the user. this.sendEmail(documents, email, null); updateSentDocuments(documents, email); //now we update the request table/ db.updateRequestTable(requestid); //now we clean up the documents from the temp folder. foreach (Document doc in documents) { string path = @"c:\temp\" + doc.getFileName(); File.Delete(path); } } ``` I would of thought that the this.sendEmail() method would of sent the email before returning to the sendDocument method, as I think it is the smtp object that is causing the deletes to fail. This is the sendEmail method: ``` public void sendEmail(List<Document> documents, String email, string division) { String SMTPServer = null; String SMTPUser = null; String SMTPPwd = null; String sender = ""; String emailMessage = ""; //first we get all the app setting used to send the email to the users Database db = new Database(dbServer, dbName, dbUser, dbPwd); SMTPServer = db.getAppSetting("smtp_server"); SMTPUser = db.getAppSetting("smtp_user"); SMTPPwd = db.getAppSetting("smtp_password"); sender = db.getAppSetting("sender"); emailMessage = db.getAppSetting("bulkmail_message"); DateTime date = DateTime.Now; MailMessage emailMsg = new MailMessage(); emailMsg.To.Add(email); if (division == null) { emailMsg.Subject = "Document(s) Request - " + date.ToString("dd-MM-yyyy"); } else { emailMsg.Subject = division + " Document Request - " + date.ToString("dd-MM-yyyy"); } emailMsg.From = new MailAddress(sender); emailMsg.Body = emailMessage; bool hasAttachements = false; foreach (Document doc in documents) { String filepath = @"c:\temp\" + doc.getFileName(); Attachment data = new Attachment(filepath); emailMsg.Attachments.Add(data); hasAttachements = true; } SmtpClient smtp = new SmtpClient(SMTPServer); //we try and send the email and throw an exception if it all goes tits. try { if (hasAttachements) { smtp.Send(emailMsg); } } catch (Exception ex) { throw new Exception("EmailFailure"); } } ``` How to I get around this problem with a process hogging the file I wish to delete. I can delete the file(s) once the application finishes.
You're email message isn't being Disposed, try disposing it after you've sent it: ``` try { if (hasAttachements) { smtp.Send(emailMsg); } } catch ... finally { emailMsg.Dispose(); } ```
The first step is to figure out what process is holding onto the file in question. I would grab the SysInternals toolkit and use the handle.exe command to determine what process is holding onto the file. Without knowing what process has the file open, there is no way to fix this problem. Sysinternals Link: <http://technet.microsoft.com/en-us/sysinternals/default.aspx>
Deleting files fails as held by and existing process
[ "", "c#", "email", "delete-file", "" ]
Hi I am using a lot of temporary files in java and my problem is that they do not get deleted. Without having to implement my own handling of temporary file management (not hard I grant you but I am lazy plus with so many things to do If I can save reinventing the wheel for this all the better) is there a way to ensure the temp files on disk will get deleted in a fairly regular fashion. 1 - using File tmp = File.createTempFile(), sure I can say tmp.deleteOnExit() but If the thing runs in a service the only way it exits is when it either crashes (happens rarely), or when the system crashes (like when the drive is completely full of temp files and topples the cluster... oops !) Ideally, the instances created gets collected at some point by the garbage collector, and since there is a LOT of idle time in the application it would just be dandy if the GC could, well, finish it`s cleanup and actually delete the file on disk as well when dereferencing the instance from memory. the only way I see for now is overload the File class and add a finalized method... If I do that might as well go with my own temp file manager ! **So long story short, can I use the Garbage Collector to clean up system resources (ie files) as well ?** --- Thank you all for your answers. I accepted Christoffer's as it was the simplest to implement and is what I ended up doing. I guess being cleaned up after for so many years made me forget the basic housekeeping I was though to do the hard way in the good'ol days of C++.
Sure you can. The question is whether you really want to :) I've actually encountered this problem in the wild; as you noticed, cleaning up temporary files with deleteOnExit() is useless when running a service rather than an application. I found that the most stable solution was to restructure the program flow such that temporary files were created on a per-task basis, and explicitly deleted when no longer needed. If you do it any other way, i.e. if the program is unable to conclude whether a temporary file should be kept or discarded at any point during the execution, you might have a design problem. Wrapping files in some manager harness would just postpone the "real" solution ;)
You might want to look into [PhantomReference](http://java.sun.com/javase/6/docs/api/java/lang/ref/PhantomReference.html): > Phantom reference objects, which are enqueued after the collector determines that their referents may otherwise be reclaimed. Phantom references are most often used for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism.
How to use garbage collection to delete files?
[ "", "java", "temporary-files", "garbage-collection", "" ]
This should be a simple question, but I just can't recall the relevant API. A search on google with the term "[combine directory name php](http://www.google.com.my/search?hl=en&safe=off&rlz=1C1GGLS_enMY291MY303&q=combine+directory+name+php&btnG=Search&meta=)" ~~doesn't yield any results . So I guess I am doing both myself and the programming community a service by asking this question.~~ this is now the top entry returned by Google and DDG! How to combine directory and file name to form a full file path in PHP? Let's say the directory name is "`D:\setup program`", and the file name is "`mj.txt`". The method should return me, on Windows "`D:\setup program\mj.txt`". Of course the method should return the correct file path in Linux or other OS. The related function in .Net is [Path.Combine](http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx), but in PHP, I couldn't recall that, even though I must have seen it before.
``` $filepath = $path . DIRECTORY_SEPARATOR . $file; ``` Although in newer versions of PHP it doesn't matter which way the slashes go, so it is fine to always use forward slashes. You can get a correct absolute path using [`realpath()`](http://php.net/realpath), this will also remove things like extra unnecessary slashes and resolve references like `../`. It will return false if the path is not valid.
I think the most clean and flexible way to do it would be using the join function plus the DIRECTORY\_SEPARATOR constant: ``` $fullPath = join(DIRECTORY_SEPARATOR, array($directoryPath, $fileName)); ```
Combine directory and file name in PHP ( equivalent of Path.Combine in .Net)
[ "", "php", "" ]