Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have created an application that does the following: 1. Make some calculations, **write** calculated data to a file - repeat for 500,000 times (over all, write 500,000 files one after the other) - repeat 2 more times (over all, 1.5 mil files were written). 2. **Read** data from a file, make some intense calculations with the data from the file - repeat for 1,500,000 iterations (iterate over all the files written in step 1.) 3. Repeat step 2 for 200 iterations. Each file is ~212k, so over all i have ~300Gb of data. It looks like the entire process takes ~40 days on a Core 2 Duo CPU with 2.8 Ghz. My problem is (as you can probably guess) is the time it takes to complete the entire process. All the calculations are serial (each calculation is dependent on the one before), so i can't parallel this process to different CPUs or PCs. I'm trying to think how to make the process more efficient and I'm pretty sure the most of the overhead goes to file system access (duh...). Every time i access a file i open a handle to it and then close it once i finish reading the data. One of my ideas to improve the run time was to use one big file of 300Gb (or several big files of 50Gb each), and then I would only use one open file handle and simply seek to each relevant data and read it, but I'm not what is the overhead of opening and closing file handles. can someone shed some light on this? Another idea i had was to try and group the files to bigger ~100Mb files and then i would read 100Mb each time instead of many 212k reads, but this is much more complicated to implement than the idea above. Anyway, if anyone can give me some advice on this or have any idea how to improve the run time i would appreciate it! Thanks. *Profiler update:* I ran a profiler on the process, it looks like the calculations take 62% of runtime and the file read takes 34%. Meaning that even if i miraculously cut file i/o costs by a factor of 34, I'm still left with 24 days, which is quite an improvement, but still a long time :)
Opening a file handle isn't probable to be the bottleneck; actual disk IO is. If you can parallelize disk access (by e.g. using multiple disks, faster disks, a RAM disk, ...) you may benefit way more. Also, be sure to have IO not block the application: read from disk, and process while waiting for IO. E.g. with a reader and a processor thread. Another thing: if the next step depends on the current calculation, why go through the effort of saving it to disk? Maybe with another view on the process' dependencies you can rework the data flow and get rid of a lot of IO. Oh yes, and *measure it* :)
> Each file is ~212k, so over all i have > ~300Gb of data. It looks like the > entire process takes ~40 days ...a ll the > calculations are serial (each > calculation is dependent on the one > before), so i can't parallel this > process to different CPUs or PCs. ... pretty > sure the most of the overhead goes to > file system access ... Every > time i access a file i open a handle > to it and then close it once i finish > reading the data. Writing data 300GB of data serially might take 40 minutes, only a tiny fraction of 40 days. Disk write performance shouldn't be an issue here. Your idea of opening the file only once is spot-on. Probably closing the file after every operation is causing your processing to block until the disk has completely written out all the data, negating the benefits of disk caching. My bet is the fastest implementation of this application will use a memory-mapped file, all modern operating systems have this capability. It can end up being the simplest code, too. You'll need a 64-bit processor and operating system, you should *not* need 300GB of RAM. Map the whole file into address space at one time and just read and write your data with pointers.
Many small files or one big file? (Or, Overhead of opening and closing file handles) (C++)
[ "", "c++", "optimization", "file-io", "" ]
I’m currently monitoring a Java application with jconsole. The memory tab lets you choose between: ``` Heap Memory Usage Non-Heap Memory Usage Memory Pool “Eden Space” Memory Pool “Survivor Space” Memory Pool “Tenured Gen” Memory Pool “Code Cache” Memory Pool “Perm Gen” ``` What is the difference between them ?
## Heap memory The heap memory is the runtime data area from which the Java VM allocates memory for all class instances and arrays. The heap may be of a fixed or variable size. The garbage collector is an automatic memory management system that reclaims heap memory for objects. * **Eden Space**: The pool from which memory is initially allocated for most objects. * **Survivor Space**: The pool containing objects that have survived the garbage collection of the Eden space. * **Tenured Generation** or **Old Gen**: The pool containing objects that have existed for some time in the survivor space. ## Non-heap memory Non-heap memory includes a method area shared among all threads and memory required for the internal processing or optimization for the Java VM. It stores per-class structures such as a runtime constant pool, field and method data, and the code for methods and constructors. The method area is logically part of the heap but, depending on the implementation, a Java VM may not garbage collect or compact it. Like the heap memory, the method area may be of a fixed or variable size. The memory for the method area does not need to be contiguous. * **Permanent Generation**: The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas. * **Code Cache**: The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code. [Here's some documentation on how to use Jconsole](http://java.sun.com/javase/6/docs/technotes/guides/management/jconsole.html).
The `new` keyword allocates memory on the Java heap. The heap is the main pool of memory, accessible to the whole of the application. If there is not enough memory available to allocate for that object, the JVM attempts to reclaim some memory from the heap with a garbage collection. If it still cannot obtain enough memory, an `OutOfMemoryError` is thrown, and the JVM exits. The heap is split into several different sections, called generations. As objects survive more garbage collections, they are promoted into different generations. The older generations are not garbage collected as often. Because these objects have already proven to be longer lived, they are less likely to be garbage collected. When objects are first constructed, they are allocated in the Eden Space. If they survive a garbage collection, they are promoted to Survivor Space, and should they live long enough there, they are allocated to the Tenured Generation. This generation is garbage collected much less frequently. There is also a fourth generation, called the Permanent Generation, or PermGen. The objects that reside here are not eligible to be garbage collected, and usually contain an immutable state necessary for the JVM to run, such as class definitions and the String constant pool. Note that the PermGen space is planned to be removed from Java 8, and will be replaced with a new space called Metaspace, which will be held in native memory. reference:http://www.programcreek.com/2013/04/jvm-run-time-data-areas/ [![Diagram of Java memory for several threads](https://i.stack.imgur.com/BNLk0.jpg)](https://i.stack.imgur.com/BNLk0.jpg) [![Diagram of Java memory distribution](https://i.stack.imgur.com/uDdEk.png)](https://i.stack.imgur.com/uDdEk.png)
How is the java memory pool divided?
[ "", "java", "memory", "pool", "" ]
I need a plugin which highlights/points to a div box on the page on page load. The tooltip should then be able to be closed and/or will disappear after a few seconds. I am having difficulty finding one, as all the current ones seem to require the mouse to hover over the intended target. Are there any plugins that people recommend out of experience? I use Jquery, so ideally it would be in Javascript and/or JQuery.
[qTip](http://craigsworks.com/projects/qtip/) is the best tooltip I've ever seen. Try it.
<http://flowplayer.org/tools/tooltip.html>
Good Javascript plugin to display tooltip briefly on page load
[ "", "javascript", "jquery", "plugins", "tooltip", "" ]
I have a situation whereby I'm populating an `ArrayList` with "`TransactionEvent`"s. `TransactionEvent` has a property "transaction ID". In the large majority of cases each new event has a transaction ID greater the previous event's ID - However, this is not guaranteed; i.e. the data is *almost sorted*. My question is this: How can I perform fast look-ups based on transaction ID? My current idea is to call `Collections.binarySearch(...)` and if this fails then perform a linear search. However, I notice the Javadoc states that the result of binarySearch is undefined is the data is unordered so I may have to roll my own implementation. Additional: * I have tried using a map of index -> transaction ID but this approach is flawed because whenever an list element is updated / deleted I have to rebuild the entire map; i.e. any gains are erased by this. * This is not a case of premature-optimisation: The `List` is the basis for a `TableModel` currently performing very slowly when containing a large number of rows (100,000). Any help appreciated.
You could keep the ArrayList sorted by searching for the insertion point as you add each `TransactionEvent`. [Collections.binarySearch](http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html#binarySearch(java.util.List,%20java.lang.Object,%20java.util.Comparator)) returns > index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size(), if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found. Once you search for the insertion point you can use the ArrayList [add(int index, Object element)](http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#add(int,%20java.lang.Object)) method instead of just adding to the end of the list as you would normally. This will slow down each insertion by a small factor, but it will enable you to use binary search for fast look-up.
Using a LinkedHashMap, which combines a double linked list which hash access, you should be able to interface with the TableModel as you are with an ArrayList but also access the entries via a hash lookup on TransactionID. You can even replace (e.g. update) based on a key without affecting the iteration order.
Efficient look-up in a List
[ "", "java", "algorithm", "data-structures", "" ]
``` new Timer(...).schedule(task) ``` Is `task` guaranteed to be run by a single thread at any given time?
From the [Javadoc](http://java.sun.com/javase/6/docs/api/java/util/Timer.html) > Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially. Timer tasks should complete quickly. If a timer task takes excessive time to complete, it "hogs" the timer's task execution thread. This can, in turn, delay the execution of subsequent tasks, which may "bunch up" and execute in rapid succession when (and if) the offending task finally completes. So, yes, you get a new Thread (separate from the caller's thread). Every task in that timer shares the same thread.
There is a single thread per Timer, so the answer to your question is yes
Is Java's Timer task guaranteed not to run concurrently?
[ "", "java", "concurrency", "timer", "" ]
> **Possible Duplicate:** > [What is the best way to compare two entity framework entities?](https://stackoverflow.com/questions/1092534/what-is-the-best-way-to-compare-two-entity-framework-entities) I want to know the most efficient way of comparing two entities of the same type. One entity is created from an xml file by hand ( ie new instance and manually set properties) and the other is retvied from my object context. I want to know if the property values are the same in each instance. My first thoughts are to generate a hash of the property values from each object and compare the hashes, but there might be another way, or a built in way? Any suggestions would be welcome. Many thanks, James UPDATE I came up with this: ``` static class ObjectComparator<T> { static bool CompareProperties(T newObject, T oldObject) { if (newObject.GetType().GetProperties().Length != oldObject.GetType().GetProperties().Length) { return false; } else { var oldProperties = oldObject.GetType().GetProperties(); foreach (PropertyInfo newProperty in newObject.GetType().GetProperties()) { try { PropertyInfo oldProperty = oldProperties.Single<PropertyInfo>(pi => pi.Name == newProperty.Name); if (newProperty.GetValue(newObject, null) != oldProperty.GetValue(oldObject, null)) { return false; } } catch { return false; } } return true; } } } ``` I haven't tested it yet, it is more of a food for thought to generate some more ideas from the group. One thing that might be a problem is comparing properties that have entity values themselves, if the default comparator compares on object reference then it will never be true. A possible fix is to overload the equality operator on my entities so that it compares on entity ID.
As is the code will not do what you are expecting. Try this simple test: ``` class A { public int Id { get; set; } public string Name { get; set; } } class B : A { public DateTime BirthDate { get; set; } } class ObjectComparer { public static void Show() { A a = new A(); B b = new B(); A a1 = new A(); Console.WriteLine(ObjectComparator.CompareProperties(a, b)); Console.WriteLine(ObjectComparator.CompareProperties(b, a)); Console.WriteLine(ObjectComparator.CompareProperties(a, a1)); } } ``` You would expect it to return false false true but it returns false false false try changing the inner if to look like: ``` if (!object.Equals(newProperty.GetValue(newObject, null), oldProperty.GetValue(oldObject, null))) { return false; } ``` You can also save some time in the case a and a1 both reference the same object by checking that in the begining of the method. ``` static class ObjectComparator { public static bool CompareProperties(T newObject, T oldObject) { if (object.Equals(newObject, oldObject)) { return true; } if (newObject.GetType().GetProperties().Length != oldObject.GetType().GetProperties().Length) { return false; } else { var oldProperties = oldObject.GetType().GetProperties(); foreach (PropertyInfo newProperty in newObject.GetType().GetProperties()) { try { PropertyInfo oldProperty = oldProperties.Single(pi => pi.Name == newProperty.Name); if (!object.Equals(newProperty.GetValue(newObject, null), oldProperty.GetValue(oldObject, null))) { return false; } } catch { return false; } } return true; } } } ``` If you are concered with performance, you can cache the return of Type.GetProperties into a local variable during the lifetime of the method, since Reflection does not do that by itself at least up to version 3.5 SP1. In doing that you will drop GetProperties calls from four to two. If you are only expecting to compare objects of exactly the same type (or put another way not compare between base and derived instances), you can further reduce the calls of GetProperties to one. Hope this helps.
I would do something like this ``` static class ObjectComparator<T> { public static bool CompareProperties(T newObject, T oldObject) { if (Equals(newObject, oldObject)) { return true; } PropertyInfo[] newProps = newObject.GetType().GetProperties(); PropertyInfo[] oldProps = oldObject.GetType().GetProperties(); if (newProps.Length != oldProps.Length) { return false; } foreach (PropertyInfo newProperty in newProps) { PropertyInfo oldProperty = oldProps.SingleOrDefault(pi => pi.Name == newProperty.Name); if (oldProperty == null) return false; object newval = newProperty.GetValue(newObject, null); object oldval = oldProperty.GetValue(oldObject, null); if (!Equals(newval, oldval)) return false; } return true; } } ```
How to write an entity comparator in C# (with example code of first attempt)
[ "", "c#", ".net", "performance", "entity-framework", "comparison", "" ]
im trying to create an array: `int HR[32487834];` doesn't this only take up about 128 - 130 megabytes of memory? im using MS c++ visual studios 2005 SP1 and it crashes and tells me stack overflow.
While your computer may have gigabytes of memory, the stack does not (by default, I think it is ~1 MB on windows, but you can make it larger). Try allocating it on the heap with `new []`.
Use a vector - the array data will be located on the heap, while you'll still get the array cleaned up automatically when you leave the function or block: ``` std::vector<int> HR( 32487834); ```
c++ memory allocation question
[ "", "c++", "memory", "allocation", "" ]
I have content that is first `htmlentities` and then `stripslashes` followed by `nl2br`. This means a watermark at the end ends up as: ``` <li><p><!-- watermark --></p></li> ``` Not very useful. I have the code below to try and strip the html comments and stop it displaying but its not very good at it! ``` $methodfinal = str_replace('<li><p><!--', '<!--', $method); $methodfinal2 = str_replace('--></p></li>', '-->', $methodfinal); echo $methodfinal2; ``` anyone got any ideas?
EDIT: following Zed's and your comments I've done some testing and this is what you should use: ``` $final = preg_replace('/<li><p>[\s]*?&lt\;!--(.*?)--&gt\;<\/p><\/li>/m', "<!--$1-->", $z); ``` Here is a breakdown of the RE: ``` <li><p> ``` this is obvious ``` [\s]*? ``` because you have a few spaces and a newline between the `<li>` and the comment, but we want the least number of newlines so we use the non greedy \*? (it sould work with \* as well) ``` &lt\; ``` need to escape the ; ``` !--(.*?)-- ``` again we use \*? so we would match only this line (other wise if you had the same line again it wold match from the first one to the last one ``` &gt\;<\/p><\/li> ``` same as above ``` /m' ``` so php would treat newlines as whitespace (i am not sure about this but it seems to be working)
Something like this? ``` $final = preg_replace("/<li><p>(<!--.*-->)<\/p><\/li>/", "$1", $original); ```
I have HTML comments being wrapped in Li and P tags :(
[ "", "php", "html", "regex", "preg-replace", "" ]
I know there's an easy answer to this, but this comes in the form of 2 problems. **Problem 1:** In an asp.net page there is a javascript block like this: ``` <script type="text/javascript"> function doSomethingRandom() { var myVarToUse = <asp:Literal runat="server" ID="HackyLiteral" /> } </script> ``` Ok, so it's a simplified version of the problem, but it should be clear. I now want to move this function in to a JS file...but I can't get the asp:Literal into the JS. ``` var myVarToUse = <asp:Literal runat="server" ID="HackyLiteral" /> <script src="myJSFile.js" /> ``` ...Makes me a little sick, is there a better way? **Problem 2:** Similar problem, but this time the second version looks like this: ``` <asp:ScriptManagerProxy runat="server"> <Scripts> <asp:ScriptReference Path="~/tree/AttributeTree.js" /> </Scripts> </asp:ScriptManagerProxy> ``` But this time I can't realistically put the ``` var myVarToUse = <asp:Literal runat="server" ID="HackyLiteral" /> ``` above it because with the ScriptManagerProxy there's no real way of knowing exactly where the script file is going to appear. So, them's the problems! Thanks.
We use the `Page`'s [`RegisterStartupScript`](http://msdn.microsoft.com/en-us/library/system.web.ui.page.registerstartupscript.aspx) method to register initialization functions with the ClientScriptManager. Our Javascript files only contain functions and are loaded via `ScriptManager` (like in your snippet). We wrote an extension method for the Page (called `JSStartupScript`) that helps with registering the startup scripts and at the end of the day our code looks like the following: ``` <% Page.JSStartupScript(string.Format("initFeatureX({0}, {1}, {2});", AntiXss.JavaScriptEncode(ViewData.Property1), AntiXss.JavaScriptEncode(ViewData.Property2), AntiXss.JavaScriptEncode(ViewData.Property3))); %> ``` This also works great in combination with the `ScriptManager`s `CompositeScript` collection and `LoadScriptsBeforeUI = false` setting.
Basically: you can't do that. What you can do is set the value on the site which is generated by ASP (like you have now) and then refer to that variable from external js scripts, but that's ugly. The other solution is that you can store this variable in a cookie (which will be set by ASP) and then read that cookie in external JS. You can also pass this value to a URL of a site you are displaying and parse the url in JS to get the value but I think cookies will be better for that since you will still have a clean URL and reading cookie is easier then parsing url params.
How to pass variables in to a JS file
[ "", "asp.net", "javascript", "asp.net-ajax", "" ]
I am using VSTS2008 + C# + .Net 3.0. I am using below code to serialize XML, here is my current code and serialized XML file. My purpose is I want to make MyInnerObjectProperties belongs to a special XML namespace (<http://foo/2009>) and making this namespace as default namespace. Any ideas how to implement this? Current output: ``` <?xml version="1.0"?> <MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <MyObjectProperty> <MyInnerObjectProperties> <MyInnerObjectProperty> <ObjectName>Foo Type</ObjectName> </MyInnerObjectProperty> <MyInnerObjectProperty> <ObjectName>Goo Type</ObjectName> </MyInnerObjectProperty> </MyInnerObjectProperties> </MyObjectProperty> </MyClass> ``` Current code: ``` public class MyClass { private MyObject[] _myObjectProperty; [XmlElement(IsNullable=false)] public MyObject[] MyObjectProperty { get { return _myObjectProperty; } set { _myObjectProperty = value; } } } public class MyObject { private MyInnerObject[] _myInnerObjectProperty; [XmlArrayItemAttribute("MyInnerObjectProperty", typeof(MyInnerObject), IsNullable=false)] public MyInnerObject[] MyInnerObjectProperties { get { return _myInnerObjectProperty; } set { _myInnerObjectProperty = value; } } } public class MyInnerObject { public string ObjectName; } public class Program { static void Main(string[] args) { XmlSerializer s = new XmlSerializer(typeof(MyClass)); FileStream fs = new FileStream("foo.xml", FileMode.Create); MyClass instance = new MyClass(); instance.MyObjectProperty = new MyObject[1]; instance.MyObjectProperty[0] = new MyObject(); instance.MyObjectProperty[0].MyInnerObjectProperties = new MyInnerObject[2]; instance.MyObjectProperty[0].MyInnerObjectProperties[0] = new MyInnerObject(); instance.MyObjectProperty[0].MyInnerObjectProperties[0].ObjectName = "Foo Type"; instance.MyObjectProperty[0].MyInnerObjectProperties[1] = new MyInnerObject(); instance.MyObjectProperty[0].MyInnerObjectProperties[1].ObjectName = "Goo Type"; s.Serialize(fs, instance); return; } } ```
You need to create an **XmlSerializerNamespaces** object, and add your needed namespaces to it. The [XmlSerializerNamespaces](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializernamespaces.aspx) object contains the XML namespaces and prefixes that the XmlSerializer uses to generate qualified names in an XML-document instance. In your c# code: ``` XmlSerializerNamespaces myNameSpaces = new XmlSerializerNamespaces(); myNameSpaces.Add("MyInnerObject", "http://foo/2009"); ``` Then, add an attribute to your class, like this: ``` public class MyInnerObject { [XmlElement(Namespace = "http://foo/2009")] ``` More info at: <http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializernamespaces.aspx>
How about this: ``` [XmlArrayItemAttribute( Namespace = "http://foo.com/2009" /* other attr. params. */ )] public MyInnerObject[] MyInnerObjectProperties { get { ... } set { ... } } ```
Placing a Property into a Different XML Namespace with XML Serialization
[ "", "c#", ".net", "xml", "visual-studio-2008", "xml-serialization", "" ]
Im trying to setup a program that will accept an incoming email and then break down the "sender" and "message" into php variables that i can then manipulate as needed, but im unsure where to start. I already have the email address piped to the php file in question (via cpanel)
Start with: ``` $lines = explode("\n",$message_data); $headers = array(); $body = ''; $in_body = false; foreach($lines as $line) { if($in_body) { $body .= $line; } elseif($line == '') { $in_body = true; } else { list($header_name,$header_value) = explode(':',$line,2); $headers[$header_name] = $header_body; } } // now $headers is an array of all headers and you could get the from address via $headers['From'] // $body contains just the body ``` I just wrote that off the top of my head; haven't tested for syntax or errors. Just a starting point.
Here is working solution ``` #!/usr/bin/php -q <?php // read from stdin $fd = fopen("php://stdin", "r"); $email = ""; while (!feof($fd)) { $email .= fread($fd, 1024); } fclose($fd); // handle email $lines = explode("\n", $email); // empty vars $from = ""; $subject = ""; $headers = ""; $message = ""; $splittingheaders = true; for ($i=0; $i < count($lines); $i++) { if ($splittingheaders) { // this is a header $headers .= $lines[$i]."\n"; // look out for special headers if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) { $subject = $matches[1]; } if (preg_match("/^From: (.*)/", $lines[$i], $matches)) { $from = $matches[1]; } } else { // not a header, but message $message .= $lines[$i]."\n"; } if (trim($lines[$i])=="") { // empty line, header section has ended $splittingheaders = false; } } echo $from; echo $subject; echo $headers; echo $message; ?> ``` Works like a charm.
php email piping
[ "", "php", "email", "string", "" ]
We are searching for an Library which supports the marshalling and unmarshalling like JAX-B in Java, is there any state-of-the-art library to use?
Like Bruno said, what you're looking for is in the [System.Xml.Serialization](http://msdn.microsoft.com/en-us/library/system.xml.serialization.aspx) namespace, more specifically the [XmlSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx) class. To serialize an object into XML, you just need to call the [Serialize](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.serialize.aspx) method, and the reverse can be done with the [Deserialize](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.deserialize.aspx) method. For more information, have a look at the MSDN topic [Introducing XML Serialization](http://msdn.microsoft.com/en-us/library/182eeyhh(VS.71).aspx). You can sometimes hit a snag when serializing to XML, if you're having trouble be sure to check out (and contribute to) [this thread](https://stackoverflow.com/questions/67959/net-xml-serialization-gotchas).
[`System.Xml.Serialization`](http://msdn.microsoft.com/en-us/library/system.xml.serialization.aspx) Namespace is what you need. It can work with [attributes](http://msdn.microsoft.com/en-us/library/z0w1kczw.aspx), like Java annotations.
Is there something like JAX-B for C#?
[ "", "c#", "xml", "jaxb", "marshalling", "" ]
In a model I have a such field: mydate = models.DateField() now a javascript graph function requires unix timestamp such as "1196550000000", how can I return the unix timestamp of my mydate input. Thanks
**edit: please check the second answer, it has a much better solution** In python code, you can do this to convert a date or datetime to the Unix Epoch ``` import time epoch = int(time.mktime(mydate.timetuple())*1000) ``` This doesn't work in a Django template though, so you need a custom filter, e.g: ``` import time from django import template register = template.Library() @register.filter def epoch(value): try: return int(time.mktime(value.timetuple())*1000) except AttributeError: return '' ```
I know another answer was accepted a while ago, but this question appears high on Google's search results, so I will add another answer. If you are working at the template level, you can use the [`U` parameter](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#std:templatefilter-date) to the `date` filter, e.g.: ``` {{ mydate|date:"U" }} ``` Note that it will be based upon the `TIMEZONE` in your settings.py.
django Datefield to Unix timestamp
[ "", "python", "django", "unix-timestamp", "" ]
I want to increment a url automatically using javascript and use it in Greasemonky on "Firefox" ex: ``` www.google.com/id=1 www.google.com/id=01 www.google.com/id=001 www.google.com/id=0001 ``` how can I achieve that using javascript??? here is what I wrote --- ``` var numberr = “2”; var totall = “”; var timeout = 12000; setTimeout(function() { var numm = “0” + numberr; totall = “http://www.google.com/id=0” + numm; window.location.href = totall; }, timeout); ``` --- but i doesn't increment the zeros as i expected, can anybody help me? I don't know what is the problem, maybe it is the Greasemonkey?? I don't know ## --------------------------------------------------------------- OK, It seems to be a javascript unfixable problem, So I'll implement the logic in a Windows application using C#, BUT I neet to know how to access [[firefox]] url , and reload action through C# in a windows application, can anybody help?????
Your variable values won't persist between page loads, thus resetting the counter each time. There is a solution, however! ``` GM_setValue(key, value); GM_getValue(key[, defaultValue]); ``` <http://diveintogreasemonkey.org/advanced/gm_getvalue.html> Alternatively, you can parse the current URL to determine your location within the loop. Try this: ``` // ==UserScript== // @name Incremental URL // @include http://www.google.com/* // ==/UserScript== var url = 'http://www.google.com/id=', start = '2', prepend = '0', limit = 10, timeout = 1000*12, regex = new RegExp('^' + url + '(' + prepend + '{0,' + (limit-1) + '})' + start + '$'); matches = window.location.href.match(regex); if(matches) { setTimeout(function() { window.location.href = url + prepend + matches[1] + start; }, timeout); } ```
What number are you coming up with? it looks like you are always going to be adding one more 0 than your description indicates since you are automatically adding one 0 with ``` var numm = “0” + numberr; totall = “http://www.google.com/id=0” + numm; ``` by the look of those lines, even if you start out with "2", your first request will be ``` www.google.com/id=002 ``` edit: and another thing, you are going to need to assign numm to numberrr at the end of the function call. Is this what you are trying to achieve? ``` var numberr = “2”; var totall = “”; var timeout = 12000; setTimeout(function() { var numm = “0” + numberr; totall = “http://www.google.com/id=” + numm; window.location.href = totall; numberr = numm; }, timeout); ``` edit again: ya, what Zed says, once you change your page location everything will reset anyways.
how to increment a url with zeros every specific interval "Javascript"?
[ "", "javascript", "" ]
I need to validate the below range via regex in javascript. -20.00 to +20.00 with an increment of 0.5. The user should be able to enter the 1.50 as well instead of +01.50. I tried to do a lot of research in google, though regex is not easy. If I understand it correctly, then I will need to split up the regex into smaller groups. From a programmers view, I would think, that I need to validate each "char" that was keyed into the input field. If I understand how grouping works in regex then I guess I could do the regex myself. So please help me to understand regex with the above problem, don't just throw the regex in :) Thanks,
Following should do it ``` var myregexp = /^[+-]?(20\.00|[01?][0-9]\.[05]0)$/m; if (subject.match(myregexp)) { // Successful match } else { // Match attempt failed } // ^[+-]?(20\.00|[01?][0-9]\.[05]0)$ // // Options: ^ and $ match at line breaks // // Assert position at the beginning of a line (at beginning of the string or after a line break character) «^» // Match a single character present in the list below «[+-]?» // Between zero and one times, as many times as possible, giving back as needed (greedy) «?» // The character “+” «+» // The character “-” «-» // Match the regular expression below and capture its match into backreference number 1 «(20\.00|[01?][0-9]\.[05]0)» // Match either the regular expression below (attempting the next alternative only if this one fails) «20\.00» // Match the characters “20” literally «20» // Match the character “.” literally «\.» // Match the characters “00” literally «00» // Or match regular expression number 2 below (the entire group fails if this one fails to match) «[01?][0-9]\.[05]0» // Match a single character present in the list “01?” «[01?]» // Match a single character in the range between “0” and “9” «[0-9]» // Match the character “.” literally «\.» // Match a single character present in the list “05” «[05]» // Match the character “0” literally «0» // Assert position at the end of a line (at the end of the string or before a line break character) «$» ```
It doesn't really make sense to use a regular expression to validate a numeric value. Try: ``` function checkRange(input) { var value = parseFloat(input); return (!isNaN(value) && (value >= -20) && (value <= 20) && (value % 0.5 == 0)); } ```
Javascript Regex help for beginner
[ "", "javascript", "regex", "" ]
I would like to be able to change the default behaviour of an ASP.NET link button so that the JavaScript postback call happens in the onclick event rather than having it as the href attribute. This would mean that a user hovering over the button would not see the JavaScript in the browsers status bar. Is this possible or should I attempt to abandon the link button altogether?
You can do it by writing a control adapter that outputs the javascript in the onclick instead of the href. There are a couple of linkbutton adapters listed in the patches for the cssfriendly control adapter set on this page: <http://cssfriendly.codeplex.com/SourceControl/PatchList.aspx?ViewAll=true> I don't know if a link button adapter has been added to the release version. But you could download one from this page and used it as a reference when creating your own adapter. . . . **Update 10/10/2009:** I've actually changed my answer a bit, the control adapter idea will still work, but it might be easier to just to create a new control that inherits from linkbutton. I say this because you could just get the rendered output and replace the href with onclick, then you don't have to worry about losing any of the functionality of the linkbutton formatting, the only thing you lose is OnClientClick Here is a control I wrote to add a NavigateURL property to a linkbutton, and when the NavigateURL is set, it will render the postback javascript in the onclick. It is pretty close to what you want. The reason I wrote this control is because I have paging on certain pages, and I want to provide paging links that search engines can follow, but have the postback functionality for regular users so that their filters get posted back. ``` using System; using System.ComponentModel; using System.Drawing; using System.Globalization; using System.IO; using System.Web.UI; using System.Web.UI.WebControls; using System.Text.RegularExpressions; namespace CustomControls { /// <summary> /// This control renders the postback javascript in the onclick event if a href is passed in /// this allow the control to work as normal for browsers, but will provide an alternate link for /// crawlers to follow. If the href is not set it works identically to the original link button /// </summary> /// [Themeable(true), ToolboxData("<{0}:OnClickLinkButton runat=server></{0}:OnClickLinkButton>")] public class OnClickLinkButton : LinkButton { [Browsable(true), DefaultValue(""), Bindable(true), Category("Navigation"), Description("Set the hyperlink url for the linkbutton for browsers without javascript")] public string NavigateURL { get { return ViewState["NavigateURL"] == null ? string.Empty : (string)ViewState["NavigateURL"]; } set { ViewState["NavigateURL"] = value; } } protected override void Render(HtmlTextWriter output) { if (NavigateURL == string.Empty) { base.Render(output); } else { //we need to clear out the on client click because we are //abusing the onclient click for our own purposes OnClientClick = ""; StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); base.Render(hw); string RenderedOutput = sw.ToString(); Match m = Regex.Match(RenderedOutput, @"doPostBack\(.+\)", RegexOptions.IgnoreCase); if (m.Success) { RenderedOutput = RenderedOutput.Replace("href", string.Format("href=\"{0}\" onclick", NavigateURL)) .Replace(m.Value, m.Value + "; return false;"); } output.Write(RenderedOutput); } } } } ```
You can use the OnClientClick attribute to set the javascript click event, but by default the LinkButton will still fire a postback. If this isn't desired, you could always add "return false;" to the end of your OnClientClick javascript call. This would keep the link from leaving the page. `<asp:LinkButton OnClientClick="alert('hi');return false;" runat="server" PostBackUrl="#" ID="TEST">TEST</asp:LinkButton>`
On an ASP.NET link button, Is it possible to move the JavaScript function call from the "href" attribute to the onclick event?
[ "", "asp.net", "javascript", "" ]
does someone knows how to use the "new" Zend Autoloader to Load Models ? In the Moment my Configuration looks like this : application.ini ``` # Autoloader Namespace autoloadernamespaces.0 = "Sl_" ``` Bootstrap.php ``` /** * Start Autoloader * * @access protected * @return Zend_Application_Module_Autoloader */ protected function _initAutoload() { $autoloader = new Zend_Application_Module_Autoloader(array( 'namespace' => 'Sl_', 'basePath' => dirname(__FILE__), )); return $autoloader; } ``` So when I place a Model in /Models/User.php with ``` class Sl_Model_User{} ``` and create an new object , everything works like designed. But how can i use the Autoloader to load a Model placed in /Models/Dao/UserDB.php ? ``` class Dao_UserDB{} ```
Check the documentation on the Resource\_Autoloader (its purpose is to load resources that reside in the models directory or elsewhere - i.e outside the /library folder). "Resource autoloaders are intended to manage namespaced library code that follow Zend Framework coding standard guidelines, but which do not have a 1:1 mapping between the class name and the directory structure. Their primary purpose is to facilitate autoloading application resource code, such as application-specific models, forms, and ACLs. Resource autoloaders register with the autoloader on instantiation, with the namespace to which they are associated. This allows you to easily namespace code in specific directories, and still reap the benefits of autoloading." ``` path/to/some/directory/ acls/ Site.php forms/ Login.php models/ User.php $resourceLoader = new Zend_Loader_Autoloader_Resource(array( 'basePath' => 'path/to/some/directory', 'namespace' => 'My', ``` )); ``` $resourceLoader->addResourceTypes(array( 'acl' => array( 'path' => 'acls/', 'namespace' => 'Acl', ), 'form' => array( 'path' => 'forms/', 'namespace' => 'Form', ), 'model' => array( 'path' => 'models/', ), ``` )); Try this in your boostrap file: ``` protected function _initLoaderResource() { $resourceLoader = new Zend_Loader_Autoloader_Resource(array( 'basePath' => 'your_doc_root' . '/application', 'namespace' => 'MyNamespace' )); $resourceLoader->addResourceTypes(array( 'model' => array( 'namespace' => 'Model', 'path' => 'models' ) )); } ```
Depending on your current setup ClassFile: /Models/Dao/UserDB.php ClassName: class Dao\_UserDB{} should be: ``` $autoloader = new Zend_Application_Module_Autoloader(array( 'namespace' => 'Dao_', 'basePath' => APPLICATION_ROOT.'/Models/Dao/', )); ``` But you also could name the Class: S1\_Dao\_UserDB() this should work without changing.
Use Zend_Autoloader for Models
[ "", "php", "zend-framework", "autoloader", "" ]
I need to run a .cmd batch file from within a php script. The PHP will be accessed via an authenticated session within a browser. When I run the .cmd file from the desktop of the server, it spits out some output to cmd.exe. I'd like to route this output back to the php page. Is this doable?
Yes it is doable. You can use ``` exec("mycommand.cmd", &$outputArray); ``` and print the content of the array: ``` echo implode("\n", $outputArray); ``` [look here for more info](https://www.php.net/manual/en/function.exec.php)
``` $result = `whatever.cmd`; print $result; // Prints the result of running "whatever.cmd" ```
How to run a .cmd file from within PHP and display the results
[ "", "php", "batch-file", "cmd", "windows-server-2003", "" ]
I'm trying to develop a cross platform application, where the most obvious route would be a web site with JavaScript, but then I lose the cosy comforts I'm used to using in my C# desktop apps, like file system access etc. How do I go about accessing *similar* services from within the browser? E.g. I don't need to access anything I don't create, so actual file system access is just a luxury. I can use whatever the browser offers for offline storage, but have no clue how to do this.
Have a look at [Google Gears](http://code.google.com/intl/sv/apis/gears/api_database.html).
Depending what you need to store you could possibly use a cookie. For larger storage this is what the upcoming HTML5 client-side storage methods address, but we're not quite there yet. Security concerns prevent browsers from getting real access to storing things client-side for the most part, though.
How do I get maximum offline storage from within a web site?
[ "", "javascript", "" ]
I've added a checkbox column to a DataGridView in my C# form. The function needs to be dynamic - you select a customer and that brings up all of their items that could be serviced, and you select which of them you wish to be serviced this time around. Anyway, the code will now add a chckbox to the beginning of the DGV. What I need to know is the following: 1) How do I make it so that the whole column is "checked" by default? 2) How can I make sure I'm only getting values from the "checked" rows when I click on a button just below the DGV? Here's the code to get the column inserted: ``` DataGridViewCheckBoxColumn doWork = new DataGridViewCheckBoxColumn(); doWork.HeaderText = "Include Dog"; doWork.FalseValue = "0"; doWork.TrueValue = "1"; dataGridView1.Columns.Insert(0, doWork); ``` So what next? Any help would be greatly appreciated!
1. There is no way to do that directly. Once you have your data in the grid, you can loop through the rows and check each box like this: ``` foreach (DataGridViewRow row in dataGridView1.Rows) { row.Cells[CheckBoxColumn1.Name].Value = true; } ``` 2. The Click event might look something like this: ``` private void button1_Click(object sender, EventArgs e) { List<DataGridViewRow> rows_with_checked_column = new List<DataGridViewRow>(); foreach (DataGridViewRow row in dataGridView1.Rows) { if (Convert.ToBoolean(row.Cells[CheckBoxColumn1.Name].Value) == true) { rows_with_checked_column.Add(row); } } // Do what you want with the check rows } ```
``` private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { DataGridViewCheckBoxCell ch1 = new DataGridViewCheckBoxCell(); ch1 = (DataGridViewCheckBoxCell)dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0]; if (ch1.Value == null) ch1.Value=false; switch (ch1.Value.ToString()) { case "True": ch1.Value = false; break; case "False": ch1.Value = true; break; } MessageBox.Show(ch1.Value.ToString()); } ``` best solution to find if the checkbox in the datagridview is checked or not.
DataGridView checkbox column - value and functionality
[ "", "c#", "winforms", "datagridview", "checkbox", "" ]
An easy question I guess, but in the documentation of the Type class they only talk of interfaces on the GetInterfaces method. i.e. typeof(ChildClass).XXX(typeof(ParentClass)
It depends on what you need; IsAssignableFrom, perhaps: ``` bool stringIsObj = typeof(object).IsAssignableFrom(typeof(string)); ``` or `IsSubclassOf`: ``` bool stringIsObj = typeof(string).IsSubclassOf(typeof(object)); ```
typeof(ParentClass).IsAssignableFrom(typeof(ChildClass))
In C# what is the equivalent of "is" keyword but using Type objects
[ "", "c#", "introspection", "" ]
Within a HttpModule I would like to check whether the url ends with a file: ie. www.example.com/images/images.css and what the file extension is ie. css or js In the Begin\_Request event handler, using the Url property of the Request object nested in the HttpApplication, I am currently cutting of the file extension using String operations. Is there a better way to do this?
The code below should get you the extension for the requested file. ``` private void context_BeginRequest(object sender, EventArgs e) { HttpApplication application = (HttpApplication)sender; HttpContext context = application.Context; string ext = System.IO.Path.GetExtension(context.Request.Path); // ext will always start with dot } ``` But unlike file types such as .aspx and .ashx file types such as .js and .css that you have used in your example are not by default registered with the ASP.Net dll within IIS so when they are requested IIS doesn't pass the request through the ASP.Net pipeline so no HttpModules or HttpHandlers will run. How you configure this to happen depends on what version of IIS you are running on.
``` string url = context.Request.Path; string extension = VirtualPathUtility.GetExtension(url); ```
HttpModule/HttpApplication testing whether url is a request for a file
[ "", "c#", "file", "request", "httpmodule", "" ]
Classic javascript: ``` var myvar = document.getElementById("abc"); abc.value += "test"; abc.value += "another test"; ``` Jquery: ``` $("#abc").val($("#abc").val()+"test"); $("#abc").val($("#abc").val()+"another test"); ``` Is there a way to make my Jquery prettier, maybe with a hidden += function that I could use? I know that .val() is not an attribute, but I feel there must be a way to make this code more beautiful to look at... Something like this would be great: ``` $("#abc").valueAttribute += "test" $("#abc").val().content += "test" $("#abc").val().add("test") ```
Since jQuery 1.4, it is possible to pass a function to [`.val()`](http://api.jquery.com/val/#val2) which gets the current value as second argument: ``` $("#abc").val(function(i, val) { return val + "test"; }); ```
You could go back to the original DOM element. ``` $("#abc").get(0).value += "test"; ``` Otherwise, you'd have to write a plugin ``` $.fn.appendVal = function (newPart) { return this.each(function(){ $(this).val( $(this).val() + newPart); }); }; $("#abc").appendVal("test"); ```
Is it possible to do ".value +=" in JQuery?
[ "", "javascript", "jquery", "" ]
I need a quick regexp for validating that a string is a valid .au domain name. For example: ``` xxx.com.au xxx.net.au xxx.org.au xxx.biz.au xxx.--.au ``` all of these should be considered valid. This should be pretty simple for someone not as hopeless with regexps as I am. Any ideas?
If you want to only allow certain secondary TLDs in the .au space: ``` /^[a-zA-Z0-9-]+\.(?:com|net|org|biz)\.au$/ ``` Modify the list of secondaries separated by |'s as you desire. If you don't mind about strictly validating the secondary TLD: ``` ^[a-zA-Z0-9-]+\.\a+\.au$ ``` And if you want to allow more subdomains (i.e. xxxx.yyyy.com.au): ``` ^(?:[a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.\a+\.au$ ``` You may need to use `a-zA-Z` instead of `\a` if the particular regex engine you're using doesn't support the latter.
``` ^[\w\d-\.]+\.au$ ``` That should work fine. You can't really do much else since what comes before the .au might add other second level domains on top of [the ones that already exist](http://en.wikipedia.org/wiki/.au#Second-level_domains).
Regexp for validating .au domain names
[ "", "php", "regex", "string", "" ]
I am programmer with a games and 3D graphics background and at the moment I would like to brush up on my networking and web development skills. I have a task that I would like to accomplish to do this. My idea is that I would like to be able to send a HTTP request or something similar to my webserver, which runs a LAMP based setup. I would like to know how I can send a HTTP request containing some information from my iPhone using the Cocoa Touch framework, to my webserver. I would like the webserver (using PHP) to be able to record the sent information into a plain text file, that I can use later to make graphs. For my example we could just send the current date. I think that people must do this very often and I really want to know how to do this. Thanks for your help. P.S. If you don't know the Cocoa code in order to send the request, that's okay I'm sure I can figure that out, but I would like to at least know how to get the Linux server to save the HTTP request, preferrably PHP but another appropriate language is fine. Bonus marks for away to do this **securely**. Also: I am a total noob at this and require source code, cheers :D
You really can't go past a library like [ASIHTTPRequest](http://allseeing-i.com/ASIHTTPRequest/) if you need to make HTTP requests from an iPhone or Mac client to a web server. The documentation is very good, and covers all the important topics like: * asynchronous vs synchronous requests * sending data to the server * tracking upload/download progress * handling authentication * using the keychain for storage of credentials * compressing request bodies with gzip You should [check it out](http://allseeing-i.com/ASIHTTPRequest/How-to-use) -- it will make your life much easier.
Okay no one has given an answer so I went off and discovered a project that details how to do this using either a Mac native app for a client or a PHP web page client. I modified some of the original server code slightly, just so you know I have tested this on my own site and it works for uploading files to a web server. **PHP Server (uploader.php)** ``` <?php $target = "upload/"; $target = $target . basename( $_FILES['uploaded']['name'] ); $filename = "\"" . basename( $_FILES['uploaded']['name'] ) . "\""; $ok = 1; if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "$filename"; echo "was uploaded successfully"; } else { echo "$filename"; echo "upload failed"; } ?> ``` **Web Client (index.php)** ``` <form enctype="multipart/form-data" action="uploader.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> Choose a file to upload: <input name="uploaded" type="file" /><br /> <input type="submit" value="Upload File" /> </form> ``` **Cocoa Client** The code for the Cocoa client is quite long and the code that goes with the above can be found [here](http://www.cocoadev.com/index.pl?HTTPFileUploadSample). There is an [alternative](http://cocoawithlove.com/2009/07/simple-extensible-http-server-in-cocoa.html) here, which I think is better code, but I haven't tested it with the PHP server above. I expect you could modify it with minimal changes if any though. **Here is a basic way in Cocoa to send a text POST request to a webserver:** ``` NSString* content = [@"item=" stringByAppendingString:@"Something to Post"]; NSURL* url = [NSURL URLWithString:@"http://www.mysite.com/index.php"]; NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc] initWithURL:url]; [urlRequest setHTTPMethod:@"POST"]; [urlRequest setHTTPBody:[content dataUsingEncoding:NSASCIIStringEncoding]]; ``` I like this because it is a minimal solution and you can build upon it easily and hopefully this can help someone else should they come across this :)
Send iPhone HTTP request to Apache PHP webserver
[ "", "php", "iphone", "linux", "http", "networking", "" ]
I have the following line of code: ``` var html = "..."; $("#id_name").append(html).fadeIn("slow"); ``` This causes the entire div #id\_name to fade in. I want *only* the *appended HTML* to fade in. How can this be accomplished?
You could do something like: ``` $('<div></div>').appendTo("#id_name").hide().append(html).fadeIn('slow'); ```
you'd have to make sure the variable "html" is a jquery object first , and present in the DOM. So you'd typically fire a callback function, fired when the append() is effective. example: ``` $("#id_name").append(html,function(){ $(html).fadeIn("slow"); }); ```
How to fade in appended HTML with jQuery?
[ "", "javascript", "jquery", "" ]
I was searching for the old versions of [SuperWaba](http://www.superwaba.com.br/), but i can't found anyone on internet, because the newer versions of SuperWaba are commercial, but the old versions are free, then if someone have the SuperWaba SDK free version on archive, please post it here. Thanks!
One more thing: the SuperWaba project with all sources is available at superwaba.sourceforge.net. But are you sure you can't afford 14.95usd to get a vm and a database? And, honestly, TotalCross is a great piece of software. There are many big companies around the world that adopted it. The next Brazilian Census will be made with it (200 thousands device running on field). If you're a student, you can just use the demo vm (which expires after 80 hours of continuous use). Then you are allowed to hard reset the device, install it again and use more 80 hours. regards
Great answer, thanks. I'll like to explain why we do not use GPL. Rick Wild sent us an agreement, when we developed SuperWaba, to allow us to change the license to LGPL. Without this change, no one would be able to produce commercial applications. In TotalCross, the Java classes are still LGPL. Regarding why the VM is not GPL/LGPL. The vm was written from SCRATCH, so we are able to put any license we want. We made this specially to not have to be tied to old licenses. Best regards ``` guich (TotalCross Lead Developer) ```
Old Version of SuperWaba
[ "", "java", "download", "archive", "" ]
I'm trying to make my child dialog box to be created as a member of the main application class as follows: ``` class ParentWindow : public CWinApp { public: // Other MFC and user-implemented classes before this line MiscSettings activeMiscSettings; public: ParentWindow(); ~ParentWindow(); // Overrides virtual BOOL InitInstance(); // Implementation afx_msg void OnAppAbout(); afx_msg void OnMiscSettingsPrompt(); DECLARE_MESSAGE_MAP() }; ``` I would like to have the dialog box described by MiscSettings to be instantiated when the program starts up, destructed when the program exits, and show/hide according to whether the user select a particular menu option vs. the user clicking a "OK" or "Cancel" button of the dialog box. However, when I implemented the OnMiscSettingsPrompt() handler function as follows: ``` void ParentWindow::OnMiscSettingsPrompt() { float temp; INT_PTR status = activeMiscSettings.DoModal(); switch(status) { case IDOK: temp = activeMiscSettings.GetSpeed(); break; case IDCANCEL: default: break; } } ``` I cannot access activeMiscSettings.GetSpeed() method b/c the handle is invalid after the DoModal() call. I used this method similar to other examples on showing child dialog boxes. However, the contents of activeMiscSettings were not accessible by ParentWindow class. I know I can put handlers in MiscSettings class to transfer the contents properly in the OK button handler of the edit control and other user control settings to the appropriate class contents of the rest of the application. At this point, I'm not sure what would be the cleanest way of transferring the settings on the child popup dialog to the rest of the application. Another specification that I am trying to achieve is to have the misc. settings pop-up dialog to show pre-configured settings when it first appears when the user selected the menu option for the first time. After changing some settings and pressing ok, if the user opens the settings window again, I would like to have the current settings show up in the user controls rather than showing the preconfigured settings previously seen in the very first instance. Is this an easily achievable goal? Thanks in advance for the comments.
I have ended up deciding to create a struct containing the settings to be configured in the child dialog in the parent dialog class, passing in the pointer to the struct when calling a constructor, and have the child dialog's OK button handler modify the struct's contents as it is a pointer. I think this is as clean as I can make the implementation for now.
You can achieve what you want with a modeless dialog, though it's a bit strange: - call the dialogs `Create` in `ParentWindow.OnCreate`. Pass ParentWindow as parent - the dialog needs to be created invisibly, IIRC you need to override `CMyDialog::PreCreateWindow` for that - to open the dialog, use `dlg.ShowWindow(SW_SHOW)` and `parent.EnableWindow(false)` - to close, use `dlg.ShowWindow(SW_HIDE)` and `parent.EnableWindow(true)` However, I'd advice against that. * It doesn't even attempt to separate view from controller, but that might be forgivable. * It binds the dialog to one parent, i.e. it can't be shown from another window. * It doesn't allow to implement "Cancel" correctly * Last not least, it feels very strange - which might be a code smell or a matter of taste. Here's what I'd consider "normal": All my settings dialogs are associated with a Settings class, and end up following roughly the following interface: ``` class CSettings { double speed; EDirection direction; bool hasSpeedStripes; bool IsValid(CString & diagnostics); }; class CSettingsDialog { CSettings m_currentSettings; public: // that's the method to call! bool Edit(CWnd * parent, CSettings & settings) { m_currentSettings = settings; // create copy for modification if (DoModal(parent) != IDOK) return false; settings = m_currentSettings; return true; } OnInitDialog() { // copy m_cuirrentSettings to user controls } OnOK() { // copy user controls to m_currentSettings CString diagnostics; if (!m_currentSettings.IsValid(diagnostics)) { MessageBox(diagnostics); // or rather, a non-modal error display return; } EndDialog(IDOK); } }; ``` The copy is necessary for the validate. I use the settings class for the "currentSettings" again, since I am not much in favor of MFC's DDX/UpdateData() mechanism, and often do the transfer manually. However, if you follow MFC's ideas, you would * use class wizard to map the controls to data members, where you can do basic range validation * In OnInitDialog, copy the settings to the data members and call UpdateData(false) * In OnOK, call UpdateData(true), and "return" the data members. You could even manually edit the DoDataExchange to map the controls directly to m\_currentSettings members, but that doesn't work always. --- A interdependency validation should be done on the copy since the user might change the values, see that the new values aren't ok, and then press cancel, expecting the original values to be preserved. Example: ``` if (speed < 17 && hasSpeedStripes) { diagnsotics = "You are to slow to wear speed stripes!"; return false; } ``` the validation should be separate from the dialog class (though one could argue that generating the diagnostics don't belong into the settings class either, in that case you'd need a third "controller" entity indeed. Though I usually get by without)
MFC: child dialog behavior
[ "", "c++", "visual-c++", "mfc", "dialog", "" ]
I wrote a quick and dirty logger as a jQuery plugin... ``` (function($){ $.log = function(debug) { if (console.debug) { console.debug(debug); }; }; })(jQuery); ``` It works fine in Firefox, but in IE7, I'm getting the error... > console.debug is null or not an object How do I perform a function exists in JavaScript that's compatible with IE7?
`console.debug` is specific to Firebug, which runs under Firefox. You need to check if `window.console` is available before checking for `console.log`! Here's your code reworked with no errors: ``` (function($){ $.log = function(debug) { if (window.console && console.debug) { console.debug(debug); }; }; })(jQuery); ```
Check if console is defined, then check if debug is a function: ``` if (typeof(console) != 'undefined' && typeof(console.debug) == 'function'){ //... } ```
How can I determine in JS if a function/method exists in IE7?
[ "", "javascript", "jquery", "internet-explorer-7", "" ]
From a Java application I can log a string, using a custom logging framework, as follows: ``` logger.info("Version 1.2 of the application is currently running"); ``` Therefore when a user sends me a log file I can easily see what version of the application they are running. The problem with the code above is that the version is hardcoded in the string literal and someone needs to remember to update it for every release. It's fairly inevitable that updating this string could be forgotten for a release. What I would like to do is have this string literal automatically updated based on one of the version numbers in the manifest file for the application's JAR: ``` Specification-Version: 1.2 Implementation-Version: 1.2.0.0 ``` I don't mind if this happens at compile time or at runtime as long as the version number gets into the log file.
The standard way to get that information is `SomeClass.`[`class`](http://java.sun.com/javase/6/docs/api/java/lang/Class.html)`.`[`getPackage()`](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getPackage())`.`[`getImplementationVersion()`](http://java.sun.com/javase/6/docs/api/java/lang/Package.html#getImplementationVersion()). There's no need to do any parsing on your own.
You can load the manifest at runtime using the following class ``` public class ManifestFinder { private final Class<?> _theClass; public ManifestFinder(Class<?> theClass) { _theClass = theClass; } public Manifest findManifest() throws MalformedURLException, IOException { String className = _theClass.getSimpleName(); String classFileName = className + ".class"; String pathToThisClass = _theClass.getResource(classFileName).toString(); int mark = pathToThisClass.indexOf("!"); String pathToManifest = pathToThisClass.toString().substring(0, mark + 1); pathToManifest += "/META-INF/MANIFEST.MF"; return new Manifest(new URL(pathToManifest).openStream()); } } ``` parse the data from the manifest ( untested ) ``` String specificationVersion = manifest.getMainAttributes().getValue("Implementation-Version"); ``` and then include the parsed version in the log statement ``` logger.info("Version " + specificationVersion + " of the application is currently running"); ``` See [the Jar file specification](http://java.sun.com/j2se/1.4.2/docs/guide/jar/jar.html) for more details.
In Java, how can I include dynamic version information in a log file?
[ "", "java", "logging", "manifest", "" ]
I'm wondering if PHP has a type of variable in classes that functions like static in other languages. And by that I mean all objects of the same class use the same variable and when it's updated on one it's updated on every one. Static is close because it is shared throughout all objects but I need to be able to update it. Will I have to use globals for this?
I think static is what you want. You can update a static variable, you just have to do it in a "static context" (ie. using the :: operator. ``` class Class1 { protected static $_count = 0; public function incrementCount() { return self::$_count++; } } $instance1 = new Class1(); $instance2 = new Class1(); var_dump($instance1->incrementCount(), $instance2->incrementCount()); ``` will output: int 0 int 1
The correct answer is that there is no equivalent in PHP to final, but **static** seems like what you wanted in the first place anyway. *static* has the property that it will have the same value across all instances of a class, because it is not tied to a particular instance. You will need to use the **::** operator to access it, because being static, you cannot use **->**.
What's the PHP equivalent of a static variable in other languages?
[ "", "php", "final", "" ]
What do you think of the following way to simulate a static class in java? You can add non static methods but you wouldn't be able to call them. ``` /** * Utility class: this class contains only static methods and behaves as a static class. */ // ... prevent instantiation with abstract keyword public abstract class Utilities { // ... prevent inheritance with private constructor private Utilities() {} // ... all your static methods here public static Person convert(String foo) {...} } ```
**Item 4** in [Effective Java](http://java.sun.com/docs/books/effective/) (a very... effective book) says: ``` // Noninstantiable utility class public final class Utility { private Utility() { throw new AssertionError(); } } ``` because the explicit costructor is private: * you cannot instantiate it * you cannot extend it (as if it was declared as final) The `AssertionError` isn't required but it provides another small benefit: it prevents that the costructior is accidentally invoked from within the class. You can also create a specific annotation, like @BagOfFunction, and annotate your class: ``` @BagOfFunctions public final class Utility { private Utility() { throw new AssertionError(); } } ``` basically you trade a comment for a self-documenting annotation.
That is the usual way. However, there is not need for the *abstract* keyword. Using a private constructor is sufficient because * it prevents the creation of objects (from outside the class) * it prevents inheritance The *abstract* keyword suggests the user that users of the class might implemented the class what is not the case here.
simulation of static class in java
[ "", "java", "" ]
Was thinking I could test the various answers I got in my question about an [algorithm for collapsing ranges](https://stackoverflow.com/questions/1233292/whats-a-good-generic-algorithm-for-collapsing-a-set-of-potentially-overlapping). So I was thinking I should create a method that creates a whole bunch of ranges and see how the various methods handles it. But when it comes to generating random stuff I am not very good. I created something like this: ``` private static IEnumerable<Range<int>> GenerateRanges() { var r = new Random(); var n = 10000; while(--n >= 0) { var start = r.Next(10000); var end = r.Next(10000); if (end < start) Swap(ref start, ref end); yield return Range.Create(start, end); } } ``` This creates a lot of ranges of course, but they do not give particularly interesting results since I always end up with only one range after collapsing them. How can I create more interesting ranges?
``` private static IEnumerable<Range<int>> GenerateRanges(int amount, int max, float density, int seed) { var r = new Random(seed); var commonLength = max * density / amount; // edited var maxLength = commonLength * 2; while(--amount >= 0) { var length = r.Next(maxLength); var start = r.Next(max - length); var end = start + length; yield return Range.Create(start, end); } } ``` Usage could be: `GenerateRanges(1000, 10000, 1.0, someTestSeed)` or could be: `GenerateRanges(1000, 10000, .5, someTestSeed)` for less overlaps
Make sure you also add specific tests for corner cases, like this: * Empty list of ranges * Two identical ranges * Two ranges that overlap partially * Two ranges that overlap partially, but specified in the opposite order (ie. change which one is added to the list first) * Two ranges that does not overlap, and check both ways * Two ranges that touch (ie. 1-10 and 11-20) integer-wise, but they should perhaps not be combined Problem with random tests is that typically you also have to duplicate the code that performs the calculation in the test itself, otherwise, what are you going to test against? How would you know that the random data was processed correctly, except for doing the job once more and comparing?
C#: Algorithm for creating random evenly distributed potentially overlapping ranges
[ "", "c#", "algorithm", "range", "" ]
I have a web service that contains this method: ``` [WebMethod] public static List<string> GetFileListOnWebServer() { DirectoryInfo dInfo = new DirectoryInfo(HostingEnvironment.MapPath("~/UploadedFiles/")); FileInfo[] fInfo = dInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly); List<string> listFilenames = new List<string>(fInfo.Length); for(int i = 0; i < fInfo.Length; i++) { listFilenames.Add(fInfo[i].Name); } return listFilenames; } ``` This returns a list of filenames in a folder. When i debug the application, it works fine. What I want to do, is to call this webservice method from a winform application. I added a reference to the .dll of the webservice, and this is how I call the above method: ``` private void Form1_Load(object sender, EventArgs e) { List<string> files = TestUploaderWebService.Service1.GetFileListOnWebServer(); } ``` The above code does not work - when it enters the method, the path of the web app is null, and lots of properties from HostingEnvironment class are also null. Where is my mistake, in trying to call a web service method from another winform app? Please note that the web service is made in Visual Web Developer Express, and the winform in Visual C# express; this is why I had to add the web service dll as a reference in the winform app. I do not have Visual Studio full, which would have allowed me a single solution with both projects. I am new to web services. PS - i love the formatting of text on-the-fly here :)
In visual studio, use the "Add Web Reference" feature and then enter in the URL of your web service. By adding a reference to the DLL, you not referencing it as a web service, but simply as an assembly. When you add a web reference it create a proxy class in your project that has the same or similar methods/arguments as your web service. That proxy class communicates with your web service via SOAP but hides all of the communications protocol stuff so you don't have to worry about it.
The current way to do this is by using the "Add Service Reference" command. If you specify "`TestUploaderWebService`" as the service reference name, that will generate the type `TestUploaderWebService.Service1`. That class will have a method named `GetFileListOnWebServer`, which will return an array of strings (you can change that to be a list of strings if you like). You would use it like this: ``` string[] files = null; TestUploaderWebService.Service1 proxy = null; bool success = false; try { proxy = new TestUploaderWebService.Service1(); files = proxy.GetFileListOnWebServer(); proxy.Close(); success = true; } finally { if (!success) { proxy.Abort(); } } ``` --- P.S. Tell your instructor to look at "[Microsoft: ASMX Web Services are a “Legacy Technology”](http://johnwsaundersiii.spaces.live.com/blog/cns!600A2BE4A82EA0A6!860.entry)", and ask why he's teaching out of date technology.
How to call a Web Service Method?
[ "", "c#", "winforms", "web-services", "" ]
I want to restrict access to a particular url unless the user is a member of 2 different roles. In this case I only want to grant access to this url if the user is in both the Reporting **AND** Archiving role. Is there a way to do this in ASP.net? ``` <location path="testpage.aspx"> <system.web> <authorization> <allow roles="Reporting, Archiving"/> <deny users="*"/> </authorization> </system.web> ``` I want something like this: ``` <location path="testpage.aspx"> <system.web> <authorization> <allow roles="Reporting & Archiving"/> <deny users="*"/> </authorization> </system.web> ```
It's kind of ugly, but you can inherit from the role provider you're currently using (SqlRoleProvider, WindowsTokenRoleProvider, AuthorizationStoreRoleProvider), override GetRolesForUser, call the base implementation to get the roles, and combine them as necessary there. Then obviously put your custom role provider in your web.config in the <roleManager> configuration section. You'd only need to override the one method (and maybe GetUsersInRole) and combine them as necessary. ``` public override string[] GetRolesForUser( string username ) { List<string> roles = new List<string>( base.GetRolesForUser(username) ); if( roles.Contains("Reporting") && roles.Contains("Archiving") ) { roles.Add("ReportingAndArchiving"); } return roles.ToArray(); } ```
You could create a SQL function which, given a particular user ID, page URL, and list of allowed roles (XML), returns a bit indicating whether access is granted to that URL, and subsequently use that to set a flag which would determine whether to show that as a valid choice in a javascript or DHTML menu or whatever.
Asp.Net Conditional URL Role Authentication
[ "", "c#", "asp.net", "roles", "security-roles", "" ]
I need to access motheroard identification (serial, manufacture, etc) in my application on multiple processes. *I have been able to successfully query this using WMI, but I'm looking for an alternative.* If you care to know situation: I have some application behavior that is different depending on the hardware configuration, or if a particular environment variable is set (for testing purposes). ``` bool IsVideoCardDisplay = ( getenv("Z_VI_DISPLAY") || !QueryWmiForSpecialBoard() ) ? false : true; ``` When the environment variable is set the WMI query isn't necessary--the application runs fine. However, when the environment variable is not present some of the components of my app fail to launch when is necessary to make the the WMI queries. I suspect that there may be some side effects of the WMI calls (which only a maximum of happen once per processes. This is why I'm seeking an alternative way.
Apparently there is no way to do this, which is unfortunate.
In Vista+ you can use [`GetSystemFirmwareTable`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms724379%28v=vs.85%29.aspx) API to access SMBIOS tables and parse them out to obtain [possibly available] serial numbers and other identification strings and values. In particular you can access motherboard data, including vendor and S/N: ``` Intel Corporation DZ77BH-55K AAG39018-400 BQBH206600DT ```
Access Motherboard information without using WMI
[ "", "c++", "winapi", "hardware", "wmi", "motherboard", "" ]
Here is my PHP code: ``` echo '<br />1. '.$w_time_no; echo '<br />2. '.strtotime($w_time_no); echo '<br />3. '.date('G:i', strtotime($w_time_no)); ``` That's what I get: ``` 1. 0000-00-00 22:00:00 2. 3. 2:00 ``` Why strtotime() outputs nothing by itself? Is there something wrong with server settings? Server: Apache/2.2.11 (Win32), PHP 5.2.10, MySQL client version: 5.0.51a.
`strtotime` doesn't "output" anything, btw : it returns `false` in case of an error ; see the [manual](http://php.net/strtotime) : > **Return Values** > > Returns a timestamp on success, FALSE > otherwise. Previous to PHP 5.1.0, this > function would return -1 on failure. What doesn't output anything is `echo` : `false` is considered as an empty string, and nothing get outputed. strtotime's documentation also gives the valid range for dates : > Note: The valid range of a timestamp > is typically from Fri, 13 Dec 1901 > 20:45:54 UTC to Tue, 19 Jan 2038 > 03:14:07 UTC. (These are the dates > that correspond to the minimum and > maximum values for a 32-bit signed > integer.) Additionally, not all > platforms support negative timestamps, > therefore your date range may be > limited to no earlier than the Unix > epoch. This means that e.g. dates > prior to Jan 1, 1970 will not work on > Windows, some Linux distributions, and > a few other operating systems. PHP > 5.1.0 and newer versions overcome this limitation though. `'0000-00-00'` is outside of this range, so it's not considered a valid date ; hence the `false` return value. As a sidenote, to really know what's inside a variable, you can use [`var_dump`](http://php.net/var_dump). As a bnus, used with [Xdebug](http://xdebug.org/), it'll get you a nice-formated output ;-)
0000-00-00 is not a valid date. date() gives an output because it interprets the input time as 0 and compensates for the timezone of your server, I'd assume. I'd bet that `date('Y-m-d H:i', strtotime(...))` would give 1970-01-01 2:00
PHP strtotime() outputs nothing
[ "", "php", "datetime", "strtotime", "" ]
How can I iterate over a tuple (using C++11)? I tried the following: ``` for(int i=0; i<std::tuple_size<T...>::value; ++i) std::get<i>(my_tuple).do_sth(); ``` but this doesn't work: > Error 1: sorry, unimplemented: cannot expand ‘Listener ...’ into a fixed-length argument list. > Error 2: i cannot appear in a constant expression. So, how do I correctly iterate over the elements of a tuple?
[Boost.Fusion](http://www.boost.org/libs/fusion/) is a possibility: Untested example: ``` struct DoSomething { template<typename T> void operator()(T& t) const { t.do_sth(); } }; tuple<....> t = ...; boost::fusion::for_each(t, DoSomething()); ```
I have an answer based on [Iterating over a Tuple](https://stackoverflow.com/questions/4832949/c-iterating-over-a-tuple-resolution-of-type-vs-constant-parameters): ``` #include <tuple> #include <utility> #include <iostream> template<std::size_t I = 0, typename... Tp> inline typename std::enable_if<I == sizeof...(Tp), void>::type print(std::tuple<Tp...>& t) { } template<std::size_t I = 0, typename... Tp> inline typename std::enable_if<I < sizeof...(Tp), void>::type print(std::tuple<Tp...>& t) { std::cout << std::get<I>(t) << std::endl; print<I + 1, Tp...>(t); } int main() { typedef std::tuple<int, float, double> T; T t = std::make_tuple(2, 3.14159F, 2345.678); print(t); } ``` The usual idea is to use compile time recursion. In fact, this idea is used to make a printf that is type safe as noted in the original tuple papers. This can be easily generalized into a `for_each` for tuples: ``` #include <tuple> #include <utility> template<std::size_t I = 0, typename FuncT, typename... Tp> inline typename std::enable_if<I == sizeof...(Tp), void>::type for_each(std::tuple<Tp...> &, FuncT) // Unused arguments are given no names. { } template<std::size_t I = 0, typename FuncT, typename... Tp> inline typename std::enable_if<I < sizeof...(Tp), void>::type for_each(std::tuple<Tp...>& t, FuncT f) { f(std::get<I>(t)); for_each<I + 1, FuncT, Tp...>(t, f); } ``` Though this then requires some effort to have `FuncT` represent something with the appropriate overloads for every type the tuple might contain. This works best if you know all the tuple elements will share a common base class or something similar.
How can you iterate over the elements of an std::tuple?
[ "", "c++", "c++11", "iteration", "template-meta-programming", "stdtuple", "" ]
We have large (100,000+ elements) ordered vectors of structs (operator < overloaded to provide ordering): ``` std::vector < MyType > vectorMyTypes; std::sort(vectorMyType.begin(), vectorMyType.end()); ``` My problem is that we're seeing performance problems when adding new elements to these vectors while preserving sort order. At the moment we're doing something like: ``` for ( a very large set ) { vectorMyTypes.push_back(newType); std::sort(vectorMyType.begin(), vectorMyType.end()); ... ValidateStuff(vectorMyType); // this method expects the vector to be ordered } ``` This isn't *exactly* what our code looks like since I know this example could be optimised in different ways, however it gives you an idea of how performance could be a problem because I'm sorting after every `push_back`. I think I essentially have two options to improve performance: 1. Use a (hand crafted?) *insertion sort* instead of `std::sort` to improve the sort performance (insertion sorts on a partially sorted vector are blindingly quick) 2. Create a heap by using `std::make_heap` and `std::push_heap` to maintain the sort order My questions are: * **Should I implement an insertion sort? Is there something in Boost that could help me here?** * **Should I consider using a heap? How would I do this?** --- **Edit:** Thanks for all your responses. I understand that the example I gave was far from optimal and it doesn't fully represent what I have in my code right now. It was simply there to illustrate the performance bottleneck I was experiencing - perhaps that's why this question isn't seeing many up-votes :) Many thanks to you [Steve](https://stackoverflow.com/users/13005/), it's often the simplest answers that are the best, and perhaps it was my over analysis of the problem that blinded me to perhaps the most obvious solution. I do like the neat method you outlined to insert directly into a pre-ordered vector. As I've commented, I'm constrained to using vectors right now, so std::set, std::map, etc aren't an option.
Ordered insertion doesn't need boost: ``` vectorMyTypes.insert( std::upper_bound(vectorMyTypes.begin(), vectorMyTypes.end(), newType), newType); ``` `upper_bound` provides a valid insertion point provided that the vector is sorted to start with, so as long as you only ever insert elements in their correct place, you're done. I originally said `lower_bound`, but if the vector contains multiple equal elements, then `upper_bound` selects the insertion point which requires less work. This does have to copy O(n) elements, but you say insertion sort is "blindingly fast", and this is faster. If it's not fast enough, you have to find a way to add items in batches and validate at the end, or else give up on contiguous storage and switch to a container which maintains order, such as `set` or `multiset`. A heap does not maintain order in the underlying container, but is good for a priority queue or similar, because it makes removal of the maximum element fast. You say you want to maintain the vector in order, but if you never actually iterate over the whole collection in order then you might not need it to be fully ordered, and that's when a heap is useful.
According to item 23 of Meyers' Effective STL, you should use a sorted vector if you application use its data structures in 3 phases. From the book, they are : > 1. **Setup**. Create a new data structure by inserting lots of elements into it. During this phase, almost all operation are insertions and erasure. Lookups are rare on nonexistent > 2. **Lookup**. Consult the data structure to find specific pieces of information. During this phase, almost all operations are lookups. Insertion and erasures are rare or nonexistent. There are so many lookups, the performance of this phase makes the performance of the other phases incidental. > 3. **Reorganize.** Modify the content of the data structure. perhaps by erasing all the current data and inserting new data in its place. Behaviorally, this phase is equivalent to phase 1. Once this phase is completed, the application return to phase 2 If your use of your data structure resembles this, you should use a sorted vector, and then use a binary\_search as mentionned. If not, a typical associative container should do it, that means a *set, multi-set, map or multimap* as those structure **are ordered by default**
Should use an insertion sort or construct a heap to improve performance?
[ "", "c++", "algorithm", "sorting", "stl", "boost", "" ]
I've asked this somewhere else, but the people there don't seem to understand what I am talking about. When I go to the PECL website, all extensions found there are inside TGZ files. Which is not a problem, any modern archiving program can open it. Inside is always a .tar file and inside that are the source files. So, what do I do with that? I'm particularly interested in using the pecl\_http extension, but I'm not sure what to do. Note: there are no DLL files inside the .TAR files. None whatsoever, not a single one. All you find is C code and C headers.
If there is not .dll provided, you have to compile it :-( There was a pecl4win website some time ago, but it's down ; and the new <http://windows.php.net/> does not have extensions on it yet *(there is work going on, but windows is not **the** platform of choice for PHP developpers, nor core-developpers, so it's not going really fast).* You say this : > there are no DLL files inside the .TAR > files. None whatsoever, not a single > one. All you find is C code and C > headers. Which means you will have to compile the extension yourself :-( *(maybe you'll get lucky, and find a .dll somewhere that fits your version of PHP ; some extensions, like [Xdebug](http://xdebug.org/download.php), have those on their official website, at least for recent versions of PHP... But it's not always the case :-( )* To compile a PECL extension with windows, you can take a look at these links : * [Installing a PHP extension on Windows](https://www.php.net/manual/en/install.pecl.windows.php) * [Building from source](https://www.php.net/manual/en/install.windows.building.php) * [How do I get my PECL extension compiling on Windows?](http://wiki.php.net/internals/windows/peclbuilds) Anyway... Good luck... As a sidenote : if I remember correctly, the PHP's installer for windows has some PECL extensions bundled in ; maybe this one is one of those ?
There **ARE** pecl library collections for Windows, and they're either appended (as a separate link) on PHP download page (named X.Y.Z-win32-pecl.zip or similar), or linked somehow (for example, the latest PHP5 can use PECL from the previous 5.X setup, and it says so on the download page). If all You get is source code, You will need to build these yourself. a) download PHP source code (a lot of headers required to build the libs and link them to PHP on Windows), b) download the extensions You want to build, and put them in /phpsource/src/ext/ folder, c) prepare Your favorite C/C++ IDE (I prefer to use VisualC++ 6.0 for the sole purpose of writing PHP extensions on Windows) d) make a build environ, and finally e) build ;-) Do note You will need PHP[ver]debug\_ts.lib or PHP[ver]release\_ts.lib to link them properly. Unless You're building them for PHP 4.4.4 (which I use to develop .exe apps using BamCompile - a roundabout way, but it works magic), in which case just send Your source code to me, I'll build it for You if I have time. ;-) Also chances are, the extension You're looking for **HAS** a .dll built for it already. Just take the name of the extension, and search Google for " php\_*NameOfTheExtension*.dll PHP*YourPHPVersionNumber* " and You just might find it (although a few, like php\_openAl.dll don't exist as .dll).
Can I add extensions to PHP on windows that are not DLL files?
[ "", "php", "dll", "pecl", "" ]
I understand that in a managed language like Java or C# there is this thing called a garbage collector that every once in a while checks to see if there are any object instances that are no longer referenced, and thus are completely orphaned, and clears then out of memory. But if two objects are not referenced by any variable in a program, but reference each other (like an event subscription), the garbage collector will see this reference and not clear the objects from memory. Why is this? Why can't the garbage collector figure out that neither of the objects can be reference by any active part of the running program and dispose them.
Your presumption is incorrect. If the GC 'sees' (see below) a cyclic reference of 2 or more objects (during the 'Mark' phase) but are not referenced by any other objects or permanent GC handles (strong references), those objects will be collected (during the 'Sweep' phase). An in-depth look at the CLR garbage collector can be found in [this MSDN article](http://msdn.microsoft.com/en-us/magazine/cc163316.aspx) and in [this blog post](http://vineetgupta.spaces.live.com/blog/cns!8DE4BDC896BEE1AD!1104.entry). Note: In fact, the GC doesn't even 'see' these types of objects during the *mark* phase since they are unreachable, and hence get collected during a *sweep*.
Most GCs don't work with reference counting anymore. They usually (and this is the case both in Java and .NET) work with reach-ability from the root set of objects. The root set of objects are globals and stack referenced instances. Anything reachable from that set directly or indirectly is alive. The rest of the memory is unreachable and thus prone to be collected.
Why can't the garbage collector figure out when objects referencing eachother are really orphaned
[ "", "c#", "garbage-collection", "" ]
What is Java equivalent for LINQ?
There is nothing like LINQ for Java. ... **Edit** Now with Java 8 we are introduced to the [Stream API](http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html), this is a similar kind of thing when dealing with collections, but it is not quite the same as Linq. If it is an ORM you are looking for, like Entity Framework, then you can try [Hibernate](http://hibernate.org/orm/) :-)
There is an alternate solution, [Coollection](http://github.com/19WAS85/coollection#readme). Coolection has not pretend to be the new lambda, however we're surrounded by old legacy Java projects where this lib will help. It's really simple to use and extend, covering only the most used actions of iteration over collections, like that: ``` from(people).where("name", eq("Arthur")).first(); from(people).where("age", lessThan(20)).all(); from(people).where("name", not(contains("Francine"))).all(); ```
What is the Java equivalent for LINQ?
[ "", "java", "linq", "" ]
I want to identify the country my visitors come from using php. How can I do this?
You need to use the PHP GeoIP extension that allows you to locate various information about the users via IP. <http://us.php.net/geoip> or you can use Maxmind's API to access the data aswell. <http://www.maxmind.com/app/php>
You need to use a Geolocation service/database. Check out the [Maxmind API](http://www.maxmind.com/app/php).
Identifying the country of visitor to my website
[ "", "php", "geolocation", "" ]
I would expect something like this to work but the ListItem, BeforeProperties, AfterProperties are all null/empty. I need the file name and file content. ``` public class MyItemEventReceiver : SPItemEventReceiver { public MyItemEventReceiver() {} public override void ItemAdding(SPItemEventProperties properties) { SPListItem item = properties.ListItem; bool fail = item.File.Name.Equals("fail.txt"); if (fail) { properties.ErrorMessage = "The file failed validation"; properties.Cancel = true; } } } ``` I can't use ItemAdded as it is asynchronous and I need to be synchronous, I may prevent the upload and display a message to the user. Any suggestions would be appreciated. For example, is it possible to override the Upload.aspx?
You can use the HttpContext to retrieve the HttpFileCollection which should contain the uploaded files. This will only work for individual file uploads through the web UI. Doing multiple file uploads, or saving directly from Office won't create an HttpContext. Try something like this: ``` private HttpContext context; public MyItemEventReceiver() { context = HttpContext.Current; } public override void ItemAdding(SPItemEventProperties properties) { HttpFileCollection collection = context.Request.Files; foreach (String name in collection.Keys) { if (collection[name].ContentLength > 0) { // Do what you need with collection[name].InputStream } } } ```
Notice the suffix -"adding." It's going to be null because it wasn't added yet. Try using -"added." EDIT: I believe there's an "AfterProperties rather than properties object you can grab somewhere, i'm out the door at the moment, but i'm sure you can do some digging on google to find the related method getting thrown.
How do you get file details in a SharePoint ItemEventReciever in the ItemAdding Event?
[ "", "c#", "sharepoint", "validation", "events", "sharepointdocumentlibrary", "" ]
Ive got some in memory images in various simple formats, which I need to quickly convert to another format. In cases where the target format contains an alpha channel but the source does not, alpha should be taken as its full value (eg 0xFF for an 8bit target alpha channel). I need to be able to deal with various formats, such as A8R8G8B8, R8G8B8A8, A1R4G4B4, R5G6B5, etc. Conversion of pixels between any of these formats is simple, however I don't want to have to manually code every single combination, I also don't want to have a 2 pass solution of converting to a common format (eg A8R8G8B8) before converting again to the final format both for performance reasons, and that if I want to use a higher definition format, say A16B16G16R16 or a floating point I'd either loose some data converting to the intermediate format, or have to rewrite everything to use a different higher definition format... Ideally id like some sort of enum with values for each format, and then a single method to convert, eg say ``` enum ImageFormat { FMT_A8R8G8B8,//32bit FMT_A1R4G4B4,//16bit FMT_R5G6B5,//16bit FMT_A32R32G32B32F,//128bit floating point format ... }; struct Image { ImageFormat Format; size_t Width, Height; size_t Pitch; void *Data; }; Image *ConvertImage(ImageFormat *targetFormat, const Image *sourceImage); ```
You might want `boost::gil`.
Take a look at [FreeImage](http://freeimage.sourceforge.net/); it's a library that will convert between various images. You can also try [ImageMagick](http://www.imagemagick.org/script/index.php) to just convert back and forth, if you don't want to do anything to them.
C++ Fast way to convert between image formats
[ "", "c++", "image-processing", "" ]
After reading (yet another) [post](https://blog.codinghorror.com/the-wrong-level-of-abstraction/) by [Jeff Atwood](http://en.wikipedia.org/wiki/Jeff_Atwood) more or less concluding that us mortal developers shouldn't be getting too involved with encryption, I'm left wondering what library I should be using. The only two libraries I've found that seem legitimate are entlib's and [Bouncy Castle](https://en.wikipedia.org/wiki/Bouncy_Castle_%28cryptography%29), but they don't seem much more of an abstraction than the .NET cryptography APIs to me. I guess what I'm wondering is if there is a "jQuery of cryptography libraries" that is simple, widely-trusted, open and well-documented.
**edit:** Here is a comprehensive list of popular crypto libraries from <https://github.com/quozd/awesome-dotnet/blob/master/README.md#cryptography>: * [BouncyCastle](https://bouncycastle.org/) - Together with the .Net System.Security.Cryptography, the reference implementation for cryptographic algorithms on the CLR. * [HashLib](http://hashlib.codeplex.com/) - HashLib is a collection of nearly all hash algorithms you've ever seen, it supports almost everything and is very easy to use * [libsodium-net](https://github.com/adamcaudill/libsodium-net) - libsodium for .NET - A secure cryptographic library * [Pkcs11Interop](https://github.com/Pkcs11Interop/Pkcs11Interop) - Managed .NET wrapper for unmanaged PKCS#11 libraries that provide access to the cryptographic hardware * [StreamCryptor](https://github.com/bitbeans/StreamCryptor) - Stream encryption & decryption with libsodium and protobuf * [SecurityDriven.Inferno](https://github.com/sdrapkin/SecurityDriven.Inferno) - .NET crypto library. Professionally audited. Original answer follows. --- The Bouncy Castle library is indeed a well respected, and mature encryption library, but what's wrong with using many of the fantastic encryption functions that are built right into the .NET framework? [System.Security.Cryptography Namespace](http://msdn.microsoft.com/en-us/library/system.security.cryptography.aspx) In my experience, these implementations are rock-solid, provide numerous options (for example: you've usually got a [Crypto API](http://en.wikipedia.org/wiki/Cryptographic_API), [CNG](http://en.wikipedia.org/wiki/Cryptography_API:_Next_Generation) and Managed implementations of each algorithm to choose from) , and you're not going to "get it wrong", since you're only *using* the implementation. If you're slightly worried that you might *use* them incorrectly, you can always follow [MSDN's own example code](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx).
You have completely misunderstood the maxim "do not implement encryption routines yourself". What this means is: do not roll your own RSA/DSA/whatever encryption algorithm. It doesn't mean that you shouldn't use one written by someone who knows what they are doing. In fact, if anything, adding more layers between you and the trusted algorithm is going to hurt you, and not the reverse.
Recommended .NET encryption library
[ "", "c#", ".net", "encryption", "" ]
That: ``` {{ wpis.entry.lastChangeDate|date:"D d M Y" }} ``` gives me (why?): ``` 2009-07-24 21:45:38.986156 ``` And, I don't know how to skip fraction part... In my model, I have: ``` addedDate = models.DateTimeField(default=datetime.now) ```
You can use this: `addedDate = datetime.now().replace(microsecond=0)`
This is exactly what you want. Try this: ``` {{ wpis.entry.lastChangeDate|date:'Y-m-d H:i' }} ```
How to format dateTime in django template?
[ "", "python", "django", "django-models", "django-templates", "datetime-format", "" ]
I have a nested repeater control that displays a list of data, in my case it is an FAQ list. here is the design portion: ``` <asp:Repeater ID="lists" runat="server"> <ItemTemplate> <h2 class="sf_listTitle"><asp:Literal ID="listTitle" runat="server"></asp:Literal></h2> <p class="sf_controlListItems"> <a id="expandAll" runat="server"> <asp:Literal ID="Literal1" runat="server" Text="<%$Resources:ExpandAll %>"></asp:Literal> </a> <a id="collapseAll" runat="server" style="display:none;"> <asp:Literal ID="Literal2" runat="server" Text="<%$Resources:CollapseAll %>"></asp:Literal> </a> </p> <ul class="sf_expandableList" id="expandableList" runat="server"> <asp:Repeater ID="listItems" runat="server"> <HeaderTemplate> </HeaderTemplate> <ItemTemplate> <li> <h1 id="headlineContainer" runat="server" class="sf_listItemTitle"> <a id="headline" runat="server" title="<%$Resources:ClickToExpand %>"></a> </h1> <div id="contentContainer" runat="server" class="sf_listItemBody" style="display:none;"> <asp:Literal ID="content" runat="server"></asp:Literal> </div> </li> </ItemTemplate> <FooterTemplate> </FooterTemplate> </asp:Repeater> </ul> </ItemTemplate> </asp:Repeater> ``` The repeater that I am interested in is the second repeater, `listItems`. In my code-behind, I cannot directly call `listItems` and see the controls inside of it. I tried to grab the control inside of `list.DataBinding` (maybe I need to use a different event?) method: ``` void lists_ItemDataBound(object sender, RepeaterItemEventArgs e) { var oRepeater = (Repeater) lists.FindControl("listItems"); } ``` but this comes up as `null`. Can anyone give me some pointers/tips of what I need to do to gain access to the `listItems` repeater and it's children controls? Thanks!
``` lists ``` belongs to each RepeaterItem, not directly to the Repeater itself. Try :- ``` void lists_ItemDataBound(object sender, RepeaterItemEventArgs e) { if ( e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item ) { Repeater oRepeater = (Repeater)e.Item.FindControl("listItems"); // And to get the stuff inside. foreach ( RepeaterItem myItem in oRepeater.Items ) { if ( myItem.Item.ItemType == ListItemType.AlternatingItem || myItem.Item.ItemType == ListItemType.Item ) { Literal myContent = (Literal)myItem.FindControl("content"); // Do Something Good! myContent.Text = "Huzzah!"; } } } } ``` And you should be good :) Edited to incorporate DavidP's helpful refinement.
You need to change that line to ``` var oRepeater = (Repeater) e.Item.FindControl("listItems"); ```
Change value of databound control within Repeaters in C#
[ "", "c#", "asp.net", "data-binding", "repeater", "" ]
I'm working on a Python web application in which I have some small modules that serve very specific functions: `session.py`, `logger.py`, `database.py`, etc. And by "small" I really do mean small; each of these files currently includes around 3-5 lines of code, or maybe up to 10 at most. I might have a few imports and a class definition or two in each. I'm wondering, is there any reason I should or shouldn't merge these into one module, something like `misc.py`? My thoughts are that having separate modules helps with code clarity, and later on, if by some chance these modules grow to more than 10 lines, I won't feel so bad about having them separated. But on the other hand, it just seems like such a waste to have a bunch of files with only a few lines in each! And is there any significant difference in resource usage between the multi-file vs. single-file approach? (Of course I'm nowhere near the point where I should be worrying about resource usage, but I couldn't resist asking...) I checked around to see whether this had been asked before and didn't see anything specific to Python, but if it's in fact a duplicate, I'd appreciate being pointed in the right direction.
> My thoughts are that having separate > modules helps with code clarity, and > later on, if by some chance these > modules grow to more than 10 lines, I > won't feel so bad about having them > separated. This. Keep it the way you have it.
As a user of modules, I greatly prefer when I can include the entire module via a single import. Don't make a user of your package do multiple imports unless there's some reason to allow for importing different alternates. BTW, there's no reason a single modules can't consist of multiple source files. The simplest case is to use an [\_\_init\_\_.py](http://docs.python.org/tutorial/modules.html#packages) file to simply load all the other code into the module's namespace.
Python: prefer several small modules or one larger module?
[ "", "python", "refactoring", "module", "" ]
I am developing under Windows, and using Eclipse with CDT to develop C++ applications. Now, for build management I can create a normal **C++ project** and Eclipse will completely manage the build (calling the g++ compiler with proper arguments), or I can create a **Managed Make C++ project** and Eclipse will manage the Makefile then call make on that Makefile (when building the project) which in turn will complete the build process. Is there any advantage of using one of these approaches and not the other? **EDIT**: I am not talking about Managed Make vs Standard Make, rather I am talking about Make vs Eclipse. Yesterday I tried compiling a C++ project under eclipse on a system that doesn't include Make at all, and the project compiled fine, meaning that eclipse can manage the build completely on it's own, which bring the original question into focus: do I need Make?; I can use eclipse alone. That's my question...
One consideration is, do you want to **require** that developers who work with your project must install and use Eclipse? It's not a value judgement about Eclipse, rather an assumption as to your audience and how familiar they are with your chosen tool. If a C++ programmer is familiar with Java/Eclipse it may not be a problem. If they aren't familiar with Eclipse, they are going to see Eclipse as an obstacle to getting their work done. You need to pay attention to your instructions for putting together a build environment from scratch AND keep it updated. You know developers, There will be some C++ die-hards who will curse your decision and rant about how you should have just done it with Make instead of making (heh) them install a whole new platform just to do a build.
I'm not sure if you would have this option in the **C++ project**, but with the **Managed Make C++ project** you would be able to call the makefile directly from a command line environment (provided you have mapped the make executable into your path). I would consider this to be a real asset - especially when it comes to automated build scripts and user who are more CLI-centric. Also - don't forget that writing your own makefile is an option with the CDT. If you have specific requirements you can write your own make and linker files and Eclipse will bind it's build targets to that makefile.
Build Managment: Eclipse project vs Eclipse Managed Make project
[ "", "c++", "build", "mingw", "eclipse-cdt", "" ]
also how can you tell if it is running, enabled/disabled, etc.?
There is a [Task Scheduler API](http://msdn.microsoft.com/en-us/library/aa383614(VS.85).aspx) that you can use to access information about tasks. (It is a com library, but you can call it from C# using pinvokes) There is an [article on codeproject](http://www.codeproject.com/KB/cs/tsnewlib.aspx) that provides a .net wrapper for the API. [There is also the [schtasks](http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/schtasks.mspx) command - [more info](http://msdn.microsoft.com/en-us/library/bb736357(VS.85).aspx)]
The API can be installed [via NuGet](https://www.nuget.org/packages/TaskScheduler). The package name is 'TaskScheduler'. (<https://github.com/dahall/taskscheduler>) The following example shows how you can test whether a task is installed using its name and if not install it with an hourly execution. ``` using (TaskService service = new TaskService()) { if (!service.RootFolder.AllTasks.Any(t => t.Name == "YourScheduledTaskName")) { Console.WriteLine("YourScheduledTaskName is not installed on this system. Do you want to install it now? (y/n)"); var answer = Console.ReadLine(); if (answer == "y") { var task = service.NewTask(); task.RegistrationInfo.Description = "YourScheduledTaskDescription"; task.RegistrationInfo.Author = "YourAuthorName"; var hourlyTrigger = new DailyTrigger { StartBoundary = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 1, 0 , 0) }; hourlyTrigger.Repetition.Interval = TimeSpan.FromHours(1); task.Triggers.Add(hourlyTrigger); var taskExecutablePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "YourScheduledTaskName.exe"); task.Actions.Add(new ExecAction(taskExecutablePath)); service.RootFolder.RegisterTaskDefinition("YourScheduledTaskName", task); } } } ```
How do you verify that a scheduled task exists on a server using C#?
[ "", "c#", ".net", "scheduled-tasks", "" ]
I've download the [Refresh template by Styleshout.com](http://www.styleshout.com/templates/preview/Refresh1-0/index.html) since I really like it. But unfortunately, there was no drop down menu in it, only a normal menu. So I tried to integrate a drop down menu [which I found a nice tutorial for](http://www.htmldog.com/articles/suckerfish/dropdowns/). It does almost work - almost. Here's the result: [the template on my webspace](http://wp1080088.wp029.webpack.hosteurope.de/Refresh1-1/). The menus are opened - but at the wrong location. Why? What's wrong with my implementation? All 3 drop down lists are opened under the first item. I hope you can help me. Thanks in advance! PS: Here's the code: ``` #################### ####### HTML ####### #################### <ul id="nav"> <li><a href="index.html">Nav #1</a> <ul> <li><a href="#">Nav #1.1</a></li> <li><a href="#">Nav #1.2</a></li> </ul> </li> <li><a href="index.html">Nav #2</a> <ul> <li><a href="#">Nav #2.1</a></li> <li><a href="#">Nav #2.2</a></li> </ul> </li> <li><a href="index.html">Nav #3</a> <ul> <li><a href="#">Nav #3.1</a></li> <li><a href="#">Nav #3.2</a></li> </ul> </li> </ul> #################### #### JAVASCRIPT #### #################### sfHover = function() { var sfEls = document.getElementById("nav").getElementsByTagName("LI"); for (var i=0; i<sfEls.length; i++) { sfEls[i].onmouseover=function() { this.className+=" sfhover"; } sfEls[i].onmouseout=function() { this.className=this.className.replace(new RegExp(" sfhover\\b"), ""); } } } if (window.attachEvent) window.attachEvent("onload", sfHover); ################### ####### CSS ####### ################### ul#nav li ul { position: absolute; left: -9999px; top: 38px; display: block; width: 100px; background-color: transparent; } ul#nav li { position: relative; } ul#nav li ul li { float: none; } /* Links in the drop down lists start */ ul#nav li ul li a { clear: left; display: block; text-decoration: none; width: 100px; background-color: #333; } /* Links in the drop down lists end */ /* Making visible start */ ul#nav li:hover ul, #nav li.sfhover ul { left: auto; } /* Making visible end */ ```
You need to float the container LI's left and set the 'top' value on the pop-up boxes to 100%. (Tested only in FF3.5) ``` ul#nav li { position: relative; float: left; } ul#nav li ul { position: absolute; left: -9999px; top: 100%; display: block; width: 100px; background-color: transparent; } ```
I think the reason it's only working in Firefox, or I should say was only working in Firefox since this was posted so long ago, is that IE might need specific pixel locations for the top attribute instead of 100%. I would recommend trying 0px at least for IE, this worked for me recently at least.
Why doesn't this drop down menu work?
[ "", "javascript", "html", "css", "drop-down-menu", "" ]
I've developped a DLL for a driver in C. I wrote a test program in C++ and the DLL works fine. Now I'd like to interract with this DLL using Python. I've successfully hidden most of the user defined C structures but there is one point where I have to use C structures. I'm rather new to python so I may get things wrong. My approach is to redefine a few structures in python using ctype then pass the variable to my DLL. However in these class I have a custom linked list which contains recursive types as follow ``` class EthercatDatagram(Structure): _fields_ = [("header", EthercatDatagramHeader), ("packet_data_length", c_int), ("packet_data", c_char_p), ("work_count", c_ushort), ("next_command", EthercatDatagram)] ``` This fails, because inside EthercatDatagram, EthercatDatagram is not already defined so the parser returns an error. How should I represent this linked list in python so that my DLL understands it correctly?
You almost certainly want to declare next\_command as a pointer. Having a structure that contains itself isn't possible (in any language). I think this is what you want: ``` class EthercatDatagram(Structure): pass EthercatDatagram._fields_ = [ ("header", EthercatDatagramHeader), ("packet_data_length", c_int), ("packet_data", c_char_p), ("work_count", c_ushort), ("next_command", POINTER(EthercatDatagram))] ```
The reason why ``` EthercatDatagram._fields_.append(("next_command", EthercatDatagram)) ``` does not work is that the machinery that creates the descriptor objects (see the source of the [`PyCStructType_setattro`](http://hg.python.org/cpython/file/tip/Modules/_ctypes/_ctypes.c) function) for accessing the `next_command` attribute is activated *only upon assignment* to the `_fields_` attribute of the class. Merely appending the new field to the list goes completely unnoticed. To avoid this pitfall, use always a tuple (and not a list) as the value of the `_fields_` attribute: that will make it clear that you have to assign a new value to the attribute and not modify it in place.
python ctype recursive structures
[ "", "python", "dll", "recursion", "structure", "ctypes", "" ]
A lot of C++ code uses syntactical conventions for marking up data members. Common examples include * `m_memberName` for public members (where public members are used at all) * `_memberName` for private members or all members Others try to enforce using `this->member` whenever a data member is used. In my experience, most larger code bases fail at applying such rules consistently. In other languages, these conventions are far less widespread. I see it only occasionally in Java or C# code. I think I have never seen it in Ruby or Python code. Thus, there seems to be a trend with more modern languages to not use special markup for data members. Is this convention still useful today in C++ or is it just an anachronism, especially as it is used so inconsistently across libraries? Haven't the other languages shown that one can do without member prefixes?
You have to be careful with using a leading underscore. A leading underscore before a capital letter in a word is reserved. For example: \_Foo \_L are all reserved words while \_foo \_l are not. There are other situations where leading underscores before lowercase letters are not allowed. In my specific case, I found the \_L happened to be reserved by Visual C++ 2005 and the clash created some unexpected results. I am on the fence about how useful it is to mark up local variables. Here is a link about which identifiers are reserved: [What are the rules about using an underscore in a C++ identifier?](https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier)
I'm all in favour of **prefixes done well**. I think (System) Hungarian notation is responsible for most of the "bad rap" that prefixes get. This notation is largely pointless in strongly typed languages e.g. in C++ "lpsz" to tell you that your string is a long pointer to a nul terminated string, when: segmented architecture is ancient history, C++ strings are by common convention pointers to nul-terminated char arrays, and it's not really all that difficult to know that "customerName" is a string! However, I do use prefixes to specify the *usage* of a variable (essentially "Apps Hungarian", although I prefer to avoid the term Hungarian due to it having a bad and unfair association with System Hungarian), and this is a very handy **timesaving** and **bug-reducing** approach. I use: * m for members * c for constants/readonlys * p for pointer (and pp for pointer to pointer) * v for volatile * s for static * i for indexes and iterators * e for events Where I wish to make the *type* clear, I use standard suffixes (e.g. List, ComboBox, etc). This makes the programmer aware of the *usage* of the variable whenever they see/use it. Arguably the most important case is "p" for pointer (because the usage changes from var. to var-> and you have to be much more careful with pointers - NULLs, pointer arithmetic, etc), but all the others are very handy. For example, you can use the same variable name in multiple ways in a single function: (here a C++ example, but it applies equally to many languages) ``` MyClass::MyClass(int numItems) { mNumItems = numItems; for (int iItem = 0; iItem < mNumItems; iItem++) { Item *pItem = new Item(); itemList[iItem] = pItem; } } ``` You can see here: * No confusion between member and parameter * No confusion between index/iterator and items * Use of a set of clearly related variables (item list, pointer, and index) that avoid the many pitfalls of generic (vague) names like "count", "index". * Prefixes reduce typing (shorter, and work better with auto-completion) than alternatives like "itemIndex" and "itemPtr" Another great point of "iName" iterators is that I never index an array with the wrong index, and if I copy a loop inside another loop I don't have to refactor one of the loop index variables. Compare this unrealistically simple example: ``` for (int i = 0; i < 100; i++) for (int j = 0; j < 5; j++) list[i].score += other[j].score; ``` (which is hard to read and often leads to use of "i" where "j" was intended) with: ``` for (int iCompany = 0; iCompany < numCompanies; iCompany++) for (int iUser = 0; iUser < numUsers; iUser++) companyList[iCompany].score += userList[iUser].score; ``` (which is much more readable, and removes all confusion over indexing. With auto-complete in modern IDEs, this is also quick and easy to type) The next benefit is that code snippets *don't require any context* to be understood. I can copy two lines of code into an email or a document, and anyone reading that snippet can tell the difference between all the members, constants, pointers, indexes, etc. I don't have to add "oh, and be careful because 'data' is a pointer to a pointer", because it's called 'ppData'. And for the same reason, I don't have to move my eyes out of a line of code in order to understand it. I don't have to search through the code to find if 'data' is a local, parameter, member, or constant. I don't have to move my hand to the mouse so I can hover the pointer over 'data' and then wait for a tooltip (that sometimes never appears) to pop up. So programmers can read and understand the code *significantly* faster, because they don't waste time searching up and down or waiting. > *(If you don't think you waste time searching up and down to work stuff out, find some code you wrote a year ago and haven't looked at > since. Open the file and jump about half way down without reading it. > See how far you can read from this point before you don't know if > something is a member, parameter or local. Now jump to another random > location... This is what we all do all day long when we are single > stepping through someone else's code or trying to understand how to > call their function)* The 'm' prefix also avoids the (IMHO) ugly and wordy "this->" notation, and the inconsistency that it guarantees (even if you are careful you'll usually end up with a mixture of 'this->data' and 'data' in the same class, because nothing enforces a consistent spelling of the name). 'this' notation is intended to resolve *ambiguity* - but why would anyone deliberately write code that can be ambiguous? Ambiguity *will* lead to a bug sooner or later. And in some languages 'this' can't be used for static members, so you have to introduce 'special cases' in your coding style. I prefer to have a single simple coding rule that applies everywhere - explicit, unambiguous and consistent. The last major benefit is with Intellisense and auto-completion. Try using Intellisense on a Windows Form to find an event - you have to scroll through hundreds of mysterious base class methods that you will never need to call to find the events. But if every event had an "e" prefix, they would automatically be listed in a group under "e". Thus, prefixing works to group the members, consts, events, etc in the intellisense list, making it much quicker and easier to find the names you want. (Usually, a method might have around 20-50 values (locals, params, members, consts, events) that are accessible in its scope. But after typing the prefix (I want to use an index now, so I type 'i...'), I am presented with only 2-5 auto-complete options. The 'extra typing' people attribute to prefixes and meaningful names drastically reduces the search space and measurably accelerates development speed) I'm a lazy programmer, and the above convention saves me a lot of work. I can code faster and I make far fewer mistakes because I know how every variable should be used. --- **Arguments against** So, what are the cons? Typical arguments against prefixes are: * *"Prefix schemes are bad/evil"*. I agree that "m\_lpsz" and its ilk are poorly thought out and wholly useless. That's why I'd advise using a well designed notation designed to support your requirements, rather than copying something that is inappropriate for your context. (Use the right tool for the job). * *"If I change the usage of something I have to rename it"*. Yes, of course you do, that's what refactoring is all about, and why IDEs have refactoring tools to do this job quickly and painlessly. Even without prefixes, changing the usage of a variable almost certainly means its name *ought* to be changed. * *"Prefixes just confuse me"*. As does every tool until you learn how to use it. Once your brain has become used to the naming patterns, it will filter the information out automatically and you won't really mind that the prefixes are there any more. But you have to use a scheme like this solidly for a week or two before you'll really become "fluent". And that's when a lot of people look at old code and start to wonder how they ever managed *without* a good prefix scheme. * *"I can just look at the code to work this stuff out"*. Yes, but you don't need to waste time looking elsewhere in the code or remembering every little detail of it when the answer is right on the spot your eye is already focussed on. * *(Some of) that information can be found by just waiting for a tooltip to pop up on my variable*. Yes. Where supported, for some types of prefix, when your code compiles cleanly, after a wait, you can read through a description and find the information the prefix would have conveyed instantly. I feel that the prefix is a simpler, more reliable and more efficient approach. * *"It's more typing"*. Really? One whole character more? Or is it - with IDE auto-completion tools, it will often reduce typing, because each prefix character narrows the search space significantly. Press "e" and the three events in your class pop up in intellisense. Press "c" and the five constants are listed. * *"I can use `this->` instead of `m`"*. Well, yes, you can. But that's just a much uglier and more verbose prefix! Only it carries a far greater risk (especially in teams) because to the compiler it is *optional*, and therefore its usage is frequently inconsistent. `m` on the other hand is brief, clear, explicit and not optional, so it's much harder to make mistakes using it.
Why use prefixes like m_ on data members in C++ classes?
[ "", "c++", "class", "coding-style", "naming-conventions", "" ]
> **Possible Duplicate:** > [In PHP (>= 5.0), is passing by reference faster?](https://stackoverflow.com/questions/178328/in-php-5-0-is-passing-by-reference-faster) I wonder if by declaring the parameter pass by reference, the PHP interpreter will be faster for not having to copy the string to the function's local scope? The script turns XML files into CSVs, which have thousands of records, so little time optimizations count. Would this: ``` function escapeCSV( & $string ) { $string = str_replace( '"', '""', $string ); // escape every " with "" if( strpos( $string, ',' ) !== false ) $string = '"'.$string.'"'; // if a field has a comma, enclose it with dobule quotes return $string; } ``` Be faster than this: ``` function escapeCSV( $string ) { $string = str_replace( '"', '""', $string ); // escape every " with "" if( strpos( $string, ',' ) !== false ) $string = '"'.$string.'"'; // if a field has a comma, enclose it with dobule quotes return $string; } ``` ?
**Don't think, profile**. Run scripts that use each version of the function for 100,000 repetitions under, say, the Unix `time` command. Do not philosophize about what is faster; find out.
[PHP references are not pointers](http://www.php.net/manual/en/language.references.arent.php). They do not speed anything up - In fact they do the contrary, since they require an additional internal entry in the symbol table.
passing a string by reference to a function would speed things up? (php)
[ "", "php", "optimization", "function", "pass-by-reference", "premature-optimization", "" ]
I have an XML document that looks like this: ``` <Data xmlns="http://www.domain.com/schema/data" xmlns:dmd="http://www.domain.com/schema/data-metadata" > <Something>...</Something> </Data> ``` I am parsing the information using SimpleXML in PHP. I am dealing with arrays and I seem to be having a problem with the namespace. My question is: How do I remove those namespaces? I read the data from an XML file. Thank you!
If you're using XPath then it's a limitation with XPath and **not** PHP look at this explanation on [xpath and default namespaces](http://www.edankert.com/defaultnamespaces.html) for more info. More specifically its the `xmlns=""` attribute in the root node which is causing the problem. This means that you'll need to register the namespace then use a [QName](http://en.wikipedia.org/wiki/QName) thereafter to refer to elements. ``` $feed = simplexml_load_file('http://www.sitepoint.com/recent.rdf'); $feed->registerXPathNamespace("a", "http://www.domain.com/schema/data"); $result = $feed->xpath("a:Data/a:Something/..."); ``` **Important**: The URI used in the `registerXPathNamespace` call must be identical to the one that is used in the actual XML file.
I found the answer above to be helpful, but it didn't quite work for me. This ended up working better: ``` // Gets rid of all namespace definitions $xml_string = preg_replace('/xmlns[^=]*="[^"]*"/i', '', $xml_string); // Gets rid of all namespace references $xml_string = preg_replace('/[a-zA-Z]+:([a-zA-Z]+[=>])/', '$1', $xml_string); ```
Remove namespace from XML using PHP
[ "", "php", "simplexml", "xml-namespaces", "" ]
Somehow this is the first time I've ever encountered this problem in many years of programming, and I'm not sure what the options are for handling it. I am in the process of porting an application to Linux, and there is a header file in one of the directories that apparently has the same name as a header file in the standard C library, and when "cstdlib" is included from another file in that directory, it's trying to include the local file rather than the correct one from the standard library. In particular, the file is named "endian.h", which is trying to be included from /usr/include/bits/waitstatus.h. So instead of including /usr/include/bits/endian.h it is trying to include ./endian.h. makes no difference Is my only option to rename the endian.h in the project to something else, or is there a way that I can force the compiler to look in the same directory as the file that it's being included from first? --- Edit: Okay it was just a stupid mistake on my part. My Makefile was setting -I. , so it was looking in the current directory first. D'oh.
There is an important difference between: ``` #include "endian.h" // Look in current directory first. ``` And ``` #include <endian.h> // Look in the standard search paths. ``` If you want the one in the current directory, use the quotes. If you want the system one, then use the angle brackets. Note that if you have put the current directory in the include path via the "-I" flag, then both might resolve to the one in the current directory, in which case you shouldn't use "-I" with the current directory.
If you include the file with "" instead of <>, the header should be first looked in the same directory as the file including it. But if possible, renaming the file is much better IMHO: it will avoid problems if files are moved, when you change your build system, etc... The "" vs <> is compiler dependent, also (it is NOT mandated by the C standard to behave as g++ does).
Question about include directory order in g++
[ "", "c++", "g++", "" ]
I've written a simple shell-like program that uses readline in order to provide smart completion of arguments. I would like the mechanism to support arguments that have spaces and are quoted to signify as one argument (as with providing the shell with such). I've seen that shlex.split() knows how to parse quoted arguments, but in case a user wants to complete mid-typing it fails (for example: 'complete "Hello ' would cause an exception to be thrown when passed to shlex, because of unbalanced quotes). Is there code for doing this? Thanks!
I don't know of any existing code for the task, but if I were to do this I'd catch the exception, try adding a fake trailing quote, and see how shlex.split does with the string thus modified.
GNU Readline allows for that scenario with the variable `rl_completer_quote_characters`. Unfortunatelly, Python does not export that option on the standard library's `readline` module (even on 3.7.1, the latest as of this writing). I found a way of doing that with `ctypes`, though: ``` import ctypes libreadline = ctypes.CDLL ("libreadline.so.6") rl_completer_quote_characters = ctypes.c_char_p.in_dll ( libreadline, "rl_completer_quote_characters" ) rl_completer_quote_characters.value = '"' ``` Note this is clearly not portable (possibly even between Linux distros, as the libreadline version is hardcoded, but I didn't have plain `libreadline.so` on my computer), so you may have to adapt it for your environment. Also, in my case, I set only double quotes as special for the completion feature, as that was my use case. **References** * <https://robots.thoughtbot.com/tab-completion-in-gnu-readline#adding-quoting-support> * @eryksun's comment on [how to set data to a global variable in a shared library using python](https://stackoverflow.com/questions/34214677/how-to-set-data-to-a-global-variable-in-a-shared-library-using-python)
Handling lines with quotes using python's readline
[ "", "python", "readline", "" ]
Why does this give me parse error? going crazy over here.. I have this file right: ``` function start_connection() { global $config['db_host']; } ``` Parse error: parse error, expecting `','' or`';'' in functions.php on line 5
You can't global an array within a variable. Only the variable.
when declaring the global variable do not include the array key, so: ``` global $config; ``` this will provide access to all key => value pairs within $config array within the function start\_connection().
Cannot understand this php parser error
[ "", "php", "" ]
I am starting a new project, and I am considering using alias data types in my SQL Server 2005 database, for common table columns. For e.g. I would define an alias data type to hold the name of an object, as follows: > CREATE TYPE adt\_Name FROM > varchar(100) not null Then use it for the definition of table columns, ensuring all my columns share the exact same definition (length, nullability, precision, etc). 1. What are the advantages of using alias data types? 2. What are the disadvantages of using alias data types? 3. What naming conventions would you recommend? I was thinking adt\_Xxx (adt = alias data type). 4. Why does SQL Server 2005 Management Studio not allow me to work with alias data types from the GUI. I can only use them through SQL Scripts. The GUI doesn't list them in any of the drop-down boxes - its frustrating. 5. How will the use of alias data types affect my Linq to SQL model?
**Advantages:** * Reusable and Sharable, the ADT is reusable within the database it's created in, if you want it across all your DBs then create it in the model database * Enforcement, the ADT will enforce the characteristics, length and nullability of it's base type, and can be used to enforce development standards * Disallows implicit conversions, ADTs cannot be CAST or CONVERTed * Simplicity, as with other languages, ADTs lend simplicity to development and maintenance * Data Hiding **Disadvantages:** * Unmodifiable, ADTs cannot be directly modified, you must DROP and reCREATE them. Note that you can still ALTER the tables they're in to another base type or ADT, then DROP and reCREATE them, then ALTER the tables back (or just CREATE a new one to alter them to). * No Tools, ADTs must be created with a direct query using the CREATE statement (sp\_addtype is deprecated and shouldn't be used). * Table variables are not supported **Naming Conventions:** * 'adt\_' looks like it will work just fine **Linq to SQL:** * Treat these types as either the base type in your querys, or create the corresponding type to use
I would advise against it. I support some customers who have products that use them and they are a constant PITA (pain-in-the-ankle). In particular, you cannot use them in #temp tables unless you also define them in TempDB. And as TempDB gets reset every time you restart SQL Server, that means that you also have to redefine them every time that you restart SQL Server. But that means a startup procedure which must be in Master and has certain privs. And since the Alias definitions (really UDT's in Ms terminology) might change, that means that the DBA has to give someone else the rights to edit that procedure which could be a security issue. Oh, and lest I forget, if you have to upgrade, migrate or reinstall your server, you'll need an external copy of that proc to re-add to Master and you'll need to remember to do that. And then there's the limitations: in my experience developers want to use these "Alias's" because they think that it will give them the flexibility to change the definition later on if they need to. It won't. Persistent data is NOT like persistent code, it doesn't have that kind of flexibility and SQL Server isn't going to help you much at all here. After you try to do this once, you'll quickly conclude that you never should have used the darn things in the first place.
SQL alias data types
[ "", "sql", "sql-server", "sql-server-2005", "alias-data-type", "" ]
If you have an Interface `IFoo` and a class `Bar : IFoo`, why can you do the following: ``` List<IFoo> foo = new List<IFoo>(); foo.Add(new Bar()); ``` But you cannot do: ``` List<IFoo> foo = new List<Bar>(); ```
At a casual glance, it appears that this *should* (as in beer *should* be free) work. However, a quick sanity check shows us why it can't. Bear in mind that the following code **will not compile**. It's intended to show why it isn't allowed to, even though it *looks* alright up until a point. ``` public interface IFoo { } public class Bar : IFoo { } public class Zed : IFoo { } //..... List<IFoo> myList = new List<Bar>(); // makes sense so far myList.Add(new Bar()); // OK, since Bar implements IFoo myList.Add(new Zed()); // aaah! Now we see why. //..... ``` `myList` is a `List<IFoo>`, meaning it can take any instance of `IFoo`. However, this conflicts with the fact that it was instantiated as `List<Bar>`. Since having a `List<IFoo>` means that I could add a new instance of `Zed`, we can't allow that since the underlying list is actually `List<Bar>`, which can't accommodate a `Zed`.
The reason is that C# does not support co- and contravariance for generics in C# 3.0 or earlier releases. This is being implemented in C# 4.0, so you'll be able to do the following: ``` IEnumerable<IFoo> foo = new List<Bar>(); ``` Note that in C# 4.0, you can cast to IEnumerable<IFoo>, but you won't be be able cast to List<IFoo>. The reason is due to type safety, if you were able to cast a List<Bar> to List<IFoo> you would be able to add other IFoo implementors to the list, breaking type safety. For more background on covariance and contravariance in C#, Eric Lippert has a [nice blog series](http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx).
C# List<Interface>: why you cannot do `List<IFoo> foo = new List<Bar>();`
[ "", "c#", "generics", "" ]
I have three lists, the first is a list of names, the second is a list of dictionaries, and the third is a list of data. Each position in a list corresponds with the same positions in the other lists. List\_1[0] has corresponding data in List\_2[0] and List\_3[0], etc. I would like to turn these three lists into a dictionary inside a dictionary, with the values in List\_1 being the primary keys. How do I do this while keeping everything in order?
``` >>> a = [1,2,3] >>> b = [4,5,6] >>> c = [7,8,9] >>> dict(zip(a, zip(b, c))) {1: (4, 7), 2: (5, 8), 3: (6, 9)} ``` See the [documentation](http://docs.python.org/library/functions.html#zip) for more info on `zip`. As lionbest points out below, you might want to look at [`itertools.izip()`](http://docs.python.org/library/itertools.html) if your input data is large. `izip` does essentially the same thing as `zip`, but it creates iterators instead of lists. This way, you don't create large temporary lists before creating the dictionary.
Python 3: ``` combined = {name:dict(data1=List_2[i], data2=List_3[i]) for i, name in enumerate(List_1)} ``` Python 2.5: ``` combined = {} for i, name in enumerate(List_1): combined[name] = dict(data1=List_2[i], data2=List_3[i]) ```
Concatenating Dictionaries
[ "", "python", "dictionary", "merge", "key", "" ]
I ran FxCop on one of the projects that I am working on and I got a whole slew of warnings that look like the following: > CA1703 : Microsoft.Naming : In > resource > 'MyProject.Properties.Resources.resx', > referenced by name 'MyString', > correct the spelling of 'Myyyy' in > string value 'Some format string: > {0:dMMMyyyy}' As Resources is a generated class, I can't simply suppress these messages using the normal mechanism. Does anyone have any bright ideas how I can get around this problem? **Edit**: Just to make things clear (as I wasn't aware that this was any different with Team System), I am interested in non- Team System solutions - in particular for MS Visual Studio Pro 2008.
I ended up disabling spell-checking for resources by setting the Neutral Language of the assembly to nothing i.e. in AssemblyInfo.cs, I have this line added: ``` [assembly: NeutralResourcesLanguage("")] ``` This is as suggested [here](http://social.msdn.microsoft.com/Forums/en-US/vstscode/thread/6275ca1e-e7f4-4577-a992-f93502f2c5ad/).
If you don't want to have naming rules applied to resources, just turn off this rule in the project settings. 1. Right click on the project in the project tree 2. Click "Properties" 3. Go to the tab "Code Analysis" 4. Expand the branch "Naming Rules" 5. Disable CA1703 If you just want to suppress certain resources, you can suppress them in the global suppression file. This is normally available on the right mouse key in the Error List of visual studio. 1. Right click on the CA message(s) in the Error List 2. Choose "Suppress Messages(s)" 3. Choose "In Project Suppression File"
FxCop taking issue with my use of format strings in resources with NON-Team System Visual Studio
[ "", "c#", "visual-studio-2008", "resources", "fxcop", "" ]
Java is not allowing inheritance from multiple classes (still it allows inheritance from multiple interfaces.), I know it is very much inline with classic diamond problem. But my questions is why java is not allowing multiple inheritance like C++ when there is no ambiguity (and hence no chances of diamond problem) while inheriting from multiple base class ?
It was a [design decision](http://www.javaworld.com/javaqa/2002-07/02-qa-0719-multinheritance.html) of Java. You'll never get it, so don't worry too much about it. Although MI might help you make Mixins, that's the only good MI will ever do you.
I have read that most programmers don't use multiple inheritance in a proper way. "Just go ahead and inherit from a class just to reuse code" is not the best practice in case of multiple inheritance. Many programmers do not know when to use simple inheritance in most cases. Multiple inheritance must be used with caution and only if you know what you are doing if you want to have a good design. I don't think that the lack of multiple inheritance in java (as in c++) will put restrictions in your code / application design / problem domain mapping into classes.
Multiple Inheritance in java
[ "", "java", "oop", "multiple-inheritance", "diamond-problem", "" ]
I've spent quite a lot of time today trying various things, but none of them seem to work. Here's my situation, I'd like to be able to select the rank of a row based on it's ID from a specifically sorted row For example, if my query is something like: ``` SELECT id, name FROM people ORDER BY name ASC ``` with results like: ``` id name 3 Andrew 1 Bob 5 Joe 4 John 2 Steve ``` I would like to get the rank (what row it ends up in the results) without returning all the rows and looping throw them until I get to the one I want (in PHP). For example, I'd like to select the 'rank' of 'Steve' so that it returns -- in this case -- 5 (not his id, but the 'rank' of his name in the above query). Similarly, I'd like to be able to select the rank of whatever row has the ID of 1. For this example, I'd like to return a 'rank' of 2 (because that's in what result row there is an ID of 1) and nothing else. I've Google'd as much as I could with varying results... either having really slow queries for larger tables or having to create all sorts of temporary tables and user variables (the former I'd REALLY like to avoid, the latter I suppose I can live with). Any help or insight would be greatly appreciated.
from [artfulsoftware](http://www.artfulsoftware.com/infotree/queries.php?&bw=1280#460): ``` SELECT p1.id, p1.name, COUNT( p2.name ) AS Rank FROM people p1 JOIN people p2 ON p1.name < p2.name OR ( p1.name = p2.name AND p1.id = p2.id ) GROUP BY p1.id, p1.name ORDER BY p1.name DESC , p1.id DESC LIMIT 4,1 ```
Something like this? ``` SELECT Row, id, name FROM (SELECT @row := @row + 1 AS Row, id, name FROM people ORDER BY name ASC) WHERE Row = @SomeRowNumber ``` If you want to go by the ID, just alter the where clause.
Using MySQL, how do I select query result rank of one particular row?
[ "", "php", "mysql", "rank", "" ]
Is it different than C or C#?
Java has one keyword, **for**, but it can be used in two different manner: ``` /* classical, C/C++ school */ for (int i = 0; i < N; i++) { } ``` for-each style: ``` // more object oriented, since you use implicitly an Iterator // without exposing any representation details for (String a : anyIterable) { } ``` it works for any type that implements `Iterable<String>` such as `List<String>`, `Set<String>`, etc. The latter form works also for **arrays**, [see this question for a more "phisophical approach"](https://stackoverflow.com/questions/1160081/why-an-array-is-not-assignable-to-an-iterable).
The following demonstrates the syntax of a java for loop (from [the for loop in Java](http://www.cafeaulait.org/course/week2/32.html)): ``` class Hello { public static void main (String args[]) { System.out.print("Hello "); // Say Hello for (int i = 0; i < args.length; i = i + 1) { // Test and Loop System.out.print(args[i]); System.out.print(" "); } System.out.println(); // Finish the line } } ``` Also see the Wiki entry on [For loop](http://en.wikipedia.org/wiki/For_loop)
How is a for loop structured in Java?
[ "", "java", "for-loop", "" ]
I'm looking for a way to accelerate a repeatable task when I write code. I have ReSharper and I'm thinking a customization could do what I need. I have two objects of the same type. I want to copy all of the public properties of one object to the other object. I want the tool, ReSharper in this case, to do generate the code for me. I'll tell it the names of the first object and the second object. I want it to find all the public properties of the first object and copy the values to the second object. Here's the type of code I'm looking to have generated with a tool like ReSharper: ``` foo.Name = moo.Name; foo.Age = moo.Age; foo.City = moo.City; ``` Automating this simple code that copies values from right to left would save a ton of time and I'm thinking that ReSharper can do it. However, I haven't seen anything pop-up in searches for it though. I'm not looking for a CodeSmith code generation technique or T4 template because I only want it to generate these specific lines inside my class, not generate and entire class or a separate file. Does anyone know a way to press a few keystrokes, enter the "foo" and "moo" object names above and have the tool generate these copy from right to left lines of code? **Update:** I've found some documentation on building extensions to ReSharper, and this can probably be achieved by that path, but it looks really involved. <http://www.jetbrains.net/confluence/display/ReSharper/PowerToys+Pack+3.0+User+Guide> This is beginning to look like a weekend challenge unless someone else has already written it.
I don't believe Resharper can do this, but Open Source [AutoMapper](http://www.codeplex.com/AutoMapper) can. New to AutoMapper? Check out the [Getting Started](http://automapper.codeplex.com/Wiki/View.aspx?title=Getting%20Started) page.
It's really easy. ReSharper doesn't do it, but you can use a super duper REGEX! In Visual Studio: ``` public string Email { get; set; } public string CellPhone { get; set; } public int NumChildren { get; set; } public DateTime BirthDate { get; set; } ``` 1. Select all your properties. Hit `CTRL-D` to copy down. 2. Now hit `CTRL-H` to replace. Make sure **`.*`** is selected for Regex matching. 3. Replace: `public [\w?]* (\w*) .*` (This Regex may need to be tweaked) 4. With: `dest.$1 = source.$1;` Now you have some beautiful code you can put in a method of your choosing: ``` dest.Email = source.Email; dest.CellPhone = source.CellPhone; dest.NumChildren = source.NumChildren; dest.BirthDate = source.BirthDate; ``` ## EDIT: New alternatives 1. You can use AutoMapper for dynamic runtime mapping. 2. [Mapping Generator](https://github.com/cezarypiatek/MappingGenerator) is really nice for static mapping. It can generate the code above and it works well with R#.
Can ReSharper generate code that copies properties from one object to another?
[ "", "c#", "visual-studio", "resharper", "" ]
I am trying to find if an image has in its source name `noPic` which can be in upper or lower case. ``` var noPic = largeSrc.indexOf("nopic"); ``` Should I write : ``` var noPic = largeSrc.toLowerCase().indexOf("nopic"); ``` But this solution doesn't work...
You can use regex with a case-insensitive modifier - admittedly not necessarily as fast as indexOf. ``` var noPic = largeSrc.search(/nopic/i); ```
No, there is no case-insensitive way to call that function. Perhaps the reason your second example doesn't work is because you are missing a call to the `text()` function. Try this: ``` var search = "nopic"; var noPic = largeSrc.text().toLowerCase().indexOf(search.toLowerCase()); ```
JavaScript indexOf to ignore Case
[ "", "javascript", "" ]
I want to sort a dictionary of lists, by third item in each list. It's easy enough sorting a dictionary by value when the value is just a single number or string, but this list thing has me baffled. Example: ``` myDict = {'item1': [7, 1, 9], 'item2': [8, 2, 3], 'item3': [9, 3, 11] } ``` I want to be able to iterate through the dictionary in order of the third value in each list, in this case `item2`, `item1` then `item3`.
Here is one way to do this: ``` >>> sorted(myDict.items(), key=lambda e: e[1][2]) [('item2', [8, 2, 3]), ('item1', [7, 1, 9]), ('item3', [9, 3, 11])] ``` The [`key` argument](http://wiki.python.org/moin/HowTo/Sorting#Sortingbykeys) of the `sorted` function lets you derive a sorting key for each element of the list. To iterate over the keys/values in this list, you can use something like: ``` >>> for key, value in sorted(myDict.items(), key=lambda e: e[1][2]): ... print key, value ... item2 [8, 2, 3] item1 [7, 1, 9] item3 [9, 3, 11] ```
You stated two quite different wants: 1. "What I want to do is sort a dictionary of lists ..." 2. "I want to be able to iterate through the dictionary in order of ..." The first of those is by definition impossible -- to sort something implies a rearrangement in some order. Python dictionaries are inherently unordered. The second would be vaguely possible but extremely unlikely to be implemented. What you can do is 1. Take a copy of the dictionary contents (which will be quite unordered) 2. Sort that 3. Iterate over the sorted results -- and you already have two solutions for that. By the way, the solution that uses "key" instead of "cmp" is better; see [sorted](http://docs.python.org/library/functions.html#sorted) "the third item in the list" smells like "the third item in a tuple" to me, and "e[1][2]" just smells :-) ... you may like to investigate using named tuples instead of lists; see [named tuple factory](http://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields) If you are going to be doing extract/sort/process often on large data sets, you might like to consider something like this, using the Python-supplied sqlite3 module: ``` create table ex_dict (k text primary key, v0 int, v1 int, v2 int); insert into ex_dict values('item1', 7, 1, 9); -- etc etc select * from ex_dict order by v2; ```
Sorting a dictionary with lists as values, according to an element from the list
[ "", "python", "list", "sorting", "dictionary", "" ]
How Facebook detects your away state (you know, the half moon in the chat window)? How you can check in Javascript if a person is away from your page, even if it's open in the browser? Do you think there is any library that already does it?
[JQuery idleTimer plugin](http://paulirish.com/2009/jquery-idletimer-plugin/)
They have JavaScript which runs every 30-60 seconds and reports back, plus they know if you're browsing to other pages on the site, which would reset the counter. Note, if you open up Facebook, and then browse another site and never go back to the Facebook tab, you'll be 'away'
How Facebook detects that you are away?
[ "", "javascript", "facebook", "" ]
I recently got thinking about alignment... It's something that we don't ordinarily have to consider, but I've realized that some processors require objects to be aligned along 4-byte boundaries. What exactly does this mean, and which specific systems have alignment requirements? Suppose I have an arbitrary pointer: `unsigned char* ptr` Now, I'm trying to retrieve a double value from a memory location: `double d = **((double*)ptr);` Is this going to cause problems?
It can definitely cause problems on some systems. For example, on ARM-based systems you cannot address a 32-bit word that is not aligned to a 4-byte boundary. Doing so will result in an access violation exception. On x86 you can access such non-aligned data, though the performance suffers a little since two words have to be fetched from memory instead of just one.
Here's what the [**Intel x86/x64 Reference Manual**](http://www.intel.com/Assets/PDF/manual/253665.pdf) says about alignments: > ### 4.1.1 Alignment of Words, Doublewords, Quadwords, and Double Quadwords > > Words, doublewords, and quadwords do > not need to be aligned in memory on > natural boundaries. The natural > boundaries for words, double words, > and quadwords are even-numbered > addresses, addresses evenly divisible > by four, and addresses evenly > divisible by eight, respectively. > However, to improve the performance of > programs, data structures (especially > stacks) should be aligned on natural > boundaries whenever possible. The > reason for this is that the processor > requires two memory accesses to make > an unaligned memory access; aligned > accesses require only one memory > access. A word or doubleword operand > that crosses a 4-byte boundary or a > quadword operand that crosses an > 8-byte boundary is considered > unaligned and requires two separate > memory bus cycles for access. > > Some instructions that operate on > double quadwords require memory > operands to be aligned on a natural > boundary. These instructions generate > a general-protection exception (#GP) > if an unaligned operand is specified. > A natural boundary for a double > quadword is any address evenly > divisible by 16. Other instructions > that operate on double quadwords > permit unaligned access (without > generating a general-protection > exception). However, additional memory > bus cycles are required to access > unaligned data from memory. Don't forget, reference manuals are the ultimate source of information of the responsible developer and engineer, so if you're dealing with something well documented such as Intel CPUs, just look up what the reference manual says about the issue.
Alignment along 4-byte boundaries
[ "", "c++", "cpu", "alignment", "internals", "" ]
I'm sorry for the generic title of this question but I wish I was able to articulate it less generically. :-} I'd like to write a piece of software (in this case, using C++) which translates a stream of input tokens into a stream of output tokens. There are just five input tokens (lets call them 0, 1, 2, 3, 4) and each of them can have a few different attributes (like, There might be an 4.x property or 0.foo). There are a few more output tokens, about ten, let's call them (Out0..Out9) each of them also has a few properties. Now, we've been working on a mapping of sequences from input tokens to possible output tokens, like this: ``` 01 -> Out0 34 -> Out1 0101 -> Out3 ``` ...so different sequences of input tokens map to a single output token. In my scenario, the set of input tokens is fixed, but the set of output tokens is not - we might decide to introduce new 'productions'. My question is: Does anybody know whether there are good patterns and/or idioms which help in such a situation? Right now I have a set of 'Compressor' object, each of which can eat the input tokens and eventually produces the output tokens. The problem is that some input tokens clash, consider 'Out0' and 'Out3' in the above case. The input '0101' should yield Out3 but *not* Out0. However, the input '0104 should yield Out0 and then leave 0 and 4 in the queue. I'm wondering whether there are maybe patterns from data compression or other areas which might be beneficial. This work of 'reducing' an input of lowlevel tokens to highlevel tokens and dealing with possible conflicts is common among parser writers, no? Are there are useful patterns there? **UPDATE:** A bit more information: 1. in my concrete case, the input tokens are C structs, and the output tokens are C++ objects. I have no control whatsoever over the input stream of tokens, but I can queue them and then modify the queue in case that is beneficial. 2. I solved clashes (like Out3 (0101) vs. Out0 (01)) by trying to match Out3 first and then Out0, but it's a bit ugly. The possible productions are in a list and I simply try to apply them to the input stream, one after the other 3. The list of possible productions can be extended by the user, so I cannot generate one huge DAG and then have a state machine which implements that to handle every possible transition. Of course, this means that the user can add clashes, but that's just the way it is.
You could define a graph, where each node contains an input token and an associated output. The links of each node describe the possible next tokens. Thus, a path in the graph describe a possible transformation rule. To transform the data, start from the node corresponding to the first input token, and try to navigate the graph on the longest path possible, matching the next input token to the nodes linked to the current node. When no linked node matches the next input node, take the output associated with the current node as the result.
When designing a data compression algorithm, you need to take care that the beginning of one code can't be mistaken for another shorter code. This is the basis for [Hamming code](http://en.wikipedia.org/wiki/Hamming_code). The other alternative is to have a delimiter character separating your tokens, like in Morse code (which uses a short pause between characters).
Are there good Patterns/Idioms for Data Translation/Transformation?
[ "", "c++", "algorithm", "design-patterns", "parsing", "compression", "" ]
I have a hibernate object that gets detached and transferred to a thick java swing client using EJBs. The object is then modified in some way and returned to the server where the server then updates the modified object to the database. Everything works well for properties that change, but I am having a problem on how to delete a `many-to-one` mapping. For instance, given the following mapping: ``` <hibernate-mapping> <class name="com.wg.common.bean.Patient" table="patient"> <id name="id" type="integer"> <column name="id" /> <generator class="sequence"> <param name="sequence">patient_id_seq</param> </generator> </id> <many-to-one name="address" class="com.wg.common.bean.Address" cascade="all"> <column name="address_id" /> </many-to-one> ... ``` Say I have a patient object that is sent to the client. The user has previously added an address. There can only be one address per patient. On the client if the user removes the address, I call `setAddress(null)` on the patient object before returning to the server. When I get to the server it saves the address\_id field as null, but leaves the address record in the database. I understand why it is doing that. I am only breaking one end of the relationship. Preferably I would use `delete-orphan`. However, according to the Hibernate documentation, `delete-orphan` is not available for `many-to-one` mappings. The proper procedure is to call on the server (pseudocode): ``` Address address = patient.getAddress(); session.delete(address); patient.setAddress(null); ``` The problem with this pattern is that if I want to stick to a process of simply passing back the Patient object I want saved, I have no way of knowing if it had an address that needs to be deleted. I have to do some less-than-elegant workarounds to solve this problem, such as querying the database to see if there was an Address and removing it if it is null in the passed object, or creating `setDeleteAddress(boolean)`, `getDeleteAddress()` methods in Patient class and setting those on the client side if the user wants to remove the address. Another alternative would be to make the association a one-to-many between Patient and Address. Then I could use `delete-orphan`. However, since it is really a one-to-one relationship, I would need to put some crazy getter/setter in the Patient class like this so I don't litter my code with collection references when there isn't really a collection: ``` public Address getAddress() { if(addresses != null && addresses.size() > 0) return addresses.get(0); else return null; } ``` Is there a better way to address this issue? How have you handled removing an entity on detached objects?
I ended up simply creating a `deleteFlag` in the `Address` class to designate to the EJB that the `Address` in question should be deleted from the `Patient`.
Mappings address as `many-to-one` seems to be the root of your problems. Address is the "parent" in such a relationship, which doesn't make a lot of sense. Consider either mapping it as component or one-to-one instead. No collection should be involved either way.
Hibernate - How to cascade delete on detached objects
[ "", "java", "hibernate", "" ]
From [this site](http://www.mvps.org/directx/articles/catmull/), which seems to have the most detailed information about Catmull-Rom splines, it seems that four points are needed to create the spline. However, it does not mention how the points p0 and p3 affect the values between p1 and p2. Another question I have is how would you create continuous splines? Would it be as easy as defining the points p1, p2 to be continuous with p4, p5 by making p4 = p2 (that is, assuming we have p0, p1, p2, p3, p4, p5, p6, ..., pN). A more general question is how would one calculate tangents on Catmull-Rom splines? Would it have to involve taking two points on the spline (say at 0.01, 0.011) and getting the tangent based on Pythagoras, given the position coordinates those input values give?
Take a look at equation 2 -- it describes how the control points affect the line. You can see points `P0` and `P3` go into the equation for plotting points along the curve from `P1` to `P2`. You'll also see that the equation gives `P1` when `t == 0` and `P2` when `t == 1`. This example equation can be generalized. If you have points `R0`, `R1`, … `RN` then you can plot the points between `RK` and `RK + 1` by using equation 2 with `P0 = RK - 1`, `P1 = RK`, `P2 = RK + 1` and `P3 = RK + 2`. You can't plot from `R0` to `R1` or from `RN - 1` to `RN` unless you add extra control points to stand in for `R - 1` and `RN + 1`. The general idea is that you can pick whatever points you want to add to the head and tail of a sequence to give yourself all the parameters to calculate the spline. You can join two splines together by dropping one of the control points between them. Say you have `R0`, `R1`, …, `RN` and `S0`, `S1`, … `SM` they can be joined into `R0`, `R1`, …, `RN - 1`, `S1`, `S2`, … `SM`. To compute the tangent at any point just take the derivative of equation 2.
The [Wikipedia article](http://en.wikipedia.org/wiki/Cubic_Hermite_spline) goes into a little bit more depth. The general form of the spline takes as input 2 control points with associated tangent vectors. Additional spline segments can then be added provided that the tangent vectors at the common control points are equal, which preserves the C1 continuity. In the specific Catmull-Rom form, the tangent vector at intermediate points is determined by the locations of neighboring control points. Thus, to create a C1 continuous spline through multiple points, it is sufficient to supply the set of control points and the tangent vectors at the first and last control point. I think the standard behavior is to use P1 - P0 for the tangent vector at P0 and PN - PN-1 at PN. According to the Wikipedia article, to calculate the tangent at control point Pn, you use this equation: ``` T(n) = (P(n - 1) + P(n + 1)) / 2 ``` This also answers your first question. For a set of 4 control points, P1, P2, P3, P4, interpolating values between P2 and P3 requires information form all 4 control points. P2 and P3 themselves define the endpoints through which the interpolating segment must pass. P1 and P3 determine the tangent vector the interpolating segment will have at point P2. P4 and P2 determine the tangent vector the segment will have at point P3. The tangent vectors at control points P2 and P3 influence the shape of the interpolating segment between them.
How does the centripetal Catmull–Rom spline work?
[ "", "c++", "opengl", "graphics", "directx", "spline", "" ]
I need serialize a Com Object using .net using c# or Delphi .Net is this possible?
You could probably do this by wrapping the COM object in a (serializable) .NET class, exposing the fields that you want serialized.
Check to see if you COM object implements [IPersistStream](http://msdn.microsoft.com/en-us/library/ms690091(VS.85).aspx), [IPersistMemory](http://msdn.microsoft.com/en-us/library/aa768210(VS.85).aspx) or any other of the [IPersist](http://msdn.microsoft.com/en-us/library/ms688695(VS.85).aspx) variants -- that would be your best bet.
How Do I serialize a COM object in .Net?
[ "", "c#", "xml-serialization", "com-interop", "delphi.net", "" ]
I would like to create my own accordion component without using any AJAX toolkits, mostly for learning purposes. I am not sure quite where to start with this one. I'm assuming I would begin by creating div's for each section in the accordion. Perhaps each div would contain a header, which would be the actual button selected to move the accordion to that section. I am not sure the correct approach to take once an accordion's section button is selected though. Would I use the z-order, so that each section is of a higher z-order? Any help is appreciated. Thanks
I would highly recommend picking up a book such as John Resig's [Pro JavaScript techniques](https://rads.stackoverflow.com/amzn/click/com/1590597273) that will give you some ideas and initial thoughts about how to approach bulding your own client-side solutions. Essentially, you would have an element to act as a header, for example `<h1>` or `<div>` under which you would have a `<div>` with an initial style of `display: none;`. Set up an event handler on the click event of the header to change the style of the div below to `display: block` and ensuring that any other content `<div>`s are hidden (do this by using a CSS class on each content `<div>` for example). I'll leave the smooth animation to you as an exercise for how it might be accomplished. As a hint, I would recommend looking at how a JavaScript library like [jQuery](http://jquery.com) handles animation, by checking out the source.
The best way to order it would be like this ``` <div id="accordion"> <h3 class="accordion title">Title</h3> <div class="accordion section"> Section Content </div> <h3 class="accordion title">Title 2</h3> <div class="accordion section"> Section Content </div> <h3 class="accordion title">Title 3</h3> <div class="accordion section"> Section Content </div> <h3 class="accordion title">Title 4</h3> <div class="accordion section"> Section Content </div> </div> ``` You would want to avoid `z-order` entirely because it is a compatibility mess. Instead you would have the accordion titles be what you would click to open the accordion. You would want to set all of the accordion section `<div>`'s to `visibility:hidden;` by default, and then, when one of them is clicked, change it's visibility, and hide all the others. If you want it to work with any amount of accordion sections, you would have it count each `<h3 class="accordion title">` and each `<div class="accordion section">`, and pair those up into an array. When a title is clicked, show it's corresponding div. Alternatively you could give each one a separate ID, but the first way would be much more useful. Actually, it might be `display:none;` instead of `visibility:hidden;`, I would try both. In addition it's worth mentioning that the animation is usually handled by changing things like the size of the div, so if you were hiding a section, you would make the height smaller and smaller until it reaches 0 and is hidden.
How a Javascript Accordion Works?
[ "", "javascript", "jquery", "ajax", "" ]
I have to check if a set of file paths represent an existing file. It works fine except when the path contains a network share on a machine that's not on the current network. In this case it takes a pretty long time (30 or 60 seconds) to timeout. Questions * Is there a way to shorten the timeout for non existing network shares? (I'm certain that when they do exist they'll answer quickly, so a timeout of 1 sec would be fine) * Is there any other way to solve this issue without starting to cache and making the algorithm more complex? (ie, I already know these X network shares don't exist, skip the rest of the matching paths) UPDATE: Using Threads work, not particularly elegant, though ``` public bool pathExists(string path) { bool exists = true; Thread t = new Thread ( new ThreadStart(delegate () { exists = System.IO.File.Exists(path); }) ); t.Start(); bool completed = t.Join(500); //half a sec of timeout if (!completed) { exists = false; t.Abort(); } return exists; } ``` This solution avoids the need for a thread per attempt, first check which drives are reachable and store that somewhere. --- ## [**Experts exchange solution**](http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_22595703.html): > First of all, there is a "timeout" value that you can set in the IsDriveReady function. I have it set for 5 seconds, but set it for whatever works for you. > > 3 methods are used below: > > 1. The first is the WNetGetConnection API function that gets the > UNC (\servername\share) of the drive > 2. The second is our main method: The Button1\_Click event > 3. The third is the IsDriveReady function that pings the server. > > This worked great for me! Here you go: > > ``` > 'This API Function will be used to get the UNC of the drive > Private Declare Function WNetGetConnection Lib "mpr.dll" Alias _ > "WNetGetConnectionA" _ > (ByVal lpszLocalName As String, _ > ByVal lpszRemoteName As String, _ > ByRef cbRemoteName As Int32) As Int32 > > > 'This is just a button click event - add code to your appropriate event > Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click > > Dim bIsReady As Boolean = False > > For Each dri As IO.DriveInfo In IO.DriveInfo.GetDrives() > > 'If the drive is a Network drive only, then ping it to see if it's ready. > If dri.DriveType = IO.DriveType.Network Then > > 'Get the UNC (\\servername\share) for the > ' drive letter returned by dri.Name > Dim UNC As String = Space(100) > WNetGetConnection(dri.Name.Substring(0, 2), UNC, 100) > > 'Presuming the drive is mapped \\servername\share > ' Parse the servername out of the UNC > Dim server As String = _ > UNC.Trim().Substring(2, UNC.Trim().IndexOf("\", 2) - 2) > > 'Ping the server to see if it is available > bIsReady = IsDriveReady(server) > > Else > bIsReady = dri.IsReady > > End If > > 'Only process drives that are ready > If bIsReady = True Then > 'Process your drive... > MsgBox(dri.Name & " is ready: " & bIsReady) > > End If > > Next > > MsgBox("All drives processed") > > End Sub > > Private Function IsDriveReady(ByVal serverName As String) As Boolean > Dim bReturnStatus As Boolean = False > > '*** SET YOUR TIMEOUT HERE *** > Dim timeout As Integer = 5 '5 seconds > > Dim pingSender As New System.Net.NetworkInformation.Ping() > Dim options As New System.Net.NetworkInformation.PingOptions() > > options.DontFragment = True > > 'Enter a valid ip address > Dim ipAddressOrHostName As String = serverName > Dim data As String = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" > Dim buffer As Byte() = System.Text.Encoding.ASCII.GetBytes(data) > Dim reply As System.Net.NetworkInformation.PingReply = _ > pingSender.Send(ipAddressOrHostName, timeout, buffer, options) > > If reply.Status = Net.NetworkInformation.IPStatus.Success Then > bReturnStatus = True > > End If > > Return bReturnStatus > End Function > ```
Use Threads to do the checks. I think that threads can be timed out.
### In a nutshell 1. Build a list of available drives. 2. Try to resolve the driveletter to an `UNC` name. 3. Try to `ping` the drive. ### Edit regarding Bill's comment *if Google is not the referer, EE doesn't show the answer for free. Links to EE are not helpful.* OP found the article I've mentioned in my original answer and was kind enough to include [the source code for the solution](https://stackoverflow.com/q/1232953/52598) to his question.
Speed up File.Exists for non existing network shares
[ "", "c#", "networking", "timeout", "c#-2.0", "" ]
I am working on deploying a J2ee application that I have previously been deploying in JBOSS into Weblogic 10.3.1.0. I am running into an issue with external properties files. In Jboss I can just put the properties files into $JBOSS\_HOME/server/default/conf, and they are loaded onto the system classpath and I can access them without any problems. I was able to put shared libraries into $MIDDLEWAREHOME/user\_projects/domains/mydomain/lib and they were loaded into the system classpath without any problems but I am unable to load properties files. Does anyone know how to include external properties files in Weblogic? Thanks,
I figured this out and have it working the way I would expect. First I did try the suggestions as above. If i added a folder to my classpath, or put the properties files in a folder on my classpath, the jars in the file were picked up, but not properties files. If i put my properties files in a jar, and put them in a folder on my classpath everything worked. But I did not want to have jar my files everytime a change was made. The following works in my env. If i place the properties files in %WEBLOGIC\_HOME%/user\_projects/domains/MYDOMAIN then they are getting picked up, without having to be placed in a jar file.
In weblogic jars will be loaded from the lib and the non jar files will be loaded from the domain folder
Using external properties files in weblogic
[ "", "java", "jakarta-ee", "properties", "weblogic", "classpath", "" ]
I have a problem with site deployed on IIS6 sever. Here the problem, when I first deploy asp.net 3.5 site to server (site is relatively small with 5 pages and 5 libraries in bin), it is works as expected. But after some period of time (~1h) server returns black pages instead of expected content: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD> <META http-equiv=Content-Type content="text/html; charset=utf-8"></HEAD> <BODY></BODY></HTML> ``` First my idea was that my site conflicts with other .net 2.0 sites that hosted in the same server, so I put my site into dedicated pool but without success. First time site works, then no. There is no errors or something like that in iis logs. And I do not use ClearError() method in my site. I have found similar question [here (I’m getting blank pages instead of error messages using classic ASP, IIS6 and WinServer 2003 R2)](https://stackoverflow.com/questions/243457/im-getting-blank-pages-instead-of-error-messages-using-classic-asp-iis6-and-win), but it is for classic ASP. Also several topics at ASP.NET: * [Blank page problem.](http://forums.asp.net/t/1423943.aspx) * [Blank pages on deployed website](http://forums.asp.net/t/1166864.aspx) * [blank page in IIS 7 on Server 2K8](http://forums.asp.net/p/1432022/3224449.aspx) But this solutions also not help me. For example when I replace web.config with new one, or replace one of the required assemblies with rebuilded one, I have the same result. First time site works, then - black pages. From what I see, I think that this is kind of configuration problem, but I completely stunned right now, because I've tried everything and now I lack any ideas, so help is very appreciated.
I didn't find the origins of the problem. However problem was solved by using Publish Project wizard. Original variant was distributed at xcopy basis with code-behind sources.
I have just had **exactly** the same problem with IIS 7.5. I tried uninstalling IIS multiple times, changing configuration etc., but nothing seemed to do any difference. I followed all the guides available - still nothing. What I ended up doing, was completely removing IIS and all related files and configuration (except registry settings): * Uninstall IIS via Add/Remove Programs > Turn Windows Features on or off * Rebooted * Removed the directory including all files: c:\inetpub * Removed the folder inkluding all files: C:\Windows\System32\inetsrv * Reinstalled IIS via Add/Remove Programs > Turn Windows Features on or off Finally it worked. Hope someone else will benefit from this :)
Server returns blank pages with asp.net 3.5 on IIS6
[ "", "c#", ".net", "asp.net", "asp.net-3.5", "" ]
Just wondering how many people use a path module in Python such as Jason Orendorff's one, instead of using `os.path` for joining and splitting paths? Have you used: * [Jason's path module](http://wiki.python.org/moin/PathModule) (updated for PEP 355) * [Mike Orr's Unipath](http://sluggo.scrapping.cc/python/unipath/Unipath-current/README.html), basically a more modern version of the above * [Noam Raphael's alternative path module](http://wiki.python.org/moin/AlternativePathModule) that subclasses tuple instead of str I know Jason's path module was made into [PEP 355](http://www.python.org/dev/peps/pep-0355/) and rejected by the BDFL. This seems like it was mainly because it tried to do everything in one class. Our use case is mainly to simplify joining and splitting components of paths, so we'd be quite happy if such a path class only implemented the split/join type of operations. Who wouldn't want to do this: ``` path(build_dir, path(source_file).name) ``` or this: ``` build_dir / path(source_file).name ``` instead of this: ``` os.path.join(build_dir, os.path.basename(source_file)) ```
I can pick up a Python program and interpret the current standard method without hesitation - it's explicit and there's no ambiguity: ``` os.path.join(build_dir, os.path.basename(source_file)) ``` Python's dynamic typing makes the first method rather difficult to comprehend when reading: ``` build_dir / path(source_file).name ``` Plus it's not common to divide strings, which brings up more confusion. How do I know that those two aren't integers? Or floats? You won't get a TypeError at runtime if both end up as non-string types. Finally, ``` path(build_dir, path(source_file).name) ``` How is that any better than the os.path method? While they may "simplify" coding (ie, make it easier to write), you're going to run into strife if someone else who is unfamiliar with the alternative modules needs to maintain the code. So I guess my answer is: I don't use an alternative path module. os.path has everything I need already, and it's interface isn't half bad.
A simple but useful trick is this: > import os > > Path = os.path.join Then, instead of this: > os.path.join(build\_dir, os.path.basename(source\_file)) You can do this: > Path(build\_dir, Path(source\_file))
Which path module or class do Python folks use instead of os.path?
[ "", "python", "path", "" ]
I see VARCHAR(255) being used all the time instead of VARCHAR(256), but I also see VARCHAR(16) being used instead of VARCHAR(15). This seems inconsistent to me. If an extra byte is being used to store the VARCHAR's length, shouldn't this rule also apply to the smaller lengths like 2, 4, 8 to be 1, 3, 7, instead? Or am I totally missing something? In other words, if I have a number that I know will never be above 12, should I just go ahead and use a VARCHAR(15) or VARCHAR(16) instead? Because it uses the same amount of space as a VARCHAR(12)? If so, which one do I use? 15 or 16? Does this rule change at all when I get closer to 256? I use both MySQL and SQL, depending on the project.
> In other words, if I have a number that I know will never be above 12, should I just go ahead and use a VARCHAR(15) or VARCHAR(16) instead? No! Use varchar(12) (or maybe even char(12) if the length is fairly constant ). Once upon a time the varchar type was limited to 255 characters on some systems ([including MySql prior to 5.0.3](http://forums.mysql.com/read.php?98,37000,37052)) because the first byte stored indicated the length of the field. Given this restriction, devs wanting to allow a reasonable amount of text would choose 255 rather than going to a different data type altogether. But if you know the size of your data, definitely use exactly that size for the database.
It has nothing to do with odd or even numbers. Historically, 255 characters has often been the maximum length of a `VARCHAR` in various DBMSes. The length limit for a field that wasn't an `LOB` (Large Object) back then was 255 bytes (1 byte int). So the first byte was used to store the length of the field (0-255), and the remaining `n` bytes for the characters. That's why you often see `VARCHAR(255)`. If the field will never be greater than 12, use `VARCHAR(12)`.
VARCHARS: 2, 4, 8, 16, etc.? Or 1, 3, 7, 15, etc.?
[ "", "sql", "mysql", "storage", "limit", "varchar", "" ]
I found this piece of Java code at [Wikipedia](http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) that is supposed to shuffle an array in place: ``` public static void shuffle (int[] array) { Random rng = new Random(); int n = array.length; while (n > 1) { n--; int k = rng.nextInt(n + 1); int tmp = array[k]; array[k] = array[n]; array[n] = tmp; } } ``` Though I didn't test the code, it looks like it should work just fine with an array. In my C# project I created a `CardSet` class and used the above code in a `Shuffle()` method: ``` public class CardSet { private List<Card> cards; public Card this[int i] { get { return cards[i]; } set { cards[i] = value; } } public void Shuffle() { Random rng = new Random(); int n = this.NumberOfCards; while (n < 1) { n--; int k = rng.Next(n + 1); Card tmp = this[k]; this[k] = this[n]; this[n] = tmp; } } ``` When I use the method, however, no shuffling happens: ``` CardSet cs = new CardSet(); cs.Shuffle(); foreach (Card c in cs) { Console.WriteLine(c.ToString()); } ``` I just can't figure out why it doesn't work. I thought that the List might be automatically sorting its objects, so I tried changing one of its values, ``` cs[8] = new Card(Suites.Hearts, Numbers.Two); ``` and that `Card` was exactly where I put it. Either I made some simple mistake or I didn't write the shuffling algorithm correctly. If the code I supplied looks good and someone thinks the mistake might be somewhere else in my code, I can supply the rest of my code.
Change ``` while (n < 1) ``` to ``` while (n > 1) ```
[look into LINQ and orderby with a GUID](http://www.codinghorror.com/blog/archives/001008.html)
How to shuffle a List<T>
[ "", "c#", ".net", "generics", "" ]
My question is how to pull the username into the confirmation popup... would I have to change the way my php is generating the list of users or would it need some mootools coding to select the parent and then the username... if so how could I achieve that? I have my PHP code using codeigniter to generate the following kinda things which is basically listing a username and a link to delete the user. ``` <div class='item'> <a href="http://localhost/nstrust/index.php/admin/users/delete/9" class="delete">Delete</a> <a href="http://localhost/nstrust/index.php/admin/users/view/9" class="view">Jamalia</a> </div> <div class='item'> <a href="http://localhost/nstrust/index.php/admin/users/delete/13" class="delete">Delete</a> <a href="http://localhost/nstrust/index.php/admin/users/view/13" class="view">Timothy</a> </div> ``` I have the following mootools code to pop up and confirmation to see if the user really want to delete the user ``` window.addEvent('domready', function() { $$('a.delete').addEvent('click', function(event) { if (!confirm("Are you sure you want to remove this user?")) { event.stop(); } }); }); ```
The following will work nicely on your markup: ``` $$('a.delete').addEvent('click', function(event) { var username = $(event.target).getNext().get('text'); //The username is in the next tag. if (!confirm("Are you sure you want to remove " + username + "?")) { event.stop(); } }); ``` Since the next link holds the user name, you can simply traverse the DOM to it and get the text value.
Assuming that your HTML will always follow the markup given above, your `confirm()` call could be something like: `var username = $$(event.target).getNext().text; confirm("Are you sure that you want to delete " + username + "?");` This relies on the fact that the next element after the 'delete' link will be an element containing the username being deleted.
Questions regarding PHP and mootools
[ "", "php", "mootools", "selection", "" ]
I was going through IEnumerable and IEnumerator , but could not get one point clearly..if we have foreach, then why do we need this two interfaces? Is there any scenario where we have to use interfaces.If yes, then can somebody explain with an example. Any suggestions and remarks are welcome. Thanks.
`foreach` *uses* the interfaces in many cases. You need the interfaces if you want to *implement* a sequence which `foreach` can then use. (Iterator blocks usually make this implementation task very simple though.) However, just *occasionally* it can be useful to use the iterators directly. A good example is when trying to "pair up" two different sequences. For example, suppose you receive two sequences - one of names, one of ages, and you want to print the two together. You might write: ``` static void PrintNamesAndAges(IEnumerable<string> names, IEnumerable<int> ages) { using (IEnumerator<int> ageIterator = ages.GetEnumerator()) { foreach (string name in names) { if (!ageIterator.MoveNext()) { throw new ArgumentException("Not enough ages"); } Console.WriteLine("{0} is {1} years old", name, ageIterator.Current); } if (ageIterator.MoveNext()) { throw new ArgumentException("Not enough names"); } } } ``` Likewise it can be useful to use the iterator if you want to treat (say) the first item differently to the rest: ``` public T Max<T>(IEnumerable<T> items) { Comparer<T> comparer = Comparer<T>.Default; using (IEnumerator<T> iterator = items.GetEnumerator()) { if (!iterator.MoveNext()) { throw new InvalidOperationException("No elements"); } T currentMax = iterator.Current; // Now we've got an initial value, loop over the rest while (iterator.MoveNext()) { T candidate = iterator.Current; if (comparer.Compare(candidate, currentMax) > 0) { currentMax = candidate; } } return currentMax; } } ``` --- Now, if you're interested in the difference between `IEnumerator<T>` and `IEnumerable<T>`, you might want to think of it in database terms: think of `IEnumerable<T>` as a table, and `IEnumerator<T>` as a cursor. You can ask a table to give you a new cursor, and you can have multiple cursors over the same table at the same time. It can take a while to really grok this difference, but just remembering that a list (or array, or whatever) doesn't have any concept of "where you are in the list" but an iterator over that list/array/whatever *does* have that bit of state is helpful.
What Jon said. * `IEnumerable` or `IEnumerable<T>` : by implementing this an object states that it can give you an iterator that you can use to traverse over the sequence/collection/set * `IEnumerator` or `IEnumerator<T>` : if you call the GetEnumerator method defined in the previous interface, you get an iterator object as an IEnumerator reference. This enables you to call MoveNext() and get the Current object. * `foreach` : is a C# construct/facade in a sense in that you don't need to know how it works under the hood. It internally gets the iterator and calls the right methods for you to concentrate on what you want to do with each item (the contents of the foreach block). Most of the time, you'd just need foreach unless you're implementing your own type or custom iteration, in which case you'd need to get to know the first 2 interfaces.
IEnumerable , IEnumerator vs foreach, when to use what
[ "", "c#", "enumeration", "" ]
I have a JDialog with a button/textfield for the user to select a file. Here's the code: ``` FileDialog chooser = new FileDialog(this, "Save As", FileDialog.SAVE ); String startDir = saveAsField.getText().substring( 0, saveAsField.getText().lastIndexOf('\\') ); chooser.setDirectory(startDir); chooser.setVisible(true); String fileName = chooser.getFile(); ``` My problem is that instead of seeing an All Files filter, I want to provide a custom filter, e.g. for Word docs or something. I setup a custom FilenameFilter using setFilenameFilter(), but it didn't seem to work. I did notice that it says in the docs that the custom filter doesn't work in Windows (this runs in Windows XP/Vista/7). Here was my implementation of the filter: ``` chooser.setFilenameFilter( new geFilter() ); public class geFilter implements FilenameFilter { public boolean accept(File dir, String name) { return name.endsWith( ".doc" ) || name.endsWith( ".docx" ); } } ``` Am I doing something wrong here? Also, I want a description to appear in the box, like "Microsoft Word (\*.doc \*.docx)" but I'm not sure how to do that. Any and all help is appreciated.
AWT isn't really the preferred way of writing Java GUI apps these days. Sun seems to have mostly abandoned it. The two most popular options are Swing and [SWT](http://www.eclipse.org/swt/). So I think they didn't really develop the APIs very extensively to add modern features. (err, to answer your question: No you don't appear to be able to do that with AWT) Swing has the advantage that it is truly write-once-run-anywhere and it can look exactly the same everywhere. There are Look & Feels that try to make Swing look native, some are better than others (Mac isn't terrible, Windows is okay, GTK isn't). Still, if you want an app that really looks and acts EXACTLY the same everywhere, Swing will let you do that. Plus it runs out-of-the-box without any extra libraries. Performance isn't great. Swing's [JFileChooser](http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JFileChooser.html) will let you do what you want. Create a subclass of [FileFilter](http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/filechooser/FileFilter.html) and call `setFileFilter` on the `JFileChooser`. SWT takes the write-once-run-anywhere to the opposite extreme. You still have one codebase that you write against, but it actually uses the native widgets on each platform so it generally looks like a native app (not perfect everywhere, but still impressive). It's fast and pretty reliable in my experience. Eclipse (and other high profile software) uses SWT so it's in pretty heavy use. But it does require platform-specific JARs and DLLs.
since you are using JDialog, that is a swing class why not using [JFileChooser](http://java.sun.com/javase/6/docs/api/javax/swing/JFileChooser.html)? ``` JFileChooser fc = new JFileChooser("C:\\"); fc.setFileFilter(new FileNameExtensionFilter("Microsoft Word (*.doc, *.docx)", "doc", "docx")); ``` [FileNameExtensionFilter](http://java.sun.com/javase/6/docs/api/javax/swing/filechooser/FileNameExtensionFilter.html) is a nice Java 6 class that does exactly what you want.
Need FileDialog with a file type filter in Java
[ "", "java", "swing", "awt", "filedialog", "" ]
Is there a good way to identify a cell phone or any other mobile device (which may be subject to a limited data plan) through the user agent or similar, easily accessible methods?
Yes: [WURFL](http://wurfl.sourceforge.net/), the Wireless Universal Resource File: *"The WURFL is an XML configuration file which contains information about capabilities and features of many mobile devices."*
You'd want to look in the User Agent for specific browsers and keywords like 'Mobile', 'Skyfire', etc. That should be a pretty reliable way. You'd want to do a Google Search for Mobile Browser UserAgents. Someone probably has made a list.
Identify a cell phone by user-agent
[ "", "php", "mobile", "user-agent", "mobile-browser", "" ]
I'm a little confused about when exactly my Property is being initialized. Suppose I have a property declared like this: ``` private Dictionary<string, Dictionary<string,string>> MessageLookup { get { return messages ?? doSomething(); } } ``` The doSomething method populates the messages Dictionary and returns it. My question is, when is this code run? If I place a breakpoint into the doSomething code, it isn't hit, but the MessageLookup property is holding data (this is the only place it is initialized) when I view it in the debugger. Is this code run at construction? does the debugger run it automatically when I hover over the variable name? If so, why isn't the breakpoint hit?
That code is run whenever anyone refers to the property, and not before. If you use the debugger, you'll see it because the debugger tries to fetch property values automatically (so you can see the state of the object). I don't know whether the debugger ignores breakpoints while it's evaluating properties for itself - that would explain everything. Try running your code *not* in a debugger, and make some code access your property: ``` var lookup = someObject.MessageLookup; ``` Make `doSomething()` dump a stack trace and you'll see what's going on.
It is run when your property is first evaluated. No background stuff going on. I'm guessing you're not seeing this because you use Quickwatch to inspect your object. At that point it will get executed and your breakpoint will be skipped.
When is my C# property initialized?
[ "", "c#", "properties", "initialization", "getter", "" ]
What is the fastest way to display images to a Qt widget? I have decoded the video using libavformat and libavcodec, so I already have raw RGB or YCbCr 4:2:0 frames. I am currently using a QGraphicsView with a QGraphicsScene object containing a QGraphicsPixmapItem. I am currently getting the frame data into a QPixmap by using the QImage constructor from a memory buffer and converting it to QPixmap using QPixmap::fromImage(). I like the results of this and it seems relatively fast, but I can't help but think that there must be a more efficient way. I've also heard that the QImage to QPixmap conversion is expensive. I have implemented a solution that uses an SDL overlay on a widget, but I'd like to stay with just Qt since I am able to easily capture clicks and other user interaction with the video display using the QGraphicsView. I am doing any required video scaling or colorspace conversions with libswscale so I would just like to know if anyone has a more efficient way to display the image data after all processing has been performed. Thanks.
Thanks for the answers, but I finally revisited this problem and came up with a rather simple solution that gives good performance. It involves deriving from `QGLWidget` and overriding the `paintEvent()` function. Inside the `paintEvent()` function, you can call `QPainter::drawImage(...)` and it will perform the scaling to a specified rectangle for you using hardware if available. So it looks something like this: ``` class QGLCanvas : public QGLWidget { public: QGLCanvas(QWidget* parent = NULL); void setImage(const QImage& image); protected: void paintEvent(QPaintEvent*); private: QImage img; }; QGLCanvas::QGLCanvas(QWidget* parent) : QGLWidget(parent) { } void QGLCanvas::setImage(const QImage& image) { img = image; } void QGLCanvas::paintEvent(QPaintEvent*) { QPainter p(this); //Set the painter to use a smooth scaling algorithm. p.setRenderHint(QPainter::SmoothPixmapTransform, 1); p.drawImage(this->rect(), img); } ``` With this, I still have to convert the YUV 420P to RGB32, but ffmpeg has a very fast implementation of that conversion in libswscale. The major gains come from two things: * No need for software scaling. Scaling is done on the video card (if available) * Conversion from `QImage` to `QPixmap`, which is happening in the `QPainter::drawImage()` function is performed at the original image resolution as opposed to the upscaled fullscreen resolution. I was pegging my processor on just the display (decoding was being done in another thread) with my previous method. Now my display thread only uses about 8-9% of a core for fullscreen 1920x1200 30fps playback. I'm sure it could probably get even better if I could send the YUV data straight to the video card, but this is plenty good enough for now.
I have the same problem with gtkmm (gtk+ C++ wrapping). The best solution besides using a SDL overlay was to update directly the image buffer of the widget then ask for a redraw. But I don't know if it is feasible with Qt ... my 2 cents
What is the most efficient way to display decoded video frames in Qt?
[ "", "c++", "qt", "image-processing", "" ]
I imported a bunch of tables from an old sql server (2000) to my 2008 database. All the imported tables are prefixed with my username, for example: `jonathan.MovieData`. In the table `properties` it lists `jonathan` as the db schema. When I write stored procedures I now have to include `jonathan.` in front of all the table names which is confusing. How do I change all my tables to be dbo instead of jonathan? Current result: `jonathan.MovieData` Desired result: `dbo.MovieData`
``` ALTER SCHEMA dbo TRANSFER jonathan.MovieData; ``` See [ALTER SCHEMA](http://msdn.microsoft.com/en-us/library/ms173423.aspx). **Generalized Syntax:** ``` ALTER SCHEMA TargetSchema TRANSFER SourceSchema.TableName; ```
You can run the following, which will generate a set of ALTER sCHEMA statements for all your talbes: ``` SELECT 'ALTER SCHEMA dbo TRANSFER ' + TABLE_SCHEMA + '.' + TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'jonathan' ``` You then have to copy and run the statements in query analyzer. Here's an older script that will do that for you, too, I think by changing the object owner. Haven't tried it on 2008, though. ``` DECLARE @old sysname, @new sysname, @sql varchar(1000) SELECT @old = 'jonathan' , @new = 'dbo' , @sql = ' IF EXISTS (SELECT NULL FROM INFORMATION_SCHEMA.TABLES WHERE QUOTENAME(TABLE_SCHEMA)+''.''+QUOTENAME(TABLE_NAME) = ''?'' AND TABLE_SCHEMA = ''' + @old + ''' ) EXECUTE sp_changeobjectowner ''?'', ''' + @new + '''' EXECUTE sp_MSforeachtable @sql ``` Got it from [this site](http://weblogs.asp.net/owscott/archive/2004/01/30/SQL-Table-Ownership-Changes_2C00_-Quick-and-Easy.aspx). It also talks about doing the same for stored procs if you need to.
How do I change db schema to dbo
[ "", "sql", "sql-server", "database", "sql-server-2008", "schema", "" ]
I am using C# 2008 SP1 I developed a program that will be run on several user computers, ranging from a few hundred to a few thousand. What is the best way to download the files to update the user program HTTP or FTP? Also, are the security issues related to each protocol? Many thanks
Either protocol should work most all the time, HTTP might be a bit more likely to be working (i.e. if the only way to connect to the internet on that system is through an HTTP proxy). As for security, neither protocol ensures that the server is actually the right server... so really, there's not really any. HTTPS would solve that problem, but might not be possible. If security (not privacy) is a concern, I'd recommend signing the package and verifying the signature with a public key embedded inside your application after downloading, that way you won't need to verify that the protocol is secure.
The easiest way to handle this is probably via a ClickOnce deployment. But that isn't an option for everyone.
What is the best and most secure way to programatically download files from a web server (HTTP/FTP)?
[ "", "c#", ".net", "security", "deployment", "" ]
In Oracle SQL Developer, there's a "SQL" tab for each table. This tab contains most of the SQL code (`CREATE TABLE`, `CREATE TRIGGER`, etc) that's needed to recreate the table. Is this information available programatically from the database system, or is this an application feature of SQL Developer? If the former, what commands/statements would I need to run to retrieve this information? If the later, are there any clever ways to get SQL Developer to export these statements?
If you are using Oracle 9i+ then you are looking for the DBMS\_METADATA package. <http://download.oracle.com/docs/cd/B10500_01/appdev.920/a96612/d_metada.htm>. It will allow you to extract whatever DDL you want. If you are looking for more specific information there is a whole host of views you can access for specific data elements similar to the ones given by @Quassnoi.
There are lots of information, but here are the main queries: ``` SELECT * FROM dba_tables SELECT * FROM dba_tab_columns SELECT * FROM dba_ind_columns ``` To see what `SQL Developer` actually outputs, enable trace for all sessions with a `LOGON TRIGGER` and look into the trace file created by `SQL Developer`'s internal session.
CREATE TABLE reverse engineering in Oracle
[ "", "sql", "oracle", "" ]
I want to insert the data in my table tblSubscriptions and I only want to use one insert statement. I am going to insert data for every userId in User Table. The following SQL doesnot work. ``` Insert tblSubscriptions (UserID, ProductID, isACtive, SubscriptionDays, Price, MonthlyPrice, ProductType, CurrencyID) Values ((Select userID From tblUser where SubscriptionType in(1, 0, null)), 7, 1, 0, 0, 0, 30, 1) ``` How to do this using one insert statement i.e Without cursors.
## Query ``` INSERT INTO tblSubscriptions (UserID, ProductID, IsActive, SubscriptionDays, Price, MonthlyPrice, ProductType, CurrencyID) SELECT UserID, 7, 1, 0, 0, 0, 30, 1 FROM tblUser WHERE ISNULL(SubscriptionType, 0) IN (1, 0) ```
``` Insert tblSubscriptions (UserID, ProductID, isACtive, SubscriptionDays, Price, MonthlyPrice, ProductType, CurrencyID) Select userID, 7, 1, 0, 0, 0, 30, 1 From tblUser where SubscriptionType in (1, 0) or SubScriptionType is null ``` The IN clause will not work with NULL
Insert using single insert statement
[ "", "sql", "sql-server-2005", "t-sql", "insert-update", "" ]
I know this has been covered before but I cannot find an answer to this, I have always used this; ``` header("Location: http://www.website.com/"); exit(); ``` This has always worked in my current project and all of a sudden it is not working in any of my browsers I would like to figure out the problem and fix it instead of using ``` echo "<script type='text/javascript'>window.top.location='http://website.com/';</script>"; ``` I also have error reporting enabled and it shows no errors ``` // SET ERROR REPORTING error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE); ini_set('display_errors', TRUE); ``` **Any ideas why it will not work?**
Try: ``` error_reporting(E_ALL | E_WARNING | E_NOTICE); ini_set('display_errors', TRUE); flush(); header("Location: http://www.website.com/"); die('should have redirected by now'); ``` See what you get. You shouldn't use ^ (xor) in your error\_reporting() call because you're unintentionally asking for all errors EXCEPT notices and warnings.. which is what a 'headers already sent' error is. Edit: Also try putting flush() right above your header() call.
# COMMON PROBLEMS: **1)** there should not be any output (i.e. **`echo..`** or HTML codes) before the **`header(.......);`** command. **2)** there should not be a **white-space**(or **newline**) before `<?php` and after `?>` tags. **3)** **GOLDER RULE!** - the file (and other `include()`-d files) should have **UTF8 without BOM** encoding (and not just **UTF-8**). That is problem in many cases (because typical **UTF8** encoded file has something special character in the start of file output)!!!!!!!!!!! **4)** When **redirecting**, after `header(...);` you must use `exit;` **5)** Recommended practice - always use 301 or 302 in reference: ``` header("location: http://example.com", true, 301 ); exit; ``` **6)** If none of above helps, use JAVSCRIPT redirection(but it's highly not recommended By Google), but it may be the last chance...: ``` echo "<script type='text/javascript'>window.top.location='http://example.com/';</script>"; exit; ```
PHP header redirect not working
[ "", "php", "redirect", "" ]
Let say I devise an architecture like this - an application consists of modules and modules uses domain-specific utilities to perform changes to the model or database. An example, a registration module which shows the form, accept input and then use a registration utility which will perform the calls to insert the user info do the DB. Who is responsible for performing data validation? 1) The module, as it is the 'superior' passing data down to an utility 2) The utility, this way no suspect data would ever get through 3) Both should have thorough data validation 4) Some other arrangements Thoughts? Opinions?
Any component that is using data is responsible for validating the data for its own purpose. For example: Some part of a service layer may validate that an input field is a valid email address, because that's what the business rules dictate. While the data layer may validate that the data is no longer than a particular length, because that is the largest that can fit in the database column, but it doesn't particularly care if it's an email address or not. It should also be in a location that allows re-use. So (in MVC) the "valid email" validation from above wouldn't go into a controller or view because input into that piece of business logic is likely to happen in more than one controller/view, and this would require the duplication of the validation logic.
Data should be validated as soon as possible - ie, there should be the minimum amount of distance between when data is read from input (such as user input) and when it is validated. The practical reason for this is it makes it easier to review the validation code. In MVC, I would say it should go into the 'controller', assuming that the controller is where you read in all the input values (the controller then passes the validated values to the model, when you do it this way). That said, there will likely be a fair bit of stuff in your validation code that can be shared, and you can write yourself helper code for validation.
Which 'layer' is responsible for validation of data
[ "", "php", "validation", "" ]
Where do you store application scoped components in your winforms apps? I see that I can create a descendant of Component in my application. I could then drag and drop the components that I want to share among the forms in my project. Is this the best practice for shared access to components (non-visual controls)? In Delphi, we had a DataModule. A DataModule was a simple design surface that functioned as a container for non-visual components. I would drag and drop Data Access objects onto this surface and access them from all forms. It provided a nice central location and cache for my data objects. How are you guys doing this in Winforms?
[System.ComponentModel.Component](http://msdn.microsoft.com/en-us/library/system.componentmodel.component.aspx) provides a [design-surface for non-visual components in Visual Studio](http://msdn.microsoft.com/en-us/library/a8y82386.aspx). Usually, in your project, you can just "Add" "Component" and start adding and configuring non-visual components as you can with the designers for forms and user controls. For global access (application scope) you could provide access to a component in your Program class as a public (or internal) static member. You can initialize this member in the Main method, or by arbitrarily complex interaction between Program and MainForm or other components, e.g. using the service infrastructure stipulated by the related classes in System.ComponentModel and a customized implementation of IContainer.
I normally use a singleton for things like logging classes, database adapters, etc. This is handy when you want a static reference to your objects throughout your application. I may have misunderstood your question, though.
Where to put Application scope components in Winforms?
[ "", "c#", "winforms", "scope", "components", "" ]
Is it worth to use Google Web Toolkit for heavy traffic website (something like Youtube, Hulu). If not then what Java framework should be used?
What are you planning on doing with GWT? If you will be serving up huge video files, I don't think GWT will be much of a blip on your radar. Since GWT executes on the client side, it won't be putting any processor load on your servers, and the actual javascript files that are generated are compiled down to the bare minimum of code needed, and would be tiny compared to even one video download. GWT is used for google's adsense management console, and for google wave. Is your site going to get more traffic than either of those? ;) With GWT 2.0 we should see even more performance gains as the optimization techniques get even better. This [IO](http://code.google.com/events/io/sessions/EffectiveGwt.html) session talks a bit about squeezing extra performance out of GWT.
> As a part of evaluation of > presentation layer frameworks, we > performed load tests for the Google > Web Toolkit. We used sample > application DynaTable, shipped with > the GWT. We deployed DynaTable > application to Tomcat Server. We > recorded test scripts using Grinder > TCPProxy. The test methodology is > described in this post. <http://jroller.com/galina/entry/google_web_toolkit_performance_test>
GWT for heavy traffic website
[ "", "java", "gwt", "" ]
I have a table in SQL Server consisting of two columns that track how many users are logged into a system at a particular interval. The first column is Time15, which is the time rounded to the nearest 15 minute interval (datetime). The second column is UserCount, which is the number of users logged into the system during that 15 minute interval. I need a query that will show me the peak number of users logged in for each day. So if at 1 PM on 1/1/09 the system reached a peak of 100 users, I need output that looks like: 1/1/09 - 100 1/2/09 - 94 1/3/09 - 98 etc ... Any idea what T-SQL is going to accomplish this? Thanks!
Try this: ``` SELECT YEAR(Time15), MONTH(Time15), DAY(Time15), MAX(UserCount) FROM Table GROUP BY YEAR(Time15), MONTH(Time15), DAY(Time15) ``` I like Russ's approach for getting rid of the time portion - if you have SQL Server 2005+ you can use this approach to preserve the time of day the peak happened: ``` WITH cte AS ( SELECT Time15, UserCount, ROW_NUMBER() OVER (PARTITION BY DATEADD(dd, DATEDIFF(d, 0, Time15), 0) ORDER BY UserCount DESC) AS RowNumber FROM <Table> ) SELECT Time15, UserCount FROM cte WHERE RowNumber = 1 ```
You basically need to drop the time part from the Time15 field in order to get the Date. Then it's just a simple case of getting the Maximum UserCount when you group by the Date. ``` SELECT DATEADD(dd, DATEDIFF(d, 0, Time15), 0) As [Date], MAX(UserCount) As [Maximum Users] FROM Table GROUP BY DATEADD(dd, DATEDIFF(d, 0, Time15), 0) ```
T-SQL query - GROUP BY issue
[ "", "sql", "sql-server", "t-sql", "" ]
Feels like Im about to reinvent the wheel. Im having a message payload (e.g. from a client through a socket) in XML format (in a simple java.lang.String). Below is an example what the payload could look like: ``` <update> <type>newsource</type> <sources> <source>vedbyroad box 1492</source> </sources> </update> ``` I want to verify that the structure of the xml document really looks like this. Feels like the correct xml tool already is available for this?
You need to validate your XML with a **schema**. Here's an example with JAXB: ``` JAXBContext jc = JAXBContext.newInstance("com.acme.foo:com.acme.bar" ); Umarshaller u = jc.createUnmarshaller(); u.setValidating(true); SchemaFactory sf = SchemaFactory.newInstance( javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(new File("mySchema.xsd")); u.setSchema(schema); MyObject myObj = (MyObject)u.unmarshal( new File( "myFile.xml" ) ); ```
Sounds like you need an [XML Schema](http://www.w3schools.com/Schema/default.asp) for this document. Here's a [Java-based](http://www.javaworld.com/javaworld/jw-09-2000/jw-0908-validation.html) tutorial.
XML format verification
[ "", "java", "xml", "" ]
I'm writing a C# app that will be required to integrate with twitter, I need to be able to do the following: * send direct messages * read all messages that are either @helloapp or #helloapp If you are interested the app is part of [Carsonified](http://carsonified.com)'s app in 4 days for FOWA. Read more [here](http://thinkvitamin.com/code/sketches-wireframes-logo-ideas-meet-our-new-app/) or see the [tweets](http://search.twitter.com/search?q=%23helloapp).
[TweetSharp](https://github.com/danielcrenna/tweetsharp) can take care of both those requirements. Yedda doesn't support Direct Messages as of now.
See available APIs [here](http://dev.twitter.com/docs/twitter-libraries#dotnet) I think most preferable will be [Yedda Twitter Library](http://devblog.yedda.com/index.php/twitter-c-library/)
What's the best C# Twitter API for a twitter bot
[ "", "c#", "twitter", "" ]
Suppose I have these abstract classes `Foo` and `Bar`: ``` class Foo; class Bar; class Foo { public: virtual Bar* bar() = 0; }; class Bar { public: virtual Foo* foo() = 0; }; ``` Suppose further that I have the derived class `ConcreteFoo` and `ConcreteBar`. I want to covariantly refine the return type of the `foo()` and `bar()` methods like this: ``` class ConcreteFoo : public Foo { public: ConcreteBar* bar(); }; class ConcreteBar : public Bar { public: ConcreteFoo* foo(); }; ``` This won't compile since our beloved single pass compiler does not know that `ConcreteBar` will inherit from `Bar`, and so that `ConcreteBar` is a perfectly legal covariant return type. Plain forward declaring `ConcreteBar` does not work, either, since it does not tell the compiler anything about inheritance. Is this a shortcoming of C++ I'll have to live with or is there actually a way around this dilemma?
You can fake it quite easily, but you lose the static type checking. If you replace the `dynamic_casts` by `static_casts`, you have what the compiler is using internally, but you have no dynamic nor static type check: ``` class Foo; class Bar; class Foo { public: Bar* bar(); protected: virtual Bar* doBar(); }; class Bar; { public: Foo* foo(); public: virtual Foo* doFoo(); }; inline Bar* Foo::bar() { return doBar(); } inline Foo* Bar::foo() { return doFoo(); } class ConcreteFoo; class ConcreteBar; class ConcreteFoo : public Foo { public: ConcreteBar* bar(); protected: Bar* doBar(); }; class ConcreteBar : public Bar { public: ConcreteFoo* foo(); public: Foo* doFoo(); }; inline ConcreteBar* ConcreteFoo::bar() { return &dynamic_cast<ConcreteBar&>(*doBar()); } inline ConcreteFoo* ConcreteBar::foo() { return &dynamic_cast<ConcreteFoo&>(*doFoo()); } ```
Doesn't static polymorphism solve your problem? Feeding the base class with the derived class through template argument? So the base class will know the derivative Type and declare a proper virtual?
Is there a way to forward declare covariance?
[ "", "c++", "covariance", "forward-declaration", "" ]