Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I did a quick google on implementing clone() in Java and found: <http://www.javapractices.com/topic/TopicAction.do?Id=71> It has the following comment: > copy constructors and static factory methods provide an alternative to clone, and are much easier to implement. All I want to do is make a deep copy. Implementing clone() seems to make a lot of sense, but this highly google ranked article makes me a bit afraid. Here are the issues that I've noticed: ## Copy constructors don't work with Generics. Here's some pseudo-code that won't compile. ``` public class MyClass<T>{ .. public void copyData(T data){ T copy=new T(data);//This isn't going to work. } .. } ``` Sample 1: Using a copy constructor in a generic class. ## Factory methods don't have standard names. It's quite nice to have an interface for reusable code. ``` public class MyClass<T>{ .. public void copyData(T data){ T copy=data.clone();//Throws an exception if the input was not cloneable } .. } ``` Sample 2: Using clone() in a generic class. I noticed that clone is not a static method, but wouldn't it still be necessary to make deep copies of all the protected fields? When implementing clone(), the extra effort to throw exceptions in non-cloneable subclasses seems trivial to me. Am I missing something? Any insights would be appreciated.
Basically, [clone is broken](http://www.artima.com/intv/bloch13.html). Nothing will work with generics easily. If you have something like this (shortened to get the point across): ``` public class SomeClass<T extends Copyable> { public T copy(T object) { return (T) object.copy(); } } interface Copyable { Copyable copy(); } ``` Then with a compiler warning you can get the job done. Because generics are erased at runtime, something that does a copy is going to have a compiler warning generating cast in it. It is not avoidable in this case.. It is avoidable in some cases (thanks, kb304) but not in all. Consider the case where you have to support a subclass or an unknown class implementing the interface (such as you were iterating through a collection of copyables that didn't necessarily generate the same class).
There is also the Builder pattern. See Effective Java for details. I don't understand your evaluation. In a copy constructor you are fully aware of the type, why is there a need to use generics? ``` public class C { public int value; public C() { } public C(C other) { value = other.value; } } ``` There was a similar question recently [here](https://stackoverflow.com/questions/1052340/what-is-wrong-with-this-clone/1052352#1052352). ``` public class G<T> { public T value; public G() { } public G(G<? extends T> other) { value = other.value; } } ``` A runnable sample: ``` public class GenTest { public interface Copyable<T> { T copy(); } public static <T extends Copyable<T>> T copy(T object) { return object.copy(); } public static class G<T> implements Copyable<G<T>> { public T value; public G() { } public G(G<? extends T> other) { value = other.value; } @Override public G<T> copy() { return new G<T>(this); } } public static void main(String[] args) { G<Integer> g = new G<Integer>(); g.value = 1; G<Integer> f = g.copy(); g.value = 2; G<Integer> h = copy(g); g.value = 3; System.out.printf("f: %s%n", f.value); System.out.printf("g: %s%n", g.value); System.out.printf("h: %s%n", h.value); } } ```
clone() vs copy constructor vs factory method?
[ "", "java", "clone", "" ]
I'm coming from the Java world and are building a small c++ program at the moment. I have an object that does some work and then returns the result of the work as a list. Now a day later i changed the behavior of the object to save the results in a set to avoid duplicates in the container. But I can't simply return the set because I used a list for the interface in the first time. Is there a common container interface that I can use to specify the interface of my object and forget about the container type I use internally? At the moment I'm creating a set adding all the values and then creating a list from the set: ``` return std::list<foo>(this->mySet.begin(), this->mySet.end()) ``` Seems a little strange.
The concept of a container is enbodied by iterators. As you have seen hard coding a specific type of container is probably not what you want. So make your class return iterators. You can then re-use the conatiners iterators. ``` class MyClass { private: typedef std::list<int> Container; public: typedef Container::iterator iterator; typedef Container::const_iterator const_iterator; iterator begin() {return myData.begin();} const_iterator begin() const {return myData.begin();} iterator end() {return myData.end();} const_iterator end() const {return myData.end();} private: Container myData; }; ``` Now when you change the Container type from std::list to std::set nobody needs to know. Also by using the standard names that other containers use your class starts to look like any other container from the STL. Note: A method that returns a const\_iterator should be a const method.
The whole C++- standard library including its containers is - unlike Java - not interface (inheritance, polymorphism)- but template-based (for the sake of efficiency). You could create a polymorphic wrapper around your collection but this isn't the C++-way. The simplest solution is just to simplify the programm with some type aliases: ``` #include <iostream> #include <list> #include <vector> using namespace std; class Test { private: typedef vector<int> Collection; Collection c; public: typedef Collection::const_iterator It; void insert(int Item) { c.push_back(Item); } It begin() const { return c.begin(); } It end() const { return c.end(); } }; int main() { Test foo; foo.insert(23); foo.insert(40); for (Test::It i = foo.begin(); i != foo.end(); ++i) cout << *i << endl; return 0; } ``` You can now change the `Collection`-typedef without having to change anything else. (Note: If you make `Collection` public, the user will be able to refer the the type you used explicitly)
Interface/Superclass for Collections/Containers in c++
[ "", "c++", "collections", "interface", "language-design", "containers", "" ]
I'm using the built-in Joomla! breadcrumb module, but nothing shows up but "Home" on all my pages. I looked @ the internals of the module, and inside /modules/mod\_breadcrumbs/helper.php ``` $pathway = &$mainframe->getPathway(); $items = $pathway->getPathWay(); ``` When I do a print\_r on $items, the only thing in the array is "Home". My menus and sub-menus work fine, my urls show up as <http://foobar.com/foo/bar>
I failed to set a default menu, this caused all the problems.
I think you need to check your menu structure. I don't remember exactly how the breadcrumbs work, but it should run off the main menu. Do you need to make your menu items sub-menu items of "Home"? EDIT: on second thoughts, I'm pretty sure it runs off the Section/Category listings. So you'd need to categorise all your articles.
Joomla breadcrumbs only shows "Home"
[ "", "php", "joomla", "joomla1.5", "" ]
I am reading at the time the "Effective C++" written by *Scott Meyers* and came across the term "translation unit". Could somebody please give me an explanation of the following: 1. What exactly is it? 2. When should I consider using it while programming with C++? 3. Is it C++ only, or can it be used with other programming languages? I might already use it without knowing the term...
From [here](http://www.efnetcpp.org/wiki/Translation_unit): ([wayback machine link](http://web.archive.org/web/20090427201018/http://efnetcpp.org/wiki/Translation_unit)) > According to [standard C++](http://www.efnetcpp.org/wiki/ISO/IEC_14882) ([wayback machine link](http://web.archive.org/web/20070403232333/http://www.efnetcpp.org/wiki/ISO/IEC_14882)) : > A translation unit is the basic unit > of compilation in C++. It consists of > the contents of a single source file, > plus the contents of any header files > directly or indirectly included by it, > minus those lines that were ignored > using conditional preprocessing > statements. > > A single translation unit can be > compiled into an object file, library, > or executable program. > > The notion of a translation unit is > most often mentioned in the contexts > of the One Definition Rule, and > templates.
A translation unit is for all intents and purposes a file (.c/.cpp), *after* it's finished including all of the header files. <http://web.archive.org/web/20091213073754/http://msdn.microsoft.com/en-us/library/bxss3ska(VS.80).aspx>
What is a "translation unit" in C++?
[ "", "c++", "c++-faq", "" ]
I am trying to figure out how to use Apache Commons IO [`DirectoryWalker`](http://commons.apache.org/io/api-release/org/apache/commons/io/DirectoryWalker.html). It's pretty easy to understand how to subclass `DirectoryWalker`. But how do you start executing it on a particular directory?
It looks like the subclass should provide a public method that calls walk().
Just to expand on this answer since I was puzzled at first of how to use the class as well and this question came up on google when I was looking around. This is just an example of how I used it (minus some things): ``` public class FindConfigFilesDirectoryWalker extends DirectoryWalker { private static String rootFolder = "/xml_files"; private Logger log = Logger.getLogger(getClass()); private static IOFileFilter filter = FileFilterUtils.andFileFilter(FileFilterUtils.fileFileFilter(), FileFilterUtils.suffixFileFilter("xml")); public FeedFileDirectoryWalker() { super(filter, -1); } @SuppressWarnings("unchecked") @Override protected void handleFile(final File file, final int depth, final Collection results) throws IOException { log.debug("Found file: " + file.getAbsolutePath()); results.add(file); } public List<File> getFiles() { List<File> files = new ArrayList<File>(); URL url = getClass().getResource(rootFolder); if (url == null) { log.warn("Unable to find root folder of configuration files!"); return files; } File directory = new File(url.getFile()); try { walk(directory, files); } catch (IOException e) { log.error("Problem finding configuration files!", e); } return files; } } ``` And then you would just invoke it via the public method you created, passing in any arguments that you may want: ``` List<File> files = new FindConfigFilesDirectoryWalker().getFiles(); ```
How to use Apache Commons DirectoryWalker?
[ "", "java", "apache-commons", "" ]
I'm trying to validate an XML file against a number of different schemas (apologies for the contrived example): * a.xsd * b.xsd * c.xsd c.xsd in particular imports b.xsd and b.xsd imports a.xsd, using: `<xs:include schemaLocation="b.xsd"/>` I'm trying to do this via Xerces in the following manner: ``` XMLSchemaFactory xmlSchemaFactory = new XMLSchemaFactory(); Schema schema = xmlSchemaFactory.newSchema(new StreamSource[] { new StreamSource(this.getClass().getResourceAsStream("a.xsd"), "a.xsd"), new StreamSource(this.getClass().getResourceAsStream("b.xsd"), "b.xsd"), new StreamSource(this.getClass().getResourceAsStream("c.xsd"), "c.xsd")}); Validator validator = schema.newValidator(); validator.validate(new StreamSource(new StringReader(xmlContent))); ``` but this is failing to import all three of the schemas correctly resulting in cannot resolve the name 'blah' to a(n) 'group' component. I've validated this successfully using **Python**, but having real problems with **Java 6.0** and **Xerces 2.8.1**. Can anybody suggest what's going wrong here, or an easier approach to validate my XML documents?
So just in case anybody else runs into the same issue here, I needed to load a parent schema (and implicit child schemas) from a unit test - as a resource - to validate an XML String. I used the Xerces XMLSchemFactory to do this along with the Java 6 validator. In order to load the child schema's correctly via an include I had to write a custom resource resolver. Code can be found here: <https://code.google.com/p/xmlsanity/source/browse/src/com/arc90/xmlsanity/validation/ResourceResolver.java> To use the resolver specify it on the schema factory: ``` xmlSchemaFactory.setResourceResolver(new ResourceResolver()); ``` and it will use it to resolve your resources via the classpath (in my case from src/main/resources). Any comments are welcome on this...
<http://www.kdgregory.com/index.php?page=xml.parsing> section '**Multiple schemas for a single document**' *My solution based on that document:* ``` URL xsdUrlA = this.getClass().getResource("a.xsd"); URL xsdUrlB = this.getClass().getResource("b.xsd"); URL xsdUrlC = this.getClass().getResource("c.xsd"); SchemaFactory schemaFactory = schemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); //--- String W3C_XSD_TOP_ELEMENT = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\">\n" + "<xs:include schemaLocation=\"" +xsdUrlA.getPath() +"\"/>\n" + "<xs:include schemaLocation=\"" +xsdUrlB.getPath() +"\"/>\n" + "<xs:include schemaLocation=\"" +xsdUrlC.getPath() +"\"/>\n" +"</xs:schema>"; Schema schema = schemaFactory.newSchema(new StreamSource(new StringReader(W3C_XSD_TOP_ELEMENT), "xsdTop")); ```
Validate an XML File Against Multiple Schema Definitions
[ "", "java", "xsd", "xerces", "" ]
using c# (asp.net) i'm programmatically creating several drop down lists (random number). the user selects a particular value from each list and i need to save the user selected value. if i try to save the data to session state by using a button click event it says the drop down list object hasn't been created. (obviously cuz i'm creating the drop down lists in the page load event under !IsPostBack.) if i try to save the data to session state in the page load event under IsPostBack i only get the first value from each list. (obviously cuz when the page is recreated after the postback, the drop down lists have been recreated and the user entered data is lost). How do i save the user selected value from the drop down lists when a button is clicked? i'm doing this in the code behind file.
As John Saunders said, you have to recreate all of your DropDownList controls on every postback. Additionally, you have to create them *before* state is restored. That means that "under !IsPostBack" in the page load event is already too late. Move it up to Page Init.
You have to recreate all of the dropdowns on every postback.
How to save user entered data to session state from a dynamically created control?
[ "", "c#", "asp.net", "session-state", "" ]
[PEP 8](http://www.python.org/dev/peps/pep-0008/) says: > * Imports are always put at the top of the file, just after any module > comments and docstrings, and before module globals and constants. On occation, I violate PEP 8. Some times I import stuff inside functions. As a general rule, I do this if there is an import that is only used within a single function. Any opinions? **EDIT (the reason I feel importing in functions can be a good idea):** Main reason: It can make the code clearer. * When looking at the code of a function I might ask myself: "What is function/class xxx?" (xxx being used inside the function). If I have all my imports at the top of the module, I have to go look there to determine what xxx is. This is more of an issue when using `from m import xxx`. Seeing `m.xxx` in the function probably tells me more. Depending on what `m` is: Is it a well-known top-level module/package (`import m`)? Or is it a sub-module/package (`from a.b.c import m`)? * In some cases having that extra information ("What is xxx?") close to where xxx is used can make the function easier to understand.
In the long run I think you'll appreciate having most of your imports at the top of the file, that way you can tell at a glance how complicated your module is by what it needs to import. If I'm adding new code to an existing file I'll usually do the import where it's needed and then if the code stays I'll make things more permanent by moving the import line to the top of the file. One other point, I prefer to get an `ImportError` exception before any code is run — as a sanity check, so that's another reason to import at the top. You can use a linter to check for unused modules.
There are two occasions where I violate PEP 8 in this regard: * Circular imports: module A imports module B, but something in module B needs module A (though this is often a sign that I need to refactor the modules to eliminate the circular dependency) * Inserting a pdb breakpoint: `import pdb; pdb.set_trace()` This is handy b/c I don't want to put `import pdb` at the top of every module I might want to debug, and it easy to remember to remove the import when I remove the breakpoint. Outside of these two cases, it's a good idea to put everything at the top. It makes the dependencies clearer.
Is it pythonic to import inside functions?
[ "", "python", "conventions", "" ]
I know there's been a handful of questions regarding std::ifstream::open(), but the answers didn't solve my problem. Most of them were specific to Win32, and I'm using SDL, not touching any OS-specific functionality (...that's not wrapped up into SDL). The problem is: std::ifstream::open() doesn't seem to work anymore since I've switched from Dev-C++ to Code::Blocks (I've been using the same MinGW-GCC back-end with both), and from Windows XP to Vista. (It also works perfectly with OS X / xcode (GCC back-end).) My project links against a static library which #includes <string>, <iostream>, <fstream> and <cassert>, then a call is made to functionality defined in the static library, which in turn calls std::ifstream::open() (this time, directly). Following this, the stream evaluates to false (with both the implicit bool conversion operator and the good() method). Code: ``` #include "myStaticLibrary.hpp" int main(int argc, char **argv) { std::string filename("D:/My projects/Test/test.cfg"); std::cout << "opening '" << filename << "'..." << std::endl; bool success(false); // call to functionality in the static library { std::ifstream infile(filename.c_str()); success = infile.good(); // ... } // success == false; // ... return 0; } ``` stdcout.txt says: > opening 'D:/My projects/Test/test.cfg'... When I open stdcout.txt, and copy-paste the path with the filename into Start menu / Run, the file is opened as should be (I'm not entirely sure how much of diagnostic value this is though; also, the address is converted to the following format: file:///D:/My%20projects/test/test.cfg). I've also tried substituting '/'s with the double backslash escape sequence (again, slashes worked fine before), but the result was the same. It *is* a debug version, but I'm using the whole, absolute path taken from main()'s argv[0]. Where am I going wrong and what do I need to do to fix it?
I have overseen the importance of the fact that the function in question has `close()`d the stream without checking if it `is_open()`. The fact that it will set the stream's fail\_bit (causing it to evaluate to false) was entirely new to me (it's not that it's an excuse), and I still don't understand why did this code work before. Anyway, the c++ reference is quite clear on it; the problem is now solved.
1. Please create a minimal set that recreates the problem. For example, in your code above there's parsing of argv and string concatentation, which do not seem like a necessary part of the question. A minimal set would help you (and us) see exactly what's going wrong, and not be distracted by questions like "what's GetPath()?". 2. Try to do this instead of `assert(infile.good())`: assert(infile);
Windows std::ifstream::open() problem
[ "", "c++", "path", "debugging", "ifstream", "" ]
I would like to be able to use the same Session variable when transferring to another app. Does Response.Redirect use the same session or start a new one? I am using c#, aspnet 3.5
`Response.Redirect` does nothing with the session. The session is tied (typically) to a cookie associated with the URI of the web app. If you switch to another web app on another server or a separate URI, the session will not carry over even if you managed to preserve the cookie. Can you clarify what problem it is you're trying to solve?
`Response.Redirect` sends an Http Response to the browser with a status code of `302 Found` and a header `Location: {redirection-url}`. The browser receives this response, and knows to send a new request to the `{redirection-url}` when it receives a response with a status code of `302 Found`. That's all that happens. `Response.Redirect` does not start or stop or have anything to do with any sessions.
Does Response.Redirect use the same session or start a new one?
[ "", "c#", "asp.net", "session", "response.redirect", "" ]
I've got some aspx pages being created by the user from a template. Included is some string replacement (anyting with ${fieldname}), so a portion of the template looks like this: ``` <% string title = @"${title}"; %> <title><%=HttpUtility.HtmlEncode(title) %></title> ``` When an aspx file is created from this template, the ${title} gets replaced by the value the user entered. But obviously they can inject arbitrary HTML by just closing the double quote in their input string. How do I get around this? I feel like it should be obvious, but I can't figure a way around this. I have no control over the template instantiating process -- I need to accept that as a given.
Can you store their values in another file(xml maybe) or in a database? That way their input is not compiled into your page. Then you just read the data into variables. Then all you have to worry about is html, which your html encode would take care of.
If they include a double quote in their string, that will not inject arbitrary HTML, but arbitrary code, which is even worse. You can use a regex to filter the input string. I would use an inclusive regex rathern than trying to exclude dangerous chars. Only allow them A-Za-z0-9 and whitespace.
string replacement in page created from template
[ "", "c#", "asp.net", "templates", "string", "escaping", "" ]
I'd like to generate the classes the xsd.exe way and not the **linq**toxsd way.
Look at the [System.Xml.Serialization.XmlCodeExporter](http://msdn2.microsoft.com/en-us/library/system.xml.serialization.xmlcodeexporter) class. **UPDATE** (in case John Saunders didnt bother reading further) > "Xsd.exe uses XmlCodeExporter to > generate classes from XML Schema > Definition (XSD) documents."
Try [Xsd2Code](http://www.codeplex.com/Xsd2Code) Seems to be the best free/Open source tool out there. Good integration with VS2010 It's working great for me.
How to programmatically generate .NET classes from XSD? (Like xsd.exe do)
[ "", "c#", ".net", "xml", "xsd", "schema", "" ]
Directories some\_folder, some\_folder\_1, some\_folder\_2, and some\_folder\_3 don't exist initially. ``` File folder1 = new File("some_folder/some_folder_1"); File folder2 = new File("some_folder/some_folder_2"); File folder3 = new File("some_folder/some_folder_3"); if(!folder1.exists()) { folder1.mkdirs(); } if(!folder2.exists()) { folder2.mkdirs(); } if(!folder3.exists()) { folder3.mkdirs(); } ``` Would that be a good way to do this?
Don't use the path separator, use the correct constructor instead: ``` File folder1 = new File("some_folder", "some_folder_1"); if (!folder1.exists()) { folder1.mkdirs(); // returns a boolean } ```
Well you don't need the tests - mkdirs just returns `false` if the directory already exists. I'd prefer to use one "base" file for `some_folder` to avoid hard-coding the slash, even though a forward slash is *likely* to work on most popular platforms :) ``` File baseFolder = new File("some_folder"); new File(baseFolder, "some_folder_1").mkdirs(); new File(baseFolder, "some_folder_2").mkdirs(); new File(baseFolder, "some_folder_3").mkdirs(); ``` Note that this won't throw any exceptions if the names already exist but as *files* instead of folders...
Java: Proper Way of Making Directories
[ "", "java", "directory", "createfile", "" ]
I am getting the following exception when I try to update an object: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: ...... Can anyone help??? The object that I am trying to update has the 'lazy' attribute set to false in the mapping file. Seems like hibernate is expecting me to save child objects before it flushes the update??? EDIT (ADDED): ``` <hibernate-mapping> <class name="utils.message.Message" table="messages"> <id name="id" column="message_id"> <generator class="native" /> </id> <property name="message_text" column="message_text" /> <property name="message_file" column="message_file" /> <property name="is_active" column="is_active" type="boolean"/> <property name="is_global" column="is_global" type="boolean"/> <property name="start" column="start" type="java.util.Date"/> <property name="end" column="end" type="java.util.Date"/> <property name="last_updated" column="last_updated" type="java.util.Date"/> <many-to-one name="last_updated_by" class="utils.user.User" column="last_updated_by" lazy="false"/> <many-to-one name="healthDepartment" class="utils.healthdepartment.HealthDepartment" column="health_department_id" lazy="false"/> </class> </hibernate-mapping> ```
App is in a Spring environment. Fix: to run update from within Hibernate environment.
TransientObjectException occurs when you save an object which references another object that is transient (meaning it has the "default" identifier value, frequently null) and then flush the Session. This commonly happens when you are creating an entire graph of new objects but haven't explicitly saved all of them. There are two ways to work around this: 1. As you suggest, you could use cascading of saves to other associated objects. However, cascading wasn't really intended as a workaround for TOE but rather as a convenience for saving a group of related objects that are frequently manipulated together. If you detach your objects without its full set of associated data and then save it with cascading enabled, you could inadvertently delete data you don't want to lose. 2. Ensure that all transient objects in your graph are explicitly saved as part of your unit of work. This is really just a case of understanding how your application will be creating an object graph and what entities are transient and which might be persistent or detached. I would recommend reading this entire chapter from the Hibernate docs to understand fully the terminology of transient, persistent and detached: <http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html>
Hibernate Exception help: TransientObjectException
[ "", "java", "hibernate", "" ]
Here's the code: ``` ProductList products = xxx.GetCarProducts(productCount); List<CarImageList> imageList = new List<CarImageList>(); foreach(Product p in products) { string imageTag = HttpUtility.HtmlEncode(string.Format(@"<img src=""{0}"" alt="""">", ImageUrl(p.Image, false))); imageList.Add(new CarImageList{ImageTag = imageTag}); i++; } ``` Under the covers ProductList is really defined like this: ``` public class ProductList : List<Product> { static Random rand = new Random(); public ProductList Shuffle() { ProductList list = new ProductList(); list.AddRange(this); for (int i = 0; i < list.Count; i++) { int r = rand.Next(list.Count - 1); Product swap = list[i]; list[i] = list[r]; list[r] = swap; } return list; } public Product FindById(int id) { foreach (Product p in this) if (p.Id == id) return p; return null; } public Product GetRandom() { int r = rand.Next(this.Count - 1); return this[r]; } } ``` so why do I get the error when I try to foreach through the ProductList instance? Cannot convert type 'xxx.Product' to 'Product' is the error I get. But if ProductList is really List why in the world would it have an issue with conversion?
It seems to me that `Product` in the context of the first example is a different `Product` type than `Product` in the context of the second example. Are you sure you have your namespaces sorted out?
I think your `xxx.GetCarProducts(productCount);` may be returning a reference to `List<Product>` which is less defined than your `ProductList` class, meaning in your GetCarProducts method you probably do new `List<Product>` instead of `new ProductList()`. If anything can you post the body of `GetCarProducts`
Trouble iterating Generic list with custom object
[ "", "c#", "" ]
We are importing from CSV to SQL. To do so, we are reading the CSV file and writing to a temporary .txt file using a schema.ini. (I'm not sure yet exactly why are are writing to this temporary file, but that's how the code currently works). From there, we are loading a DataTable via OleDB using the following connection string (for ASCII files). ``` "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sPath + ";Extended Properties=\"text;HDR=Yes;FMT=Delimited\""; ``` The problem we are having is that fields with more than 255 characters get truncated. I've read online about this problem and it seems that by default, text fields get truncated thusly. I set my registry settings `ImportMixedTypes=Majority Type` and `TypeGuessRows=0` in `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Excel` , hoping that `mycolumns` will no longer be interpreted as text. After doing that, the temporary txt file is being written correctly from the CSV file, but when I call `dataAdapter.Fill`, the resulting DataTable still has a truncated value. Here is the column definition in question. CommaDelimited#txt Notes 2 false 234 true 130 0 0 Any help would be appreciated. At this time, I'm not interested in using any 3d party code to solve this problem, there must be a way using built in tools. Here is the table definition: ``` <Columns> <TABLE_NAME>CommaDelimited#txt</TABLE_NAME> <COLUMN_NAME>Notes</COLUMN_NAME> <ORDINAL_POSITION>2</ORDINAL_POSITION> <COLUMN_HASDEFAULT>false</COLUMN_HASDEFAULT> <COLUMN_FLAGS>234</COLUMN_FLAGS> <IS_NULLABLE>true</IS_NULLABLE> <DATA_TYPE>130</DATA_TYPE> <CHARACTER_MAXIMUM_LENGTH>0</CHARACTER_MAXIMUM_LENGTH> <CHARACTER_OCTET_LENGTH>0</CHARACTER_OCTET_LENGTH> </Columns> ``` Thanks, Greg --- I tried editing the schema.ini specifying text with a width, and that did not help (it was set to memo before) [CommaDelimited.txt] Format=CSVDelimited DecimalSymbol=. Col1=Notes Text Width 5000
The Jet database engine truncates memo fields if you ask it to process the data based on the memo: aggregating, de-duplicating, formatting, and so on. <http://allenbrowne.com/ser-63.html>
Here's a simple class for reading a delimited file and returning a DataTable (all strings) that doesn't truncate strings. It has an overloaded method to specify column names if they're not in the file. Maybe you can use it? Imported Namespaces ``` using System; using System.Text; using System.Data; using System.IO; ``` Code ``` /// <summary> /// Simple class for reading delimited text files /// </summary> public class DelimitedTextReader { /// <summary> /// Read the file and return a DataTable /// </summary> /// <param name="filename">File to read</param> /// <param name="delimiter">Delimiting string</param> /// <returns>Populated DataTable</returns> public static DataTable ReadFile(string filename, string delimiter) { return ReadFile(filename, delimiter, null); } /// <summary> /// Read the file and return a DataTable /// </summary> /// <param name="filename">File to read</param> /// <param name="delimiter">Delimiting string</param> /// <param name="columnNames">Array of column names</param> /// <returns>Populated DataTable</returns> public static DataTable ReadFile(string filename, string delimiter, string[] columnNames) { // Create the new table DataTable data = new DataTable(); data.Locale = System.Globalization.CultureInfo.CurrentCulture; // Check file if (!File.Exists(filename)) throw new FileNotFoundException("File not found", filename); // Process the file line by line string line; using (TextReader tr = new StreamReader(filename, Encoding.Default)) { // If column names were not passed, we'll read them from the file if (columnNames == null) { // Get the first line line = tr.ReadLine(); if (string.IsNullOrEmpty(line)) throw new IOException("Could not read column names from file."); columnNames = line.Split(new string[] { delimiter }, StringSplitOptions.RemoveEmptyEntries); } // Add the columns to the data table foreach (string colName in columnNames) data.Columns.Add(colName); // Read the file string[] columns; while ((line = tr.ReadLine()) != null) { columns = line.Split(new string[] { delimiter }, StringSplitOptions.None); // Ensure we have the same number of columns if (columns.Length != columnNames.Length) { string message = "Data row has {0} columns and {1} are defined by column names."; throw new DataException(string.Format(message, columns.Length, columnNames.Length)); } data.Rows.Add(columns); } } return data; } } ``` Required Namespaces ``` using System; using System.Data; using System.Windows.Forms; using System.Data.SqlClient; using System.Diagnostics; ``` Here's an example of calling it and uploading to a SQL Database: ``` Stopwatch sw = new Stopwatch(); TimeSpan tsRead; TimeSpan tsTrunc; TimeSpan tsBcp; int rows; sw.Start(); using (DataTable dt = DelimitedTextReader.ReadFile(textBox1.Text, "\t")) { tsRead = sw.Elapsed; sw.Reset(); rows = dt.Rows.Count; string connect = @"Data Source=.;Initial Catalog=MyDB;Integrated Security=SSPI"; using (SqlConnection cn = new SqlConnection(connect)) using (SqlCommand cmd = new SqlCommand("TRUNCATE TABLE dbo.UploadTable", cn)) using (SqlBulkCopy bcp = new SqlBulkCopy(cn)) { cn.Open(); sw.Start(); cmd.ExecuteNonQuery(); tsTrunc = sw.Elapsed; sw.Reset(); sw.Start(); bcp.DestinationTableName = "dbo.UploadTable"; bcp.ColumnMappings.Add("Column A", "ColumnA"); bcp.ColumnMappings.Add("Column D", "ColumnD"); bcp.WriteToServer(dt); tsBcp = sw.Elapsed; sw.Reset(); } } string message = "File read:\t{0}\r\nTruncate:\t{1}\r\nBcp:\t{2}\r\n\r\nTotal time:\t{3}\r\nTotal rows:\t{4}"; MessageBox.Show(string.Format(message, tsRead, tsTrunc, tsBcp, tsRead + tsTrunc + tsBcp, rows)); ```
Reading Comma Delimited Text File to C# DataTable, columns get truncated to 255 characters
[ "", "c#", ".net", "csv", "oledb", "jet", "" ]
How can I get `DateTime` value in C# from row, the current code is giving me error any help is appreciated, the data is coming in from progress database: ``` foreach (DataRow r in ds.Tables[0].Rows) { string prodCode = r["PRD-CDE"].ToString(); statCode = r["STAT"].ToString(); DateTime firstIssueDate = (DateTime)(r["FISS"]); DateTime endIssueDate = (DateTime)(r["EISS"]); if(endIssueDate > DateTime.Now) { /*do some thing...*/} else {/*user invalid...*/} } ``` there are two ways used in getting date convert and pars, thank you all for the help **Final working Code snippet:** ``` foreach (DataRow r in ds.Tables[0].Rows) { string prodCode = r["PRD-CDE"].ToString(),statCode = r["STAT"].ToString(); // r.<DateTime?>("FISS"); if (r["FISS"] != DBNull.Value) { DateTime firstIssueDate = Convert.ToDateTime(r["FISS"]); if (r["EISS"] != DBNull.Value) { DateTime endIssueDate = DateTime.Parse(r["EISS"].ToString()); if (endIssueDate > DateTime.Now) { ```
This is just a guess but if the corresponding type in the database is DateTime, could you check if the column is nullable? If so you may want to do a check `r["column"] == DBNull.Value` and then pass it to a nullable DateTime? Field. Or even easier: ``` row.Field<DateTime?>("column") ``` If it isn't then yeah, Convert.ToDateTime() or something else should do it. **EDIT:** I see your final code there but is there any chance you want to do this: ``` DateTime? firstIssueDate = r.Field<DateTime?>("fiss"); DateTime? endIssueDate = r.Field<DateTime?>("eiss"); if (firstIssueDate.HasValue && endIssueDate.HasValue) { firstIssueDate.Value // blah blah endIssueDate.Value // blah blah } ```
I would recommend using DateTime.Parse() if the row is returning a string for that index. ``` string prodCode = r["PRD-CDE"].ToString(),statCode = r["STAT"].ToString(); DateTime firstIssueDate = DateTime.Parse(r["FISS"].ToString()); DateTime endIssueDate = DateTime.Parse(r["EISS"].ToString()); ``` You could also use `TryParse` depending on your needs.
Retrieving a DateTime value from a DataRow (C#)
[ "", "c#", "datetime", "ado.net", "" ]
I'd like to write a decorator that would limit the number of times a function can be executed, something along the following syntax : ``` @max_execs(5) def my_method(*a,**k): # do something here pass ``` I think it's possible to write this type of decorator, but I don't know how. I think a function won't be this decorator's first argument, right? I'd like a "plain decorator" implementation, not some class with a ****call**** method. The reason for this is to learn how they are written. Please explain the syntax, and how that decorator works.
This is what I whipped up. It doesn't use a class, but it does use function attributes: ``` def max_execs(n=5): def decorator(fn): fn.max = n fn.called = 0 def wrapped(*args, **kwargs): fn.called += 1 if fn.called <= fn.max: return fn(*args, **kwargs) else: # Replace with your own exception, or something # else that you want to happen when the limit # is reached raise RuntimeError("max executions exceeded") return wrapped return decorator ``` `max_execs` returns a functioned called `decorator`, which in turn returns `wrapped`. `decoration` stores the max execs and current number of execs in two function attributes, which then get checked in `wrapped`. **Translation:** When using the decorator like this: ``` @max_execs(5) def f(): print "hi!" ``` You're basically doing something like this: ``` f = max_execs(5)(f) ```
Decorator is merely a callable that transforms a function into something else. In your case, `max_execs(5)` must be a callable that transforms a function into another callable object that will count and forward the calls. ``` class helper: def __init__(self, i, fn): self.i = i self.fn = fn def __call__(self, *args, **kwargs): if self.i > 0: self.i = self.i - 1 return self.fn(*args, **kwargs) class max_execs: def __init__(self, i): self.i = i def __call__(self, fn): return helper(self.i, fn) ``` I don't see why you would want to limit yourself to a function (and not a class). But if you really want to... ``` def max_execs(n): return lambda fn, i=n: return helper(i, fn) ```
How are these type of python decorators written?
[ "", "python", "language-features", "decorator", "" ]
I have developed an application using [Entity Framework](http://en.wikipedia.org/wiki/ADO.NET_Entity_Framework), SQL Server 2000, Visual Studio 2008 and Enterprise Library. It works absolutely fine locally, but when I deploy the project to our test environment, I am getting the following error: > Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information > > Stack trace: at System.Reflection.Module.\_GetTypesInternal(StackCrawlMark& stackMark) > > at System.Reflection.Assembly.GetTypes() > > at System.Data.Metadata.Edm.ObjectItemCollection.AssemblyCacheEntry.LoadTypesFromAssembly(LoadingContext context) > > at System.Data.Metadata.Edm.ObjectItemCollection.AssemblyCacheEntry.InternalLoadAssemblyFromCache(LoadingContext context) > > at System.Data.Metadata.Edm.ObjectItemCollection.AssemblyCacheEntry.LoadAssemblyFromCache(Assembly assembly, Boolean loadReferencedAssemblies, Dictionary`2 knownAssemblies, Dictionary`2& typesInLoading, List`1& errors) > > at System.Data.Metadata.Edm.ObjectItemCollection.LoadAssemblyFromCache(ObjectItemCollection objectItemCollection, Assembly assembly, Boolean loadReferencedAssemblies) > > at System.Data.Metadata.Edm.ObjectItemCollection.LoadAssemblyForType(Type type) > > at System.Data.Metadata.Edm.MetadataWorkspace.LoadAssemblyForType(Type type, Assembly callingAssembly) > > at System.Data.Objects.ObjectContext.CreateQuery[T](String queryString, ObjectParameter[] parameters) Entity Framework seems to have issue, any clue how to fix it?
I solved this issue by setting the Copy Local attribute of my project's references to true.
This error has no true magic bullet answer. The key is to have all the information to understand the problem. Most likely a dynamically loaded assembly is missing a referenced assembly. That assembly needs to be in the bin directory of your application. Use this code to determine what is missing. ``` using System.IO; using System.Reflection; using System.Text; try { //The code that causes the error goes here. } catch (ReflectionTypeLoadException ex) { StringBuilder sb = new StringBuilder(); foreach (Exception exSub in ex.LoaderExceptions) { sb.AppendLine(exSub.Message); FileNotFoundException exFileNotFound = exSub as FileNotFoundException; if (exFileNotFound != null) { if(!string.IsNullOrEmpty(exFileNotFound.FusionLog)) { sb.AppendLine("Fusion Log:"); sb.AppendLine(exFileNotFound.FusionLog); } } sb.AppendLine(); } string errorMessage = sb.ToString(); //Display or log the error based on your application. } ```
Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.'
[ "", "c#", "entity-framework", "" ]
I'm programming my very first GUI app in Java using the Swing framework. I've coded a basic login system using the JTextField, JPasswordField, and JButton classes. Now, I'm writing the actionPerformed method for the button, which I want to remove these items as they are no longer necessary, but I am unsure as to the best way of achieving this. I've considered using the setVisible method of these components, which seems to work, but I'm sure that's not the preferred way of doing it. Sorry if this is a bit of a dumb question..
Have your login dialog separated from your main window. When you finished with the login, just hide the login dialog. You can also save your text fields and buttons into a class field, and later call remove(Component) for each one.
Generally, you would want to be able to do this in one line of code. So, you should consider wrapping the different things you'd like to show or hide in a JPanel. Then, you can dynamically show or hide the JPanels.
Java GUI Design Advice
[ "", "java", "user-interface", "swing", "" ]
we need to evaluate a value in an object in run time while we have a textual statement of the exact member path for example: **myobject.firstMember.secondMember[3].text** we thought of parsing this textual statement using regex and then evaluate the text value by using reflection but before we do that i wonder if C# support some kind of **eval** ability? so we won't have to do the parsing ourself. How do microsoft do this in their immediate window or watch windows? thanks you very much, Adi Barda
Probably the easiest way is to use [DataBinder.Eval](http://msdn.microsoft.com/en-us/library/system.web.ui.databinder.eval.aspx) from System.Web.UI: ``` var foo = new Foo() { Bar = new Bar() { Value = "Value" } }; var value = DataBinder.Eval(foo, "Bar.Value"); ```
I have written an open source project, [Dynamic Expresso](https://github.com/davideicardi/DynamicExpresso/), that can convert text expression written using a C# syntax into delegates (or expression tree). Expressions are parsed and transformed into [Expression Trees](http://msdn.microsoft.com/en-us/library/bb397951.aspx) without using compilation or reflection. You can write something like: ``` var interpreter = new Interpreter(); var result = interpreter.Eval("8 / 2 + 2"); ``` or ``` var interpreter = new Interpreter() .SetVariable("service", new ServiceExample()); string expression = "x > 4 ? service.SomeMethod() : service.AnotherMethod()"; Lambda parsedExpression = interpreter.Parse(expression, new Parameter("x", typeof(int))); parsedExpression.Invoke(5); ``` My work is based on Scott Gu article <http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx> .
C# Eval() support
[ "", "c#", "eval", "" ]
Are they less vulnerable to SQL injection than doing stuff like `mysql_query("SELECT important_data FROM users WHERE password = $password")`?
They are more secure than what you are doing. Your query is posting raw SQL to the db which means that your parameters aren't treated as sql parameters but as plain old sql. Here is what I mean. With a stored prococedure the password variable can't be sql, it has to be a piece of information the system is looking for. In your example what is actually sent to the db is SELECT \* FROM User where password = ('your password here'--$Password variable).....so someone can do something like SELECT \* FROM user WHERE Password = ('your password here';SELECT \* FROM User --$password variable). or worse yet: SELECT \* FROM user WHERE Password = ('your password here';DROP Database Database\_Name --$password variable). A non-dynamic sql stored procedure won't allow this, because the input parameter won't execute as extra sql. Parametrized SQL does take care of this, but technically stored procedures are still a little more secure, because the user accessing information in the table doesn't need Read Access. It only needs to be able to execute the stored procedure. Depending on your need this may or may not come into play.
Not necessarily, you could be doing string concatenation inside of it and the exposure would be the same. If you use dynamic sql with parameter variables (no string concatenation to produce SQL) you'd be fairly well protected.
Are SQL stored procedures secure?
[ "", "sql", "stored-procedures", "sql-injection", "" ]
I'm running pylons and I did this: paster server development.ini It's running on :5000 But when I try to run the command again: paster serve development.ini I get this message: socket.error: [Errno 98] Address already in use Any ideas?
Normally that means it's still running, but that should only happen if it's in daemon mode. After you started it, do you get a command prompt, or do you have to stop it with Ctrl-C? If you get a command prompt back it's deamon mode and you have to stop it with ``` paster server development.ini stop ``` If you have stopped it with Ctrl-C (and not Ctrl-Z of course), I have no idea.
I've found this trick in a forum: This will kill all programs listening to port 5000 ``` kill -9 `fuser -n tcp 5000` ```
Pylons: address already in use when trying to serve
[ "", "python", "nginx", "pylons", "paste", "paster", "" ]
I am getting tired of manually installing javax jar files in Maven and would like to know what is the best solution to include a dependency on javax.cache, javax.transaction, or other JSRs that are not easy to find in Maven repositories.
Have you seen [https://people.apache.org/~ltheussl/maven-stage-site/guides/mini/guide-coping-with-sun-jars.html](https://people.apache.org/%7Eltheussl/maven-stage-site/guides/mini/guide-coping-with-sun-jars.html) ? This link suggests groupID and artifactID's to use, as well as a java.net repository. It looks to me like almost all of these exist in the central Maven repository under this naming scheme.
I'm not aware of one, but adding the java.net repository may help you with some of these dependencies: ``` <repositories> <repository> <id>java.net repository</id> <url>http://download.java.net/maven/2</url> </repository> </repositories> ```
How to add javax.* dependencies in Maven?
[ "", "java", "maven-2", "jakarta-ee", "" ]
Does anyone knows a good **business calendar** library in java? It should handle easy :) date calculations, taking holidays into account. Ideally, besides **configuring holidays** and company off days, we should also be able to **configure 'working hours**' on a day basis so we can calculate SLA's and KPI's on working hours. I know something like this is part of jboss jBpm, but I was wondering if their was any other project doing this. Off course, **open source** is a big plus point!
Check out this library, it has functionality for holidays and such, it's built around joda. <http://objectlabkit.sourceforge.net/>
Below is a very longwinded answer. It's something that I put together for exactly this purpose. It's not super user friendly, but it should give you want you are looking for. It relies on the Apache commons project which can be acquired here: [http://commons.apache.org/lang/](http://commons.apache.org/lang/ "Apache Common Lang") ``` package com.yourPackageName; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.time.DateUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class BusinessDayUtil { private static Log log = LogFactory.getLog(BusinessDayUtil.class); private static transient Map<Integer, List<Date>> computedDates = new HashMap<Integer, List<Date>>(); /* * This method will calculate the next business day * after the one input. This means that if the next * day falls on a weekend or one of the following * holidays then it will try the next day. * * Holidays Accounted For: * New Year's Day * Martin Luther King Jr. Day * President's Day * Memorial Day * Independence Day * Labor Day * Columbus Day * Veterans Day * Thanksgiving Day * Christmas Day * */ public static boolean isBusinessDay(Date dateToCheck) { //Setup the calendar to have the start date truncated Calendar baseCal = Calendar.getInstance(); baseCal.setTime(DateUtils.truncate(dateToCheck, Calendar.DATE)); List<Date> offlimitDates; //Grab the list of dates for the year. These SHOULD NOT be modified. synchronized (computedDates) { int year = baseCal.get(Calendar.YEAR); //If the map doesn't already have the dates computed, create them. if (!computedDates.containsKey(year)) computedDates.put(year, getOfflimitDates(year)); offlimitDates = computedDates.get(year); } //Determine if the date is on a weekend. int dayOfWeek = baseCal.get(Calendar.DAY_OF_WEEK); boolean onWeekend = dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY; //If it's on a holiday, increment and test again //If it's on a weekend, increment necessary amount and test again if (offlimitDates.contains(baseCal.getTime()) || onWeekend) return false; else return true; } /** * * This method will calculate the next business day * after the one input. This leverages the isBusinessDay * heavily, so look at that documentation for further information. * * @param startDate the Date of which you need the next business day. * @return The next business day. I.E. it doesn't fall on a weekend, * a holiday or the official observance of that holiday if it fell * on a weekend. * */ public static Date getNextBusinessDay(Date startDate) { //Increment the Date object by a Day and clear out hour/min/sec information Date nextDay = DateUtils.truncate(addDays(startDate, 1), Calendar.DATE); //If tomorrow is a valid business day, return it if (isBusinessDay(nextDay)) return nextDay; //Else we recursively call our function until we find one. else return getNextBusinessDay(nextDay); } /* * Based on a year, this will compute the actual dates of * * Holidays Accounted For: * New Year's Day * Martin Luther King Jr. Day * President's Day * Memorial Day * Independence Day * Labor Day * Columbus Day * Veterans Day * Thanksgiving Day * Christmas Day * */ private static List<Date> getOfflimitDates(int year) { List<Date> offlimitDates = new ArrayList<Date>(); Calendar baseCalendar = GregorianCalendar.getInstance(); baseCalendar.clear(); //Add in the static dates for the year. //New years day baseCalendar.set(year, Calendar.JANUARY, 1); offlimitDates.add(offsetForWeekend(baseCalendar)); //Independence Day baseCalendar.set(year, Calendar.JULY, 4); offlimitDates.add(offsetForWeekend(baseCalendar)); //Vetrans Day baseCalendar.set(year, Calendar.NOVEMBER, 11); offlimitDates.add(offsetForWeekend(baseCalendar)); //Christmas baseCalendar.set(year, Calendar.DECEMBER, 25); offlimitDates.add(offsetForWeekend(baseCalendar)); //Now deal with floating holidays. //Martin Luther King Day offlimitDates.add(calculateFloatingHoliday(3, Calendar.MONDAY, year, Calendar.JANUARY)); //Presidents Day offlimitDates.add(calculateFloatingHoliday(3, Calendar.MONDAY, year, Calendar.FEBRUARY)); //Memorial Day offlimitDates.add(calculateFloatingHoliday(0, Calendar.MONDAY, year, Calendar.MAY)); //Labor Day offlimitDates.add(calculateFloatingHoliday(1, Calendar.MONDAY, year, Calendar.SEPTEMBER)); //Columbus Day offlimitDates.add(calculateFloatingHoliday(2, Calendar.MONDAY, year, Calendar.OCTOBER)); //Thanksgiving Day and Thanksgiving Friday Date thanksgiving = calculateFloatingHoliday(4, Calendar.THURSDAY, year, Calendar.NOVEMBER); offlimitDates.add(thanksgiving); offlimitDates.add(addDays(thanksgiving, 1)); return offlimitDates; } /** * This method will take in the various parameters and return a Date objet * that represents that value. * * Ex. To get Martin Luther Kings BDay, which is the 3rd Monday of January, * the method call woudl be: * * calculateFloatingHoliday(3, Calendar.MONDAY, year, Calendar.JANUARY); * * Reference material can be found at: * http://michaelthompson.org/technikos/holidays.php#MemorialDay * * @param nth 0 for Last, 1 for 1st, 2 for 2nd, etc. * @param dayOfWeek Use Calendar.MODAY, Calendar.TUESDAY, etc. * @param year * @param month Use Calendar.JANUARY, etc. * @return */ private static Date calculateFloatingHoliday(int nth, int dayOfWeek, int year, int month) { Calendar baseCal = Calendar.getInstance(); baseCal.clear(); //Determine what the very earliest day this could occur. //If the value was 0 for the nth parameter, incriment to the following //month so that it can be subtracted alter. baseCal.set(year, month + ((nth <= 0) ? 1 : 0), 1); Date baseDate = baseCal.getTime(); //Figure out which day of the week that this "earliest" could occur on //and then determine what the offset is for our day that we actually need. int baseDayOfWeek = baseCal.get(Calendar.DAY_OF_WEEK); int fwd = dayOfWeek - baseDayOfWeek; //Based on the offset and the nth parameter, we are able to determine the offset of days and then //adjust our base date. return addDays(baseDate, (fwd + (nth - (fwd >= 0 ? 1 : 0)) * 7)); } /* * If the given date falls on a weekend, the * method will adjust to the closest weekday. * I.E. If the date is on a Saturday, then the Friday * will be returned, if it's a Sunday, then Monday * is returned. */ private static Date offsetForWeekend(Calendar baseCal) { Date returnDate = baseCal.getTime(); if (baseCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) { if (log.isDebugEnabled()) log.debug("Offsetting the Saturday by -1: " + returnDate); return addDays(returnDate, -1); } else if (baseCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { if (log.isDebugEnabled()) log.debug("Offsetting the Sunday by +1: " + returnDate); return addDays(returnDate, 1); } else return returnDate; } /** * Private method simply adds * @param dateToAdd * @param numberOfDay * @return */ private static Date addDays(Date dateToAdd, int numberOfDay) { if (dateToAdd == null) throw new IllegalArgumentException("Date can't be null!"); Calendar tempCal = Calendar.getInstance(); tempCal.setTime(dateToAdd); tempCal.add(Calendar.DATE, numberOfDay); return tempCal.getTime(); } } ```
A good Business calendar library in Java?
[ "", "java", "open-source", "calendar", "" ]
I want to use some Python libraries to replace MATLAB. How could I import Excel data in Python (for example using [NumPy](http://en.wikipedia.org/wiki/NumPy)) to use them? I don't know if Python is a credible alternative to MATLAB, but I want to try it. Is there a a tutorial?
Depending on what kind of computations you are doing with [MATLAB](http://en.wikipedia.org/wiki/MATLAB) (and on which toolboxes you are using), Python could be a good alternative to MATLAB. Python + [NumPy](http://en.wikipedia.org/wiki/NumPy) + [SciPy](http://en.wikipedia.org/wiki/SciPy) + [Matplotlib](http://en.wikipedia.org/wiki/Matplotlib) are the right combination to start. For the data, you can, for example, save your data directly in text file (assuming that you are not directly concerned by floating-point precision issues) and read it in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29). If your data are [Excel](http://en.wikipedia.org/wiki/Microsoft_Excel) data, where each value is separated by a ";", you can for example read the file line by line, and use the split() method (with ";" as argument) to get each value. For MATLAB up to version 7.1, it is possible to directly load .mat files from Python with the [scipy.io.matlab.mio](http://www.scipy.org/doc/api_docs/SciPy.io.mio.html) module.
There are probably hundreds of ways you could import text data into Python. But since you want to replace [MATLAB](http://en.wikipedia.org/wiki/MATLAB), you're going be using [NumPy](http://en.wikipedia.org/wiki/NumPy) and probably [SciPy](http://en.wikipedia.org/wiki/SciPy). Keep things simple: use NumPy's standard text-loading: ``` import numpy imported_array = numpy.loadtxt('file.txt',delimiter='\t') # Assuming tab-delimiter print imported_array.shape ```
Using Python to replace MATLAB: how to import data?
[ "", "python", "excel", "matlab", "numpy", "" ]
I want to do something like: ``` object[] rowOfObjects = GetRow();//filled somewhere else object[,] tableOfObjects = new object[10,10]; tableOfObjects[0] = rowOfObjects; ``` is this somehow possible and what is the syntax? or I need to do this: ``` for (int i = 0; i < rowOfObjects.Length; i++) { tableOfObjects[0,i] = rowOfObjects[i]; } ``` and fill up the 2 dimensional arrays row using a loop? Thanks
No, if you are using a two dimensional array it's not possible. You have to copy each item. If you use a jagged array, it works just fine: ``` // create array of arrays object[][] tableOfObject = new object[10][]; // create arrays to put in the array of arrays for (int i = 0; i < 10; i++) tableOfObject[i] = new object[10]; // get row as array object[] rowOfObject = GetRow(); // put array in array of arrays tableOfObjects[0] = rowOfObjects; ``` If you are getting all the data as rows, you of course don't need the loop that puts arrays in the array of arrays, as you would just replace them anyway.
If your array is an array of [value types](http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx), it is possible. ``` int[,] twoD = new int[2, 2] { {0,1}, {2,3} }; int[] oneD = new int[2] { 4, 5 }; int destRow = 1; Buffer.BlockCopy( oneD, // src 0, // srcOffset twoD, // dst destRow * twoD.GetLength(1) * sizeof(int), // dstOffset oneD.Length * sizeof(int)); // count // twoD now equals // {0,1}, // {4,5} ``` It is not possible with an array of objects. Note: Since .net3.5 this will only work with an array of primitives.
c# assign 1 dimensional array to 2 dimensional array syntax
[ "", "c#", "arrays", "multidimensional-array", "" ]
[Complete C++ i18n gettext() “hello world” example](https://stackoverflow.com/questions/1003360/complete-c-i18n-gettext-hello-world-example/1033337#1033337) has C++ code that works for a simple fixed string. I am now looking for an example program that works with plurals. This example code displays six lines. Only one is correct in English. It does not handle the plurals correctly. ``` cat >helloplurals.cxx <<EOF // hellopurals.cxx #include <libintl.h> #include <locale.h> #include <iostream> #include <stdio.h> int main (){ setlocale(LC_ALL, ""); bindtextdomain("helloplurals", "."); textdomain( "helloplurals"); for (int ii=0; ii<5; ii++) printf (gettext("Hello world with %d moon.\n"), ii); } EOF g++ -o helloplurals helloplurals.cxx ./helloplurals ``` [GNU gettext() for plural forms](http://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms) describes various ways that languages handle plurals for example: * Korean - no pluals * English - two forms, singular used for one only * French - two forms, singular used for zero and one * Polish - three forms, special case for one and some numbers ending in 2, 3, or 4 My expectation is that the code will be able to work (given message catalogs) specifically for all of the above cases and several more variations not listed here. The correct output when it is executed with English would be: ``` Hello world with 0 moons. Hello world with 1 moon. Hello world with 2 moons. Hello world with 3 moons. Hello world with 4 moons. ```
I'm not sure what you want. If it is slight modification of your example that give your wanted output, just replace the printf line by ``` printf(ngettext("Hello world with %d moon\n", "Hello world with %d moons\n", ii), ii); ``` but as it is a trivial modification of unwind's answer and the gettext documentation has the very similar example, ``` printf (ngettext ("%d file removed", "%d files removed", n), n); ``` I wonder if it is really what you wanted. If you want to use gettext with a more C++ syntax, you'll have to look for libraries like Boost::Format.
First, `gettext()` is not magical. It does not somehow contain a global dictionary of all words in all languages. All it does is look up a message's translation in your application's message database, so this example assumes there is such a file (where `gettext()` can find it, this can be somewhat tricky). Next, you're using it wrong. The page you linked to describes the `ngettext()` function, which is what you're going to have to use in order to get a translation that varies with a count. Your call should look something like this: ``` printf("%s", ngettext("moon", "moons", ii)); ``` This lets gettext decide which form to use, based on the count parameter.
I18n C++ hello world with plurals
[ "", "c++", "internationalization", "gettext", "" ]
Is there a way to get the location mouse inside a `<canvas>` tag? I want the location relative to to the upper right corner of the `<canvas>`, not the entire page.
Easiest way is probably to add a onmousemove event listener to the canvas element, and then you can get the coordinates relative to the canvas from the event itself. This is trivial to accomplish if you only need to support specific browsers, but there are differences between f.ex. Opera and Firefox. Something like this should work for those two: ``` function mouseMove(e) { var mouseX, mouseY; if(e.offsetX) { mouseX = e.offsetX; mouseY = e.offsetY; } else if(e.layerX) { mouseX = e.layerX; mouseY = e.layerY; } /* do something with mouseX/mouseY */ } ```
The accepted answer will not work every time. If you don't use relative position the attributes offsetX and offsetY can be misleading. You should use the function: `canvas.getBoundingClientRect()` from the canvas API. ``` function getMousePos(canvas, evt) { var rect = canvas.getBoundingClientRect(); return { x: evt.clientX - rect.left, y: evt.clientY - rect.top }; } canvas.addEventListener('mousemove', function(evt) { var mousePos = getMousePos(canvas, evt); console.log('Mouse position: ' + mousePos.x + ',' + mousePos.y); }, false); ```
Getting mouse location in canvas
[ "", "javascript", "html", "canvas", "" ]
I'd like to trim these purchase order file names (a few examples below) so that everything after the first "\_" is omitted. INCOLOR\_fc06\_NEW.pdf Keep: INCOLOR (write this to db as the VendorID) Remove: \_fc08\_NEW.pdf NORTHSTAR\_sc09.xls Keep: NORTHSTAR (write this to db as the VendorID) Remove: \_sc09.xls Our scenario: The managers are uploading these files to our Intranet web server, to make them available to download/view ect. I'm using Brettles NeatUpload, and for each file uploaded, am writing the files attributes into the PO table (sql 2000). The first part of the file name will be written to the DB as a VendorID. The naming convention for these files is consistent in that the the first part of the file is always the vendor name (or Vendor ID) followed by an "\_" then other unpredictable chars used to identify the type of Purchase Order then the file extention - which is consistently either .xls, .XLS, .PDF, or .pdf. I tried TrimEnd - but the array of chars that you have to provide ends up being long and can conflict with the part of the file name I want to keep. I have a feeling I'm not using TrimEnd properly. What is the best way to use string.TrimEnd (or any other string manipulation in C#) that will strip off all chars after the first "\_" ?
I'll probably offend the anti-regex lobby, but here I go (ducking): ``` string stripped = Regex.Replace(filename, @"(?<=[^_]*)_.*",String.Empty); ``` This code will strip all extra characters after the first `'_'`, unless there is no `'_'` in the string (then it will just return the original string). It's one line of code. It's slower than the more elaborate IndexOf() algorithm, but when used in a non-performance-sensitive part of the code, it's a good solution. Get your flame-throwers out...
``` String s = "INCOLOR_fc06_NEW.pdf"; int index = s.IndexOf("_"); return index >= 0 ? s.Substring(0,index) : s; ```
Trim all chars off file name after first "_"
[ "", "c#", "string", "" ]
I wrote a regex to fetch string from HTML, but it seems the multiline flag doesn't work. This is my pattern and I want to get the text in `h1` tag. ``` var pattern= /<div class="box-content-5">.*<h1>([^<]+?)<\/h1>/mi m = html.search(pattern); return m[1]; ``` I created a string to test it. When the string contains "\n", the result is always null. If I removed all the "\n"s, it gave me the right result, no matter with or without the `/m` flag. What's wrong with my regex?
You are looking for the `/.../s` modifier, also known as the *dotall* modifier. It forces the dot `.` to also match newlines, which it *does not do* by default. The bad news is that it ~~does not exist in JavaScript~~ *(it does as of ES2018, see below)*. The good news is that you can work around it by using a character class (e.g. `\s`) and its negation (`\S`) together, like this: ``` [\s\S] ``` So in your case the regex would become: ``` /<div class="box-content-5">[\s\S]*<h1>([^<]+?)<\/h1>/i ``` --- As of ES2018, JavaScript supports the `s` (dotAll) flag, so in a modern environment your regular expression could be as you wrote it, but with an `s` flag at the end (rather than `m`; `m` changes how `^` and `$` work, not `.`): ``` /<div class="box-content-5">.*<h1>([^<]+?)<\/h1>/is ```
You want the `s` (dotall) modifier, which apparently doesn't exist in Javascript - you can replace `.` with [\s\S] as suggested by @molf. The `m` (multiline) modifier makes ^ and $ match lines rather than the whole string.
JavaScript regex multiline text between two tags
[ "", "javascript", "regex", "" ]
I'm trying to create a faster query, right now i have large databases. My table sizes are 5 col, 530k rows, and 300 col, 4k rows (sadly i have 0 control over architecture, otherwise I wouldn't be having this silly problem with a poor db). ``` SELECT cast( table2.foo_1 AS datetime ) as date, table1.*, table2.foo_2, foo_3, foo_4, foo_5, foo_6, foo_7, foo_8, foo_9, foo_10, foo_11, foo_12, foo_13, foo_14, foo_15, foo_16, foo_17, foo_18, foo_19, foo_20, foo_21 FROM table1, table2 WHERE table2.foo_0 = table1.foo_0 AND table1.bar1 >= NOW() AND foo_20="tada" ORDER BY date desc LIMIT 0,10 ``` I've indexed the table2.foo\_0 and table1.foo\_0 along with foo\_20 in hopes that it would allow for faster querying.. i'm still at nearly 7 second load time.. is there something else I can do? Cheers
I think an index on bar1 is the key. I always run into performance issues with dates because it has to compare each of the 530K rows.
Create the following indexes: ``` CREATE INDEX ix_table1_0_1 ON table1 (foo_1, foo_0) CREATE INDEX ix_table2_20_0 ON table2 (foo_20, foo_0) ``` and rewrite you query as this: ``` SELECT cast( table2.foo_1 AS datetime ) as date, table1.*, table2.foo_2, foo_3, foo_4, foo_5, foo_6, foo_7, foo_8, foo_9, foo_10, foo_11, foo_12, foo_13, foo_14, foo_15, foo_16, foo_17, foo_18, foo_19, foo_20, foo_21 FROM table1 JOIN table2 ON table2.foo_0 = table1.foo_0 AND table2.foo_20 = "tada" WHERE table1.bar1 >= NOW() ORDER BY table1.foo_1 DESC LIMIT 0, 10 ``` The first index will be used for `ORDER BY`, the second one will be used for `JOIN`. You, though, may benefit more from creating the first index like this: ``` CREATE INDEX ix_table1_0_1 ON table1 (bar, foo_0) ``` which may apply more restrictive filtering on `bar`. I have a blog post on this: * [**Choosing index**](http://explainextended.com/2009/04/01/choosing-index/) , which advices on how to choose which index to create for cases like that.
Creating a quicker MySQL Query
[ "", "sql", "performance", "mysql", "" ]
I have the following rule in my current .htaccess file to redirect `/videos/login/` requests to `/videos/login.php` ``` RewriteRule login/ /videos/login.php ``` This works fine if I am access login page using `http://mysite.com/videos/login/` but when I am trying to access the same page using `http://mysite.com/videos/login` (without ending slash) then it gives me "404 page not found" error. Please tell me what will be the correct rule of .htaccess file so that any request for `http://mysite.com/videos/login/` or `http://mysite.com/videos/login` will point to the same /videos/login.php page. Thanks
Just make the trailing slash optional: ``` RewriteRule ^videos/login/?$ /videos/login.php ``` But you should better use just one variant (with or without trailing slash) and redirect one to the other: ``` # add trailing slash RewriteCond %{REQUEST_FILENAME} !-f RewriteRule .*[^/]$ /$0/ [L,R=301] # remove trailing slash RewriteRule (.*)/$ /$1 [L,R=301] ```
This work fine for me: Rewriterule ^login(/|)$ /videos/login.php
htaccess rule to forward /login/ and /login to same page?
[ "", "php", "apache", ".htaccess", "url-rewriting", "" ]
Sometimes, I just want to execute a function for a list of entries -- eg.: ``` for x in wowList: installWow(x, 'installed by me') ``` Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda: ``` map(lambda x: installWow(x, 'installed by me'), wowList) ``` But this of course creates a nice list [None, None, ...] so my question is, if there is a similar function without a return-list -- since I just don't need it. (off course I can also use \_x and thus not leaving visible footprint -- but the map-solution looks so neat ...)
You can use the built-in `any` function to apply a function **without return statement** to any item returned by a generator without creating a list. This can be achieved like this: ``` any(installWow(x, 'installed by me') for x in wowList) ``` I found this the most concise idom for what you want to achieve. Internally, the `installWow` function does return `None` which evaluates to `False` in logical operations. `any` basically applies an `or` reduction operation to all items returned by the generator, which are all `None` of course, so it has to iterate over all items returned by the generator. In the end it does return `False`, but that doesn't need to bother you. The good thing is: no list is created as a side-effect. Note that this only works as long as your function returns something that evaluates to `False`, e.g., `None` or 0. If it does return something that evaluates to `True` at some point, e.g., `1`, it will not be applied to any of the remaining elements in your iterator. To be safe, use this idiom mainly for functions without return statement.
You could make your own "each" function: ``` def each(fn, items): for item in items: fn(item) # called thus each(lambda x: installWow(x, 'installed by me'), wowList) ``` Basically it's just map, but without the results being returned. By using a function you'll ensure that the "item" variable doesn't leak into the current scope.
Is there a map without result in python?
[ "", "python", "iteration", "" ]
I'm looking for an "elegant" way to suppress exceptions when calling a method. I think the following code is way too verbose: ``` try { CallToMethodThatMayFail(3); } catch {} ``` Is there some syntactic sugar I can use to say "I don't really care if this method fails"? I want to call the method and continue execution regardless of what happens with the method.
It is rarely a good idea to ignore/swallow errors... To allow re-use, the only option you have is something like a method that takes an `Action`: ``` static void IgnoreErrors(Action action) {try {action();} catch {}} ``` But you haven't exactly saved much by the time you've done: ``` SomeHelper.IgnoreErrors(() => CallToMethodThatMayFail(3)); ``` I'd just leave the `try`/`catch` in place... --- Re the question in the comment: ``` static void IgnoreErrors<T>(Action action) where T : Exception { try { action(); } catch (T) {} } SomeHelper.IgnoreErrors<ParseException>(() => CallToMethodThatMayFail(3)); ``` but I would still find it clearer to have the `try`/`catch` locally...
Nope this is it. And it's a good thing it's verbose. If you're suppressing a possible exception you better have a very good reason. The verbosity will help you or the next person who looks at the code in a few months.
How do you suppress errors to a method call in C#?
[ "", "c#", "error-handling", "" ]
Does enabling the configuration option `with-config-file-scan-dir` when compiling PHP lead to performance issues? Specifically, does this tell the PHP binary to do a file system scan every time the PHP module is loaded to respond to a request? I imagine it does, and that having multiple ini files causes just a little more disk access on every request. I suppose this could be mitigated by placing all those separate directives into the same php.ini file. Can anyone confirm or deny this?
No, If I understand it correctly you will provide it a directory which when the PHP config is loaded (at apache startup) PHP will read every file in the directory as a config file. Some info [here](http://www.radwin.org/michael/blog/2006/07/phpini_hacks_withconfigfil.html) and more [here](http://marc.info/?l=php-internals&m=122971082314313&w=2) (better link)
Bryan, The CLI/(Fast)CGI versions do load the .ini files each time they are fired up; however, the apache module loads them once into memory when the server is started. You can test this behavior by changing a value in any of the .ini files and running the CLI binary. Notice that you need a server restart before you can see the changes in the server module version.
php.ini config file scan performance
[ "", "php", "apache", "" ]
The "classic" approach to web development has been for some time a thin client and a thick server: the server generates HTML and spits it out for the browser to render only. But with current browsers (and also due to the availability of good libraries and frameworks) Javascript now works. Web devs can now pretty much assume that their Javascript code will work and stop bothering. This certainly opened new possibilities for web development. Apps could now be composed mostly of HTML content returned from the server and rendered by the browser with some UI manipulation being done client-side. The client could even query the server for fresh data for updating parts of the UI. But can we go down all the other way? An app can certainly be designed as a server that spits only the most minimalist JSON glued together to a thick Javascript client responsible for building and controlling the whole user interface. Yeah, this approach can seriously break URLs to the extent that people can no longer send pointers around, but it is certainly possible to design your way around that (and for some apps, like e-mail and feed readers, this doesn't even matter). What do you think? Have you ever tried that approach? Do things get too slow? Are modern browsers capable of dealing with that amount of Javascript code? Are there any significant differences between browsers implementations that still bite the unadvised developer even with the latest libraries? What kinds of applications do you think this approach is suitable for? Is it actually suitable for *anything*?
I'm on the tail end of building just this sort of app. It's an ExtJS GUI on top of Zend Framework JSON-RPC web services, implementing an iGoogle-like gadget portal. Advantages: * Very responsive UI, ExtJS gives you a great user experience. * Very predictable client-server communication. Everything's json (easy to debug). There's standardized error handling inherent in the API (at least that's how I designed it). * The front-end is replaceable. I could write a C++ app on top of the same server back-end. Separating front-end and back-end across client-server lines means they're easier to test independently. * You get to live and breathe javascript, which is great if you like it. Disadvantages: * You have to live and breathe javascript, which sucks if you hate it. In our case this meant a major retraining of the developer team because we were PHP-heavy. * Everything lives in a single long-lived DOM, so you have to stay on your toes with memory management and making sure stuff gets cleaned up correctly. Also, loading too much UI makes IE go "ow, ow, you're hurting my brain". * There's no running a quick query to fetch an option in the middle of generating the UI. The program design constraints of living on the client are daunting at first. You get used to it, but it's a bit of a hurdle. * Loading all that javascript means your users need to have fast connections and modern browsers. The driving reason for us to do this was to deliver a better user experience. Users expect a desktop-like experience, and you can't deliver that across a server roundtrip. We get to deliver that now, but there's no denying there are big challenges with an approach like this. Overall I'm satisfied though. **Update (september 2013):** Still using this architecture and still thinking it's the right architecture if you are building a genuine web application (not just a web page with some dynamic features). Our team and product is now much larger (nearing 500.000 lines of code), but the architecture has scaled without issue. There are now many really good scalable javascript frameworks (angular, ember, ...), so it is easier than ever to adopt this way of working. Because @rwoo asked, some challenges that we still have: * On-demand loading of js code turns out to be a trickier problem than foreseen. It's important to get this part right in your architecture. * We have had to integrate automatic jshint validation in a pre-commit hook in subversion because js is way too tolerant of syntax errors and you often don't notice this until the product reaches the customer. * Because the database is on the other end of a web service request, you have to carefully design your web service API or you will end up with lousy performance due to waiting for too many XHR requests. This is solvable, but challenging, and it doesn't get easier with time. * While with the right framework cross-browser issues are minimized, they don't go away entirely which means that you need to test in all browsers, all versions. This is so much work that you have to automate it using something like selenium, and as it turns out this is more difficult to do with a client-side rendered UI than a server-side rendered UI.
Your assertion that web developers can now "pretty much assume their Javascript code is working" is a tough one to agree with. In my experience Javascript is almost always a black hole sucking all the time and energy you can supply it. Frameworks like Prototype and Script.aculo.us have made things MUCH better, but they are not yet as hardened as your question assumes. The two main issues are one, browser support and two is development time. You are relying on an application you cannot control to handle the bulk of your app's work load. The fact this can be broken with even the most minor update to the browser would concern me. Generating HTML server-side mitigates this risk to a large extent. Development of a rich Javascript front-end is time consuming, difficult to debug and equally difficult to test across the wide array of available browsers. While those concerns are real, the fact you can achieve some fantastic User Experiences via client-side Javascript cannot be ignored. The frameworks I mentioned earlier expose functionality that was not even dreamed of a year or two ago and as a result make the up front development price in some cases largely worth it (and sometimes significantly shortened when the frameworks are implemented effectively). I think there are applications for A Javascript-powered UI, as long as the decision to go that route is well thought-out. We would not be discussing this on SO were it not for the fact that the UI potential using this strategy is awesome. Web-based applicationsusing web-based data are perfect candiates (RSS, REST Services). Applications hitting a relation database or complex Web services repeadly are going to by necessity maintain a tighter coupling with the server-side. My 2 cents.
Is client-side UI rendering via Javascript a good idea?
[ "", "javascript", "" ]
I am wondering if it is possible to load javascript in a way in which it does not block the user experience. I am not sure how to achieve the same, but I am looking for a cross-browser solution. I am wondering if someone can guide me in the right direction. Placing the js at the bottom of the page does not work too well. Thank you for your time.
Javascript runs in a single-thread, so if you have massive Javascript calls, let say with librairies like ExtJS, it's normal that it can be slow. You might however consider the following alternatives: First and foremost, try to optimize the code as much as you can. Then, you could use timers in Javascript to simulate asynchronous work. Here is a good example on how to do this : <http://ejohn.org/blog/how-javascript-timers-work/> If you want more information, here are some additional tips on how to attempt to reduce Javascript freezing time. <http://debuggable.com/posts/run-intense-js-without-freezing-the-browser:480f4dd6-f864-4f72-ae16-41cccbdd56cb> Good luck !
Quoting [this answer](https://stackoverflow.com/questions/950280/javascript-being-loaded-asynchronously-in-firefox-3-according-to-firebug): > Javascript resource requests are > indeed blocking, but there are ways > around this (to wit: DOM injected > script tags in the head, and AJAX > requests) which without seeing the > page myself is likely to be what's > happening here. > > Including multiple copies of the same > JS resource is extremely bad but not > necessarily fatal, and is typical of > larger sites which might have been > accreted from the work of separate > teams, or just plain old bad coding, > planning, or maintenance. > > As far as yahoo's recommendation to > place scripts at the bottom of the > body, this improves percieved response > times, and can improve actual loading > times to a degree (because all the > previous resources are allowed to > async first), but it will never be as > effective as non-blocking requests > (though they come with a high barrier > of technical capability). You can take a look at a YUI blog entry about [Non-Blocking Javascript](http://yuiblog.com/blog/2008/07/22/non-blocking-scripts/).
Non-blocking Javascript
[ "", "javascript", "jquery", "" ]
``` private List<String> subList; private List<List<String>> records = new ArrayList<List<String>>(); for(....){ subList = new ArrayList<String>(); ...populate.. records.add(subList); } ``` For example, subList has three Strings - a, b, and c. I want to sort the records by the value of b in subList. ``` records at 0 has a list of "10", "20", "30" records at 1 has a list of "10", "05", "30" records at 2 has a list of "10", "35", "30" ``` After the sort, the order of records should be - ``` records at 0 = records at 1 above records at 1 = records at 0 above records at 2 = records at 2 above ``` What could be a good algorithm for that?
Something like: ``` Collections.sort(records, new Comparator<List<String>>() { public int compare(List<String> o1, List<String> o2) { //Simple string comparison here, add more sophisticated logic if needed. return o1.get(1).compareTo(o2.get(1)); } }) ``` Though I find hard-coding the positions a little dubious in practice, your opinion may differ.
This is just like sorting a string of characters: given two strings, start at the beginning and compare each character; if there's a difference, the string with the lower value comes first, otherwise, look at the next characters from each string. If the strings are of different lengths, treat the shorter string as if it had a suffix of zeroes. In this case, the "characters" are integer values, obtained by calling [`Integer.parseInt()`](http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#parseInt(java.lang.String)). Additionally, implementing a [`Comparator`](http://java.sun.com/javase/6/docs/api/java/util/Comparator.html) for a `List<String>` would be helpful here. Then the [`Collections.sort()`](http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator)) method can be used. The comparator might look something like this: ``` final class MyComparator implements Comparator<List<String>> { public int compare(List<String> a, List<String> b) { /* Assume all strings are parseable to values * in range [0,Integer.MAX_VALUE] */ int len = Math.min(a.size(), b.size()); for (int idx = 0; idx < len; ++idx) { int va = Integer.parseInt(a.get(idx)), vb = Integer.parseInt(b.get(idx)); if (va != vb) return va - vb; } return va.size() - vb.size(); } @Override public boolean equals(Object o) { return o instanceof MyComparator; } @Override public int hashCode() { return MyComparator.class.hashCode(); } } ```
Sorting a List of LIst by the Value of the sublist
[ "", "java", "list", "collections", "sorting", "" ]
Here is a question that I have had for some time but never actually got around to asking... In quite a lot of the designer files that Visual Studio generates some of the variables are prefixed with global:: Can someone explain what this means, what this prefix does and where should I be using it?
The global namespace qualifier allows you to access a member in the global ("empty") namespace. If you were to call an unqualified type (e.g. MyClass.DoSomething() rather than MyNamespace.MyClass.DoSomething()), then it is assumed to be in the current namespace. How then do you qualify the type to say it is in the global/empty namespace? This code sample (console app) should illustrate its behaviour: ``` using System; namespace MyNamespace { public class Program { static void Main(string[] args) { MessageWriter.Write(); // writes "MyNamespace namespace" global::MessageWriter.Write(); // writes "Global namespace" Console.ReadLine(); } } // This class is in the namespace "MyNamespace" public class MessageWriter { public static void Write() { Console.WriteLine("MyNamespace namespace"); } } } // This class is in the global namespace (i.e. no specified namespace) public class MessageWriter { public static void Write() { Console.WriteLine("Global namespace"); } } ```
The prefix indicates the global namespace. Here is an example: ``` namespace Bar { class Gnat { } } namespace Foo { namespace Bar { class Gnat { } } class Gnus { Bar.Gnat a; // Foo.Bar.Gnat global::Bar.Gnat b; // Bar.Gnat } } ``` Note how the member a perhaps inadvertedly refers to the Foo.Bar.Gnat class. To avoid this use the global:: prefix.
What does global:: mean in the .Net designer files?
[ "", "c#", "namespaces", "" ]
I was told that to be a good developer, you should read a lot of other peoples source code. I think that sounds reasonable. So I ask you, what is the most beautifully written piece of open source software that is written in c++ out there? (Apply any definition of beautiful you like.)
You could look at the source code of MySQL GUI Tools. Its written using gtkmm, and the code does some interesting difficult-to-implement GUI things.
IMHO... [Notepad++](http://notepad-plus.sourceforge.net/uk/site.htm)
Most beautiful open source software written in c++
[ "", "c++", "" ]
I have a problem with debugging sessions. My program executes very well in a debug session but if I start a normal run, it behaves completely different. The problem is, that I cannot say, why it acts different. One possible reason is the slower execution time because you alway have to press `F6` or so. I tried to insert `Thread.sleep(1000);` but I don't get the instruction causing the different behaviour. So: What are hints, best practices to get to know why it acts so different in debug sessions?
Two solutions: a) Use poor man's debugger (print to the console) or use a logging framework. After the error happens, analyze the output. b) Write a test case that tries to reproduce the problem. Even if you can't find it that way, this will clean your code and sometimes solve the issue.
You might observe a race-condition that only occurs when there are no debug statements that slow down execution. It could be helpful to start with reviewing your threading model and to watch out for any possible locks.
What to do, if debug behaviour differs from normal execution?
[ "", "java", "debugging", "language-agnostic", "" ]
I'm trying to sanitize/format some input using regex for a mixed latin/ideographic(chinese/japanse/korean) full text search. I found an old example of someone's attempt at sanitizing a latin/asian language string on a forum of which I cannot find again (full credit to the original author of this code). I am having trouble fully understanding the regex portion of the function in particular why it seems to be treating the numbers 0, 2, and 3 differently than the rest of the latin based numbers 1,4-9 (basically it treats the numbers 0,4-9 properly, but the numbers 0,2-3 in the query are treated as if they are Asian characters). For example. I am trying to sanitize the following string: "hello 1234567890 蓄積した abc123def" and it will turn into: "hello 1 456789 abc1 def 2 3 0 蓄 積 し た 2 3" the correct output for this sanitized string should be: "hello 1234567890 蓄 積 し た abc123def" As you can see it properly spaces out the Asian characters but the numbers 0, 2, 3 are treated differently than all other number. Any help on why the regex is treating those numbers 0,2 and 3 differently would be a great help (or if you know of a better way of achieving a similar result)! Thank you I have included the function below ``` function prepareString($str) { $str = mb_strtolower(trim(preg_replace('#[^\p{L}\p{Nd}\.]+#u', ' ', $str))); return trim(preg_replace('#\s\s+#u', ' ', preg_replace('#([^\12544-\65519])#u', ' ', $str) . ' ' . implode(' ', preg_split('#([\12544-\65519\s])?#u', $str, -1, PREG_SPLIT_NO_EMPTY)))); } ``` **UPDATE: Providing context for clarity** I am authoring a website that will be launched in China. This website will have a search function and I am trying to write a parser for the search query input. Unlike the English language which uses a " " as the delimiter between words in a sentence, Chinese does not use spaces between words. Because of this, I have to re-format a search query by breaking apart each Chinese character and searching for each character individually within the database. Chinese users will also use latin/english characters for things such as brand names which they can mix together with their Chinese characters (eg. Ivy牛仔舖). What I would like to do is separate all of the English words out from the Chinese characters, and Seperate each Chinese character with a space. A search query could look like this: Ivy牛仔舖 And I would want to parse it so that it looks like this: Ivy 牛 仔 舖
After further research and the help of Alan's comments I was able to find the correct regex combinations to achieve a query parsing function for seperating lating and ideographic (chinese/japanese) characters that I'm happy with: ``` function prepareString($str) { $str = mb_strtolower(trim(preg_replace('#[^\p{L}\p{Nd}]+#u', ' ', $str))); return trim(preg_replace('#\s\s+#u', ' ', preg_replace('#\p{Han}#u', ' ', $str) . ' ' . implode(' ', preg_split('#\P{Han}?#u', $str, -1, PREG_SPLIT_NO_EMPTY)))); } $query = "米娜Mi-NaNa日系時尚館╭☆ 旅行 渡假風格 【A6402】korea拼接條紋口袋飛鼠棉" echo prepareString($query); //"mi nana a6402 korea 米 娜 日 系 時 尚 館 旅 行 渡 假 風 格 拼 接 條 紋 口 袋 飛 鼠 棉" ``` Disclaimer: I cannot read mandarin and the string above was copied from a Chinese website. if it says anything offensive please let me know and I will remove it.
I'm not set up to work with either PHP or Chinese, so I can't give you a definitive answer, but this should at least help you refine the question. As I see it, it's basically a four-step process: * get rid of undesirable characters like punctuation, replacing them with whitespace * normalize whitespace: get rid of leading and trailing spaces, and collapse runs of two or more spaces to one space * normalize case: replace any uppercase letters with their lowercase equivalents * wherever a Chinese character is next to another non-whitespace character, separate the two characters with a space For the first three steps, the first line of the code you posted should suffice: ``` $str = mb_strtolower(trim(preg_replace('#[^\p{L}\p{Nd}\.]+#u', ' ', $str))); ``` For the final step, I would suggest lookarounds: ``` $str = preg_replace( '#(?<=\S)(?=\p{Chinese})|(?<=\p{Chinese})(?=\S)#u', ' ', $str); ``` That should insert a space at any position where the next character is Chinese and the previous character is not whitespace, or the *previous* character is Chinese and the *next* character is not whitespace.
How to correctly parse a mixed latin/ideographic full text query with regex?
[ "", "php", "regex", "internationalization", "full-text-search", "cjk", "" ]
I use curl, in php and httplib2 in python to fetch URL. However, there are some pages that use JavaScript (AJAX) to retrieve the data after you have loaded the page and they just overwrite a specific section of the page afterward. So, is there any command line utility that can handle JavaScript? To know what I mean go to: monster.com and try searching for a job. You'll see that the Ajax is getting the list of jobs afterward. So, if I wanted to pull in the jobs based on my keyword search, I would get the page with no jobs. But via browser it works.
you can use PhantomJS [http://phantomjs.org](http://phantmjs.org) You can use it as below : ``` var page=require("webpage"); page.open("http://monster.com",function(status){ page.evaluate(function(){ /* your javascript code here $.ajax("....",function(result){ phantom.exit(0); }); */ }); }); ```
I think [env.js](http://github.com/thatcher/env-js/) can handle `<script>` elements. It runs in the [Rhino JavaScript interpreter](http://www.mozilla.org/rhino/) and has it's own XMLHttpRequest object, so you should be able to at least run the scripts manually (select all the `<script>` tags, get the .js file, and call `eval`) if it doesn't automatically run them. Be careful about running scripts you don't trust though, since they can use any Java classes. I haven't played with it since John Resig's first version, so I don't know much about how to use it, but there's a [discussion group on Google Groups](http://groups.google.com/group/envjs).
Command line URL fetch with JavaScript capabliity
[ "", "javascript", "curl", "wget", "httplib2", "" ]
Is there a difference in [double](http://msdn.microsoft.com/en-us/library/system.double.aspx) size when I run my app on 32 and 64 bit environment? If I am not mistaken the double in 32 bit environment will take up 16 digits after 0, whereas the double in 64 bit will take up 32 bit, am I right?
No, an [IEEE 754 double-precision floating point number](http://en.wikipedia.org/wiki/Double_precision_floating-point_format) is always 64 bits. Similarly, a single-precision `float` is always 32 bits. If your question is about C# and/or .NET specifically (as your tag would indicate), *all* of the data type sizes are fixed, independent of your system architecture. This is the same as Java, but different from C and C++ where type sizes do vary from platform to platform. It is common for the integral types to have different sizes on different architectures in C and C++. For instance, `int` was 16 bits wide in 16-bit DOS and 32 bits wide in Win32. However, the IEEE 754 standard is so ubiquitous for floating-point computation that the sizes of `float` and `double` do *not* vary on any system you will find in the real world--20 years ago `double` was 64 bits and so it is today.
In c# double is always 8 bytes (64 bits)
The Double byte size in 32 bit and 64 bit OS
[ "", "c#", "64-bit", "floating-point", "double", "ieee-754", "" ]
It probably isn't even possible to do this, but I will ask anyway. Is it possible to create a function that receives a string and then uses it as a right side argument for the goes to operator (=>) used in lambda? Actually, what I want to do is to be able to redefine an specific method of a specific class during runtime. I want to be write down a function with the program running and attaching it to a delegate. Is it possible?
The easiest way to do it is probably DLINQ as TcKs suggested. The fastest (I believe, in 3.5) is to create a [DynamicMethod](http://msdn.microsoft.com/en-us/library/system.reflection.emit.dynamicmethod.aspx). Its also the scariest method as well. You're essentially building a method using IL, which has about the same feel as writing code in machine language. I needed to do this to dynamically attach event handlers in some thing or another (well, I didn't need to do it, I just wanted to make unit testing events easier). It seemed a bit daunting at the time because I don't know crap about IL, but I figured out a simple way to accomplish this. What you do is create a method that does exactly what you want. The more compact the better. I'd provide an example if I could figure out exactly what you're trying to do. You write this method in a class within a DLL project and compile it in release mode. Then you open the DLL in Reflector and disassemble your method. Reflector gives you the option of what language you wish to disassemble to--select IL. You now have the exact calls you need to add to your dynamic method. Just follow the example on MSDN, switching out the example's IL for your reflected methods' code. Dynamic methods, once constructed, invoke at about the same speed as compiled methods (saw a test where dynamic methods could be called in ~20ms where reflection took over 200ms).
You have several ways how to do it: * dynamically create lambda expression (look at [Dynamic LINQ: Part 1](http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx)) * dynamically create CodeDom model and compile it at run-time (look at [CodeDom.Compiler namespace](http://msdn.microsoft.com/en-us/library/system.codedom.compiler.aspx) * dynamically create C#/VB.NET source code and compile it at run-time (look at [CSharpCodeProvider](http://msdn.microsoft.com/en-us/library/microsoft.csharp.csharpcodeprovider.aspx) and [VBCodeProvider](http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.vbcodeprovider(VS.80).aspx) classes ) * dynamically create object model, which can do same things like the method (look at [Strategy Design Pattern](http://en.wikipedia.org/wiki/Strategy_Pattern)
Creating a function dynamically at run-time
[ "", "c#", ".net-3.5", "delegates", "lambda", "" ]
I'm writing some code that has a lot of substitution. There's a **list<char> productions** which has a bunch of characters in it. I repeatedly need to replace every character in **productions** with the rules corresponding to it in a **map<char,char\*> productionRules**. So every character in **productions** might be replaced by zero or more characters as indicated by **productionRules**. I'm thinking there's 2 ways to do it: 1. iterate over **productions** and .insert() all replacement characters in **productions** before [.erase()'ing](https://stackoverflow.com/questions/1038708/erase-remove-contents-from-the-map-or-any-other-stl-container-while-iterating#1038757) each element 2. Create a NEW **list<char> newProductions** then reassign productions to refer to **newProductions**. Which is better? To .insert() and .erase() a whole lot or to just create a new one?
It depends on how likely it is that each character would be replaced by zero or >2 characters. If it's unlikely that any such replacement will take place, then you'll probably win by iterating over it. But if it's likely that you will often perform that operation you should almost certainly just create a new list. You can have your algorithm try to iterate over the list, and if you find you have to do a zero or >2 replacement, then create a new list. Whether or not this wins or not again depends on how likely you are to run into a case where you have to do such a replacement.
Create one is always appending to the end which is more efficient and less complicated to implement.
to insert() or to make new
[ "", "c++", "" ]
I want to write a function which can validate a given value (passed as a string) against possible values of an `enum`. In the case of a match, it should return the enum instance; otherwise, it should return a default value. The function may not internally use `try`/`catch`, which excludes using `Enum.Parse`, which throws an exception when given an invalid argument. I'd like to use something along the lines of a `TryParse` function to implement this: ``` public static TEnum ToEnum<TEnum>(this string strEnumValue, TEnum defaultValue) { object enumValue; if (!TryParse (typeof (TEnum), strEnumValue, out enumValue)) { return defaultValue; } return (TEnum) enumValue; } ```
As others have said, you have to implement your own `TryParse`. Simon Mourier is providing a full implementation which takes care of everything. If you are using bitfield enums (i.e. flags), you also have to handle a string like `"MyEnum.Val1|MyEnum.Val2"` which is a combination of two enum values. If you just call `Enum.IsDefined` with this string, it will return false, even though `Enum.Parse` handles it correctly. **Update** As mentioned by Lisa and Christian in the comments, `Enum.TryParse` is now available for C# in .NET4 and up. [MSDN Docs](https://msdn.microsoft.com/en-us/library/dd783499(v=vs.110).aspx)
Enum.IsDefined will get things done. It may not be as efficient as a TryParse would probably be, but it will work without exception handling. ``` public static TEnum ToEnum<TEnum>(this string strEnumValue, TEnum defaultValue) { if (!Enum.IsDefined(typeof(TEnum), strEnumValue)) return defaultValue; return (TEnum)Enum.Parse(typeof(TEnum), strEnumValue); } ``` Worth noting: a [`TryParse`](http://msdn.microsoft.com/en-us/library/dd783499.aspx) method was added in .NET 4.0.
How to TryParse for Enum value?
[ "", "c#", "enums", "" ]
I don't know alot about ASP.Net but I'm trying to make a new control for a message box. You enter some info and press a button. However, for some bizarre reason when the button is pressed, Page\_Load() gets called a second time, and all of the member variables are reset to null! I need those variables, and Page\_Load() has not reason to be called a second time! Of course the callstack is useless.
Remember, in ASP.Net every time you cause a postback of any kind, including handling events like button clicks, you're working with a brand new instance of your page class that must be rebuilt from scratch. Any work you've done previously to build the page on the server is *gone*. That means running the *entire* page life cycle, including your page load code, and not just the click code. > Always two there are, no more, no less. A request and a response.
When the page posts back, the Page\_Load method is called. Then, once the server actually processes the page and sends you a new one based on changes, the Page\_Load is called again, actually the first time on the new page sent to you. So if you are pulling data in the Page\_Load event or setting some values, enclose it in the following block: ``` if(!Page.IsPostBack) { } ``` to preserve some of your state. Otherwise, the instructions that you put into the Page\_Load event will execute every time. It helps to review the ASP.Net page lifecycle :)
ASP.Net: Page_Load() being called multiple times
[ "", "c#", "asp.net", "" ]
I have several PHP files include()ing other files from several other directories. In one of those included files: `foo/bar.php`, I want bar.php to include 3 other files contained in the directory foo. However bar.php is actually included by another file in another directory, which is included by yet another file, and so on. If I did: ``` include('./apple.php'); include('./orange.php'); ``` In `foo/bar.php`, will it include the correct files from the `foo` directory regardless of which file included bar.php in itself?
No. Using `./` at the start of your include file name forces it to be searched from the "current directory" as set by your web server (most probably the directory of the initial script, or the DocumentRoot, depending on the webserver). The way to get the behaviour you want depends on the value of your [`include_path`](http://au.php.net/manual/en/ini.core.php#ini.include-path) (which can be modified with [`set_include_path()`](http://au.php.net/set_include_path) if necessary). From the documentation for [`include()`](http://au.php.net/manual/en/function.include.php): > Files for including are first looked for in each `include_path entry` relative to the current working directory, and then in the directory of current script. E.g. if your `include_path` is **`libraries`**, current working directory is **`/www/`**, you included **`include/a.php`** and there is include "**`b.php`**" in that file, b.php is first looked in **`/www/libraries/`** and then in **`/www/include/`**. If filename begins with `./` or `../`, it is looked for only in the current working directory or parent of the current working directory, respectively. So, if there's no chance that the filename will be found in another directory in the `include_path` first, you could use `include('apple.php')`. If there is a possibility that apple.php exists elsewhere, and you want the copy in this folder to be used first, you could either use Matthew's suggestion, and ``` include(dirname(__FILE__).'/apple.php'); ``` or, if you have many files to include from the current directory: ``` old_include_path = set_include_path(dirname(__FILE__)); include('apple.php'); include('orange.php'); include('peach.php'); include('pear.php'); set_include_path(old_include_path); ```
Use the following instead: ``` include(dirname(__FILE__).'/apple.php'); ``` I don't know if what you've posted will work reliably or not, but this will.
Nested php includes using './'
[ "", "php", "" ]
Is there anything in Python akin to Java's JLS or C#'s spec?
There's no specification per se. The closest thing is the [Python Language Reference](http://docs.python.org/reference/), which details the syntax and semantics of the language.
You can check out the [Python Reference](http://docs.python.org/dev/reference/index.html)
Is there a Python language specification?
[ "", "python", "specifications", "" ]
What's the difference between `getPath()`, `getAbsolutePath()`, and `getCanonicalPath()` in Java? And when do I use each one?
Consider these filenames: `C:\temp\file.txt` - This is a path, an absolute path, and a canonical path. `.\file.txt` - This is a path. It's neither an absolute path nor a canonical path. `C:\temp\myapp\bin\..\\..\file.txt` - This is a path and an absolute path. It's not a canonical path. A canonical path is always an absolute path. Converting from a path to a canonical path makes it absolute (usually tack on the current working directory so e.g. `./file.txt` becomes `c:/temp/file.txt`). The canonical path of a file just "purifies" the path, removing and resolving stuff like `..\` and resolving symlinks (on unixes). Also note the following example with nio.Paths: ``` String canonical_path_string = "C:\\Windows\\System32\\"; String absolute_path_string = "C:\\Windows\\System32\\drivers\\..\\"; System.out.println(Paths.get(canonical_path_string).getParent()); System.out.println(Paths.get(absolute_path_string).getParent()); ``` While both paths refer to the same location, the output will be quite different: ``` C:\Windows C:\Windows\System32\drivers ```
The best way I have found to get a feel for things like this is to try them out: ``` import java.io.File; public class PathTesting { public static void main(String [] args) { File f = new File("test/.././file.txt"); System.out.println(f.getPath()); System.out.println(f.getAbsolutePath()); try { System.out.println(f.getCanonicalPath()); } catch(Exception e) {} } } ``` Your output will be something like: ``` test\..\.\file.txt C:\projects\sandbox\trunk\test\..\.\file.txt C:\projects\sandbox\trunk\file.txt ``` So, `getPath()` gives you the path based on the File object, which may or may not be relative; `getAbsolutePath()` gives you an absolute path to the file; and `getCanonicalPath()` gives you the unique absolute path to the file. Notice that there are a huge number of absolute paths that point to the same file, but only one canonical path. When to use each? Depends on what you're trying to accomplish, but if you were trying to see if two `Files` are pointing at the same file on disk, you could compare their canonical paths. Just one example.
What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?
[ "", "java", "" ]
I have a form with a list that shows information from a database. I want the list to update in real time (or almost real time) every time something changes in the database. These are the three ways I can think of to accomplish this: * Set up a timer on the client to check every few seconds: I know how to do this now, but it would involve making and closing a new connection to the database hundreds of times an hour, regardless of whether there was any change * Build something sort of like a TCP/IP chat server, and every time a program updates the database it would also send a message to the TCP/IP server, which in turn would send a message to the client's form: I have no idea how to do this right now * Create a web service that returns the date and time of when the last time the table was changed, and the client would compare that time to the last time the client updated: I could figure out how to build a web service, but I don't how to do this without making a connection to the database anyway The second option doesn't seem like it would be very reliable, and the first seems like it would consume more resources than necessary. Is there some way to tell the client every time there is a change in the database without making a connection every few seconds, or is it not that big of a deal to make that many connections to a database?
Try the [`SqlDependency` class](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldependency.aspx). It will fire an OnChange event whenever the results of its `SqlCommand` change. **EDIT**: Note that if there are large numbers of copies of your program running, it can generate excessive server load. If your app will be publicly available, it might not be a good idea. Also note that it can fire the event on different threads, so you'll need to use `Control.BeginInvoke` to update your UI.
You can use Event Notifications in SQL Server to raise events in .Net letting you know that the data has changed. See article linked below. Eric [SQL Server Event Notification](http://msdn.microsoft.com/en-us/library/ms190427.aspx)
How do I get a Windows Form client to update every time a SQL Server table changes?
[ "", "c#", ".net", "sql-server", "" ]
I have the following in a C# class: ``` public static readonly SortedDictionary<string, string> Fields = new SortedDictionary<string, string> { ... } ``` I was hoping there was a way to get Intellisense to provide prompts for all the keys defined in `Fields`. It supplies lists of the methods and properties in the class, including the `Fields` property, but when I go to access `Fields[` or `Fields["`, it says nothing other than that I need to supply a string key. Is there a way to have it tell me a list of the string keys since this is a static class property that is not at all dynamic or changed after compilation?
Do this instead: ``` public enum MyKeys { Key1, Key2, Key3 } public static readonly SortedDictionary<MyKeys, string> Fields = new SortedDictionary<MyKeys, string> { ... } ``` This will cause intellisense to pick up the enum type so you'll get the desired effect.
If the keys are static wouldn't you be better off using an enumeration as your key instead of a string? With an enumeration your compiler can tell you what the options are, but you can't do that with strings.
VS 2008 Intellisense for C# static dictionaries
[ "", "c#", "visual-studio-2008", "dictionary", "intellisense", "" ]
I have a bunch of these little bits of HTML code repeated over and over again: ``` <div class="collapse" id="any_mins"> <fieldset> <legend><img title="Click to expand" class="plus" alt="+" src="" />Heading</legend> <table class="mins_table"> lots of rows and cells go here </table> </fieldset> </div> ``` Inside the tables there are form elements, mainly textboxes and selects. I have a bit of jQuery that makes the `<legend>` heading highlighted if there are non-blank form elements in the containing table. It looks like this: ``` // input td tr tbody table legend img $("input[type='text'][value!=0]").parent().parent().parent().parent().show();//the table $("input[type='text'][value!=0]").parent().parent().parent().parent().siblings().children().attr("src", minus_path);//the image $("input[type='text'][value!=0]").parent().parent().parent().parent().siblings().addClass("highlighted")//the legend // option select td tr tbody table legend img $("option:selected[value!=0]").parent().parent().parent().parent().parent().show();//the table $("option:selected[value!=0]").parent().parent().parent().parent().parent().siblings().children().attr("src", minus_path);//the image $("option:selected[value!=0]").parent().parent().parent().parent().parent().siblings().addClass("highlighted") ``` This works, but is obviously the wrong way. Whats the right way?
``` $("input[type='text'][value!=0], option:selected[value!=0]"). closest("table").show().siblings("legend").addClass("highlighted"). find("img").attr("src", minus_path); ``` is how I would (break into multiple statements if preferred) [docs for `closest`](http://docs.jquery.com/Traversing/closest)
I think this could work with `has` selector: ``` $( "#table_id:has(input[type='text'][value!=0])").show( ); ```
Transversing the DOM in jQuery
[ "", "javascript", "jquery", "" ]
How can I get a client's address from a WCF Service Application? Also, is there an event raised when a client connects, possibly with address information?
In 3.0, this is quite hard; but was improved in 3.5 ([read Detect Client IP in WCF 3.5](http://keyvan.io/detect-client-ip-in-wcf-3-5)). I'm not aware of an event, though.
Which address are you looking for? The IP address? If so, I hope you're aware of the limitations on that - it won't be accurate if the client's on the other side of a NAT device or Internet proxy.
How do I get a client's address from a WCF Service Application?
[ "", "c#", ".net", "wcf", "windows-services", "" ]
I'm trying to use jQuery to parse the DHS Threat Level that they have in their [XML file](http://www.dhs.gov/dhspublic/getAdvisoryCondition), but I can't seem to get it to work. I'm very new with Javascript and non-presentational jQuery, so I'm probably missing something obvious. This is the XML file: ``` <?xml version="1.0" encoding="UTF-8" ?> <THREAT_ADVISORY CONDITION="ELEVATED" /> ``` This is the Javascript I've written: ``` $(document).ready(function() { $.ajax({ type : 'GET', url : 'http://www.dhs.gov/dhspublic/getAdvisoryCondition', dataType : 'xml', success : function parseThreatLevel(xml) { var threatLevel = $(xml).find('threat_advisory').attr('condition'); $('#nationalThreatLevel').append(threatLevel); } }); }); ``` Below is the HTML I'm trying to use. Thanks in advance for any help or advice! ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js'></script> <script type='text/javascript' src='lib/parseThreatLevel.js'></script> <title>National Threat Level</title> </head> <body> <div id='nationalThreatLevel'></div> </body> </html> ```
For security reasons, javascript has no access to other domains. To bypass this, you need to add a script on your server that does have access to other domains - often times called a *proxy*. PHP is a great option for many web-developers. What you would do is post the website url you want to hit to your local PHP script, it will then request that page and return the contents of it to your jQuery script which you can then parse for the data you desire. ### Non-SO Solutions: * [Cross domain AJAX querying with jQuery](http://jquery-howto.blogspot.com/2009/04/cross-domain-ajax-querying-with-jquery.html) ### Stackoverflow Archive: * Similar Material + [jQuery Cross Site Fetch](https://stackoverflow.com/questions/1050996/jquery-cross-site-fetch) + [Cross Domain Ajax Request with JQuery/PHP](https://stackoverflow.com/questions/752319/cross-domain-ajax-request-with-jquery-php/752403) * Related Material + [Why is cross-domain Ajax a security concern?](https://stackoverflow.com/questions/466737/why-is-cross-domain-ajax-a-security-concern)
All of your code is correct, but the problem is that you are making a cross domain request. The only way this will work with JavaScript / jQuery is if you can find a [JSONP](http://en.wikipedia.org/wiki/JSON) provider. Well, that or you write your own server side (PHP/ASP/ColdFusion/Something) to retrieve the XML and provide a local copy to be able to retrieve the XML using JavaScript.
Parsing the National Threat Level XML File with jQuery
[ "", "javascript", "jquery", "html", "xml", "ajax", "" ]
I have a date string of the form '2009/05/13 19:19:30 -0400'. It seems that previous versions of Python may have supported a %z format tag in strptime for the trailing timezone specification, but 2.6.x seems to have removed that. What's the right way to parse this string into a datetime object?
You can use the parse function from dateutil: ``` >>> from dateutil.parser import parse >>> d = parse('2009/05/13 19:19:30 -0400') >>> d datetime.datetime(2009, 5, 13, 19, 19, 30, tzinfo=tzoffset(None, -14400)) ``` This way you obtain a datetime object you can then use. As [answered](https://stackoverflow.com/questions/7804505/dateutil-parser-parse-gives-error-initial-value-must-be-unicode-or-none-not/7804999#7804999), dateutil2.0 is written for Python 3.0 and does not work with Python 2.x. For Python 2.x dateutil1.5 needs to be used.
`%z` is supported in Python 3.2+: ``` >>> from datetime import datetime >>> datetime.strptime('2009/05/13 19:19:30 -0400', '%Y/%m/%d %H:%M:%S %z') datetime.datetime(2009, 5, 13, 19, 19, 30, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000))) ``` On earlier versions: ``` from datetime import datetime date_str = '2009/05/13 19:19:30 -0400' naive_date_str, _, offset_str = date_str.rpartition(' ') naive_dt = datetime.strptime(naive_date_str, '%Y/%m/%d %H:%M:%S') offset = int(offset_str[-4:-2])*60 + int(offset_str[-2:]) if offset_str[0] == "-": offset = -offset dt = naive_dt.replace(tzinfo=FixedOffset(offset)) print(repr(dt)) # -> datetime.datetime(2009, 5, 13, 19, 19, 30, tzinfo=FixedOffset(-240)) print(dt) # -> 2009-05-13 19:19:30-04:00 ``` where `FixedOffset` is a class based on [the code example from the docs](https://docs.python.org/2/library/datetime.html#datetime.tzinfo.fromutc): ``` from datetime import timedelta, tzinfo class FixedOffset(tzinfo): """Fixed offset in minutes: `time = utc_time + utc_offset`.""" def __init__(self, offset): self.__offset = timedelta(minutes=offset) hours, minutes = divmod(offset, 60) #NOTE: the last part is to remind about deprecated POSIX GMT+h timezones # that have the opposite sign in the name; # the corresponding numeric value is not used e.g., no minutes self.__name = '<%+03d%02d>%+d' % (hours, minutes, -hours) def utcoffset(self, dt=None): return self.__offset def tzname(self, dt=None): return self.__name def dst(self, dt=None): return timedelta(0) def __repr__(self): return 'FixedOffset(%d)' % (self.utcoffset().total_seconds() / 60) ```
How to parse dates with -0400 timezone string in Python?
[ "", "python", "datetime", "timezone", "" ]
this is my addCard function which takes a playingCard as a parameter then hands over the address of its self to an allocated array of pointers to playingCard objects. ``` void cardHand::addCard(playingCard card) { theHand[nElems++] = &card; } // addCard() ``` now when i run my program it runs fine but then crashes when the destructor is called. ``` cardHand::~cardHand() { for(int c = 0;c<MAX;c++) { if(theHand[c] != NULL) delete theHand[c]; // here is the problem } delete [] theHand; } // class destructor ``` is it crashing because I'm only handing over the address of the playingCard object in the addCard function. should it be a pointer instead?
The problem is here `void cardHand::addCard(playingCard card) { theHand[nElems++] = &card; }` You store address of the temporary card object which will be destructed at the end of the addCard method. And in your destructor you attempt to delete it again. You have two options. **First**: make addCard to accept just card configuration and create your card with `new` in the `addCard` method. **Second**: accept card by pointer but then your cardHand's destructor can't be responsible for card deletion. And deletion will perform Deck object which created all the cards.
When you say: ``` theHand[nElems++] = &card; ``` You are storing the address of a function parameter, which is effectively a local variable. This is always a bad thing to do, and in your case causes the crash when you attempt to delete it. You probably want something like: ``` theHand[nElems++] = new playingcCard( card ); ``` but the real solution is to use a std::vector of playingCard and to do away with dynamic allocation altogether.
destructor problem
[ "", "c++", "pointers", "destructor", "" ]
Is there a way to use reflection to completely "scan" an assembly to see if System.IO.File or System.IO.Directory is ever used? These are just example classes. Just wondering if there is a way to do it via reflection (vs code analysis). **update**: see comments
As Tommy Carlier suggested, it's very easy to do with [Cecil](http://mono-project.com/Cecil). ``` using Mono.Cecil; // .. var assembly = AssemblyFactory.GetAssembly ("Foo.Bar.dll"); var module = assembly.MainModule; bool references_file = module.TypeReferences.Contains ("System.IO.File"); ```
The fantastic NDepend tool will give you this sort of dependency information. Load your dll in NDepend and either use the GUI to find what you want, or the following CQL query: ``` SELECT TYPES WHERE IsDirectlyUsing "System.IO.File" ``` and you should get a list of all the types that use this.
.NET / C# - Reflection - System.IO.File ever used
[ "", "c#", ".net", "reflection", "" ]
Ok, lets say I go to <http://www.google.com/intl/en_ALL/images/logo.gif> , which is not really a document, but an image, iin my browser. Does it still have a document object? Can I use `javascript:` in my location bar? Wha'ts the deal with this? Thanks.
A quick look with Firebug reveals that yes indeed, there is a DOM and a document object. For example, `javascript:alert(document.title)` in the location bar gives "logo.gif (GIF Image, 276x110 pixels)". This results from the construction of the following document by the browser: ``` <html> <head> <title>logo.gif (GIF Image, 276x110 pixels)</title> </head> <body> <img src="http://www.google.com/intl/en_ALL/images/logo.gif" alt="http://www.google.com/intl/en_ALL/images/logo.gif"/> </body> </html> ``` This is also true in Chrome (with a slightly different string for the title); the HTML is ``` <html> <body style="margin: 0px;"> <img style="-webkit-user-select: none" src="http://www.google.com/intl/en_ALL/images/logo.gif"> </body> </html> ``` In IE, it appears that `document.title` is empty, but `javascript:alert(document.body.clientWidth)` gives a result equal to the client area of the browser, so it looks like there's a DOM there as well. The HTML is as follows: ``` <html> <head> <title></title> </head> <body> <img src="http://www.google.com/intl/en_ALL/images/logo.gif" complete="complete"/> </body> </html> ```
It depends on the browser. If you go to that URL in firefox, for example, and open the DOM Inspector, you will see an `html`, `body` and `img` tag; also, typing `javascript:alert(document)` in the location bar will alert `[object ImageDocument]`. IE8 exhibits similar behaviour (but alerts just `[object]`).
DOM when not an actual document
[ "", "javascript", "" ]
I need to write a delegate function that can 'wrap' some while/try/catch code around a basic UDP call to verify the link. I made it work for Func for a function that has no arguments, but I can't make it work for Action, which has an argument (but no return). I can't seem to pass in the argument in a logical way without the compiler complaining. Am I going about this all wrong? I'm new to C# and I'm essentially trying to mimick the idea of a function pointer. Should I not be overloading this function? I know you can't overload delegates (I assume that's why Func and Action exist). This works: ``` protected TResult udpCommand<TResult>(Func<TResult> command) { TResult retValue = default(TResult); while (!linkDownFail) { try { retValue = command(); break; } catch { LinkStateCallBack(ip, getLinkStatus()); if (linkDownFail) throw new LinkDownException(); Thread.Sleep(100); } } return retValue; } ``` But this does not: ``` protected void udpCommand<T>(Action<T> command(T value)) { while(!linkDownFail) { try { command(value); break; } catch { LinkStateCallBack(ip, getLinkStatus()); if (linkDownFail) throw new LinkDownException(); Thread.Sleep(100); } } return; } ``` Calling convention (for one that works): ``` udpCommand<uint>(someUdpCommand); ```
If you want this to be generic enough to handle any number of arguments, try using the non-genernic Action delegate: ``` protected void udpCommand(Action command) { while(!linkDownFail) { try { command(); break; } catch { LinkStateCallBack(ip, getLinkStatus()); if (linkDownFail) throw new LinkDownException(); Thread.Sleep(100); } } return; } ``` In C# 3.0, you can call it like this: ``` udpCommand(() => noParameterMethod()); udpCommand(() => singleParameterMethod(value)); udpCommand(() => manyParameterMethod(value, value2, value3, value4)); ``` In C# 2.0 it's a little uglier: ``` udpCommand(delegate { noParameterMethod(); }); udpCommand(delegate { singleParameterMethod(value); }); udpCommand(delegate { manyParameterMethod(value, value2, value3, value4); }); ``` This gives you deferred execution without locking you into a particular method signature. **EDIT** I just notice I kinda stole Marc Gravell's comment... apologies Marc. To answer how you might reduce your duplication, you can have the `Action` method call the `Func<T>` method, like this: ``` protected void udpCommand(Action command) { udpCommand(() => { command(); return 0; }); } ``` I believe (and I may be wrong) that returning 0 is no more costly than (implicitly) returning void, but I may be way off here. Even it it does have a cost, it would only put a tiny itty bitty snoodge extra on the stack. In most cases, the additional cost won't ever cause you any grief.
Do you mean: ``` protected void udpCommand<T>(Action<T> command, T value) {...} ``` With calling: ``` udpCommand(someUdpCommand, arg); ``` Note that this may work better on C# 3.0, which has stronger generic type inference than C# 2.0.
Using Action<T> as an argument in C# (mimicking a function pointer)
[ "", "c#", "delegates", "" ]
Here is my ultimate goal... to take this xml file.. ``` <?xml version="1.0"?> <Songs> <Song> <Name>Star Spangled Banner</Name> <Artist>Francis Scott Key</Artist> <Genre>Patriotic</Genre> </Song> <Song> <Name>Blankity Blank Blank</Name> <Artist>Something Something</Artist> <Genre>Here here</Genre> </Song> </Songs> ``` and load it into a list view component when my application starts up. I also want to have the "Songs" be separated into categories by either Artist or Genre. I'm new to Visual C#, but I've been coding for a while, so I'm really just looking for someone to point me in the right direction here... Looking on google it looks like people seem to read XML files and loop through the contents to populate a list view component. Which seems impractical on the count that there are all of these "dataset" and "binding source" things available. It looks like there should be a way that I load the XML file into a data set, then link a binding source to the dataset, and then finally link the listview to the binding source (or something along these lines).. Though I can't seem to find any "setter" methods on any of these components which would do this, I've also looked up and down the "properties" window for these components with no success.
With [Linq to XML](http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx), you can do something like the following: ``` XDocument loaded = XDocument.Load("myfile.xml"); var songs = from x in loaded.Descendants( "Song" ) select new { Name = x.Descendants( "name" ).First().Value, Category = x.Descendants( "artist" ).First().Value, Genre = x.Descendants( "genre" ).First().Value, }; //Returns an anonymous custom type MyListView.DataSource = songs; MyListView.DataBind(); ``` Now you can use the three fields (from the anonymous type you just returned) in your `ListView`'s template and your data will be displayed.
You can use LINQ to XML - <http://msdn.microsoft.com/en-us/library/bb387098.aspx>.
Visual C# 2008, reading an XML file and populating a listView
[ "", "c#", "xml", "winforms", "listview", "dataset", "" ]
An easy problem, but for some reason I just can't figure this out today. I need to resize an image to the maximum possible size that will fit in a bounding box while maintaining the aspect ratio. Basicly I'm looking for the code to fill in this function: ``` void CalcNewDimensions(ref int w, ref int h, int MaxWidth, int MaxHeight); ``` Where w & h are the original height and width (in) and the new height and width (out) and MaxWidth and MaxHeight define the bounding box that the image must fit in.
Find which is smaller: `MaxWidth / w` or `MaxHeight / h` Then multiply `w` and `h` by that number **Explanation:** You need to find the scaling factor which makes the image fit. To find the scaling factor, `s`, for the width, then `s` must be such that: `s * w = MaxWidth`. Therefore, the scaling factor is `MaxWidth / w`. Similarly for height. The one that requires the most scaling (smaller `s`) is the factor by which you must scale the whole image.
Based on Eric's suggestion I'd do something like this: ``` private static Size ExpandToBound(Size image, Size boundingBox) { double widthScale = 0, heightScale = 0; if (image.Width != 0) widthScale = (double)boundingBox.Width / (double)image.Width; if (image.Height != 0) heightScale = (double)boundingBox.Height / (double)image.Height; double scale = Math.Min(widthScale, heightScale); Size result = new Size((int)(image.Width * scale), (int)(image.Height * scale)); return result; } ``` I might have gone a bit overboard on the casts, but I was just trying to preserve precision in the calculations.
Resize Image to fit in bounding box
[ "", "c#", "algorithm", "image-processing", "image-manipulation", "" ]
I have been reading through this wonderful website regarding the recommended Python IDEs and have narrowed it down to either 1. WingIDE 2. KomodoIDE which you guys will recommend for the purpose of developing Pylons apps? I know that most questions have been asked pertaining to Python IDEs but how about Python web framework IDEs which is a mishmash of various templating languages and Python itself. One con i have to raise about WingIDE on Windows is that it has an AWFUL interface (probably cos of the GTK+ toolkit?) I have been using e-text editor all the while and increasingly been dissatisfied with it especially when its unable to do correct syntax highlighting at times. Furthermore I am hoping syntax coloration can be done for Mako templates. Thank you very much all and have a great day!
after very very careful comparison, KomodoIDE 5.1 is most suitable for my purposes. Reasons: 1. Extensibility 2. Support for Mako and YUI (required by me) 3. Native interface support (no GTK unfamiliarity) 4. Support for Mercurial SCM (required by me) thats all I guess. I am extremely satisfied with KomodoIDE and have just shelled out some money to buy it. I figured when making a choice of tools, spend a day or two (yes, it takes time) trying them out and choosing what best suits your day-to-day purposes. If its just your first time coding, using a standard free tool or open source tool is far more useful than expending the time to find out the best tool. Only after some degree of expertise is acquired, you have a very narrow spectrum of requirements/preferences which will make choosing a tool far easier.
Did you try [Eclipse](http://eclipse.org/) with [PyDev](http://pydev.sourceforge.net/) plugin? Which is FREE plus works for any OS. Screenshots [at the PyDev website](http://pydev.sourceforge.net/screenshots.html). [![Code completion screenshot](https://i.stack.imgur.com/mbSpO.png)](https://i.stack.imgur.com/mbSpO.png) (source: [sourceforge.net](http://pydev.sourceforge.net/images/screenshot/screenshot2.png))
Recommended IDE for developing Pylons apps
[ "", "python", "ide", "pylons", "" ]
How to find available COM ports in my PC? I am using framework v1.1. Is it possible to find all COM ports? If possible, help me solve the problem.
As others suggested, you can use WMI. You can find a sample [in CodeProject](http://www.codeproject.com/KB/dotnet/WMICodeCreator_Demo.aspx?fid=1533382&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2880850) ``` try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSSerial_PortName"); foreach (ManagementObject queryObj in searcher.Get()) { Console.WriteLine("-----------------------------------"); Console.WriteLine("MSSerial_PortName instance"); Console.WriteLine("-----------------------------------"); Console.WriteLine("InstanceName: {0}", queryObj["InstanceName"]); Console.WriteLine("-----------------------------------"); Console.WriteLine("MSSerial_PortName instance"); Console.WriteLine("-----------------------------------"); Console.WriteLine("PortName: {0}", queryObj["PortName"]); //If the serial port's instance name contains USB //it must be a USB to serial device if (queryObj["InstanceName"].ToString().Contains("USB")) { Console.WriteLine(queryObj["PortName"] + " is a USB to SERIAL adapter/converter"); } } } catch (ManagementException e) { Console.WriteLine("An error occurred while querying for WMI data: " + e.Message); } ```
Framework v1.1 AFAIK doesn't allow you to do this. In 2.0 there is a static function ``` SerialPort.GetPortNames() ``` <http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.getportnames.aspx>
How to find available COM ports?
[ "", "c#", "serial-port", "" ]
I want to convert a nullable DateTime (`DateTime?`) to a `DateTime`, but I am getting an error: > Cannot implicitly convert type 'System.DateTime?' to > 'System.DateTime'. An explicit conversion exists (are you missing a > cast?) I have attempted the following: ``` DateTime UpdatedTime = (DateTime)_objHotelPackageOrder.UpdatedDate == null ? DateTime.Now : _objHotelPackageOrder.UpdatedDate; ```
You want to use the [null-coalescing operator](http://msdn.microsoft.com/en-us/library/ms173224.aspx), which is designed for exactly this purpose. Using it you end up with this code. ``` DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now; ```
MS already made a method for this, so you dont have to use the null coalescing operator. No difference in functionality, but it is easier for non-experts to get what is happening at a glance. ``` DateTime updatedTime = _objHotelPackageOrder.UpdatedDate.GetValueOrDefault(DateTime.Now); ```
How to convert DateTime? to DateTime
[ "", "c#", ".net", "datetime", "" ]
I have 4 base classes: ``` class A { virtual SomeMethod () { <code> } } class A<T> { virtual SomeMethod () { <code> } } class B { virtual SomeMethod () { <code> } } class B<T2> { virtual SomeMethod () { <code> } } ``` Now, i have 4 implementations (each implementation is derived from the corresponding base type). ``` class Aa : A { override SomeMethod () { <code> } } class Aa<Tt> : A<T> { override SomeMethod () { <code> } } class Bb : b { override SomeMethod () { <code> } } class Bb<Tt2> : B<T2> { override SomeMethod () { <code> } } ``` Now, i need to add SomeMethod implementation (it should be an override for the one from the base class). The SAME ONE for all of the mentioned derived classes. What is the best solution? (i will share all my ideas right after the question is solved. since if i put my implementation here, the discussion will most likely go my direction, but i'm not quite sure if i'm right). Thank you for your great ideas!!
So you want one implementation for some 4 classes, and a different implementation for some other 4 classes? Perhaps the [Strategy pattern](http://en.wikipedia.org/wiki/Strategy_pattern) would work. ``` interface ISomeMethodStrategy { string SomeMethod(string a, string b); } class DefaultStrategy : ISomeMethodStrategy { public string SomeMethod(string a, string b) { return a + b; } public static ISomeMethodStrategy Instance = new DefaultStrategy(); } class DifferentStrategy : ISomeMethodStrategy { public string SomeMethod(string a, string b) { return b + a; } public static ISomeMethodStrategy Instance = new DifferentStrategy(); } class A { private ISomeMethodStrategy strategy; private string a, b, c; public A() : this(DefaultStrategy.Instance) {} protected A(ISomeMethodStrategy strategy){ this.strategy = strategy; } public void SomeMethod() { a = strategy.SomeMethod(b, c); } } class Aa : A { public Aa() : base(DifferentStrategy.Instance) {} } ``` I've implemented the pattern here with an interface, but you can do the same with delegates.
A). it would be better if you did post your implementation regardless of whther you think it would skew anything B). the concept of having a `class A` and a generic form `class A<T>` seems *really* alien. It's like your generic class has an exclusion for one specific case, which means it's less generic than other generics, i.e. wierd. C). Why would you not just have all 4 base classes inherit from a higher class X if you mean to literally have the same method on each, or from an interface if you merely mean for them to implement this common method. Seems too obvious, have I missed something in your question?
Tricky architecture question. 4 Base classes require a bit of extensibility
[ "", "c#", "design-patterns", "architecture", "polymorphism", "" ]
How do I get the selected value from a dropdown list using JavaScript? ``` <form> <select id="ddlViewBy"> <option value="1">test1</option> <option value="2" selected="selected">test2</option> <option value="3">test3</option> </select> </form> ```
Given a select element that looks like this: ``` <select id="ddlViewBy"> <option value="1">test1</option> <option value="2" selected="selected">test2</option> <option value="3">test3</option> </select> ``` Running this code: ``` var e = document.getElementById("ddlViewBy"); var value = e.value; var text = e.options[e.selectedIndex].text; ``` Results in: ``` value == 2 text == "test2" ``` --- Interactive example: ``` var e = document.getElementById("ddlViewBy"); function onChange() { var value = e.value; var text = e.options[e.selectedIndex].text; console.log(value, text); } e.onchange = onChange; onChange(); ``` ``` <form> <select id="ddlViewBy"> <option value="1">test1</option> <option value="2" selected="selected">test2</option> <option value="3">test3</option> </select> </form> ```
Plain JavaScript: ``` var e = document.getElementById("elementId"); var value = e.options[e.selectedIndex].value; var text = e.options[e.selectedIndex].text; ``` jQuery: ``` $("#elementId :selected").text(); // The text content of the selected option $("#elementId").val(); // The value of the selected option ``` [AngularJS](http://en.wikipedia.org/wiki/AngularJS): (<http://jsfiddle.net/qk5wwyct>): ``` // HTML <select ng-model="selectItem" ng-options="item as item.text for item in items"> </select> <p>Text: {{selectItem.text}}</p> <p>Value: {{selectItem.value}}</p> // JavaScript $scope.items = [{ value: 'item_1_id', text: 'Item 1' }, { value: 'item_2_id', text: 'Item 2' }]; ```
Get selected value in dropdown list using JavaScript
[ "", "javascript", "html-select", "" ]
I can write an assertion message one of two ways. Stating success: ``` assertEquals( "objects should be identical", expected, actual ); ``` Or stating the condition of being broken: ``` assertEquals( "objects aren't identical", expected, actual ); ``` Is there a standard for this in JUnit specifically? If not, what are the arguments for each side? P.S. I've seen articles on the web demonstrating both of these without explanation, so just saying "search Google" is not an answer! **[UPDATE]** Everyone is getting hung up on the fact that I used `assertEquals` and therefore the message is probably useless. But of course that's just because I wanted to illustrate the question simply. So imagine instead it's: ``` assertTrue( ... big long multi-line expression ... ); ``` Where a message is useful.
I rarely even bother with a message, at least for `assertEquals`. Any sensible test runner will explain that you were using `assertEquals` and the two things which were meant to be equal. Neither of your messages give more information than that. I usually find that unit test failures are transient things - I'll rapidly find out what's wrong and fix it. The "finding out what's wrong" usually involves enough detail that a single message isn't going to make much difference. Consider "time saved by having a message" vs "time spent thinking of messages" :) EDIT: Okay, one case where I *might* use a message: when there's a compact description in text which isn't obvious from the string representation of the object. For example: "Expected date to be December 1st" when comparing dates stored as milliseconds. I wouldn't worry about how you express it exactly though: just make sure it's obvious from the message which way you mean. Either "should be" or "wasn't" is fine - just "December 1st" wouldn't be obvious.
According to the junit API the message is the "the identifying message for the AssertionError" so its not a message describing the condition that should be met but a message describing what's wrong if the condition isn't met. So in your example "objects aren't identical" seems to be more conformant.
Should the JUnit message state the condition of success or failure?
[ "", "java", "unit-testing", "junit", "" ]
I'm learning about C++ in a class right now and I don't quite grok pure virtual functions. I understand that they are later outlined in a derived class, but why would you want to declare it as equal to 0 if you are just going to define it in the derived class?
Briefly, it's to make the class abstract, so that it can't be instantiated, but a child class can override the pure virtual methods to form a concrete class. This is a good way to define an interface in C++.
This forces a derived class to define the function.
What are the uses of pure virtual functions in C++?
[ "", "c++", "virtual-functions", "pure-virtual", "" ]
My question is very related to this one: [Multiple dynamic data sources for a servlet context](https://stackoverflow.com/questions/932625/multiple-dynamic-data-sources-for-a-servlet-context). However I haven’t found a proper solution just yet and would like to ask it again. I have a little JSF application that talks to a MS SQL Server via JDBC. Tomcat is used as the web container. The application retrieves and stores its data from a single database. A login screen is provided. If the credentials match the ones stored in the database then access is granted and I can play around with the application. Now I would like to add more databases and provide a login screen which not only requests the username and password but the database name as well. Different databases are used because I would like to have some for testing and development. The backup plans are also not the same for every database. Currently I use JNDI Resources to look up the databases in my code. However this forces me to edit context.xml and web.xml and to restart tomcat. I don’t want to do that. The restart forces me to run around an tell everyone: “Hey I am rebooting do you mind losing all your connections?” Is the some more dynamic way to do that?
For your purposes, you should really have three separate application server instances (either on three separate machines, or on the same machine listening to different ports, or different host headers etc). The development server instance should always look up the development database, the staging server looks up the staging database etc, and JNDI should be set up to reflect this. That's what JNDI is for. That said, if you *must* set things up with just a single application server, you will probably need to look into writing a custom [authentication realm](http://tomcat.apache.org/tomcat-5.5-doc/realm-howto.html) that does this. You could either do the actual work of determining which data source to use yourself, or look into something like [Hibernate Shards](https://www.hibernate.org/414.html).
I dont know the answer but if you call `OSQL -L` from JNI you can get a list of available SQL database instances in the area. Then you can connect and get the list of databases within. So: 1. user enters username and password 2. app runs OSQL -L to get the list of instances and provides a select list 3. user selects instance, jdbc uses credentials in step 1 to get a list of databases from the instance 4. jdbc uses selected database to connect.
Dynamically access multiple databases?
[ "", "java", "jdbc", "jndi", "" ]
The method `ObjectOutputStream.writeStreamHeader()` can be overridden to prepend or append data to the header. However, if that data is based on an argument passed to the derived class's constructor like: ``` public class MyObjectOutputStream extends ObjectOutputStream { public MyObjectOutputStream( int myData, OutputStream out ) throws IOException { super( out ); m_myData = myData; } protected void writeStreamHeader() throws IOException { write( m_myData ); // WRONG: m_myData not initialized yet super.writeStreamHeader(); } private final int m_myData; } ``` it doesn't work because `super()` is called before `m_myData` is initialized and `super()` calls `writeStreamHeader()`. The only way I can think to work around this is by using `ThreadLocal` like: ``` public class MyObjectOutputStream extends ObjectOutputStream { public MyObjectOutputStream( int myData, OutputStream out ) throws IOException { super( thunk( myData, out ) ); } protected void writeStreamHeader() throws IOException { write( m_myData.get().intValue() ); super.writeStreamHeader(); } private static OutputStream thunk( int myData, OutputStream out ) { m_myData.set( myData ); return out; } private static final ThreadLocal<Integer> m_myData = new ThreadLocal<Integer>(); } ``` This seems to work, but is there a better (less clunky) way?
There is a general way to solve this sort of problem. Make the class and inner class and reference a variable in the outer scope. (Note, this only works with `-target 1.4` or greter, which is the default in current versions of javac. With `-target 1.3` you will get an NPE.) ``` public static ObjectOutputStream newInstance( final int myData, final OutputStream out ) throws IOException { return new ObjectOutputStream(out) { @Override protected void writeStreamHeader() throws IOException { write(myData); super.writeStreamHeader(); } }; } ``` But, it's probably easier just to write the data out before constructing the `ObjectOuputStream`.
It is generally a bad idea to call non-final methods from the constructor (for exactly the reason you presented). Can you achieve your custom serialization without extending ObjectOutputStream? I am thinking about stream composition. For example, you could prepend your header by writing it to the underlying OutputStream before ObjectOutputStream does. This can obviously not be done in a subclass of ObjectOutputStream, but it can easily be done from the outside. ``` out.write(myExtraHeader); ObjectOutputStream oos = new ObjectOutputStream(out); ``` If you want, you can wrap this all up nicely behind the ObjectOutput interface as Stu Thompson suggested in his answer, so that it can look to the outside almost like an ObjectOutputStream. **Update:** Looking at the JavaDocs and source for ObjectOutputStream, there is a second (protected) constructor, that does not call `writeStreamHeader()`. However, this constructor also does not initialize other internal structures. To quote the docs, it is intended "for subclasses that are completely reimplementing ObjectOutputStream to not have to allocate private data just used by this implementation of ObjectOutputStream". In this case it also calls some other methods, such as "writeObjectOverride". Messy...
How to override ObjectOutputStream.writeStreamHeader()?
[ "", "java", "constructor", "thread-local", "objectoutputstream", "" ]
I have a project that contains a single module, and some dependencies. I'd like to create a JAR, in a separate directory, that contains the compiled module. In addition, I would like to have the dependencies present beside my module. No matter how I twist IntelliJ's "build JAR" process, the output of my module appears empty (besides a `META-INF` file).
#### Instructions: `File` -> `Project Structure` -> `Project Settings` -> `Artifacts` -> Click `+` (plus sign) -> `Jar` -> `From modules with dependencies...` Select a `Main Class` (the one with `main()` method) if you need to make the jar runnable. Select `Extract to the target Jar` Click `OK` Click `Apply`/`OK` The above sets the "skeleton" to where the jar will be saved to. To actually build and save it do the following: `Build` -> `Build Artifact` -> `Build` Try Extracting the .jar file from: ``` ProjectName ┗ out ┗ artifacts ┗ ProjectName_jar ┗ ProjectName.jar ``` #### References: * (Aug 2010) <http://blogs.jetbrains.com/idea/2010/08/quickly-create-jar-artifact/> (Here's how to build a jar with IntelliJ 10) * (Mar 2023) <https://www.jetbrains.com/help/idea/compiling-applications.html#package_into_jar>
This is still an issue in 2017, I hope it will help somebody out there! I found 2 possibilities to create working jar-s under IntelliJ 2017.2 **1. Creating artifact from IntelliJ:** * Go to project structure: [![File menu](https://i.stack.imgur.com/yHR9P.png)](https://i.stack.imgur.com/yHR9P.png) * Create a new artifact: [![Create a new artifact](https://i.stack.imgur.com/wEbRv.png)](https://i.stack.imgur.com/wEbRv.png) * Select the main class, and be sure to change the manifest folder: [![enter image description here](https://i.stack.imgur.com/qvw7j.png)](https://i.stack.imgur.com/qvw7j.png) You have to change manifest directory: ``` <project folder>\src\main\java ``` replace "java" with "resources" ``` <project folder>\src\main\resources ``` This is how it should look like: [![correct way for new manifest](https://i.stack.imgur.com/SZvc6.png)](https://i.stack.imgur.com/SZvc6.png) * Then you choose the dependencies what you want to be packed IN your jar, or NEAR your jar file * To build your artifact go to build artifacts and choose "rebuild". It will create an "out" folder with your jar file and its dependencies. [![enter image description here](https://i.stack.imgur.com/5B2Vo.png)](https://i.stack.imgur.com/5B2Vo.png) **2. Using maven-assembly-plugin** Add build section to the pom file ``` <build> <plugins> <plugin> <artifactId>maven-assembly-plugin</artifactId> <configuration> <finalName>ServiceCreate</finalName> <appendAssemblyId>false</appendAssemblyId> <archive> <manifest> <mainClass>com.svt.optimoo.App</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> ``` * Create a new run/debug configuration: [![Create a new run/debug configuration:](https://i.stack.imgur.com/kxSjf.png)](https://i.stack.imgur.com/kxSjf.png) * Choose application: [![Choose application](https://i.stack.imgur.com/UIQu2.png)](https://i.stack.imgur.com/UIQu2.png) * Fill in the form * Add the "assembly:single" maven goal after build to be executed last [![enter image description here](https://i.stack.imgur.com/xkgpA.png)](https://i.stack.imgur.com/xkgpA.png) [![Final setup](https://i.stack.imgur.com/t354C.png)](https://i.stack.imgur.com/t354C.png) * Save it, then run [![enter image description here](https://i.stack.imgur.com/g6IsY.png)](https://i.stack.imgur.com/g6IsY.png) This procedure will create the jar file under the "target" folder [![JAR file location](https://i.stack.imgur.com/irtgF.png)](https://i.stack.imgur.com/irtgF.png)
How to build JARs from IntelliJ IDEA properly?
[ "", "java", "intellij-idea", "build", "jar", "artifact", "" ]
I am guessing getElementById doesn't work with radio buttons when you want to get the value of it or to find out if it is checked? I say this because I did this: ``` <input id="radio1" type="radio" name="group1" value="h264" checked="checked" /> <input id="radio2" type="radio" name="group1" value="flv" /> ``` To get the value of the selected one I did this: ``` function getRadioValue() { if(document.getElementById('radio1').value=='h264'){ return 'h264'; } else{ return 'flv'; } } ``` However, firebug keeps telling me: ``` document.getElementById("radio1") is null [Break on this error] if(document.getElementById('radio1').checked==true){ ``` What am I doing wrong? Thanks all
You should call `document.getElementById` after the document is loaded. Try executing your code like this: ``` window.onload = function() { alert(getRadioValue()); } ```
Here is a reliable function to get the radio button selection. Since radio buttons are grouped by the `name` attribute, it makes sense to use [getElementsByName](https://developer.mozilla.org/En/DOM/Document.getElementsByName)... ``` function getRadioVal(radioName) { var rads = document.getElementsByName(radioName); for(var rad in rads) { if(rads[rad].checked) return rads[rad].value; } return null; } ``` In your case, you'd use it like this... ``` alert(getRadioVal("group1")); ```
getElementById not playing nice with Radio Buttons
[ "", "javascript", "" ]
I have a page that allows the user to download a dynamically-generated file. It takes a long time to generate, so I'd like to show a "waiting" indicator. The problem is, I can't figure out how to detect when the browser has received the file so that I can hide the indicator. I'm requesting a hidden form, which [POSTs](https://en.wikipedia.org/wiki/POST_%28HTTP%29) to the server, and targets a hidden iframe for its results. This is, so I don't replace the entire browser window with the result. I listen for a "load" event on the iframe, hoping that it will fire when the download is complete. I return a "`Content-Disposition: attachment`" header with the file, which causes the browser to show the "Save" dialog. But the browser doesn't fire a "load" event in the iframe. One approach I tried is using a `multi-part` response. So it would send an empty HTML file, as well as the attached downloadable file. For example: ``` Content-type: multipart/x-mixed-replace;boundary="abcde" --abcde Content-type: text/html --abcde Content-type: application/vnd.fdf Content-Disposition: attachment; filename=foo.fdf file-content --abcde ``` This works in Firefox; it receives the empty HTML file, fires the *"load"* event, and then shows the *"Save"* dialog for the downloadable file. But it fails on [Internet Explorer](https://en.wikipedia.org/wiki/Internet_Explorer) and [Safari](https://en.wikipedia.org/wiki/Safari_%28web_browser%29); Internet Explorer fires the "load" event, but it doesn't download the file, and *Safari downloads* the file (with the wrong name and content-type) and doesn't fire the *"load"* event. A different approach might be to call to start the file creation, poll the server until it's ready, and then download the already-created file. But I'd rather avoid creating temporary files on the server. What should I do?
One [possible solution](http://gruffcode.com/2010/10/28/detecting-the-file-download-dialog-in-the-browser/) uses JavaScript on the client. The client algorithm: 1. Generate a random unique token. 2. Submit the download request, and include the token in a GET/POST field. 3. Show the "waiting" indicator. 4. Start a timer, and every second or so, look for a cookie named "fileDownloadToken" (or whatever you decide). 5. If the cookie exists, and its value matches the token, hide the "waiting" indicator. The server algorithm: 1. Look for the GET/POST field in the request. 2. If it has a non-empty value, drop a cookie (e.g. "fileDownloadToken"), and set its value to the token's value. --- Client source code (JavaScript): ``` function getCookie( name ) { var parts = document.cookie.split(name + "="); if (parts.length == 2) return parts.pop().split(";").shift(); } function expireCookie( cName ) { document.cookie = encodeURIComponent(cName) + "=deleted; expires=" + new Date( 0 ).toUTCString(); } function setCursor( docStyle, buttonStyle ) { document.getElementById( "doc" ).style.cursor = docStyle; document.getElementById( "button-id" ).style.cursor = buttonStyle; } function setFormToken() { var downloadToken = new Date().getTime(); document.getElementById( "downloadToken" ).value = downloadToken; return downloadToken; } var downloadTimer; var attempts = 30; // Prevents double-submits by waiting for a cookie from the server. function blockResubmit() { var downloadToken = setFormToken(); setCursor( "wait", "wait" ); downloadTimer = window.setInterval( function() { var token = getCookie( "downloadToken" ); if( (token == downloadToken) || (attempts == 0) ) { unblockSubmit(); } attempts--; }, 1000 ); } function unblockSubmit() { setCursor( "auto", "pointer" ); window.clearInterval( downloadTimer ); expireCookie( "downloadToken" ); attempts = 30; } ``` Example server code (PHP): ``` $TOKEN = "downloadToken"; // Sets a cookie so that when the download begins the browser can // unblock the submit button (thus helping to prevent multiple clicks). // The false parameter allows the cookie to be exposed to JavaScript. $this->setCookieToken( $TOKEN, $_GET[ $TOKEN ], false ); $result = $this->sendFile(); ``` Where: ``` public function setCookieToken( $cookieName, $cookieValue, $httpOnly = true, $secure = false ) { // See: http://stackoverflow.com/a/1459794/59087 // See: http://shiflett.org/blog/2006/mar/server-name-versus-http-host // See: http://stackoverflow.com/a/3290474/59087 setcookie( $cookieName, $cookieValue, 2147483647, // expires January 1, 2038 "/", // your path $_SERVER["HTTP_HOST"], // your domain $secure, // Use true over HTTPS $httpOnly // Set true for $AUTH_COOKIE_NAME ); } ```
A very simple (and lame) one line solution is to use the `window.onblur()` event to close the loading dialog. Of course, if it takes too long and the user decides to do something else (like reading emails) the loading dialog will close.
Detect when a browser receives a file download
[ "", "javascript", "http", "mime", "" ]
Java's Regex.Pattern supports the following character class: ``` [a-z&&[def]] ``` which matches "d, e, or f" and is called an intersection. Functionally this is no different from: ``` [def] ``` which is simpler to read and understand in a big RE. So my question is, what use are intersections, other than specifying complete support for CSG-like operations on character classes? (Please note, I understand the utility of subtractions like `[a-z&&[^bc]]` and `[a-z&&[^m-p]]`, I am asking specifically about intersections as presented above.)
Though I've never had the need to do so, I could imagine a use with pre-defined character classes that aren't proper subsets of each other (thus making the intersection produce something different than the original two character classes). E.g. matching only lower case Latin characters: ``` [\p{Ll}&&\p{InBasicLatin}] ```
I believe that particular sample is just a "proof of concept." Two intersected character classes only match a character that matches both character sets individually. The substractions you mentioned are the real practical applications of the operator. Simply put, there is no hidden meaning.
What is the point behind character class intersections in Java's Regex?
[ "", "java", "regex", "" ]
I am trying to output dates in the Italian format using `date()` as follows: ``` <?php setlocale(LC_ALL, 'it_IT'); echo date("D d M Y", $row['eventtime']); ?> ``` However, it is still coming out in the English format. What else could I do? Is there something wrong? The solution has to be script specific and not server-wide.
[`date()`](http://php.net/date) is not locale-aware. You should use [`strftime()`](http://php.net/strftime) and its format specifiers to output locale-aware dates (from the [`date()`](http://php.net/date) PHP manual): > To format dates in other languages, > you should use the [`setlocale()`](http://php.net/setlocale) and > [`strftime()`](http://php.net/strftime) functions instead of > [`date()`](http://php.net/date). Regarding [Anti Veeranna](https://stackoverflow.com/users/135594/anti-veeranna)'s comment: he is absolutely right, since you have to be very careful with setting locales as they are sometimes not limited to the current script scope. The best way would be: ``` $oldLocale = setlocale(LC_TIME, 'it_IT'); echo utf8_encode( strftime("%a %d %b %Y", $row['eventtime']) ); setlocale(LC_TIME, $oldLocale); ```
I found that `setlocale` isn't reliable, as it is set per process, not per thread (the manual mentions this). This means other running scripts can change the locale at any time. A solution is using [IntlDateFormatter](http://php.net/manual/en/class.intldateformatter.php) from the `intl` php extension. ``` $fmt = new \IntlDateFormatter('it_IT', NULL, NULL); $fmt->setPattern('d MMMM yyyy HH:mm'); // See: http://userguide.icu-project.org/formatparse/datetime for pattern syntax echo $fmt->format(new \DateTime()); ``` If it doesn't work you might need to: * Install `intl` php extension (ubuntu example): `sudo apt-get install php5-intl` * Install the locale you want to use: `sudo locale-gen it_IT`
Date function output in a local language
[ "", "php", "date", "" ]
This is the function i currently use(from a php book i bought): ``` function escape($data) { return mysql_real_escape_string(trim($data), $this->linkid); } ``` But I feel like it could be safer. for example, maybe use htmlspecialchars. It always makes me paranoid. I've read that mysql\_real\_escape\_string is bad and never to use it, but then i've also read it's the best way. Lots of confusion regarding data sanitizing when inserting them to the database. So how do you do it? and what are the pros and cons of the way you do it.
You're talking about two different types of escaping. `mysql_real_escape_string()` escapes data so it'll be safe to send to MySQL. `htmlspecialchars()` escapes data so it'll be safe to send to something that renders HTML. Both work fine for their respective purposes, but [parameterized queries via something like mysqli](http://devzone.zend.com/article/686) are quite a bit neater.
**Lets have a quick review of WHY escaping is needed in different contexts:** If you are in a quote delimited string, you need to be able to escape the quotes. If you are in xml, then you need to separate "content" from "markup" If you are in SQL, you need to separate "commands" from "data" If you are on the command line, you need to separate "commands" from "data" This is a really basic aspect of computing in general. Because the syntax that delimits data can occur IN THE DATA, there needs to be a way to differentiate the DATA from the SYNTAX, hence, escaping. In web programming, the common escaping cases are: 1. Outputting text into HTML 2. Outputting data into HTML attributes 3. Outputting HTML into HTML 4. Inserting data into Javascript 5. Inserting data into SQL 6. Inserting data into a shell command Each one has a different security implications if handled incorrectly. THIS IS REALLY IMPORTANT! Let's review this in the context of PHP: 1. Text into HTML: htmlspecialchars(...) 2. Data into HTML attributes htmlspecialchars(..., ENT\_QUOTES) 3. HTML into HTML Use a library such as [HTMLPurifier](http://htmlpurifier.org/) to ENSURE that only valid tags are present. 4. Data into Javascript I prefer `json_encode`. If you are placing it in an attribute, you still need to use #2, such as 5. Inserting data into SQL Each driver has an escape() function of some sort. It is best. If you are running in a normal **latin1** character set, addslashes(...) is suitable. *mysql\_real\_escape\_string() is better.* Don't forget the quotes AROUND the addslashes() call: "INSERT INTO table1 SET field1 = '" . addslashes($data) . "'" 6. Data on the command line escapeshellarg() and escapeshellcmd() -- read the manual -- Take these to heart, and you will eliminate 95%\* of common web security risks! (\* a guess)
How do you sanitize your data?
[ "", "php", "" ]
How do I determine and force users to view my website using HTTPS only? I know it can be done through IIS, but want to know how its done programmatically.
You can write an `HttpModule` like this: ``` /// <summary> /// Used to correct non-secure requests to secure ones. /// If the website backend requires of SSL use, the whole requests /// should be secure. /// </summary> public class SecurityModule : IHttpModule { public void Dispose() { } public void Init(HttpApplication application) { application.BeginRequest += new EventHandler(application_BeginRequest); } protected void application_BeginRequest(object sender, EventArgs e) { HttpApplication application = ((HttpApplication)(sender)); HttpRequest request = application.Request; HttpResponse response = application.Response; // if the secure connection is required for backend and the current // request doesn't use SSL, redirecting the request to be secure if ({use SSL} && !request.IsSecureConnection) { string absoluteUri = request.Url.AbsoluteUri; response.Redirect(absoluteUri.Replace("http://", "https://"), true); } } } ``` Where `{use SSL}` is a some condition whether to use SSL or not. **EDIT**: and, of course, don't forget to add a module definition to a `web.config`: ``` <system.web> <httpModules> <!--Used to redirect all the unsecure connections to the secure ones if necessary--> <add name="Security" type="{YourNamespace}.Handlers.SecurityModule, {YourAssembly}" /> ... </httpModules> </system.web> ```
A bit hard coded but straighforward! ``` if (!HttpContext.Current.Request.IsSecureConnection) { Response.Redirect("https://www.foo.com/foo/"); } ```
C# How to determine if HTTPS
[ "", "c#", "security", "https", "" ]
I want to remove all special characters from a string. Allowed characters are A-Z (uppercase or lowercase), numbers (0-9), underscore (\_), or the dot sign (.). I have the following, it works but I suspect (I know!) it's not very efficient: ``` public static string RemoveSpecialCharacters(string str) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.Length; i++) { if ((str[i] >= '0' && str[i] <= '9') || (str[i] >= 'A' && str[i] <= 'z' || (str[i] == '.' || str[i] == '_'))) { sb.Append(str[i]); } } return sb.ToString(); } ``` What is the most efficient way to do this? What would a regular expression look like, and how does it compare with normal string manipulation? The strings that will be cleaned will be rather short, usually between 10 and 30 characters in length.
Why do you think that your method is not efficient? It's actually one of the most efficient ways that you can do it. You should of course read the character into a local variable or use an enumerator to reduce the number of array accesses: ``` public static string RemoveSpecialCharacters(this string str) { StringBuilder sb = new StringBuilder(); foreach (char c in str) { if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.' || c == '_') { sb.Append(c); } } return sb.ToString(); } ``` One thing that makes a method like this efficient is that it scales well. The execution time will be relative to the length of the string. There is no nasty surprises if you would use it on a large string. Edit: I made a quick performance test, running each function a million times with a 24 character string. These are the results: Original function: 54.5 ms. My suggested change: 47.1 ms. Mine with setting StringBuilder capacity: 43.3 ms. Regular expression: 294.4 ms. Edit 2: I added the distinction between A-Z and a-z in the code above. (I reran the performance test, and there is no noticable difference.) Edit 3: I tested the lookup+char[] solution, and it runs in about 13 ms. The price to pay is, of course, the initialization of the huge lookup table and keeping it in memory. Well, it's not that much data, but it's much for such a trivial function... ``` private static bool[] _lookup; static Program() { _lookup = new bool[65536]; for (char c = '0'; c <= '9'; c++) _lookup[c] = true; for (char c = 'A'; c <= 'Z'; c++) _lookup[c] = true; for (char c = 'a'; c <= 'z'; c++) _lookup[c] = true; _lookup['.'] = true; _lookup['_'] = true; } public static string RemoveSpecialCharacters(string str) { char[] buffer = new char[str.Length]; int index = 0; foreach (char c in str) { if (_lookup[c]) { buffer[index] = c; index++; } } return new string(buffer, 0, index); } ```
Well, unless you really need to squeeze the performance out of your function, just go with what is easiest to maintain and understand. A regular expression would look like this: For additional performance, you can either pre-compile it or just tell it to compile on first call (subsequent calls will be faster.) ``` public static string RemoveSpecialCharacters(string str) { return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled); } ```
Most efficient way to remove special characters from string
[ "", "c#", "string", "special-characters", "" ]
See [this question](https://stackoverflow.com/questions/934794/is-there-break-on-exception-in-intellij) on how to break on any exceptions. I'm getting a million exceptions on startup. I've tried ignoring ClassNotFoundException, but it's no good, the IDE still seems to break on these (and other) exceptions. So .. what's a decent configuration for this to catch only real exceptions caught from user code? (Ignore also any exception in jUnit, if applicable)
As mentioned by the other posters, **Class Filters** are the way to do this. Specifically, you could add the package names for what you consider "your code" as a class filter. The syntax is a little opaque, but using a simple wildcard filter like: > com.whatever.package.\* sounds like it it will work for you. IntelliJ will break on any exception in any class in any package under here. You can of course define multiple wildcard filters if your code is in more than one place.
I was just messing with this earlier. Two ways to go: 1) Configure it to explicitly catch your exception, not "any exception" - if it's something like RuntimeException, this may not be filter-y enough. 2) Use the class results filter - this for whatever reason did NOT work for me. Ever.
Breaking on your own exceptions in IntelliJ
[ "", "java", "debugging", "exception", "intellij-idea", "breakpoints", "" ]
I want to execute [this script (view source)](http://code.google.com/apis/ajaxlanguage/documentation/translate.html) that uses Google Translate AJAX API from python, and be able to pass arguments and get the answer back. I don't care about the HTML. I understand I need to embed a Javascript interpreter of some sort. Does this mean I need to have a browser instance and manipulate it? What is the cleanest way to access this API from python?
You can use [google-api-translate-python](http://googletranslate.sourceforge.net/) to talk to google api. **EDIT:** It wasn't clear where the sources are, found them [here](https://googletranslate.svn.sourceforge.net/svnroot/googletranslate/src/trunk/).
You can use the RESTful API instead. It's designed for environments that are not Javascript. <http://code.google.com/apis/ajaxlanguage/documentation/reference.html#_intro_fonje> That should be easy to use from Python.
Call Google Translate from Python
[ "", "python", "ajax", "" ]
I think I want to use pythons built in calendar module to create an HTML calendar with data. I say I think because I'll probably think of a better way, but right now it's a little personal. I don't know if this was intended to be used this way but it seems like it is a little pointless if you can't at least making the days into a `<a hrefs>`. This sets up a calendar for this month with Sunday as the first day. ``` import calendar myCal = calendar.HTMLCalendar(calendar.SUNDAY) print myCal.formatmonth(2009, 7) ``` it prints ``` <table border="0" cellpadding="0" cellspacing="0" class="month">\n<tr> <th colspan="7" class="month">July 2009</th></tr>\n<tr><th class="sun">Sun</th> <th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th> <th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th></tr>\n <tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td> <td class="noday">&nbsp;</td><td class="wed">1</td><td class="thu">2</td><td class="fri">3</td> <td class="sat">4</td></tr>\n<tr><td class="sun">5</td><td class="mon">6</td><td class="tue">7</td> <td class="wed">8</td><td class="thu">9</td><td class="fri">10</td> <td class="sat">11</td></tr>\n<tr><td class="sun">12</td><td class="mon">13</td> <td class="tue">14</td><td class="wed">15</td><td class="thu">16</td><td class="fri">17</td> <td class="sat">18</td></tr>\n<tr><td class="sun">19</td><td class="mon">20</td> <td class="tue">21</td><td class="wed">22</td><td class="thu">23</td><td class="fri">24</td> <td class="sat">25</td></tr>\n<tr><td class="sun">26</td><td class="mon">27</td> <td class="tue">28</td><td class="wed">29</td><td class="thu">30</td><td class="fri">31</td> <td class="noday">&nbsp;</td></tr>\n</table>\n ``` I would like to insert some data into the HTMLCalendar object before it renders the html string. I just can't figure out how. For example ``` <td class="tue">28<br />[my data]</td> ```
You may load html, which seems to be valid XMl into a XML tree, modify it and again output it. e.g. this adds `<br/> cool` to each Tue td node. ``` import calendar import xml.etree.ElementTree as etree myCal = calendar.HTMLCalendar(calendar.SUNDAY) htmlStr = myCal.formatmonth(2009, 7) htmlStr = htmlStr.replace("&nbsp;"," ") root = etree.fromstring(htmlStr) for elem in root.findall("*//td"): if elem.get("class") != "tue": continue elem.text += "!" br = etree.SubElement(elem, "br") br.tail = "cool!" print etree.tostring(root) ``` I do not yet know why you need to generate a HTML calendar, but there are better ways of doing that depending on needs and framework you are using.
Create a new class inheriting from HTMLCalendar. Override the formatday method. Whoever makes comments like "this library is useless" obviously doesn't understand Python. ``` class EmployeeScheduleCalendar(HTMLCalendar): def formatday(self, day, weekday): """ Return a day as a table cell. """ if day == 0: return '<td class="noday">&nbsp;</td>' # day outside month else: return '<td class="%s"><a href="%s">%d</a></td>' % (self.cssclasses[weekday], weekday, day) ```
python calendar.HTMLCalendar
[ "", "python", "html", "calendar", "" ]
How can I check to see if a file is already open by another user in javascript? As it is right now, the program I'm trying to fix will open/edit a file then fail on trying to save if the file is already in use. Also, is there an easy way to add a lock on the file so another process knows it's in use? Edit: the program is a .hta using Active X Objects. i guess i should have been more specific, here's some code about how it is opening/editing/saving the files. ``` var FileSystem = new ActiveXObject( "Scripting.FileSystemObject" ); var xmlDoc = new ActiveXObject( "Msxml2.DOMDocument.3.0" ); var fFile = FileSystem.GetFile( strPath ); xmlDoc.load( fFile.Path ); // some method's to edit documentElement in xmlDoc... xmlDoc.save( fFile.Path ); ```
I'm not too familiar with ActiveX, but maybe when you open a file you could create a temporary file like file.ext.lock (and delete it when you save the file), so when another user tries to open the same file and sees the .lock file exists, you know it's being used.
Are you sure it's just JavaScript and not a combo of maybe an ActiveX or flash component? Is the file on the client or server? If server, this question makes more sense to me (ie. using some AJAX solution).
Detecting if a file is already open in javascript
[ "", "javascript", "activex", "" ]
I am trying to setup a development environment for Linux C++ application. Because I'm limited to my laptop (vista) which provides essential office applications, I want to program and access email, word at the same time. I'd prefer a local Windows IDE. SSH to a company linux server and using VI doesn't seem productive to me. Even using some IDE installed on the linux server doesn't seem good to me, because I can't do the work at home. So does Eclipse CDT + MinGW work for me, or is there any other choice? Thanks. ZXH
Why not install a Linux virtual machine on your laptop, in VMware or similar? That way you can test while you're developing too.
You can also try <http://cygwin.com/>
C++ development for Linux on Windows
[ "", "c++", "ide", "" ]
I'm trying to do some very basic time math - basically, given inputs of time and distance, calculate the speed. I chose to use strtotime() to convert the time inputs into seconds - but I'm getting some bizarre results. For example, given this sample program: ``` <?php $t1 = strtotime("3:15:00",0); $t2 = strtotime("1:00:00",0); $t3 = strtotime("2:00:00",0); $t4 = strtotime("9:00:00",0); echo $t1 . "\n"; echo $t2 . "\n"; echo $t3 . "\n"; echo $t4 . "\n"; ?> ``` Why do I get these results? ``` $ php test.php -56700 -64800 -61200 -36000 ``` **Update:** Since no one said it explicitly, let me explain the bug in the above function. I had assumed that passing a time of zero to strtotime() would cause it to generate time stamps derived from midnight, 12/31/1969, UTC - which sounds odd, but would work for my purposes. What I hadn't counted on was that strtotime() takes time zones into account when converting strings, and my server is apparently 5 hours behind UTC. On top of that, because of the time zone shift, PHP then interprets the times as relative to **the day before the epoch** which means it is interpreting my times as occurring relative to December **30th**, 1969 instead of the 31st, resulting in negative numbers... It appears that Eugene is correct - if I want to calculate just the elapsed time, I can't use the built in time functions.
If you want to do something like that, I think you want to just do some math on the time strings themselves and convert them to a number of seconds, like this: ``` <?php function hmstotime($hms) { list($hours, $minutes, $seconds) = explode(":",$hms); return $hours * 60 * 60 + $minutes * 60 + $seconds; } ?> ```
Apparently with just bare times PHP is assigning the date December 31, 1969. When I ran this: ``` echo date('F j, Y H:i:s', $t1) . "\n"; echo date('F j, Y H:i:s', $t2) . "\n"; echo date('F j, Y H:i:s', $t3) . "\n"; echo date('F j, Y H:i:s', $t4) . "\n"; ``` I got this: ``` December 31, 1969 03:15:00 December 31, 1969 01:00:00 December 31, 1969 02:00:00 December 31, 1969 09:00:00 ``` Remember that `strtotime` returns a UNIX timestamp, which is defined as the number of seconds since January 1, 1970. By definition a UNIX timestamp refers to a specific month/day/year, so despite the name `strtotime` is not really intended for bare times without dates.
Strange behavior of PHP time math: Why is strtotime() returning negative numbers?
[ "", "php", "" ]
How to pass a class and a method name as *strings* and invoke that class' method? Like ``` void caller(string myclass, string mymethod){ // call myclass.mymethod(); } ``` Thanks
You will want to use [reflection](http://msdn.microsoft.com/en-us/library/ms173183(VS.80).aspx). Here is a simple example: ``` using System; using System.Reflection; class Program { static void Main() { caller("Foo", "Bar"); } static void caller(String myclass, String mymethod) { // Get a type from the string Type type = Type.GetType(myclass); // Create an instance of that type Object obj = Activator.CreateInstance(type); // Retrieve the method you are looking for MethodInfo methodInfo = type.GetMethod(mymethod); // Invoke the method on the instance we created above methodInfo.Invoke(obj, null); } } class Foo { public void Bar() { Console.WriteLine("Bar"); } } ``` Now this is a *very* simple example, devoid of error checking and also ignores bigger problems like what to do if the type lives in another assembly but I think this should set you on the right track.
Something like this: ``` public object InvokeByName(string typeName, string methodName) { Type callType = Type.GetType(typeName); return callType.InvokeMember(methodName, BindingFlags.InvokeMethod | BindingFlags.Public, null, null, null); } ``` You should modify the binding flags according to the method you wish to call, as well as check the Type.InvokeMember method in msdn to be certain of what you really need.
How to dynamically call a class' method in .NET?
[ "", "c#", "reflection", "" ]
I'm dealing with an annoying database where one field contains what really should be stored two separate fields. So the column is stored something like "The first string~@~The second string", where "~@~" is the delimiter. (Again, I didn't design this, I'm just trying to fix it.) I want a query to move this into two columns, that would look something like this: ``` UPDATE UserAttributes SET str1 = SUBSTRING(Data, 1, STRPOS(Data, '~@~')), str2 = SUBSTRING(Data, STRPOS(Data, '~@~')+3, LEN(Data)-(STRPOS(Data, '~@~')+3)) ``` But I can't find that any equivalent to strpos exists.
User charindex: ``` Select CHARINDEX ('S','MICROSOFT SQL SERVER 2000') Result: 6 ``` [Link](https://learn.microsoft.com/en-us/sql/t-sql/functions/charindex-transact-sql)
The PatIndex function should give you the location of the pattern as a part of a string. ``` PATINDEX ( '%pattern%' , expression ) ``` <http://msdn.microsoft.com/en-us/library/ms188395.aspx>
SQL Server: any equivalent of strpos()?
[ "", "sql", "sql-server", "syntax", "strpos", "" ]
I'm looking for a good way to get autocomplete and click-for-reference (whatever that's called) for libraries in codeigniter working in Zend Studio for Eclipse. for instance, if i do $this->load->library('dx\_auth'); $this->dx\_auth->get\_user\_id(); zend studio doesn't know what it is.. There is this sortof hacky way to do it (see below, [source](http://codeigniter.com/forums/viewthread/115310/#583621)), but i feel like there should be a better way of doing it.. Anyone have any ideas? ``` // All of these are added so I get real auto complete // I don't have to worry about it causing any problems with deployment // as this file never gets called as I'm in PHP5 mode // Core CI libraries $config = new CI_Config(); $db = new CI_DB_active_record(); $email = new CI_Email(); $form_validation = new CI_Form_validation(); $input = new CI_Input(); $load = new CI_Loader(); $router = new CI_Router(); $session = new CI_Session(); $table = new CI_Table(); $unit = new CI_Unit_test(); $uri = new CI_URI(); ```
Add CI's library path as an include path to your project. 1. In the **PHP Explorer**, open your project and right-click on **Include Paths** 2. Select **Configure** from the context menu 3. Then in the include path dialog, select the **Library** tab 4. Click **Add External Folder...** 5. Browse to a local copy of CI and choose it's library directory (wherever it keeps those class files) 6. Click **Done** Voila, there you go! I should note that you can also define include paths at the time of project creation.
As Peter's answer instructs, adding an include path is definitely the best way to go. However, this relies on the docblocks in the CI source code to be complete, accurate, and not ambiguous. For example, if a methods `@return` is declared as `Some_Class|false`, the autocompletion won't know what to do with it. To add to Peter's answer, you can also force PDT/Eclipse/ZSfE to treat any variable as an instance of a particular class like so: ``` /* @var $varName Some_Class_Name */ ```
how to get zend studio autocomplete with codeigniter
[ "", "php", "codeigniter", "autocomplete", "zend-studio", "" ]
In C#, is it possible to get all values of a particular column from all rows of a DataSet with a simple instruction (no LINQ, no For cicle)?
Only by iterating over the rows, as [Utaal noted in this answer](https://stackoverflow.com/questions/1080071/get-all-values-of-a-column-from-a-dataset/1080084#1080084). You might expect that the `DataTable.DefaultView.RowFilter` would support grouping, but it does not (it mainly offers the equivalent functionality of a `Where` clause, with some basic aggregations - though not simple grouping).
Why No LINQ? For people coming here without the same restriction, here are three ways to do this, the bottom two both using LINQ. **C#** ``` List<object> colValues = new List<object>(); //for loop foreach (DataRow row in dt.Rows) { colValues.Add(row["ColumnName"]); } //LINQ Query Syntax colValues = (from DataRow row in dt.Rows select row["ColumnName"]).ToList(); //LINQ Method Syntax colValues = dt.AsEnumerable().Select(r => r["ColumnName"]).ToList(); ``` **VB** ``` Dim colValues As New List(Of Object) 'for loop For Each row As DataRow In dt.Rows colValues.Add(row("ColumnName")) Next 'LINQ Query Syntax colValues = (From row As DataRow In dt.Rows Select row("ColumnName")).ToList 'LINQ Method Syntax colValues = dt.Rows.AsEnumerable.Select(Function(r) r("ColumnName")).ToList ``` To use the `AsEnumerable` method on a `DataTable`, you'll have to have a Reference to System.Data.DataSetExtensions which add the [LINQ extension methods](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aspx). Otherwise, you can just cast the `Rows` property of the `DataTable` as type `DataRow` (you don't have to do this with the Query syntax because it automatically casts for you).
Get all values of a column from a DataSet
[ "", "c#", "dataset", "" ]
I know this isn't "best practice", but can I include all of the dependencies in one big jar?
There's a utility called [One-Jar](http://one-jar.sourceforge.net/) which does what you want, although I'd advise against it. The performance is usually awful.
My feeling is that calling One-Jar's performance awful and poor is unjust. For moderately sized application one can expect startup will take a couple of seconds longer (which does not affect JVM splash screen though). Memory overhead of tens of megabytes is negligible for most environments, except perhaps embedded systems. Also, One-Jar is capable of automatically extracting some files to the file system, which saves the need to develop an installer in my case. Below is an attempt to quantify the performance impact introduced by One-Jar to my application. It is Swing-based GUI application, consists of 352 classes obfuscated with ProGuard 4.5b2. One-Jar 0.96 is used to bundle resulting classes with 12MB worth of libraries (ODFDOM, Saxon HE, Xerces, Jaxen, VLDocking, Apache Commons, etc). I have compared performance of the obfuscated jar with the same jar processed by One-Jar. * From JVM start to the start of of main() method: 0.5s without One-Jar and 1.7s with One-Jar. From JVM start to the appearance of application window on the screen: 2.3s without One-Jar and 3.4s with One-Jar. So One-Jar adds 1.1s to startup time. * One-Jar will not increase the delay between JVM start and splash image appearing on the screen (if implemented via jar manifest), so the startup time increase is not too annoying for interactive applications. * We are talking about a class loader, so there should be no impact on code execution speed, unless you are extensively using dynamic class loading. * Looking at JVM statistics (via jconsole) shows that One-Jar'red version takes more heap memory. For my application the overhead is in the order of tens of MBs. I saw figures like 16MB vs 40MB, 306MB vs 346MB, 131MB vs 138MB, depending on now much user data the application is handling and now long time ago garbage collector has been executed. The above timing was obtained by taking a timestamp just before starting JVM from Linux shell, in beginning of main() method, and in windowOpened() event handler of my application window. The measurements were taken on a not particularly fast D820 laptop, with dual core 1GHz CPU and 2G or RAM running Ubuntu 8.04. Hope it helps.
Is it possible to package all the jar dependencies in one big jar?
[ "", "java", "jar", "dependencies", "" ]
I'm using the javax.xml.transform.Transformer class to perform some XSLT translations, like so: ``` TransformerFactory factory = TransformerFactory.newInstance(); StreamSource source = new StreamSource(TRANSFORMER_PATH); Transformer transformer = factory.newTransformer(source); StringWriter extractionWriter = new StringWriter(); String xml = FileUtils.readFileToString(new File(sampleXmlPath)); transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(extractionWriter)); System.err.println(extractionWriter.toString()); ``` However, no matter what I do I can't seem to avoid having the transformer convert any tabs that were in the source document in to their character entity equivalent (`&#9;`). I have tried both: ``` transformer.setParameter("encoding", "UTF-8"); ``` and: ``` transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); ``` but neither of those help. Does anyone have any suggestions? Because: ``` &#9;&#9;&#9;&#9;&#9;<MyElement> ``` looks really stupid (even if it does work).
So the answer to this one turned out to be pretty lame: update Xalan. I don't know what was wrong with my old version, but when I switched to the latest version at: <http://xml.apache.org/xalan-j/downloads.html> suddenly the entity-escaping of tabs just went away. Thanks everyone for all your help though.
You could try using a SAXTransformerFactory in combination with a XMLReader. Something like: ``` SAXTransformerFactory transformFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); StreamSource source = new StreamSource(TRANSFORMER_PATH); StringWriter extractionWriter = new StringWriter(); TransformerHandler transformerHandler = null; try { transformerHandler = transformFactory.newTransformerHandler(source); transformerHandler.setResult(new StreamResult(extractionWriter)); } catch (TransformerConfigurationException e) { throw new SAXException("Unable to create transformerHandler due to transformer configuration exception."); } XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); reader.setContentHandler(transformerHandler); reader.parse(new InputSource(new FileReader(xml))); System.err.println(extractionWriter.toString()); ``` You should be able to set the SAX parser to not include ignorable whitespace, if it doesn't already do it by default. I haven't actually tested this, but I do something similar in one of my projects.
How Do You Prevent A javax Transformer From Escaping Whitespace?
[ "", "java", "entity", "escaping", "transformer-model", "xslt", "" ]
I get this error message in Eclipse: ``` Access restriction: The type DirectoryWalker is not accessible due to restriction on required library /Library/Java/Extensions/commons-io-1.4.jar ``` what does this mean? There's [this other SO question](https://stackoverflow.com/questions/860187/access-restriction-on-class-due-to-restriction-on-required-library-rt-jar) on the same topic but it doesn't seem to apply in this case. I'm not creating a new java class, I'm trying to use one.
At a guess another library you are using also requires Apache Commons I/O, but a different version. Having a piece of code (transitively) have access to two versions of the same packages is a little tricky. You can probably arrange it so your code and the other library use the same version. It's all much easier with CLASSPATH! :)
go to java build path and under Library tab, remove JRE System Library. Then again Add Library --> JRE System Library Worked for me
Access restriction on class due to restriction on required library
[ "", "java", "eclipse", "" ]
I'm writing a program in C++ and it takes some command line arguments. The only way I know to pass command line arguments in VSC++ is to open up the properties and navigate to the command line argument field and enter them in, then run it. That's not exactly streamlined if I want to pass in different arguments each time I run it. The other option is to just open up a command prompt in the directory where the executable is placed and to run it from the command line there, but then if I want to use the debugger I have to attach it and that's a pain too. Is there a better way to do this?
If its just for quick testing or whatever, you could just create local variables in your main method instead of passing arguments in. Makes it a lot quicker/easier to change them.
I don't think there's anything built-in that can do that, but you could write a macro that asks for input, sets the command line arguments and starts the debugger. I don't have code to sets the command line arguments, but I could probably dig up some code that starts the debugger. Regards, Sebastiaan
Is there a better way to pass command line arguments to my programs in VC++?
[ "", "c++", "visual-studio", "visual-c++", "command-line", "" ]
In some of my tests i need to check the order of Lists and do it something like this ``` DateTime lastDate = new DateTime(2009, 10, 1); foreach (DueAssigmentViewModel assignment in _dueAssigments) { if (assignment.DueDate < lastDate) { Assert.Fail("Not Correctly Ordered"); } lastDate = assignment.DueDate; } ``` What i would like to do i turn this into an extension method on IEnumerable to make it reusable. My inital idea was this ``` public static bool IsOrderedBy<T, TestType>(this IEnumerable<T> value, TestType initalValue) { TestType lastValue = initalValue; foreach (T enumerable in value) { if(enumerable < lastValue) { return false; } lastValue = value; } return true; } ``` The ovious problem here is you cant compaire to generic values. Can anyone suggest a way round this. Cheers Colin
I think it would make more sense to use a method signature similar to the `OrderBy` method... ``` public static bool IsOrderedBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { bool isFirstPass = true; TSource previous = default(TSource); foreach (TSource item in source) { if (!isFirstPass) { TKey key = keySelector(item); TKey previousKey = keySelector(previous); if (Comparer<TKey>.Default.Compare(previousKey, key) > 0) return false; } isFirstPass = false; previous = item; } return true; } ``` You can then use it like that : ``` List<Foo> list = new List<Foo>(); ... if (list.IsOrderedBy(f => f.Name)) Console.WriteLine("The list is sorted by name"); else Console.WriteLine("The list is not sorted by name"); ```
You could add a restraint: ``` where T:IComparable ``` Then instead of using the `<` operator, you could use the CompareTo() method of the IComparable interface.
IsOrderedBy Extension Method
[ "", "c#", "generics", "" ]
I have a small app that downloads some files from a remote (HTTP) server to the users local hard drive, some of the files are large, but I don't know just how large at run time. Is there any method that will allow me download a file with some type of progress meter? This is a WinForms app, right now I'm using WebClient.DownloadFile() to download the file. Edit: I've looked into the DownloadProgressChanged and OnDownloadProgressChanged events and they seem to work fine, but they will not work for my solution. I am downloading several files and if I use WebClient.DownloadFileAsync then the event is called several times/second because each file calls it. Here is the basic structure of the app: * Download a list of files typically about 114 * Run a loop over the list of files and download each one to its desination I don't mind downloading each file seperatly but without downloading them with DownloadFileAsync() I cannot use the event handlers.
Use [WebClient.OnDownloadProgressChanged](http://msdn.microsoft.com/en-us/library/system.net.webclient.ondownloadprogresschanged.aspx). Keep in mind, it's only possible to calculate progress if the server reports the size up front. EDIT: Looking at your update, what you can try is making a [queue](http://msdn.microsoft.com/en-us/library/7977ey2c.aspx) of URLs. Then, when a file finishes downloading ([DownloadDataCompleted](http://msdn.microsoft.com/en-us/library/system.net.webclient.downloaddatacompleted.aspx) event), you will launch the async download of the next URL in the queue. I haven't tested this.
Handle the WebClient [DownloadProgressChanged](http://msdn.microsoft.com/en-us/library/system.net.webclient.downloadprogresschanged.aspx) event.
Download file from web to local file with progress meter in C#
[ "", "c#", ".net-3.0", "" ]
I want to show the image that mobile phone's camera its taking on a control in a WinForm. The idea is that my application works like camera's program. I want to show the image like if the user is going to take a photo. How can I do that? Can I do that? If you need more details ask me. Thank you!
Not very sure what you need, but you may try using Microsoft.WindowsMobile.Forms.CameraCaptureDialog: ``` string originalFileName; using (CameraCaptureDialog dlg = new CameraCaptureDialog()) { dlg.Mode = CameraCaptureMode.Still; dlg.StillQuality = CameraCaptureStillQuality.Low; //dlg.Resolution = new Size(800, 600); dlg.Title = "Take the picture"; DialogResult res; try { res = dlg.ShowDialog(); } catch (Exception ex) { Trace.WriteLine(ex); return null; } if (res != DialogResult.OK) return null; this.Refresh(); originalFileName = pictureFileName = dlg.FileName; } ``` **Later Edit:** Some of you might find useful this link, too: <http://community.intermec.com/t5/General-Development-Developer/CN50-MS-Camera-Capture-Dialog-generates-error/m-p/12881#M4083>
What you want is a preview, not the capture, which is far more difficult. The best (and maybe only) solution is to insert a DShow Filter into the filtergraph to pipe the preview window to where you want. COM is a bear in the Compact Framework, and DShow is tough no matter what platform you're on. There are some resources online, like the [DShow.NET library at sourceforge](http://sourceforge.net/projects/directshownet), and [Alex Mogurenko's blog](http://alexmogurenko.com/blog/programming/windows-mobile-how-to-play-audiovideo-c-or-directshownet-cf-part-i/), but nothing specific to creating a capture. There is a native capture sample in the WinMo SDK that would be a useful guide to getting you there.
Windows Mobile: using phone's camera with C#
[ "", "c#", "windows-mobile", "compact-framework", "camera", "" ]
I need a regular expression to validate a timestamp of the format, **using Javascript**: > YYYY/MM/DD HH:MI:SS I tried cooking up a few, but seems my regex skills fail to cover something or other. Please give me a reference or way to do it. *P.S. : I mention regex, only as a suggestion. Im using Javascript and welcome any alternative.*
I would recommend to use [Datejs](http://www.datejs.com/) for this. Parsing the date yourself is not necessary and a Regex is not enough to validate a timestamp. With datejs you could parse the string in a date and you'll get null if its invalid: ``` Date.parse("2009/06/29 13:30:10", "yyyy/MM/dd HH:mm:ss"); ```
If you just want to validate the syntax, here is the POSIX regex: ``` [0-9]{1,4}/[0-9]{1,2}/[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2} ``` But if you want to check the semantics, I would process the string using your language of choice, there are too many cases you cannot cover with regular expressions (like leap years/seconds, daylight savings, etc)
Regular Expression to validate a timestamp
[ "", "javascript", "regex", "validation", "timestamp", "" ]
the best way to explain is with example so: this is the model ``` public class Person { public int age; public string name; } ``` this is the view model ``` public class PersonVM { } ``` my question is: should the vm expose the person to the data template or encapsulate the model properties with his own properties?
The view model should declare its own properties and hide the specifics of the model from the view. This gives you the most flexibility, and helps keep view model-type issues from leaking into the model classes. Usually your view model classes encapsulate the model by delegation. For example, ``` class PersonModel { public string Name { get; set; } } class PersonViewModel { private PersonModel Person { get; set;} public string Name { get { return this.Person.Name; } } public bool IsSelected { get; set; } // example of state exposed by view model public PersonViewModel(PersonModel person) { this.Person = person; } } ``` Remember: the model shouldn't know anything about the view model that is consuming it, and the view model shouldn't know anything about the view that is consuming it. The view should know nothing about the models lurking in the background. Thus, encapsulate the model behind properties in the view model.
There is not a general agreement about that question. For example it was one of the open questions about MVVM formulated by Ward Bell [here](http://neverindoubtnet.blogspot.com/2009/05/birth-and-death-of-m-v-vm-triads.html): > Is the VM allowed to offer the V an > unwrapped M-object (e.g., the raw > Employee) ? Or must the M-object’s > properties (if it is even permitted to > have properties!) be exposed > exclusively through the surface of a > VM wrapper? The principal advantages of not directly exposing the Model in the VM are: * you can use it as a "converter on steroids", formating the model values in a convenient way for the view * you can inject other funcionality related to the user interface, like [data validation messages](http://karlshifflett.wordpress.com/mvvm/input-validation-ui-exceptions-model-validation-errors/), [undo redo](http://blog.notifychanged.com/2009/01/30/using-the-viewmodel-pattern-to-provide-undo-redo-in-wpf/),.. The cons are: * you will have to duplicate a lot of code to expose all the models properties in the viewmodel. * if you bind the view control to the viewmodels property, you will send the propertyChanged events from the viewmodel. But what happens if the models property change from other source different from the viewmodel setter? Then it has to notify the viewmodel so you end with 2 OnPropertyChanged, one in the model and one in the viewmodel... quite complex! So for me the correct answer is: it depends on your requirements.
MVVM: Should a VM object expose an M object directly, or only through getters delegating to M's getters?
[ "", "c#", "design-patterns", "mvvm", "getter", "access-modifiers", "" ]