Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
below is some code I am using to "translate" a map array into SQL code so I can easily update my database when I have updated my game map. As you can see it prints out the SQL code onto the screen so I can copy and paste it. As my maps will get bigger this will become inefficient as it will crash the browser due to mass output, so instead I am wondering if it is possible to make it create a .txt file and write all of the data to it instead of printing onto the screen? ``` <?php if (isset($_POST['code'])){ $map = $_POST['code']; $map = preg_replace("/,\\s*}/i", "}", $map); $map = str_replace("{", "[", $map); $map = str_replace("}", "]", $map); $map = json_decode('[' . $map . ']'); $arrayCount1 = 0; $arrayCount2 = -1; $H = sprintf('%05d', 00000); $V = sprintf('%05d', 00000); $id = 1; echo "INSERT INTO `map` (`id`, `horizontal`, `verticle`, `image`) VALUES" . "<br />"; for ($count1 = 0; $count1 < sizeof($map[0]); $count1++){ $arrayCount2++; $arrayCount1 = 0; $V = sprintf('%05d', $V + 1); $H = sprintf('%05d', 00000); for ($count2 = 0; $count2 < sizeof($map); $count2++){ echo "(" . $id . ", '" . $H . "', '" . $V . "', '" . $map[$arrayCount1][$arrayCount2] . "')," . "<br />"; $arrayCount1++; $id++; $H = sprintf('%05d', $H + 1); } } } ?> ```
That should be quite simple. Add ``` // second parameter 'a' stands for APPEND $f = fopen('/path/to/the/file/you/want/to/write/to', 'a'); ``` to the beginning of your script. Add ``` fclose($f); ``` to the end fo your script to cleanly close the file handle (good pratice even though handles would be closed the the terminating script automatically). And the change all your `echo`'s and `print`s to ``` fwrite($f, '<<your string>>'); ``` **EDIT:** That way you can even compress the data on the fly using a [compression stream wrapper](http://de.php.net/manual/en/wrappers.compression.php) if amnount of data gets really large.
There is an even simpler approach: ``` ob_start(); # Your code here ... file_put_contents('yourfile.txt', ob_get_clean()); ```
PHP write to file
[ "", "php", "file", "" ]
Is there a way to start a script from another process, so that if the process dies/ends, the script still continues? Will setuid do this? If I were to set the owner to root, and then start the script? For example, if I have some PHP code starting a script, but httpd dies or gets killed, I think that it takes my script with it. Is there a way around this? Specifically, I'm on Fedora 10 with Apache 2 and PHP 5.
From [here](http://www.perkiset.org/forum/php/forked_php_daemon_example-t474.0.html): ``` function become_daemon() { $child = pcntl_fork(); if($child) { exit; // kill parent } posix_setsid(); // become session leader } ``` Additionally, it's a good idea to close STDIN, STDOUT, and STDERR but I'm not sure how to do that in PHP.
Try "nohup yourscript.sh &"
Can I start a script so it's independent of its parent process on Linux?
[ "", "php", "linux", "scripting", "process", "daemon", "" ]
I have this array in PHP: ``` array( [0] => array( 'username' => 'user1' ) [1] => array( 'username' => 'user2' ) ) ``` If I have the 'username' string how can I get the index value as a number? Example, if I have 'user1' how can I get 0?
If you have a 2D array, like in your example, you'll need to customise things a little: ``` function array_search2d($needle, $haystack) { for ($i = 0, $l = count($haystack); $i < $l; ++$i) { if (in_array($needle, $haystack[$i])) return $i; } return false; } $myArray = array( array( 'username' => 'user1' ), array( 'username' => 'user2' ) ); $searchTerm = "user1"; if (false !== ($pos = array_search2d($searchTerm, $myArray))) { echo $searchTerm . " found at index " . $pos; } else { echo "Could not find " . $searchTerm; } ``` If you wanted to search in just one particular field, you could alter the function to something like this: ``` function array_search2d_by_field($needle, $haystack, $field) { foreach ($haystack as $index => $innerArray) { if (isset($innerArray[$field]) && $innerArray[$field] === $needle) { return $index; } } return false; } ```
Take a look at [array\_search](http://us.php.net/array_search). From the PHP help file: ``` <?php $array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red'); $key = array_search('green', $array); // $key = 2; $key = array_search('red', $array); // $key = 1; ?> ```
Get index of row with qualifying value from a 2d array
[ "", "php", "arrays", "multidimensional-array", "key", "" ]
I am writing a class that I know that needs a lock, because the class must be thread safe. But as I am Test-Driven-Developing I know that I can't write a line of code before creating a test for it. And I find very difficult to do since the tests will get very complex in the end. What do you usually do in those cases? There is any tool to help with that? This question is .NET specific Someone asked for the code: ``` public class StackQueue { private Stack<WebRequestInfo> stack = new Stack<WebRequestInfo>(); private Queue<WebRequestInfo> queue = new Queue<WebRequestInfo>(); public int Count { get { return this.queue.Count + this.stack.Count; } } public void Enqueue(WebRequestInfo requestInfo) { this.queue.Enqueue(requestInfo); } public void Push(WebRequestInfo requestInfo) { this.stack.Push(requestInfo); } private WebRequestInfo Next() { if (stack.Count > 0) { return stack.Pop(); } else if (queue.Count > 0) { return queue.Dequeue(); } return null; } } ```
When writing multi-threaded code, you must use your brain even more than the usual. You must reason logically about every single line of code, whether it is thread safe or not. It's like proving the correctness of a mathematical formula - you can not prove things like "N + 1 > N for all N" by just giving examples of values of N with which the formula is true. Similarly, proving that a class is thread-safe is not possible by writing test cases that try to expose problems with it. With a test it's only possible to prove that there is a fault, but not that there are no faults. The best thing that you can do, is to minimize the need for multi-threaded code. Preferably the application should have no multi-threaded code (for example by relying on thread-safe libraries and suitable design patterns), or it should be restricted to a very small area. Your `StackQueue` class looks like simple enough, so that you can make it safely thread-safe with a little thinking. Assuming that the `Stack` and `Queue` implementations are thread-safe (I don't know .NET's libraries), you just need to make `Next()` thread-safe. `Count` is already thread-safe as it is, because no client can use the value returned from it safely without using client-based locking - [state dependencies between methods](http://www.ibm.com/developerworks/java/library/j-jtp09263.html#2.2) would otherwise break the code. `Next()` is not thread-safe, because it has state dependencies between methods. If threads T1 and T2 call `stack.Count` at the same time and it returns 1, then one of them will get the value with `stack.Pop()`, but the other will call `stack.Pop()` when the stack is empty (which then appears to throw `InvalidOperationException`). You will need a stack and queue with non-blocking versions of `Pop()` and `Dequeue()` (ones that return null when empty). Then the code would be thread-safe when written like this: ``` private WebRequestInfo Next() { WebRequestInfo next = stack.PopOrNull() if (next == null) { next = queue.DequeueOrNull(); } return next; } ```
Well, you can usually use things like `ManualResetEvent` to get a few threads into an expected problem state before releasing the gate... but that only covers a small subset of threading issues. For the bigger problem of threading bugs, there is [CHESS](http://msdn.microsoft.com/en-us/devlabs/cc950526.aspx) (in progress) - maybe an option in the future.
Should I unit test for multithreading problems before writing any lock?
[ "", "c#", ".net", "multithreading", "unit-testing", "tdd", "" ]
> IDLE's subprocess didn't make > connection. Either IDLE can't start a > subprocess or personal firewall > software is blocking the connection. Don't think this has been asked-how come this comes up occasionally when running very simple programs-I then have to go to Task Manager & stop all Pythonw processes to get it to work again? It seems to happen randomnly on different bits of code-here is the one I'm doing at the moment- ``` f = open('money.txt') currentmoney = float(f.readline()) print(currentmoney, end='') howmuch = (float(input('How much did you put in or take out?:'))) now = currentmoney + howmuch print(now) f.close() f = open('money.txt', 'w') f.write(str(now)) f.close() ``` Sometimes it works, sometimes it doesn't!
In Python 3.0.1, I have gotten that error after I Ctrl-C to interrupt a previous run of a program in Idle's Python Shell and then try to run a script. Also in 3.0.1: Let's say you have two Idle windows open: a script open for editing in one, and Idle's Python Shell window. I have found that if you close the shell window and then immediately try to run the script, it will give that error when it tries to re-open the shell - but not if you wait a bit in between to let Idle do whatever connection clean up it needs to do. Worse bugs I have found (again, in v3.0.1- not sure if this would happen in the 2.x versions): I had a long script - getting up towards 9k lines - and once it got to a certain size, doing "save as" on it would crash Idle. I am not sure what the exact threshold was for size - but before that, I would also get some intermittent "save as" crashes that seemed to depend on what else I had going on - other Idle windows, how much output was in the shell window perhaps - stuff like that. It can crash and you will lose unsaved work. Also - one thing I commonly do is have a scratch window open where I cut and paste bits of code in various stages of validity, write notes to myself, etc - so not a valid python script, but I sometimes save these so I can come back to them. I have one such file that will crash Idle every time I try to open it - and I lost unsaved work the first time. (FYI: Other editors including PythonWin 2.5.2 have no problem opening the file.)
I was getting the same error message. What was causing the problem for me was that I named one of my scripts 'string.py'. Every time I tried to run a script with 'string.py' in the same directory this happened.
Python IDLE subprocess error?
[ "", "python", "python-3.x", "python-idle", "" ]
I'm having trouble writing a query for the following domain classes: ``` class Person { static hasMany = [memberships: Membership] } class Membership { static belongsTo = [person: Person, group: Group] Date joinDate = new Date(); Group group; Person person; } class Group { static hasMany = [memberships: Membership] } ``` Basically, I want to found all persons which belongs to a list of groups (Let's say group ids are `(1,2)`. The trick here is that the person must be a member of both groups. I'd prefer a criteria query, but HQL is ok also. Note that querying with something like `group.id in (1,2)` won't work because it can be any of the groups, not **both**.
That's my simple HQL approach: ``` Person.executeQuery("FROM Person x WHERE x IN (SELECT m.person from Membership m WHERE m.group = :group1) AND x IN (SELECT m.person from Membership m WHERE m.group = :group2)", [ group1: Group.get(1), group2: Group.get(2) ]) ``` Cheers
Maybe you don't need a query. In the Person class, memberships is a list of Membership objects. You can find if an object is in a Collection (list) without making any query. Something like this should do the job. ``` if(Person.memberships.contains(Membership.findByPersonAndGroup(person1,group1)) && Person.memberships.contains(Membership.findByPersonAndGroup(person1,group2))){ ...do something... } ``` Probably the other solution is simplier, but I think this is just another option. Cheers [Groovy Collections](http://groovy.codehaus.org/Collections)
Grails query association problem
[ "", "java", "grails", "hql", "criteria", "grails-orm", "" ]
Can I make C# start Outlook in the code? In VB6 we use object 'Outlook.Application' and write:' ``` Set oOutlook = CreateObject("Outlook.Application") Set oNameSpace = oOutlook.GetNamespace("MAPI") Set oInbox = oNameSpace.Folders(1) 'Set oInbox = oInbox.Folders("Inbox") oInbox.Display 'oOutlook.Quit 'Close All Outlook copies ``` Copy/Paste from link: <http://www.ozgrid.com/forum/showthread.php?t=73886>
If you just want to start the outlook; using [System.Diagnostics.Process](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx) would be the easiest way. :)
`System.Diagnostics.Process` will only start a process. To do additional actions such choosing folders, you need to use Microsoft Visual Studio Tools for Office (VSTO). And [here](http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.aspx) is it's reference. For example: ``` var outlook = new Microsoft.Office.Interop.Outlook.ApplicationClass(); outlook.Quit(); ```
Start Outlook with c#
[ "", "c#", ".net", "outlook", "" ]
I can never remember all the rules for implementing the IDisposable interface, so I tried to come up with a base class that takes care of all of this and makes IDisposable easy to implement. I just wanted to hear your opinion if this implementation is ok as it is or whether you see something I could improve. The user of this base class is supposed to derive from it and then implement the two abstract methods `ReleaseManagedResources()` and `ReleaseUnmanagedResources()`. So here is the code: ``` public abstract class Disposable : IDisposable { private bool _isDisposed; private readonly object _disposeLock = new object(); /// <summary> /// called by users of this class to free managed and unmanaged resources /// </summary> public void Dispose() { DisposeManagedAndUnmanagedResources(); } /// <summary> /// finalizer is called by garbage collector to free unmanaged resources /// </summary> ~Disposable() { //finalizer of derived class will automatically call it's base finalizer DisposeUnmanagedResources(); } private void DisposeManagedAndUnmanagedResources() { lock (_disposeLock) //make thread-safe if (!_isDisposed) { //make sure only called once try { //suppress exceptions ReleaseManagedResources(); ReleaseUnmanagedResources(); } finally { GC.SuppressFinalize(this); //remove from finalization queue since cleaup already done, so it's not necessary the garbage collector to call Finalize() anymore _isDisposed = true; } } } private void DisposeUnmanagedResources() { lock (_disposeLock) //make thread-safe since at least the finalizer runs in a different thread if (!_isDisposed) { //make sure only called once try { //suppress exceptions ReleaseUnmanagedResources(); } finally { _isDisposed = true; } } } protected abstract void ReleaseManagedResources(); protected abstract void ReleaseUnmanagedResources(); } ```
You are accessing the managed object \_disposeLock in the finalizer. It may have already been garbage-collected by then. Not sure what the implications of this would be as you are only using it to lock. Thread-safety seems like overkill. I don't think you need to worry about contention between the GC thread and your application thread. Otherwise it looks correct.
I can't really comment on the correctness of your code, but I question whether you'll find having the Disposable class at the base of your inheritance tree as flexible as it needs to be. It's won't be much use when you want to inherit from something you don't own. I think that IDispoasble is left as an interface because of the many different domains across which it might be used. Providing a concrete implementation at the foot of the inheritance hierarchy would be... limiting.
Is this IDisposable implementation correct?
[ "", "c#", ".net", "dispose", "idisposable", "" ]
Isn't there a way with Hibernate to return a list of (primitive) values from one column in a table? I need this for a subselect where I only want rows where a particular field is not in a list of ids from another table.
well it turned to be as simple as something such as the following, from the URL <https://www.hibernate.org/hib_docs/nhibernate/html/queryhql.html> which was actually one of the first results I found when googling but I was concerned it might be NHibernate specific ``` from Eg.DomesticCat as cat where cat.Name not in ( select name.NickName from Eg.Name as name ) ```
Can you use a Hibernate raw SQLQuery? ``` SQLQuery q = getSession().createSQLQuery("select int_column from table"); List<Integer> list = (List<Integer>) q.list(); ```
Hibernate for getting a list of primitive integers for subselect
[ "", "java", "hibernate", "subquery", "" ]
I have a simple OpenGL application where I have 2 objects displayed on screen: 1) particle system, where each particle is texture mapped with glTexImage2D() call. In the drawEvent function, I draw it as a GL\_TRIANGLE\_STRIP with 4 glVertex3f. 2) a 3D text loaded from an object file, where each point is loaded using glNewList/glGenLists and store each point as glVertex. I draw it by making call to glCallList. The problem is as soon as I call glTexImage2D() to map my particle with a .bmp file, the 3D text would not show on the screen. The particle would look fine. (this is not expected) If I dont call glTexImage2D, I see both the 3D text and particle system. In this case, particle system looks horrible because I didnt texture map with anything. (this is expected) Does anyone know why using call list and glTexImage2D might conflict with each other? **EDIT** i also forgot to mention: I do call glBindTexture(GL\_TEXTURE\_2D, this->texture); inside the drawLoop before particle system is called. **EDIT2** i only call glTexImage2D() once at system start up (when I texture mapped the bitmap)
glTexImage2D uploads the texture to the video-ram (simplified said). If OpenGL would allow you to place a glTexImage2D call inside the list it had to store the pixel-data in the list as well. Now what happends if you would execute the list? You would upload the same image data into the same texture all over gain. That makes no sense, therefore it's left out. If you want to change textures between draw calls use glBindTexure. That call sets the current texture. It's much faster. Regarding your image-upload via glTexImage2D: Do that only once for each texture. Either at the start of your program (if it's small) or each time you load new content from disk.
It might not be a conflict of glTexImage2D and glCallList at all. Is your texture mapping ok ? have you set the texture coordinates propperly? Try checking for a vertex to texture coordinates missmatch.
OpenGL: glTexImage2D conflicts with glGenLists & glCallList?
[ "", "c++", "c", "opengl", "" ]
We decided to use Linq To SQL for our Data Layer on our most recent project. We have a functional solution, that so far has handled everything we have thrown at it, with one major problem. We have to code the same method over and over again to retrieve just slightly different result sets from our database. As an example: ``` public List<TeamBE> GetTeamsBySolutionID(Guid SolutionID) { List<TeamBE> teams = new List<TeamBE>(); Esadmin db = new Esadmin(_connectionString); var qry = (from teamsTable in db.Teams join solutionsTable in db.Solutions on teamsTable.SolutionID equals solutionsTable.SolutionID where teamsTable.SolutionID == SolutionID select new { teamsTable, solutionsTable.SolutionName }); foreach (var result in qry) { TeamBE team = new TeamBE(); team.TeamID = result.teamsTable.TeamID; team.Description = result.teamsTable.Description; team.Status = result.teamsTable.Status; team.LastModified = result.teamsTable.LastModified; team.SolutionID = result.teamsTable.SolutionID; team.SolutionName = result.SolutionName; team.Name = result.teamsTable.Name; team.LocationLevel = result.teamsTable.LocationLevel; team.AORDriven = result.teamsTable.AoRDriven; team.CriteriaID = result.teamsTable.CriteriaID ?? Guid.Empty; teams.Add(team); } return teams; } public TeamBE GetTeamByID(Guid TeamID) { Esadmin db = new Esadmin(_connectionString); TeamBE team = new TeamBE(); var qry = (from teamsTable in db.Teams join solutionsTable in db.Solutions on teamsTable.SolutionID equals solutionsTable.SolutionID where teamsTable.TeamID == TeamID select new { teamsTable, solutionsTable.SolutionName }).Single(); team.TeamID = qry.teamsTable.TeamID; team.Description = qry.teamsTable.Description; team.Status = qry.teamsTable.Status; team.LastModified = qry.teamsTable.LastModified; team.SolutionID = qry.teamsTable.SolutionID; team.SolutionName = qry.SolutionName; team.Name = qry.teamsTable.Name; team.LocationLevel = qry.teamsTable.LocationLevel; team.AORDriven = qry.teamsTable.AoRDriven; team.CriteriaID = qry.teamsTable.CriteriaID ?? Guid.Empty; return team; } ``` And on and on ad nauseum. Is there is a way to pass Linq results as a parameter to a function, so I can place my object mappings in one function, and not repeat myself so much?
I took a quick stab at it. Probably doesn't compile (Especially the "from teamsTalbe in teams), but the idea is you can factor out something that returns an IQueryable<>. You're IQueryable returns an anonymous type though, which wouldn't work. So you may need to create an explicit type to use in place of 'select new { teamsTable, solutionsTable.SolutionName }' ``` public List<TeamBE> GetTeamsBySolutionID(int solutionID) { Esadmin db = new Esadmin(_connectionString); return GetTeamsBy(db, _GetTeamsBySolutionID(db, solutionID)); } IQueryable<Team> _GetTeamsBySolutionID(Esadmin db, int solutionID) { return from teamsTable in db.Teams where teamsTable.SolutionID == SolutionID select teamsTable; } List<TeamBE> GetTeamsBy(Esadmin db, IQueryable<Team> teams) { List<TeamBE> teams = new List<TeamBE>(); var qry = (from teamsTable in teams join solutionsTable in db.Solutions on teamsTable.SolutionID equals solutionsTable.SolutionID select new { teamsTable, solutionsTable.SolutionName }); foreach (var result in qry) { TeamBE team = new TeamBE(); team.TeamID = result.teamsTable.TeamID; team.Description = result.teamsTable.Description; team.Status = result.teamsTable.Status; team.LastModified = result.teamsTable.LastModified; team.SolutionID = result.teamsTable.SolutionID; team.SolutionName = result.SolutionName; team.Name = result.teamsTable.Name; team.LocationLevel = result.teamsTable.LocationLevel; team.AORDriven = result.teamsTable.AoRDriven; team.CriteriaID = result.teamsTable.CriteriaID ?? Guid.Empty; teams.Add(team); } return teams; } ```
I think you could declare your `qry` variable as `IEnumerable<YourDataTypeEntity>` and pass that to a method. I tend to like doing it as a constructor: ``` class MyDataType { public MyDataType() {} public MyDataType(MyDataTypeEntity mdte) { // set properties and fields here } // ... } ```
Making Linq To SQL DRY
[ "", "c#", ".net", "linq", "linq-to-sql", ".net-3.5", "" ]
I have some C# unit tests that perform some float/double operations and I would like to unit test them. Assert.AreEqual is insufficient because of rounding errors. Take unit conversion as an example. 10.5 meters to feet has a conversion factor of 3.281 so I get 34.4505. Using a more accurate conversion factor gives me 34.4488189. I want to test this within, say, 0.1 (so 34.3488-34.5488 would pass the test). I could certain manually test the value with a tolerance in my unit test but that's highly repetitive and the failure message wouldn't be very descriptive (again without having to write my own Assert failure message): ``` Assert.IsTrue(Math.Abs(34.4488189 - value) < 0.1); ``` **How can I unit test my float operations to within a certain error tolerance?** I cannot find any Assert classes that do this that come with VS. Am I missing it or do I have to roll my own? **Are there standard practices in testing floats/doubles to keep in mind?**
Assert.AreEqual in MSTest has overloads that accept a delta (error tolerance) parameter: ``` public static void AreEqual (double expected, double actual, double delta) ``` for example: ``` Assert.AreEqual(34.4488189, value, 0.1); ``` or, for the smallest possible tolerance: ``` Assert.AreEqual(34.4488189, value, double.Epsilon); ```
You could take a look at the [NUnit](http://sourceforge.net/projects/nunit) framework: ``` //Compare Float values Assert.AreEqual(float expected, float actual, float tolerance); Assert.AreEqual(float expected, float actual, float tolerance, string message); //Compare Double values Assert.AreEqual(double expected, double actual, double tolerance); Assert.AreEqual(double expected, double actual, double tolerance, string message) ``` (Above taken from [this](http://www.code-magazine.com/article.aspx?quickid=0411051&page=2) article) More listed [here](http://www.nunit.org/index.php?p=equalityAsserts&r=2.2.7).
Unit testing float operations in Visual Studio 2008 Pro
[ "", "c#", "unit-testing", ".net-3.5", "floating-point", "" ]
Python has a singleton called [`NotImplemented`](https://docs.python.org/2/library/constants.html#NotImplemented). Why would someone want to ever return `NotImplemented` instead of raising the [`NotImplementedError`](https://docs.python.org/2/library/exceptions.html#exceptions.NotImplementedError) exception? Won't it just make it harder to find bugs, such as code that executes invalid methods?
It's because `__lt__()` and related comparison methods are quite commonly used indirectly in list sorts and such. Sometimes the algorithm will choose to try another way or pick a default winner. Raising an exception would break out of the sort unless caught, whereas `NotImplemented` doesn't get raised and can be used in further tests. <http://jcalderone.livejournal.com/32837.html> To summarise that link: > "`NotImplemented` signals to the runtime that it should ask someone else to satisfy the operation. In the expression `a == b`, if `a.__eq__(b)` returns `NotImplemented`, then Python tries `b.__eq__(a)`. If `b` knows enough to return `True` or `False`, then the expression can succeed. If it doesn't, then the runtime will fall back to the built-in behavior (which is based on identity for `==` and `!=`)."
**Because they have different use cases.** Quoting the docs (Python 3.6): **[NotImplemented](https://docs.python.org/3.6/library/constants.html#NotImplemented)** > should be returned by the binary special methods (e.g. `__eq__()`, > `__lt__()`, `__add__()`, `__rsub__()`, etc.) to indicate that the operation is not implemented with respect to the other type **[exception NotImplementedError](https://docs.python.org/3.6/library/exceptions.html#NotImplementedError)** > [...] In user defined base > classes, abstract methods should raise this exception when they > require derived classes to override the method, or while the class is > being developed to indicate that the real implementation still needs > to be added. See the links for details.
Why return NotImplemented instead of raising NotImplementedError
[ "", "python", "exception", "" ]
I'm trying to show a list of all users but am unsure how to go about this using the MVC model. I can obtain the list of all users via the `Membership.GetAllUsers()` method however if I try to pass this to the view from the `ActionResult`, I'm told that Model is not enumerable.
You have to set the View to accept an object of type MembershipUserCollection ``` <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MembershipUserCollection>" %> ``` In your action: ``` public ActionResult GetUsers() { var users = Membership.GetAllUsers(); return View(users); } ``` then you can write in your view something like: ``` <ul> <%foreach (MembershipUser user in Model){ %> <li><%=user.UserName %></li> <% }%> </ul> ```
In your view page, on top, you need to set the type of the view page. IE: On the top of your View, in the first line of the markup, you'll see something like this: ``` Inherits="System.Web.Mvc.ViewPage" ``` Change that to be: ``` Inherits="System.Web.Mvc.ViewPage<MembershipUserCollection>" ``` or whatever the type you're trying to pass to the view. The "Model" object will now be of type MembershipUserCollection which you can safely iterate over.
ASP.NET MVC List All Users
[ "", "c#", "asp.net-mvc", "asp.net-membership", "" ]
I am porting a Delphi application to C# and I've run into a problem. The Delphi app records the time into a log file, which then gets read back into the program. But the format of the time it records confuses me. I can find no .Net library to convert it properly. Delphi recorded time in log file: 976129709 (this gets converted to 1/14/2009 5:53:26 PM in the Delphi code) ``` //Here is the Delphi code which records it: IntToStr(DirInfo.Time); //Here is the Delphi code which reads it back in: DateTimeToStr(FileDateToDateTime(StrToInt(stringTime)); ``` Anybody have any ideas how I can read this in .Net?
Delphi's TSearchRec.Time format is the old DOS 32-bit date/time value. As far as I know there's no built-in converter for it, so you'll have to write one. For example: ``` public static DateTime DosDateToDateTime(int DosDate) { Int16 Hi = (Int16)((DosDate & 0xFFFF0000) >> 16); Int16 Lo = (Int16)(DosDate & 0x0000FFFF); return new DateTime(((Hi & 0x3F00) >> 9) + 1980, (Hi & 0xE0) >> 5, Hi & 0x1F, (Lo & 0xF800) >> 11, (Lo & 0x7E0) >> 5, (Lo & 0x1F) * 2); } ```
[Here is description of different date/time formats](http://blogs.msdn.com/oldnewthing/archive/2003/09/05/54806.aspx) (Delphi's native TDateTime is OLE Automation date format). According to this, you need [System.DateTime.FromFileTime()](http://msdn.microsoft.com/en-us/library/system.datetime.fromfiletime.aspx) and [System.DateTime.ToFileTime()](http://msdn.microsoft.com/en-us/library/system.datetime.tofiletime.aspx) + [DosDateTimeToFileTime()](http://msdn.microsoft.com/en-us/library/ms724247(VS.85).aspx) and [FileTimeToDosDateTime()](http://msdn.microsoft.com/en-us/library/ms724274(VS.85).aspx) functions. Actually, this is conversion in two-steps.
Need Help to Converting Delphi Time to .Net Time
[ "", "c#", ".net", "delphi", "datetime", "" ]
I have been optimising memory performance on a Windows Mobile application and have encountered some differences in behaviour between **VirtualAlloc** [on Win32](http://msdn.microsoft.com/en-us/library/windows/desktop/aa366887.aspx) and [Windows CE](http://msdn.microsoft.com/en-us/library/ee488564.aspx). Consider the following test: ``` // Allocate 64k of memory BYTE *a = (BYTE*)VirtualAlloc(0, 65536, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); // Allocate a second contiguous 64k of memory BYTE *b = (BYTE*)VirtualAlloc(a+65536, 65536, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); BYTE *c = a + 65528; // Set a pointer near the end of the first allocation BOOL valid1 = !IsBadWritePtr(c, 8); // Expect TRUE BOOL valid2 = !IsBadWritePtr(c+8, 4088); // Expect TRUE BOOL valid3 = !IsBadWritePtr(c, 4096); // TRUE on Win32, FALSE on WinCE ``` The code "allocates" 4096 of data starting at "c". On Win32 this works. I can find no mention in the **VirtualAlloc** documentation whether it is legal or coincidence but there are many examples of code that I have found via google that expect this behaviour. On Windows CE 5.0/5.2 if I use the memory block at "c", in 99% of cases there are no problems, however on some (not all) Windows Mobile 6 devices, **ReadFile** & **WriteFile** will fail with error 87 (The parameter is incorrect.). I assume **ReadFile** is calling **IsBadWritePtr** or similar and return false due to this. If I perform two **ReadFile** calls then everything works fine. (There may of course be other API calls that will also fail.) I am looking for a way to extend the memory returned by **VirtualAlloc** so that I can make the above work. Reserving a large amount of memory on Windows CE is problematic as each process only gets 32MB and due to other items being loaded it is not possible to reserve a large region of memory without causing other problems. (It is possible to reserve a larger amount of memory in the shared region but this also has other problems.) Is there a way to get **VirtualAlloc** to enlarge or combine regions without reserving it up front? I suspect it may be problematic given the following examples: ``` HANDLE hHeap1 = HeapCreate(0, 0, 0); // Heap defaults to 192k BYTE * a1 = (BYTE*)HeapAlloc(hHeap1, 0, 64000); // +96 bytes from start of heap BYTE * b1 = (BYTE*)HeapAlloc(hHeap1, 0, 64000); // +16 bytes from end of a1 BYTE * c1 = (BYTE*)HeapAlloc(hHeap1, 0, 64000); // +16 bytes from end of b1 BYTE * d1 = (BYTE*)HeapAlloc(hHeap1, 0, 64000); // +4528 bytes from end of c1 HANDLE hHeap2 = HeapCreate(0, 4*1024*1024, 4*1024*1024); // 4MB Heap BYTE * a2 = (BYTE*)HeapAlloc(hHeap2, 0, 64000); // +96 bytes from start of heap BYTE * b2 = (BYTE*)HeapAlloc(hHeap2, 0, 64000); // +16 bytes from end of a2 BYTE * c2 = (BYTE*)HeapAlloc(hHeap2, 0, 64000); // +16 bytes from end of b2 BYTE * d2 = (BYTE*)HeapAlloc(hHeap2, 0, 64000); // +16 bytes from end of c2 ```
No, it's not possible.
I wouldn't trust IsBadWritePtr, see this: <http://support.microsoft.com/kb/960154> I think it does something like tries to write to the memory, and sees if it gets a hardware exception. It handles the exception and then returns true or false. But, I've heard that some hardware will only raise an exception once for an attempt to write to one page, or something like that. Is it not possible for you to VirtualAlloc without a MEM\_COMMIT, so you just reserve the virtual memory addresses. Then when you actually want to use the memory, call VirtualAlloc again to do the commit. As you already reserved the pages, you should be able to commit them contiguously. You say you want to do it without reserving up front. But, what's wrong with reserving up front. Reserving doesn't actually use any physical memory, it reserves a range of virtual addresses, it'll only use physical memory when you commit the pages.
Contiguous VirtualAlloc behaviour on Windows Mobile
[ "", "c++", "windows-mobile", "memory-management", "windows-ce", "virtualalloc", "" ]
How can I make Unity not to throw `ResolutionFailedException` if `Resolve` fails? Is there something like `TryResolve<IMyInterface>`? ``` var container = new UnityContainer(); var foo = container.TryResolve<IFoo>(); Assert.IsNull(foo); ```
This has been an issue on the codeplex site, you can find the code here (look at the bottom of that thread and they have made an extension method...very handy) <http://unity.codeplex.com/Thread/View.aspx?ThreadId=24543> and the you can use code like this: ``` if (container.CanResolve<T>() == true) { try { return container.Resolve<T>(); } catch (Exception e) { // do something else } } ``` `CanResolve` is that extension method. I'm actually registering that extension upon creation of the container...something like this: ``` private void CreateContainer() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = // path to config file // get section from config code goes here IUnityContainer container = new UnityContainer(); container.AddNewExtension<UnityExtensionWithTypeTracking>(); section.Containers.Default.Configure(container); } ```
Also note that, if you're using [Unity 2.0](http://msdn.microsoft.com/en-us/library/ee651008%28v=PandP.20%29.aspx) you can use the new [IsRegistered()](http://msdn.microsoft.com/en-us/library/ff661604%28PandP.20%29.aspx) method and it's [generic version](http://msdn.microsoft.com/en-us/library/ff661003%28v=PandP.20%29.aspx) as well.
Is there TryResolve in Unity?
[ "", "c#", "unity-container", "ioc-container", "" ]
When you drag a block of text from a Word document into a Java text component, the text is removed from the Word document. This is obviously undesirable in some cases. Is there a way I can prevent Word from removing the text, while still copying it into the Java text component?
Return `false` from `TransferHandler.importData(JComponent comp,Transferable t)`. You can keep the data but you tell the drag system that you didn't take it.
Try holding down ALT, CTL, or SHIFT (I forget) while dragging. I believe this changes the default behavior of your cursor from cut -> copy. You may be able to set the default Drop action in your JText component to only allow copy, I know you can do that in SWT.
Dragging text from a Word document to a Java text component?
[ "", "java", "swing", "ms-word", "jtextcomponent", "" ]
I have an input form with two textareas allowing a user to type in words separated by commas in each. ``` <form action="http://www.example.com/output.php" method="post"> <table border="0"> <tr> <td> <h3 class="title">Prefix</h3> <textarea cols="34" rows="8" name="cat[]"></textarea></td> <td> <h3 class="title">Suffix</h3> <textarea cols="34" rows="8" name="cat[]"></textarea></td> </tr> </table> Enter words separated by a comma. <input type="submit" value="Go" /> </form> ``` It then passes these to the output form which explodes the words from the commas and then concatenates them together until all possible permutations of the words are created. It then prints out the results into a textarea. My problem is that the output (whilst correctly formatted and have the linebreaks in between each permutation) has a br tag at the end of each line. Eg. ``` testtest2<br /> testtest2<br /> testtest4<br /> testetest2<br /> testetest2<br /> testetest4<br /> ``` Output form: ``` $cat = $_POST['cat']; //trait set for textbox inputs foreach(array_keys($cat) as $key){ $cat[$key] = explode(",", str_replace(' ','',$cat[$key])); } function showCombinations($string, $traits, $i) { if ($i >= count($traits)) echo trim($string)."\n"; else { foreach ($traits[$i] as $trait) showCombinations("$string$trait", $traits, $i + 1); } } ?> <form name=form1 method=post action=''''> <textarea><?php ShowCombinations('', $cat, 0); ?></textarea> </form> ``` 1. When I remove the textarea tags for the output it works fine. 2. When I leave the textarea tags and remove/replace echo trim($string)."\n"; with "\r" or 'n' or "\n\r", the disappears but I also lose the linebreak 3. Replace echo trim($string)."\n"; with echo nl2br($string); then same result as 2. 4. Replace with echo nl2br($string)."\n"; then same result as 1. Would appreciate any help. My noob brain is about to implode.
I'll preface this by saying I use Blogger not Wordpress but I imagine there are similarities. In Blogger there is a setting to convert line breaks into `<br>` tags. I guess it's convenient if you're not putting code snippets and the like in (if you're blogging about cats or something) but not so much for programming. I had to turn it off and put in my paragraph tags, etc manually. Here is one [less than ideal solution](http://sltaylor.co.uk/blog/get-rid-of-br-tags-inserted-by-wordpress/), which also mentions the issue of Wordpress inserting `<br>` tags in forms.
I think the `<br />` tag is what you want in this case. Newline characters like \n and \r don't do anything in HTML - all whitespace, including newlines, is ignored. The `<br />` tag is essentially the HTML equivalent - it stands for "break". I don't know too much about PHP specifically, so I don't know why it's putting the `<br />` there for you automatically, but that's the correct HTML for what you're describing. Technically, there are better ways to format your output then using those tags, but that's more of an advanced topic. If you are a bit new to this, like you said, then just get it working this way for now, and then maybe sometime down the road you can learn about proper semantic HTML markup, CSS styling, etc.
<br /> tags appearing in textarea output
[ "", "php", "html", "wordpress", "" ]
I am searching for records in a table as follows: ``` SELECT Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10; ``` Now, I am adding LIMIT to maintain my paging. But when user searches for word 'prashant' then total records I have is 124 for 'prashant'. But as the limit applied to the query so it only fetches 10 records in my PHP script and when I am count the mysql variable in PHP code it returns total records found is 10. So basically I want to count and Limit using a single query, by making some modification in the above query, I want the total count (124) of records. I don't want to run a separate count(\*) query for just counting the total result found by the query. Thanks.
``` SELECT SQL_CALC_FOUND_ROWS Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10; # Find total rows SELECT FOUND_ROWS(); ``` [more info](http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows)
MySQL supports doing this using [`SQL_CALC_FOUND_ROWS`](https://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_found-rows) as mentioned by Ionut. However, it turns out that [in many cases](http://www.mysqlperformanceblog.com/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/) it's actually faster to do it the old fashioned way using two statements, where one of them is a regular `count()`. This does however require that the counting can be done using an index scan, which won't be the case for this very query, but I thought I'd mention it anyway.
How to count and limit record in a single query in MYSQL?
[ "", "php", "mysql", "count", "" ]
I'm working on some existing c++ code that appears to be written poorly, and is very frequently called. I'm wondering if I should spend time changing it, or if the compiler is already optimizing the problem away. I'm using Visual Studio 2008. Here is an example: ``` void someDrawingFunction(....) { GetContext().DrawSomething(...); GetContext().DrawSomething(...); GetContext().DrawSomething(...); . . . } ``` Here is how I would do it: ``` void someDrawingFunction(....) { MyContext &c = GetContext(); c.DrawSomething(...); c.DrawSomething(...); c.DrawSomething(...); . . . } ```
If you're sure it's a performance problem, change it. If GetContext is a function call (as opposed to a macro or an inline function), then the compiler is going to HAVE to call it every time, because the compiler can't necessarily see what it's doing, and thus, the compiler probably won't know that it can eliminate the call. Of course, you'll need to make sure that GetContext ALWAYS returns the same thing, and that this 'optimization' is safe.
Don't guess at where your program is spending time. **Profile first** to find your bottlenecks, then optimize those. As for `GetContext()`, that depends on how complex it is. If it's just returning a class member variable, then chances are that the compiler will inline it. If `GetContext()` has to perform a more complicated operation (such as looking up the context in a table), the compiler probably isn't inlining it, and you may wish to only call it once, as in your second snippet. If you're using GCC, you can also tag the `GetContext()` function with the [`pure` attribute](http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html#index-g_t_0040code_007bpure_007d-function-attribute-2256). This will allow it to perform more optimizations, such as [common subexpression elimination](http://en.wikipedia.org/wiki/Common_subexpression_elimination).
c++ optimization
[ "", "c++", "optimization", "performance", "" ]
I have a datepicker control setup using the JQuery UI, I am also using the JQuery UI themes which provide a bunch of default icons that I want to use. The DatePicker allows for specifying a specific image, i.e.: ``` <script type="text/javascript"> $(document).ready(function() { $("#DateFrom").datepicker({ showOn: 'button', buttonImageOnly: true, buttonImage: 'images/ui-icon-calendar.png' }); }); </script> ``` To display an icon from the icon set you use something like: ``` <span class="ui-icon ui-icon-calendar"></span> ``` Is there an easy to integrate the two or do I just need to hack out the styles/images manually?
I'm afraid you'll have to do that manually. By default, the Datepicker plugin uses the following HTML to insert the specified `buttonImage`: ``` <img title="..." alt="..." src="images/ui-icon-calendar.png" class="ui-datepicker-trigger"> ``` By the way, you might want to use... ``` $(function() { // your code here }); ``` ...instead of... ``` $(document).ready(function() { // your code here }); ```
I got it working by doing this ``` $("#DateFrom").datepicker({ showOn: 'button' }).next('button').button({ icons: { primary: 'ui-icon-calendar' }, text:false }); ``` Just modifies the button that it inserts next to your input for the calendar. By default they throw three ellipses in the text, so I remove that as well.
Use JQuery UI Datepicker with Icons from Jquery UI Theme
[ "", "javascript", "css", "jquery-ui", "" ]
I have a text file that I want to edit using Java. It has many thousands of lines. I basically want to iterate through the lines and change/edit/delete some text. This will need to happen quite often. From the solutions I saw on other sites, the general approach seems to be: * Open the existing file using a BufferedReader * Read each line, make modifications to each line, and add it to a StringBuilder * Once all the text has been read and modified, write the contents of the StringBuilder to a new file * Replace the old file with the new file This solution seems slightly "hacky" to me, especially if I have thousands of lines in my text file. Anybody know of a better solution?
I haven't done this in Java recently, but writing an entire file into memory seems like a bad idea. The best idea that I can come up with is open a temporary file in writing mode at the same time, and for each line, read it, modify if necessary, then write into the temporary file. At the end, delete the original and rename the temporary file. If you have modify permissions on the file system, you probably also have deleting and renaming permissions.
if the file is just a few thousand lines you should be able to read the entire file in one read and convert that to a String. You can use apache IOUtils which has method like the following. ``` public static String readFile(String filename) throws IOException { File file = new File(filename); int len = (int) file.length(); byte[] bytes = new byte[len]; FileInputStream fis = null; try { fis = new FileInputStream(file); assert len == fis.read(bytes); } catch (IOException e) { close(fis); throw e; } return new String(bytes, "UTF-8"); } public static void writeFile(String filename, String text) throws IOException { FileOutputStream fos = null; try { fos = new FileOutputStream(filename); fos.write(text.getBytes("UTF-8")); } catch (IOException e) { close(fos); throw e; } } public static void close(Closeable closeable) { try { closeable.close(); } catch(IOException ignored) { } } ```
Modify a .txt file in Java
[ "", "java", "" ]
I have a string read from another source such as "\b\bfoo\bx". In this case, it would translate to the word "fox" as the first 2 \b's are ignored, and the last 'o' is erased, and then replaced with 'x'. Also another case would be "patt\b\b\b\b\b\b\b\b\b\bfoo" should be translated to "foo" I have come up with something using String.Replace, but it is complex and I am worried it is not working correctly, also it is creating a lot of new string objects which I would like to avoid. Any ideas?
Probably the easiest is to just iterate over the entire string. Given your inputs, the following code does the trick in 1-pass ``` public string ReplaceBackspace(string hasBackspace) { if( string.IsNullOrEmpty(hasBackspace) ) return hasBackspace; StringBuilder result = new StringBuilder(hasBackspace.Length); foreach (char c in hasBackspace) { if (c == '\b') { if (result.Length > 0) result.Length--; } else { result.Append(c); } } return result.ToString(); } ```
The way I would do it is low-tech, but easy to understand. Create a stack of characters. Then iterate through the string from beginning to end. If the character is a normal character (non-slash), push it onto the stack. If it is a slash, and the next character is a 'b', pop the top of the stack. If the stack is empty, ignore it. At the end, pop each character in turn, add it to a StringBuilder, and reverse the result.
Is there a better way than String.Replace to remove backspaces from a string?
[ "", "c#", "string", "" ]
I just run into the weirdest thing I've ever encounter. Consider this test page: ``` <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title></title> <script language=javascript> function test(myParameter) { alert(myParameter); } </script> </head> <body> <input type="button" value="Strange" onclick="javascript: test(044024);" /> <input type="button" value="Ok" onclick="javascript: test('044024');" /> </body> </html> ``` If I click the "strange" button, I get **18452**, if I click the "ok" button I get **044024** Does anyone know what is happening and explain it to me?
Javascript is interpreting the symbol 044024 as an octal value because of the leading 0. 044024 oct to dec is 18452
Numbers prefixed with 0 are considered to be in octal (base 8)
Can someone help me understand why this is happening?
[ "", "javascript", "html", "" ]
Why is class based OO so popular instead of prototype based OO? Do they teach the latter in schools? Though Javascript is prototype based, most people use it mostly functionally, or via frameworks that try to emulate a class based system. I know that Sun has had some research on [Self](http://research.sun.com/self/) - is there any other source of knowledge on prototype based oo? preferably something that is accessible for self learned. I found a book that contains published papers: [Prototype-Based Programming: Concepts, Languages and Applications](https://rads.stackoverflow.com/amzn/click/com/9814021253) Has anyone read it? -- So I gave the bounty for the answer that gave me most. Still, I'm not really satisfied. I would have liked to hear much more techical answers. Maybe I didn't explain myself well.
The advantage of prototypal inheritance is that it potentially allows fancy metaprogramming in a straightforward way because the prototype chain is easily manipulated. This is a rather academic advantage because metaprogramming is the wrong answer 99% of the time. As an example, you could have a Javascript Key-Value Observer style data manipulation layer with a special DSL that transparently switched between a local SQLite backing when offline and a REST based server store when online via prototype swapping. I'm not sure it's the best way to do this, but it's the best I can come up with this late. It's not the sort of thing you generally want to do in project code since this sort of indirection is hell to debug once you start getting it going on multiple layers, but it's not bad when you keep it in a library. Another less helpful advantage is that it allows you to design your own class system. I say less helpful because more or less all javascript libraries have their own slightly incompatible approach to how 'classes' are put together. There are a lot of people replying who are mixing the inheritance model with the languages implemented in that model. The fact that javascript is dynamic and weakly typed and thus hard to tool has nothing to do with it being a prototypal language.
If you're looking for someone to point out the advantages/disadvantages of each as an explanation for their popularity, I think you're falling for a fallacy which is for some reason very common in technology – that popularity has something to do with some absolute measure of quality. The truth is a lot more bland – class-based OO is popular because Java uses classic OO, and Sun spent millions of dollars and a very long time building the popularity of Java – making sure people know it's used successfully in corporations, taught widely in universities, and on high school AP tests. Prototypal/classical OO are just different ways of organizing your ideas. You can implement either one in languages that don't support it natively ([Python](http://mail.python.org/pipermail/python-list/2000-September/053605.html) and [Java](http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html) come to mind, and [JavaScript](http://justin.harmonize.fm/index.php/2009/01/cobra-a-little-javascript-class-library/) on the other side). In classical OO, you define an abstract hierarchy of classes for your objects, and then actually work with instances of those classes. In prototypal inheritance, you create a hierarchy of object instances. Although I imagine it might be a bit heretical in both camps, I don't see a reason you couldn't mix the two...
What are the advantages that prototype based OO has over class based OO?
[ "", "javascript", "oop", "class", "programming-languages", "selflanguage", "" ]
I am writing a Wordpress plugin and need to go through a number of posts, grab the data from them (for the most part title, permalink, and content), and apply processing to them without displaying them on the page. **What I've looked at:** I've looked at [get\_posts()](http://codex.wordpress.org/Template_Tags/get_posts) for getting the posts, and then ``` getting title via the_title(), content via the_content(), and permalink via the_permalink() ``` Keep in mind that I need this data after all filters had already been applied, so that I get the exact data that would be displayed to the user. Each of the functions above seems to apply all necessary filters and do some postprocessing already, which is great. **The Problem:** The problem is all these functions, at least in WP 2.7.1 (latest released version right now) by default just echo everything and don't even return anything back. the\_title() actually supports a flag that says do not print and return instead, like so ``` the_title(null, null, false) ``` The other 2, however, don't have such flags, and such inconsistency is quite shocking to me. I've looked at what each of the\_() functions does and tried to pull this code out so that I can call it without displaying the data (this is a hack in my book, as the behavior of the\_() functions can change at any time). This worked for permalink but for some reason get\_the\_content() returns NULL. There has to be a better way anyway, I believe. **So, what is the best way to pull out these values without printing them?** Some sample code ``` global $post; $posts = get_posts(array('numberposts' => $limit)); foreach($posts as $post){ $title = the_title(null, null, false); // the_title() actually supports a "do not print" flag $permalink = apply_filters('the_permalink', get_permalink()); // thanks, WP, for being so consistent in your functions - the_permalink() just prints /s $content = apply_filters('the_content', get_the_content()); // this doesn't even work - get_the_content() returns NULL for me print "<a href='$permalink'>$title</a><br>"; print htmlentities($content, ENT_COMPAT, "UTF-8"). "<br>"; } ``` P.S. I've also looked at [What is the best method for creating your own Wordpress loops?](https://stackoverflow.com/questions/570152/what-is-the-best-method-for-creating-your-own-wordpress-loops) and while it deals with an already obvious way to cycle through posts, the solution there just prints this data. **UPDATE:** I've opened a ticket with Wordpress about this. <http://core.trac.wordpress.org/ticket/9868>
OK, I got it all sorted now. Here is the final outcome, for whoever is interested: * Each post's data can be accessed via iterating through the array returned by get\_posts(), but this data will just be whatever is in the database, without passing through any intermediate filters * The preferred way is to access data using get\_the\_ functions and them wrapping them in an call to apply\_filters() with the appropriate filter. This way, all intermediate filters will be applied. `apply_filters('the_permalink', get_permalink())` * the reason why `get_the_content()` was returning an empty string is that apparently a special call to `setup_postdata($post);` needs to be done first. Then `get_the_content()` returns data properly Thanks everyone for suggestions.
Most functions the\_stuff() in WP that echo something have their get\_the\_stuff() counterpart that *returns* something. Eg `get_the_title()`, `get_permalink()`...
Best way to get post info into variables without displaying them in Wordpress
[ "", "php", "wordpress", "post", "" ]
I am helping s.o. out over mail to start with c#, and I would like to recommend VS express for it (from [this](http://www.microsoft.com/express/vcsharp/) link) It's not clear to me which version of .NET ships with it, and if there will be an SDK with a commandline compiler (cs.exe).. I am using VS2008 and not too keen to test it all on my system. tx!
The command line compiler is part of the standard .NET framework. Express 2005 has been retired, AFAIK. The current C# express download is 2008 Express with Service Pack 1, which includes: * .NET Framework 3.5 SP1 (and all previous service packs, such as 2.0 SP2, 3.0 SP1, etc) * Visual C# Express 2008 SP1
VS 2008 Express any language has the following .Net Versions * .Net 2.0 SP1 * .Net 3.5 The .Net SDK will be included with the install. For the C# version, it will include the 3.0 C# language compiler. The 2.0 version will also be available in the 2.0 install directory.
Which version of sdk and .NET come together with visual studio express c# 2008?
[ "", "c#", "visual-studio-2008", "" ]
I'm trying to join multiple tables, but one of the tables has multiple records for a partid with different dates. I want to get the record with the most recent date. Here are some example tables: ``` Table: MyParts Partid Partnumber Description 1 ABC-123 Pipe 2 ABC-124 Handle 3 ABC-125 Light Table: MyPrices Partid Price PriceDate 1 $1 1/1/2005 1 $2 1/1/2007 1 $3 1/1/2009 2 $2 1/1/2005 2 $4 1/1/2006 2 $5 1/1/2008 3 $10 1/1/2008 3 $12 1/1/2009 ``` If I was just wanted to find the most recent price for a certain part I could do: ``` SELECT * FROM MyPrice WHERE PriceDate = (SELECT MAX(PriceDate) FROM MyPrice WHERE Partid = 1) ``` However I want to do a join first and get back the correct price for all parts not just one. This is what I have tried: ``` SELECT * FROM MyParts LEFT JOIN MyPrice ON MyParts.Partid = MyPrice.Partid WHERE MyPart.PriceDate = (SELECT MAX(PriceDate) FROM MyPrice) ``` The results are wrong as it takes the highest price date of the entire table. ``` SELECT * FROM MyParts LEFT JOIN MyPrice ON MyParts.Partid = MyPrice.Partid WHERE MyPart.PriceDate = (SELECT MAX(PriceDate) FROM MyPrice WHERE MyPrice.Partid = MyParts.Partid) ``` That errors out. What can I do to get the results I want.
Try this: ``` Select *, Price = (Select top 1 Price From MyPrices where PartID = mp.PartID order by PriceDate desc ) from MyParts mp ```
Here's another way to do it without subqueries. This method will often outperform others, so it's worth testing both methods to see which gives the best performance. ``` SELECT PRT.PartID, PRT.PartNumber, PRT.Description, PRC1.Price, PRC1.PriceDate FROM MyParts PRT LEFT OUTER JOIN MyPrices PRC1 ON PRC1.PartID = PRT.PartID LEFT OUTER JOIN MyPrices PRC2 ON PRC2.PartID = PRC1.PartID AND PRC2.PriceDate > PRC1.PriceDate WHERE PRC2.PartID IS NULL ``` This will give multiple results if you have two prices with the same EXACT PriceDate (Most other solutions will do the same). Also, I there is nothing to account for the last price date being in the future. You may want to consider a check for that regardless of which method you end up using.
T-SQL Subquery Max(Date) and Joins
[ "", "sql", "sql-server", "t-sql", "join", "subquery", "" ]
I'm working on a form validation script at work and am having some difficulty. The form is meant to make sure that the user fills out a name, a real-looking email, a category (fromt he drop down) and a question: This names the form and gathers all the data up from the form: ``` <script> function checkForm(form1) { name = document.getElementById("FieldData0").value; category = document.getElementById("FieldData3").value; question = document.getElementById("FieldData1").value; email = document.getElementById("FieldData2").value; ``` This checks to see that something is in the "name" field. It works fine and validates exactly like it should, displaying the error text: ``` if (name == "") { hideAllErrors(); document.getElementById("nameError").style.display = "inline"; document.getElementById("FieldData0").select(); document.getElementById("FieldData0").focus(); return false; ``` This also works just like it should. It checks to see if the email field is empty and if it is empty,displays error text and selects that field: ``` } else if (email == "") { hideAllErrors(); document.getElementById("emailError").style.display = "inline"; document.getElementById("FieldData2").select(); document.getElementById("FieldData2").focus(); return false; } ``` This also works just like it should, makes sure that the questions field isn't empty: ``` else if (question == "") { hideAllErrors(); document.getElementById("questionError").style.display = "inline"; document.getElementById("FieldData1").select(); document.getElementById("FieldData1").focus(); return false; } ``` This one works partially - If no drop down is selected, it will display the error message, but that doesn't stop the form from submitting, it just displays the error text while the form submits: ``` else if (category == "") { hideAllErrors(); document.getElementById("categoryError").style.display = "inline"; document.getElementById("FieldData3").select(); document.getElementById("FieldData3").focus(); return false; } ``` This one doesn't work at all no matter where I put it. I used a variation on the same script last week and it worked fine. This is supposed to check to see that the email entered looks like a real email address: ``` else if (!check_email(document.getElementById("FieldData1").value)) { hideAllErrors(); document.getElementById("emailError2").style.display = "inline"; document.getElementById("FieldData2").select(); document.getElementById("FieldData2").focus(); return false; } Otherwise it lets the form submit: return true; } ``` This checks the email out: ``` function check_email(e) { ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM"; for(i=0; i < e.length ;i++){ if(ok.indexOf(e.charAt(i))<0){ return (false); } } if (document.images) { re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/; re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; if (!e.match(re) && e.match(re_two)) { return (-1); } } } ``` This function hides all errors so the user isn't bombarded with red text. I tried putting in "document.getElementById("emailError").style.display = "none"" but that breaks the whole thing: ``` function hideAllErrors() { document.getElementById("nameError").style.display = "none" document.getElementById("emailError").style.display = "none" document.getElementById("categoryError").style.display = "none" document.getElementById("questionError").style.display = "none" } </script> ``` And the form looks like this: ``` <form onSubmit="return checkForm();" method="post" action="http://www.emailmeform.com/fid.php?formid=303341io4u" name="form1"> <p><div class=error id=nameError>Required: Please enter your name<br/></div><p><strong>Name:</strong> <span></span><br><input type="text" name="FieldData0" id="FieldData0" value="" size="22" tabindex="1" /> <label for="name"></label></p> <p><div class=error id=emailError>Required: Please enter your email address<br/></div> <div class=error id=nameError2>This doesn't look like a real email address, please check and reenter<br/></div> <strong><p>Email:</strong> <span>(will not be published)</span><br><input type="text" name="FieldData2" id="FieldData2" value="" size="22" tabindex="2" /> <label for="email"></label> </p> <div class=error id=categoryError>Please select a category from the drop-down menu<br></div> <p><strong>Category:</strong> <span></span><br> <p><select id="FieldData3" name="FieldData3"> <option value="">Please select a category</option> <option value="a">a</option> <option value="b">b</option> <option value="c">c</option> <option value="d">d</option> <option value="e">e</option> <option value="f">f</option> <option value="other">Other</option> </select><label for="category"></label> <p><div class=error id=questionError>Please type your question in the box below:<br></div><label for="question"><strong><p>Your Question:</strong> <span></span></label><br> <textarea name="FieldData1" id="FieldData1" cols="50" rows="10"></textarea></p> <p><input type="submit" class="btn" value="Submit Question" name="Submit"></p> </div> </form> ``` Is the problem the order that I run the checks? I can't seem to figure this out. Any help would be appreciated.
I've taken the liberty to re-write your javascript to make it more readable and easier to debug. As Marc Bernier mentioned, the dropdown element does not support the `select` function so I put an `if` statement around it to prevent an exception. I've also simplified your `checkEmail` function, it seemed rather convoluted. I renamed it to `isAnInvalidEmail` in order to make the `checkForm` code simpler. You have also incorrectly named the 'emailError2' `div` in your HTML, which would cause another exception in the javascript. Your HTML is rather messy and, in some cases, invalid. There are missing quotes on some attribute values and missing end-tags. You should consider using the [W3C validator](http://validator.w3.org) to ensure your HTML is clean and is standards compliant. I've hosted your code on jsbin: <http://jsbin.com/iyeco> (editable via <http://jsbin.com/iyeco/edit>) Here's the cleaned up Javascript: ``` function checkForm() { hideAllErrors(); var formIsValid = showErrorAndFocusIf('FieldData0', isEmpty, 'nameError') && showErrorAndFocusIf('FieldData2', isEmpty, 'emailError') && showErrorAndFocusIf('FieldData2', isAnInvalidEmail, 'emailError2') && showErrorAndFocusIf('FieldData3', isEmpty, 'categoryError') && showErrorAndFocusIf('FieldData1', isEmpty, 'questionError'); /* For debugging, lets prevent the form from submitting. */ if (formIsValid) { alert("Valid form!"); return false; } return formIsValid; } function showErrorAndFocusIf(fieldId, predicate, errorId) { var field = document.getElementById(fieldId); if (predicate(field)) { document.getElementById(errorId).style.display = 'inline'; if (field.select) { field.select(); } field.focus(); return false; } return true; } function isEmpty(field) { return field.value == ''; } function isAnInvalidEmail(field) { var email = field.value; var ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM"; for(i = 0; i < email.length; i++){ if(ok.indexOf(email.charAt(i)) < 0) { return true; } } re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/; re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; return re.test(email) || !re_two.test(email); } function hideAllErrors() { document.getElementById("nameError").style.display = "none" document.getElementById("emailError").style.display = "none" document.getElementById("emailError2").style.display = "none" document.getElementById("categoryError").style.display = "none" document.getElementById("questionError").style.display = "none" } ``` And the cleaned up HTML: ``` <form onSubmit="return checkForm();" method="post" action="http://www.emailmeform.com/fid.php?formid=303341io4u" name="form1"> <div> <div class="error" id="nameError"> Required: Please enter your name </div> <label for="FieldData0"><strong>Name:</strong></label> <input type="text" name="FieldData0" id="FieldData0" value="" size="22" tabindex="1" /> </div> <div> <div class="error" id="emailError"> Required: Please enter your email address </div> <div class="error" id="emailError2"> This doesn't look like a real email address, please check and reenter </div> <label for="FieldData2"><strong>Email:</strong>(will not be published)</label> <input type="text" name="FieldData2" id="FieldData2" value="" size="22" tabindex="2" /> </div> <div> <div class="error" id="categoryError"> Please select a category from the drop-down menu </div> <label for="FieldData3"><strong>Category:</strong></label> <select id="FieldData3" name="FieldData3"> <option value="">Please select a category</option> <option value="a">a</option> <option value="b">b</option> <option value="c">c</option> <option value="d">d</option> <option value="e">e</option> <option value="f">f</option> <option value="other">Other</option> </select> </div> <div> <div class="error" id="questionError"> Please type your question in the box below: </div> <label for="FieldData1"><strong>Your Question:</strong></label> <textarea name="FieldData1" id="FieldData1" cols="50" rows="10"></textarea> </div> <input type="submit" class="btn" value="Submit Question" name="Submit"> </form> ```
Regarding the error on the drop-down, don't call this line: document.getElementById("FieldData1").select(); I seem to recall having the exact same problem a few weeks ago.
inline javascript form validation
[ "", "javascript", "validation", "forms", "" ]
I wonder what options there are for templating in PHP? If the templating code can be very similar to PHP, it'd be best.
I can recommend [Smarty](http://www.smarty.net/) The template is a plain HTML with some extra markup for PHP calls. The template compiles itself to a PHP and runs on the server.
there is an ["alternative" syntax](http://www.php.net/alternative_syntax) to php that makes it more attractive amidst html tags, I can highly recommend it. Short tags, though mostly discouraged and/or ridiculed also have a nice advantage: ``` <?php echo $variable; ?> ``` can become: ``` <?= $variable; ?> ``` And you can do stuff like: ``` <ul> <? foreach ( $myListItems as $id => $itemText ) : ?> <li id="<?= $id; ?>"> <?= $itemText; ?> </li> <? endforeach; ?> </ul> ``` Which is the lowest level templating you are going to achieve with php, but is still very readable and it does not require you to mix in controller or model logic with your view.
what templating engine options are there for PHP?
[ "", "php", "templates", "templating", "templating-engine", "" ]
I am writing a jQuery plugin and I am at the optimization stage. I wonder which of these leads to a quicker script in general, and what sort of mitigating factors are important: 1. Have the script generate lots of classes and ids at the start so finding elements in the dom is easier (quicker too?) later on. 2. Keep classes and ids to a minimum (so save time by not creating them), but then look for elements in more convoluted ways later (eg the nth item in an object), which I presume is slower than getting by id/class.
The question is not really specific enough so I can give you advice directly relevant to your code, but here are some of my favorite jQuery optimization tips: 1. Whenever possible, specify a context! Don't make jQuery look places it doesn't have to. If you know that something is going to be inside the `#container` div, then do `$(something, '#container');` 2. `.myclass` is *slow*. Internally, jQuery has to go through *every single* element to see if it has the class you are searching for, at least for those browsers not supporting `getElementsByClassName`. If you know that a class will only be applied to a certain element, it is *way* faster to do `tag.myclass`, as jQuery can then use the native `getElementsByTagName` and only search through those. 3. Don't do complicated selectors in one bang. Sure, jQuery can figure out what you want, but it takes time to parse out the string and apply the logic you want to it. As such, I always like to separate my "queries" out into patches. While most people might do `$('#myform input:eq(2)');` or something like that, I prefer to do `$('input','#myform').eq(2);` to help jQuery out. 4. Don't re-query the DOM if you plan on doing multiple things with a set of objects. Take advantange of chaining, and if not possible to use chaining for whatever reason, cache the results of the query into a variable and perform your calls on that.
The way the browser works is that upon load it creates an in-memory DOM tree which looks as follows: ``` P _______________|______________ | | childNodes attributes ______________|___________ | | | | title = 'Test paragraph' 'Sample of text ' DIV 'in your document' | childNodes __________|_______ | | | 'HTML you might' B 'have' ``` So when you lookup `P > DIV > B`, the lookup has to find all `P` elements, then find all DIV elements within `P` and then find all `B` elements within DIV. The deeper the nesting the more lookups it needs to do. Further, it might find all `P > DIV` only to find that none of them have `B` and it will have wasted time looking through all `P > DIV` matches. Lookups by ID are faster because IDs are guaranteed to be unique so the DOM can store them as hash table entries which have very fast lookups. In terms of jQuery the implementation might be slightly different, however, document.getElementById has the fastest lookup time so `$('#my_node_id')` should also be quite fast. Consequently, if your node doesn't have an ID, you can find the nearest ancestor that does and find your node relative to that ancestor ``` #my_node_id > div > b ``` because the look up only needs to happen under the sub-tree of `#my_node_id` it will be faster than `p > div > b`
What is the most efficient way to access DOM elements in jQuery?
[ "", "javascript", "jquery", "" ]
I am attempting to take a list of objects, and turn that list into a dict. The dict values would be each object in the list, and the dict keys would be a value found in each object. Here is some code representing what im doing: ``` class SomeClass(object): def __init__(self, name): self.name = name object_list = [ SomeClass(name='a'), SomeClass(name='b'), SomeClass(name='c'), SomeClass(name='d'), SomeClass(name='e'), ] object_dict = {} for an_object in object_list: object_dict[an_object.name] = an_object ``` Now that code works, but its a bit ugly, and a bit slow. Could anyone give an example of something thats faster/"better"? *edit:* Alright, thanks for the replies. I must say i am surprised to see the more pythonic ways **seeming** slower than the hand made way. *edit2:* Alright, i updated the test code to make it a bit more readable, with so many tests heh. Here is where we are at in terms of code, i put authors in the code and if i messed any up please let me know. ``` from itertools import izip import timeit class SomeClass(object): def __init__(self, name): self.name = name object_list = [] for i in range(5): object_list.append(SomeClass(name=i)) def example_1(): 'Original Code' object_dict = {} for an_object in object_list: object_dict[an_object.name] = an_object def example_2(): 'Provided by hyperboreean' d = dict(zip([o.name for o in object_list], object_list)) def example_3(): 'Provided by Jason Baker' d = dict([(an_object.name, an_object) for an_object in object_list]) def example_4(): "Added izip to hyperboreean's code, suggested by Chris Cameron" d = dict(izip([o.name for o in object_list], object_list)) def example_5(): 'zip, improved by John Fouhy' d = dict(zip((o.name for o in object_list), object_list)) def example_6(): 'izip, improved by John Fouhy' d = dict(izip((o.name for o in object_list), object_list)) def example_7(): 'Provided by Jason Baker, removed brackets by John Fouhy' d = dict((an_object.name, an_object) for an_object in object_list) timeits = [] for example_index in range(1, 8): timeits.append( timeit.Timer( 'example_%s()' % example_index, 'from __main__ import example_%s' % example_index) ) for i in range(7): timeit_object = timeits[i] print 'Example #%s Result: "%s"' % (i+1, timeit_object.repeat(2)) ``` With 5 objects in the list i am getting a result of: ``` Example #1 Result: "[1.2428441047668457, 1.2431108951568604]" Example #2 Result: "[3.3567759990692139, 3.3188660144805908]" Example #3 Result: "[2.8346641063690186, 2.8344728946685791]" Example #4 Result: "[3.0710639953613281, 3.0573830604553223]" Example #5 Result: "[5.2079918384552002, 5.2170760631561279]" Example #6 Result: "[3.240635871887207, 3.2402129173278809]" Example #7 Result: "[3.0856869220733643, 3.0688989162445068]" ``` and with 50: ``` Example #1 Result: "[9.8108220100402832, 9.9066231250762939]" Example #2 Result: "[16.365023136138916, 16.213981151580811]" Example #3 Result: "[15.77024507522583, 15.771029949188232]" Example #4 Result: "[14.598290920257568, 14.591825008392334]" Example #5 Result: "[20.644147872924805, 20.64064884185791]" Example #6 Result: "[15.210831165313721, 15.212569952011108]" Example #7 Result: "[17.317100048065186, 17.359367847442627]" ``` And lastly, with 500 objects: ``` Example #1 Result: "[96.682723999023438, 96.678673028945923]" Example #2 Result: "[137.49416589736938, 137.48705387115479]" Example #3 Result: "[136.58069896697998, 136.5823769569397]" Example #4 Result: "[115.0344090461731, 115.1088011264801]" Example #5 Result: "[165.08325910568237, 165.06769108772278]" Example #6 Result: "[128.95187497138977, 128.96077489852905]" Example #7 Result: "[155.70515990257263, 155.74126601219177]" ``` Thanks to all that replied! Im very surprised with the result. If there are any other tips for a faster method i would love to hear them. Thanks all!
In python 3.0 you can use a dict comprehension: ``` {an_object.name : an_object for an_object in object_list} ``` This is also possible in Python 2, but it's a bit uglier: ``` dict([(an_object.name, an_object) for an_object in object_list]) ```
``` d = dict(zip([o.name for o in object_list], object_list)) ```
Best way to turn a list into a dict, where the keys are a value of each object?
[ "", "python", "" ]
I found that using Smarty with PHP, sometimes extra time will need to be used for 1) using quite different syntax than PHP itself 2) need to check small cases, because documentation doesn't give finer details, such as for "escape" <http://www.smarty.net/manual/en/language.modifier.escape.php> it doesn't say escape:"quotes" is for double quotes only or for single quotes as well, so you need to write code to test it. Also for the case of escape:"javascript" -- can't tell exactly what and how it is escaped. 3) for something complicated, need to write helper functions or modifiers, so it needs a creation of new files and ending up doing it in PHP again. by the way, does using Smarty provide a good speed up over use PHP alone? thanks.
First, PHP is a templating language. Keep that in mind when you talk about using a template system for your PHP-based web applications. The only 'real' argument that I've ever heard for using ANY templating engine was that they provide a simpler language for template manipulation which can be handy if you have template designers who don't know PHP and whom you don't trust to learn to use PHP judiciously. Regarding these arguments, I would argue that if your template designers are not competent to learn enough PHP for template design, you should probably consider finding new template designers. Additionally, PHP itself provides a different syntax for control statements that you might use in a template versus in code. For example: ``` <? foreach($array as $key => $val): ?> <?= $val ?> <? endforeach; ?> ``` VS: ``` <?php foreach($array as $key => $val) { echo $val; } ?> ``` Personally, I believe that templating engines arose in PHP because: 1. That's way that other languages do it 2. Better PHP programmers realized that they needed a way to enforce separation between presentation and application logic and templates were an easy way to do this. The first reason is just kinda silly. The second reason can be overcome with a little self-control and even a rudimentary understanding of the necessity of separating layers in an application. The MVC design pattern is one way of approaching this problem. As far as exercising some self-control, my rule is that only necessary loops and if statements get used as well as functions that filter, escape, format the output for the screen. Having used Smarty extensively, I can honestly say that it always presented me with more hurdles to get over than it did solutions. If anything, switching to PHP-based templates is what has actually decreased development time for both templates and code.
I don't like templating engines. I find them very lossy and resource-intensive for PHP. With MediaWiki, around version 1.6.x we backed off using Smarty by default and just use PHP's built-in templating, with a great improvement in performance. I've found that most of what people want to do with a templating system (add links, change colors, remove text or sections of the page) are better done with a simple system of event hooks. Laconica, the open microblogging platform, doesn't do any templating by default. We have a plugin for people who are crazy for templating.
how to use Smarty better with PHP?
[ "", "php", "smarty", "template-engine", "templating", "" ]
I need an example of the shortest path of a directed cyclic graph from one node (it should reach to all nodes of the graph from a node that will be the input). Please if there is an example, I need it in C++, or the algorithm.
EDIT: Oops, misread the question. Thanks @jfclavette for picking this up. Old answer is at the end. The problem you're trying to solve is called the [Travelling salesman problem](http://en.wikipedia.org/wiki/Travelling_salesman_problem). There are many [potential solutions](http://en.wikipedia.org/wiki/Travelling_salesman_problem#Computing_a_solution), but it's NP-complete so you won't be able to solve for large graphs. Old answer: What you're trying to find is called the [girth](http://en.wikipedia.org/wiki/Girth_(graph_theory)) of a graph. It can be solved by setting the distances from a node to itself to infinity and using the [Floyd-Warshall](http://en.wikipedia.org/wiki/Floyd-Warshall) algorithm. The length of the shortest cycle from node i is then just the entry in position ii.
In the unweighted case: [Breadth first search](http://en.wikipedia.org/wiki/Breadth-first_search). In the weighted case: [Dijkstra's](http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm).
How do I find the shortest path that covers all nodes in a directed cyclic graph?
[ "", "c++", "algorithm", "graph-theory", "cycle", "shortest-path", "" ]
What library should I use to connect to odbc from python on windows? Is there a good alternative for pywin32 when it comes to odbc? I'm looking for something well-documented, robust, actively maintained, etc. [`pyodbc`](https://github.com/mkleehammer/pyodbc) looks good -- are there any others?
You already suggested **pyodbc**, and I am going to agree with you. It has given me the least amount of issues in my experience; I've used [pymssql](http://pymssql.sourceforge.net/) and [adodbapi](http://adodbapi.sourceforge.net/), and when those threw exceptions/created issues, I swapped out the code and replaced it with pyodbc and it either fixed the problem, or gave better error messages so I could debug faster. It's worth mentioning that I primarily use it to connect to **MSSQL Server** DBs.
I use [SQLAlchemy](http://www.sqlalchemy.org) for all python database access. I highly recommend SQLAlchemy. SA uses pyodbc under the hood when connecting to SQL server databases. It uses other DBAPI libraries to connect to other database, for instance cx\_Oracle. A simplistic example, using SQLAlchemy like you would normally use a DBAPI module: ``` import sqlalchemy engine = sqlalchemy.create_engine('sqlite:///database.db') for r in engine.execute('SELECT * FROM T'): print(r.OneColumn, r.OtherColumn) ``` But the real value of SQLAlchemy lies in its [ORM](http://www.sqlalchemy.org/docs/05/ormtutorial.html) and [SQL expression language](http://www.sqlalchemy.org/docs/05/sqlexpression.html). Have a look, it is well worth the effort to learn to use.
Common ways to connect to odbc from python on windows?
[ "", "python", "windows", "odbc", "pywin32", "pyodbc", "" ]
I find that if there are a lot of classes the compilation time is dramatically increased when I use one \*.h and one \*.cpp file per class. I already use precompiled headers and incremental linking, but still the compile time is very long (yes I use boost ;) So I came up with the following trick: * defined \*.cpp files as non-compilable * defined \*.cxx files as compilable * added one \*.cxx file per application module, and #included all the \*.cpp files of this module in it. So instead of 100+ translation units I ended up with only 8 translation units. The compile time became 4-5 times shorter. The downsides are that you have to manually include all the \*.cpp files (but it's not really a maintenance nightmare since if you forget to include something the linker will remind you), and that some VS IDE conveniences are not working with this scheme, e.g. Go To/ Move to Implementation etc. So the question is, is having lots of cpp translation units really the only true way? Is my trick a known pattern, or maybe I'm missing something? Thanks!
The concept is called [unity build](https://stackoverflow.com/questions/847974/c-the-benefits-disadvantages-of-unity-builds)
One significant drawback of this approach is caused by having one .obj file for each translation unit. If you create a static library for reuse in other projects you will often face bigger binaries in those projects if you have several huge translation units instead of many small ones because the linker will only include the .obj files containing the functions/variables really referenced from within the project using the library. In case of big translation units it's more likely that each unit is referenced and the corresponding .obj file is included. Bigger binaries may be a problem in some cases. It's also possible that some linkers are smart enough to only include the necessary functions/variables, not the whole .obj files. Also if the .obj file is included and all the global variables are included too then their constructors/destructors will be called when the program is started/stopped which surely will take time.
Is reducing number of cpp translation units a good idea?
[ "", "c++", "performance", "build-process", "module", "header-files", "" ]
How do I generate a unique session id in Python?
You can use the [uuid library](http://docs.python.org/library/uuid.html) like so: ``` import uuid my_id = uuid.uuid1() # or uuid.uuid4() ```
**UPDATE: 2016-12-21** A lot has happened in a the last ~5yrs. `/dev/urandom` has been updated and is now considered a high-entropy source of randomness on modern Linux kernels and distributions. In the last 6mo we've seen entropy starvation on a Linux 3.19 kernel using Ubuntu, so I don't think this issue is "resolved", but it's sufficiently difficult to end up with low-entropy randomness when asking for any amount of randomness from the OS. --- I hate to say this, but none of the other solutions posted here are correct with regards to being a "secure session ID." ``` # pip install M2Crypto import base64, M2Crypto def generate_session_id(num_bytes = 16): return base64.b64encode(M2Crypto.m2.rand_bytes(num_bytes)) ``` Neither `uuid()` or `os.urandom()` are good choices for generating session IDs. Both may generate **random** results, but random does not mean it is **secure** due to poor **entropy**. See "[How to Crack a Linear Congruential Generator](http://www.reteam.org/papers/e59.pdf)" by Haldir or [NIST's resources on Random Number Generation](http://csrc.nist.gov/groups/ST/toolkit/rng/index.html). If you still want to use a UUID, then use a UUID that was generated with a good initial random number: ``` import uuid, M2Crypto uuid.UUID(bytes = M2Crypto.m2.rand_bytes(num_bytes))) # UUID('5e85edc4-7078-d214-e773-f8caae16fe6c') ``` or: ``` # pip install pyOpenSSL import uuid, OpenSSL uuid.UUID(bytes = OpenSSL.rand.bytes(16)) # UUID('c9bf635f-b0cc-d278-a2c5-01eaae654461') ``` M2Crypto is best OpenSSL API in Python atm as pyOpenSSL appears to be maintained only to support legacy applications.
Unique session id in python
[ "", "python", "session", "" ]
In python, is there a way to create a class that is treated like a dictionary but have the keys pre-defined when a new instance is created?
You can easily extend any built in type. This is how you'd do it with a dict: ``` >>> class MyClass(dict): ... def __init__(self, *args, **kwargs): ... self['mykey'] = 'myvalue' ... self['mykey2'] = 'myvalue2' ... >>> x = MyClass() >>> x['mykey'] 'myvalue' >>> x {'mykey2': 'myvalue2', 'mykey': 'myvalue'} ``` I wasn't able to find the Python documentation that talks about this, but the very popular book [Dive Into Python](http://diveintopython.net/index.html) (available for free online) [has a few examples](http://diveintopython.net/object_oriented_framework/userdict.html) on doing this.
You can also have the dict subclass restrict the keys to a predefined list, by overriding `__setitem__()` ``` >>> class LimitedDict(dict): _keys = "a b c".split() def __init__(self, valtype=int): for key in LimitedDict._keys: self[key] = valtype() def __setitem__(self, key, val): if key not in LimitedDict._keys: raise KeyError dict.__setitem__(self, key, val) >>> limited = LimitedDict() >>> limited['a'] 0 >>> limited['a'] = 3 >>> limited['a'] 3 >>> limited['z'] = 0 Traceback (most recent call last): File "<pyshell#61>", line 1, in <module> limited['z'] = 0 File "<pyshell#56>", line 8, in __setitem__ raise KeyError KeyError >>> len(limited) 3 ```
Creating dictionaries with pre-defined keys
[ "", "python", "dictionary", "" ]
I want my web page to beep whenever a user exceeds the maximum character limit of my `<textarea>`.
It's not possible to do directly in JavaScript. You'll need to embed a short WAV file in the HTML, and then play that via code. An Example: ``` <script> function PlaySound(soundObj) { var sound = document.getElementById(soundObj); sound.Play(); } </script> <embed src="success.wav" autostart="false" width="0" height="0" id="sound1" enablejavascript="true"> ``` You would then call it from JavaScript code as such: ``` PlaySound("sound1"); ``` This should do exactly what you want - you'll just need to find/create the beep sound yourself, which should be trivial.
**Solution** You can now use [base64 files](http://en.wikipedia.org/wiki/Base64) to produce sounds when imported as [data URI](http://en.wikipedia.org/wiki/Data_URI_scheme). The solution is almost the same as the previous ones, except you do not need to import an external audio file. ``` function beep() { var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4k6jzRnqasNKIeoh5gI7BJaC1A1AoNBjJgbyApVS4IDlZgDU5WUAxEKDNmmALHzZp0Fkz1FMTmGFl1FMEyodIavcCAUHDWrKAIA4aa2oCgILEBupZgHvAhEBcZ6joQBxS76AgccrFlczBvKLC0QI2cBoCFvfTDAo7eoOQInqDPBtvrDEZBNYN5xwNwxQRfw8ZQ5wQVLvO8OYU+mHvFLlDh05Mdg7BT6YrRPpCBznMB2r//xKJjyyOh+cImr2/4doscwD6neZjuZR4AgAABYAAAABy1xcdQtxYBYYZdifkUDgzzXaXn98Z0oi9ILU5mBjFANmRwlVJ3/6jYDAmxaiDG3/6xjQQCCKkRb/6kg/wW+kSJ5//rLobkLSiKmqP/0ikJuDaSaSf/6JiLYLEYnW/+kXg1WRVJL/9EmQ1YZIsv/6Qzwy5qk7/+tEU0nkls3/zIUMPKNX/6yZLf+kFgAfgGyLFAUwY//uQZAUABcd5UiNPVXAAAApAAAAAE0VZQKw9ISAAACgAAAAAVQIygIElVrFkBS+Jhi+EAuu+lKAkYUEIsmEAEoMeDmCETMvfSHTGkF5RWH7kz/ESHWPAq/kcCRhqBtMdokPdM7vil7RG98A2sc7zO6ZvTdM7pmOUAZTnJW+NXxqmd41dqJ6mLTXxrPpnV8avaIf5SvL7pndPvPpndJR9Kuu8fePvuiuhorgWjp7Mf/PRjxcFCPDkW31srioCExivv9lcwKEaHsf/7ow2Fl1T/9RkXgEhYElAoCLFtMArxwivDJJ+bR1HTKJdlEoTELCIqgEwVGSQ+hIm0NbK8WXcTEI0UPoa2NbG4y2K00JEWbZavJXkYaqo9CRHS55FcZTjKEk3NKoCYUnSQ0rWxrZbFKbKIhOKPZe1cJKzZSaQrIyULHDZmV5K4xySsDRKWOruanGtjLJXFEmwaIbDLX0hIPBUQPVFVkQkDoUNfSoDgQGKPekoxeGzA4DUvnn4bxzcZrtJyipKfPNy5w+9lnXwgqsiyHNeSVpemw4bWb9psYeq//uQZBoABQt4yMVxYAIAAAkQoAAAHvYpL5m6AAgAACXDAAAAD59jblTirQe9upFsmZbpMudy7Lz1X1DYsxOOSWpfPqNX2WqktK0DMvuGwlbNj44TleLPQ+Gsfb+GOWOKJoIrWb3cIMeeON6lz2umTqMXV8Mj30yWPpjoSa9ujK8SyeJP5y5mOW1D6hvLepeveEAEDo0mgCRClOEgANv3B9a6fikgUSu/DmAMATrGx7nng5p5iimPNZsfQLYB2sDLIkzRKZOHGAaUyDcpFBSLG9MCQALgAIgQs2YunOszLSAyQYPVC2YdGGeHD2dTdJk1pAHGAWDjnkcLKFymS3RQZTInzySoBwMG0QueC3gMsCEYxUqlrcxK6k1LQQcsmyYeQPdC2YfuGPASCBkcVMQQqpVJshui1tkXQJQV0OXGAZMXSOEEBRirXbVRQW7ugq7IM7rPWSZyDlM3IuNEkxzCOJ0ny2ThNkyRai1b6ev//3dzNGzNb//4uAvHT5sURcZCFcuKLhOFs8mLAAEAt4UWAAIABAAAAAB4qbHo0tIjVkUU//uQZAwABfSFz3ZqQAAAAAngwAAAE1HjMp2qAAAAACZDgAAAD5UkTE1UgZEUExqYynN1qZvqIOREEFmBcJQkwdxiFtw0qEOkGYfRDifBui9MQg4QAHAqWtAWHoCxu1Yf4VfWLPIM2mHDFsbQEVGwyqQoQcwnfHeIkNt9YnkiaS1oizycqJrx4KOQjahZxWbcZgztj2c49nKmkId44S71j0c8eV9yDK6uPRzx5X18eDvjvQ6yKo9ZSS6l//8elePK/Lf//IInrOF/FvDoADYAGBMGb7FtErm5MXMlmPAJQVgWta7Zx2go+8xJ0UiCb8LHHdftWyLJE0QIAIsI+UbXu67dZMjmgDGCGl1H+vpF4NSDckSIkk7Vd+sxEhBQMRU8j/12UIRhzSaUdQ+rQU5kGeFxm+hb1oh6pWWmv3uvmReDl0UnvtapVaIzo1jZbf/pD6ElLqSX+rUmOQNpJFa/r+sa4e/pBlAABoAAAAA3CUgShLdGIxsY7AUABPRrgCABdDuQ5GC7DqPQCgbbJUAoRSUj+NIEig0YfyWUho1VBBBA//uQZB4ABZx5zfMakeAAAAmwAAAAF5F3P0w9GtAAACfAAAAAwLhMDmAYWMgVEG1U0FIGCBgXBXAtfMH10000EEEEEECUBYln03TTTdNBDZopopYvrTTdNa325mImNg3TTPV9q3pmY0xoO6bv3r00y+IDGid/9aaaZTGMuj9mpu9Mpio1dXrr5HERTZSmqU36A3CumzN/9Robv/Xx4v9ijkSRSNLQhAWumap82WRSBUqXStV/YcS+XVLnSS+WLDroqArFkMEsAS+eWmrUzrO0oEmE40RlMZ5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU="); snd.play(); } beep(); ``` **Compatibility** Data URI is supported on almost every browser now. More information on <http://caniuse.com/datauri> **Demo** <http://jsfiddle.net/7EAgz/> **Conversion Tool** And here is where you can convert mp3 or wav files into Data URI format: <https://dopiaza.org/tools/datauri/index.php>
How do I make JavaScript beep?
[ "", "javascript", "audio", "browser", "beep", "" ]
I'm trying to convert some date/times to UTC, which I thought would be dead simple in Python - batteries included, right? Well, it would be simple except that Python (2.6) doesn't include any tzinfo classes. No problem, a quick search turns up [python-dateutil](http://pypi.python.org/pypi/python-dateutil) which should do exactly what I need. The problem is that I need to install it on Windows. I was able to upack the .tar.gz2 distribution using 7-zip, but now I'm left with a collection of files and no guidance on how to proceed. When I try to run setup.py I get the error "No module named setuptools".
If dateutil is missing install it via: ``` pip install python-dateutil ``` Or on Ubuntu: ``` sudo apt-get install python-dateutil ```
Why didn't someone tell me I was being a total noob? All I had to do was copy the `dateutil` directory to someplace in my Python path, and it was good to go.
How to install python-dateutil on Windows?
[ "", "python", "installation", "python-dateutil", "" ]
I'm working on a MVC based web app on LAMP that needs some records to be modified only under the approval of a "superior" user. (The normal user can submit changes but they get applied only after this approval) There are is only a table in which this would have to take place, say "events": EVENTS - id - name VARCHAR - start\_date DATETIME - guest INTEGER Every time one of the attributes of an events gets modified by a "normal" user, these changes are not made official until there's a revision (and possible approval) from this "super" user. At first I though of the following options: * Duplicating each columns, except the id, say name\_temp for "name", to hold the pending-approval modification. * Creating a separate table with a duplicate structure and hold there all the pending approval modifications. Have you implemented this before? What do you think is the best/your way to do this? And also: **Is there any pattern for this kind of problem?** Thanks!!! PD: I need to keep the "old" record where it was, until the new one gets approved..
Let me add my vote for the "second table" approach -- as both other respondents said, it's head and shoulders above attempts to shoehorn "proposed changes" into the master table (that would complicate its schema, every query on it, etc, etc). Writing all intended changes to an auxiliary table and processing them (applying them to the master table if they meed certain conditions) "in batches" later is indeed a common pattern, often useful when you need the master table to change only at certain times while proposed changes can come in any time, and also in other conditions, e.g. when writes to the master table are very costly (lock contention or whatever) but writing N changes is not much costlier than writing one, or validating a proposed change is very time-consuming (you could class your use case as an extreme case of the latter category, since in your case the validation requires a human to look at the proposed change -- VERY slow indeed by computer standards;-).
If history or versioning is important, combined with the approval, I would go for a single table. You would add a revision number, which could work with your existing primary key and could be incremented on each revision. You could then add a state field to show which is the current version, expired versions and needs approval versions. A nice index on the state and key field will get you snappy results. If this is just one, two or three fields out of many, then a specific table to handle these unapproved edits might be better as suggested above.
What's the best way to implement a "soft" save or modification workflow?
[ "", "php", "mysql", "database", "database-design", "design-patterns", "" ]
I keep getting this : ``` DeprecationWarning: integer argument expected, got float ``` How do I make this message go away? Is there a way to avoid warnings in Python?
From documentation of the [`warnings` module](https://docs.python.org/3/library/warnings.html): ``` #!/usr/bin/env python -W ignore::DeprecationWarning ``` If you're on Windows: pass `-W ignore::DeprecationWarning` as an argument to Python. Better though to resolve the issue, by casting to [int](http://docs.python.org/3.0/library/functions.html#int). (Note that in Python 3.2, deprecation warnings are ignored by default.)
You should just fix your code but just in case, ``` import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) ```
How to ignore deprecation warnings in Python
[ "", "python", "warnings", "deprecated", "" ]
I've got a model (Listings) that has and belongs to a few different models, I'd like to find all of this model where it's related model (Openhouses) have a condition. The 'has and belongs to' are setup in the model files. Listings hasmany Openhouses and Openhouses belong to Listings. (And listings has many and blongs to a few other models where I want the data.) I've been trying. ``` $this->Listing->find('all', array('conditions' => array('Openhouse.date >' => $openhouse_start->format('Y-m-d H:i:s'), 'Openhouse.date <' => $openhouse_end->format('Y-m-d H:i:s')) )); ``` but to no avail. ``` Error: 1054: Unknown column 'Openhouse.date' in 'where clause ``` I know I can search on the Openhouse model and get related Listings but then the data is returned in a different format and I need to turn recursion way up to get data from my other models. (And I end up with duplicate openhouse data!). I can post some more code examples if needed. My question is basically do I need to just query the openhouse model and live with it or is my syntax for putting conditions on related models incorrect?
Try this: ``` $this->List->find('all', array( 'contain' => array( 'Openhouse.conditions' => array( 'Openhouse.date >' => $openhouse_start->format('Y-m-d H:i:s'), 'Openhouse.date <' => $openhouse_end->format('Y-m-d H:i:s')) ) ) ) ```
If you have a lot of linked models, settings recursive to 2 might bring more data than you might want. If that is true, there is an alternative to what mavarro said, you can also try using the [Containable behaviour](http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html): ``` $this->Listing->find ( 'all', array ( 'conditions' => array ( 'Openhouse.date >' => $openhouse_start->format('Y-m-d H:i:s'), 'Openhouse.date <' => $openhouse_end->format('Y-m-d H:i:s') ), 'contain' => array('Openhouse') ) ); ```
In cakephp how can I do a find with conditions on a related field?
[ "", "php", "cakephp", "" ]
Whenever I use the rand function in C++: ``` #include<iostream> #include<time.h> #include<stdlib.h> using namespace std; int main(){ srand(time(0)); int n=(rand()%6)+1; cout<<"The dice roll is "<<n<<"."<<endl; } ``` I get a warning about conversion from time\_t to int at line 5: ``` srand(time(0)); ``` Is there any way to get rid of this warning?
Actually, you should be using an an [**unsigned** int with srand()](http://linux.die.net/man/3/srand): ``` srand((unsigned) time(0)); ```
On A different note, this code: ``` rand()%6 ``` is generally regarded as a bad practice. the lower bits of rand() are significantly less random than the higher bits. You'll get better randomness if you do: ``` (rand() >> 8)%6 ``` for instance. EDIT: For more detail on this, see [this note](http://members.cox.net/srice1/random/crandom.html) and also this article from [Dr. Dobbs](http://www.ddj.com/cpp/184403169) journal which at least hint at the reason: > Note: Do NOT use > > ``` > y = rand() % M; > ``` > > as this focuses on the lower bits of > rand(). For linear congruential random > number generators, which rand() often > is, the lower bytes are much less > random than the higher bytes. In fact > the lowest bit cycles between 0 and 1. > Thus rand() may cycle between even and > odd (try it out). Note rand() does not > have to be a linear congruential > random number generator. It's > perfectly permissible for it to be > something better which does not have > this problem. DDJ: > The most important point is that the > lower bits of the output from the > usual (linear congruential) random > number generators are the least > "random." That is, patterns in the > lower bits are common. Hence, the > output from the routine roll in your > discussion is not surprising. Also, it > is avoidable by relying on the upper > bits to determine the integer > returned. For example, if you wanted to choose a random "true" or "false" value, and you used the code: ``` rand() % 2 ``` Then you might end up seeing the pattern of results: 1,0,1,0,1,0,1,0,1,0 (etc) This is obviously not that random, but it is a property of the linear congruential generator that might be in use. A better scheme altogether (for C++) might be to use the [Boost.Random](http://www.boost.org/doc/libs/1_39_0/libs/random/index.html) library which has support for all kinds of pluggable random generators (including Mersenne Twister which does not have this flaw).
How can I get rid of the warning with rand()? (C++)
[ "", "c++", "time", "random", "standard-library", "seed", "" ]
I'm looking for the best way to select numbers directly from an in clause. Basically like: ``` SELECT * FROM (2,6,1,8); ``` That doesn't work. I can do it this way: ``` SELECT Lv FROM ( SELECT Level LV FROM DUAL CONNECT BY Level < 20) WHERE Lv IN (2,6,1,8); ``` But that seems to be a bit clunky. Is there a more elegant way?
It's more elegant if you materialize an auxiliary numbers table: ``` SELECT num FROM numbers WHERE num IN (2,6,1,8); ``` And this is also useful when combined with another table. For instance, I've had a case where I needed to populate large configuration tables with changes from piecewise results: Big SP or Excel sheet or report identifies missing cost centers in config gives a large set of results which need to be inserted with varying data in some groups. Paste partial results into a individual comma separated lists: ``` INSERT INTO {stuff} SELECT {stuff}, 130 as line_item FROM numbers WHERE numbers.num IN ({pasted a section of results}) INSERT INTO {stuff} SELECT {stuff}, 135 as line_item FROM numbers WHERE numbers.num IN ({pasted another section of results}) ```
You can do ``` select column_value from table(sys.dbms_debug_vc2coll(1,2,3,4,5)); ``` but that actually returns a varchar2. You can create your own TYPE and use that ``` create type tab_num is table of number; / select column_value from table(tab_num(1,2,3,4,5)); ``` It's also worth looking at the MODEL clause. It looks complicated, but it is very good at generating data ``` SELECT x from dual MODEL DIMENSION BY (1 AS z) MEASURES (1 x) RULES ITERATE (7) (x[ITERATION_NUMBER]=ITERATION_NUMBER+1) ```
Oracle Select numbers from an IN clause
[ "", "sql", "oracle", "" ]
I have a Lucene index where every document has several fields which contain numeric values. Now I would like to sort the search result on a weighted sum of this field. For example: ``` field1=100 field2=002 field3=014 ``` And the weighting function looks like: ``` f(d) = field1 * 0.5 + field2 * 1.4 + field3 * 1.8 ``` The results should be ordered by `f(d)` where `d` represents the document. The sorting function should be non-static and could differ from search to search because the constant factors are influenced by the user who performs the search. Has anyone an idea how to solve this or maybe an idea how to accomplish this goal in another way?
You could try implementing a custom [ScoreDocComparator](http://lucene.apache.org/java/2_4_1/api/core/org/apache/lucene/search/ScoreDocComparator.html). For example: ``` public class ScaledScoreDocComparator implements ScoreDocComparator { private int[][] values; private float[] scalars; public ScaledScoreDocComparator(IndexReader reader, String[] fields, float[] scalars) throws IOException { this.scalars = scalars; this.values = new int[fields.length][]; for (int i = 0; i < values.length; i++) { this.values[i] = FieldCache.DEFAULT.getInts(reader, fields[i]); } } protected float score(ScoreDoc scoreDoc) { int doc = scoreDoc.doc; float score = 0; for (int i = 0; i < values.length; i++) { int value = values[i][doc]; float scalar = scalars[i]; score += (value * scalar); } return score; } @Override public int compare(ScoreDoc i, ScoreDoc j) { float iScore = score(i); float jScore = score(j); return Float.compare(iScore, jScore); } @Override public int sortType() { return SortField.CUSTOM; } @Override public Comparable<?> sortValue(ScoreDoc i) { float score = score(i); return Float.valueOf(score); } } ``` Here is an example of `ScaledScoreDocComparator` in action. I believe it works in my test, but I encourage you to prove it against your data. ``` final String[] fields = new String[]{ "field1", "field2", "field3" }; final float[] scalars = new float[]{ 0.5f, 1.4f, 1.8f }; Sort sort = new Sort( new SortField( "", new SortComparatorSource() { public ScoreDocComparator newComparator(IndexReader reader, String fieldName) throws IOException { return new ScaledScoreDocComparator(reader, fields, scalars); } } ) ); IndexSearcher indexSearcher = ...; Query query = ...; Filter filter = ...; // can be null int nDocs = 100; TopFieldDocs topFieldDocs = indexSearcher.search(query, filter, nDocs, sort); ScoreDoc[] scoreDocs = topFieldDocs.scoreDocs; ``` ## Bonus! It appears that the Lucene developers are deprecating the `ScoreDocComparator` interface (it's currently deprecated in the Subversion repository). Here is an example of the `ScaledScoreDocComparator` modified to adhere to `ScoreDocComparator`'s successor, `FieldComparator`: ``` public class ScaledComparator extends FieldComparator { private String[] fields; private float[] scalars; private int[][] slotValues; private int[][] currentReaderValues; private int bottomSlot; public ScaledComparator(int numHits, String[] fields, float[] scalars) { this.fields = fields; this.scalars = scalars; this.slotValues = new int[this.fields.length][]; for (int fieldIndex = 0; fieldIndex < this.fields.length; fieldIndex++) { this.slotValues[fieldIndex] = new int[numHits]; } this.currentReaderValues = new int[this.fields.length][]; } protected float score(int[][] values, int secondaryIndex) { float score = 0; for (int fieldIndex = 0; fieldIndex < fields.length; fieldIndex++) { int value = values[fieldIndex][secondaryIndex]; float scalar = scalars[fieldIndex]; score += (value * scalar); } return score; } protected float scoreSlot(int slot) { return score(slotValues, slot); } protected float scoreDoc(int doc) { return score(currentReaderValues, doc); } @Override public int compare(int slot1, int slot2) { float score1 = scoreSlot(slot1); float score2 = scoreSlot(slot2); return Float.compare(score1, score2); } @Override public int compareBottom(int doc) throws IOException { float bottomScore = scoreSlot(bottomSlot); float docScore = scoreDoc(doc); return Float.compare(bottomScore, docScore); } @Override public void copy(int slot, int doc) throws IOException { for (int fieldIndex = 0; fieldIndex < fields.length; fieldIndex++) { slotValues[fieldIndex][slot] = currentReaderValues[fieldIndex][doc]; } } @Override public void setBottom(int slot) { bottomSlot = slot; } @Override public void setNextReader(IndexReader reader, int docBase, int numSlotsFull) throws IOException { for (int fieldIndex = 0; fieldIndex < fields.length; fieldIndex++) { String field = fields[fieldIndex]; currentReaderValues[fieldIndex] = FieldCache.DEFAULT.getInts(reader, field); } } @Override public int sortType() { return SortField.CUSTOM; } @Override public Comparable<?> value(int slot) { float score = scoreSlot(slot); return Float.valueOf(score); } } ``` Using this new class is very similar to the original, except that the definition of the `sort` object is a bit different: ``` final String[] fields = new String[]{ "field1", "field2", "field3" }; final float[] scalars = new float[]{ 0.5f, 1.4f, 1.8f }; Sort sort = new Sort( new SortField( "", new FieldComparatorSource() { public FieldComparator newComparator(String fieldname, int numHits, int sortPos, boolean reversed) throws IOException { return new ScaledComparator(numHits, fields, scalars); } } ) ); ```
Implement your own similarity class and override [idf(Term, Searcher)](http://lucene.apache.org/java/2_4_0/api/org/apache/lucene/search/Similarity.html#idf(org.apache.lucene.index.Term,%20org.apache.lucene.search.Searcher)) method. In this method, you can return the score as follows. if (term.field.equals("field1") { ``` if (term.field.equals("field1") { score = 0.5 * Integer.parseInt(term.text()); } else if (term.field.equals("field2") { score = 1.4 * Integer.parseInt(term.text()); } // and so on return score; ``` When you execute the query, make sure it is on all the fields. That is query should look like > field1:term field2:term field3:term The final score will also add some weights based on the query normalization. But, that will not affect the relative ranking of the documents as per the equation given by you.
How to sort search results on multiple fields using a weighting function?
[ "", "java", "sorting", "lucene", "" ]
In my previous [question](https://stackoverflow.com/questions/746774/basic-python-quick-question-regarding-calling-a-function), Andrew Jaffe [writes](https://stackoverflow.com/a/746844/17242583): > In addition to all of the other hints and tips, I think you're missing something crucial: your functions actually need to return something. > When you create `autoparts()` or `splittext()`, the idea is that this will be a function that you can call, and it can (and should) give something back. > Once you figure out the output that you want your function to have, you need to put it in a `return` statement. ``` def autoparts(): parts_dict = {} list_of_parts = open('list_of_parts.txt', 'r') for line in list_of_parts: k, v = line.split() parts_dict[k] = v print(parts_dict) >>> autoparts() {'part A': 1, 'part B': 2, ...} ``` This function creates a dictionary, but it does not return something. However, since I added the `print`, the output of the function is shown when I run the function. What is the difference between `return`ing something and `print`ing it?
`print` simply prints out the structure to your output device (normally the console). Nothing more. To return it from your function, you would do: ``` def autoparts(): parts_dict = {} list_of_parts = open('list_of_parts.txt', 'r') for line in list_of_parts: k, v = line.split() parts_dict[k] = v return parts_dict ``` Why return? Well if you don't, that dictionary dies (gets garbage collected) and is no longer accessible as soon as this function call ends. If you return the value, you can do other stuff with it. Such as: ``` my_auto_parts = autoparts() print(my_auto_parts['engine']) ``` See what happened? `autoparts()` was called and it returned the `parts_dict` and we stored it into the `my_auto_parts` variable. Now we can use this variable to access the dictionary object and it continues to live even though the function call is over. We then printed out the object in the dictionary with the key `'engine'`. For a good tutorial, check out [dive into python](https://diveintopython3.problemsolving.io/). It's free and very easy to follow.
The print statement will output an object to the user. A return statement will allow assigning the dictionary to a variable *once the function is finished*. ``` >>> def foo(): ... print "Hello, world!" ... >>> a = foo() Hello, world! >>> a >>> def foo(): ... return "Hello, world!" ... >>> a = foo() >>> a 'Hello, world!' ``` Or in the context of returning a dictionary: ``` >>> def foo(): ... print {'a' : 1, 'b' : 2} ... >>> a = foo() {'a': 1, 'b': 2} >>> a >>> def foo(): ... return {'a' : 1, 'b' : 2} ... >>> a = foo() >>> a {'a': 1, 'b': 2} ``` (The statements where nothing is printed out after a line is executed means the last statement returned None)
How is returning the output of a function different from printing it?
[ "", "python", "return", "output", "" ]
I'm looking to get up to speed on **Python**: Is it worth working locally via the **ActivePython interface**, then progressing to a website that supports one of the standard frameworks (**Django** or **Pylons**) OR utilize the **Google Apps environment**? I want to stay as interactive as possible - making feedback/learning easier.
Go with the Python interpreter. Take one of the tutorials that many people on SO [recommend](https://stackoverflow.com/search?q=python+tutorial) and you're on your way. Once you're comfortable with the language, have a look at a framework like Django, but not sooner.
Not sure what you mean. For development First choice: idle -- you already have it. Second choice: Komodo Edit -- very easy to use, but not as directly interactive as idle. For deploying applications, that depends on your application. If you're building desktop applications or web applications, you still use similar tools. I prefer using Komodo Edit for big things (either desktop or web) because it's a nice IDE. What are you asking about? Development tools or final deployment of a finished product?
Python learning environment
[ "", "python", "django", "pylons", "activepython", "" ]
I'm trying to help debug a hang with the VS 2008 debugger. If I double click a thread in the Threads pane, I can see the trace for that thread in the Call Stack pane. My question is: Is there a way to get all the call stacks for all the threads in one shot, without having to select each thread individually? I want to email the traces for all threads to the developer who is going to be investigating it.
Much more useful for the developer of an application than text stack traces would be to save a minidump using Debug | Save Dump As (in Visual Studio) and send that instead.
... although I found an easier way to do this outside of VS. [Managed Stack Explorer](http://blogs.msdn.com/tess/archive/2009/05/08/neat-net-2-0-stackviewer-to-troubleshoot-hangs-performance-issues.aspx) is exactly what I was looking for. It's a free and lightweight exe that hooks into a running app, and can give you a dump of all the stack traces in one place.
how to get all stack traces with VS 2008 debugger
[ "", "c#", "visual-studio-2008", "debugging", "stack-trace", "" ]
The Entity Framework context object implements a Dispose() method which "Releases the resources used by the object context". What does it do really? Could it be a bad thing to always put it into a using {} statement? I've seen it being used both with and without the using statement. I'm specifically going to use the EF context from within a WCF service method, create the context, do some linq and return the answer. **EDIT:** Seems that I'm not the only one wondering about this. Another question is what's really happening inside the Dispose() method. Some say it closes connections, and some articles says not. What's the deal?
If you create a context, you must dispose it later. If you should use the `using` statement depends on the life time of the context. 1. If you create the context in a method and use it only within this method, you should really use the `using` statement because it gives you the exception handling without any additional code. 2. If you use the context for a longer period - that is the life time is not bound by the execution time of a method - you cannot use the `using` statement and you have to call `Dispose()` yourself and take care that you always call it. What does `Dispose()`do for an object context? I did not look at the code, but at least I exspect it to close the database connection with its underlying sockets or whatever resources the transport mechanism used.
Per [Progamming Entity Framework](https://rads.stackoverflow.com/amzn/click/com/0596807260): "You can either explicitly dispose the ObjectContext or wait for the garbage collector to do the job." So in short, while the using statement isn't required, it's best practice if you know you're done using the ObjectContext since the resource is freed up immediately instead of waiting for garbage collection.
Should Entity Framework Context be Put into Using Statement?
[ "", "c#", "entity-framework", "" ]
What is the best way to create a JSON web service? We have another team that is using Java and they insist to having all communication done using JSON. I would prefer to use WCF rather than any 3rd party framework. I found this blog: <http://www.west-wind.com/weblog/posts/164419.aspx>, and it suggests that the Microsoft implementation is flawed with M$ specific crap.
I ended up using [JayRock](http://jayrock.berlios.de/). Its fantastic piece of technology, just works. You don't get any NullReferenceExceptions like from this crap WCF if you don't configure it correctly.
If you use WCF and the 3.5 Framework, it couldn't be easier. When you mark your OperationContracts with the WebGet attribute, just set the ResponseFormat parameter to WebMessageFormat.Json. When the service is accessed RESTfully, it will return the data using the DataContractJsonSerializer. It's really helpful to mark the POCOs that you want to JSON serialize as [DataContract] and to mark each serializable member as [DataMember]. Otherwise, you end up with funky JSON, as Rick pointed out in his blog post.
wcf json web service
[ "", "c#", ".net", "wcf", "json", "" ]
I am trying to parse some .txt files. These files serve as containers for a variable number of 'children' files that are set off or identified within the container with SGML tags. With python I can easily separate the children files. However I am having trouble writing the binary content back out as a binary file (say a gif or jpg). In the simplest case the container might have an embedded html file followed by a graphic that is called by the html. I am assuming that my problem is because I am reading the original .txt file using open(filename,'r'). But that seems the only option to find the sgml tags to split the file. I would appreciate any help to identify some relevant reading material. I appreciate the suggestions but I am still struggling with the most basic questions. For example when I open the file with wordpad and scroll down to the section tagged as a gif I see this: ``` <FILENAME>h65803h6580301.gif <DESCRIPTION>GRAPHIC <TEXT> begin 644 h65803h6580301.gif M1TE&.#EA(P)I`=4@`("`@,#`P$!`0+^_OW]_?_#P\*"@H.#@X-#0T&!@8!`0 M$+"PL"`@('!P<)"0D#`P,%!04#\_/^_O[Y^?GZ^OK]_?WX^/C\_/SV]O;U]? ``` I can handle finding the section easily enough but where does the gif file begin. Does the header start with 644, the blanks after the word begin or the line beginning with MITE? Next, when the file is read into python does it do anything to the binary code that has to be undone when it is read back out? I can find the lines where the graphics begin: ``` filerefbin=file('myfile.txt','rb') wholeFile=filerefbin.read() import re graphicReg=re.compile('<DESCRIPTION>GRAPHIC') locationGraphics=graphicReg.finditer(wholeFile) graphicsTags=[] for match in locationGraphics: graphicsTags.append(match.span()) ``` I can easily use the same process to get to the word begin, or to identify the filename and get to the end of the filename in the 'first' line. I have also successefully gotten to the end of the embedded gif file. But I can't seem to write out the correct combination of things so when I double click on h65803h6580301.gif when it has been isolated and saved I get to see the graphic. Interestingly, when I open the file in rb, the line endings appear to still be present even though they don't seem to have any effect in notebpad. So that is clearly one of my problems I might need to readlines and join the lines together after stripping out the \n I love this site and I love PYTHON This was too easy once I read bendin's post. I just had to snip the section that began with the word begin and save that in a txt file and then run the following command: ``` import uu uu.decode(r'c:\test2.txt',r'c:\test.gif') ``` I have to work with some other stuff for the rest of the day but I will post more here as I look at this more closely. The first thing I need to discover is how to use something other than a file, that is since I read the whole .txt file into memory and clipped out the section that has the image I need to work with the clipped section instead of writing it out to test2.txt. I am sure that can be done its just figuring out how to do it.
What you're looking at isn't "binary", it's **[uuencoded](http://en.wikipedia.org/wiki/Uuencode)**. Python's standard library includes the module [uu](http://docs.python.org/library/uu.html#module-uu), to handle uuencoded data. The module [uu](http://docs.python.org/library/uu.html#module-uu) requires the use of temporary files for encoding and decoding. You can accomplish this without resorting to temporary files by using Python's [codecs](http://docs.python.org/library/codecs.html) module like this: ``` import codecs data = "Let's just pretend that this is binary data, ok?" uuencode = codecs.getencoder("uu") data_uu, n = uuencode(data) uudecode = codecs.getdecoder("uu") decoded, m = uudecode(data_uu) print """* The initial input: %(data)s * Encoding these %(n)d bytes produces: %(data_uu)s * When we decode these %(m)d bytes, we get the original data back: %(decoded)s""" % globals() ```
You definitely need to be reading in binary mode if the content includes JPEG images. As well, Python includes an SGML parser, <http://docs.python.org/library/sgmllib.html> . There is no example there, but all you need to do is setup do\_ methods to handle the sgml tags you wish.
How to separate content from a file that is a container for binary and other forms of content
[ "", "python", "text", "encoding", "file", "binary", "" ]
I am still getting started with Unity, and have what seems to be a simple question. I have a class that has a dependency on two different instances of the same interface. How do I configure and resolve this class? I.E. Given: ``` public interface ILogger { void Write(string message); } public class ConsoleLogger : ILogger { public void Write(string message) { Console.WriteLine(message); } } public class AnotherLogger : ILogger { public void Write(string message) { Console.WriteLine(DateTime.Now.ToString() + " " + message); } } public class CombinedLogger : ILogger { IList<ILogger> _loggers; public CombinedLogger(params ILogger[] loggers) { _loggers = new List<ILogger>(loggers); } public void Write(string message) { foreach(var logger in _loggers) logger.Write(message); } } ``` I know how to configure for ConsoleLogger, and AnotherLogger. I also know how to access them in the actual code. What I seem to be blocking on is figuring out how to configure and use CombinedLogger, passing in the instances of ConsoleLogger and AnotherLogger.
Read the documentation on [configuration support for arrays](http://msdn.microsoft.com/en-us/library/dd203195.aspx).
``` IUnityContainer container = new UnityContainer(); container.RegisterType<ILogger, ConsoleLogger>(); container.RegisterType<ILogger, AnotherLogger>("another"); container.RegisterType<ILogger, CombinedLogger>("combined"); var instances = container.ResolveAll<ILogger>(); ```
How do I configure Unity to create a class that takes two different items of same type?
[ "", "c#", "unity-container", "" ]
Am I right in thinking that until I am able to afford dedicated servers or have any spare servers, I could successfully run a small number of memcached servers through EC2? With the annoucement of the new auto-scaling and load balancing by Amazon today, do you guys think this would be a viable option? And what would be the basic technical steps you'd recommend me taking? Thanks Currently, I have one dedicated server and no memcached servers. I want to use the power of EC2 to setup a few instances and run such memcached servers. That's my current setup.
* Load balancing has nothing to do with Memcached -- it uses a hash algorithm for connecting to servers * I highly recommend not using autoscaling with Memcached -- adding servers breaks the hashing algorithm and invalidates your cache. Data will go missing and you'll have to recache. * You'll want to check the latency from your servers to EC2 -- if it's more than 50ms, you'll be hurting your performance significantly. Well, I'd assume anyway. You can pull multiple keys (see [here for how](https://www.php.net/manual/en/memcached.getmulti.php)) with one request to reduce the latency effect, but you'll still take the initial hit. And it also means you need to know all the keys your going to get before you make the call. Otherwise each request adds 50ms (or more) to the execution time of your script. Consider the data your trying to cache. Is a 64mb slab large enough to help you? You can probably run it on your main servers.
To really take advantage of memcached you need to have your memcache communicating with your code as quickly as possible. You may want to investigate how much latency you'd have between the EC2 servers and your own. Ultimately, you might be better served upping the ram on your current box to something like 4 gigs (should run you about 50 bucks) and putting memcached on the main server. The documentation actually recommends that you install memcached on the same server that is serving out requests. Depending on the size of your application and what it does, a memcached instance with a gig or two may be way more than what you need. Also, if you're not using a php object caching engine like APC or Eaccelerator, that will also help.
Memcached on EC2
[ "", "php", "memcached", "amazon-ec2", "load-balancing", "" ]
Note: I'm a newb to Continuous Integration What is the "best" approach to get these functions: 1. Build (assemblies and web app) 2. Testing (MbUnit or NUnit) 3. and if it passes tests deploy via FTP to the main server (internet). And what I mean by "best" is cheapest option, and easy to learn (low headache).
I have written a pretty detailed blog post using TeamCity, and Web Deployment projects to automate build and deployment (local) here: <http://www.diaryofaninja.com/blog/2010/05/09/automated-site-deployments-with-teamcity-deployment-projects-amp-svn> I have then added to this to show FTP addition <http://www.diaryofaninja.com/blog/2010/09/21/continuous-integration-tip-1-ndash-ftp-deployment> Basically the process is like this: * Using a teamcity build server i download from my SVN repo * I build and deploy the site to a local folder on the build server * I fire a command line FTP client that supports scripting called WinSCP using the MSBUILD Task EXEC (<http://winscp.net/>) * Upload all my sites content * Have *insert beverage of choice* I then make sure that i only deploy the Trunk of my SVN repo, and develop and test everything in an branch before merging - this way only tested stuff gets deployed. Add Automated testing to your build cycle and you've got a match made in heaven.
I would go with msbuild and mbunit for the unit tests. For the FTP part google for msbuild custom tasks with FTP and you should be cooking on gas.
C#/.NET - Continuous Integration and FTP Deployment
[ "", "c#", ".net", "deployment", "ftp", "continuous-integration", "" ]
In a `ListView` control, the focus is on some `Item` within that control - that is, the control maintains its own internal notion of what is in focus, which can be retrieved using the `FocusedItem` property. I would like *no* items to be focused. In other words, I want the `FocusedItem` property to set to `null`. Any idea how I might accomplish this?
To expand on Vanuan's answer: ``` if (listView1.FocusedItem != null) { listView1.FocusedItem.Focused = false; } ``` Something tells me that you also want to un-select the item. So, you probably want to do this as well: ``` if (listView1.SelectedItems.Count != 0) { listView1.SelectedItems[0].Selected = false; } ```
I think, it is ``` listView1.FocusedItem.Focused=false; ``` Make sure that listView1.FocusedItem is not null. (Thanks to **brianpeiris** for expanding)
How might I remove focus from all items in a ListView control?
[ "", "c#", "winforms", "listview", "" ]
i have a form and would like to give users the ability to duplicate a group of fields as many times as necessary. With one group it iterates correctly but when I add a second group the "current" variable iterates collectively instead of being unique to each group... i tried changing all of the "current" to "newFieldset.current" but that returns NAN... any ideas? ``` <script type="text/javascript"> $(document).ready(function() { var current = 0; //Add New Fieldset with Button var newFieldset = { init: function(groupIndex) { current++; $newPerson= $("#Template"+groupIndex).clone(true); $newPerson.children("p").children("label").each(function(i) { var $currentElem= $(this); $currentElem.attr("for",$currentElem.attr("for")+current); }); $newPerson.children("p").children("input").each(function(i) { var $currentElem= $(this); $currentElem.attr("name",$currentElem.attr("name")+current); $currentElem.attr("value",$currentElem.attr("value")+groupIndex+current); $currentElem.attr("id",$currentElem.attr("id")+current); }); $newPerson.appendTo("#mainField"+groupIndex); $newPerson.removeClass("hideElement"); }, currentID: null, obj: null }; $(".addButton").each(function() { $(this).click(function() { var groupIndex = $(this).attr("title"); //newFieldset.obj = this; //var fieldIndex = $(this).attr("class"); newFieldset.init(groupIndex); }); }); console.log('r'); }); </script> <style> .hideElement {display:none;} </style> <form name="demoForm" id="demoForm" method="post" action="#"> <div id="groupCtr1"> <fieldset id="mainField1"> <div id="Template1" class="hideElement"> <p> <label for="firstname">Name</label> <em>*</em> <input id="firstname" name="firstname" size="25" /> <input id="lastname" name="lastname" size="25" /> </p> <p> <label for="email">Email</label> <em>*</em><input id="email" name="email" size="25" /> </p> </div> <div> <p> <label for="firstname1">Name</label> <em>*</em> <input id="firstname1" name="firstname1" size="25" /> <input id="lastname1" name="lastname1" size="25" /> </p> <p> <label for="email1">Email</label> <em>*</em><input id="email1" name="email1" size="25" /> </p> </div> </fieldset> <p> <input type="button" class="addButton" title="1" value="Add Another Person"> </p> </div> <div id="groupCtr2"> <fieldset id="mainField2"> <div id="Template2" class="hideElement"> <p> <label for="coname">Company Name</label> <em>*</em> <input id="coname" name="coname" size="25" /> </p> <p> <label for="codesc">Description</label> <em>*</em><input id="codesc" name="codesc" size="25" /> </p> </div> <div> <p> <label for="coname1">Company Name</label> <em>*</em> <input id="coname1" name="coname1" size="25" /> </p> <p> <label for="codesc1">Description</label> <em>*</em><input id="codesc1" name="codesc1" size="25" /> </p> </div> </fieldset> <p> <input type="button" class="addButton" title="2" value="Add Another Company"> </p> </div> <input type="submit" value="Save"> </form> ```
Attach the value to the element with the jQuery data method. Increment it on click, and then pass it to the newFieldset.init method as the second param. Voila! ``` $(document).ready(function() { //Add New Fieldset with Button var newFieldset = { init: function(groupIndex,current) { $newPerson= $("#Template"+groupIndex).clone(true); $newPerson.children("p").children("label").each(function(i) { var $currentElem= $(this); $currentElem.attr("for",$currentElem.attr("for")+current); }); $newPerson.children("p").children("input").each(function(i) { var $currentElem= $(this); $currentElem.attr("name",$currentElem.attr("name")+current); $currentElem.attr("value",$currentElem.attr("value")+groupIndex+current); $currentElem.attr("id",$currentElem.attr("id")+current); }); $newPerson.appendTo("#mainField"+groupIndex); $newPerson.removeClass("hideElement"); }, currentID: null, obj: null }; $(".addButton").click(function() { var groupIndex = $(this).attr("title"); var current = $(this).data('current'); $(this).data('current',++current); //newFieldset.obj = this; //var fieldIndex = $(this).attr("class"); newFieldset.init(groupIndex,current); }).data('current',0); console.log('r'); }); ``` Happy jquery-ing to you sir.
I would do something like that: ``` ... var currents = {}; var newFieldset = { init: function(groupIndex) { var current = 0; if (currents[groupIndex]) { current = currents[groupIndex]; } ++current; currents[groupIndex] = current; ... ```
Mutilple javascript variable iterations with jquery
[ "", "javascript", "jquery", "forms", "iteration", "" ]
I am trying to make a Java implementation of the Park-Miller-Carta PRNG random number generator. Below is the implementation of the Random function in ActionScript 3 [from here](http://www.gskinner.com/blog/archives/2008/01/source_code_see.html). ``` return (_currentSeed = (_currentSeed * 16807) % 2147483647) / 0x7FFFFFFF + 0.000000000233; ``` I am not having much luck getting this to work in Java: ``` int seed = 20; //for example. public double random() { seed = (seed * 16807) % 2147483647; return seed / 0x7FFFFFFF + 0.000000000233; } ``` This always returns `2.33E-10`. Any ideas what I am doing wrong in Java? (the AS3 code returns `0.0001565276181885122`, then `0.6307557630963248` for the first two responses with a seed of `20`).
``` seed / 0x7FFFFFFF ``` is an integer operation, since both arguments are integers. Integer division always rounds the "true" result downwards. In this case, the true result is between 0 and 1, so the operation always returns 0. To get a floating-point result, at least one of the arguments must be a float, which can be achieved like this: ``` return (double)seed / 0x7FFFFFFF + 0.000000000233; ```
OK, so the essential problem is that you need to do floating-point division, not integer division, as others have pointed out. But I think fixing this particular code is sort of besides the point. Why bother with it in the first place? It's using essentially the same class of algorithm is java.lang.Random! If you want a fast generator, consider an [XORShift generator](http://www.javamex.com/tutorials/random_numbers/xorshift.shtml). If you want a good-quality generator, you have [SecureRandom](http://www.javamex.com/tutorials/random_numbers/securerandom.shtml) out of the box (though it's much slower), consider the Numerical Recipes algorithm (a fairly fast, combined generator), which you could implement in Java as follows: ``` public class HighQualityRandom extends Random { private Lock l = new ReentrantLock(); private long u; private long v = 4101842887655102017L; private long w = 1; public HighQualityRandom() { this(System.nanoTime()); } public HighQualityRandom(long seed) { l.lock(); u = seed ^ v; nextLong(); v = u; nextLong(); w = v; nextLong(); l.unlock(); } @Override public long nextLong() { l.lock(); try { u = u * 2862933555777941757L + 7046029254386353087L; v ^= v >>> 17; v ^= v << 31; v ^= v >>> 8; w = 4294957665L * (w & 0xffffffff) + (w >>> 32); long x = u ^ (u << 21); x ^= x >>> 35; x ^= x << 4; return (x + v) ^ w; } finally { l.unlock(); } } protected int next(int bits) { return (int) (nextLong() >>> (64-bits)); } } ``` This is copied from some code where I needed it to be concurrent; you could get rid of the lock in principle, or just use regular synchronization. If you absolutely insist on using Park-Miller-Carta, I'd at least wrap it in a Random subclass, and let java.util.Random take care of converting ints to doubles etc-- after all, that's what extensible libraries in an object-oriented language are for...
Park-Miller-Carta PRNG random generator allways returns 2.33E-10
[ "", "java", "actionscript-3", "random", "" ]
If I have a class that contains a number of `typedef`'d variables, like so: ``` class X { typedef token TokenType; bool doStuff() { TokenType data; fillData(&data); return true; } }; ``` Is there any way to override the `typedef` for `TokenType` in a derived class? N.B. This is NOT a good place to use templates (This is already a templated class and any changes are likely to result in [EDIT: *infinite*] recursive definitions [`class X < class Y = class X < class Y . . .> >` etc.].)
What you can do is shadow, but not override. That is: you can define a derived class Y with its own typedefs for TokenType, but that will only come into play if somebody references Y::TokenType directly or via an object statically typed as Y. Any code that references X::TokenType statically will do so even for objects of type Y.
Typedefs are resolved at compile time – making them overridable would be meaningless, since overriding is a feature of *runtime* polymorphism. Simply redeclaring the typedef will work – though I'm not sure why you think templates would be a bad idea here – recursive templates are actually feasible.
TypeDef as an overridable class feature
[ "", "c++", "typedef", "" ]
I would like to parse the values from aspx pages, both what is passed before the ? and after it? So, what is the C# function that allows me to parse that out? I would like to do something like: ``` var pageType = parameter.trimBefore?(); var pageString = parameter.trimAfter?(); ``` Thanks for any advice.
Try the Split method in string. You provide the delimiter, ?, in this case, and the method will divide the string into the string that comes before the character and after the character. ``` String[] urlComponents = myUrl.Split('?') ```
`Request.QueryString` and `Request.Uri` should get you those values without string manipulation.
ASP.NET - How to strip Query String after/before ? from ASPX parameter passing?
[ "", "c#", "asp.net", "" ]
I have a rather enormous project in which I'm trying to retrofit in-memory data. Essentially, I have a big collection of objects which contain primitives and other objects which exist in hibernate. Large sections of non-dao code rely on lazy-loading through hibernate to hydrate objects on the fly. However, since everything exists in memory, my object are not loaded, and I get hibernate lazy loading exceptions. I could just manually implement hibernate lazy loading by dipping to hibernate and hydrating the hibernate object manually, but the object graph for that object is huge, containing hundreds of types that would need to be initialized and set. This seems impractical, and I'm looking for a viable solution to this problem. If anyone has ANY kind of tips, hints, solutions, or stories relating to this kind of problem or similar problems, I would be very grateful. Thanks much.
If you are handling the sessions by hand, try passing object ids (row ids in the database) instead of full objects. Then preform a database read when you want to get the full blown ORM object and only keep the ORM object in a limited scope so it could be garbage collected when you were done with it. This would probably save you some memory. This has a side effect of also limiting the amount of time you need an open session for. As you could open sessions (I would recommend a session factory) and close them as needed. However, I think there may be a significant database hit for opening and closing sessions (I think the underlying transaction is the real problem). You may want to look into JPA, which as far as I understand, doesn't need a transaction for reads. Spring also has some nice features to automate transaction and session management they may want to investigate.
You probably have session already closed. Try to keep the session open when data is lazy loaded or if this is not possible, do eager load by specifying lazy="false" attribute on the collection (lazy="true" is the default).
How can I pull objects out of hibernate and into memory. I'm hitting session problems
[ "", "java", "hibernate", "session", "lazy-loading", "in-memory", "" ]
How do I unbind "hover" in jQuery? This does not work: ``` $(this).unbind('hover'); ```
`$(this).unbind('mouseenter').unbind('mouseleave')` or more succinctly (thanks *@Chad Grant*): `$(this).unbind('mouseenter mouseleave')`
Actually, the [jQuery documentation](http://docs.jquery.com/Events/hover#overout) has a more simple approach than the chained examples shown above (although they'll work just fine): ``` $("#myElement").unbind('mouseenter mouseleave'); ``` As of jQuery 1.7, you are also able use [`$.on()`](http://api.jquery.com/on/) and [`$.off()`](http://api.jquery.com/off/) for event binding, so to unbind the hover event, you would use the simpler and tidier: ``` $('#myElement').off('hover'); ``` The pseudo-event-name "hover" [is used as a shorthand](http://api.jquery.com/on/#additional-notes) for "mouseenter mouseleave" but was handled differently in earlier jQuery versions; requiring you to expressly remove each of the literal event names. Using `$.off()` now allows you to drop both mouse events using the same shorthand. **Edit 2016:** Still a popular question so it's worth drawing attention to [@Dennis98](https://stackoverflow.com/users/3439786/dennis98)'s point in the comments below that in jQuery 1.9+, the "hover" event was [deprecated](https://bugs.jquery.com/ticket/12736) in favour of the standard "mouseenter mouseleave" calls. So your event binding declaration should now look like this: `$('#myElement').off('mouseenter mouseleave');`
How do I unbind "hover" in jQuery?
[ "", "javascript", "jquery", "" ]
I wish to send an email from my localhost machine (using PHPs mail function) but I can not do this since I don't have a mail server. In addition, I need to be able to send emails through a network that is heavily firewalled (to what extent I do not know yet). My idea is to make use of "QK SMTP Server 3" and get that to use an external server I have as a "Relay server". Will this work? Is there an easier option? If my approach is Ok. I would like to know how I can open port 25 on my server so it can receive this request. By executing this command I get: ``` [root@balder296 ~]# service iptables status Firewall is stopped. [root@balder296 ~]# ``` Thank you for any help and advice. ## Solved Hotmail (surprisingly) provides a free relay service. I hope this works for me when I test this! But an external mail server is the way to go.
Figure out if you can connect to the Internet on port 25 (SMTP) * `telnet gmail-smtp-in.l.google.com 25` (this is one of the Gmail servers) If you're able to open up a connection, you can simply install a mail-server and use the mail() function to send messages. * `yum install postfix` (for example, from your 'service' remark I assume you're running Redhat or Centos) If you're unable to connect to Internet mail servers on port 25, you can try finding an internal mail relay (this is something you will have to find yourself, depending on your network). At that point you have two options. You can use the internal mail() function with your local mail server if you define the 'relay' parameter in your mails-server (/etc/postfix if you're using Postfix). The other option is to follow [this guide](http://www.dreamincode.net/forums/showtopic36108.htm) and get get PHP to send the messages to an internal relay.
Maybe there is a (good?) reason which explain why the network where you are is heavily firewalled. Why don't you ask guy's from the network what is the good solution to send mail ?
How to send emails with PHP from a heavily firewalled network?
[ "", "php", "email", "smtp", "firewall", "mail-server", "" ]
I'm trying to decide the best way of having radiobuttons switch around the contents of a panel (or another container), using Windows Forms .NET (C#), and maintaining the ability to use the Visual Studio designer on the form/usercontrol that contains these. What I'd really like is something like the TabControl where I can select the pages programmatically based on which radiobutton is checked, but without the display of the actual tabs. The reason I'm not just using a tabcontrol is that using the currently selected tab as an input-value seems wrong. The obvious solution is to simply have a panel for each radiobutton, and switch them around using visibility and such - but this is annoying to work with in the Visual Studio designer, as these panels will either be hidden beneath each other or not in the correct position (and the overall form not in the right size if there's no room for more than the one panel that should be shown at a time.) I seem to remember Delphi having a PageControl or something like this, which was basically a tabcontrol without the tab-header. It seems to me that this is a situation that often arises, so I'm curious: How would you set something like this up?
I guess I would simply build such a page control. Can't be too hard, I guess (even though design time support tend to be a tad more complicated than you would wish for sometimes...)
I always played with the visibility feature.
.NET Radiobuttons "content" design
[ "", "c#", ".net", "winforms", "radio-button", "" ]
I have a timer that needs to not process its elapsed event handler at the same time. But processing one Elapsed event *may* interfere with others. I implemented the below solution, but something feels wrong; it seems like either I should be using the timer differently or using another object within the threading space. The timer seemed to fit best because I do need to periodically check for a status, but sometimes checking will take longer than my interval. Is this the best way to approach this? ``` // member variable private static readonly object timerLock = new object(); private bool found = false; // elsewhere timer.Interval = TimeSpan.FromSeconds(5).TotalMilliseconds; timer.Elapsed = Timer_OnElapsed; timer.Start(); public void Timer_OnElapsed(object sender, ElapsedEventArgs e) { lock(timerLock) { if (!found) { found = LookForItWhichMightTakeALongTime(); } } } ```
You could set AutoReset to false, then explicitly reset the timer after you are done handling it. Of course, how you handle it really depends on how you expect the timer to operate. Doing it this way would allow your timer to drift away from the actual specified interval (as would stopping and restarting). Your mechanism would allow each interval to fire and be handled but it may result in a backlog of unhandled events that are handled now where near the expiration of the timer that cause the handler to be invoked. ``` timer.Interval = TimeSpan.FromSeconds(5).TotalMilliseconds; timer.Elapsed += Timer_OnElapsed; timer.AutoReset = false; timer.Start(); public void Timer_OnElapsed(object sender, ElapsedEventArgs e) { if (!found) { found = LookForItWhichMightTakeALongTime(); } timer.Start(); } ```
I usually stop the timer while processing it, enter a try/finally block, and resume the timer when done.
How to block a timer while processing the elapsed event?
[ "", "c#", ".net", "multithreading", "timer", "" ]
What is main difference between `INSERT INTO table VALUES ..` and `INSERT INTO table SET`? Example: ``` INSERT INTO table (a, b, c) VALUES (1,2,3) INSERT INTO table SET a=1, b=2, c=3 ``` And what about performance of these two?
As far as I can tell, both syntaxes are equivalent. The first is SQL standard, the second is MySQL's extension. So they should be exactly equivalent performance wise. <http://dev.mysql.com/doc/refman/5.6/en/insert.html> says: > INSERT inserts new rows into an existing table. The INSERT ... VALUES and INSERT ... SET forms of the statement insert rows based on explicitly specified values. The INSERT ... SELECT form inserts rows selected from another table or tables.
I think the extension is intended to allow a similar syntax for inserts and updates. In Oracle, a similar syntactical trick is: ``` UPDATE table SET (col1, col2) = (SELECT val1, val2 FROM dual) ```
MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET
[ "", "sql", "mysql", "performance", "" ]
Consider the following: ``` @property def name(self): if not hasattr(self, '_name'): # expensive calculation self._name = 1 + 1 return self._name ``` I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;) PS the real calculation doesn't depend on mutable values
**Python 3.8 `functools.cached_property` decorator** <https://docs.python.org/dev/library/functools.html#functools.cached_property> `cached_property` from Werkzeug was mentioned at: <https://stackoverflow.com/a/5295190/895245> but a supposedly derived version will be merged into 3.8, which is awesome. This decorator can be seen as caching `@property`, or as a cleaner `@functools.lru_cache` for when you don't have any arguments. The docs say: > ``` > @functools.cached_property(func) > ``` > > Transform a method of a class into a property whose value is computed once and then cached as a normal attribute for the life of the instance. Similar to property(), with the addition of caching. Useful for expensive computed properties of instances that are otherwise effectively immutable. > > Example: > > ``` > class DataSet: > def __init__(self, sequence_of_numbers): > self._data = sequence_of_numbers > > @cached_property > def stdev(self): > return statistics.stdev(self._data) > > @cached_property > def variance(self): > return statistics.variance(self._data) > ``` > > New in version 3.8. > > Note This decorator requires that the **dict** attribute on each instance be a mutable mapping. This means it will not work with some types, such as metaclasses (since the **dict** attributes on type instances are read-only proxies for the class namespace), and those that specify **slots** without including **dict** as one of the defined slots (as such classes don’t provide a **dict** attribute at all).
Starting from Python 3.2 there is a built-in decorator: [`@functools.lru_cache(maxsize=100, typed=False)`](http://docs.python.org/dev/library/functools.html#functools.lru_cache) > Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments. Example of an LRU cache for computing [Fibonacci numbers](http://en.wikipedia.org/wiki/Fibonacci_number): ``` from functools import lru_cache @lru_cache(maxsize=None) def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) >>> print([fib(n) for n in range(16)]) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] >>> print(fib.cache_info()) CacheInfo(hits=28, misses=16, maxsize=None, currsize=16) ``` --- If you are stuck with Python 2.x, here's a list of other compatible memoization libraries: * `functools32` | [PyPI](https://pypi.python.org/pypi/functools32) | [Source code](https://github.com/MiCHiLU/python-functools32) * `repoze.lru` | [PyPI](https://pypi.python.org/pypi/repoze.lru/) | [Source code](https://github.com/repoze/repoze.lru) * `pylru` | [PyPI](https://pypi.python.org/pypi/pylru/) | [Source code](https://github.com/jlhutch/pylru) * `backports.functools_lru_cache` | [PyPI](https://pypi.python.org/pypi/backports.functools_lru_cache) | [Source code](https://github.com/jaraco/backports.functools_lru_cache)
Is there a decorator to simply cache function return values?
[ "", "python", "caching", "decorator", "memoization", "" ]
I have a Java project that needs a "addon" interface. I was thinking about loading some kind of class files having default methods like `initialize()` and `shutdown()` that will be called after the class has been loaded into the application. Is this the way to do it? How would I approach this problem?
Have a look at the [Class](http://java.sun.com/javase/6/docs/api/java/lang/Class.html) class, specifically the [forName](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#forName(java.lang.String)) method, which allows you to reference a class by name. Any class in the path can be loaded like this. Whether *reloading* is possible I don't know. In any case, each class that you want to dynamically load would have to implement your custom `AddOn` interface, thus implementing `initialize` and `shutdown`.
First, you will need a [`ClassLoader`](http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html); you can get the current one with `getClass().getClassLoader()`, but then your addon classes must be in the classpath. You'll probably want to create a custom classloader that searches your addon directory. Once you've got the `ClassLoader`, you can use it to [load a class](http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html#loadClass(java.lang.String)). This gives you a [`Class`](http://java.sun.com/javase/6/docs/api/java/lang/Class.html) object; you can then use reflection to call the `initialize()` method if it is present.
Including Java classes and running them during runtime
[ "", "java", "reflection", "dynamic-loading", "" ]
I need to get all the objects whose id matches a specific pattern . How can I do it? Thanks!
Current Browsers: ``` // DOM collection as proper array const matches = Array.from(document.querySelectorAll('[id^=log_]')); ``` --- Older Browsers: (IE9+) ``` // Use Array.prototype.slice to turn the DOM collection into a proper array var matches = [].slice.call(document.querySelectorAll('[id^=log_]')); ``` --- jQuery: ``` $('[id^=log_]') ``` --- Really Old Browsers, no jQuery: ``` var matches = []; var elems = document.getElementsByTagName("*"); for (var i=0; i<elems.length; i++) { if (elems[i].id.indexOf("log_") == 0) matches.push(elems[i]); } //matches now is an array of all matching elements. ```
Ok, here's a straight JavaScript answer: ``` // a handy function to aid in filtering: // takes an array and a function, returns another array containing // only those elements for which f() returns true function filter(a, f) { var ret = []; for (var i=0; i<a.length; ++i) { if ( f(a[i]) ) ret.push(a[i]); } return ret; } // this collects all elements in the current document var elements = document.getElementsByTagName("*"); // and this filters out all but those that match our pattern var logElements = filter(elements, function(el) { return /log_/.test(el.id) } ); // simple expression ```
Javascript : get all the object where id is like log_XXXX
[ "", "javascript", "" ]
I have read some posts on here about not mixing parameters when passing into a constructor, but have a question. I have classes and they all depend on a company parameter, all of the methods are dependent on the company. I do not want to have to pass the company in on every method call, I would like to pass that into the constructor. This does make it difficult on the classes because I have to pretty much make sure the constructors of the concrete classes take in certain parameteres, which I am not a fan of (cannot put that in the contract that is the interface). Recommend just passing the company into every method call in the class???
If all the methods require a company name then it is perfectly reasonable from a OOP design point of view to pass this company name into the constructor of your class. This means that your class cannot function correctly without a company name so any consumer of the class will be forced to supply required dependency.
Assuming you aren't working with a known IoC framework which already handles this for you, you could always implement this as property injection. Not that I see a problem with doing this at the constructor level either - you haven't really said why you feel that's a problem. Certainly wouldn't recommend passing it to every method (clearly redundant).
IOC and dynamic parameters
[ "", "c#", "inversion-of-control", "" ]
I would like to listen for the mouse over event in GWT 1.6. Since GWT 1.6 has introduced handlers and deprecated listeners I'm unsure as to how I can accomplish this with what little information exists. Note: I have an Element object. That's what I need to add the mouse handler to. I apologize for my lack of clarity. Thanks!
I was hoping we'd see an answer before I needed to tackle this myself. There are some errors in the example code he posted, but the [post by Mark Renouf in this thread](http://groups.google.com/group/Google-Web-Toolkit/browse_thread/thread/b2eae8c3700291fb/d879a9c2a2796a76?lnk=raot) has most of what we need. Let's say you want to listen for mouse over and mouse out events on a custom widget. In your widget, add two methods: ``` public HandlerRegistration addMouseOverHandler(MouseOverHandler handler) { return addDomHandler(handler, MouseOverEvent.getType()); } public HandlerRegistration addMouseOutHandler(MouseOutHandler handler) { return addDomHandler(handler, MouseOutEvent.getType()); } ``` Then create a handler class: ``` public class MyMouseEventHandler implements MouseOverHandler, MouseOutHandler { public void onMouseOver(final MouseOverEvent moe) { Widget widget = (Widget) moe.getSource(); widget.addStyleName("my-mouse-over"); } public void onMouseOut(final MouseOutEvent moe) { Widget widget = (Widget) moe.getSource(); widget.removeStyleName("my-mouse-over"); } } ``` Finally, add the handler to the widget: ``` myWidget.addMouseOverHandler(new MyMouseEventHandler()); myWidget.addMouseOutHandler(new MyMouseEventHandler()); ``` If you are only listening to the mouse over event, you can skip the mouse out handling. And if you aren't making a custom widget, the widget my already have a method to add the handler. Finally, per the warning from the thread, remember to `addDomHandler` for the mouse events, not `addHandler`.
You'd want to implement these interfaces in your class: * HasMouseOverHandlers * HasMouseOutHandlers * MouseOverHandler * MouseOutHandler MouseOverEvent is fired when the mouse enters the element, and MouseOutEvent is fired when it's no longer over. **HasMouseOverHandler** is implemented like this: ``` public HandlerRegistration addMouseOverHandler(MouseOverHandler handler) { return addDomHandler(handler, MouseOverEvent.getType()); } ``` **HasMouseOutHandler** is implemented like this: ``` public HandlerRegistration addMouseOutHandler(MouseOutHandler handler) { return addDomHandler(handler, MouseOutEvent.getType()); } ``` After that you just handle the events with a MouseOverHandler and MouseOutHandler, should be pretty straightforward after that. If you want to add an EventHandler to an Element that already exists in the HTML the only idea I've come up with is creating a wrapper class. **This is completely untested.** ``` class ElementWrapper extends UIObject implements HasMouseOverHandlers, HasMouseOutHandlers { public ElementWrapper(Element theElement) { setElement(theElement); } public HandlerRegistration addMouseOutHandler(MouseOutHandler handler) { return addDomHandler(handler, MouseOutEvent.getType()); } public HandlerRegistration addMouseOverHandler(MouseOverHandler handler) { return addDomHandler(handler, MouseOverEvent.getType()); } } ``` Then you could get an existing Element from the HTML and initialize like this: ``` onModuleLoad() { Element theElement = RootPanel().get("elementID"); ElementWrapper wrapper = new ElementWrapper(theElement); wrapper.addMouseOverHandler(new myHandler()); } ``` Hope this helps.
Adding a MouseOverHandler to an Element?
[ "", "java", "gwt", "" ]
I cannot get my SID working ... ``` <?php session_start(); // Or maybe pass along the session id, if needed echo '<br /><a href="page2.php?' . SID . '">page 2</a>';?> ``` does not show up SID number but session\_id is working not sure if I am missing something. THnks
You need to have [`session.use_trans_sid`](http://docs.php.net/manual/en/session.configuration.php#ini.session.use-trans-sid) enabled to have PHP accept a session ID passed by either GET or POST.
The SID constant will show an empty string if a a cookie with the name of [session.name](http://www.php.net/manual/en/session.configuration.php#ini.session.name) has been detected by PHP. See [the manual page](http://www.php.net/manual/en/session.constants.php). That means, that SID will contain a useful string only before the session cookie has been sent to the browser. That also means that if a browser refuses cookies the SID constant will work. Provided that seesion.use\_trans\_id is enabled, as Gumbo said.
PHP SID not showing
[ "", "php", "" ]
Is there a way to access SQLite results by column name (like a C++ Map) instead of index number in C/C++? For example, Python's SQLite access allows dictionary access ``` Results = Query("SELECT * FROM table"); print Results['colname'] print Results['anothercol'] ``` Any similar methods available in C++ for the SQLite's interface?
I'd go with Daniel in recommending SQLAPI++ at www.sqlapi.com -- at <http://www.sqlapi.com/HowTo/fetch.html> you can find a simple example of fetching fields by name. The example is a bit verbose so here's a code-only gist: ``` void showemps(SAConnection* pconn, int minage) { SACommand cmd(pconn, "select name, age from employees where age>:1"); cmd << minage; cmd.execute(); while(cmd.FetchNext()) { SAString sName = cmd.Field("name"); long nAge = cmd.Field("age"); printf("Name: %s, age: %d \n", sName, nAge); } } ```
**newer answer** <http://www.sqlapi.com/> This library might do what you want it to. **old answer** Basically you will have to iterate the columns with `sqlite3_column_name16` or `sqlite3_column_name`. You will have to compare the strings these return with the one you want to look up. I have used this, its MFC, but it gives you the basic idea of what needs done. ``` int CSQLite3Query::FieldIndex(const CString &field) { CheckVM(); if ( !field.IsEmpty() ) { for ( int nField = 0; nField < m_nCols; nField++ ) { #ifdef UNICODE CString sTemp = (LPCTSTR)sqlite3_column_name16(m_VM, nField); #else CString sTemp = (LPCTSTR)sqlite3_column_name(m_VM, nField); #endif if (sTemp == field) return nField; } } else { throw new CSQLite3Exception(MFCSQLITE3_ERROR, MFCSQLITE3_INVALID_FIELD_NAME); } return -1; } ```
SQLite C++ Access Columns by Name
[ "", "c++", "c", "sqlite", "dictionary", "" ]
I have an app that needs to read a PDF file from the file system and then write it out to the user. The PDF is 183KB and seems to work perfectly. When I use the code at the bottom the browser gets a file 224KB and I get a message from Acrobat Reader saying the file is damaged and cannot be repaired. Here is my code (I've also tried using File.ReadAllBytes(), but I get the same thing): ``` using (FileStream fs = File.OpenRead(path)) { int length = (int)fs.Length; byte[] buffer; using (BinaryReader br = new BinaryReader(fs)) { buffer = br.ReadBytes(length); } Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", Path.GetFileName(path))); Response.ContentType = "application/" + Path.GetExtension(path).Substring(1); Response.BinaryWrite(buffer); } ```
Try adding Response.End(); after the call to Response.BinaryWrite(). You may inadvertently be sending other content back after Response.BinaryWrite which may confuse the browser. Response.End will ensure that that the browser only gets what you really intend.
``` Response.BinaryWrite(bytes); Response.Flush(); Response.Close(); Response.End(); ``` This works for us. We create PDFs from SQL Reporting Services.
Reading a binary file and using Response.BinaryWrite()
[ "", "c#", "asp.net", "" ]
I am developing a application that needs to store data with many writes and reads as requiring fast searching of data (the need for indexes of some sort), and also be able to serialize and save the data. Currently I am thinking about using SQLite, which gets the job done, but I am open for alternatives. The SQLite's syntax really doesn't fit elegantly in C++ code (for example I am forced to access the results by column index numbers instead of column names, etc).
Stay with SQLite but find a good C++ library for this. This [StackOverflow question](https://stackoverflow.com/questions/120295/what-is-a-good-oo-c-wrapper-for-sqlite) should help you ...
I would argue that the added dependency on a wrapper library is not worth the cost of having to deal with the costs of that extra dependency. You don't want to be stuck debugging these wrapper libs when the documentation for them may be scant. SQLLite is bound to be more stable and have better documentation and therefore a more reliable dependency. I would either deal with sqllite or wrap it yourself in some intelligent way based on your end application.
SQLite Alternatives for C++
[ "", "c++", "sqlite", "indexing", "persistence", "" ]
I'm trying to change a JList inside a JScrollPane dynamically, using ``` myList.setListData(someArray); ``` After this I would expect the JScrollPane to show Scrollbars as needed, but this doesn't happen. Googling the issue was not very helpful. I tried various combinations of the following methods, with little success (basically poking through the api docs): ``` myScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); myList.validate(); myScrollPane.validate(); myScrollPane.setPreferredSize(Dimension someDimension); myScrollPane.setViewportView(moduleList); myScrollPane.setLayout(...); ``` When using the first method a scrollbar appears, but it doesn't get activated by the model change. I also hooked into the PropertyChangeEvent and validated that the JList fires and event when the model changed. What am I missing here? What method do I have to use to make this work, or even better what property would make this work out of the box?
if the preferredSize is set on JList, even if (0, 0), then JScrollPane doesn't work - ensure that it is unset, setPreferredSize(null) if necessary see [mrtextminer](http://mrtextminer.wordpress.com/2007/11/20/jlist-is-not-scrollable/) as follows > The solution to this problem is to not setting the preferredSize of the JList (removing the setting statement). In Netbeans IDE 5.5.1, unsetting the preferredSize of the JList can be achieved by right clicking on the preferredSize property of the JList and then selecting “restoring default value”. > > In conclusion, set preferredSize of the JScrollPane only. Do not set the preferredSize of the JList.
just wrote a little sample app to test this behaviour, and it works out of the box. when you modify the list data, vertical and horizontal scrollbars are added to the scrollpane as needed by default. ``` public class Frametest { private JList list; public Frametest() { JFrame f = new JFrame("Scrollable JList"); f.setSize(200, 300); JScrollPane jsp = new JScrollPane(); list = new JList(); jsp.getViewport().add(list); f.getContentPane().setLayout(new BorderLayout()); f.getContentPane().add(jsp, BorderLayout.CENTER); JButton button = new JButton("update"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Object[] objects = new Object[20]; for(int i=0; i<20; i++) { objects[i] = "foo foo foo foo foo foo foo foo foo foo foo foo "+i; } list.setListData(objects); } }); f.getContentPane().add(button, BorderLayout.SOUTH); f.setVisible(true); } public static void main(String[] args) { new Frametest(); }} ```
Make JScrollPane display scrollbars when JList inside is changed
[ "", "java", "swing", "" ]
Okay, This may be really simple or it may not even be possible, or I am just having a brain freeze :) Here is an example of what I am trying to do: ``` public void SomeMethod(bool include) { using (AccountDataContext db = AccountContextFactory.CreateContext()) { if (include) { var query = from a in db.FundingTypes where a.FundingTypeId == 1 select a; } else { var query = from a in db.FundingTypes where a.FundingTypeId != 1 select a; } } } ``` I would like to dynamically change the != and = without having to write an entire new query. The query that I am using in real life is very large and I don't like code duplication. Thought or Ideas? Thanks
That seems perfectly straightforward. ``` var predicate = include ? (Func<int, bool>) x=>x == 1 : (Func<int, bool>) x=>x != 1 ; var query = from a in db.FundingTypes where predicate(a.FundingTypeId) select a; ```
How about this: ``` var query = from a in db.FundingTypes where (a.FundingTypeId == 1) == include select a; ``` Joe
Dynamic "Not" by parameter in LINQ (Or any other code for that matter)
[ "", "c#", "linq", "parameters", "" ]
I have a `for` loop generating integers. For instance: ``` for (int i=300; i>200; i--) {(somefunction)*i=n; cout<<n; } ``` This produces an output on the screen like this: ``` f=00000000000100023; ``` I want to store the 100023 part of this number (i.e just ignore all the zeros before the non zero numbers start but then keeping the zeros which follow) as an array. Like this: ``` array[0]=1; array[1]=0; array[2]=0; array[3]=0; array[4]=2; array[5]=3; ``` How would I go about achieving this?
This is a mish-mash of answers, because they are all there, I just don't think you're seeing the solution. First off, if they are integers [Bill's answer](https://stackoverflow.com/questions/879375/how-can-i-remove-the-leading-zeroes-from-an-integer-generated-by-a-loop-and-store/879446#879446) along with the other answers are great, save some of them skip out on the "store in array" part. Also, as pointed out in a comment on your question, this part is [a duplicate](https://stackoverflow.com/questions/515612/convert-an-integer-number-into-an-array). But with your new code, the solution I had in mind was [John's solution](https://stackoverflow.com/questions/879375/how-can-i-remove-the-leading-zeroes-from-an-integer-generated-by-a-loop-and-store/879525#879525). You just need to figure out how to ignore leading zero's, which is easy: ``` std::vector<int> digits; bool inNumber = false; for (int i=300; i>200; i--) { int value = (somefunction) * i; if (value != 0) { inNumber = true; // its not zero, so we have entered the number } if (inNumber) { // this code cannot execute until we hit the first non-zero number digits.push_back(value); } } ``` Basically, just don't start pushing until you've reached the actual number.
In light of the edited question, my original answer (below) isn't the best. If you absolutely have to have the output in an array instead of a vector, you can start with GMan's answer then transfer the resulting bytes to an array. You could do the same with JohnFx's answer once you find the first non-zero digit in his result. --- I'm assuming `f` is of type `int`, in which case it doesn't store the leading zeroes. ``` int f = 100023; ``` To start you need to find the required length of the array. You can do that by taking the log (base 10) of `f`. You can import the cmath library to use the `log10` function. ``` int length = log10(f); int array[length]; ``` `length` should now be 6. Next you can strip each digit from `f` and store it in the array using a loop and the modulus (%) operator. ``` for(int i=length-1; i >= 0; --i) { array[i] = f % 10; f = f / 10; } ``` Each time through the loop, the modulus takes the last digit by returning the remainder from division by 10. The next line divides `f` by 10 to get ready for the next iteration of the loop.
How can I remove the leading zeroes from an integer generated by a loop and store it as an array?
[ "", "c++", "arrays", "integer", "" ]
Using LINQ on collections, what is the difference between the following lines of code? ``` if(!coll.Any(i => i.Value)) ``` and ``` if(!coll.Exists(i => i.Value)) ``` When I disassemble `.Exists`, it looks like there is no code. Why is that?
[List.Exists](http://msdn.microsoft.com/en-us/library/bfed8bca.aspx) (Object method - MSDN) > Determines whether the List(T) contains elements that match the conditions defined by the specified predicate. This has existed since .NET 2.0, so before LINQ. It's meant to be used with the Predicate **delegate**, but lambda expressions are backward compatible. Also, just List has this (not even IList). --- [IEnumerable.Any](http://msdn.microsoft.com/en-us/library/bb534972.aspx) (Extension method - MSDN) > Determines whether any element of a sequence satisfies a condition. This is new in .NET 3.5 and uses Func(TSource, bool) as an argument, so this was intended to be used with lambda expressions and LINQ. In terms of behaviour, these are identical.
The difference is that `Any` is an extension method for any `IEnumerable<T>` defined in `System.Linq.Enumerable`. It can be used on any `IEnumerable<T>` instance. `Exists` does not appear to be an extension method. My guess is that `col1` in your example is of type `List<T>`. If so, `Exists` is an instance method which functions very similar to `Any`. **In short**, *the methods are essentially the same. One is more general than the other.* * **Any** also has an overload which takes no parameters and simply looks for any item in the enumerable. * **Exists** has no such overload.
LINQ .Any VS .Exists - What's the difference?
[ "", "c#", "linq", "collections", "" ]
How can I write a wrapper that can wrap any function and can be called just like the function itself? The reason I need this: I want a Timer object that can wrap a function and behave just like the function itself, plus it logs the accumulated time of all its calls. The scenario would look like this: ``` // a function whose runtime should be logged double foo(int x) { // do something that takes some time ... } Timer timed_foo(&foo); // timed_foo is a wrapping fct obj double a = timed_foo(3); double b = timed_foo(2); double c = timed_foo(5); std::cout << "Elapsed: " << timed_foo.GetElapsedTime(); ``` How can I write this `Timer` class? I am trying something like this: ``` #include <tr1/functional> using std::tr1::function; template<class Function> class Timer { public: Timer(Function& fct) : fct_(fct) {} ??? operator()(???){ // call the fct_, // measure runtime and add to elapsed_time_ } long GetElapsedTime() { return elapsed_time_; } private: Function& fct_; long elapsed_time_; }; int main(int argc, char** argv){ typedef function<double(int)> MyFct; MyFct fct = &foo; Timer<MyFct> timed_foo(fct); double a = timed_foo(3); double b = timed_foo(2); double c = timed_foo(5); std::cout << "Elapsed: " << timed_foo.GetElapsedTime(); } ``` (BTW, I know of `gprof` and other tools for profiling runtime, but having such a `Timer` object to log the runtime of a few selected functions is more convenient for my purposes.)
Here is an *easy* way to wrap functions. ``` template<typename T> class Functor { T f; public: Functor(T t){ f = t; } T& operator()(){ return f; } }; int add(int a, int b) { return a+b; } void testing() { Functor<int (*)(int, int)> f(add); cout << f()(2,3); } ```
Basically, what you want to do is impossible in current C++. For any number of arity of function you want to wrap, you need to overload by ``` const reference non-const reference ``` But then it's still not perfectly forwarding (some edge cases still stand), but it should work reasonable well. If you limit yourself to const references, you can go with this one (not tested): ``` template<class Function> class Timer { typedef typename boost::function_types ::result_type<Function>::type return_type; public: Timer(Function fct) : fct_(fct) {} // macro generating one overload #define FN(Z, N, D) \ BOOST_PP_EXPR_IF(N, template<BOOST_PP_ENUM_PARAMS(N, typename T)>) \ return_type operator()(BOOST_PP_ENUM_BINARY_PARAMS(N, T, const& t)) { \ /* some stuff here */ \ fct_(ENUM_PARAMS(N, t)); \ } // generate overloads for up to 10 parameters BOOST_PP_REPEAT(10, FN, ~) #undef FN long GetElapsedTime() { return elapsed_time_; } private: // void() -> void(*)() typename boost::decay<Function>::type fct_; long elapsed_time_; }; ``` Note that for the return type, you can use boost's function types library. Then ``` Timer<void(int)> t(&foo); t(10); ``` You can also overload using pure value parameters, and then if you want to pass something by reference, use `boost::ref`. That's actually a pretty common technique, especially when such parameters are going to be saved (this technique is also used for `boost::bind`): ``` // if you want to have reference parameters: void bar(int &i) { i = 10; } Timer<void(int&)> f(&bar); int a; f(boost::ref(a)); assert(a == 10); ``` Or you can go and add those overloads for both const and non-const versions as explained above. Look into [Boost.Preprocessor](http://www.boost.org/doc/libs/1_39_0/libs/preprocessor/doc/index.html) for how to write the proper macros. You should be aware that the whole thing will become more difficult if you want to be able to pass arbitrary callables (not only functions), since you will need a way then to get their result type (that's not all that easy). C++1x will make this sort of stuff way easier.
C++: Function wrapper that behaves just like the function itself
[ "", "c++", "function", "wrapper", "functional-programming", "tr1", "" ]
I'm looking to integrate a form builder into a site I'm using, but I'm hoping to find a library that has some or most of the functionality I'm looking for. I'm looking for a library that will give me a nice GUI for building the form, and a JSON (or XML, or similar) output that I can play with in the `django` backend. I'm planning to use `django` to output the finished form. I tried running this through Google, but that only yields companies who make a business out of creating and hosting the forms online. But nothing in the form of a library. Any suggestions?
If you dont mind spending a bit of cash you can look at: Machforms : <http://www.appnitro.com/> The form builder itself is entirely client side JS, so you would just need to post the output (which is JSON) to django instead of their php script.
I have the same requirement, I will update this answer over time but bootstrap form builder ( PHP ) seems nice <https://github.com/minikomi/Bootstrap-Form-Builder> demo : <http://minikomi.github.io/Bootstrap-Form-Builder/>
Suggestions for a JavaScript form builder?
[ "", "javascript", "javascript-framework", "" ]
I'm creating a class. What's the best practice for naming properties/methods when your preferred name is a reserved word?
I usually try to think of some synonymous alternative word, or variation, though it doesn't sound like that is applicable for you. Alternatively, you can use the '@' prefix (in C#) or [square braces] (in VB.NET) to explicitly avoid the conflict with reserved words in the language.
In VB.NET, you can enclose the property name within square brackets: ``` Public Property [Make] As String ``` (I'm not sure about C#, but you also tagged the post as vb.net)
Best practice for renaming property/method names that are reserved words?
[ "", "c#", ".net", "vb.net", "naming-conventions", "" ]
What is the best way to maintain upgrade scripts between versions of a product? If a customer starts with version 3 of your product and goes to version 5, what is the best way to generate an upgrade script for the customer so that any differences in the database schema between versions 3 and 5 are resolved?
1) Use a Tool like [RedGate's Schema and Data Compare](http://www.redgate.com) 2) Use [Visual Studio 2008's GDR project](http://blogs.msdn.com/gertd/archive/2009/04/22/rtm-of-vsdb-2008-gdr-r2.aspx) 3) Write your own!
This has been discussed many times before: [How to automatically upgrade deployed database for end-users](https://stackoverflow.com/questions/812210/how-to-automatically-upgrade-deployed-database-for-end-users) [Database Deployment Strategies (SQL Server)](https://stackoverflow.com/questions/504909/sql-deployment-strategies) [Any SQL Server 2008 Database Change Management (MIgrations) Tools Available?](https://stackoverflow.com/questions/466689/any-sql-server-2008-database-change-management-migrations-tools-available/466756) [Migrator.net](http://code.google.com/p/migratordotnet/) seems to be the preferred approach in those questions. I do like that approach, but if your case is simple you might prefer to store the SQL to perform the changes in a table with the version number, like this: ``` create table upgradetable (major int, minor int, revision int, change text) ``` and then you can get a script to perform the upgrade with a simple: ``` select change from upgradetable where major > (select major from versiontable) ``` (adjust to taste, of course). This will not work if you cannot do all upgrades via SQL, in which case I recommend migrator.net
Generating SQL upgrade scripts for the customer
[ "", "sql", "database", "" ]
The .NET framework ships with 6 different hashing algorithms: * MD5: 16 bytes (Time to hash 500MB: 1462 ms) * SHA-1: 20 bytes (1644 ms) * SHA256: 32 bytes (5618 ms) * SHA384: 48 bytes (3839 ms) * SHA512: 64 bytes (3820 ms) * RIPEMD: 20 bytes (7066 ms) Each of these functions performs differently; MD5 being the fastest and RIPEMD being the slowest. MD5 has the advantage that it fits in the built-in Guid type; [and it is the basis of the type 3 UUID](https://www.rfc-editor.org/rfc/rfc4122#section-4.3). [SHA-1 hash is the basis of type 5 UUID.](https://www.rfc-editor.org/rfc/rfc4122#section-4.3) Which makes them really easy to use for identification. MD5 however is vulnerable to [collision attacks](http://en.wikipedia.org/wiki/Cryptographic_hash_function), SHA-1 is also vulnerable but to a lesser degree. ### Under what conditions should I use which hashing algorithm? Particular questions I'm really curious to see answered are: * Is MD5 not to be trusted? Under normal situations when you use the MD5 algorithm with no malicious intent and no third party has any malicious intent would you expect ANY collisions (meaning two arbitrary byte[] producing the same hash) * How much better is RIPEMD than SHA1? (if its any better) its 5 times slower to compute but the hash size is the same as SHA1. * What are the odds of getting non-malicious collisions when hashing file-names (or other short strings)? (Eg. 2 random file-names with same MD5 hash) (with MD5 / SHA1 / SHA2xx) In general what are the odds for non-malicious collisions? This is the benchmark I used: ``` static void TimeAction(string description, int iterations, Action func) { var watch = new Stopwatch(); watch.Start(); for (int i = 0; i < iterations; i++) { func(); } watch.Stop(); Console.Write(description); Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds); } static byte[] GetRandomBytes(int count) { var bytes = new byte[count]; (new Random()).NextBytes(bytes); return bytes; } static void Main(string[] args) { var md5 = new MD5CryptoServiceProvider(); var sha1 = new SHA1CryptoServiceProvider(); var sha256 = new SHA256CryptoServiceProvider(); var sha384 = new SHA384CryptoServiceProvider(); var sha512 = new SHA512CryptoServiceProvider(); var ripemd160 = new RIPEMD160Managed(); var source = GetRandomBytes(1000 * 1024); var algorithms = new Dictionary<string,HashAlgorithm>(); algorithms["md5"] = md5; algorithms["sha1"] = sha1; algorithms["sha256"] = sha256; algorithms["sha384"] = sha384; algorithms["sha512"] = sha512; algorithms["ripemd160"] = ripemd160; foreach (var pair in algorithms) { Console.WriteLine("Hash Length for {0} is {1}", pair.Key, pair.Value.ComputeHash(source).Length); } foreach (var pair in algorithms) { TimeAction(pair.Key + " calculation", 500, () => { pair.Value.ComputeHash(source); }); } Console.ReadKey(); } ```
In cryptography, hash functions provide three separate functions. 1. **Collision resistance**: How hard is it for someone to find two messages (*any* two messages) that hash the same. 2. **Preimage Resistance**: Given a hash, how hard is it to find another message that hashes the same? Also known as a *one way hash function*. 3. **Second preimage resistance**: Given a message, find another message that hashes the same. These properties are related but independent. For example, collision resistance implies second preimage resistance, but not the other way around. For any given application, you will have different requirements, needing one or more of these properties. A hash function for securing passwords on a server will usually only require preimage resistance, while message digests require all three. It has been shown that MD5 is not collision resistant, however, that does not preclude its use in applications that do not require collision resistance. Indeed, MD5 is often still used in applications where the smaller key size and speed are beneficial. That said, due to its flaws, researchers recommend the use of other hash functions in new scenarios. SHA1 has a flaw that allows collisions to be found in theoretically far less than the 2^80 steps a secure hash function of its length would require. The attack is continually being revised and currently can be done in ~2^63 steps - just barely within the current realm of computability (as of April, 2009). For this reason NIST is phasing out the use of SHA1, stating that the SHA2 family should be used after 2010. SHA2 is a new family of hash functions created following SHA1. Currently there are no known attacks against SHA2 functions. SHA256, 384 and 512 are all part of the SHA2 family, just using different key lengths. RIPEMD I can't comment too much on, except to note that it isn't as commonly used as the SHA families, and so has not been scrutinized as closely by cryptographic researchers. For that reason alone I would recommend the use of SHA functions over it. In the implementation you are using it seems quite slow as well, which makes it less useful. In conclusion, there is no one best function - it all depends on what you need it for. Be mindful of the flaws with each and you will be best able to choose the right hash function for *your* scenario. --- # ⚠️ WARNING *August, 2022* **DO NOT USE SHA-1 OR MD5 FOR CRYPTOGRAPHIC APPLICATIONS.** Both of these algorithms **are broken** (MD5 can be cracked in 30 seconds by a cell phone). ---
## All hash functions are "broken" The [pigeonhole principle](http://en.wikipedia.org/wiki/Pigeonhole_principle) says that try as hard as you will you can not fit more than 2 pigeons in 2 holes (unless you cut the pigeons up). Similarly you can not fit 2^128 + 1 numbers in 2^128 slots. All hash functions result in a hash of finite size, this means that you can always find a collision if you search through "finite size" + 1 sequences. It's just not feasible to do so. Not for MD5 and not for [Skein](http://www.schneier.com/skein.html). ## MD5/SHA1/Sha2xx have no chance collisions All the hash functions have collisions, its a fact of life. Coming across these collisions by accident is the equivalent of **winning the intergalactic lottery**. That is to say, [no one wins the intergalactic lottery](https://stackoverflow.com/questions/201705/how-many-random-elements-before-md5-produces-collisions/288519#288519), its just not the way the lottery works. You will not come across an accidental MD5/SHA1/SHA2XXX hash, EVER. Every word in every dictionary, in every language, hashes to a different value. Every path name, on every machine in the entire planet has a different MD5/SHA1/SHA2XXX hash. How do I know that, you may ask. Well, as I said before, no one wins the intergalactic lottery, ever. ## But ... MD5 is broken **Sometimes the fact that its broken does not matter**. As it stands there are no known [pre-image or second pre-image attacks](http://en.wikipedia.org/wiki/Preimage_attack) on MD5. So what is so broken about MD5, you may ask? It is possible for a third party to generate 2 messages, one of which is EVIL and another of which is GOOD that both hash to the same value. ([Collision attack](http://en.wikipedia.org/wiki/Birthday_attack)) Nonetheless, the current RSA recommendation is not to use MD5 if you need pre-image resistance. People tend to err on the side of caution when it comes to security algorithms. ## So what hash function should I use in .NET? * Use MD5 if you need the speed/size and don't care about birthday attacks or pre-image attacks. Repeat this after me, **there are no chance MD5 collisions**, malicious collisions can be carefully engineered. Even though there are no known pre-image attacks to date on MD5 the line from the security experts is that MD5 should not be used where you need to defend against pre-image attacks. **SAME goes for SHA1**. Keep in mind, not all algorithms need to defend against pre-image or collision attacks. Take the trivial case of a first pass search for duplicate files on your HD. * Use SHA2XX based function if you want a cryptographically secure hash function. No one ever found any SHA512 collision. EVER. They have tried really hard. For that matter no one ever found any SHA256 or 384 collision ever. . * Don't use SHA1 or RIPEMD unless its for an interoperability scenario. RIPMED has not received the same amount of scrutiny that SHAX and MD5 has received. Both SHA1 and RIPEMD are vulnerable to birthday attacks. They are both slower than MD5 on .NET and come in the awkward 20 byte size. Its pointless to use these functions, forget about them. SHA1 collision attacks are down to 2^52, its not going to be too long until SHA1 collisions are out in the wild. For up to date information about the various hash functions have a look at [the hash function zoo](http://ehash.iaik.tugraz.at/wiki/The_Hash_Function_Zoo). ## But wait there is more Having a **fast** hash function can be a curse. For example: a very common usage for hash functions is password storage. Essentially, you calculate hash of a password combined with a known random string (to impede rainbow attacks) and store that hash in the database. The problem is, that if an attacker gets a dump of the database, he can, quite effectively guess passwords using brute-force. Every combination he tries only takes a fraction of millisecond, and he can try out hundreds of thousands of passwords a second. To work around this issue, the [bcrypt](https://stackoverflow.com/questions/873403/net-impl-of-bcrypt) algorithm can be used, it is designed to be slow so the attacker will be heavily slowed down if attacking a system using bcrypt. Recently [scrypt](http://www.daemonology.net/blog/2009-05-09-scrypt-key-derivation.html) has made some headline and is considered by some to be more effective than bcrypt but I do not know of a .Net implementation.
Which cryptographic hash function should I choose?
[ "", "c#", ".net", "hash", "cryptography", "cryptographic-hash-function", "" ]
I am trying to delete the all but the most recent 3,000 items in a table. The table has 105,000 records. I am trying this, but an error is generated incorrect syntax. ``` delete tRealtyTrac where creation in( select top 103000 from tRealtyTrac order by creation) ```
The delete syntax is going to be slightly different from what you have. An example would be: ``` DELETE FROM tRealtyTrac WHERE creation in( select top 103000 creation from tRealtyTrac order by creation) ``` Notice how there is the "from" keyword. This is saying we want to delete from the table called tRealtyTrac The one problem I foresee with this is, you are probably going to want to not use creation... Instead: ``` DELETE FROM tRealtyTrac WHERE someuniqueidcolumnlikeakeyofsomesort in( select top 103000 someuniqueidcolumnlikeakeyofsomesort from tRealtyTrac order by creation) ``` Otherwise you may delete more than you intended.
The inner query needs to be: select top 103000 **creation** from ...
SQl Delete top 100 from table
[ "", "sql", "" ]
Is this a simple process? I'm only writing a quick hacky UI for an internal tool. I don't want to spend an age on it.
Here's a quick down and dirty app. Basically I created a Form with a button and a ListBox. On button click, the ListBox gets populated with the date of the next 20 days (had to use something just for testing). Then, it allows drag and drop within the ListBox for reordering: ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); this.listBox1.AllowDrop = true; } private void button1_Click(object sender, EventArgs e) { for (int i = 0; i <= 20; i++) { this.listBox1.Items.Add(DateTime.Now.AddDays(i)); } } private void listBox1_MouseDown(object sender, MouseEventArgs e) { if (this.listBox1.SelectedItem == null) return; this.listBox1.DoDragDrop(this.listBox1.SelectedItem, DragDropEffects.Move); } private void listBox1_DragOver(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Move; } private void listBox1_DragDrop(object sender, DragEventArgs e) { Point point = listBox1.PointToClient(new Point(e.X, e.Y)); int index = this.listBox1.IndexFromPoint(point); if (index < 0) index = this.listBox1.Items.Count-1; object data = e.Data.GetData(typeof(DateTime)); this.listBox1.Items.Remove(data); this.listBox1.Items.Insert(index, data); } ```
7 Years Late. But for anybody new, here is the code. ``` private void listBox1_MouseDown(object sender, MouseEventArgs e) { if (this.listBox1.SelectedItem == null) return; this.listBox1.DoDragDrop(this.listBox1.SelectedItem, DragDropEffects.Move); } private void listBox1_DragOver(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Move; } private void listBox1_DragDrop(object sender, DragEventArgs e) { Point point = listBox1.PointToClient(new Point(e.X, e.Y)); int index = this.listBox1.IndexFromPoint(point); if (index < 0) index = this.listBox1.Items.Count - 1; object data = listBox1.SelectedItem; this.listBox1.Items.Remove(data); this.listBox1.Items.Insert(index, data); } private void itemcreator_Load(object sender, EventArgs e) { this.listBox1.AllowDrop = true; } ```
Reorder a winforms listbox using drag and drop?
[ "", "c#", "winforms", "listbox", "" ]
I'm considering developing an application as portlets, to be integrated in Liferay portal. Are there any significant disadvantages or restrictions in developing such an application, as opposed to developing a normal web application using Spring framework? Liferay seems to require that all content is added as portlets. Another option I ponder is to use Liferay just for some parts of the application and add external links to other self-developed content, developed as a normal web application. That would, however, create a need of multiple user authentication mechanisms and some kind of cross-site authentication between Liferay and the other web application. Which is the best way to go?
(Disclaimer: I'm one of Liferay's developers) I think both options are good depending on your needs. If you have previous experience developing standalone web applications but no experience developing portlets, then picking the former will get you started faster. The drawbacks would be that you would have to implement your own users and permissions system and would not be able to leverage the portal services provided by Liferay. If you decide to use this alternative, note that you can deploy regular WAR files to Liferay and it will automatically create a simple portlet that uses an iframe to show your app. This will allow you to put the standalone app along with the portlets in Liferay's pages. Developing a portlet for Liferay starts to pay off when you start leveraging the portal services it provides. To start with by developing a portlet you can forget about developing your own user system and use the one that Liferay provides (which is quite powerful). You can also use other services such as permissions, comments, tagging, categorization, data scoping, etc. which will allow you to develop pretty complete application in a shorter time. The drawback is that the first time you do this you'll have to learn several new things, but the second time you'll go much faster. I hope that helps.
I've been using Liferay for about 2 years now for an internal application. We had the same discussion many times throughout the development cycle before our first release. We had to fight Liferay a few times, sometimes because of our own lack of knowledge, sometimes because of the portlet environment, and occasionally because of Liferay. If you want the layout options for multiple applications that you can get from a portal, then you should certainly use Liferay. If you are writing a single application, then I would probably not use Liferay. I think a hybrid of some Liferay and some not is by far the worst option. We are probably not leveraging Liferay to its fullest capabilities, but if this is your first Liferay app, then chances are you won't either because of the learning curve. We originally hoped to have many different portlets for the different aspects of our application, but due to a lack of good inter-portlet communication mechanisms during development ( pre JSR-286 ) we ended up writing a single application. Now that we ended up in that boat, I wish we had gone without Liferay since all we are really using is some user management capabilities. We use JSF and facelets (both new technologies to us, so the pain may have been self inclicted) and while we've gotten better at it, it seems like there were a few hoops we had to jump through in order to get it working correctly in a portlet; Things that wouldn't have had to happen in a regular web-app environment. For many frameworks, it seems that portlet support is an afterthought. This is obviously not Liferay specific, it's just a byproduct of working within the portlet environment. In a webapp using Spring MVC, Struts, Faces, Wicket, whatever, you are going to have a lot more control over everything, but also be responsible for implementing more stuff. In a portlet, you are going to be subject to the terms of JSR-168 and/or JSR-286. The portal container will provide some functionality for you, like user authentication, but IMO, an entire portal for user authentication is way too heavy. I see the power of the portal being allowing the user to customize their view of multiple applications, not presenting a single application. You should review the portlet related specs and see if it fits your needs. <http://developers.sun.com/portalserver/reference/techart/jsr168/>
Restrictions/disadvantages of developing portlets for Liferay
[ "", "java", "portlet", "liferay", "portal", "" ]
I'm working on a PHP project with several developers, each who has their own style. The styles differ significantly, and can make the code really hard to read, and everyone is in agreement that we need to standardize our style. The issue I'm having is that I can't find any good program or system to help enforce standards for PHP. I've used a number of programs in the past for C++ and Java, and I'm a huge checkstyle fan, but I can't find anything so elegant for PHP. What program, tool, or system would you recommend to help developers adhere to a common set of PHP coding standards? Additionally, it would be great if the solution also handled PHP embedded in XHTML, but that is not a requirement.
[PHP\_CodeSniffer](http://pear.php.net/manual/en/package.php.php-codesniffer.php) seems like a great tool. A project I was affiliated with used the [Zend Framework coding standard](http://framework.zend.com/manual/en/coding-standard.html) as a basis for our own, and we looked into using it. However, our deadline did not allow much leeway for experimenting with new tools, so we never got into using it past initial testing.
I used in the past [phpCodeBeautifier](http://www.waterproof.fr/products/phpCodeBeautifier/). It does not have lots of options, but it gets the job done to certain point and helps keeping standard code. It's run from command line and, provided your IDE supports external formatters, you could integrate with that, or create a script to run on all your files. Alternatively, if you use Eclipse or you don't but plan to run this occasionally, you could use Eclipse with its PHP plugin. You can re-format code inside folders with just a couple of clicks.
What do you recommend for a PHP Coding Standards tool/system/program?
[ "", "php", "coding-style", "" ]
Has anybody out there got any real world experience with the [H2 database](http://www.h2database.com/html/main.html)? I'm interested in: * performance * stability * bugs
We use H2 as the storage engine for a very large RCP/Eclipse-based design tool. The tool itself has been in use for over 2 years now on some data-heavy projects so we've stressed H2 pretty thoroughly. We did a fairly in-depth analysis of other Java embeddable db engines and chose H2. Overall I think we're pretty happy with it. We've had very few stability issues, but, as zvikico says, the development team is VERY responsive. While the performance is good, sometimes you need to do some optimizations by hand. If you're used to working with enterprise-level databases that do a lot of this optimization for you, it may be a bit of a change. I'd recommend using the EXPLAIN command if you encounter a slow query to see what it's doing. Very often you can switch around the JOIN statements to force it to use indices more efficiently. So, in short, thumbs up from me!
I'm using it as the base of [nWire](http://www.nwiresoftware.com/), which is an Eclipse plugin for Java code exploration. It is working in embedded mode as part of the Java process, not as a server. Overall, it is very stable. I'm working with H2 for a long time now: I encountered some bugs in the early days, but that hasn't happened in some time now. The response of the developer has been great, too. Regarding performance: it is very good. You can see the tests on the site. I didn't get a chance to compare it to other tools, but I'm very happy with it. In recent versions, it does tend to take a bit more time to open large databases, but that issue seems to be resolved, too. Some other strong points: * Very simple distribution: just one JAR. * The embedded web console is very useful for quick access to the database. It proved to be a valuable development tool. * Responsive community support, especially from the development team.
Any real world experience with H2 database?
[ "", "java", "database", "h2", "" ]
I have created a simple test form with FormBorderStyle = FixedToolWindow by default and added a button that will switch between FixedToolWindow and SizableToolWindow on mouse press. Switching the FormBorderStyle between these two seems to produce a weird effect that's causing a lot of issues on my application. The problem is that the window seems to change size and I can't have that. I just want to change the border, I need the form size to remain the same. For instance, here's the button code: ``` private void button1_Click(object sender, System.EventArgs e) { if(FormBorderStyle == FormBorderStyle.FixedToolWindow) { System.Diagnostics.Debug.WriteLine("SWITCHING: FIXED -> SIZABLE"); FormBorderStyle = FormBorderStyle.SizableToolWindow; } else { System.Diagnostics.Debug.WriteLine("SWITCHING: SIZABLE -> FIXED"); FormBorderStyle = FormBorderStyle.FixedToolWindow; } } ``` And to debug I use this: ``` private void Settings_SizeChanged(object sender, System.EventArgs e) { System.Diagnostics.Debug.WriteLine(this.Size); } ``` And here's the output when I press the switch button: ``` SWITCHING: FIXED -> SIZABLE {Width=373, Height=169} {Width=383, Height=179} SWITCHING: SIZABLE -> FIXED {Width=383, Height=179} {Width=373, Height=169} ``` How can I fix this behavior? And by "fix", I mean, prevent this from happening if possible. I want to be able to specify my form size and to remain like that, no matter the type of border style. Also, a solution by subclassing the Form class would be the perfect solution for me in case anyone as any ideas to solve this problem with such a method. **EDIT:** I made a little video to demonstrate the problem. The first test shows that the form size doesn't actually change (visually), only the location of the form changes a little bit; but the values for the Size property do change, as you can see on the debug output. The second test you will see on the debug output that the form Size property values change and the window size itself will also change. Please look here: <http://screencast.com/t/0vT1vCoyx2u>
Your issue is with the Location changing, not the Size. This code solves the problem seen in the video. ``` private void Form1_DoubleClick(object sender, EventArgs e) { Point _location = this.PointToScreen(this.ClientRectangle.Location); if (this.FormBorderStyle == FormBorderStyle.SizableToolWindow) { this.FormBorderStyle = FormBorderStyle.FixedToolWindow; } else { this.FormBorderStyle = FormBorderStyle.SizableToolWindow; } Point _newloc = this.PointToScreen(this.ClientRectangle.Location); Size _diff = new Size(_newloc) - new Size(_location); this.Location -= _diff; } ``` It appears to me that the issue of the rendered form moving when switching between those two borderstyles is a bug in the DWM.
I suspect what's happening is that Windows Forms is keeping the client size (i.e. inner area) the same while the border size changes. This is generally a good thing because it ensures that the window can still correctly fit the content that you've put on it. If you want to maintain the same outer dimensions, you could work around it by saving the size to a variable before changing the border type, and then restoring it back. They'll probably a slight flicker, though.
Strange behavior in FormBorderStyle between Fixed and Sizable
[ "", "c#", ".net", "winforms", "border", "" ]
Probably a bit off topic question, but it's something I'm really interested in getting to know from other people with different experience and backgrounds. How do you keep track of your huge projects? Do you use subversion? EER-models? Do you write notes? Does all your faith lie in phpdoc? Which framework do you use, and which design pattern do you follow? A lot of questions, I know, and I don't expect you to answer ALL of them, just summarize whatever you want to emphasize the most. Personally, I use subversion for source control, phpdoc, writing down personal notes for each model/controller etc and I'm almost always following the MVC-pattern. Have a fantastic and automagic day! ;-)
I would recommend on using the tools that work best for the people that you have, and the parts that are likely to be the most difficult to manage. If you have a lot of requirements, use a tool which tracks requirements well. If you have a lot of simple one-off projects, maybe simple project tracking works well.
A great way to document your project (especially the high level stuff) is to have a wiki. The success of that obviously depends entirely on your teammates. If they hate writing prose then the whole idea is basically doomed from the start. But given the right people it can *really* pay off. A few wiki pages with a couple of diagrams can go a long way and oftentimes be way more expressive than any UML diagram and what-have-you (of course, the combination of both is even better :-) If you can get your testers and other people to join in, you're off to a good start. The more, the merrier. One thing you forgot to mention in your post is a bug tracker. That is an absolute must-have, I am sure Joel has some good tips on which is the best software choice there ;)
Staying consistent when working with large scale projects
[ "", "php", "design-patterns", "environment", "" ]
I want to change some properties of a LINQ query result object without creating a new object and manually setting every property. Is this possible? Example: ``` var list = from something in someList select x // but change one property ```
I'm not sure what the query syntax is. But here is the expanded LINQ expression example. ``` var query = someList.Select(x => { x.SomeProp = "foo"; return x; }) ``` What this does is use an anonymous method vs and expression. This allows you to use several statements in one lambda. So you can combine the two operations of setting the property and returning the object into this somewhat succinct method.
If you just want to update the property on all elements then ``` someList.All(x => { x.SomeProp = "foo"; return true; }) ```
LINQ: Select an object and change some properties without creating a new object
[ "", "c#", "linq", "" ]
I have been tasked with refactoring some components that used xmlbeans to now make use of jaxb. Everything is going great, until I get to a place where the previous author has called the [copy() function of one of the XmlObjects](http://xmlbeans.apache.org/docs/2.0.0/reference/org/apache/xmlbeans/XmlObject.html#copy()). Since all objects in xmlbeans extend XmlObject, we get the magic deep copy function for free. Jaxb does not seem to provide this for us. What is the correct and simple way to make a deep copy of a Jaxb object?
You could make your JAXB classes serializable and then deep copying an object by serializing and deserializing it. The code might look something like: ``` Object obj = ... // object to copy ObjectOutputStream out = new ObjectOutputStream(new ByteArrayOutputStream()); out.writeObject(obj); byte[] bytes = baos.toByteArray(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes)); Object copy = in.readObject(); ```
You can refer this ``` public static <T> T deepCopyJAXB(T object, Class<T> clazz) { try { JAXBContext jaxbContext = JAXBContext.newInstance(clazz); JAXBElement<T> contentObject = new JAXBElement<T>(new QName(clazz.getSimpleName()), clazz, object); JAXBSource source = new JAXBSource(jaxbContext, contentObject); return jaxbContext.createUnmarshaller().unmarshal(source, clazz).getValue(); } catch (JAXBException e) { throw new RuntimeException(e); } } public static <T> T deepCopyJAXB(T object) { if(object==null) throw new RuntimeException("Can't guess at class"); return deepCopyJAXB(object, (Class<T>) object.getClass()); } ``` It works for me. All the credit goes to <https://gist.github.com/darrend/821410>
How to make a deep copy of JAXB object like xmlbean XmlObject.copy()?
[ "", "java", "jaxb", "" ]
It looks like SpringSource [has just released a GA version](http://www.springsource.org/node/1385) of their [tc Server](http://www.springsource.com/products/tcserver) application server. It sounds from their description like it is a drop-in replacement for Apache Tomcat, with better "enterprise capabilities", such as "advanced diagnostics", better operations management, deployment, etc. (and of course, the support that they want to sell you as their primary business model). So I'm curious (and I'm not sure if this is truly a SO question), but is anyone using tc Server today in any shape or fashion? Has it worked out well for you? Did you find whatever features they are adding to Tomcat to be worth it?
As I see it, the primary advantage of tcServer is in managing large clusters of load-balanced tomcats. Aside from the management/monitoring layer (which is very cool, by the way), it also has a faster database connection pooling mechanism, and a generally tweaked configuration optimised for high volume. Other than that, it's just Tomcat.
They've just released a [developer edition](http://www.springsource.com/products/tcserver/devedition). Have a look at this [screencast](http://s3.springsource.com/MRKT/spring-metrics/Spring_Insight_Preview-final2.mov) which demonstrates how their diagnostics work.
Is anyone using SpringSource tc server as a Tomcat replacement?
[ "", "java", "spring", "tomcat", "jakarta-ee", "" ]
What is difference between in the following statements ``` String name = "Tiger"; final String name ="Tiger"; ``` Although the `String` class is `final` class, why do we need to create a String "CONSTANT" variable as final?
`final` in this context means that the variable `name` can only be assigned once. Assigning a different `String` object to it again results in a compile error. I think the source of the confusion here is that the `final` keyword can be used in several different contexts: * final class: The class cannot be subclassed. * final method: The method cannot be overridden. * final variable: The variable can only be assigned once. See the Wikipedia article on [final in Java](http://en.wikipedia.org/wiki/Final_(Java)) for examples on each case.
"final" means different things in the two cases. The java.lang.String class is final. This means you can't inherit from it. The variable "name" is final, meaning that you can't change it to point to a different instance of String. So a non-final String variable isn't a constant, because you could read it at two different times and get different values. As it happens, Java string objects are also immutable. This means that you cannot modify the value which a particular String object represents. Compare this with an array - you can replace the first element of an array object with a different object, but you can't replace the first character of a String object with a different char. This is why String.replace() returns a new string - it can't modify the old one. One reason that String is final is to prevent an instance of a subclass of String, which implements mutable behaviour, being passed in place of a String. But whether you can modify a particular object, and whether you can assign a different object to a variable, are completely different concepts. One is a property of String objects, and the other is a property of String variables, which are references to String objects.
String and Final
[ "", "java", "string", "variables", "final", "" ]
I'm filling PDF applications using classes that represent the pdf. I have a property per textbox on the pdf and am using attributes to specify the pdf textbox that the propery maps to. All of my PDF's have the same properties, but the pdf's use different names for the textboxes. So, the only solution I could think of was to create a base class and have each application type extend my base class and override each of the properties just to throw the new attribute value on it. Is there a simpler way? Example (Notice the only difference between Application1 and Application2 is the ITextField value changes from "TextBox1" to "TextBox2": ``` public class Application { private string accountNumber; public virtual string AccountNumber { get { return this.accountNumber; } set { this.accountNumber = value; } } } public class Application1 : Application { [ITextField("TextBox1")] public override string AccountNumber { get { return base.AccountNumber; } set { base.AccountNumber = value; } } } public class Application2 : Application { [ITextField("TextBox2")] public override string AccountNumber { get { return base.AccountNumber; } set { base.AccountNumber = value; } } } ``` Thanks
If you are going to use attributes, I would say that the base class was not the right choice. To define a scheme like this I would choose Interfaces over the base class. There is less code to maintain and it nets you the same effect. ``` public interface IApplication { string AccountNumber { get; set; } } public class Application1 : IApplication { [ITextField("TextBox1")] public string AccountNumber { get; set; } } public class Application2 : IApplication { [ITextField("TextBox2")] public override string AccountNumber { get; set; } } ``` Also, you could use the base class idea to contain a dictionary that maps property to text field and just set it up in the derived class... This would only really be efficient if you have a large number of properties in each form that you need to do this for. ``` public abstract class Application { public Application() { } private Dictionary<string, string> mappings = new Dictionary<string, string>(); public Dictionary<string, string> Mappings { get { return mappings; } } public string AccountNumber { get; set; } protected abstract void ProvideMappings(); } public class Application1 : Application { protected override void ProvideMappings() { Mappings.Add("AccountNumber", "TextBox1"); } } public class Application2 : Application { protected override void ProvideMappings() { Mappings.Add("AccountNumber", "TextBox2"); } } ``` Really need more context to say which if any of these are good ideas. The use case would drive the specifics. For instance, the dictionary may help you a lot more if it maps PropertyInfo to the string name of the PDF field, it just depends on how you are using it.
I know this is a poor answer, but that seems like a pretty good method. It also should work well for changes in the future.
Inheritance and attribute values
[ "", "c#", "inheritance", "" ]
I have a big problem opening <http://localhost/> on Windows 7 (beta). I installed this os and everything went great; when I installed Wamp I saw that localhost is not working at all. I just see this error: > ### Failed to Connect > > Firefox can't establish a connection to the server at localhost. in Mozilla and Explorer. I removed Wamp and after some weeks (that means two weeks from today) I installed NetBeans on Windows 7. I created a test PHP script and when I debug it, I get the same error again. I tried to access it with ip 127.... but still the same. What is the problem? When i installed NetBeans I installed it in port 8080.
To fix the port 80 problem do: From cmd as administrator: 1. `sc config http start= demand` (you need a space after the equal sign and not before) 2. Reboot 3. Run the command (`netsh http show servicestate`) as administrator to check that the port 80 is in use After you have run this command, you can disable http.sys as follows: 1. `net stop http` (stop the process) 2. `Sc config http start= disabled` (if you want to disable the service forever) it works for me.
If you installed it on port 8080, you need to access it on port 8080: <http://localhost:8080> or <http://127.0.0.1:8080>
http://localhost/ not working on Windows 7. What's the problem?
[ "", "php", "netbeans", "windows-7", "localhost", "wamp", "" ]
I need to encode/decode UTF-16 byte arrays to and from `java.lang.String`. The byte arrays are given to me with a [Byte Order Marker (BOM)](http://unicode.org/faq/utf_bom.html#bom1), and I need to encoded byte arrays with a BOM. Also, because I'm dealing with a Microsoft client/server, I'd like to emit the encoding in little endian (along with the LE BOM) to avoid any misunderstandings. I do realize that with the BOM it should work big endian, but I don't want to swim upstream in the Windows world. As an example, here is a method which encodes a `java.lang.String` as `UTF-16` in little endian with a BOM: ``` public static byte[] encodeString(String message) { byte[] tmp = null; try { tmp = message.getBytes("UTF-16LE"); } catch(UnsupportedEncodingException e) { // should not possible AssertionError ae = new AssertionError("Could not encode UTF-16LE"); ae.initCause(e); throw ae; } // use brute force method to add BOM byte[] utf16lemessage = new byte[2 + tmp.length]; utf16lemessage[0] = (byte)0xFF; utf16lemessage[1] = (byte)0xFE; System.arraycopy(tmp, 0, utf16lemessage, 2, tmp.length); return utf16lemessage; } ``` What is the best way to do this in Java? Ideally I'd like to avoid copying the entire byte array into a new byte array that has two extra bytes allocated at the beginning. The same goes for decoding such a string, but that's much more straightforward by using the [`java.lang.String` constructor](http://file:///Users/jared/Documents/jdk-6u10-docs/api/java/lang/String.html#String(byte[],%20int,%20int,%20java.lang.String)): ``` public String(byte[] bytes, int offset, int length, String charsetName) ```
The "UTF-16" charset name will always encode with a BOM and will decode data using either big/little endianness, but "UnicodeBig" and "UnicodeLittle" are useful for encoding in a specific byte order. Use UTF-16LE or UTF-16BE for no BOM - [see this post](http://illegalargumentexception.blogspot.com/2009/05/java-rough-guide-to-character-encoding.html#javaencoding_boms) for how to use "\uFEFF" to handle BOMs manually. See [here](http://java.sun.com/javase/6/docs/technotes/guides/intl/encoding.doc.html) for canonical naming of charset string names or (preferably) the [Charset](http://java.sun.com/javase/6/docs/api/java/nio/charset/Charset.html) class. Also take note that only a [limited subset of encodings](http://illegalargumentexception.blogspot.com/2009/05/java-rough-guide-to-character-encoding.html#javaencoding_encodings) are absolutely required to be supported.
First off, for decoding you can use the character set "UTF-16"; that automatically detects an initial BOM. For encoding UTF-16BE, you can also use the "UTF-16" character set - that'll write a proper BOM and then output big endian stuff. For encoding to little endian with a BOM, I don't think your current code is too bad, even with the double allocation (unless your strings are truly monstrous). What you might want to do if they are is not deal with a byte array but rather a java.nio ByteBuffer, and use the java.nio.charset.CharsetEncoder class. (Which you can get from Charset.forName("UTF-16LE").newEncoder()).
How do I encode/decode UTF-16LE byte arrays with a BOM?
[ "", "java", "unicode", "utf-16", "byte-order-mark", "" ]
I've used ``` #include<stdlib> #include<time> using namespace std; srand((unsigned)time(0)); int n=(rand()>>8)%4; ``` but what other random functions are there, or what other function could be used as random number generators? EDIT: I don't really have a particular reason for asking this question, I just wanted to know if C++ had any other random functions.
The rand() and srand() functions are all the C++ Standard specifies. And if it comes to writing your own, be aware of what John von Neumann said: > "Anyone who considers arithmetical > methods of producing random digits is > of course in a state of sin"
* [Boost Random Number Library](http://www.boost.org/doc/libs/release/libs/random) offers a broad range of generators (quality vs performance) and some typical random distributions. Everything rather nice and straightforward to use. * If you want some other methods/libraries - then google for cryptographic random numbers, also you can use [this document](http://www.cypherpunks.to/~peter/06_random.pdf) as a reference. * Don't invent your own solutions unless you are an expert/researcher in the field/etc, take advantage of already existing solutions which were usually written by Smart People, and thoroughly examined by other Smart People.
What is the most random function in C++?
[ "", "c++", "random", "" ]