Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I develop web applications and in my job so far, I have been waging battles with various browsers whenever some JS or CSS quirks happen. I believe using GWT will help me tremendously from what I understand from [this](http://code.google.com/webtoolkit/) description: > Writing web apps today is a tedious > and error-prone process. Developers > can spend 90% of their time working > around browser quirks. In addition, > building, reusing, and maintaining > large JavaScript code bases and AJAX > components can be difficult and > fragile. Google Web Toolkit (GWT) > eases this burden by allowing > developers to quickly build and > maintain complex yet highly performant > JavaScript front-end applications in > the Java programming language. What is the general opinion on GWT? How easy is it to learn and use it? EDIT: I am a Java developer!
You don't say if you've got any background with Java. If you don't, then, well, I can't speak to what your learning curve may be. However...as someone who's been working with Java for ~9 years, and much of that time spent with Swing, I've found GWT very easy to learn. The widgets are different from Swing, so that takes some getting used to. But, from my perspective, it's really no different than learning any other library. Personally, I love that I can use IntelliJ (my editor of choice) and take advantage of all the fantastic Java tools that help me write better code. (BTW...that's part of the [GWT mission](http://code.google.com/webtoolkit/makinggwtbetter.html#introduction).) I love the fact that this is a vibrant, and highly active toolkit, with lots of people really interested in making it better. (Again, take a look at the discussion group, or even browse through the [Contributor's discussion group](http://groups.google.com/group/Google-Web-Toolkit-Contributors).) If you want access to more or different widgets, there are lots of projects looking to fill the gaps: * [GWT-Ext](http://code.google.com/p/gwt-ext/) * [ExtGWT](http://extjs.com/products/gxt/) * [SmartGWT](http://code.google.com/p/smartgwt/) * [Advanced GWT Components](http://advanced-gwt.sourceforge.net/) * [GWT Incubator](http://code.google.com/p/google-web-toolkit-incubator/) (where lots of interesting ideas from the GWT team originate) (NOTE: I am NOT endorsing any of these project or commenting on their relative merits, just trying to provide some references...) I think if you dig around on the web, especially taking a look at the [GWT Discussion Group](http://groups.google.com/group/Google-Web-Toolkit/) you can get a good feeling for what others are doing with GWT. Having said all that, beware...you will still find some issues with how things render on IE6 vs IE7 vs FireFox 3, vs... I've not written a webapp in straight JavaScript or with any other toolkits, so I can't say how much better GWT is in this respect. All I know is that in 10+ months of working on the application I work on, we've encountered only a few cases where we had to specialize CSS for one browser or another.
If you're coming from Java background or are used to something like Swing I think it makes sense to use GWT as it keeps you coding in a familiar environment with familiar concepts. The other good reason to use GWT is if your team consists of mostly Java developers and very few web developers. In these cases it should be fairly easy to learn and use. On the other hand, I' not sure it's the right level of abstraction for building most web applications, especially if you're not building a desktop-like application but web pages mixed with rich functionality. Javascript is a powerful language, more suited for web in some ways than Java (Groovy could amend that, but I'm not sure how easy it is to integrate with GWT), there are plenty of mature JS frameworks that keep you away from most browser quirks and offer just the right level of abstraction, there are unit testing frameworks for JS, and there are some good programming practices to make your code more managable. For writing web apps I prefer doing client development on the client, and would like to see browsers evolve more in that direction instead of becoming containers for various sandboxes like Flex or GWT.
How useful is learning GWT?
[ "", "java", "gwt", "" ]
I have a table of data sorted by date, from which a user can select a set of data by supplying a start and end date. The data itself is non-continuous, in that I don't have data for weekends and public holidays. I would like to be able to list all the days that I don't have data for in the extracted dataset. Is there an easy way, in Java, to go: 1. Here is an ordered array of dates. 2. This is the selected start date. (The first date in the array is not always the start date) 3. This is the selected end date. (The last date in the array is not always the end date) 4. Return a list of dates which have no data.
You could create a temp list and x it as needed. (Not actual Java. Sorry, my memory of it is horrible.) ``` dates = [...]; // list you have now; // build list unused = []; for (Date i = startdate; i < enddate; i += day) { unused.push(i); } // remove used dates for (int j = 0; j < dates.length; j += 1) { if (unused.indexOf((Date) dates[j]) > -1) { // time = 00:00:00 unused.remove(unused.indexOf((Date) dates[j])); } } ```
You should be able to create a filtered iterator that provides this. Perhaps have the method for the iterator accept the start and stop date of your sub-collection. As for the actual implementation of the iterator, I can't think of anything much more elegant than a brute-force run at the whole collection once the start element has been found.
How can I list the missing dates from an array of non-continuous dates in Java?
[ "", "java", "datetime", "" ]
I have a Java method which returns an array of doubles. I would then like to store these values in individual variables in the calling function. Is there an elegant way of doing this in Java. I could write it as this: ``` double[] returnValues = calculateSomeDoubles(); double firstVar = returnValues[0]; double secondVar = returnValues[1]; ``` I was just wondering if there was some way of compressing this down to a single line? Something like: ``` (firstVar, secondVar) = calculateSomeDoubles(); ``` This type of thing is quite easy when scripting, but the stronger typing of Java means it probably isn't possible.
Basically no, this isn't possible. You'll have to return an object that contains the values. ``` MyObject myObject = calculateMyObject(); ```
The only way would be using reflection, granted you know upfront how many items method "calculateSomeDouble" will return. A variation of ***[this](https://stackoverflow.com/questions/271109/iterate-static-int-values-in-java#271127)*** would be needed. But as you see there's more to code. So the question that raises is? DO you want this for an automated stuff ? Or to save time for developing ( avoid having to copy/paste ) ? If you want to automate some task ( like filling an object at runtime ) then it is worth to do the reflection call and write the method. You will need to set the value rather than only print it. The client call should look like ``` SomeUtility.fill( myObject , withDoublesFromMethod() ); ```
Set Variable from an Array directly into a List of Variables in Java
[ "", "java", "function", "return", "" ]
Is there any way to split a long string of HTML after N words? Obviously I could use: ``` ' '.join(foo.split(' ')[:n]) ``` to get the first n words of a plain text string, but that might split in the middle of an html tag, and won't produce valid html because it won't close the tags that have been opened. I need to do this in a zope / plone site - if there is something as standard in those products that can do it, that would be ideal. For example, say I have the text: ``` <p>This is some text with a <a href="http://www.example.com/" title="Example link"> bit of linked text in it </a>. </p> ``` And I ask it to split after 5 words, it should return: ``` <p>This is some text with</p> ``` 7 words: ``` <p>This is some text with a <a href="http://www.example.com/" title="Example link"> bit </a> </p> ```
Take a look at the [truncate\_html\_words](http://code.djangoproject.com/browser/django/trunk/django/utils/text.py) function in django.utils.text. Even if you aren't using Django, the code there does exactly what you want.
I've heard that [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) is very good at parsing html. It will probably be able to help you get correct html out.
Split HTML after N words in python
[ "", "python", "html", "plone", "zope", "" ]
How can I get the current system status (current CPU, RAM, free disk space, etc.) in Python? Ideally, it would work for both Unix and Windows platforms. There seems to be a few possible ways of extracting that from my search: 1. Using a library such as [PSI](http://www.psychofx.com/psi/trac/wiki/) (that currently seems not actively developed and not supported on multiple platforms) or something like [pystatgrab](http://www.i-scream.org/pystatgrab/) (again no activity since 2007 it seems and no support for Windows). 2. Using platform specific code such as using a `os.popen("ps")` or similar for the \*nix systems and `MEMORYSTATUS` in `ctypes.windll.kernel32` (see [this recipe on ActiveState](http://code.activestate.com/recipes/511491/)) for the Windows platform. One could put a Python class together with all those code snippets. It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing?
[The psutil library](https://pypi.python.org/pypi/psutil) gives you information about CPU, RAM, etc., on a variety of platforms: > psutil is a module providing an interface for retrieving information on running processes and system utilization (CPU, memory) in a portable way by using Python, implementing many functionalities offered by tools like ps, top and Windows task manager. > > It currently supports Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.5 (users of Python 2.4 and 2.5 may use 2.1.3 version). --- Some examples: ``` #!/usr/bin/env python import psutil # gives a single float value psutil.cpu_percent() # gives an object with many fields psutil.virtual_memory() # you can convert that object to a dictionary dict(psutil.virtual_memory()._asdict()) # you can have the percentage of used RAM psutil.virtual_memory().percent 79.2 # you can calculate percentage of available memory psutil.virtual_memory().available * 100 / psutil.virtual_memory().total 20.8 ``` Here's other documentation that provides more concepts and interest concepts: * <https://psutil.readthedocs.io/en/latest/>
Use the [psutil library](https://pypi.org/project/psutil/). On Ubuntu 18.04, pip installed 5.5.0 (latest version) as of 1-30-2019. Older versions may behave somewhat differently. You can check your version of psutil by doing this in Python: ``` from __future__ import print_function # for Python2 import psutil print(psutil.__versi‌​on__) ``` To get some memory and CPU stats: ``` from __future__ import print_function import psutil print(psutil.cpu_percent()) print(psutil.virtual_memory()) # physical memory usage print('memory % used:', psutil.virtual_memory()[2]) ``` The `virtual_memory` (tuple) will have the percent memory used system-wide. This seemed to be overestimated by a few percent for me on Ubuntu 18.04. You can also get the memory used by the current Python instance: ``` import os import psutil pid = os.getpid() python_process = psutil.Process(pid) memoryUse = python_process.memory_info()[0]/2.**30 # memory use in GB...I think print('memory use:', memoryUse) ``` which gives the current memory use of your Python script. There are some more in-depth examples on the [pypi page for psutil](https://pypi.org/project/psutil/).
How to get current CPU and RAM usage in Python?
[ "", "python", "system", "cpu", "status", "ram", "" ]
I have a class like this: ``` public class myClass { public List<myOtherClass> anewlist = new List<myOtherClass>; public void addToList(myOtherClass tmp) { anewList.Add(tmp); } } ``` So I call "addToList" a hundred times, each adding a unique item to the list. I've tested my items to show that before I run the "addToList" method, they are unique. I even put a line in to test "tmp" to make sure it was what I was expecting. However, when I do this (lets say myClass object is called tmpClass): ``` int i = tmpClass.anewList.Count(); for (int j = 0; j<i; j++) { //write out each member of the list based on index j... } ``` I get the same exact item, and it's the last one that was written into my list. It's as if when I add, I'm overwriting the entire list with the last item I've added. Help? This makes no sense. I've also tried List.Insert, where I'm always inserting at the end or at index 0. Still no dice. Yes, I'm doubly source my indexing is correct and when I do my test I'm indexing through each of the elements. :) UPDATE: Okay, I tried this and still had the same problem: ``` foreach(myOtherClass tmpC in tmpClass.anewList) { Console.WriteLine(tmpC.theStringInMyClass.ToString()); } ``` and still for each of the 100 items, I got the same string output... I'm sure I'm doing something completely stupid, but I don't know what yet. I'm still 100% sure that the right string is getting passed in to begin with. -Adeena --- Okay, I tried this and still had the same problem: ``` foreach(myOtherClass tmpC in tmpClass.anewList) { Console.WriteLine(tmpC.theStringInMyClass.ToString()); } ``` and still for each of the 100 items, I got the same string output... I'm sure I'm doing something completely stupid, but I don't know what yet. I'm still 100% sure that the right string is getting passed in to begin with. -Adeena
Given the signature of your addToList method: ``` public void addToList(myOtherClass tmp) { anewList.Add(tmp); } ``` Is is possible that in the consumer of that method, you aren't actually creating a new instance? You said that you are calling addToList 100 times. Presumably, that is in a loop. At each loop iteration, you will need to create a new instance of "myOtherClass", otherwise, you'll just be updating the same object in memory. For example, if you do the below, you will have 100 copies of the same object: ``` myOtherClass item = new myOtherClass(); for(int i=0; i < 100; i++) { item.Property = i; addToList(item); } ``` However, if your loop looks like the below, it will work fine: ``` myOtherClass item = null; for(int i=0; i < 100; i++) { item = new myOtherClass(); item.Property = i; addToList(item); } ``` Hope that helps!
In this case, it would likely be helpful to see how you are validating each item to be sure that the items are unique. If you could show the ToString() method of your class it might help: you might be basing it on something that is actually the same between each of your objects. This might help decide whether you really are getting the same object each time, or if the pieces under consideration really are not unique. Also, rather than accessing by index, you should use a `foreach` loop whenever possible. Finally, the items in a list are not universally unique, but rather references to an object that exists elsewhere. If you're trying to check that the retrieved item is unique with respect to an external object, you're going to fail. One more thing, I guess: you probably want to have the access on `anewList` to be private rather than `public`.
List.Add seems to be duplicating entries. What's wrong?
[ "", "c#", "list", "" ]
So I've got some scripts I've written which set up a Google map on my page. These scripts are in included in the `<head>` of my page, and use jQuery to build the map with markers generated from a list of addresses on the page. However, I have some exact co-ordinate data for each address which the javascript requires to place the markers correctly. This isn't information I want to be visible on the screen to the user, so what's the "best practice" way to put that data into my document?
I would not reccomend using style to hide something, it will show up in browsers without (or with disabled) css suppor and look strange. You could store it in a javascript variable or add a form with hidden values like this (inside an unused form to be sure it validates): ``` <form action="#" method="get" id="myHiddenValues"> <input type="text" name="hiddenval1" id="hiddenval1" value="1234"/> <input type="text" name="hiddenval2" id="hiddenval2" value="5678"/> </form> ``` wich you can read and update from javascript.
My first thought was a hidden input with a CSV or similar of the data. Since the data is not really secret, just not for display. ``` <input id="coordinates" type="hidden" value="123.2123.123:123,123,321;....." /> ``` Then access it with jquery ``` var myCoordsCSV = $("#coordinates").val(); ``` Edit: A below answer mentions JSON which would be a better solution combined with using multiple hidden inputs as pointed out in another answer.
Best way to include unobtrusive information on a web page
[ "", "javascript", "html", "json", "google-maps", "" ]
I have the following code for a UDF but it errors with the message: > Msg 156, Level 15, State 1, Procedure > CalendarTable, Line 39 Incorrect > syntax near the keyword 'OPTION'. is it because of my WITH statement as I can run the same code fine in a stored procedure? ``` SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Anthony Main -- Create date: 18/11/08 -- Description: Produce Table of Dates for Month -- ============================================= CREATE FUNCTION CalendarTable ( @StartDate DATETIME, @EndDate DATETIME ) RETURNS TABLE AS RETURN ( with MyCalendar as ( select cast(@StartDate as datetime) DateValue union all select DateValue + 1 from MyCalendar where DateValue + 1 <= @EndDate ) select DateValue , datepart(dy, DateValue) [day of year] , datename(dw, DateValue) [day] , datepart(dw, DateValue-1) [day of week] , datepart(dd, DateValue) [day of month] , datepart(ww, DateValue) [week] , datepart(mm, DateValue) [month] , datename(mm, DateValue) [month] , datepart(qq, DateValue) [quarter] , datepart(yy, DateValue) [year] , datepart(HH, DateValue) [HOUR] , datepart(MI, DateValue) [MIN] , datepart(SS, DateValue) [SEC] , datepart(MS, DateValue) [MILLISECOND] from MyCalendar OPTION (MAXRECURSION 0) ) GO ```
No, you can't use the OPTION keyword. From the documentation: "MAXRECURSION can be used to prevent a poorly formed recursive CTE from entering into an infinite loop. The following example intentionally creates an infinite loop and uses the MAXRECURSION hint to limit the number of recursion levels to two." If you explain what you want to query (what do you want the end results to look like), we could write a better SQL statement that doesn't need recursion.
From what I can tell, OPTION MAXRECURSION is not allowed in a UDF. There is an item at [connect.microsoft.com](http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=124653) with the issue.
Can you have a WITH statement in a tabular user defined function
[ "", "sql", "sql-server-2005", "t-sql", "" ]
I have an array of different type objects and I use a BinaryWriter to convert each item to its binary equivalent so I can send the structure over the network. I currently do something like ``` for ( i=0;i<tmpArrayList.Count;i++) { object x=tmpArrayList[i]; if (x.GetType() == typeof(byte)) { wrt.Write((byte)x); } ........ ``` The problem is that if miss a type them my code might break in the future. I would like to do something like. ``` object x=tmpArrayList[i]; wrt.Write(x); ``` but it doesn't work unless I do each cast. Edit: After consulting the answers this is what I came up with for the function. For testing this function sends the array to syslog. ``` private void TxMsg(ArrayList TxArray,IPAddress ipaddress) { Byte[] txbuf=new Byte[0]; int sz=0; // caculate size of txbuf foreach (Object o in TxArray) { if ( o is String ) { sz+=((String)(o)).Length; } else if ( o is Byte[] ) { sz+=((Byte[])(o)).Length; } else if ( o is Char[] ) { sz+=((Char[])(o)).Length; } else // take care of non arrays { sz+=Marshal.SizeOf(o); } } txbuf = new Byte[sz]; System.IO.MemoryStream stm_w = new System.IO.MemoryStream( txbuf, 0,txbuf.Length); System.IO.BinaryWriter wrt = new System.IO.BinaryWriter( stm_w ); foreach (Object o in TxArray) { bool otypefound=false; if (o is String) // strings need to be sent one byte per char { otypefound=true; String st=(String)o; for(int i=0;i<st.Length;i++) { wrt.Write((byte)st[i]); } } else { foreach (MethodInfo mi in typeof(BinaryWriter).GetMethods()) { if (mi.Name == "Write") { ParameterInfo[] pi = mi.GetParameters(); if ((pi.Length == 1)&&(pi[0].ParameterType==o.GetType())) { otypefound=true; mi.Invoke(wrt, new Object[] { o }); } } } } if(otypefound==false) { throw new InvalidOperationException("Cannot write data of type " + o.GetType().FullName); } } IPEndPoint endpoint = new IPEndPoint(ipaddress, 514); //syslog port UdpClient udpClient_txmsg = new UdpClient(); udpClient_txmsg.Send(txbuf, txbuf.Length,endpoint); // send udp packet to syslog } ```
Here is a solution for BinaryWriter that uses reflection. This basically scans BinaryWriter for methods named Write that takes exactly one parameter, then builds a dictionary of which method handles which type, then for each object to write, finds the right method and calls it on the writer. Dirty, and you should probably look for better ways of doing the whole thing (not just the writing part), but it should work for your current needs: ``` using System.IO; using System; using System.Reflection; using System.Collections.Generic; namespace ConsoleApplication14 { public class Program { public static void Main() { Dictionary<Type, MethodInfo> mapping = new Dictionary<Type, MethodInfo>(); foreach (MethodInfo mi in typeof(BinaryWriter).GetMethods()) { if (mi.Name == "Write") { ParameterInfo[] pi = mi.GetParameters(); if (pi.Length == 1) mapping[pi[0].ParameterType] = mi; } } List<Object> someData = new List<Object>(); someData.Add((Byte)10); someData.Add((Int32)10); someData.Add((Double)10); someData.Add((Char)10); someData.Add("Test"); using (FileStream file = new FileStream(@"C:\test.dat", FileMode.Create, FileAccess.ReadWrite)) using (BinaryWriter writer = new BinaryWriter(file)) { foreach (Object o in someData) { MethodInfo mi; if (mapping.TryGetValue(o.GetType(), out mi)) { mi.Invoke(writer, new Object[] { o }); } else throw new InvalidOperationException("Cannot write data of type " + o.GetType().FullName); } } } } } ```
No. The cast has to be known at compile-time, but the actual type is only known at execution time. Note, however, that there's a better way of testing the type calling GetType. Instead of: ``` if (x.GetType() == typeof(byte)) ``` Use: ``` if (x is byte) ``` EDIT: To answer the extra questions: "What are all the types?" Well, look down the docs for BinaryWriter, I guess... "Do I need to worry about byte and Byte?" No, byte is an alias for System.Byte in C#. They're the same type.
Is there a way cast an object back to it original type without specifing every case?
[ "", "c#", "casting", "syslog", "udpclient", "" ]
I have a J2EE project in Eclipse 3.2 and at the end of every build I want to automatically create and deploy a WAR file. At the moment I have to do this by hand which is 5 or 6 mouse-cliks and it would be nice to automate it. I know I can do this with a custom build script using ANT but I am hoping for an Eclipse native solution. I have the J2EE standard tools (JST) and Web Standard Tools (WST) plug-ins installed in my Eclipse environment.
If you can implement it as an Ant script, then you can have Eclipse invoke that Ant script on each build automatically (and inside the Eclipse environment). Use Project->Properties->Builders->Add->Ant Builder. Give that builder you custom Ant script and it will automatically be executed after the "normal" builders of your project.
There are only two options: * Or you right click on project: Run -> Run on server. (Your project needs to be a web project.) * Or you write that ant script and use eclipse to store you ant run configuration and reuse that config.
How do I automatically export a WAR after Java build in Eclipse?
[ "", "java", "eclipse", "deployment", "war", "" ]
I'm using Hibernate 3.1 and Oracle 10 DB. The blob is defined as @Lob @Basic @Column in the Hibernate entity which corresponds to the relevant DB table. The error -java.sql.SQLException: Closed Connection- seem to appear once in while, not in every attempt to get the blob from the DB. This seems like a hibernate fetching issue, so I thought of specifying the type of fetch to be used - EAGER seems right in this case -but coudln't find any way to specify type of fetching for @Column type of object (there is a way to do that for collections / "one to many" relationships etc) Would appreciate your help, thanks.
I've recently implemented a hibernate system on top of a Oracle 11g db that uses blobs. There isn't any real magic to it. The standard cause of 'Session closed' hibernate errors is (not to point out the obvious) that the session that your entity is attached to really is closed. Make a point of working out exactly where and when the session is being opened and closed. This may not be completely obvious if you are using AOP or a spring to manage this for you. In addition I'm pretty sure you need an open transaction, or at least an db connection with autocommit turned off. Gareth
Is this against an Oracle database? I've had to resort to user data types in Hibernate to get this to work, but that was using Hibernate 3.0 against an Oracle 9 db. See <http://www.hibernate.org/56.html> for a long discussion about this topic (including user data types).
"Session closed" error when trying to get a blob from DB using getBinaryStream()
[ "", "java", "oracle", "hibernate", "" ]
I noticed that the generic `IEnumerator<T>` inherits from IDisposable, but the non-generic interface IEnumerator does not. Why is it designed in this way? Usually, we use foreach statement to go through a `IEnumerator<T>` instance. The generated code of foreach actually has try-finally block that invokes Dispose() in finally.
Basically it was an oversight. In C# 1.0, `foreach` *never* called `Dispose` 1. With C# 1.2 (introduced in VS2003 - there's no 1.1, bizarrely) `foreach` began to check in the `finally` block whether or not the iterator implemented `IDisposable` - they had to do it that way, because retrospectively making `IEnumerator` extend `IDisposable` would have broken everyone's implementation of `IEnumerator`. If they'd worked out that it's useful for `foreach` to dispose of iterators in the first place, I'm sure `IEnumerator` would have extended `IDisposable`. When C# 2.0 and .NET 2.0 came out, however, they had a fresh opportunity - new interface, new inheritance. It makes much more sense to have the interface extend `IDisposable` so that you don't need an execution-time check in the finally block, and now the compiler knows that if the iterator is an `IEnumerator<T>` it can emit an unconditional call to `Dispose`. EDIT: It's incredibly useful for `Dispose` to be called at the end of iteration (however it ends). It means the iterator can hold on to resources - which makes it feasible for it to, say, read a file line by line. Iterator blocks generate `Dispose` implementations which make sure that any `finally` blocks relevant to the "current point of execution" of the iterator are executed when it's disposed - so you can write normal code within the iterator and clean-up should happen appropriately. --- 1 Looking back at the 1.0 spec, it was already specified. I haven't yet been able to verify this earlier statement that the 1.0 implementation didn't call `Dispose`.
IEnumerable<T> doesn't inherit IDisposable. IEnumerator<T> does inherit IDisposable however, whereas the non-generic IEnumerator doesn't. Even when you use *foreach* for a non-generic IEnumerable (which returns IEnumerator), the compiler will still generate a check for IDisposable and call Dispose() if the enumerator implements the interface. I guess the generic Enumerator<T> inherits from IDisposable so there doesn't need to be a runtime type-check—it can just go ahead and call Dispose() which should have better performance since it can be probably be optimized away if the enumerator has an empty Dispose() method.
Why does IEnumerator<T> inherit from IDisposable while the non-generic IEnumerator does not?
[ "", "c#", "generics", "ienumerator", "" ]
I have an array in PHP which holds a bunch of unix timestamps. As a simplified example, here is an array of 10 values. ``` $array = [ 1510790277, 1586522582, 1572272336, 1650049585, 1591332330, 1698088238, 1646561226, 1639050043, 1652067570, 1548161804, ]; ``` I need to produce an array containing the indexes of the 3 largest numbers in that array. From the sample array, I would expect a result of `[5, 8, 3]` -- in that order.
You could use [asort](https://www.php.net/manual/en/function.asort.php) to sort the array and maintain index and then use [slice](https://www.php.net/manual/en/function.array-slice.php) along with the 4th parameter, again to maintain the index, to grap the top x number of elements you are after, and finally use [array\_keys](https://www.php.net/manual/en/function.array-keys.php). There may well be a quicker way, but it's just to show there are plenty of PHP array functions to help you achieve the effect you're looking for.
Simon posted the simple and probably good-enough performing method. The other option, only if you have a really large array, is to scan through the array and keep track of the indexes of the three highest values you see. This is O(n), but (especially since its in interpreted PHP code, not a compiled built-in function), probably slower for all but the largest of arrays.
Get indexes of 3 largest values in a flat array
[ "", "php", "arrays", "sorting", "key", "slice", "" ]
I'm looking at starting a project in C++ using the Qt 4 framework (a cross-platform GUI is required). I've heard great things about the Boost libraries from friends and online. I've started reading up on both and wanted to ask a cursory question before I got too deep: Are these two development "systems" mutually exclusive? My initial searching and reading shows some overlap in the signal handling, custom build systems, and other low-level primitives. Does it make sense to use them both in the same project?
Yes it makes perfect sense. I would generally prefer using the boost/stdlib functions where possible rather than their Qt alternatives. It makes the code easier to port to the next framework. It makes is easier for new non-Qt programmers to get upto speed. Boost has some great functionality and is getting more all the time. note: strings to/from widgets are probably the main exception - inside the GUI I would use Qt strings to save confusing casts everywhere.
[This paper](http://www.elpauer.org/stuff/a_deeper_look_at_signals_and_slots.pdf) compares [signal slots](http://doc.qt.io/qt-4.8/signalsandslots.html) mechanism in QT and [Boost::Signal](http://www.boost.org/doc/html/signals.html) very decently. It is a must read for those who are a bit curious of this mix.
Mixing Qt and Boost
[ "", "c++", "qt", "boost", "" ]
I need some help calculating Pi. I am trying to write a python program that will calculate Pi to X digits. I have tried several from the python mailing list, and it is to slow for my use. I have read about the [Gauss-Legendre Algorithm](http://en.wikipedia.org/wiki/Gauss-Legendre_algorithm), and I have tried porting it to Python with no success. I am reading from [Here](http://www.geocities.com/hjsmithh/Pi/Gauss_L.html), and I would appreciate any input as to where I am going wrong! It outputs: 0.163991276262 ``` from __future__ import division import math def square(x):return x*x a = 1 b = 1/math.sqrt(2) t = 1/4 x = 1 for i in range(1000): y = a a = (a+b)/2 b = math.sqrt(b*y) t = t - x * square((y-a)) x = 2* x pi = (square((a+b)))/4*t print pi raw_input() ```
1. You forgot parentheses around `4*t`: ``` pi = (a+b)**2 / (4*t) ``` 2. You can use `decimal` to perform calculation with higher precision. ``` #!/usr/bin/env python from __future__ import with_statement import decimal def pi_gauss_legendre(): D = decimal.Decimal with decimal.localcontext() as ctx: ctx.prec += 2 a, b, t, p = 1, 1/D(2).sqrt(), 1/D(4), 1 pi = None while 1: an = (a + b) / 2 b = (a * b).sqrt() t -= p * (a - an) * (a - an) a, p = an, 2*p piold = pi pi = (a + b) * (a + b) / (4 * t) if pi == piold: # equal within given precision break return +pi decimal.getcontext().prec = 100 print pi_gauss_legendre() ``` Output: ``` 3.141592653589793238462643383279502884197169399375105820974944592307816406286208\ 998628034825342117068 ```
``` pi = (square((a+b)))/4*t ``` should be ``` pi = (square((a+b)))/(4*t) ```
Gauss-Legendre Algorithm in python
[ "", "python", "algorithm", "pi", "" ]
Why don't we get compile errors on inline code errors in asp.net mvc views f.eks ``` <h1><%= ViewData.Model.Title.Tostrig() %></h1> ``` The code above will build just fine. Wrong spelling in webform controls will give you an error so I can't see why this isn't supported in asp.net mvc EDIT: Luckily there seem to be a fix included in the first RC for asp.net mvc <http://weblogs.asp.net/scottgu/archive/2008/12/19/asp-net-mvc-design-gallery-and-upcoming-view-improvements-with-the-asp-net-mvc-release-candidate.aspx>
The ASPX files in both ASP.NET and ASP.NET MVC are not compiled from the Visual Studio IDE. This is often the cause for "false positives" as you have pointed out. I often add the [aspnet\_compiler](http://msdn.microsoft.com/en-us/library/ms229863(VS.80).aspx) as a post build action to find those errors. You will add some time to your build process, but in exchange for the wait you should be able to spot these errors more easily.
Following from Jason's answer, this line should work on most projects: ``` C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler -v / -p "$(ProjectDir)\" ``` Or for .NET 4 projects: ``` C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_compiler -v / -p "$(ProjectDir)\" ``` Source - [Compiling aspx templates using aspnet\_compiler](http://mikehadlow.blogspot.com/2008/05/compiling-aspx-templates-using.html)
Build does not catch errors in the View in asp.net mvc
[ "", "c#", "asp.net", "asp.net-mvc", "debugging", "" ]
I was wondering if it is possible to declare an array (size not known at this time), as a private member of a class and later set the size in the constructor of the class. For example: ``` class Test { int a[]; public: Test(int size); }; Test::Test(int size) { a[size]; // this is wrong, but what can i do here? } ``` Is this possible or should I use dynamic arrays? Thanks!
No this is not possible. Array declarations in headers must have constant sized value. Otherwise it's impossible for constructs like "sizeof" to function properly. You'll need to declare the array as a pointer type and use new[] in the constructor. Example. ``` class Test { int *a; public: Test(int size) { a = new int[size]; } ~Test() { delete [] a; } private: Test(const Test& other); Test& operator=(const Test& other); }; ```
Short Answer: No (The size of an array is defined at compile time only) Long Answer: You can use a vector to achieve the same result: ``` class Test { std::vector<int> a; public: Test(std::size_t size): a(size) {} }; ```
c++ array declaration in a header
[ "", "c++", "arrays", "dynamic", "header", "" ]
I need an OpenSource API in Java, which can encode \*.wav and \*.au formats to MP3 and vice-versa. I have evaluated Java Sound API and [LameOnJ](http://openinnowhere.sourceforge.net/lameonj), but they do not meet my requirements and are not stable, respectively. Please suggest one that is free and platform independent.
There may not be an adequate answer for you, yet, as the MP3 format requires the authors of decoder/encoders to obtain a license from the Fraunhofer Institute. I think the the LAME library is distributed from a country that does not respect these IP issues, but it took a considerably amount of legal hackery to get this far. For any other libraries - for example one written in Java, the authors need to get a similar license. Where cost is an issue - e.g. in an Open Source project, then this is enough of a disincentive to starting. For more details see this [wikipedia article](http://en.wikipedia.org/wiki/MP3#Licensing_and_patent_issues). If LAME4J is not stable enough for you, then I'm afraid your options are probably: * wait for Sun to license the format for the core JRE. This, I believe they have done recently, but I don't know of any release dates (perhaps to do with JavaFX) * implement your own in Java, and pay the license. I wouldn't fancy this one, either. * write your own Java wrapper to LAME, via JNA, or SWIG * contribute to Lame4J. * pick another format. OGG and FLAC are quite good, and relatively well supported.
Is has been some time, but Oracle/Sun has released MP3 support for JMF. This can be downloaded from the following url: <http://www.oracle.com/technetwork/java/javase/tech/index-jsp-140239.html> Adding it to the classpath will enable playback via the AudioSystem api.
MP3 Encoding in Java
[ "", "java", "api", "encoding", "mp3", "" ]
On my Centos server Python's mimetypes.guess\_type("mobile.3gp") returns (None, None), instead of ('video/3gpp', None). Where does Python get the list of mimetypes from, and is it possible to add a missing type to the list?
On my system (Debian lenny) its in /usr/lib/python2.5/mimetypes.py in the list `knownfiles` you can supply your own files for the `init()` function.
The mimetypes module uses mime.types files as they are common on Linux/Unix systems. If you look in mimetypes.knownfiles you will find a list of files that Python tries to access to load the data. You can also specify your own file to add new types by adding it to that list.
Adding a mimetype in python
[ "", "python", "mime-types", "" ]
I have written a game that uses GLUT, OpenGL and FMOD. The problem is that the binary won't run, unless Visual Studio 2008 is installed on the computer. Why is this?
Most likely you're linking with DLL versions of the C/C++ runtime. Go to project properties -> C++ -> Code Generation, and set Runtime Library to *not* be one of "DLL" kinds. Alternatively, you can link to DLL runtimes, but then you have to redistribute the runtime with your application. MSDN has more information on various aspects of C++ application deployment: <http://msdn.microsoft.com/en-us/library/zebw5zk9.aspx> Also, [Dependency Walker (depends.exe)](http://www.dependencywalker.com/) will show what libraries your executable depends on. It ships with some versions of Visual Studio as well.
You mean why is [Microsoft Visual C++ 2008 Redistributable Package (x86)](http://www.microsoft.com/downloads/details.aspx?FamilyID=9b2da534-3e03-4391-8a4d-074b9f2bc1bf&displaylang=en) needed? > This package installs runtime > components of C Runtime (CRT), > Standard C++, ATL, MFC, OpenMP and > MSDIA libraries. For libraries that > support side-by-side deployment model > (CRT, SCL, ATL, MFC, OpenMP) they are > installed into the native assembly > cache, also called WinSxS folder, on > versions of Windows operating system > that support side-by-side assemblies. Because they are not installed on all Windows by default, especially the ones that shipped before VS 2008. Even for ``` cout << "Hello, World" << endl; ``` You need a library, which in this case the Standard C++ library.
Why won't my program run unless Visual Studio 2008 is installed?
[ "", "c++", "visual-studio-2008", "redistributable", "" ]
I have an interface that defines some methods I would like certain classes to implement. ``` public interface IMyInterface { MethodA; MethodB; } ``` Additionally I would like all classes implementing this interface to be serializable. If I change the interface definition to implement ISerializable as below...: ``` public interface IMyInterface : ISerializable { MethodA; MethodB; } ``` ...all classes must now explicitly implement serialization as far as I am aware, since if you implement ISerializable you must implement the GetObjectData member (and the necessary constructor to deserialize). How can I insist classes using my interface be serializable, but without forcing them to custom implement serialization? Thanks, Will
Thanks for the replies. It would be nice to be able to force classes derived from an interface to implement serialization without this then forcing them to custom serialize but it doesn't seem to be possible.
**There does not seem to be a way to do this**, but I wish there were. Note two things though: * The **Serializable attribute can not be inherited from a base class**, even if the base class is marked as abstract. * You **don't technically need the Serializable attribute, IF** you are **using an XmlSerializer** because it does not make use of object graphs.
Enforcing serializable from an interface without forcing classes to custom serialize in C#
[ "", "c#", "interface", "serialization", "" ]
I have a c# struct where I need to forbid calling the no args constructor on it. ``` MyStruct a; /// init a by members // OK MyStruct b = MyStruct.Fact(args); // OK, inits by memebers MyStruct s = new MyStruct(); // can't have that ``` I'm doing this mostly to force explicet values for all members as there are no valid default values and all members must have valid values. In C++ this would be easy, add a private constructor but c# doesn't allow that. Is there a way to prevent the above? I really need to enforce using a factory so preventing all public constructor calls would work just as well. --- Full discloser: to avoid a mono dependency, the c# app is being automatically translated to D where `new Struct()` results in a pointer and this is mucking things up for me. However this question is relevant despite that so just ignore it.
You can't. All structs have a public parameterless constructor by definition in C#. (In the CLR almost none of them do, but they can always act as if they have.) See [this question](https://stackoverflow.com/questions/333829) for why you can't define your own parameterless constructors on structs (in C#, anyway). In fact, you *can* prevent this statement if you're happy to write your value type in IL. I've just checked, and if you make sure that your value type only has a parameterless constructor, and make it internal, you won't be able to write `MyStruct ms = new MyStruct();` But this doesn't prevent: ``` MyStruct[] array = new MyStruct[1]; MyStruct ms = array[0]; ``` which works around the new restriction - so it doesn't really buy you anything. That's quite good really, as messing around in IL would be messy. Are you sure you really want to be writing a struct in the first place? That's *almost* never a good idea.
You can't. All values in a struct must be initialized at construction time, and there's no way to do that outside the constructor. What exactly are you trying to accomplish by doing that? Structs are value types, so you'll get a "new" struct for most operations. It will be very difficult to enforce the sorts of constraints you'd use a factory for on a struct.
How do I enforce using a factory on a struct in C#
[ "", "c#", "struct", "factory", "" ]
My company needs a PDF viewer with Java API with the additional requirement on being able to use FDF form data. The only one i found was [JPedal](http://www.jpedal.org/index.php) which promises to feature everything we need, but it costs a bunch. So what are my options? Is there another tool to do it? edit: I found [iText](http://www.lowagie.com/iText/) to be an easy way to merge FDF data into the PDF form. The only LGPL viewer that worked *ok* (unlike Adobe's own 10 year old Java 1.1 API) was Sun's [pdf-renderer](https://pdf-renderer.dev.java.net/). But sadly it doesn't display form values. iText's form-flattening helps, but there has to be a better way.
Have a look at the Foxit SDK. <http://www.foxitsoftware.com/> The cost seems at bit less and i'm sure you'll get much more. Maybe Open Office has something in its belt for you? I also just found those: <http://www.crionics.com/> <http://www.qoppa.com/> <http://multivalent.sourceforge.net/>
Try the Big Faceless' Java Viewer: <http://big.faceless.org/products/pdfviewer/>
Java PDF viewer with FDF
[ "", "java", "pdf", "" ]
If I have an mssql varchar[1024] that is always empty in a table, how much actual bytes will be wasted in the db file on disk per row? Please let me know the size for both: 1. NULLs allowed storing '' * NULLs not allowed storing '' * NULLs allowed storing NULL Since the max varchar size is > 2^1 and < 2^3 I would assume 2 bytes for the length. But perhaps there is some more overhead, for example if there is a reference that points to the actual data.
I believe that a varchar uses only the minimum storage required to hold the string. MSDN and books online seem to confirm this. However, the sum of stored data (including other fields) cannot exceed a certain length (which I think is 8K). I don't think you've got this problem, as I think it is flagged at creation time. more details are here: <http://doc.ddart.net/mssql/sql70/ca-co_3.htm>
In each row that allows nulls, there is a null bitmap object that controls whether a particular column's value is null or not. The size in bytes of this bitmap will be NumberOfNullableColumns/8, rounded up to the next whole byte Additionally, the overhead for the length of a varchar is 2 bytes. With that in mind: 1. Nullable column storing an empty string = 2 bytes (plus 1 bit for the bitmap) 2. Non-nullable column storing an empty string = 2 bytes 3. Nullable column storing null = 0 bytes (plus 1 bit for the bitmap)
If I have an mssql varchar[1024] that is always empty in a table, how much actual bytes will be wasted?
[ "", "sql", "sql-server", "" ]
I am coding a feature in a program where users can edit documents stored in a database, it saves the document to a temporary folder then uses Process.Start to launch the document into the editing application, let's say Microsoft Word for example. Then my app needs to wait until they've closed the called process and replace the document in the database with the newly edited copy in the temp folder. The following code works great as long as the called application isn't already running: ``` ProcessStartInfo pInfo = new ProcessStartInfo(); pInfo.FileName=TempFolder + Path.DirectorySeparatorChar + f.Name; Process p = new Process(); p.StartInfo = pInfo; p.Start(); //p is null at this point if called application was already running //i.e. Microsoft Word is re-used instead of starting a fresh copy p.WaitForInputIdle(); p.WaitForExit(); ``` Is there a way to *force* starting a completely new process or can anyone think of another way to handle this. I really don't want the users to be able to do anything else in my app until they've closed the called process because I need to know if they edited that file or not at that point in time, not later when all sorts of other problems could creep up.
After further research and coming across a number of posts mentioning the unreliability of WaitForExit and the process' Exited event, I've come up with a completely different solution: I start the process and don't bother waiting for it, just pop up a modal dialog in which the user can click on update to update the temporary folder file back into the database when they've edited and saved the temporary file or cancel. This way it's in their hands and I don't have to rely on the vagaries of Process.Start. Thanks for everyone's help.
Personally I'm not sure I agree with this approach at all. Displaying a modal form might get you out of this situation, but in most cases when a solution seems hard to find, it's helpful to change the problem you're trying to solve. **Option 1:** In this case, I'd recommend a checkout/checkin model. This would allow users to "checkout" a file to their machine, and then check it in when they have finished updating it. This has a number of benefits: * They can edit many documents at once, and perform checkin operations on multiple documents at once. * They can apply comments to checkins. * The user can shutdown their PC, or go offline and still work on their document. * The user can checkout multiple documents locally, then take the work home. * You don't have to try and work out what to do if the PC crashes (or the laptop battery runs out) while a document is open, and how to get it all back together again. The model also fits well with the concept of creating a new document, and adding it to the database. It's the same as a checkin. You could easily provide reports that display who has what document checked out, and what their "working copy" location is. I would concede that typically only developers are comfortable with this model, and that you may have to invest in a small amount of re-training. I don't think it would be difficult to setup an automated reminder system that emails people when they've had a document checked out for a long time. **Option 2:** Watch the file using a FileSystemWatcher or equivalent. This would enable you to keep an eye on the file, and when the user performs a save operation, you can commit to the database. After all, it's only if the user actually saved the file that you're interested in updating the database,
C# Process.Start, how to prevent re-use of existing application?
[ "", "c#", "winforms", "" ]
Can anyone recommend a decent SFTP library for use with Windows C++ apps? If a cross-platform one is available then all the better, but it's not essential. It's for use with a commercial application, so paying for something isn't an issue. I am using the superb [Ultimate TCP/IP](http://www.codeproject.com/KB/MFC/UltimateTCPIP.aspx) library which supports FTP-S but not SFTP (yeh, I know, confusing isn't it!). I've come across the [Chilkat](http://www.chilkatsoft.com/ssh-sftp-c++.asp) library, which looks very good, but wondered if there are any others that people have used.
Check out [libcurl](http://curl.haxx.se/libcurl/). > libcurl is a free and easy-to-use client-side URL transfer library, supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. libcurl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, Kerberos4), file transfer resume, http proxy tunneling and more! > > libcurl is highly portable, it builds and works identically on numerous platforms, including Solaris, NetBSD, FreeBSD, OpenBSD, Darwin, HPUX, IRIX, AIX, Tru64, Linux, UnixWare, HURD, Windows, Amiga, OS/2, BeOs, Mac OS X, Ultrix, QNX, OpenVMS, RISC OS, Novell NetWare, DOS and more...
[OpenSSH](http://www.openssh.com/) would be a good option. It's cross-platform and comes with a BSD license, so you can use it in your commercial application without having to disclose your source code.
SFTP C++ library?
[ "", "c++", "sftp", "" ]
<http://leepoint.net/notes-java/data/expressions/22compareobjects.html> > It turns out that defining equals() > isn't trivial; in fact it's moderately > hard to get it right, especially in > the case of subclasses. The best > treatment of the issues is in > Horstmann's Core Java Vol 1. If equals() must always be overridden, then what is a good approach for not being cornered into having to do object comparison? What are some good "design" alternatives? EDIT: I'm not sure this is coming across the way that I had intended. Maybe the question should be more along the lines of "Why would you want to compare two objects?" Based upon your answer to that question, is there an alternative solution to comparison? I don't mean, a different implementation of equals. I mean, not using equality at all. I think the key point is to start with that question, why would you want to compare two objects.
> If equals() must always be overridden, > then what is a good approach for not > being cornered into having to do > object comparison? You are mistaken. You should override equals as seldom as possible. --- All this info comes from [Effective Java, Second Edition](http://java.sun.com/docs/books/effective/) ([Josh Bloch](http://en.wikipedia.org/wiki/Joshua_Bloch)). The first edition chapter on this is still available as a free [download](http://developer.java.sun.com/developer/Books/effectivejava/Chapter3.pdf). *From Effective Java:* > The easiest way to avoid problems is > not to override the equals method, in > which case each instance of the class > is equal only to itself. The problem with arbitrarily overriding equals/hashCode is inheritance. Some equals implementations advocate testing it like this: ``` if (this.getClass() != other.getClass()) { return false; //inequal } ``` In fact, the [Eclipse](http://www.eclipse.org/) (3.4) Java editor does just this when you generate the method using the source tools. According to Bloch, this is a mistake as it violates the [Liskov substitution principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle). *From Effective Java:* > There is no way to extend an > instantiable class and add a value > component while preserving the equals > contract. Two ways to minimize equality problems are described in the *Classes and Interfaces* chapter: 16. Favour composition over inheritance 17. Design and document for inheritance or else prohibit it --- As far as I can see, the only alternative is to test equality in a form external to the class, and how that would be performed would depend on the design of the type and the context you were trying to use it in. For example, you might define an interface that documents how it was to be compared. In the code below, Service instances might be replaced at runtime with a newer version of the same class - in which case, having different ClassLoaders, equals comparisons would always return false, so overriding equals/hashCode would be redundant. ``` public class Services { private static Map<String, Service> SERVICES = new HashMap<String, Service>(); static interface Service { /** Services with the same name are considered equivalent */ public String getName(); } public static synchronized void installService(Service service) { SERVICES.put(service.getName(), service); } public static synchronized Service lookup(String name) { return SERVICES.get(name); } } ``` --- > "Why would you want to compare two objects?" The obvious example is to test if two Strings are the same (or two [Files](http://java.sun.com/javase/6/docs/api/java/io/File.html), or [URIs](http://java.sun.com/javase/6/docs/api/java/net/URI.html)). For example, what if you wanted to build up a set of files to parse. By definition, the set contains only unique elements. Java's [Set](http://java.sun.com/javase/6/docs/api/java/util/Set.html) type relies on the equals/hashCode methods to enforce uniqueness of its elements.
I don't think it's true that equals should always be overridden. The rule as I understand it is that overriding equals is only meaningful in cases where you're clear on how to define semantically equivalent objects. In that case, you override hashCode() as well so that you don't have objects that you've defined as equivalent returning different hashcodes. If you can't define meaningful equivalence, I don't see the benefit.
What are the alternatives to comparing the equality of two objects?
[ "", "java", "equals", "" ]
3 fields: FirstName, MiddleName, LastName Any field can be null, but I don't want extra spaces. Format should be "First Middle Last", "First Last", "Last", etc.
use a UDF: ``` `Select udfConcatName(First, Middle, Last) from foo` ``` That way all your logic for concatenating names is in one place and once you've gotten it written it's short to call.
``` LTRIM(RTRIM( LTRIM(RTRIM(ISNULL(FirstName, ''))) + ' ' + LTRIM(RTRIM(ISNULL(MiddleName, ''))) + ' ' + LTRIM(ISNULL(LastName, '')) )) ``` NOTE: This won't leave trailing or leading spaces. That's why it's a little bit uglier than other solutions.
What's the shortest TSQL to concatenate a person's name which may contain nulls
[ "", "sql", "sql-server", "t-sql", "" ]
What do I gain by adding a timestamp column called recordversion to a table in ms-sql?
You can use that column to make sure your users don't overwrite data from another user. Lets say user A pulls up record 1 and at the same time user B pulls up record 1. User A edits the record and saves it. 5 minutes later, User B edits the record - but doesn't know about user A's changes. When he saves his changes, you use the recordversion column in your update where clause which will prevent User B from overwriting what User A did. You could detect this invalid condition and throw some kind of data out of date error.
Nothing that I'm aware of, or that Google seems to find quickly. You con't get anything inherent by using that name for a column. Sure, you can create a column and do the record versioning as described in the next response, but there's nothing special about the column name. You could call the column anything you want and do versioning, and you could call any column RecordVersion and nothing special would happen.
What do I gain by adding a timestamp column called recordversion to a table in ms-sql?
[ "", "sql", "sql-server", "t-sql", "timestamp", "" ]
How can I extend a builtin class in python? I would like to add a method to the str class. I've done some searching but all I'm finding is older posts, I'm hoping someone knows of something newer.
Just subclass the type ``` >>> class X(str): ... def my_method(self): ... return int(self) ... >>> s = X("Hi Mom") >>> s.lower() 'hi mom' >>> s.my_method() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in my_method ValueError: invalid literal for int() with base 10: 'Hi Mom' >>> z = X("271828") >>> z.lower() '271828' >>> z.my_method() 271828 ```
One way could be to use the "class reopening" concept (natively existing in Ruby) that can be implemented in Python using a class decorator. An exemple is given in this page: <http://www.ianbicking.org/blog/2007/08/opening-python-classes.html> I quote: I think with class decorators you could do this: ``` @extend(SomeClassThatAlreadyExists) class SomeClassThatAlreadyExists: def some_method(self, blahblahblah): stuff ``` Implemented like this: ``` def extend(class_to_extend): def decorator(extending_class): class_to_extend.__dict__.update(extending_class.__dict__) return class_to_extend return decorator ```
Extending builtin classes in python
[ "", "python", "string", "monkeypatching", "" ]
Has anyone attempted this? Is it possible, and if so, what kind of problems will I run into if I try to accomplish it?
Sure, you can easily subclass controllers in Cake.. and then you'd typically utilize their hook function such as 'beforeFilter', 'afterFilter', etc. to add runtime logic to your controllers.. I typically put at least 1 abstract controller between cakes controller and the final controller that you configure in the route.
If you goal is to share logic between controllers: * add the logic to the AppController to share it with all the controllers in your app. * make a component and add that to $this->components for the controllers you want to share it. Adding additional inheritance between controllers should only be concidered as a last resort, as you have to pay extra attention to how components and helpers are handled. E.g. you must manually merge $this->components & $this->helpers with the AppController and the controller you are inheriting from.
Controller inheritance in Cake PHP?
[ "", "php", "cakephp", "inheritance", "" ]
I have a version resource in my resources in a C++ project which contains version number, copyright and build details. Is there an easy way to access this at run-time to populate my *help/about* dialog as I am currently maintaining seperate const values of this information. Ideally, the solution should work for Windows/CE mobile and earlier versions of Visual C++ (6.0 upwards).
This is an edited version of my original answer. ``` bool GetProductAndVersion(CStringA & strProductName, CStringA & strProductVersion) { // get the filename of the executable containing the version resource TCHAR szFilename[MAX_PATH + 1] = {0}; if (GetModuleFileName(NULL, szFilename, MAX_PATH) == 0) { TRACE("GetModuleFileName failed with error %d\n", GetLastError()); return false; } // allocate a block of memory for the version info DWORD dummy; DWORD dwSize = GetFileVersionInfoSize(szFilename, &dummy); if (dwSize == 0) { TRACE("GetFileVersionInfoSize failed with error %d\n", GetLastError()); return false; } std::vector<BYTE> data(dwSize); // load the version info if (!GetFileVersionInfo(szFilename, NULL, dwSize, &data[0])) { TRACE("GetFileVersionInfo failed with error %d\n", GetLastError()); return false; } // get the name and version strings LPVOID pvProductName = NULL; unsigned int iProductNameLen = 0; LPVOID pvProductVersion = NULL; unsigned int iProductVersionLen = 0; // replace "040904e4" with the language ID of your resources if (!VerQueryValue(&data[0], _T("\\StringFileInfo\\040904e4\\ProductName"), &pvProductName, &iProductNameLen) || !VerQueryValue(&data[0], _T("\\StringFileInfo\\040904e4\\ProductVersion"), &pvProductVersion, &iProductVersionLen)) { TRACE("Can't obtain ProductName and ProductVersion from resources\n"); return false; } strProductName.SetString((LPCSTR)pvProductName, iProductNameLen); strProductVersion.SetString((LPCSTR)pvProductVersion, iProductVersionLen); return true; } ```
To get a language independent result to Mark's answer change : ``` // replace "040904e4" with the language ID of your resources !VerQueryValue(&data[0], _T("\\StringFileInfo\\040904e4\\ProductVersion"), &pvProductVersion, &iProductVersionLen)) { TRACE("Can't obtain ProductName and ProductVersion from resources\n"); return false; } ``` To ``` UINT uiVerLen = 0; VS_FIXEDFILEINFO* pFixedInfo = 0; // pointer to fixed file info structure // get the fixed file info (language-independent) if(VerQueryValue(&data[0], TEXT("\\"), (void**)&pFixedInfo, (UINT *)&uiVerLen) == 0) { return false; } strProductVersion.Format("%u.%u.%u.%u", HIWORD (pFixedInfo->dwProductVersionMS), LOWORD (pFixedInfo->dwProductVersionMS), HIWORD (pFixedInfo->dwProductVersionLS), LOWORD (pFixedInfo->dwProductVersionLS)); ```
How do I read from a version resource in Visual C++
[ "", "c++", "visual-c++", "resources", "version", "" ]
``` public Int64 ReturnDifferenceA() { User[] arrayList; Int64 firstTicks; IList<User> userList; Int64 secondTicks; System.Diagnostics.Stopwatch watch; userList = Enumerable .Range(0, 1000) .Select(currentItem => new User()).ToList(); arrayList = userList.ToArray(); watch = new Stopwatch(); watch.Start(); for (Int32 loopCounter = 0; loopCounter < arrayList.Count(); loopCounter++) { DoThings(arrayList[loopCounter]); } watch.Stop(); firstTicks = watch.ElapsedTicks; watch.Reset(); watch.Start(); for (Int32 loopCounter = 0; loopCounter < arrayList.Count(); loopCounter++) { DoThings(arrayList[loopCounter]); } watch.Stop(); secondTicks = watch.ElapsedTicks; return firstTicks - secondTicks; } ``` As you can see, this is really simple. Create a list of users, force to an array, start a watch, loop the list through and call a method, stop watch. Repeat. Finish up by returning the difference from the first run and the second. Now I'm calling with these: ``` differenceList = Enumerable .Range(0, 50) .Select(currentItem => ReturnDifferenceA()).ToList(); average = differenceList.Average(); differenceListA = Enumerable .Range(0, 50) .Select(currentItem => ReturnDifferenceA()).ToList(); averageA = differenceListA.Average(); differenceListB = Enumerable .Range(0, 50) .Select(currentItem => ReturnDifferenceA()).ToList(); averageB = differenceListB.Average(); ``` Now the fun part is that all averages are positive by a relatively large amount, ranging from 150k to 300k ticks. What I don't get is that I am going through the same list, the same way, with the same method and yet there is such a difference. Is there some kind of caching going on? Another interesting thing is that if I iterate through the list BEFORE the first stop watch section, the averages are around 5k or so.
by the way, using IEnumerable.Count() on an Array is hundreds of times slower than Array.Length... Although this doesn't answer the question at all.
You are running in a high level language with a runtime environment that does a lot of caching and performance optimizations, this is common. Sometimes it is called warming up the virtual machine, or warming up the server (when it is a production application). If something is going to be done repeatedly, then you will frequently notice the first time has a larger measured runtime and the rest should level off to a smaller amount. I do this in MATLAB code, and see that the first time I run a benchmark loop, it takes five seconds, and subsequent times take a fifth of a second. It's a huge difference, because it is an interpreted language that required some form of compiling, but in reality, it does not affect your performance, because the great majority will be 'second time's in any production application.
C#, For Loops, and speed test... Exact same loop faster second time around?
[ "", "c#", "arrays", "foreach", "for-loop", "loops", "" ]
There must be an easy way to do this, but somehow I can wrap my head around it. The best way I can describe what I want is a lambda function for a class. I have a library that expects as an argument an uninstantiated version of a class to work with. It then instantiates the class itself to work on. The problem is that I'd like to be able to dynamically create versions of the class, to pass to the library, but I can't figure out how to do it since the library expects an uninstantiated version. The code below describes the problem: ``` class Double: def run(self,x): return x*2 class Triple: def run(self,x): return x*3 class Multiply: def __init__(self,mult): self.mult = mult def run(self,x): return x*self.mult class Library: def __init__(self,c): self.c = c() def Op(self,val): return self.c.run(val) op1 = Double op2 = Triple #op3 = Multiply(5) lib1 = Library(op1) lib2 = Library(op2) #lib3 = Library(op3) print lib1.Op(2) print lib2.Op(2) #print lib3.Op(2) ``` I can't use the generic Multiply class, because I must instantiate it first which breaks the library "AttributeError: Multiply instance has no **call** method". Without changing the Library class, is there a way I can do this?
There's no need for lambda at all. lambda is just syntatic sugar to define a function and use it at the same time. Just like any lambda call can be replaced with an explicit def, we can solve your problem by creating a real class that meets your needs and returning it. ``` class Double: def run(self,x): return x*2 class Triple: def run(self,x): return x*3 def createMultiplier(n): class Multiply: def run(self,x): return x*n return Multiply class Library: def __init__(self,c): self.c = c() def Op(self,val): return self.c.run(val) op1 = Double op2 = Triple op3 = createMultiplier(5) lib1 = Library(op1) lib2 = Library(op2) lib3 = Library(op3) print lib1.Op(2) print lib2.Op(2) print lib3.Op(2) ```
Does the library really specify that it wants an "uninitialized version" (i.e. a class reference)? It looks to me as if the library actually wants an object factory. In that case, it's acceptable to type: ``` lib3 = Library(lambda: Multiply(5)) ``` To understand how the lambda works, consider the following: ``` Multiply5 = lambda: Multiply(5) assert Multiply5().run(3) == Multiply(5).run(3) ```
Lambda function for classes in python?
[ "", "python", "lambda", "" ]
I'd like to create an XPS document for storing and printing. What is the easiest way to create an XPS document (for example with a simple grid with some data inside) in my program, and to pass it around?
Nothing easy about it. But it can be done. I've got some (sadly, still buggy) sample code and information on my blog for creating the document in memory. Here's some code I whipped up for testing that encapsulates everything (it writes a collection of FixedPages to an XPS document in memory). It includes code for serializing the document to a byte array, but you can skip that part and just return the document: ``` public static byte[] ToXpsDocument(IEnumerable<FixedPage> pages) { // XPS DOCUMENTS MUST BE CREATED ON STA THREADS!!! // Note, this is test code, so I don't care about disposing my memory streams // You'll have to pay more attention to their lifespan. You might have to // serialize the xps document and remove the package from the package store // before disposing the stream in order to prevent throwing exceptions byte[] retval = null; Thread t = new Thread(new ThreadStart(() => { // A memory stream backs our document MemoryStream ms = new MemoryStream(2048); // a package contains all parts of the document Package p = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); // the package store manages packages Uri u = new Uri("pack://TemporaryPackageUri.xps"); PackageStore.AddPackage(u, p); // the document uses our package for storage XpsDocument doc = new XpsDocument(p, CompressionOption.NotCompressed, u.AbsoluteUri); // An xps document is one or more FixedDocuments containing FixedPages FixedDocument fDoc = new FixedDocument(); PageContent pc; foreach (var fp in pages) { // this part of the framework is weak and hopefully will be fixed in 4.0 pc = new PageContent(); ((IAddChild)pc).AddChild(fp); fDoc.Pages.Add(pc); } // we use the writer to write the fixed document to the xps document XpsDocumentWriter writer; writer = XpsDocument.CreateXpsDocumentWriter(doc); // The paginator controls page breaks during the writing process // its important since xps document content does not flow writer.Write(fDoc.DocumentPaginator); // p.Flush(); // this part serializes the doc to a stream so we can get the bytes ms = new MemoryStream(); var writer = new XpsSerializerFactory().CreateSerializerWriter(ms); writer.Write(doc.GetFixedDocumentSequence()); retval = ms.ToArray(); })); // Instantiating WPF controls on a MTA thread throws exceptions t.SetApartmentState(ApartmentState.STA); // adjust as needed t.Priority = ThreadPriority.AboveNormal; t.IsBackground = false; t.Start(); //~five seconds to finish or we bail int milli = 0; while (buffer == null && milli++ < 5000) Thread.Sleep(1); //Ditch the thread if(t.IsAlive) t.Abort(); // If we time out, we return null. return retval; } ``` Note the crappy threading code. You can't do this on MTA threads; if you are on an STA thread you can get rid of that as well.
If you are working in .NET (v2 or later), you can very easily generate a valid XPS document from a WPF visual. For an example, take a look at this blog post of mine: [<http://nixps.blogspot.com/2008/12/wpf-to-pdf.html>](http://nixps.blogspot.com/2008/12/wpf-to-pdf.html) In the example I create a WPF visual and convert it as an XPS file, before doing further processing. If you are not working in .NET, or want more control on the XPS output, then I would advise you to use a library (like the [NiXPS SDK](http://nixps.com/library.html)) for this. It is a lot easier to code for, and a lot less error prone than writing out the XML constructs yourself (and doing proper resource management, etc...).
How to create an XPS document?
[ "", "c#", ".net", "xps", "xpsdocument", "" ]
How do I add a certain number of days to the current date in PHP? I already got the current date with: ``` $today = date('y:m:d'); ``` Just need to add x number of days to it
`php` supports c style date functions. You can add or substract date-periods with English-language style phrases via the `strtotime` function. examples... ``` $Today=date('y:m:d'); // add 3 days to date $NewDate=Date('y:m:d', strtotime('+3 days')); // subtract 3 days from date $NewDate=Date('y:m:d', strtotime('-3 days')); // PHP returns last sunday's date $NewDate=Date('y:m:d', strtotime('Last Sunday')); // One week from last sunday $NewDate=Date('y:m:d', strtotime('+7 days Last Sunday')); ``` or ``` <select id="date_list" class="form-control" style="width:100%;"> <?php $max_dates = 15; $countDates = 0; while ($countDates < $max_dates) { $NewDate=Date('F d, Y', strtotime("+".$countDates." days")); echo "<option>" . $NewDate . "</option>"; $countDates += 1; } ?> ```
a day is 86400 seconds. ``` $tomorrow = date('y:m:d', time() + 86400); ```
Increase days to php current Date()
[ "", "php", "date", "days", "" ]
Say we have normal distribution n(x): mean=0 and \int\_{-a}^{a} n(x) = P. What is the easiest way to compute standard deviation of such distribution? May be there are standard libraries for python or C, that are suitable for that task?
The standard deviation of a mean-zero gaussian distribution with Pr(-a < X < a) = P is ``` a/(sqrt(2)*inverseErf(P)) ``` which is the expression you're looking for, where inverseErf is the inverse of the error function (commonly known as erf). For C, the Gnu Scientific Library (GSL) is a good resource. However it only has erf, not inverseErf, so you'd have to invert it yourself (a simple binary search would do the trick). Alternatively, here's a nice way to approximate erf and inverseErf: <http://homepages.physik.uni-muenchen.de/~Winitzki/erf-approx.pdf> For Python, inverseErf is available as `erfinv` in the SciPy library, so the following gives the standard deviation: ``` a/(math.sqrt(2)*erfinv(P)) ``` PS: There's some kind of bug in Stackoverflow's URL rendering and it wouldn't let me link to GSL above: <http://www.gnu.org/software/gsl>. It also renders wrong when I make the URL above with a pdf a proper link.
If X is normal with mean 0 and standard deviation sigma, it must hold ``` P = Prob[ -a <= X <= a ] = Prob[ -a/sigma <= N <= a/sigma ] = 2 Prob[ 0 <= N <= a/sigma ] = 2 ( Prob[ N <= a/sigma ] - 1/2 ) ``` where N is normal with mean 0 and standard deviation 1. Hence ``` P/2 + 1/2 = Prob[ N <= a/sigma ] = Phi(a/sigma) ``` Where Phi is the cumulative distribution function (cdf) of a normal variable with mean 0 and stddev 1. Now we need the *inverse* normal cdf (or the "percent point function"), which in Python is scipy.stats.norm.ppf(). Sample code: ``` from scipy.stats import norm P = 0.3456 a = 3.0 a_sigma = float(norm.ppf(P/2 + 0.5)) # a/sigma sigma = a/a_sigma # Here is the standard deviation ``` For example, we know that the probability of a N(0,1) variable falling int the interval [-1.1] is ~ 0.682 (the dark blue area in [this figure](http://en.wikipedia.org/wiki/Image:Standard_deviation_diagram.svg)). If you set P = 0.682 and a = 1.0 you obtain sigma ~ 1.0, which is indeed the standard deviation.
Standard C or Python libraries to compute standard deviation of normal distribution
[ "", "python", "c", "algorithm", "math", "probability", "" ]
We are scheduling a task programatically. However, the executable to be scheduled could be installed in a path that has spaces. ie c:\program Files\folder\folder\folder program\program.exe When we provide this path as a parameter to the Tasjk Scheduler it fails to start because it cannot find the executable. It obviously needs to be enclosed in quotes ("). The problem we are having is that even when we enclosed the path in quotes when we pass it as a paramemter (cmd + "\" + path + "\") it still doesnt include the quotes in the path that is used to schedule the task. Anyone have any idea how to force the quotes to be included in the path? **EDIT: Answer to comment:** We had the same idea, and here is the problem. the ~1 format is based on the index of the folder, so if say you had these 3 folders: ``` Program Applications Program Files Program Zips ``` then the path would be: progra~2 Now if you say there are over 10 of those folders, the path could possibly look like: progr~12. Now, not to say this is not a viable solution, but having to count the folders to find the right one and then use the index to build the path is a little cumbersome and not very clean IMO. We are hoping there is a better way. **EDIT 2: Added applicable code snippet** You asked for the code: this is how we build the Args string that we pass to the scheduler: ``` string args = "/CREATE /RU SYSTEM /SC " + taskSchedule + " /MO " + taskModifier + " /SD " + taskStartDate + " /ST " + taskStartTime + " /TN " + taskName + " /TR \"" + taskSource + "\""; ``` where taskSource is the path to the application.
It appears that you're using schtasks.exe - it took me longer to figure that out than to find an answer! More details please! :) I found an answer with [a quick google search](http://tinyurl.com/6z6m8j) Try this code: ``` string args = "/CREATE /RU SYSTEM /SC " + taskSchedule + " /MO " + taskModifier + " /SD " + taskStartDate + " /ST " + taskStartTime + " /TN " + taskName + " /TR \"\\\"" + taskSource + "\"" ``` It's adding a \" to the front of the TR parameter value.
you could replace program files with progra~1 and folder program to folder~1 (1st 6 letters and ~1) to get it to work till someone posts the right answer
Schedule Task with spaces in the path
[ "", "c#", ".net", ".net-2.0", "c#-2.0", "" ]
``` <document.write("<SCR"+"IPT TYPE='text/javascript' SRC='"+"http"+(window.location.protocol.indexOf('https:')==0?'s':'')+"://"+gDomain+"/"+gDcsId+"/wtid.js"+"'><\/SCR"+"IPT>"); ``` I need to escape the string above in order to add the whole thing to a StringBuilder but so far I must be missing something because string termination is not correct...
``` string x = @"<document.write(""<SCR""+""IPT TYPE=""'text/javascript' SRC='""+""http""+(window.location.protocol.indexOf('https:')==0?'s':'')+""://""+gDomain+""/""+gDcsId+""/wtid.js""+""'><\/SCR""+""IPT>"");"; ``` The @ prefix makes escaping simpler. You just have to turn each " into "". You will find your program much easier to maintain if you store the JavaScript in an external file. I assume you're using StringBuilder so you can mix bits of constant script with a few dynamic values? You could write it in a file but put escapes like this for the dynamic values: ``` var fromCSharp = {0}; ``` Then at runtime, load the JS file and give it to string.Format as the format string, along with values to replace each occurrence of {0}, {1}, etc. You only need to load the format string from the file once and keep it cached. Also if the values you are inserting into the JavaScript are themselves string literals, you will need to escape them according to the syntax of JavaScript.
You should try something like this : ``` @"<document.write(""<SCR""+""IPT TYPE='text/javascript' SRC='""+""http""+(window.location.protocol.indexOf('https:')==0?'s':'')+""://""+gDomain+""/""+gDcsId+""/wtid.js""+""'><\/SCR""+""IPT>"");" ``` When prefixing a string literal with @, the only escaping needed is to double the " caracter. Hope this help.
C# StringBuilder - how to escape this string:
[ "", "c#", "stringbuilder", "" ]
I'm trying to change assembly binding (from one version to another) dynamically. I've tried this code but it doesn't work: ``` Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ConfigurationSection assemblyBindingSection = config.Sections["assemblyBinding"]; assemblyBindingSection.SectionInformation.ConfigSource = "bindingConf.xml"; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("assemblyBinding"); ``` with `bindingConf.xml` containing the assemblyBinding section configuration. So can a change this section at runtime? how to do it? What alternatives do I have?
The best way I've found to dynamically bind to a different version of an assembly is to hook the `AppDomain.AssemblyResolve` event. This event is fired whenever the runtime is unable to locate the exact assembly that the application was linked against, and it allows you to provide another assembly, that you load yourself, in its place (as long as it is compatible). For example, you can put in a static constructor on your application's main class that hooks the event like this: ``` using System.Reflection; static Program() { AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs e) { AssemblyName requestedName = new AssemblyName(e.Name); if (requestedName.Name == "AssemblyNameToRedirect") { // Put code here to load whatever version of the assembly you actually have return Assembly.LoadFrom("RedirectedAssembly.DLL"); } else { return null; } }; } ``` This method avoids the need to deal with the assembly bindings in configuration files and is a bit more flexible in terms of what you can do with it.
I love Eric's answer. It's a lifesaver when trying to use the new buggy NuGet PackageReference model with a Web app. The problem is that you can have msbuild automatically generate the bindings, however, they generate the bindings to Assembly.dll.config, and not to web.config. So this workaround is great. I've modified Eric's code a bit to make it more generic and work with an ASP.Net Core app: ``` AppDomain.CurrentDomain.AssemblyResolve += delegate (object sender2, ResolveEventArgs e2) { var requestedNameAssembly = new AssemblyName(e2.Name); var requestedName = requestedNameAssembly.Name; if (requestedName.EndsWith(".resources")) return null; var binFolder = System.Web.Hosting.HostingEnvironment.MapPath("~/bin"); var fullPath = Path.Combine(binFolder, requestedName) + ".dll"; if (File.Exists(fullPath)) { return Assembly.LoadFrom(fullPath); } return null; }; ```
how to update assemblyBinding section in config file at runtime?
[ "", "c#", ".net", "configuration", "" ]
What is this "Execute Around" idiom (or similar) I've been hearing about? Why might I use it, and why might I not want to use it?
Basically it's the pattern where you write a method to do things which are always required, e.g. resource allocation and clean-up, and make the caller pass in "what we want to do with the resource". For example: ``` public interface InputStreamAction { void useStream(InputStream stream) throws IOException; } // Somewhere else public void executeWithFile(String filename, InputStreamAction action) throws IOException { InputStream stream = new FileInputStream(filename); try { action.useStream(stream); } finally { stream.close(); } } // Calling it executeWithFile("filename.txt", new InputStreamAction() { public void useStream(InputStream stream) throws IOException { // Code to use the stream goes here } }); // Calling it with Java 8 Lambda Expression: executeWithFile("filename.txt", s -> System.out.println(s.read())); // Or with Java 8 Method reference: executeWithFile("filename.txt", ClassName::methodName); ``` The calling code doesn't need to worry about the open/clean-up side - it will be taken care of by `executeWithFile`. This was frankly painful in Java because closures were so wordy, starting with Java 8 lambda expressions can be implemented like in many other languages (e.g. C# lambda expressions, or Groovy), and this special case is handled since Java 7 with `try-with-resources` and `AutoClosable` streams. Although "allocate and clean-up" is the typical example given, there are plenty of other possible examples - transaction handling, logging, executing some code with more privileges etc. It's basically a bit like the [template method pattern](http://en.wikipedia.org/wiki/Template_method_pattern) but without inheritance.
The Execute Around idiom is used when you find yourself having to do something like this: ``` //... chunk of init/preparation code ... task A //... chunk of cleanup/finishing code ... //... chunk of identical init/preparation code ... task B //... chunk of identical cleanup/finishing code ... //... chunk of identical init/preparation code ... task C //... chunk of identical cleanup/finishing code ... //... and so on. ``` In order to avoid repeating all of this redundant code that is always executed "around" your actual tasks, you would create a class that takes care of it automatically: ``` //pseudo-code: class DoTask() { do(task T) { // .. chunk of prep code // execute task T // .. chunk of cleanup code } }; DoTask.do(task A) DoTask.do(task B) DoTask.do(task C) ``` This idiom moves all of the complicated redundant code into one place, and leaves your main program much more readable (and maintainable!) Take a look at [this post](http://brandonbyars.com/blog/articles/2007/06/11/c-execute-around-method) for a C# example, and [this article](http://brandonbyars.com/blog/articles/2007/06/11/c-execute-around-method) for a C++ example.
What is the "Execute Around" idiom?
[ "", "java", "language-agnostic", "design-patterns", "idioms", "" ]
When an item is clicked in the checkedlistbox, it gets highlighted. How can I prevent this highlighting effect? I can hook into the SelectedIndexChanged event and clear the selection, but the highlighting still happens and you see a blip. In fact, if you hold down the mouse click, never releasing it after you clicked on the checkbox area, the selection remains highlighted until you release the mouse button. I basically want to get rid of this highlighting effect altogether.
this will do it apart from you still get the dotted line bit. ``` this.checkedListBox1.SelectionMode = System.Windows.Forms.SelectionMode.None; ``` although now you can't click the check boxes... so you'll have to do something like so: ``` private void checkedListBox1_Click(object sender, EventArgs e) { for (int i = 0; i < checkedListBox1.Items.Count; i++) { if (checkedListBox1.GetItemRectangle(i).Contains(checkedListBox1.PointToClient(MousePosition))) { switch (checkedListBox1.GetItemCheckState(i)) { case CheckState.Checked: checkedListBox1.SetItemCheckState(i, CheckState.Unchecked); break; case CheckState.Indeterminate: case CheckState.Unchecked: checkedListBox1.SetItemCheckState(i, CheckState.Checked); break; } } } } ``` if all that isn't what your after.. you can always just make your own one. its a fairly simple control.
Use the following: ``` private void checkedListBox1__SelectedIndexChanged(object sender, EventArgs e) { checkedListBox1.ClearSelected(); } ```
How to get rid of checkedlistbox selection highlighting effect?
[ "", "c#", "winforms", "checkedlistbox", "" ]
I'm trying to open a folder in explorer with a file selected. The following code produces a file not found exception: ``` System.Diagnostics.Process.Start( "explorer.exe /select," + listView1.SelectedItems[0].SubItems[1].Text + "\\" + listView1.SelectedItems[0].Text); ``` How can I get this command to execute in C#?
Use [this method](http://msdn.microsoft.com/en-us/library/h6ak8zt5.aspx): ``` Process.Start(String, String) ``` First argument is an application (explorer.exe), second method argument are arguments of the application you run. For example: in CMD: ``` explorer.exe -p ``` in C#: ``` Process.Start("explorer.exe", "-p") ```
``` // suppose that we have a test.txt at E:\ string filePath = @"E:\test.txt"; if (!File.Exists(filePath)) { return; } // combine the arguments together // it doesn't matter if there is a space after ',' string argument = "/select, \"" + filePath +"\""; System.Diagnostics.Process.Start("explorer.exe", argument); ```
Opening a folder in explorer and selecting a file
[ "", "c#", "explorer", "" ]
I'm adding avatars to a forum engine I'm designing, and I'm debating whether to do something simple (forum image is named .png) and use PHP to check if the file exists before displaying it, or to do something a bit more complicated (but not much) and use a database field to contain the name of the image to show. I'd much rather go with the file\_exists() method personally, as that gives me an easy way to fall back to a "default" avatar if the current one doesn't exist (yet), and its simple to implement code wise. However, I'm worried about performance, since this will be run once per user shown per pageload on the forum read pages. So I'd like to know, does the file\_exists() function in PHP cause any major slowdowns that would cause significant performance hits in high traffic conditions? If not, great. If it does, what is your opinion on alternatives for keeping track of a user-uploaded image? Thanks! PS: The code differences I can see are that the file checking versions lets the files do the talking, while the database form trusts that the database is accurate and doesn't bother to check. (its just a url that gets passed to the browser of course.)
As well as what the other posters have said, the result of file\_exists() is automatically cached by PHP to improve performance. However, if you're already reading user info from the database, you may as well store the information in there. If the user is only allowed one avatar, you could just store a single bit in a column for "has avatar" (1/0), and then have the filename the same as the user id, and use something like `SELECT CONCAT(IF(has_avatar, id, 'default'), '.png') AS avatar FROM users` You could also consider storing the actual image in the database as a BLOB. Put it in its own table rather than attaching it as a column to the user table. This has the benefit that it makes your forum very easy to back up - you just export the database.
Since your web server will already be doing a lot of (the equivalent of) file\_exists() operations in the process of showing your web page, one more run by your script probably won't have a measurable impact. The web server will probably do at least: * one for each subdirectory of the web root (to check existence and for symlinks) * one to check for a .htaccess file for each subdirectory of the web root * one for the existence of your script This is not considering more of them that PHP might do itself.
Is file_exist() in PHP a very expensive operation?
[ "", "php", "performance", "" ]
Is a string literal in C++ created in static memory and destroyed only when the program exits?
Where it's created is an implementation decision by the compiler writer, really. Most likely, string literals will be stored in read-only segments of memory since they never change. In the old compiler days, you used to have static data like these literals, and global but changeable data. These were stored in the TEXT (code) segment and DATA (initialised data) segment. Even when you have code like `char *x = "hello";`, the `hello` string itself is stored in read-only memory while the variable `x` is on the stack (or elsewhere in writeable memory if it's a global). `x` just gets set to the address of the `hello` string. This allows all sorts of tricky things like string folding, so that "invalid option" (0x1000) and "valid option" (0x1002) can use the same memory block as follows: ``` +-> plus:0 1 2 3 4 5 6 7 8 9 A B C D E | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+----+ 0x1000 | i | n | v | a | l | i | d | | o | p | t | i | o | n | \0 | +---+---+---+---+---+---+---+---+---+---+---+---+---+---+----+ ``` Keep in mind I don't mean read-only memory in terms of ROM, just memory that's dedicated to storing unchangeable stuff (which may be marked really read-only by the OS). They're also never destroyed until `main()` exits.
Yes, string literals are valid for the entire duration of the program, even during the destruction of static objects. 2.13.4/1 in the Standard says > An ordinary string literal has type "array of n const char" and static storage duration. The Standard says of 'static storage duration' in 3.7.1/1: > The storage for these objects shall last for the duration of the program.
Is a string literal in С++ created in static memory?
[ "", "c++", "string", "char", "" ]
I'm trying to use reflection to get a property from a class. Here is some sample code of what I'm seeing: ``` using System.Reflection; namespace ConsoleApplication { class Program { static void Main(string[] args) { PropertyInfo[] tmp2 = typeof(TestClass).GetProperties(); PropertyInfo test = typeof(TestClass).GetProperty( "TestProp", BindingFlags.Public | BindingFlags.NonPublic); } } public class TestClass { public Int32 TestProp { get; set; } } } ``` When I trace through this, this is what I see: * When I fetch all properties using `GetProperties()`, the resulting array has one entry, for property `TestProp`. * When I try to fetch `TestProp` using `GetProperty()`, I get null back. I'm a little stumped; I haven't been able to find anything in the MSDN regarding `GetProperty()` to explain this result to me. Any help? EDIT: If I add `BindingFlags.Instance` to the `GetProperties()` call, no properties are found, period. This is more consistent, and leads me to believe that `TestProp` is not considered an instance property for some reason. Why would that be? What do I need to do to the class for this property to be considered an instance property?
Add `BindingFlags.Instance` to the `GetProperty` call. EDIT: In response to comment... The following code returns the property. Note: It's a good idea to actually make your property do something before you try to retrieve it (VS2005) :) ``` using System.Reflection; namespace ConsoleApplication { class Program { static void Main(string[] args) { PropertyInfo[] tmp2 = typeof(TestClass).GetProperties(); PropertyInfo test = typeof(TestClass).GetProperty( "TestProp", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); Console.WriteLine(test.Name); } } public class TestClass { public Int32 TestProp { get { return 0; } set { } } } } ```
Try to add the following tag: ``` System.Reflection.BindingFlags.Instance ``` **EDIT:** This works (at least to me) ``` PropertyInfo test = typeof(TestClass).GetProperty("TestProp", BindingFlags.Public | BindingFlags.Instance); Console.WriteLine(test.Name); ```
Why does GetProperty fail to find it?
[ "", "c#", "reflection", "properties", "" ]
I need to change an element's ID using jQuery. Apparently these don't work: ``` jQuery(this).prev("li").attr("id")="newid" jQuery(this).prev("li")="newid" ``` I found out that I can make it happen with the following code: ``` jQuery(this).prev("li")show(function() { this.id="newid"; }); ``` But that doesn't seem right to me. There must be a better way, no? Also, in case there isn't, what other method can I use instead of show/hide or other effects? Obviously I don't want to show/hide or affect the element every time, just to change its ID. (Yep, I'm a jQuery newbie.) **Edit** I can't use classes in this case, I must use IDs.
Your syntax is incorrect, you should pass the value as the second parameter: ``` jQuery(this).prev("li").attr("id","newId"); ```
A PREFERRED OPTION over `.attr` is to use `.prop` like so: ``` $(this).prev('li').prop('id', 'newId'); ``` `.attr` retrieves the element's attribute whereas `.prop` retrieves the property that the attribute references (i.e. what you're *actually* intending to modify)
Changing an element's ID with jQuery
[ "", "javascript", "jquery", "" ]
A few years ago, it was proven that [PRIMES is in P](http://www.cse.iitk.ac.in/~manindra/algebra/primality_v6.pdf). Are there any algorithms implementing [their primality test](http://en.wikipedia.org/wiki/AKS_primality_test) in Python? I wanted to run some benchmarks with a naive generator and see for myself how fast it is. I'd implement it myself, but I don't understand the paper enough yet to do that.
Quick answer: no, the AKS test is not the fastest way to test primality. There are much *much* faster primality tests that either assume the (generalized) Riemann hypothesis and/or are randomized. (E.g. [Miller-Rabin](http://en.wikipedia.org/wiki/Miller-Rabin_primality_test) is fast and simple to implement.) The real breakthrough of the paper was theoretical, proving that a *deterministic* polynomial-time algorithm exists for testing primality, without assuming the GRH or other unproved conjectures. That said, if you want to understand and implement it, [Scott Aaronson's short article](http://www.scottaaronson.com/writings/prime.pdf) might help. It doesn't go into all the details, but you can start at page 10 of 12, and it gives enough. :-) There is also a [list of implementations](http://fatphil.org/maths/AKS/#Implementations) (mostly in C++) here. Also, for optimization and improvements (by several orders of magnitude), you might want to look at [this report](http://www.southerington.com/souther/projects/aks/RP-3_report.pdf), or (older) [Crandall and Papadopoulos's report](http://developer.apple.com/hardware/ve/pdf/aks3.pdf), or (older still) [Daniel J Bernstein's report](http://cr.yp.to/papers/aks.pdf). All of them have fairly detailed pseudo-code that lends itself well to implementation.
I simplified using Binomial Expansion, ``` from math import comb def AKS(n): if (n ^ 1 == n + 1): # check if it's even if n == 2: return True return False for i in range(3,n//2): if comb(n,i)%n != 0: # check if any coefficient isn't divisible by n return False return True ```
AKS Primes algorithm in Python
[ "", "python", "algorithm", "primes", "" ]
Is there a way to be **sure** that a page is coming from cache on a production server and on the development server as well? The solution **shouldn't** involve caching middleware because not every project uses them. Though the solution itself might **be** a middleware. Just checking if the data is stale is not a very safe testing method IMO.
We do a lot of component caching and not all of them are updated at the same time. So we set host and timestamp values in a universally included context processor. At the top of each template fragment we stick in: ``` <!-- component_name {{host}} {{timestamp}} --> ``` The component\_name just makes it easy to do a View Source and search for that string. All of our views that are object-detail pages define a context variable "page\_object" and we have this at the top of the base.html template master: ``` <!-- {{page_object.class_id}} @ {{timestamp}} --> ``` class\_id() is a method from a super class used by all of our primary content classes. It is just: ``` def class_id(self): "%s.%s.%s" % (self.__class__._meta.app_label, self.__class__.__name__, self.id) ``` If you load a page and any of the timestamps are more than few seconds old, it's a pretty good bet that the component was cached.
Peter Rowells suggestion works well, but you don't need a custom template context processor for timestamps. You can simply use the template tag: ``` <!-- {% now "jS F Y H:i" %} --> ```
How to test django caching?
[ "", "python", "django", "caching", "django-cache", "" ]
It is my understanding that I can test that a method call will occur if I call a higher level method, i.e.: ``` public abstract class SomeClass() { public void SomeMehod() { SomeOtherMethod(); } internal abstract void SomeOtherMethod(); } ``` I want to test that if I call `SomeMethod()` then I expect that `SomeOtherMethod()` will be called. Am I right in thinking this sort of test is available in a mocking framework?
You can see if a method in something you have mocked has been called by using Verify, e.g.: ``` static void Main(string[] args) { Mock<ITest> mock = new Mock<ITest>(); ClassBeingTested testedClass = new ClassBeingTested(); testedClass.WorkMethod(mock.Object); mock.Verify(m => m.MethodToCheckIfCalled()); } class ClassBeingTested { public void WorkMethod(ITest test) { //test.MethodToCheckIfCalled(); } } public interface ITest { void MethodToCheckIfCalled(); } ``` If the line is left commented it will throw a MockException when you call Verify. If it is uncommented it will pass.
No, mock testing assumes you are using certain testable design patterns, one of which is injection. In your case you would be testing `SomeClass.SomeMethod` and `SomeOtherMethod` must be implemented in another entity which needs to be interfaced. Your `Someclass` constructor would look like `New(ISomeOtherClass)`. Then you would mock the `ISomeOtherClass` and set expectation on its `SomeOtherMethod` to be called and verify the expectation.
Using Moq to determine if a method is called
[ "", "c#", ".net", "unit-testing", "mocking", "moq", "" ]
My table has a large number of columns. I have a command to copy some data - think of it as cloning a product - but as the columns may change in the future, I would like to only select everything from the table and only change the value of one column without having to refer to the rest. Eg instead of: ``` INSERT INTO MYTABLE ( SELECT NEW_ID, COLUMN_1, COLUMN_2, COLUMN_3, etc FROM MYTABLE) ``` I would like something resembling ``` INSERT INTO MYTABLE ( SELECT * {update this, set ID = NEW_ID} FROM MYTABLE) ``` Is there a simple way to do this? This is a DB2 database on an iSeries, but answers for any platform are welcome.
You could do this: ``` create table mytable_copy as select * from mytable; update mytable_copy set id=new_id; insert into mytable select * from mytable_copy; drop table mytable_copy; ```
I don't think this is doable entirely within SQL without going to the trouble of creating a temp table. Doing it in memory should be much faster. Beware if you go the temporary table route that you must choose a unique name for your table for each function invocation to avoid the race condition where your code runs twice at the same time and mangles two rows of data into one temp table. I don't know what kind of language you're using but it should be possible to obtain a list of fields in your program. I would do it like this: ``` array_of_field_names = conn->get_field__list; array_of_row_values = conn->execute ("SELECT... "); array_of_row_values ["ID"] = new_id_value insert_query_string = "construct insert query string from list of field names and values"; conn->execute (insert_query_string); ``` Then you can encapsulate that as a function and just call it specifying table, old id and new id and it'd work it's magic. In Perl code the following snippet would do: ``` $table_name = "MYTABLE"; $field_name = "ID"; $existing_field_value = "100"; $new_field_value = "101"; my $q = $dbh->prepare ("SELECT * FROM $table_name WHERE $field_name=?"); $q->execute ($existing_field_value); my $rowdata = $q->fetchrow_hashref; # includes field names $rowdata->{$field_name} = $new_field_value; my $insq = $dbh->prepare ("INSERT INTO $table_name (" . join (", ", keys %$rowdata) . ") VALUES (" . join (", ", map { "?" } keys %$rowdata) . ");"; $insq->execute (values %$rowdata); ``` Hope this helps.
How can I copy a record, changing only the id?
[ "", "sql", "db2", "" ]
I'm playing with an embedded Linux device and looking for a way to get my application code to communicate with a web interface. I need to show some status information from the application on the devices web interface and also would like to have a way to inform the application of any user actions like uploaded files etc. PHP-seems to be a good way to make the interface, but the communication part is harder. I have found the following options, but not sure which would be the easiest and most convenient to use. **Sockets.** Have to enable sockets for the PHP first to try this. Don't know if enabling will take much more space. **Database.** Seems like an overkill solution. **Shared file.** Seems like a lot of work. **Named pipes.** Tried this with some success, but not sure if there will be problems with for example on simultaneous page loads. Maybe sockets are easier? What would be the best way to go? Is there something I'm totally missing? How is this done in those numerous commercial Linux based network switches?
I recently did something very similar using sockets, and it worked really well. I had a Java application that communicates with the device, which listened on a server socket, and the PHP application was the client. So in your case, the PHP client would initialize the connection, and then the server can reply with the status of the device. There's plenty of tutorials on how to do client/server socket communication with most languages, so it shouldn't take too long to figure out.
What kind of device is it? If you work with something like a shared file, how will the device be updated? How will named pipes run into concurrency problems that sockets will avoid? In terms of communication from the device to PHP, a file seems perfect. PHP can use something basic like file\_get\_contents(), the device can just write to the file. If you're worried about the moment in time the file is updated to a quick length check. In terms of PHP informing the device of what to do, I'm also leaning towards files. Have the device watch a directory, and have the script create a file there with something like file\_put\_contents($path . uniqid(), $command); That way should two scripts run at the exact sime time, you simply have two files for the device to work with.
Communication between PHP and application
[ "", "php", "linux", "embedded", "" ]
A few years ago client Java was unsuitable for web development because a remarkable part of web users did not have Java installed. ( I don't remember exact numbers, more than 10%). Now I see the Google Analytics stats for a big site and it tells that >98% of users have Java installed. Is these stats very biased by Javascript usage? As I understand Google Analytics measure only users that has Javascript. Is the picture similar on other big sites? **Does client Java have really "stopper" drawbacks compared to Flash?** EDIT: I mean java applets mainly, java WebStart seems to be not suitable for average user. I mention Javascript only to describe the way Google Analytics works.
When I wrote my diploma project, I had to choose between Flash and Java Applets. Here are some pros and cons: Java Applets: * [plus] you program in Java, which is mature and stable * [plus] you can use the Java GUI frameworks that pack a lot of punch * [minus] the first time the user hits the page with the applet, the JVM must be initialized and this can take up to a few minutes even on a fast computer * [minus] Applets are not meant to be used as animation media; sure, you can do stuff, but it is like programming in C - you do everything from scratch example: i needed to show a data packet as it moved between two routers. The packet must be a control of some sort, like a button or smth. This animation can be defined in 1 line of code in Flash, where all objects derive from some base object that can be animated. I could not find a suitable solution in Java. Flash: * [plus] really really focused on animations; * [plus] ActionScript is actually an OO language * [minus] ActionScript is sloppy, bughish and has only a few supporters. If you are stuck, be prepared to search obscure Japanese forums for solutions * [minus] ActionSCript may be OO, but it lacks a lot of features, like Enums, fully fledged interfaces, threads (!!!!) etc. * [minus] Flash was designed to be used by non-tech people - they just use the authoring tool; I wrote code for everything and it worked, but it was a pain. My conclusion: I eagerly await a programming paradigm for animations and rich client interfaces. ps: Silverlight seems to be a disappointment so far, maybe Microsoft will inject some $ into it.
Mmm, Java seems to be better supported than I though, I searched some stats and found between 92 and 96% of browsers support Java (ie. it is enabled enough to detect it! although I guess lot of Java detection algorithms use JavaScript to detect & report - as you point out - but JS support is very good too anyway, even more in our Web 2.0 era). Adobe boasts better support, but overall the difference is rather marginal. Anyway, somebody really wanting to see/use the application will activate/upgrade/download the needed engine. Now, we have to see what JRE is supported! Alas, I didn't found any stat for that. There, Adobe have an edge: not everybody have Flash 9 or 10, but upgrading is quite fast. While downloading and installing a new JRE is quite a bigger task... Of course, you can target the historical lowest common denominator Java 1.1, or more realistically Java 2 (1.4), but it is still frustrating not to be able to use all 1.6 features... I have seen some people complaining that Java applets crashes their browser (apparently on Unix systems) but it is more an issue with a minor number of browsers/systems than anything else. And as pointed out, startup time of a Java applet is quite longer than for Flash (although some big Flash games are slow to load too). Now, I have seen a number of [Processing](http://processing.org/ "Cover") applets, like the notorious [Webpages as graphs](http://www.aharef.info/static/htmlgraph/?url=http%3A%2F%2Fstackoverflow.com%2Fabout "Webpages as graphs - an HTML DOM Visualizer Applet"), most of them load quickly: lot of the power is already on the hard disk of the user, in the extensive Java library. Processing generates quite lightweight jars, while lot of Flash applets must include foreign libraries... or reinvent the wheel!
Client Java vs (Adobe) Flash for web applications, what to choose and when
[ "", "java", "apache-flex", "flash", "client-side", "" ]
I recently wrote a class for an assignment in which I had to store names in an ArrayList (in java). I initialized the ArrayList as an instance variable `private ArrayList<String> names`. Later when I checked my work against the solution, I noticed that they had initialized their ArrayList in the `run()` method instead. I thought about this for a bit and I kind of feel it might be a matter of taste, but in general how does one choose in situations like this? Does one take up less memory or something? PS I like the instance variables in Ruby that start with an @ symbol: they are lovelier. (meta-question: What would be a better title for this question?)
In the words of the great Knuth "Premature optimization is the root of all evil". Just worry that your program functions correctly and that it does not have bugs. This is far more important than an obscure optimization that will be hard to debug later on. But to answer your question - if you initialize in the class member, the memory will be allocated the first time a mention of your class is done in the code (i.e. when you call a method from it). If you initialize in a method, the memory allocation occurs later, when you call this specific method. So it is only a question of initializing later... this is called lazy initialization in the industry.
## Initialization As a rule of thumb, try to initialize variables when they are declared. If the value of a variable is intended never to change, make that explicit with use of the `final` keyword. This helps you reason about the correctness of your code, and while I'm not aware of compiler or JVM optimizations that recognize the `final` keyword, they would certainly be possible. Of course, there are exceptions to this rule. For example, a variable may by be assigned in an if–else or a switch. In a case like that, a "blank" declaration (one with no initialization) is preferable to an initialization that is guaranteed to be overwritten before the dummy value is read. ``` /* DON'T DO THIS! */ Color color = null; switch(colorCode) { case RED: color = new Color("crimson"); break; case GREEN: color = new Color("lime"); break; case BLUE: color = new Color("azure"); break; } color.fill(widget); ``` Now you have a `NullPointerException` if an unrecognized color code is presented. It would be better not to assign the meaningless `null`. The compiler would produce an error at the `color.fill()` call, because it would detect that you might not have initialized `color`. In order to answer your question in this case, I'd have to see the code in question. If the solution initialized it inside the `run()` method, it must have been used either as temporary storage, or as a way to "return" the results of the task. If the collection is used as temporary storage, and isn't accessible outside of the method, it should be declared as a local variable, not an instance variable, and most likely, should be initialized where it's declared in the method. ## Concurrency Issues For a beginning programming course, your instructor probably wasn't trying to confront you with the complexities of concurrent programming—although if that's the case, I'm not sure why you were using a `Thread`. But, with current trends in CPU design, anyone who is learning to program needs to have a firm grasp on concurrency. I'll try to delve a little deeper here. Returning results from a thread's `run` method is a bit tricky. This method is the [Runnable](http://java.sun.com/javase/6/docs/api/java/lang/Runnable.html) interface, and there's nothing stopping multiple threads from executing the `run` method of a single instance. The resulting concurrency issues are part of the motivation behind the [Callable](http://java.sun.com/javase/6/docs/api/java/util/concurrent/Callable.html) interface introduced in Java 5. It's much like `Runnable`, but can return a result in a thread-safe manner, and throw an `Exception` if the task can't be executed. It's a bit of a digression, but if you are curious, consider the following example: ``` class Oops extends Thread { /* Note that thread implements "Runnable" */ private int counter = 0; private Collection<Integer> state = ...; public void run() { state.add(counter); counter++; } public static void main(String... argv) throws Exception { Oops oops = new Oops(); oops.start(); Thread t2 = new Thread(oops); /* Now pass the same Runnable to a new Thread. */ t2.start(); /* Execute the "run" method of the same instance again. */ ... } } ``` By the end of the the `main` method you pretty much have no idea what the "state" of the `Collection` is. Two threads are working on it concurrently, and we haven't specified whether the collection is safe for concurrent use. If we initialize it inside the thread, at least we can say that eventually, `state` will contain one element, but we can't say whether it's 0 or 1.
Choosing when to instantiate classes
[ "", "java", "variables", "performance", "" ]
Here is the scenario. 2 web servers in two separate locations having two mysql databases with identical tables. The data within the tables is also expected to be identical in real time. Here is the problem. if a user in either location simultaneously enters a new record into identical tables, as illustrated in the two first tables below, where the third record in each table has been entered simultaneously by the different people. The data in the tables is no longer identical. Which is the best way to maintain that the data remains identical in real time as illustrated in the third table below regardless of where the updates take place? That way in the illustrations below instead of ending up with 3 rows in each table, the new records are replicated bi-directionally and they are inserted in both tables to create 2 identical tables again with 4 columns this time? ``` Server A in Location A ============== Table Names | ID| NAME | |-----------| | 1 | Tom | | 2 | Scott | |-----------| | 3 | John | |-----------| Server B in Location B ============== Table Names | ID| NAME | |-----------| | 1 | Tom | | 2 | Scott | |-----------| | 3 | Peter | |-----------| Expected Scenario =========== Table Names | ID| NAME | |-----------| | 1 | Tom | | 2 | Scott | | 3 | Peter | | 4 | John | |-----------| ```
There isn't much performance to be gained from replicating your database on two masters. However, there is a nifty bit of failover if you code your application correct. Master-Master setup is essentially the same as the Slave-Master setup but has both Slaves started and an important change to your config files on each box. Master MySQL 1: ``` auto_increment_increment = 2 auto_increment_offset = 1 ``` Master MySQL 2: ``` auto_increment_increment = 2 auto_increment_offset = 2 ``` These two parameters ensure that when two servers are fighting over a primary key for some reason, they do not duplicate and kill the replication. Instead of incrementing by 1, any auto-increment field will by default increment by 2. On one box it will start offset from 1 and run the sequence 1 3 5 7 9 11 13 etc. On the second box it will start offset at 2 and run along 2 4 6 8 10 12 etc. From current testing, the auto-increment appears to take the next free number, not one that has left before. E.g. If server 1 inserts the first 3 records (1 3 and 5) when Server 2 inserts the 4th, it will be given the key of 6 (not 2, which is left unused). Once you've set that up, start both of them up as Slaves. Then to check both are working ok, connect to both machines and perform the command `SHOW SLAVE STATUS` and you should note that both `Slave_IO_Running` and `Slave_SQL_Running` should both say “YES” on each box. Then, of course, create a few records in a table and ensure one box is only inserting odd numbered primary keys and the other is only incrementing even numbered ones. Then do all the tests to ensure that you can perform all the standard applications on each box with it replicating to the other. It's relatively simple once it's going. But as has been mentioned, MySQL does discourage it and advise that you ensure you are mindful of this functionality when writing your application code. **Edit:** I suppose it's theoretically possible to add more masters if you ensure that the offsets are correct and so on. You might more realistically though, add some additional slaves.
MySQL does not support synchronous replication, however, even if it did, you would probably not want to use it (can't take the performance hit of waiting for the other server to sync on every transaction commit). You will have to consider more appropriate architectural solutions to it - there are third party products which will do a merge and resolve conflicts in a predetermined way - this is the only way really. Expecting your architecture to function in this way is naive - there is no "easy fix" for any database, not just MySQL.
Which is the best way to bi-directionally synchronize dynamic data in real time using mysql
[ "", "php", "mysql", "database", "synchronization", "data-synchronization", "" ]
I have created a form to add a user to a database and make user available for login. Now I have two password fields (the second is for validation of the first). How can I add a validator for this kind of validation to zend\_form? This is my code for the two password fields: ``` $password = new Zend_Form_Element_Password('password', array( 'validators'=> array( 'Alnum', array('StringLength', array(6,20)) ), 'filters' => array('StringTrim'), 'label' => 'Wachtwoord:' )); $password->addFilter(new Ivo_Filters_Sha1Filter()); $password2 = new Zend_Form_Element_Password('password', array( 'validators'=> array( 'Alnum', array('StringLength', array(6,20)) ), 'filters' => array('StringTrim'), 'required' => true, 'label' => 'Wachtwoord:' )); $password2->addFilter(new Ivo_Filters_Sha1Filter()); ```
When I was looking for the same, I found this very well working generic Validator for Identical Fields. I don't find it now so I just post the code... ``` <?php class Zend_Validate_IdenticalField extends Zend_Validate_Abstract { const NOT_MATCH = 'notMatch'; const MISSING_FIELD_NAME = 'missingFieldName'; const INVALID_FIELD_NAME = 'invalidFieldName'; /** * @var array */ protected $_messageTemplates = array( self::MISSING_FIELD_NAME => 'DEVELOPMENT ERROR: Field name to match against was not provided.', self::INVALID_FIELD_NAME => 'DEVELOPMENT ERROR: The field "%fieldName%" was not provided to match against.', self::NOT_MATCH => 'Does not match %fieldTitle%.' ); /** * @var array */ protected $_messageVariables = array( 'fieldName' => '_fieldName', 'fieldTitle' => '_fieldTitle' ); /** * Name of the field as it appear in the $context array. * * @var string */ protected $_fieldName; /** * Title of the field to display in an error message. * * If evaluates to false then will be set to $this->_fieldName. * * @var string */ protected $_fieldTitle; /** * Sets validator options * * @param string $fieldName * @param string $fieldTitle * @return void */ public function __construct($fieldName, $fieldTitle = null) { $this->setFieldName($fieldName); $this->setFieldTitle($fieldTitle); } /** * Returns the field name. * * @return string */ public function getFieldName() { return $this->_fieldName; } /** * Sets the field name. * * @param string $fieldName * @return Zend_Validate_IdenticalField Provides a fluent interface */ public function setFieldName($fieldName) { $this->_fieldName = $fieldName; return $this; } /** * Returns the field title. * * @return integer */ public function getFieldTitle() { return $this->_fieldTitle; } /** * Sets the field title. * * @param string:null $fieldTitle * @return Zend_Validate_IdenticalField Provides a fluent interface */ public function setFieldTitle($fieldTitle = null) { $this->_fieldTitle = $fieldTitle ? $fieldTitle : $this->_fieldName; return $this; } /** * Defined by Zend_Validate_Interface * * Returns true if and only if a field name has been set, the field name is available in the * context, and the value of that field name matches the provided value. * * @param string $value * * @return boolean */ public function isValid($value, $context = null) { $this->_setValue($value); $field = $this->getFieldName(); if (empty($field)) { $this->_error(self::MISSING_FIELD_NAME); return false; } elseif (!isset($context[$field])) { $this->_error(self::INVALID_FIELD_NAME); return false; } elseif (is_array($context)) { if ($value == $context[$field]) { return true; } } elseif (is_string($context) && ($value == $context)) { return true; } $this->_error(self::NOT_MATCH); return false; } } ?> ```
The current version of Zend\_Validate has this built in - while there are plenty of other answers, it seems that all require passing a value to `Zend_Validate_Identical`. While that may have been needed at one point, you can now pass the name of another element. From the [`Zend_Validate` section of the reference guide](http://framework.zend.com/manual/en/zend.validate.set.html#zend.validate.set.identical): > Zend\_Validate\_Identical supports also the comparison of form elements. This can be done by using the element's name as token. See the following example: ``` $form->addElement('password', 'elementOne'); $form->addElement('password', 'elementTwo', array( 'validators' => array( array('identical', false, array('token' => 'elementOne')) ) )); ``` > By using the elements name from the first element as token for the second element, the validator validates if the second element is equal with the first element. In the case your user does not enter two identical values, you will get an validation error.
Zend_Form: how to check 2 fields are identical
[ "", "php", "validation", "zend-framework", "zend-form", "" ]
For the umpteenth time my laptop just shut down in the middle of my game because my power cable had disconnected without me noticing it. Now I want to write a little C# program that detects when my power cable disconnects and then emits a nice long System beep. What API could I use for that?
This should be trivial to implement using the [SystemInformation.PowerStatus](http://msdn.microsoft.com/en-us/library/system.windows.forms.systeminformation.powerstatus.aspx) property. And even though that lives in Windows.Forms, it should be perfectly usable from a system service. For a solution that also works on the Compact Framework, see [HOWTO: Get the Device Power Status](http://msdn.microsoft.com/en-us/library/aa457088.aspx)
[SystemEvents.PowerModeChanged](http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.powermodechanged.aspx). You will need to use either GetSystemPowerStatus (see link in one of the answers) or SystemInformation.PowerStatus (link is in another answer) in the handler to check what happened.
How to detect when laptop power cable has been disconnected?
[ "", "c#", ".net", "" ]
In javascript, is there an equivalent of `String.indexOf(...)` that takes a regular expression instead of a string for the first parameter, while still allowing a second parameter ? I need to do something like ``` str.indexOf(/[abc]/ , i); ``` and ``` str.lastIndexOf(/[abc]/ , i); ``` While String.search() takes a regexp as a parameter it does not allow me to specify a second argument! Edit: This turned out to be harder than I originally thought so I wrote a small test function to test all the provided solutions... it assumes regexIndexOf and regexLastIndexOf have been added to the String object. ``` function test (str) { var i = str.length +2; while (i--) { if (str.indexOf('a',i) != str.regexIndexOf(/a/,i)) alert (['failed regexIndexOf ' , str,i , str.indexOf('a',i) , str.regexIndexOf(/a/,i)]) ; if (str.lastIndexOf('a',i) != str.regexLastIndexOf(/a/,i) ) alert (['failed regexLastIndexOf ' , str,i,str.lastIndexOf('a',i) , str.regexLastIndexOf(/a/,i)]) ; } } ``` and I am testing as follow to make sure that at least for one character regexp, the result is the same as if we used indexOf //Look for the a among the xes test('xxx'); test('axx'); test('xax'); test('xxa'); test('axa'); test('xaa'); test('aax'); test('aaa');
Combining a few of the approaches already mentioned (the indexOf is obviously rather simple), I think these are the functions that will do the trick: ``` function regexIndexOf(string, regex, startpos) { var indexOf = string.substring(startpos || 0).search(regex); return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf; } function regexLastIndexOf(string, regex, startpos) { regex = (regex.global) ? regex : new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : "")); if(typeof (startpos) == "undefined") { startpos = string.length; } else if(startpos < 0) { startpos = 0; } var stringToWorkWith = string.substring(0, startpos + 1); var lastIndexOf = -1; var nextStop = 0; var result; while((result = regex.exec(stringToWorkWith)) != null) { lastIndexOf = result.index; regex.lastIndex = ++nextStop; } return lastIndexOf; } ``` --- UPDATE: Edited `regexLastIndexOf()` so that is seems to mimic `lastIndexOf()` now. Please let me know if it still fails and under what circumstances. --- UPDATE: Passes all tests found on in comments on this page, and my own. Of course, that doesn't mean it's bulletproof. Any feedback appreciated.
Instances of the `String` constructor have a [`.search()` method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search) which accepts a RegExp and returns the index of the first match. To start the search from a particular position (faking the second parameter of `.indexOf()`) you can `slice` off the first `i` characters: ``` str.slice(i).search(/re/) ``` But this will get the index in the shorter string (after the first part was sliced off) so you'll want to then add the length of the chopped off part (`i`) to the returned index if it wasn't `-1`. This will give you the index in the original string: ``` function regexIndexOf(text, re, i) { var indexInSuffix = text.slice(i).search(re); return indexInSuffix < 0 ? indexInSuffix : indexInSuffix + i; } ```
JavaScript: String.indexOf(...) allowing regular-expressions?
[ "", "javascript", "regex", "indexof", "" ]
I have a list of data that looks like the following: ``` // timestep,x_position,y_position 0,4,7 0,2,7 0,9,5 0,6,7 1,2,5 1,4,7 1,9,0 1,6,8 ``` ... and I want to make this look like: ``` 0, (4,7), (2,7), (9,5), (6,7) 1, (2,5), (4,7), (9,0), (6.8) ``` My plan was to use a dictionary, where the value of t is the key for the dictionary, and the value against the key would be a list. I could then append each (x,y) to the list. Something like: ``` # where t = 0, c = (4,7), d = {} # code 1 d[t].append(c) ``` Now this causes IDLE to fail. However, if I do: ``` # code 2 d[t] = [] d[t].append(c) ``` ... this works. So the question is: why does code 2 work, but code 1 doesn't? PS Any improvement on what I'm planning on doing would be of great interest!! I think I will have to check the dictionary on each loop through the input to see if the dictionary key already exists, I guess by using something like max(d.keys()): if it is there, append data, if not create the empty list as the dictionary value, and then append data on the next loop through.
Let's look at ``` d[t].append(c) ``` What is the value of `d[t]`? Try it. ``` d = {} t = 0 d[t] ``` What do you get? Oh. There's nothing in `d` that has a key of `t`. Now try this. ``` d[t] = [] d[t] ``` Ahh. Now there's something in `d` with a key of `t`. There are several things you can do. 1. Use example 2. 2. Use `setdefault`. `d.setdefault(t,[]).append(c)`. 3. Use [collections.defaultdict](http://www.python.org/doc/2.5.2/lib/defaultdict-objects.html). You'd use a `defaultdict(list)` instead of a simple dictionary, `{}`. --- **Edit 1. Optimization** Given input lines from a file in the above form: ts, x, y, the grouping process is needless. There's no reason to go from a simple list of ( ts, x, y ) to a more complex list of ( ts, (x,y), (x,y), (x,y), ... ). The original list can be processed exactly as it arrived. ``` d= collections.defaultdict(list) for ts, x, y in someFileOrListOrQueryOrWhatever: d[ts].append( (x,y) ) ``` --- **Edit 2. Answer Question** "when initialising a dictionary, you need to tell the dictionary what the key-value data structure will look like?" I'm not sure what the question means. Since, all dictionaries *are* key-value structures, the question's not very clear. So, I'll review the three alternatives, which may answer the question. **Example 2**. Initialization ``` d= {} ``` Use ``` if t not in d: d[t] = list() d[t].append( c ) ``` Each dictionary value must be initialized to some useful structure. In this case, we check to see if the key is present; when the key is missing, we create the key and assign an empty list. **Setdefault** Initialization ``` d= {} ``` Use ``` d.setdefault(t,list()).append( c ) ``` In this case, we exploit the `setdefault` method to either fetch a value associated with a key or create a new value associated with a missing key. **default dict** Initialization ``` import collections d = collections.defaultdict(list) ``` Use ``` d[t].append( c ) ``` The `defaultdict` uses an initializer function for missing keys. In this case, we provide the `list` function so that a new, empty list is created for a missing key.
I think you want to use setdefault. It's a bit weird to use but does exactly what you need. ``` d.setdefault(t, []).append(c) ``` The `.setdefault` method will return the element (in our case, a list) that's bound to the dict's key `t` if that key exists. If it doesn't, it will bind an empty list to the key `t` and return it. So either way, a list will be there that the `.append` method can then append the tuple `c` to.
Storing and updating lists in Python dictionaries: why does this happen?
[ "", "python", "dictionary", "list", "" ]
We're having a bit of fun here at work. It all started with one of the guys setting up a Hackintosh and we were wondering whether it was faster than a Windows Box of (nearly) same specs that we have. So we decided to write a little test for it. Just a simple Prime number calculator. It's written in Java and tells us the time it takes to calculate the first n Prime numbers. Optimised version below - now takes ~6.6secs ``` public class Primes { public static void main(String[] args) { int topPrime = 150000; int current = 2; int count = 0; int lastPrime = 2; long start = System.currentTimeMillis(); while (count < topPrime) { boolean prime = true; int top = (int)Math.sqrt(current) + 1; for (int i = 2; i < top; i++) { if (current % i == 0) { prime = false; break; } } if (prime) { count++; lastPrime = current; } if (current == 2) { current++; } else { current = current + 2; } } System.out.println("Last prime = " + lastPrime); System.out.println("Total time = " + (double)(System.currentTimeMillis() - start) / 1000); } } ``` We've pretty much lost the plot of the whole Hackintosh vs PC thing and are just having some fun with optimising it. First attempt with no optimisations (the above code has a couple) ran around 52.6min to find the first 150000 prime numbers. This optimisation is running around 47.2mins. If you want to have a go and post your results, then stick em up. Specs for the PC I'm running it on are Pentium D 2.8GHz, 2GB RAM, running Ubuntu 8.04. **Best Optimisation so far has been the square root of current, first mentioned by Jason Z.**
Well I see a couple of quick optimizations that can be done. First you don't have to try each number up to half of the current number. Instead you only have try up to the square root of the current number. And the other optimization was what BP said with a twist: Instead of ``` int count = 0; ... for (int i = 2; i < top; i++) ... if (current == 2) current++; else current += 2; ``` use ``` int count = 1; ... for (int i = 3; i < top; i += 2) ... current += 2; ``` This should speed things up quite a lot. **Edit:** More optimization courtesy of Joe Pineda: Remove the variable "top". ``` int count = 1; ... for (int i = 3; i*i <= current; i += 2) ... current += 2; ``` If this optimization indeed increases speed is up to java. Calculating the square root takes a lot of time compared to multiplying two numbers. However since we move the multiplication into the for loop this is done every single loop. So this COULD slow things down depending on how fast the square root algorithm in java is.
That's a bit worse than my sieve did on a 8 Mhz 8088 in turbo pascal in 1986 or so. But that was after optimisations :)
Prime number calculation fun
[ "", "java", "primes", "" ]
Let's say I have a source file with many preprocessor directives. Is it possible to see how it looks after the preprocessor is done with it?
`cl.exe`, the command line interface to Microsoft Visual C++, has three different options for outputting the preprocessed file (hence the inconsistency in the previous responses about Visual C++): * `/E`: [preprocess to stdout](http://msdn.microsoft.com/en-us/library/3xkfswhy.aspx) (similar to GCC's -E option) * `/P`: [preprocess to file](http://msdn.microsoft.com/en-us/library/8z9z0bx6.aspx) * `/EP`: [preprocess to stdout without #line directives](http://msdn.microsoft.com/en-us/library/becb7sys.aspx) If you want to preprocess to a file without #line directives, combine the `/P` and `/EP` options.
Most compilers have an option to just run the preprocessor. *e.g.*, gcc provides -E: ``` -E Stop after the preprocessing stage; do not run the compiler proper. The output is in the form of preprocessed source code, which is sent to the standard output. ``` So you can just run: ``` gcc -E foo.c ``` If you can't find such an option, you can also just find the C preprocessor on your machine. It's usually called cpp and is probably already in your path. Invoke it like this: ``` cpp foo.c ``` If there are headers you need to include from other directories , you can pass -I/path/to/include/dir to either of these, just as you would with a regular compile. For Windows, I'll leave it to other posters to provide answers as I'm no expert there.
How do I see a C/C++ source file after preprocessing in Visual Studio?
[ "", "c++", "c", "debugging", "visual-studio-2005", "c-preprocessor", "" ]
I know how they are different syntactically, and that C++ uses new, and C uses malloc. But how do they work, in a high-level explanation? See [What is the difference between new/delete and malloc/free?](https://stackoverflow.com/questions/240212/what-is-the-difference-between-newdelete-and-mallocfree#240308)
I'm just going to direct you to this answer: [What is the difference between new/delete and malloc/free?](https://stackoverflow.com/questions/240212/what-is-the-difference-between-newdelete-and-mallocfree#240308) . Martin provided an excellent overview. Quick overview on how they *work* (without diving into how you could overload them as member functions): ## new-expression and allocation 1. The code contains a new-expression supplying the type-id. 2. The compiler will look into whether the type overloads the operator new with an allocation function. 3. If it finds an overload of an operator new allocation function, that one is called using the arguments given to new and sizeof(TypeId) as its first argument: Sample: ``` new (a, b, c) TypeId; // the function called by the compiler has to have the following signature: operator new(std::size_t size, TypeOfA a, TypeOfB b, TypeOf C c); ``` 1. if operator new fails to allocate storage, it can call `new_handler`, and hope it makes place. If there still is not enough place, new has to throw `std::bad_alloc` or derived from it. An allocator that has `throw()` (no-throw guarantee), it shall return a null-pointer in that case. 2. The C++ runtime environment will create an object of the type given by the type-id in the memory returned by the allocation function. There are a few special allocation functions given special names: * `no-throw` new. That takes a `nothrow_t` as second argument. A new-expression of the form like the following will call an allocation function taking only std::size\_t and nothrow\_t: Example: ``` new (std::nothrow) TypeId; ``` * `placement new`. That takes a void\* pointer as first argument, and instead of returning a newly allocated memory address, it returns that argument. It is used to create an object at a given address. Standard containers use that to preallocate space, but only create objects when needed, later. Code: ``` // the following function is defined implicitly in the standard library void * operator(std::size_t size, void * ptr) throw() { return ptr; } ``` If the allocation function returns storage, and the the constructor of the object created by the runtime throws, then the operator delete is called automatically. In case a form of new was used that takes additional parameters, like ``` new (a, b, c) TypeId; ``` Then the operator delete that takes those parameters is called. That operator delete version is only called if the deletion is done because the constructor of the object did throw. If you call delete yourself, then the compiler will use the normal operator delete function taking only a `void*` pointer: ``` int * a = new int; => void * operator new(std::size_t size) throw(std::bad_alloc); delete a; => void operator delete(void * ptr) throw(); TypeWhosCtorThrows * a = new ("argument") TypeWhosCtorThrows; => void * operator new(std::size_t size, char const* arg1) throw(std::bad_alloc); => void operator delete(void * ptr, char const* arg1) throw(); TypeWhosCtorDoesntThrow * a = new ("argument") TypeWhosCtorDoesntThrow; => void * operator new(std::size_t size, char const* arg1) throw(std::bad_alloc); delete a; => void operator delete(void * ptr) throw(); ``` ## new-expression and arrays If you do ``` new (possible_arguments) TypeId[N]; ``` The compiler is using the `operator new[]` functions instead of plain `operator new`. The operator can be passed a first argument not exactly `sizeof(TypeId)*N`: The compiler could add some space to store the number of objects created (necassary to be able to call destructors). The Standard puts it this way: * `new T[5]` results in a call of operator `new[](sizeof(T)*5+x)`, and * `new(2,f) T[5]` results in a call of operator `new[](sizeof(T)*5+y,2,f)`.
What `new` does differently form `malloc` is the following: * It constructs a value in the allocated memory, by calling `operator new`. This behaviour can be adapted by overloading this operator, either for all types, or just for your class. * It calls handler functions if no memory can be allocated. This gives you the opportunity to free the required memory on the fly if you have registered such a handler function beforehand. * If that doesn't help (e.g. because you *didn't* register any function), it throws an exception. So all in all, `new` is highly customizable and also does initialization work besides memory allocation. These are the two big differences.
How do 'malloc' and 'new' work? How are they different (implementation wise)?
[ "", "c++", "c", "" ]
I'm writing a simple templating layer in PHP but I've got myself a little stuck. Here's how it works at the moment: Firstly I use `fetch_template` to load the template contents from the database - this works (and I collect all the templates at startup if you're interested). I use PHP variables in my template code and in the logic - e.g.: ``` // PHP: $name = 'Ross'; // Tpl: <p>Hello, my name is $name.</p> ``` I then use `output_template` (below) to parse through the variables in the template and replace them. Previously I was using template tags with a glorified `str_replace` template class but it was too inefficient. ``` /** * Returns a template after evaluating it * @param string $template Template contents * @return string Template output */ function output_template($template) { eval('return "' . $template . '";'); } ``` My problem, if you haven't already guessed, is that the variables are not declared inside the function - therefore the function can't parse them in `$template` unless I put them in the global scope - which I'm not sure I want to do. That or have an array of variables as a parameter in the function (which sounds even more tedious but possible). Does anyone have any solutions other than using the code from the function (it is only a one-liner) in my code, rather than using the function? Thanks, Ross *P.s. I know about Smarty and the vast range of templating engines out there - I'm not looking to use them so please don't suggest them. Thanks!*
Rather than run through your loop you can use `include($template_name)`. Or, if you want the content of the output from the template, you can do something like this: ``` $template_name = 'template.php'; // import the contents into this template ob_start(); include($template_name); $content = ob_get_clean(); // do something with $content now ... ``` And remember, in your template, you can use the often overlooked PHP syntax: ``` <?php if ($a == 5): ?> A is equal to 5 <?php endif; ?> ``` Alternative syntax is available for if, while, for, foreach and switch ... perfect for manipulating the data in your template. See "[Alternative syntax for control structures](http://php.net/manual/en/control-structures.alternative-syntax.php "PHP Alternative Syntax")" for more details.
I'd pass an associative array with variables to replace, then extract() them. Then you could also pass $\_GLOBALS to achieve the same result. ``` function output_template($template, $vars) { extract($vars); eval('return "' . $template . '";'); } ``` Edit: you might also want to consider string subtitution instead of eval, depending on who's allowed to write your templates and on who specifies which template to load. Then there might be a problem with escaping, too...
PHP Templating
[ "", "php", "templates", "variables", "global-variables", "" ]
I need to use `FtpWebRequest` to put a file in a FTP directory. Before the upload, I would first like to know if this file exists. What method or property should I use to check if this file exists?
``` var request = (FtpWebRequest)WebRequest.Create ("ftp://ftp.domain.com/doesntexist.txt"); request.Credentials = new NetworkCredential("user", "pass"); request.Method = WebRequestMethods.Ftp.GetFileSize; try { FtpWebResponse response = (FtpWebResponse)request.GetResponse(); } catch (WebException ex) { FtpWebResponse response = (FtpWebResponse)ex.Response; if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) { //Does not exist } } ``` As a general rule it's a bad idea to use Exceptions for functionality in your code like this, however in this instance I believe it's a win for pragmatism. Calling list on the directory has the potential to be FAR more inefficient than using exceptions in this way. If you're not, just be aware it's not good practice! EDIT: "It works for me!" This appears to work on most ftp servers but not all. Some servers require sending "TYPE I" before the SIZE command will work. One would have thought that the problem should be solved as follows: ``` request.UseBinary = true; ``` Unfortunately it is a by design limitation (big fat bug!) that unless FtpWebRequest is either downloading or uploading a file it will NOT send "TYPE I". See discussion and Microsoft response [here](http://social.msdn.microsoft.com/forums/en-US/netfxnetcom/thread/0c38814e-d8e3-49f3-8818-b5306cc100ce/). I'd recommend using the following WebRequestMethod instead, this works for me on all servers I tested, even ones which would not return a file size. ``` WebRequestMethods.Ftp.GetDateTimestamp ```
Because ``` request.Method = WebRequestMethods.Ftp.GetFileSize ``` may fails in some case (550: SIZE not allowed in ASCII mode), you can just check Timestamp instead. ``` reqFTP.Credentials = new NetworkCredential(inf.LogOn, inf.Password); reqFTP.UseBinary = true; reqFTP.Method = WebRequestMethods.Ftp.GetDateTimestamp; ```
How to check if file exists on FTP before FtpWebRequest
[ "", "c#", ".net", "ftp", "ftpwebrequest", "" ]
I am working on a small team of web application developers. We edit JSPs in Eclipse on our own machines and then move them over to a shared application server to test the changes. I have an Ant script that will take ALL the JSPs on my machine and move them over to the application server, but will only overwrite JSPs if the ones on my machine are "newer". This works well most of the time, but not all of the time. Our update method doesn't preserve file change day/times, so it is possible that an Update on my machine will set the file day/time to now instead of when the file was actually last changed. If someone else worked on that file 1 hour ago (but hasn't committed the changes yet), then the older file on my PC will actually have a newer date. So when I run the Ant script it will overwrite their changes with an older file. What I am looking for is an easy way to just move the file I am currently working on. Is there a way to specify the "current" file in an Ant script? Or an easy way to move the current file within Eclipse? Perhaps a good plugin to do this kind of stuff? I could go out to Windows Explorer to separately move the file, but I would much prefer to be able to do it from within Eclipse.
Add a target to your [ant](http://ant.apache.org) build file to copy a single jsp using a command line property definition as @matt b described. Create a new external tool launch profile and use the "String Substitution Preferences" to pass in the reference to the active file in the editor (`resource_name`). See Eclipse Help | Java Development User Guide | Reference | Preferences | Run/Debug | Launching | String Substitution
How would Ant know what file was "current"? It has no way of knowing. You *could* pass the name of the file into your Ant script (by taking advantage of the fact that any arguments you pass into Ant with `-D` are automatically parameters in your script)... > ant -Dfile=myfile.jsp update and have your script look something like... ``` <copy file=${myfile} todir="blah"/> ``` ...but it would probably be a pain to constantly type in the name of the file on the commandline. Honestly, the type of problem you've described are inevitable when you have multiple developers sharing an environment. I think that a better approach for you and your team long-term is to have each developer work/test on a local application server instance, before the code is promoted. This removes all headaches, bottlenecks, and scheduling trouble in sharing an app server with other people.
How to move only the current file with Eclipse and/or Ant?
[ "", "java", "eclipse", "ant", "" ]
I'm starting to use CUDA at the moment and have to admit that I'm a bit disappointed with the C API. I understand the reasons for choosing C but had the language been based on C++ instead, several aspects would have been a lot simpler, e.g. device memory allocation (via `cudaMalloc`). My plan was to do this myself, using overloaded `operator new` with placement `new` and RAII (two alternatives). I'm wondering if there are any caveats that I haven't noticed so far. The code *seems* to work but I'm still wondering about potential memory leaks. The usage of the **RAII** code would be as follows: ``` CudaArray<float> device_data(SIZE); // Use `device_data` as if it were a raw pointer. ``` Perhaps a class is overkill in this context (especially since you'd still have to use `cudaMemcpy`, the class only encapsulating RAII) so the other approach would be **placement `new`**: ``` float* device_data = new (cudaDevice) float[SIZE]; // Use `device_data` … operator delete [](device_data, cudaDevice); ``` Here, `cudaDevice` merely acts as a tag to trigger the overload. However, since in normal placement `new` this would indicate the placement, I find the syntax oddly consistent and perhaps even preferable to using a class. I'd appreciate criticism of every kind. Does somebody perhaps know if something in this direction is planned for the next version of CUDA (which, as I've heard, will improve its C++ support, whatever they mean by that). So, my question is actually threefold: 1. Is my placement `new` overload semantically correct? Does it leak memory? 2. Does anybody have information about future CUDA developments that go in this general direction (let's face it: C interfaces in C++ s\*ck)? 3. How can I take this further in a consistent manner (there are other APIs to consider, e.g. there's not only device memory but also a constant memory store and texture memory)? --- ``` // Singleton tag for CUDA device memory placement. struct CudaDevice { static CudaDevice const& get() { return instance; } private: static CudaDevice const instance; CudaDevice() { } CudaDevice(CudaDevice const&); CudaDevice& operator =(CudaDevice const&); } const& cudaDevice = CudaDevice::get(); CudaDevice const CudaDevice::instance; inline void* operator new [](std::size_t nbytes, CudaDevice const&) { void* ret; cudaMalloc(&ret, nbytes); return ret; } inline void operator delete [](void* p, CudaDevice const&) throw() { cudaFree(p); } template <typename T> class CudaArray { public: explicit CudaArray(std::size_t size) : size(size), data(new (cudaDevice) T[size]) { } operator T* () { return data; } ~CudaArray() { operator delete [](data, cudaDevice); } private: std::size_t const size; T* const data; CudaArray(CudaArray const&); CudaArray& operator =(CudaArray const&); }; ``` About the singleton employed here: Yes, I'm aware of its drawbacks. However, these aren't relevant in this context. All I needed here was a small type tag that wasn't copyable. Everything else (i.e. multithreading considerations, time of initialization) don't apply.
I would go with the placement new approach. Then I would define a class that conforms to the std::allocator<> interface. In theory, you could pass this class as a template parameter into std::vector<> and std::map<> and so forth. Beware, I have heard that doing such things is fraught with difficulty, but at least you will learn a lot more about the STL this way. And you do not need to re-invent your containers and algorithms.
In the meantime there were some further developments (not so much in terms of the CUDA API, but at least in terms of projects attempting an STL-like approach to CUDA data management). Most notably there is a project from NVIDIA research: [thrust](http://code.google.com/p/thrust)
CUDA: Wrapping device memory allocation in C++
[ "", "c++", "cuda", "raii", "placement-new", "" ]
I would like to generate some JavaScript on the server side in ASP.Net MVC. Is there a view engine that supports this? Ideally I would like to be able to get JavaScript from an url like: ``` http://myapp/controller/action.js ``` I've looked at the MonoRail project, and they seem to have this feature, but it's very lacking in documentation, and I can't find any ports to ASP.Net MVC. **Edit:** The idea is to be able to render a page both as standard HTML by using a url like: ``` http://myapp/controller/action ``` and as js (specifically an ExtJS component) by using the first url in the question. There would be only a single action in the controller, but two views: one for HTML and one for JS. **Edit 2:** I basically wanted to achieve the same result as [router extension parsing/request handling](http://www.pagebakers.nl/2007/06/05/using-json-in-cakephp-12/) in CakePHP.
I wanted to extend this idea to not only allow Javascript views, but more or less any type of document. To use it, you just put the views for \*.js urls in a subfolder of your controller's view folder: ``` \Views +-\MyController +-\js | +-Index.aspx <- This view will get rendered if you request /MyController/Index.js +-Index.aspx ``` The class is a decorator for any type of ViewEngine, so you can use it with NVelocity/WebForms/Whatever: ``` public class TypeViewEngine<T> : IViewEngine where T : IViewEngine { private readonly T baseEngine; public T BaseEngine { get { return baseEngine; } } public TypeViewEngine(T baseEngine) { this.baseEngine = baseEngine; } public void RegisterRoutes(RouteCollection routes) { routes.MapRoute( "TypeViewEngine", "{controller}/{action}.{type}", new {controller = "Home", action = "Index", type = "html"} ); } public ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName) { var vars = controllerContext.RouteData.Values; if(vars["type"] != null && vars["type"].ToString() != "html") { viewName = string.Format("{0}/{1}", vars["type"], viewName); } return baseEngine.FindView(controllerContext, viewName, masterName); } public ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName) { return baseEngine.FindPartialView(controllerContext, partialViewName); } public void ReleaseView(ControllerContext controllerContext, IView view) { baseEngine.ReleaseView(controllerContext, view); } } ``` Then, in your Global.asax.cs file: ``` protected void Application_Start() { var ve = new TypeViewEngine<WebFormViewEngine>(new WebFormViewEngine()); ve.RegisterRoutes(RouteTable.Routes); RegisterRoutes(RouteTable.Routes); ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(ve); } ``` Thanks for everyone's help with this!
Based on your edit I'll try with a new answer asumming you need json data for ExtJS. I've just tested it in the app I'm building and it works fine. First you need two routes ``` {controller}/{action}.{format} {controller}/{action} ``` Now the Controller class has a Json method to serialize whatever object you want and it's a JsonResult so you can just use: ``` public ActionResult List(string format) { // logic here if (string.IsNullOrEmpty(format)) { return View(); } else if (format == "js") { return Json(object_to_serialize); } } ```
Is there an ASP.Net MVC view engine that supports JavaScript views?
[ "", "javascript", "asp.net-mvc", "viewengine", "" ]
I've got this small question - given a bitmask of weekdays (e.g., `Sunday = 0x01, Monday = 0x02, Tuesday = 0x04`, etc...) and today's day (in a form of `Sunday = 1, Monday = 2, Tuesday = 3`, etc...) - what's the most elegant way to find out the next day from today, that's set in the bitmask? By elegant I mean, is there a way to do this without if/switch/etc..., because I know the non-elegant way? **Edit** I probably should've mentioned (to make this more clear) that the variable holding the bitmask can have several of the days set, so for example (roughly): ``` uDay = Sunday | Monday; today = Tuesday; ``` I need to get "Sunday"
``` int getNextDay(int days_mask, int today) { if (!days_mask) return -1; // no days set days_mask |= days_mask << 7; // duplicate days into next week mask = 1 << (today % 7); // keep track of the day while (!(mask & days_mask)) { mask <<= 1; ++today; } return today % 7; } ``` So that's just one if at the beginning and while loop. How's that? **Edit:** I just realized there was a degenerate case where if the use passes today>=14 (or greater than the highest bit set) the while loop becomes infinite. The (today % 7) on line 4 fixes this case. And if I may grouse (light-heartedly) about the other version getting the checkmark, my version only have 2 modulus calls, while the checked solution will have a minimum of 1 and a maximum of 6 modulus calls. Also, the comment about does the function return "today" if today is set is interesting. If the function should not return today unless today is the only day in the set would require that you pre-increment today on line 3 of my solution.
You don't need any extra variables at all. The simplest idea -- start with "tomorrow", look at successive days until you find a day in the mask -- is also the most elegant to implement. The trick to doing it nicely is to think of the days as Sunday=0, Monday=1 and so on (only inside this function). Then, "today" is actually `t-1` (where t is the input to the function, so it goes from 1 to 7), and "tomorrow" is `(t-1+1)%7` i.e `t%7`, etc. This is simple and has been tested against litb's code exhaustively, just to be sure :-) ``` int getNextDay(int m, int t) { if((m&127)==0) return t; //If no day is set, return today t=t%7; //Start with tomorrow while((m&(1<<t))==0) t = (t+1)%7; //Try successive days return t+1; //Change back to Sunday=1, etc. } ``` Edit: If you want "next" to mean "today or later", then the "t=t%7" line should be changed to `t=t-1` or `--t`.
An algorithm to get the next weekday set in a bitmask
[ "", "c++", "algorithm", "" ]
I'm messing around with some C code using floats, and I'm getting 1.#INF00, -1.#IND00 and -1.#IND when I try to print floats in the screen. What does those values mean? I believe that 1.#INF00 means positive infinity, but what about -1.#IND00 and -1.#IND? I also saw sometimes this value: 1.$NaN which is Not a Number, but what causes those strange values and how can those help me with debugging? I'm using [MinGW](http://en.wikipedia.org/wiki/MinGW) which I believe uses [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point) representation for float point numbers. Can someone list all those invalid values and what they mean?
From [IEEE floating-point exceptions in C++](http://www.johndcook.com/IEEE_exceptions_in_cpp.html) : > This page will answer the following questions. > > * My program just printed out 1.#IND or 1.#INF (on Windows) or nan or inf (on Linux). What happened? > * How can I tell if a number is really a number and not a NaN or an infinity? > * How can I find out more details at runtime about kinds of NaNs and infinities? > * Do you have any sample code to show how this works? > * Where can I learn more? > > These questions have to do with floating point exceptions. If you get some strange non-numeric output where you're expecting a number, you've either exceeded the finite limits of floating point arithmetic or you've asked for some result that is undefined. To keep things simple, I'll stick to working with the double floating point type. Similar remarks hold for float types. > > **Debugging 1.#IND, 1.#INF, nan, and inf** > > If your operation would generate a larger positive number than could be stored in a double, the operation will return 1.#INF on Windows or inf on Linux. Similarly your code will return -1.#INF or -inf if the result would be a negative number too large to store in a double. Dividing a positive number by zero produces a positive infinity and dividing a negative number by zero produces a negative infinity. Example code at the end of this page will demonstrate some operations that produce infinities. > > Some operations don't make mathematical sense, such as taking the square root of a negative number. (Yes, this operation makes sense in the context of complex numbers, but a double represents a real number and so there is no double to represent the result.) The same is true for logarithms of negative numbers. Both sqrt(-1.0) and log(-1.0) would return a NaN, the generic term for a "number" that is "not a number". Windows displays a NaN as -1.#IND ("IND" for "indeterminate") while Linux displays nan. Other operations that would return a NaN include 0/0, 0\*∞, and ∞/∞. See the sample code below for examples. > > In short, if you get 1.#INF or inf, look for overflow or division by zero. If you get 1.#IND or nan, look for illegal operations. Maybe you simply have a bug. If it's more subtle and you have something that is difficult to compute, see Avoiding Overflow, Underflow, and Loss of Precision. That article gives tricks for computing results that have intermediate steps overflow if computed directly.
For anyone wondering about the difference between `-1.#IND00` and `-1.#IND` (which the question specifically asked, and none of the answers address): **`-1.#IND00`** This specifically means a non-zero number divided by zero, e.g. `3.14 / 0` ([source](https://stackoverflow.com/a/33057379)) **`-1.#IND`** (a synonym for `NaN`) This means one of four things (see [wiki](https://en.wikipedia.org/wiki/NaN#Operations_generating_NaN) from [source](https://stackoverflow.com/a/7476564)): 1) `sqrt` or `log` of a negative number 2) operations where both variables are 0 or infinity, e.g. `0 / 0` 3) operations where at least one variable is already `NaN`, e.g. `NaN * 5` 4) out of range trig, e.g. `arcsin(2)`
What do 1.#INF00, -1.#IND00 and -1.#IND mean?
[ "", "c++", "c", "" ]
How can I convert an `std::string` to a `char*` or a `const char*`?
If you just want to pass a [`std::string`](http://en.cppreference.com/w/cpp/string/basic_string) to a function that needs `const char *`, you can use [`.c_str()`](https://en.cppreference.com/w/cpp/string/basic_string/c_str): ``` std::string str; const char * c = str.c_str(); ``` And if you need a non-const `char *`, call [`.data()`](https://en.cppreference.com/w/cpp/string/basic_string/data): ``` std::string str; char * c = str.data(); ``` `.data()` was added in C++17. Before that, you can use `&str[0]`. Note that if the `std::string` is `const`, `.data()` will return `const char *` instead, like `.c_str()`. The pointer becomes invalid if the string is destroyed or reallocates memory. The pointer points to a null-terminated string, and the terminator doesn't count against `str.size()`. You're not allowed to assign a non-null character to the terminator.
Given say... ``` std::string x = "hello"; ``` ## Getting a `char \*` or `const char\*` from a `string` **How to get a character pointer that's valid while `x` remains in scope and isn't modified further** **C++11** simplifies things; the following all give access to the same internal string buffer: ``` const char* p_c_str = x.c_str(); const char* p_data = x.data(); char* p_writable_data = x.data(); // for non-const x from C++17 const char* p_x0 = &x[0]; char* p_x0_rw = &x[0]; // compiles iff x is not const... ``` All the above pointers will hold the *same value* - the address of the first character in the buffer. Even an empty string has a "first character in the buffer", because C++11 guarantees to always keep an extra NUL/0 terminator character after the explicitly assigned string content (e.g. `std::string("this\0that", 9)` will have a buffer holding `"this\0that\0"`). Given any of the above pointers: ``` char c = p[n]; // valid for n <= x.size() // i.e. you can safely read the NUL at p[x.size()] ``` Only for the non-`const` pointer `p_writable_data` and from `&x[0]`: ``` p_writable_data[n] = c; p_x0_rw[n] = c; // valid for n <= x.size() - 1 // i.e. don't overwrite the implementation maintained NUL ``` Writing a NUL elsewhere in the string does *not* change the `string`'s `size()`; `string`'s are allowed to contain any number of NULs - they are given no special treatment by `std::string` (same in C++03). In **C++03**, things were considerably more complicated (key differences ***highlighted***): * `x.data()` + returns `const char*` to the string's internal buffer ***which wasn't required by the Standard to conclude with a NUL*** (i.e. might be `['h', 'e', 'l', 'l', 'o']` followed by uninitialised or garbage values, with accidental accesses thereto having *undefined behaviour*). - `x.size()` characters are safe to read, i.e. `x[0]` through `x[x.size() - 1]` - for empty strings, you're guaranteed some non-NULL pointer to which 0 can be safely added (hurray!), but you shouldn't dereference that pointer. * `&x[0]` + ***for empty strings this has undefined behaviour*** (21.3.4) - e.g. given `f(const char* p, size_t n) { if (n == 0) return; ...whatever... }` you mustn't call `f(&x[0], x.size());` when `x.empty()` - just use `f(x.data(), ...)`. + otherwise, as per `x.data()` but: - for non-`const` `x` this yields a non-`const` `char*` pointer; you can overwrite string content * `x.c_str()` + returns `const char*` to an ASCIIZ (NUL-terminated) representation of the value (i.e. ['h', 'e', 'l', 'l', 'o', '\0']). + although few if any implementations chose to do so, the C++03 Standard was worded to allow the string implementation the freedom to create a ***distinct NUL-terminated buffer*** *on the fly*, from the potentially non-NUL terminated buffer "exposed" by `x.data()` and `&x[0]` + `x.size()` + 1 characters are safe to read. + guaranteed safe even for empty strings (['\0']). ## Consequences of accessing outside legal indices Whichever way you get a pointer, you must not access memory further along from the pointer than the characters guaranteed present in the descriptions above. Attempts to do so have *undefined behaviour*, with a very real chance of application crashes and garbage results even for reads, and additionally wholesale data, stack corruption and/or security vulnerabilities for writes. ## When do those pointers get invalidated? If you call some `string` member function that modifies the `string` or reserves further capacity, any pointer values returned beforehand by any of the above methods are *invalidated*. You can use those methods again to get another pointer. (The rules are the same as for iterators into `string`s). See also *How to get a character pointer valid even after `x` leaves scope or is modified further* below.... ## So, which is *better* to use? From C++11, use `.c_str()` for ASCIIZ data, and `.data()` for "binary" data (explained further below). In C++03, use `.c_str()` unless certain that `.data()` is adequate, and prefer `.data()` over `&x[0]` as it's safe for empty strings.... *...try to understand the program enough to use `data()` when appropriate, or you'll probably make other mistakes...* The ASCII NUL '\0' character guaranteed by `.c_str()` is used by many functions as a sentinel value denoting the end of relevant and safe-to-access data. This applies to both C++-only functions like say `fstream::fstream(const char* filename, ...)` and shared-with-C functions like `strchr()`, and `printf()`. Given C++03's `.c_str()`'s guarantees about the returned buffer are a super-set of `.data()`'s, you can always safely use `.c_str()`, but people sometimes don't because: * using `.data()` communicates to other programmers reading the source code that the data is not ASCIIZ (rather, you're using the string to store a block of data (which sometimes isn't even really textual)), or that you're passing it to another function that treats it as a block of "binary" data. This can be a crucial insight in ensuring that other programmers' code changes continue to handle the data properly. * C++03 only: there's a slight chance that your `string` implementation will need to do some extra memory allocation and/or data copying in order to prepare the NUL terminated buffer As a further hint, if a function's parameters require the (`const`) `char*` but don't insist on getting `x.size()`, the function *probably* needs an ASCIIZ input, so `.c_str()` is a good choice (the function needs to know where the text terminates somehow, so if it's not a separate parameter it can only be a convention like a length-prefix or sentinel or some fixed expected length). ## How to get a character pointer valid even after `x` leaves scope or is modified further You'll need to ***copy*** the contents of the `string` `x` to a new memory area outside `x`. This external buffer could be in many places such as another `string` or character array variable, it may or may not have a different lifetime than `x` due to being in a different scope (e.g. namespace, global, static, heap, shared memory, memory mapped file). To copy the text from `std::string x` into an independent character array: ``` // USING ANOTHER STRING - AUTO MEMORY MANAGEMENT, EXCEPTION SAFE std::string old_x = x; // - old_x will not be affected by subsequent modifications to x... // - you can use `&old_x[0]` to get a writable char* to old_x's textual content // - you can use resize() to reduce/expand the string // - resizing isn't possible from within a function passed only the char* address std::string old_x = x.c_str(); // old_x will terminate early if x embeds NUL // Copies ASCIIZ data but could be less efficient as it needs to scan memory to // find the NUL terminator indicating string length before allocating that amount // of memory to copy into, or more efficient if it ends up allocating/copying a // lot less content. // Example, x == "ab\0cd" -> old_x == "ab". // USING A VECTOR OF CHAR - AUTO, EXCEPTION SAFE, HINTS AT BINARY CONTENT, GUARANTEED CONTIGUOUS EVEN IN C++03 std::vector<char> old_x(x.data(), x.data() + x.size()); // without the NUL std::vector<char> old_x(x.c_str(), x.c_str() + x.size() + 1); // with the NUL // USING STACK WHERE MAXIMUM SIZE OF x IS KNOWN TO BE COMPILE-TIME CONSTANT "N" // (a bit dangerous, as "known" things are sometimes wrong and often become wrong) char y[N + 1]; strcpy(y, x.c_str()); // USING STACK WHERE UNEXPECTEDLY LONG x IS TRUNCATED (e.g. Hello\0->Hel\0) char y[N + 1]; strncpy(y, x.c_str(), N); // copy at most N, zero-padding if shorter y[N] = '\0'; // ensure NUL terminated // USING THE STACK TO HANDLE x OF UNKNOWN (BUT SANE) LENGTH char* y = alloca(x.size() + 1); strcpy(y, x.c_str()); // USING THE STACK TO HANDLE x OF UNKNOWN LENGTH (NON-STANDARD GCC EXTENSION) char y[x.size() + 1]; strcpy(y, x.c_str()); // USING new/delete HEAP MEMORY, MANUAL DEALLOC, NO INHERENT EXCEPTION SAFETY char* y = new char[x.size() + 1]; strcpy(y, x.c_str()); // or as a one-liner: char* y = strcpy(new char[x.size() + 1], x.c_str()); // use y... delete[] y; // make sure no break, return, throw or branching bypasses this // USING new/delete HEAP MEMORY, SMART POINTER DEALLOCATION, EXCEPTION SAFE // see boost shared_array usage in Johannes Schaub's answer // USING malloc/free HEAP MEMORY, MANUAL DEALLOC, NO INHERENT EXCEPTION SAFETY char* y = strdup(x.c_str()); // use y... free(y); ``` ## Other reasons to want a `char*` or `const char*` generated from a `string` So, above you've seen how to get a (`const`) `char*`, and how to make a copy of the text independent of the original `string`, but what can you *do* with it? A random smattering of examples... * give "C" code access to the C++ `string`'s text, as in `printf("x is '%s'", x.c_str());` * copy `x`'s text to a buffer specified by your function's caller (e.g. `strncpy(callers_buffer, callers_buffer_size, x.c_str())`), or volatile memory used for device I/O (e.g. `for (const char* p = x.c_str(); *p; ++p) *p_device = *p;`) * append `x`'s text to an character array already containing some ASCIIZ text (e.g. `strcat(other_buffer, x.c_str())`) - be careful not to overrun the buffer (in many situations you may need to use `strncat`) * return a `const char*` or `char*` from a function (perhaps for historical reasons - client's using your existing API - or for C compatibility you don't want to return a `std::string`, but do want to copy your `string`'s data somewhere for the caller) + be careful not to return a pointer that may be dereferenced by the caller after a local `string` variable to which that pointer pointed has left scope + some projects with shared objects compiled/linked for different `std::string` implementations (e.g. STLport and compiler-native) may pass data as ASCIIZ to avoid conflicts
How to convert a std::string to const char* or char*
[ "", "c++", "string", "char", "stdstring", "" ]
I have two running processes in Windows, and each process has a pipe to the other. I want to serialize a complicated class and transmit it from one process to the other. I already have the serialization procedure worked out, and I understand that the pipes are sending binary streams. How should I go about sending my serialized data? I'm using WinAPI and C++. Should I develop a custom protocol? If so, should it be generic or unique to this particular class? Can I preserve virtual tables when sending the serialized class? Are there any models or design patterns that are commonly used in this case? A little bit of sample code would be greatly appreciated. Thank you!
Here is the tutorial for `boost::serialization`. I could imagine it would work fine sending the data over the pipe and deserializing on the other side: <http://www.boost.org/doc/libs/1_37_0/libs/serialization/doc/tutorial.html>
You might want to check out [protocol buffer](http://code.google.com/p/protobuf/).
Simple anonymous pipes - what wrapper model you use? (WinAPI, C++)
[ "", "c++", "winapi", "oop", "ipc", "pipe", "" ]
My question is whether or not Flex's fcsh can be called from within a PHP script. Here is the background: I have been created a simple process that creates a simple quiz/tutorial by converting a text file into a .mxml file and compiling to a .swf file using the mxmlc compiler. This works well from the command line, but I wanted to make the process easier by creating a web-interface to do this. My initial attempts with PHP's exec() function have not worked. The Python scripts I use to create the .mxml file work fine (using exec()), but I have not been able to get the mxmlc compiler to work. After searching on the Web and on this site, I believe that using fcsh (instead of mxmlc) may be the way to go. Using fcsh would certainly compile the .mxml file faster (after the first run), and I think that fcsh can be launched as a service that might be able to be called from PHP. On the other hand, maybe I am approaching this the wrong way. Would it be better to write a Flex application that calls fcsh and avoid using PHP? **Edit:** Using fcshctl as hasseg suggested in his answer below worked very well. Thanks Ali.
The problem with calling fcsh from within scripts is that it works as an *interactive shell* instead of taking command-line arguments, compiling, and returning an exit status. There are different ways to get around this, which I've listed in [this blog post of mine](http://hasseg.org/blog/?p=194), where I mainly talk about `fcshctl` (which is my own solution for this,) but at the bottom of the post I've also listed other similar solutions to get fcsh integrated into nonstandard build workflows.
There are a few other ways in php to execute an external script. They are exec(), passthru(), system(), and backticks i.e. the key to the left of the 1 key. Each one has a different purpose and return mechanism. You may have to put the command that executes your executable into a script and call that script via one of these functions.
Calling fcsh from PHP script
[ "", "php", "apache-flex", "fcsh", "" ]
Is there some way to catch exceptions which are otherwise unhandled (including those thrown outside the catch block)? I'm not really concerned about all the normal cleanup stuff done with exceptions, just that I can catch it, write it to log/notify the user and exit the program, since the exceptions in these casese are generaly fatal, unrecoverable errors. something like: ``` global_catch() { MessageBox(NULL,L"Fatal Error", L"A fatal error has occured. Sorry for any inconvience", MB_ICONERROR); exit(-1); } global_catch(Exception *except) { MessageBox(NULL,L"Fatal Error", except->ToString(), MB_ICONERROR); exit(-1); } ```
This can be used to catch unexpected exceptions. ``` catch (...) { std::cout << "OMG! an unexpected exception has been caught" << std::endl; } ``` Without a try catch block, I don't think you can catch exceptions, so structure your program so the exception thowing code is under the control of a try/catch.
Check out [`std::set_terminate()`](http://en.cppreference.com/w/cpp/error/set_terminate) Edit: Here's a full-fledged example with exception matching: ``` #include <iostream> #include <exception> #include <stdexcept> struct FooException: std::runtime_error { FooException(const std::string& what): std::runtime_error(what) {} }; int main() { std::set_terminate([]() { try { std::rethrow_exception(std::current_exception()); } catch (const FooException& e) { std::cerr << "Unhandled FooException: " << e.what() << std::endl; } catch (const std::exception& e) { std::cerr << "Unhandled exception: " << e.what() << std::endl; } catch (...) { std::cerr << "Unhandled exception of unknown type" << std::endl; } std::abort(); }); throw FooException("Bad things have happened."); // throw std::runtime_error("Bad things have happened."); // throw 9001; } ```
Catching all unhandled C++ exceptions?
[ "", "c++", "exception", "" ]
Ok, this is working on windows. My Java app is running and functioning normally ``` javac -classpath .;ojdbc14.jar -g foo.java java -classpath .;ojdbc14.jar foo ``` However, when I do the same thing on Unix I get this error: ojdbc14.jar: not found What am I doing wrong? I know the ";" is telling my shell that ojdbc14.jar is a new command, but I'm not sure how to fix this.
Use a colon (":") instead of a semicolon (";"). See [Setting the class path (Solaris and Linux)](http://java.sun.com/javase/6/docs/technotes/tools/solaris/classpath.html) vs [Setting the class path (Windows)](http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html)
The final solution was: ``` javac -classpath .:ojdbc14.jar -g foo.java java -classpath .:ojdbc14.jar foo ``` Note: Using '.;ojdbc14.jar' removed the initial error message I was getting, but resulted in the following errro: ``` Exception in thread "main" java.lang.NoClassDefFoundError: foo ```
Compiling and Running java in Unix ( coming from Windows )
[ "", "java", "bash", "unix", "sh", "" ]
When running FindBugs on my project, I got a few instances of the error described above. Namely, my overriding versions of equals cast the RHS object into the same type as the object in which the overriding version is defined. However, I'm not sure whether a better design is possible, since AFAIK Java does not allow variance in method parameters, so it is not possible to define any other type for the equals parameter. Am I doing something very wrong, or is FindBugs too eager? A different way to phrase this question is: what is the correct behavior if the object passed to equals is not the same type as an LHS: Is this a false, or should there be an exception? For example: ``` public boolean equals(Object rhs) { MyType rhsMyType = (MyType)rhs; // Should throw exception if(this.field1().equals(rhsMyType.field1())... // Or whatever } ```
Typically, when implementing equals you can check to see whether the class of the argument is equal (or compatible) to the implementing class before casting it. Something like this: ``` if (getClass() != obj.getClass()) return false; MyObj myObj = (MyObj) obj; ``` Doing it this way will prevent the FindBugs warning. A side note to address a comment: Some people argue to use `instanceof` instead of `getClass` to check type safety. There is a big debate on that, which I was trying not to get into when I noted that you can check for class equality **or** compatibility, but I guess I can't escape it. It boils down to this - if you use `instanceof` you can support equality between instances of a class and instances of its subclass, but you risk breaking the symmetric contract of `equals`. Generally I would recommend not to use `instanceof` unless you know you need it and you know what you are doing. For more information see: * <http://www.artima.com/weblogs/viewpost.jsp?thread=4744> * [What issues should be considered when overriding equals and hashCode in Java?](https://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java) * <http://www.macchiato.com/columns/Durable5.html> * <http://commons.apache.org/lang/api-release/org/apache/commons/lang/builder/EqualsBuilder.html> (Apache common's implementation helper) * <http://www.eclipsezone.com/eclipse/forums/t92613.rhtml> (Eclipse's default equals generator) * NetBeans generator also uses getClass()
You're probably doing something like this: ``` public class Foo { // some code public void equals(Object o) { Foo other = (Foo) o; // the real equals code } } ``` In this example you are assuming something about the argument of equals(): You are assuming it's of type Foo. This needs not be the case! You can also get a String (in which case you should almost definitely return false). So your code should look like this: ``` public void equals(Object o) { if (!(o instanceof Foo)) { return false; } Foo other = (Foo) o; // the real equals code } ``` (or use the more stringent `getClass() != o.getClass()` mentioned by Dave L. You could also look at it this way: ``` Integer i = new Integer(42); String s = "fourtytwo"; boolean b = i.equals(s); ``` Is there any reason that this code should throw a `ClassCastException` instead of finishing normally and setting `b` to `false`? Throwing a `ClassCastException` as a response to `.equals()` wouldn't be sensible. Because even if it is a stupid question ("Of course a String is never equal to a Foo!") it's still a valid one with a perfectly fine answer ("no" == `false`).
Findbugs warning: Equals method should not assume anything about the type of its argument
[ "", "java", "equals", "findbugs", "" ]
You may have seen JavaScript sliders before: <http://dev.jquery.com/view/tags/ui/1.5b2/demos/ui.slider.html> What I'm envisioning is a circular slider. It would consist of a draggable button at one point on the circle -- and that button can be dragged anywhere along the ring. The value depends on what position the button is at (think of a clock).
define a center point c current mouse point at m in your mouse drag event handler, you'd have ``` var dx = m.x-c.x; var dy = m.y-c.y; var scale = radius/Math.sqrt(dx*dx+dy*dy); slider.x = dx*scale + c.x; slider.y = dy*scale + c.y; ``` radius would be some preset value of the slider,
How about this: <http://www.thewebmasterservice.com/dev-blog/curved-rounded-or-circular-sliders-javascript-jquery-ui> Some explanations and a demo.
jQuery: Creating a circular slider
[ "", "javascript", "jquery", "jquery-ui", "slider", "draggable", "" ]
I'm working on a java program, and I have several vectors defined and filled (from a file) inside a method. I need to return the contents of all the vectors from the method. I have heard you can put them all in one object to return them. Is that possible, and if so, how? If not, do you have any possible solutions for me? Thanks in advance for your help! Here is a code snippet: ``` Object getInventory() { Vector<String> itemID=new Vector<String>(); Vector<String> itemName=new Vector<String>(); Vector<Integer> pOrdered=new Vector<Integer>(); Vector<Integer> pInStore=new Vector<Integer>(); Vector<Integer> pSold=new Vector<Integer>(); Vector<Double> manufPrice=new Vector<Double>(); Vector<Double> sellingPrice=new Vector<Double>(); Object inventoryItem=new Object(); //object to store vectors in try { Scanner infile= new Scanner(new FileReader("Ch10Ex16Data.txt")); int i=0; while (infile.hasNext()) { itemID.addElement(infile.next()); itemName.addElement(infile.next()+infile.nextLine()); pOrdered.addElement(infile.nextInt()); pInStore.addElement(pOrdered.elementAt(i)); pSold.addElement(0); manufPrice.addElement(infile.nextDouble()); sellingPrice.addElement(infile.nextDouble()); i++; } infile.close(); System.out.println(itemID); System.out.println(itemName); System.out.println(pOrdered); System.out.println(pInStore); System.out.println(pSold); System.out.println(manufPrice); System.out.println(sellingPrice); } catch (Exception f) { System.out.print(f); } return inventoryItem; } ```
Personnally, I'd scrap that approach completely. It seems like you need a Product class: ``` public class Product { private String itemName; private int itemID; // etc etc public Product(String itemName, int itemID) { this.itemName = itemName; this.itemID = itemID; // etc etc } public String getItemName() { return itemName; } public int getItemID() { return itemID; } // etc etc } ``` Then something like this : ``` public class Invertory { private List<Product> products = new ArrayList<Product> // etc etc public Inventory(String fileName) throws IOException { // Load file, // Read each product, products.add(new Product(...product arguments); //add to array } public Product[] getProducts() { return products.toArray(new Product[]{}); } ``` }
First of all, use ArrayList instead of Vector. Then use a Map as your return object, with each value of the entry is one of your Lists. Second of all, a much better approach is to create an object that actually holds each of your fields and return a java.util.List of these objects. ``` public class Item { String id; String name Integer pOrdered; Integer inStore; : : ```
Vectors in Java, how to return multiple vectors in an object
[ "", "java", "object", "vector", "" ]
I'm having a difficult time figuring out how to add a .jar/library to a Netbeans project in such a way that I can get it committed to the repository. The typical way to add a library (per the Netbeans documents I've already gone through) ends up with it just being local to me. Anyone who checks out my project ends up missing my required library. Inserting it manually and trying to work around Netbeans results in Netbeans hanging while trying to scan the project... So, how can I tell Netbeans to pick up a jar as a library and include it in my project in such a way that Subversion will be able to handle it?
OK, the working solution that I've now moved to is to extract the class files out of the jars and dump them into the Source Packages area. Then it all gets committed to the repository and also avoids having to deal with handling a separate "lib" directory in the deployment phase. This solution does everything I'm looking for, yet I feel real dirty about doing it this way. It just seems horribly broken and wrong... :-)
There are a couple ways to fix this. A. When you define your Library, use a path to a common location. A location that's identical on everyone's machine--such as the location of a JAR installed with a third-party app into Program Files or /usr/local/ works well or a network drive. Then, when they check-out the code, the path will still be correct and they do not have to define the Library on their Netbeans workspace. B. Edit your project.properties file to use a relative path. Open your project.properties file and look for "`libs.LIBRARY_NAME.classpath=...`". That will be the "default" location used if the Library is not defined. Change this to use a path relative to your project and store the jar files in your project. For example: `libs.Log4J.classpath=lib/log4j.jar` Keep in mind that the Library definition in your Library Manager will override this value--so make sure you keep them in-sync (i.e. append a version number to the library name!). C. Use Vincent's suggestion of using a build-system such as Maven. The Maven build-process will take care of downloading dependencies, etc. Netbeans has plugins for several popular build systems.
Getting Netbeans and Subversion to play together nicely with libraries?
[ "", "java", "svn", "netbeans", "" ]
I'm looking to learn some fundamentals on cartesian geometry or coordinates based game programming. Platform is irrelevant, although I'm most proficient in JavaScript, C, Objective-C. Ultimately being able to create something such as dots or checkers would be ideal. The idea is for me to learn how sprites work and how pathing works programmatically. My question to you folks is where is the best place to learn the fundamentals? Something that isn't math heavy because to be quite frank, anything further advanced than calculus to me at this point is a grey line and requires refreshing my memory. If there is a particular book, site, or open source project -- that would probably help me the most. Thanks for any ideas.
I think there's a few more steps to accomplishing your objective, which is understanding the basics of game programming. You mentioned understanding sprites and pathing, which are imperative to game programming, but I think that initially you should spend a little time understanding the programming and methodology behind general graphical user interaction. Regardless of what language you will eventually program your game in, I think that learning in a modern language like Java or C# will provide you with a vast amount of libraries and will allow you to accomplish tasks like animation and Event Listeners much more simply. Here is a list of guides and tutorials that I think will be extremely helpful to you just as they were to me and others: 1. [This is an extremely-detailed tutorial](http://www3.ntu.edu.sg/home/ehchua/programming/java/J8d_Game_Framework.html) for a Java Game Framework that includes full source code and a full walk through (with source code) of writing the infamous "Snake" game in Java, complete with a control panel, score board, and sound effects! 2. The book ["Beginning Java 5 Game Programming"](https://rads.stackoverflow.com/amzn/click/com/1598631500) by Jonathan S. Harbour will introduce you to concepts such as 2D vector graphics and bitmap including sprite animation. Plus you can get it used on Amazon Marketplace for $12! 3. [Here](http://www.developer.com/java/article.php/893471) is an unbelievable tutorial on Sprite Animation that has more than 5 parts to it! Plus it's written by Richard Baldwin, a Professor of CompSci and an extremely reliable and knowledgeable source. For more tutorials by him, [this is his site.](http://www.geocities.com/Athens/7077/scoop/onjava.html) Between these sources you're going to possess the methodology of the parts that go into a game, which are applicable in any language, as well as the knowledge of how those parts can be actually implemented as well. G'luck!
O'Reilly has a great tutorial on simple game development using Objective-C and Cocoa on the Mac. [Lines of Action.](http://www.oreillynet.com/pub/a/mac/2006/12/19/building-a-game-engine-with-cocoa.html)
Programming coordinates-based game, like dots or checkers
[ "", "javascript", "c", "geometry", "gridworld", "" ]
I'm looking at some open source Java projects to get into Java and notice a lot of them have some sort of 'constants' interface. For instance, [processing.org](http://www.processing.org) has an interface called [PConstants.java](http://dev.processing.org/source/index.cgi/tags/processing-1.0/core/src/processing/core/PConstants.java?view=markup), and most other core classes implement this interface. The interface is riddled with static members. Is there a reason for this approach, or is this considered bad practice? Why not use enums *where it makes sense*, or a static class? I find it strange to use an interface to allow for some sort of pseudo 'global variables'. ``` public interface PConstants { // LOTS OF static fields... static public final int SHINE = 31; // emissive (by default kept black) static public final int ER = 32; static public final int EG = 33; static public final int EB = 34; // has this vertex been lit yet static public final int BEEN_LIT = 35; static public final int VERTEX_FIELD_COUNT = 36; // renderers known to processing.core static final String P2D = "processing.core.PGraphics2D"; static final String P3D = "processing.core.PGraphics3D"; static final String JAVA2D = "processing.core.PGraphicsJava2D"; static final String OPENGL = "processing.opengl.PGraphicsOpenGL"; static final String PDF = "processing.pdf.PGraphicsPDF"; static final String DXF = "processing.dxf.RawDXF"; // platform IDs for PApplet.platform static final int OTHER = 0; static final int WINDOWS = 1; static final int MACOSX = 2; static final int LINUX = 3; static final String[] platformNames = { "other", "windows", "macosx", "linux" }; // and on and on } ```
It's generally considered bad practice. The problem is that the constants are part of the public "interface" (for want of a better word) of the implementing class. This means that the implementing class is publishing all of these values to external classes even when they are only required internally. The constants proliferate throughout the code. An example is the [SwingConstants](http://java.sun.com/javase/6/docs/api/javax/swing/SwingConstants.html) interface in Swing, which is implemented by dozens of classes that all "re-export" *all* of its constants (even the ones that they don't use) as their own. But don't just take my word for it, [Josh Bloch also says](https://rads.stackoverflow.com/amzn/click/com/0321356683) it's bad: > **The constant interface pattern is a poor use of interfaces.** That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface. An enum may be a better approach. Or you could simply put the constants as public static fields in a class that cannot be instantiated. This allows another class to access them without polluting its own API.
Instead of implementing a "constants interface", in Java 1.5+, you can use static imports to import the constants/static methods from another class/interface: ``` import static com.kittens.kittenpolisher.KittenConstants.*; ``` This avoids the ugliness of making your classes implement interfaces that have no functionality. As for the practice of having a class just to store constants, I think it's sometimes necessary. There are certain constants that just don't have a natural place in a class, so it's better to have them in a "neutral" place. But instead of using an interface, use a final class with a private constructor. (Making it impossible to instantiate or subclass the class, sending a strong message that it doesn't contain non-static functionality/data.) Eg: ``` /** Set of constants needed for Kitten Polisher. */ public final class KittenConstants { private KittenConstants() {} public static final String KITTEN_SOUND = "meow"; public static final double KITTEN_CUTENESS_FACTOR = 1; } ```
Interfaces with static fields in java for sharing 'constants'
[ "", "java", "" ]
Can the alignment of a structure type be found if the alignments of the structure members are known? Eg. for: ``` struct S { a_t a; b_t b; c_t c[]; }; ``` is the alignment of S = max(alignment\_of(a), alignment\_of(b), alignment\_of(c))? Searching the internet I found that "for structured types the largest alignment requirement of any of its elements determines the alignment of the structure" (in [What Every Programmer Should Know About Memory](http://people.redhat.com/drepper/cpumemory.pdf)) but I couldn't find anything remotely similar in the standard (latest draft more exactly). --- **Edited:** Many thanks for all the answers, especially to Robert Gamble who provided a really good answer to the original question and the others who contributed. In short: ***To ensure alignment requirements for structure members, the alignment of a structure must be at least as strict as the alignment of its strictest member.*** As for determining the alignment of structure a few options were presented and with a bit of research this is what I found: * c++ std::tr1::alignment\_of + not standard yet, but close (technical report 1), should be in the C++0x + the following restrictions are present in the latest draft: Precondition:T shall be a complete type, a reference type, or an array of unknown bound, but shall not be a function type or (possibly cv-qualified) void. - this means that my presented use case with the C99 flexible array won't work (this is not that surprising since flexible arrays are not standard c++) + in the latest c++ draft it is defined in the terms of a new keyword - alignas (this has the same complete type requirement) + in my opinion, should c++ standard ever support C99 flexible arrays, the requirement could be relaxed (the alignment of the structure with the flexible array should not change based on the number of the array elements) * c++ boost::alignment\_of + mostly a tr1 replacement + seems to be specialized for void and returns 0 in that case (this is forbidden in the c++ draft) + Note from developers: strictly speaking you should only rely on the value of ALIGNOF(T) being a multiple of the true alignment of T, although in practice it does compute the correct value in all the cases we know about. + I don't know if this works with flexible arrays, it should (might not work in general, this resolves to compiler intrinsic on my platform so I don't know how it will behave in the general case) * Andrew Top presented a simple template solution for calculating the alignment in the answers + this seems to be very close to what boost is doing (boost will additionally return the object size as the alignment if it is smaller than the calculated alignment as far as I can see) so probably the same notice applies + this works with flexible arrays * use Windbg.exe to find out the alignment of a symbol + not compile time, compiler specific, didn't test it * using offsetof on the anonymous structure containing the type + see the answers, not reliable, not portable with c++ non-POD * compiler intrinsics, eg. MSVC \_\_alignof + works with flexible arrays + alignof keyword is in the latest c++ draft --- If we want to use the "standard" solution we're limited to std::tr1::alignment\_of, but that won't work if you mix your c++ code with c99's flexible arrays. As I see it there is only 1 solution - use the old struct hack: ``` struct S { a_t a; b_t b; c_t c[1]; // "has" more than 1 member, strictly speaking this is undefined behavior in both c and c++ when used this way }; ``` The diverging c and c++ standards and their growing differences are unfortunate in this case (and every other case). --- Another interesting question is (if we can't find out the alignment of a structure in a portable way) what is the most strictest alignment requirement possible. There are a couple of solutions I could find: * boost (internally) uses a union of variety of types and uses the boost::alignment\_of on it * the latest c++ draft contains std::aligned\_storage + The value of default-alignment shall be the most stringent alignment requirement for any C++ object type whose size is no greater than Len - so the `std::alignment_of< std::aligned_storage<BigEnoughNumber>>::value` should give us the maximum alignment - draft only, not standard yet (if ever), `tr1::aligned_storage` does not have this property Any thoughts on this would also be appreciated. *I have temporarily unchecked the accepted answer to get more visibility and input on the new sub-questions*
There are two closely related concepts to here: 1. The alignment required by the processor to access a particular object 2. The alignment that the compiler actually uses to place objects in memory To ensure alignment requirements for structure members, the alignment of a structure must be at least as strict as the alignment of its strictest member. I don't think this is spelled out explicitly in the standard but it can be inferred from the the following facts (which are spelled out individually in the standard): * Structures **are** allowed to have padding between their members (and at the end) * Arrays are **not** allowed to have padding between their elements * You can create an array of any structure type If the alignment of a structure was not at least as strict as each of its members you would not be able to create an array of structures since some structure members some elements would not be properly aligned. Now the compiler must ensure a minimum alignment for the structure based on the alignment requirements of its members but it can also align objects in a stricter fashion than required, this is often done for performance reasons. For example, many modern processors will allow access to 32-bit integers in any alignment but accesses may be significantly slower if they are not aligned on a 4-byte boundary. There is no portable way to determine the alignment enforced by the processor for any given type because this is not exposed by the language, although since the compiler obviously knows the alignment requirements of the target processor it could expose this information as an extension. There is also no portable way (at least in C) to determine how a compiler will actually align an object although many compilers have options to provide some level of control over the alignment.
I wrote this type trait code to determine the alignment of any type(based on the compiler rules already discussed). You may find it useful: ``` template <class T> class Traits { public: struct AlignmentFinder { char a; T b; }; enum {AlignmentOf = sizeof(AlignmentFinder) - sizeof(T)}; }; ``` So now you can go: ``` std::cout << "The alignment of structure S is: " << Traits<S>::AlignmentOf << std::endl; ```
Determining the alignment of C/C++ structures in relation to its members
[ "", "c++", "c", "alignment", "" ]
There has been a lot of sentiment to include a `nameof` operator in C#. As an example of how this operator would work, `nameof(Customer.Name)` would return the string `"Name"`. I have a domain object. And I have to bind it. And I need names of properties as strings then. And I want them to be type-safe. I remember coming across a workaround in .NET 3.5 which provided the functionality of `nameof` and involved lambda expressions. However, I have not been able to locate this workaround. Can anyone provide that workaround to me? I am also interested in a way to implement the functionality of `nameof` in .NET 2.0 if that is possible.
This code basically does that: ``` class Program { static void Main() { var propName = Nameof<SampleClass>.Property(e => e.Name); Console.WriteLine(propName); } } public class Nameof<T> { public static string Property<TProp>(Expression<Func<T, TProp>> expression) { var body = expression.Body as MemberExpression; if(body == null) throw new ArgumentException("'expression' should be a member expression"); return body.Member.Name; } } ``` (Of course it is 3.5 code...)
While reshefm and Jon Skeet show the proper way to do this using expressions, it should be worth noting there's a cheaper way to do this for method names: Wrap a delegate around your method, get the MethodInfo, and you're good to go. Here's an example: ``` private void FuncPoo() { } ... // Get the name of the function string funcName = new Action(FuncPoo).Method.Name; ``` Unfortunately, this works only for methods; it does not work for properties, as you cannot have delegates to property getter or setter methods. (Seems like a silly limitation, IMO.)
Workaround for lack of 'nameof' operator in C# for type-safe databinding?
[ "", "c#", ".net", "data-binding", ".net-3.5", ".net-2.0", "" ]
I am working on a C++ app which internally has some controller objects that are created and destroyed regularly (using new). It is necessary that these controllers register themselves with another object (let's call it controllerSupervisor), and unregister themselves when they are destructed. The problem I am now facing is happening when I quit the application: as order of destruction is not deterministic, it so happens that the single controllerSupervisor instance is destructed prior to (some) of the controllers themselves, and when they call the unregister method in their destructor, they do so upon an already destructed object. The only idea I came up with so far (having a big cold, so this may not mean much) is not having the controllerSupervisor as a global variable on the stack, but rather on the heap (i.e. using new). However in that case I do not have a place to delete it (this is all in a 3rd party kind of library). Any hints/suggestions on what possible options are would be appreciated.
You could use the Observer pattern. A Controller communicates to it's supervisor that it's being destroyed. And the Supervisor communicates the same to it's child upon destruction. Take a look at <http://en.wikipedia.org/wiki/Observer_pattern>
The order of destruction of automatic variables (that include "normal" local variables that you use in functions) is in the reverse order of their creation. So place the controllerSupervisor at the top. Order of destruction of globals is also in the reverse of their creation, which in turn depends on the order in which they are defined: Later defined objects are created later. But beware: Objects defined in different .cpp files (translation units) are not guaranteed to created in any defined order. I think you should consider using it how Mike recommended: 1. Creation is done by using the singleton pattern (since initialization order of objects in different translation units are not defined) on first use, by returning a pointer to a function-static supervisor object. 2. The supervisor is normally destructed (using the rules about destruction of statics in functions). controllers deregister using a static function of the supervisor. That one checks whether the supervisor is already destructed (checking a pointer for `!= 0`). If it is, then nothing is done. Otherwise the supervisor is notified. Since i imagine there could be a supervisor without a controller being connected (and if only temporary), a smart pointer could not be used to destruct the supervisor automatically.
Forcing something to be destructed last in C++
[ "", "c++", "destructor", "" ]
I have a deceptively simple scenario, and I want a simple solution, but it's not obvious which is "most correct" or "most Java". Let's say I have a small authenticate(Client client) method in some class. The authentication could fail for a number of reasons, and I want to return a simple boolean for control flow, but also return a String message for the user. These are the possibilities I can think of: * Return a boolean, and pass in a StringBuilder to collect the message. This is the closest to a C-style way of doing it. * Throw an exception instead of returning false, and include the message. I don't like this since failure is not exceptional. * Create a new class called AuthenticationStatus with the boolean and the String. This seems like overkill for one small method. * Store the message in a member variable. This would introduce a potential race condition, and I don't like that it implies some state that isn't really there. Any other suggestions? **Edit** Missed this option off * Return null for success - Is this unsafe? **Edit** Solution: I went for the most OO solution and created a small AuthenticationResult class. I wouldn't do this in any other language, but I like it in Java. I also liked the suggestion of returning an String[] since it's like the null return but safer. One advantage of the Result class is that you can have a success message with further details if required.
Returning a small object with both the boolean flag and the String inside is probably the most OO-like way of doing it, although I agree that it seems overkill for a simple case like this. Another alternative is to always return a String, and have null (or an empty String - you choose which) indicate success. As long as the return values are clearly explained in the javadocs there shouldn't be any confusion.
You could use exceptions.... ``` try { AuthenticateMethod(); } catch (AuthenticateError ae) { // Display ae.getMessage() to user.. System.out.println(ae.getMessage()); //ae.printStackTrace(); } ``` and then if an error occurs in your AuthenticateMethod you send a new AuthenticateError (extends Exception)
Best way to return status flag and message from a method in Java
[ "", "java", "exception", "return-value", "" ]
At work we recently upgraded from Microsoft SQL Server 7 to SQL 2005. The database engine is a lot more advanced, but the management studio is pretty awful in a number of ways. Most of our developers decided they preferred to stick with the old Query Analyzer tool, even though it had a lot of limitations. In my spare time, I decided to write a replacement for Query Analyzer / Management Studio that did the things our developers most needed to do. I finally got permission to release it for free: Versabanq Squel (versabanq.com/squel). Like I said, it's free, so this isn't a sales pitch. But it got me thinking. What I'm wondering is: are most of you satisfied with SQL Studio the way it is? Do people just use it because it's what Microsoft pushes on them? Are there many people out there looking for something better? Maybe I can get some support for long-term development of this, if it looks like there might be some wider interest. By the way, check out [SQL Server Management Studio Alternatives](https://stackoverflow.com/questions/5170/sql-server-management-studio-alternatives), someone else's earlier question on this topic. What I see there is that there are surprisingly few options. Why do you think that is?
While I would love something better, it would have to be significantly better and free. SMS is definetly a hog but I've gotten used to it. What I miss the most is Query Analyzer. I don't mind using SSMS to manage the server but having a fast lightweight, editor for SQL queries would be awsome... Did I mention free? Not something I'm willing to pay for right now. # EDIT FYI I downloaded your tool looks neat but you need to add support for Windows Authentications unless I am just missing how its done.
Ha, I came from exactly the same standpoint, so I made a tool, code completion and all, plus there's a free edition available. It's at <http://www.atlantis-interactive.co.uk> - it's basically for people who miss QA. Your tool looks nice, good job.
Would you consider using an alternative to MS SQL Server Management Studio?
[ "", "sql", "sql-server", "sql-server-2005", "query-analyzer", "" ]
MySQL ResultSets are by default retrieved completely from the server before any work can be done. In cases of huge result sets this becomes unusable. I would like instead to actually retrieve the rows one by one from the server. In Java, following the instructions [here](http://dev.mysql.com/doc/refman/5.1/en/connector-j-reference-implementation-notes.html) (under "ResultSet"), I create a statement like this: ``` stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY); stmt.setFetchSize(Integer.MIN_VALUE); ``` This works nicely in Java. My question is: is there a way to do the same in python? One thing I tried is to limit the query to a 1000 rows at a time, like this: ``` start_row = 0 while True: cursor = conn.cursor() cursor.execute("SELECT item FROM items LIMIT %d,1000" % start_row) rows = cursor.fetchall() if not rows: break start_row += 1000 # Do something with rows... ``` However, this seems to get slower the higher start\_row is. And no, using `fetchone()` instead of `fetchall()` doesn't change anything. ## Clarification: The naive code I use to reproduce this problem looks like this: ``` import MySQLdb conn = MySQLdb.connect(user="user", passwd="password", db="mydb") cur = conn.cursor() print "Executing query" cur.execute("SELECT * FROM bigtable"); print "Starting loop" row = cur.fetchone() while row is not None: print ", ".join([str(c) for c in row]) row = cur.fetchone() cur.close() conn.close() ``` On a ~700,000 rows table, this code runs quickly. But on a ~9,000,000 rows table it prints "Executing Query" and then hangs for a long long time. That is why it makes no difference if I use `fetchone()` or `fetchall()`.
I think you have to connect passing `cursorclass = MySQLdb.cursors.SSCursor`: ``` MySQLdb.connect(user="user", passwd="password", db="mydb", cursorclass = MySQLdb.cursors.SSCursor ) ``` The default cursor fetches all the data at once, even if you don't use `fetchall`. Edit: `SSCursor` or any other cursor class that supports server side resultsets - check the module docs on `MySQLdb.cursors`.
The limit/offset solution runs in quadratic time because mysql has to rescan the rows to find the offset. As you suspected, the default cursor stores the entire result set on the client, which may consume a lot of memory. Instead you can use a server side cursor, which keeps the query running and fetches results as necessary. The cursor class can be customized by supplying a default to the connection call itself, or by supplying a class to the cursor method each time. ``` from MySQLdb import cursors cursor = conn.cursor(cursors.SSCursor) ``` But that's not the whole story. In addition to storing the mysql result, the default client-side cursor actually fetches every row regardless. This behavior is undocumented, and very unfortunate. It means full python objects are created for all rows, which consumes far more memory than the original mysql result. In most cases, a result stored on the client wrapped as an iterator would yield the best speed with reasonable memory usage. But you'll have to roll your own if you want that.
How to get a row-by-row MySQL ResultSet in python
[ "", "python", "mysql", "" ]
Similar to [this question](https://stackoverflow.com/questions/85978/query-a-tables-foreign-key-relationships) but for MySQL.... How can I programmatically determine foreign key references in MySQL (assuming InnoDB)? I can almost get them with: ``` SHOW TABLE STATUS WHERE Name = 'MyTableName'; ``` ...but alas, the comment column which seems to contain some of this info gets truncated so I can't rely on it. There must be some other way... I'd be happy with a C API call, a SQL statement, anything--I just need something that consistently works. Note: I've also considered parsing the results of a "SHOW CREATE TABLE MyTableName" statement, but I'm really hoping there's something simpler.
There are two tables you can query to get this information: [`INFORMATION_SCHEMA.TABLE_CONSTRAINTS`](http://dev.mysql.com/doc/refman/5.1/en/table-constraints-table.html) and [`INFORMATION_SCHEMA.KEY_COLUMN_USAGE`](http://dev.mysql.com/doc/refman/5.1/en/key-column-usage-table.html). Here's a query from the comments on the latter page linked above, which demonstrates how to get the info you seek. ``` SELECT CONCAT( table_name, '.', column_name, ' -> ', referenced_table_name, '.', referenced_column_name ) AS list_of_fks FROM INFORMATION_SCHEMA.key_column_usage WHERE referenced_table_schema = 'test' AND referenced_table_name IS NOT NULL ORDER BY table_name, column_name; ``` Use your schema name instead of '`test`' above.
Here you have a little improvement over the @bill solution: ``` SELECT CONSTRAINT_SCHEMA AS db, CONCAT ( TABLE_NAME, '.', COLUMN_NAME, ' -> ', REFERENCED_TABLE_NAME, '.', REFERENCED_COLUMN_NAME ) AS relationship FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_NAME = 'your_table_name' ORDER BY CONSTRAINT_SCHEMA, TABLE_NAME, COLUMN_NAME; ``` In this case I was filtering by relationships with the "your\_table\_name" fields and seeing from which database the relationship comes.
MySQL: How to determine foreign key relationships programmatically?
[ "", "sql", "mysql", "c", "foreign-keys", "" ]
How do I append an object (such as a string or number) to an array in JavaScript?
Use the [`Array.prototype.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) method to append values to the end of an array: ``` // initialize array var arr = [ "Hi", "Hello", "Bonjour" ]; // append new value to the array arr.push("Hola"); console.log(arr); ``` --- You can use the `push()` function to append more than one value to an array in a single call: ``` // initialize array var arr = ["Hi", "Hello", "Bonjour", "Hola"]; // append multiple values to the array arr.push("Salut", "Hey"); // display all values for (var i = 0; i < arr.length; i++) { console.log(arr[i]); } ``` Note that the `push()` method returns the updated length of the array. --- **Update** If you want to add the items of one array to another array, you can use [`firstArray.concat(secondArray)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat): ``` var arr = [ "apple", "banana", "cherry" ]; // Do not forget to assign the result as, unlike push, concat does not change the existing array arr = arr.concat([ "dragonfruit", "elderberry", "fig" ]); console.log(arr); ``` **Update** Just an addition to this answer if you want to prepend any value to the start of an array (i.e. first index) then you can use [`Array.prototype.unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) for this purpose. ``` var arr = [1, 2, 3]; arr.unshift(0); console.log(arr); ``` It also supports appending multiple values at once just like `push`. --- **Update** Another way with ***ES6*** syntax is to return a new array with the ***[spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)***. This leaves the original array unchanged, but returns a new array with new items appended or prepended, compliant with the spirit of functional programming. ``` const arr = [ "Hi", "Hello", "Bonjour", ]; const newArr1 = [ ...arr, "Salut", ]; const newArr2 = [ "Salut", ...arr, ]; console.log(newArr1, newArr2); ```
If you're only appending a single variable, then `push()` works just fine. If you need to append another array, use `concat()`: ``` var ar1 = [1, 2, 3]; var ar2 = [4, 5, 6]; var ar3 = ar1.concat(ar2); alert(ar1); alert(ar2); alert(ar3); ``` The concat does not affect `ar1` and `ar2` unless reassigned, for example: ``` var ar1 = [1, 2, 3]; var ar2 = [4, 5, 6]; ar1 = ar1.concat(ar2); alert(ar1); ``` There is a lot of great information on *[JavaScript Reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference)*.
How to append something to an array?
[ "", "javascript", "arrays", "append", "" ]
I wrote a `while loop` in a function, but don't know how to stop it. When it doesn't meet its final condition, the loop just go for ever. How can I stop it? ``` def determine_period(universe_array): period=0 tmp=universe_array while True: tmp=apply_rules(tmp)#aplly_rules is a another function period+=1 if numpy.array_equal(tmp,universe_array) is True: break #i want the loop to stop and return 0 if the #period is bigger than 12 if period>12: #i wrote this line to stop it..but seems it #doesnt work....help.. return 0 else: return period ```
just indent your code correctly: ``` def determine_period(universe_array): period=0 tmp=universe_array while True: tmp=apply_rules(tmp)#aplly_rules is a another function period+=1 if numpy.array_equal(tmp,universe_array) is True: return period if period>12: #i wrote this line to stop it..but seems its doesnt work....help.. return 0 else: return period ``` You need to understand that the `break` statement in your example will exit the infinite loop you've created with `while True`. So when the break condition is True, the program will quit the infinite loop and continue to the next indented block. Since there is no following block in your code, the function ends and don't return anything. So I've fixed your code by replacing the `break` statement by a `return` statement. Following your idea to use an infinite loop, this is the best way to write it: ``` def determine_period(universe_array): period=0 tmp=universe_array while True: tmp=apply_rules(tmp)#aplly_rules is a another function period+=1 if numpy.array_equal(tmp,universe_array) is True: break if period>12: #i wrote this line to stop it..but seems its doesnt work....help.. period = 0 break return period ```
``` def determine_period(universe_array): period=0 tmp=universe_array while period<12: tmp=apply_rules(tmp)#aplly_rules is a another function if numpy.array_equal(tmp,universe_array) is True: break period+=1 return period ```
How can I stop a While loop?
[ "", "python", "while-loop", "" ]
I think I've declared a Vector with an object correctly. But, I don't know how to access it's members when looping with Iterator. In my code, the line --->> cout << " " << \*Iter; How do I print the contents of the members? Like \*Iter.m\_PackLine ??? Not sure if I used the correct terminology, but appreciate the help! Thanks ``` class CFileInfo { public: std::string m_PackLine; std::string m_FileDateTime; int m_NumDownloads; }; void main() { CFileInfo packInfo; vector<CFileInfo, CFileInfo&> unsortedFiles; vector<CFileInfo, CFileInfo&>::iterator Iter; packInfo.m_PackLine = "Sample Line 1"; packInfo.m_FileDateTime = "06/22/2008 04:34"; packInfo.m_NumDownloads = 0; unsortedFiles.push_back(packInfo); packInfo.m_PackLine = "Sample Line 2"; packInfo.m_FileDateTime = "12/05/2007 14:54"; packInfo.m_NumDownloads = 1; unsortedFiles.push_back(packInfo); for (Iter = unsortedFiles.begin(); Iter != unsortedFiles.end(); Iter++ ) { cout << " " << *Iter; // !!! THIS IS WHERE I GET STUMPED // How do I output values of the object members? } } // end main ```
``` cout << " " << *Iter; ``` will only work if `CFileInfo` has an overloaded `operator<<` that can output your struct. You can output individual members of the struct instead like this: ``` cout << " " << Iter->m_PackLine; ``` Alternatively, the following is equivalent to that: ``` cout << " " << (*Iter).m_PackLine; ``` You have to put parentheses around \*Iter, since the member-access operator binds thighter otherwise. On a side-node, make your main function return int instead of void. making it return void is not valid in C++. --- You declare the vector like this: ``` vector<CFileInfo, CFileInfo&> unsortedFiles; ``` The second argument to `vector` should be another thing. It's not needed for your code to give the vector a second argument at all. Just use this: ``` vector<CFileInfo> unsortedFiles; ``` --- Another thing i noticed is you increment the iterator using `Iter++` (called `postfix increment`). For iterators, always prefer `++Iter`, which is called `prefix increment`.
Use (\*iter).member or iter->member. You can also use temporaries: ``` CFileInfo &fileInfo = *iter; cout << " " << fileInfo.myMember; ``` Also, for what you're doing, you'd probably want a const\_iterator instead of an (mutable) iterator. In addition, std::vector is a template accepting a typename and an allocator, not two typenames. You can use the default allocator by stripping the second template argument: ``` vector<CFileInfo> unsortedFiles; vector<CFileInfo>::iterator Iter; ``` --- Some nit-picking: * main should return an int. * It'd probably be best to declare your iterator variable in the for statement. * It'd probably be faster in run-time performance to use the prefix ++ operator (++iter) instead of the postfix operator (iter++) in your for loop. * No need for your comment about main() ending.
C++ STL Vector Iterator accessing members of an Object
[ "", "c++", "" ]
There's an existing function that ends in the following, where `d` is a dictionary: ``` return d.iteritems() ``` that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items sorted *by key*. How do I do that?
Haven't tested this very extensively, but works in Python 2.5.2. ``` >>> d = {"x":2, "h":15, "a":2222} >>> it = iter(sorted(d.iteritems())) >>> it.next() ('a', 2222) >>> it.next() ('h', 15) >>> it.next() ('x', 2) >>> ``` If you are used to doing `for key, value in d.iteritems(): ...` instead of iterators, this will still work with the solution above ``` >>> d = {"x":2, "h":15, "a":2222} >>> for key, value in sorted(d.iteritems()): >>> print(key, value) ('a', 2222) ('h', 15) ('x', 2) >>> ``` With Python 3.x, use `d.items()` instead of `d.iteritems()` to return an iterator.
Use the [`sorted()`](http://pydoc.org/2.5.1/__builtin__.html#-sorted) function: ``` return sorted(dict.iteritems()) ``` If you want an actual iterator over the sorted results, since `sorted()` returns a list, use: ``` return iter(sorted(dict.iteritems())) ```
In Python, how do I iterate over a dictionary in sorted key order?
[ "", "python", "sorting", "dictionary", "" ]
I'm currently working with a specialized, interpreted, programming language implemented in Java. As a very small part of the language, I'd like to add the ability to make calls into Java. Before I dive into all of the nitty-gritty of reflection, I was wondering if anyone knew of a general library for doing the "back-end" part of invoking Java code reflectively. That is, I parse a string (I define the grammar) into some data structure that represents a Java method call (or constructor, or field access) and then pass that data structure to this library that invokes the call and returns the result. In particular, I'd like it to already handle all the edge cases that I don't want to figure out: * Automagically pick the right method based on the types of arguments (like an intelligent Class.getDeclaredMethod()) * Handle distinction between arrays and normal object references * etc I've spent a little time looking at the implementations of dynamic languages on the JVM, but these are generally much more complicated than I'm looking for, or highly optimized for the particular language. Another option is to convert my grammar into a string in some dynamic language and invoke it with Rhino or something, but that's a little more overhead than I'm looking for.
Just a comment to your own answer; actually beanutils has support for getting "a close match" given a set of parameters. See [getMatchingAccessibleMethod()](http://commons.apache.org/beanutils/v1.8.0/apidocs/org/apache/commons/beanutils/MethodUtils.html#getMatchingAccessibleMethod(java.lang.Class,%20java.lang.String,%20java.lang.Class[])) BeanUtils is really powerful and has lots of utility methods for inspecting classes. The same support is naturally available for constructors.
Try the [FEST Reflection](https://github.com/alexruiz/fest-reflect) module. It's a fluent way to do Java reflection. For example: ``` String name = method("get").withReturnType(String.class) .withParameterTypes(int.class) .in(names) .invoke(8); ```
Is there a general "back-end" library for Java reflection
[ "", "java", "reflection", "dynamic", "invoke", "" ]
I have four tables containing exactly the same columns, and want to create a view over all four so I can query them together. Is this possible? (for tedious reasons I cannot/am not permitted to combine them, which would make this irrelevant!)
Assuming that in addition to having the same column names, columns of the same contain the same data, you want to create a view that is the union of all those tables. Something like the following should work, but my SQL is rusty: ``` (CREATE VIEW view_name AS (SELECT * FROM table1 UNION SELECT * FROM table2 UNION SELECT * FROM table3)); ```
It may be worth noting that you might need to use "union all" to preserve unique rows which may exist in more than one of the tables. A standard union will remove duplicates.
View over multiple tables containing same columns
[ "", "sql", "database", "union", "" ]
I don't think that this is specific to a language or framework, but I am using xUnit.net and C#. I have a function that returns a random date in a certain range. I pass in a date, and the returning date is always in range of 1 to 40 years before the given date. Now I just wonder if there is a good way to unit test this. The best approach seems to be to create a loop and let the function run i.e. 100 times and assert that every of these 100 results are in the desired range, which is my current approach. I also realize that unless I am able to control my Random generator, there will not be a perfect solution (after all, the result IS random), but I wonder what approaches you take when you have to test functionality that returns a random result in a certain range?
In addition to testing that the function returns a date in the desired range, you want to ensure that the result is well-distributed. The test you describe would pass a function that simply returned the date you sent in! So in addition to calling the function multiple times and testing that the result stays in the desired range, I would also try to assess the distribution, perhaps by putting the results in buckets and checking that the buckets have roughly equal numbers of results after you are done. You may need more than 100 calls to get stable results, but this doesn't sound like an expensive (run-time wise) function, so you can easily run it for a few K iterations. I've had a problem before with non-uniform "random" functions.. they can be a real pain, it's worth testing for early.
Mock or fake out the random number generator Do something like this... I didn't compile it so there might be a few syntax errors. ``` public interface IRandomGenerator { double Generate(double max); } public class SomethingThatUsesRandom { private readonly IRandomGenerator _generator; private class DefaultRandom : IRandomGenerator { public double Generate(double max) { return (new Random()).Next(max); } } public SomethingThatUsesRandom(IRandomGenerator generator) { _generator = generator; } public SomethingThatUsesRandom() : this(new DefaultRandom()) {} public double MethodThatUsesRandom() { return _generator.Generate(40.0); } } ``` In your test, just fake or mock out the IRandomGenerator to return something canned.
Unit Testing with functions that return random results
[ "", "c#", ".net", "unit-testing", "xunit.net", "" ]
How would I accomplish displaying a line as the one below in a console window by writing it into a variable during design time then just calling Console.WriteLine(sDescription) to display it? ``` Options: -t Description of -t argument. -b Description of -b argument. ```
If I understand your question right, what you need is the @ sign in front of your string. This will make the compiler take in your string literally (including newlines etc) In your case I would write the following: ``` String sDescription = @"Options: -t Description of -t argument."; ``` So far for your question (I hope), but I would suggest to just use several WriteLines. The performance loss is next to nothing and it just is more adaptable. You could work with a format string so you would go for this: ``` string formatString = "{0:10} {1}"; Console.WriteLine("Options:"); Console.WriteLine(formatString, "-t", "Description of -t argument."); Console.WriteLine(formatString, "-b", "Description of -b argument."); ``` the formatstring makes sure your lines are formatted nicely without putting spaces manually and makes sure that if you ever want to make the format different you just need to do it in one place.
``` Console.Write("Options:\n\tSomething\t\tElse"); ``` produces ``` Options: Something Else ``` \n for next line, \t for tab, for more professional layouts try the field-width setting with format specifiers. <http://msdn.microsoft.com/en-us/library/txafckwd.aspx>
C#: How do you go upon constructing a multi-lined string during design time?
[ "", "c#", "" ]
Is it possible to overload the null-coalescing operator for a class in C#? Say for example I want to return a default value if an instance is null and return the instance if it's not. The code would look like something like this: ``` return instance ?? new MyClass("Default"); ``` But what if I would like to use the null-coalescing operator to also check if the MyClass.MyValue is set?
Good question! It's not listed one way or another in the [list of overloadable and non-overloadable operators](http://msdn.microsoft.com/en-us/library/8edha89s.aspx) and nothing's mentioned on [the operator's page](http://msdn.microsoft.com/en-us/library/ms173224.aspx). So I tried the following: ``` public class TestClass { public static TestClass operator ??(TestClass test1, TestClass test2) { return test1; } } ``` and I get the error "Overloadable binary operator expected". So I'd say the answer is, as of .NET 3.5, a no.
According to the [ECMA-334](http://www.ecma-international.org/publications/standards/Ecma-334.htm) standard, it is not possible to overload the ?? operator. Similarly, you cannot overload the following operators: * = * && * || * ?: * ?. * checked * unchecked * new * typeof * as * is
Possible to overload null-coalescing operator?
[ "", "c#", ".net", "operator-overloading", "null-coalescing-operator", "" ]
Is this defined by the language? Is there a defined maximum? Is it different in different browsers?
JavaScript has two number types: [`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) and [`BigInt`](https://developer.mozilla.org/en-US/docs/Glossary/BigInt). The most frequently-used number type, `Number`, is a 64-bit floating point [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754) number. The largest exact integral value of this type is [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER), which is: * 253-1, or * +/- 9,007,199,254,740,991, or * nine quadrillion seven trillion one hundred ninety-nine billion two hundred fifty-four million seven hundred forty thousand nine hundred ninety-one To put this in perspective: one quadrillion bytes is a petabyte (or one thousand terabytes). "Safe" in this context refers to the ability to represent integers exactly and to correctly compare them. [From the spec:](https://www.ecma-international.org/ecma-262/10.0/index.html#sec-ecmascript-language-types-number-type) > Note that all the positive and negative integers whose magnitude is no > greater than 253 are representable in the `Number` type (indeed, the > integer 0 has two representations, +0 and -0). To safely use integers larger than this, you need to use [`BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt), which has no upper bound. Note that the bitwise operators and shift operators operate on 32-bit integers, so in that case, the max safe integer is 231-1, or 2,147,483,647. ``` const log = console.log var x = 9007199254740992 var y = -x log(x == x + 1) // true ! log(y == y - 1) // also true ! // Arithmetic operators work, but bitwise/shifts only operate on int32: log(x / 2) // 4503599627370496 log(x >> 1) // 0 log(x | 1) // 1 ``` --- Technical note on the subject of the number 9,007,199,254,740,992: There is an exact IEEE-754 representation of this value, and you can assign and read this value from a variable, so for *very carefully* chosen applications in the domain of integers less than or equal to this value, you could treat this as a maximum value. In the general case, you must treat this IEEE-754 value as inexact, because it is ambiguous whether it is encoding the logical value 9,007,199,254,740,992 or 9,007,199,254,740,993.
**>= ES6:** ``` Number.MIN_SAFE_INTEGER; Number.MAX_SAFE_INTEGER; ``` **<= ES5** From [the reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE): ``` Number.MAX_VALUE; Number.MIN_VALUE; ``` ``` console.log('MIN_VALUE', Number.MIN_VALUE); console.log('MAX_VALUE', Number.MAX_VALUE); console.log('MIN_SAFE_INTEGER', Number.MIN_SAFE_INTEGER); //ES6 console.log('MAX_SAFE_INTEGER', Number.MAX_SAFE_INTEGER); //ES6 ```
What is JavaScript's highest integer value that a number can go to without losing precision?
[ "", "javascript", "math", "browser", "cross-browser", "" ]
In my program I have one array with 25 double values 0.04 When I try to sum these values in a loop I get following results: ``` 0.0 + 0.04 = 0.04 0.04 + 0.04 = 0.08 0.08 + 0.04 = 0.12 0.12 + 0.04 = 0.16 0.16 + 0.04 = 0.2 0.2 + 0.04 = 0.24000000000000002 0.24000000000000002 + 0.04 = 0.28 0.28 + 0.04 = 0.32 0.32 + 0.04 = 0.36 0.36 + 0.04 = 0.39999999999999997 0.39999999999999997 + 0.04 = 0.43999999999999995 0.43999999999999995 + 0.04 = 0.4799999999999999 0.4799999999999999 + 0.04 = 0.5199999999999999 0.5199999999999999 + 0.04 = 0.5599999999999999 0.5599999999999999 + 0.04 = 0.6 0.6 + 0.04 = 0.64 0.64 + 0.04 = 0.68 0.68 + 0.04 = 0.7200000000000001 0.7200000000000001 + 0.04 = 0.7600000000000001 0.7600000000000001 + 0.04 = 0.8000000000000002 0.8000000000000002 + 0.04 = 0.8400000000000002 0.8400000000000002 + 0.04 = 0.8800000000000002 0.8800000000000002 + 0.04 = 0.9200000000000003 0.9200000000000003 + 0.04 = 0.9600000000000003 ``` Why on earth could that happen?!
The most common storage for floating-point values in programming languages - [IEEE singles and doubles](http://en.wikipedia.org/wiki/IEEE_754) - does not have exact representations for most decimal fractions. The reason is that they store values in binary floating-point format, rather than decimal floating-point format. The only fractional values which can be represented exactly are those which are sums of negative powers of two. Numbers like: * 0.5 (2^-1) * 0.125 (2^-3) * 0.625 (2^-1 + 2^-3) Etc. What you are seeing is the fact that representations of numbers like 0.96 are not exactly representable, because they are not expressible as a sum of negative powers of two. Thus, when printed out with full precision as a decimal fraction, they won't match the original value.
See also "[What Every Computer Scientist Should Know About Floating Point](http://docs.sun.com/source/806-3568/ncg_goldberg.html)"
Strange floating-point behaviour in a Java program
[ "", "java", "math", "" ]
I've used boost serialization but this doesn't appear to allow me to generate xml that conforms to a particular schema -- it seems it's purpose was to just to persist a class's state. Platform: linux What do you guys use to generate NOT parse xml? So far I'm going down Foredecker's route of just generating it myself -- it's not a large document but I really shouldn't be having this much trouble finding a decent library to generate it correctly. As for boost, the things that I would like to be able to do is set the node names, set attributes in my nodes, and get rid of all the extra crap that comes with it as I don't really care about having to put my document back into that class.
Some may declare me an XML heretic - but one effective way is to just generate it with your favorite string output tools (print, output streams, etc) - this can go to a buffer or a file. Once saved - you really should then validate with a schema before committing it our shipping it off. For one of our projects we have a very simple set of templates for managing begin/end tags and attributes. These each have a stream output operator. This makes it very easy to generate the source XML and debug. This makes the structure of the XML generation code look very much like the XML itself. One advantage of this is that you can generate large amounts of XML efficiently if streaming to a file. You will pay the validation costs later (presumably at a better time for an expensive operation). The downside of this technique is that it is essentially output only. It is not suitable for creating then consuming XML dynamically.
I recently reviewed a bunch of XML libraries specifically for generating XML code. Executive summary: I chose to go with [TinyXML++](http://code.google.com/p/ticpp/). TinyXML++ has decent C++ syntax, is built on the mature [TinyXML](http://www.grinninglizard.com/tinyxml/) C libraries, is free & open source (MIT license) and small. In short, it helps get the job done quickly. Here's a quick snippet: ``` Document doc; Node* root(doc.InsertEndChild(Element("RootNode"))); Element measurements("measurements"); Element tbr("TotalBytesReceived", 12); measurements.InsertEndChild(tbr); root->InsertEndChild(measurements); ``` Which produces: ``` <RootNode> <measurements> <TotalBytesReceived>12</TotalBytesReceived> </measurements> </RootNode> ``` I've been quite happy with it. I reviewed many others; here's some of the better contenders: [Xerces](http://xerces.apache.org/xerces-c/): The king-daddy. Does *everything* (especially when combined with [Xalan](http://xml.apache.org/xalan-c/)) but is heavyweight and forces memory management onto the user. [RapidXML](http://rapidxml.sourceforge.net/): Great for parsing (it's an in-situ parser and is *fast*) but not good for generation since adding nodes to the DOM requires memory management. [Boost.XML](https://svn.boost.org/svn/boost/sandbox/xml/) (proposal): Looks *great* - powerful, excellent C++ syntax. However it hasn't yet gone through the review process, is unsupported and the interface may well change. Almost used it anyway. Looking forward to it's acceptance into Boost. [Libxml](http://xmlsoft.org/)([++](http://libxmlplusplus.sourceforge.net/)): Very good; powerful, decent syntax. But it's large-ish if all you're doing is *generating* XML and is tied to the glibmm library (for ustring). If we were *only* on Linux (like yourself?) I would seriously consider. [XiMOL](http://ximol.sourceforge.net/): Unique stream-based library. This was a little too simplistic for our needs but for basic XML generation you may find it quite useful. The stream syntax is quite neat. Hopefully there's something in there of some use!
what's the easiest way to generate xml in c++?
[ "", "c++", "xml", "serialization", "" ]
For my application, I want a [Combo Box](http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html) that displays its elements when dropped down as a [Tree](http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html). Problem is, I'm not versed well enough in Swing to know how to go about doing this. At least without ending up writing a new widget from scratch, or something to that effect. How would I do something like this without creating one from scratch?
I think I would implement this as a JTree component in a JViewPort, followed by an expansion button. When collapsed, it would look like a combo box. When you click the expansion button, the viewport would expand, allowing you to scroll and select a node in the JTree. When you selected the node, the view port would collapse back to only show the selected node and the expansion button.
Hey, guess what! This is your lucky day. I've used this framework in the past. It is very complete. I didn't know they have this already. [JIDE Soft](http://www.jidesoft.com/) [alt text http://img89.imageshack.us/img89/8324/combotreejj1.png](http://img89.imageshack.us/img89/8324/combotreejj1.png) Is not too expensive, but it will take you some time to understand the API ( it is not that is complex, but they've created a LOT of new stuff )
How do I combine a Combo Box with a Tree in Swing?
[ "", "java", "swing", "combobox", "tree", "" ]