Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
What's the proper way for a Java command line application to do background work without hogging resources? Should it use sleep() in the loop or is there a more elegant/efficient way?
Some heuristics: * Don't attempt to make scheduling decisions in your application. The operating system's scheduler is way better than yours will be. Let it do its job. * Don't poll if you don't have to. For instance, instead of sleeping *n* seconds, then waking up to check a non-blocked socket, block on the socket. This second strategy plays better with the operating system's scheduler. * Don't use an enormous heap if you don't have to, and try not to allocate enormous chunks of memory at one time. A thrashing application tends to have a negative effect on system performance. * Use buffered I/O. Always. If you think you need non-buffered I/O, be absolutely sure you're right. (You're probably wrong.) * Don't spawn a lot of threads. Threads are surprisingly expensive; beyond a certain point, more threads will *reduce* your application's performance profile. If you have lots of work to do concurrently, learn and use `java.util.concurrent`. Of course, this is just a starter list...
I'd only use sleep() if there's no work to be done. For example, if you're doing something like polling a task queue periodically and there's nothing there, sleep for a while then check again, etc. If you're just trying to make sure you don't hog the CPU but you're still doing real work, you could call Thread.yield() periodically. That will relinquish control of the CPU and let other threads run, but it won't put you to sleep. If other processes don't need the CPU you'll get control back and continue to do your work. You can also set your thread to a low priority: myThread.setPriority(Thread.MIN\_PRIORITY); As Ishmael said, don't do this in your main thread. Create a "worker thread" instead. That way your UI (GUI or CLI) will still be responsive.
What's the proper background process behaviour for a non-GUI Java app?
[ "", "java", "background", "" ]
For an ASP.NET C# application, we will need to restrict access based on IP address. What is the best way to accomplish this?
In IIS 7 best way to restrict IP is by using the config file. Full article: <http://boseca.blogspot.com/2010/12/programmatically-addremove-ip-security.html>
One way is using a [HttpModule](http://www.codeproject.com/KB/aspnet/http-module-ip-security.aspx). From the link (in case it ever goes away): ``` /// <summary> /// HTTP module to restrict access by IP address /// </summary> public class SecurityHttpModule : IHttpModule { public SecurityHttpModule() { } public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(Application_BeginRequest); } private void Application_BeginRequest(object source, EventArgs e) { HttpContext context = ((HttpApplication)source).Context; string ipAddress = context.Request.UserHostAddress; if (!IsValidIpAddress(ipAddress)) { context.Response.StatusCode = 403; // (Forbidden) } } private bool IsValidIpAddress(string ipAddress) { return (ipAddress == "127.0.0.1"); } public void Dispose() { /* clean up */ } } ``` Once the HTTP Module class is built you need to register it in the httpModules section of your web.config file, like this: ``` <configuration> <system.web> <httpModules> <add name="SecurityHttpModule" type="SecurityHttpModule"/> </httpModules> </system.web> </configuration> ``` This adds the module to the ASP.NET request pipeline for your web application.
Best way to restrict access by IP address?
[ "", "c#", ".net", "asp.net", "security", "" ]
I am having a couple of issues deciding how best to describe a certain data structure in C# (.NET 3.5). I have to create a class library that creates some text files for the input of a command line program. There are dozens of file types, but most of them have a similar header, footer and a couple of other properties. So a file might look like this: ``` timestamp filename company ....lots of attributes that make up the file body.... footerdetail1 footerdetail2 footerdetail3 ``` Now out of these dozens of file types there are really only three unique header/footer combos. So I want to make a parent class that contains most of the headerItems and footeritems, and then implement the actual file types in a derived class: ``` class BaseFileType { public List<HeaderItems>; public List<BodyItems>; public List<FooterItems>; FileType filetype; String filename; public BaseFileType1 (FileType filetype,String filename) { this.filetype = filetype; this.filename = filename; // add stuff to the header list // add stuff to the footer list } // some methods to find items in the header/ footer lists } class ActualFile1 : BaseFileType { ActualFile() { //add stuff to the bodyitems list } //some other generic methods } ``` The thing is, I want to inherit the contructor from the base class for the derived class, but from what I have read this can not be done. What is the best strategy here? I have seen that I can call the base constructor from my derived class constructor like so: ActualFile() : base (parent parameters) Is this even the best way to go about my task? In the end I am just looking for the best data structures for all of this file information so I dont need to repeat myself when I make these classes. What other alternatives to people thing would work? Have a single FileFactory that spits out classes containing the structure I require?
This looks like something a Template Method would solve... (Finally a place to use a pattern :) ``` public abstract class DocumentGenerator { abstract protected void AddHeader(); abstract protected void AddBody(); abstract protected void AddFooter(); // Template Method http://en.wikipedia.org/wiki/Template_method_pattern public FileInfo Generate(string sFileName) { FileInfo f = null; //create file // either pass in the file to the below methods or use member vars + an additional write step AddHeader(); AddBody(); AddFooter(); // write out everything to the file return f; } } ``` Next for each of the 3 unique combination, intermediate level classes like ``` abstract public class UniqueHeaderFooterCombination1 : DocumentGenerator { protected override void AddHeader() { Console.WriteLine("unique combination1 header"); } protected override void AddFooter() { Console.WriteLine("unique combination1 footer"); } } ``` Finally the concrete classes for each unique filetype ``` public class LetsSayCSVGenerator : UniqueHeaderFooterCombination1 { protected override void AddBody() { Console.WriteLine("csv body items"); } } ``` Couple this with a Factory to return the right type of Generator for a FileType and you're done. ``` abstract class DocumentGeneratorFactory { public static DocumentGenerator GetGenerator(FileType eFileType) { switch (eFileType) { // a hash of FileType => Generator default: return new LetsSayCSVGenerator(); } } } class Program { static void Main(string[] args) { DocumentGenerator d = DocumentGeneratorFactory.GetGenerator(FileType.CSV); FileInfo f = d.Generate("ItsAlive.CSV"); } } ```
As you say, constructors are not inherited. Forcing the derived class to supply the details in the constructor would be the ideal case if you need to know the values during construction. If you don't, consider an abstract property that the derived class must provide: ``` // base-class public abstract FileType FileType {get;} // derived-class public override FileType FileType { get {return FileType.Excel;} // or whatever } ``` Note that unless you document it **very** clearly (and understand the implications) you shouldn't call a virtual method (such as the above) inside the constructor (since the derived type's constructor hasn't executed yet) - but it is fine after that. Since the file-name isn't really dependent on the sub-type, I suspect I would leave that as a ctor parameter either way.
How best to structure class heirachy in C# to enable access to parent class members?
[ "", "c#", "" ]
How do I find out if a class is immutable in C#?
There is `ImmutableObjectAttribute`, but this is rarely used and poorly supported - and of course not enforced (you could mark a mutable object with `[ImmutableObject(true)]`. AFAIK, the only thing this this affects is the way the IDE handles attributes (i.e. to show / not-show the named properties options). In reality, you would have to check the `FieldInfo.IsInitOnly`, but this only applies to truly 100% immutable types (assuming no reflection abuse, etc); it doesn't help with popsicle immutability, nor things that are immutable in practice, but not in their implementation; i.e. they can't be made to be publicly mutable, but in theory the object supports it. A classic example here would be string... everyone "knows" that `string` is immutable... of course, `StringBuilder` **does** mutate a string under the bonnet. No, seriously... It is so hard to define immutability given this, let alone robustly detect it...
Part of the problem is that "immutable" can have multiple meanings. Take, for example, ReadOnlyCollection<T>. We tend to consider it to be immutable. But what if it's a ReadOnlyCollection<SomethingChangeable>? Also, since it's really just a wrapper around an IList I pass in to the constructor, what if I change the original IList? A good approach might be to create an attribute with a name like ReadOnlyAttribute and mark classes you consider to be read-only with it. For classes you don't control, you can also maintain a list of known types that you consider to be immutable. EDIT: For some good examples of different types of immutability, read this series of postings by Eric Lippert: <http://blogs.msdn.com/ericlippert/archive/2007/11/13/immutability-in-c-part-one-kinds-of-immutability.aspx>
How do I find out if a class is immutable in C#?
[ "", "c#", "immutability", "" ]
Since I can't use Microsoft as an example for best practice since their exception messages are stored in resource files out of necessity, I am forced to ask where should exception messages be stored. I figure it's probably one of common locations I thought of * Default resource file * Local constant * Class constant * Global exception message class * Inline as string literals
I may get shot (well, downvoted) for this, but why not "where you create the exception"? ``` throw new InvalidDataException("A wurble can't follow a flurble"); ``` Unless you're going to internationalize the exception messages ([which I suggest you don't](https://stackoverflow.com/questions/474450/should-exception-messages-be-globalized#474468)) do you particularly need them to be constants etc? Where's the benefit?
If your exceptions are strongly typed, you don't need to worry about messages. Messages are for presenting errors to users, and exceptions are for controlling flow in exceptional cases. ``` throw new InvalidOperationException("The Nacho Ordering system is not responding."); ``` could become ``` throw new SystemNotRespondingException("Nacho Ordering"); ``` In the latter case, there's nothing to translate, and therefore no need to worry about localization.
Where Should Exception Messages be Stored
[ "", "c#", "exception", "resources", "" ]
I have a database which is in Access (you can get it [link text](http://cid-84dd6ce2da273835.skydrive.live.com/self.aspx/.Public/Unisa.accdb)). If I run ``` SELECT DISTINCT Spl.Spl_No, Spl.Spl_Name FROM Spl INNER JOIN Del ON Spl.Spl_No = Del.Spl_No WHERE Del.Item_Name <> 'Compass' ``` It provides the names of the suppliers that have never delivered a compass. However you can supposedly do this with a sub-query. So far myself and a few others have not been able to get it right. I did come close with the following, until we added more suppliers then it stopped working ``` SELECT SPL.SPL_Name FROM SPL LEFT JOIN DEL ON Del.SPL_No = SPL.SPL_No WHERE (DEL.Item_Name<>"Compass") OR (DEL.Item_Name IS NULL) GROUP BY SPL.SPL_Name HAVING COUNT(DEL.SPL_No) = 0 ``` So the question: Is this possible to do with a sub-query.
Do you mean something like this? ``` SELECT SPL.SPL_Name FROM SPL WHERE NOT SPL.SPL_no IN (SELECT SPL_no FROM DEL WHERE DEL.Item_Name = "Compass") ```
I think I would go for: ``` SELECT SELECT Spl_No, Spl_Name FROM Spl WHERE Spl_No NOT IN (SELECT Spl_No FROM Del WHERE Item_Name = 'Compass') ```
SQL Sub-Query vs Join Confusion
[ "", "sql", "ms-access", "join", "" ]
I have an array of filenames and need to sort that array by the extensions of the filename. Is there an easy way to do this?
``` Arrays.sort(filenames, new Comparator<String>() { @Override public int compare(String s1, String s2) { // the +1 is to avoid including the '.' in the extension and to avoid exceptions // EDIT: // We first need to make sure that either both files or neither file // has an extension (otherwise we'll end up comparing the extension of one // to the start of the other, or else throwing an exception) final int s1Dot = s1.lastIndexOf('.'); final int s2Dot = s2.lastIndexOf('.'); if ((s1Dot == -1) == (s2Dot == -1)) { // both or neither s1 = s1.substring(s1Dot + 1); s2 = s2.substring(s2Dot + 1); return s1.compareTo(s2); } else if (s1Dot == -1) { // only s2 has an extension, so s1 goes first return -1; } else { // only s1 has an extension, so s1 goes second return 1; } } }); ``` For completeness: [`java.util.Arrays`](http://java.sun.com/javase/6/docs/api/java/util/Arrays.html) and [`java.util.Comparator`](http://java.sun.com/javase/6/docs/api/java/util/Comparator.html).
If I remember correctly, the Arrays.sort(...) takes a Comparator<> that it will use to do the sorting. You can provide an implementation of it that looks at the extension part of the string.
Java sort String array of file names by their extension
[ "", "java", "arrays", "file", "sorting", "filenames", "" ]
* Implemented the **Sink** Class - to receive event notifications from COM Server * Event Interface derives from **IDispatch** I have an issue whereby an **IConnectionPoint::Advise** call returns **E\_NOTIMPL**. This could be because the **connection point** only allows one connection - [MSDN](http://msdn.microsoft.com/en-us/library/ms694318(VS.85).aspx). Note: * COM Server is out-of-process * Pure C++ implementation ## EDIT: **S8.tlh**: C++ source equivalent of Win32 type library S8.tlb: ``` struct __declspec(uuid("090910c3-28c3-45fe-861d-edcf11aa9788")) IS8SimulationEvents : IDispatch { // Methods: HRESULT S8SimulationReset ( ); HRESULT S8SimulationEndRun ( ); HRESULT S8SimulationCustomEvent ( BSTR * TextInfo ); HRESULT S8SimulationOpened ( ); HRESULT S8SimulationEndTrial ( ); HRESULT S8SimulationOEMEvent ( BSTR * TextInfo ); HRESULT S8SimulationReadyToClose ( ); HRESULT S8SimulationUserMessage ( long * Answer, BSTR * TextMsg, long ValidAnswers ); }; ``` Implementation of **Class** Sink - to handle event notifications: ``` class Sink : public IS8SimulationEvents { public: Sink(){ m_dwRefCount = 0; }; ~Sink(){}; /* * IS8SimulationEvent interface functions */ HRESULT S8SimulationEndTrial() { cout << "Simulation complete." << endl; return S_OK;; }; HRESULT S8SimulationOpened() { cout << "Simulation open." << endl; return S_OK; }; HRESULT S8SimulationReadyToClose() { cout << "Simulation ready to close" << endl; return S_OK; }; ULONG STDMETHODCALLTYPE AddRef() { m_dwRefCount++; return m_dwRefCount; }; ULONG STDMETHODCALLTYPE Release() { ULONG l; l = m_dwRefCount--; if (0 == m_dwRefCount) { delete this; } return m_dwRefCount; }; HRESULT STDMETHODCALLTYPE QueryInterface( REFIID iid , void **ppvObject) { m_dwRefCount++; *ppvObject = (void *)this; return S_OK; }; HRESULT STDMETHODCALLTYPE GetTypeInfoCount(UINT *pctinfo) { return E_NOTIMPL; }; HRESULT STDMETHODCALLTYPE GetIDsOfNames( REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId) { return E_NOTIMPL; }; HRESULT STDMETHODCALLTYPE GetTypeInfo( unsigned int iTInfo, LCID lcid, ITypeInfo FAR* FAR* ppTInfo) { return E_NOTIMPL; }; HRESULT STDMETHODCALLTYPE Invoke( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS FAR* pDispParams, VARIANT FAR* pVarResult, EXCEPINFO FAR* pExcepInfo, unsigned int FAR* puArgErr) { HRESULT hresult = S_OK; if (pDispParams) { switch (dispIdMember) { case 1: return S8SimulationEndTrial(); case 2: return S8SimulationOpened(); case 3: return S8SimulationReadyToClose(); default: return E_NOTIMPL; } } return E_NOTIMPL; } private: DWORD m_dwRefCount; public: void SetupConnectionPoint (IS8Simulation *pis8) { HRESULT hresult; IConnectionPointContainer *pContainer = NULL; IConnectionPoint *pConnection = NULL; IUnknown *pSinkUnk = NULL; Sink *pSink = NULL; DWORD dwAdvise; dwAdvise = 0; hresult = pis8->QueryInterface( __uuidof(IConnectionPointContainer), (void **) &pContainer); if (SUCCEEDED(hresult)) { cout << "IConnectionPointContainer inteface supported." << endl; } else { cerr << "Error: No such interface supported." << endl; exit (hresult); } __uuidof(IS8SimulationEvents), &pConnection); switch (HRESULT_CODE(hresult)) { case NOERROR: cout << "Obtained valid interface pointer." << endl; break; case E_POINTER: cerr << "Invalid pointer: the address is not valid." << endl; exit (hresult); break; case CONNECT_E_NOCONNECTION: cerr << "This connectable object not support the " "outgoing interface specified." << endl; exit (hresult); break; case E_UNEXPECTED: default: cerr << "Catastrophic failure." << endl; exit (hresult); break; } pContainer->Release(); hresult = pSink->QueryInterface( __uuidof(IUnknown), (void **)&pSinkUnk); if (FAILED(hresult)) { exit (EXIT_FAILURE); } hresult = pConnection->Advise( pSinkUnk, &dwAdvise); switch (HRESULT_CODE(hresult)) { case NOERROR: cout << "The connection has been established and " "*dwAdvise has the connection token." << endl; break; case E_POINTER: cerr << "Invalid pointer: " "the value pSinkUnk or dwAdvise is not valid." << endl; exit (hresult); break; case CONNECT_E_ADVISELIMIT: cerr << "The connection point has already reached " "its limit of connections and cannot accept " "any more." << endl; exit (hresult); break; case CONNECT_E_CANNOTCONNECT: cerr << "The sink does not support the interface " "required by this connection point." << endl; exit (hresult); break; case E_NOTIMPL: break; case E_UNEXPECTED: default: cerr << "Catastrophic failure." << endl; exit (hresult); break; } return; } }; ``` ## EDIT: Implementation of **IUnknown** Interface in **Sink** Class ``` ULONG STDMETHODCALLTYPE AddRef() { m_dwRefCount++; return m_dwRefCount; }; ULONG STDMETHODCALLTYPE Release() { ULONG l; l = m_dwRefCount--; if (0 == m_dwRefCount) { delete this; } return m_dwRefCount; }; HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) { m_dwRefCount++; *ppvObject = (void *)this; return S_OK; }; ``` **Question:** * How to check if a container supports multiple connections? * If more information is required, please comment accordingly.
## Solved: * Using **pure C++** * No ATL With the following **implementation** of **QI**: ``` HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) { if (iid == __uuidof(IUnknown) || iid == __uuidof(IS8SimulationEvents)) { *ppvObject = (IS8SimulationEvents*)this; } else { *ppvObject = NULL; return E_NOINTERFACE; } m_dwRefCount++; return S_OK; }; ```
Please read the MSDN article again. ``` A connection point that allows only one interface can return E_NOTIMPL FROM the IConnectionPoint::EnumConnections method EnumConnections : E_NOTIMPL The connection point does not support enumeration. ``` IConnectionPoint::Advise is required to reply CONNECT\_E\_ADVISELIMIT when he connection point has already reached its limit of connections and cannot accept any more. -- Michael
How to check if a container supports multiple connections?
[ "", "c++", "visual-studio-2008", "com", "connection-points", "" ]
I am developing a small business application which uses Sqlserver 2005 database. Platform: .Net framework 3.5; Application type: windows application; Language: C# Question: I need to take and restore the backup from my application. I have the required script generated from SSME. How do I run that particular script (or scripts) from my winform application?
You can run these scripts the same way you run a query, only you don't connect to the database you want to restore, you connect to master instead.
For the backup you probably want to use xp\_sqlmaint. It has the handy ability to remove old backups, and it creates a nice log file. You can call it via something like: EXECUTE master.dbo.xp\_sqlmaint N''-S "[ServerName]" [ServerLogonDetails] -D [DatabaseName] -Rpt "[BackupArchive]\BackupLog.txt" [RptExpirationSchedule] -CkDB -BkUpDB "[BackupArchive]" -BkUpMedia DISK [BakExpirationSchedule]'' (replace the [square brackets] with suitable values). Also for the backup you may need to backup the transaction log. Something like: IF DATABASEPROPERTYEX((SELECT db\_name(dbid) FROM master..sysprocesses WHERE spid=@@SPID), ''Recovery'') <> ''SIMPLE'' EXECUTE master.dbo.xp\_sqlmaint N'' -S "[ServerName]" [ServerLogonDetails] -D [DatabaseName] -Rpt "[BackupArchive]\BackupLog\_TRN.txt" [RptExpirationSchedule] -BkUpLog "[BackupArchive]" -BkExt TRN -BkUpMedia DISK [BakExpirationSchedule]'' I'd recommend storing the actual commands you're using in a database table (1 row per command) and use some sort of template replacement scheme to handle the configurable values. This would allow for easy changes to the commands, without needing to deploy new code. For the restore you will need to kill all connections except for internal sql server ones. Basically take the results of "exec sp\_who" and for rows that match on dbname, and have a status that is not "background", and a cmd that is not one of "SIGNAL HANDLER", "LOCK MONITOR", "LAZY WRITER", "LOG WRITER", "CHECKPOINT SLEEP" do a "kill" on the spid (eg: ExecuteNonQuery("kill 1283")). You'll want to trap and ignore any exceptions from the KILL command. There's nothing you can do about them. If the restore cannot proceed because of existing connections it will raise an error. One danger with killing connections is ADO's connection pool (more for asp.net apps than windows apps). ADO assumes the a connection fetched from the connection pool is valid... and it does not react well to connections that have been killed. The next operation that occurs on that connection will fail. I can't recall the error... you might be able to trap just that specific error and handle it... also with 3.5 I think you can flush the connection pool (so... trap the error, flush the connection pool, open the connection, try the command again... ugly but might be doable).
How do I run that database backup and restore scripts from my winform application?
[ "", "c#", "sql-server", "database", "backup", "database-restore", "" ]
Does creating an object using reflection rather than calling the class constructor result in any significant performance differences?
**Yes - absolutely.** Looking up a class via reflection is, *by magnitude*, more expensive. Quoting [Java's documentation on reflection](http://java.sun.com/docs/books/tutorial/reflect/index.html): > Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications. Here's a simple test I hacked up in 5 minutes on my machine, running Sun JRE 6u10: ``` public class Main { public static void main(String[] args) throws Exception { doRegular(); doReflection(); } public static void doRegular() throws Exception { long start = System.currentTimeMillis(); for (int i=0; i<1000000; i++) { A a = new A(); a.doSomeThing(); } System.out.println(System.currentTimeMillis() - start); } public static void doReflection() throws Exception { long start = System.currentTimeMillis(); for (int i=0; i<1000000; i++) { A a = (A) Class.forName("misc.A").newInstance(); a.doSomeThing(); } System.out.println(System.currentTimeMillis() - start); } } ``` With these results: ``` 35 // no reflection 465 // using reflection ``` Bear in mind the lookup and the instantiation are done together, and in some cases the lookup can be refactored away, but this is just a basic example. Even if you just instantiate, you still get a performance hit: ``` 30 // no reflection 47 // reflection using one lookup, only instantiating ``` Again, YMMV.
Yes, it's slower. But remember the damn #1 rule--PREMATURE OPTIMIZATION IS THE ROOT OF ALL EVIL (Well, may be tied with #1 for DRY) I swear, if someone came up to me at work and asked me this I'd be very watchful over their code for the next few months. You must never optimize until you are sure you need it, until then, just write good, readable code. Oh, and I don't mean write stupid code either. Just be thinking about the cleanest way you can possibly do it--no copy and paste, etc. (Still be wary of stuff like inner loops and using the collection that best fits your need--Ignoring these isn't "unoptimized" programming, it's "bad" programming) It freaks me out when I hear questions like this, but then I forget that everyone has to go through learning all the rules themselves before they really get it. You'll get it after you've spent a man-month debugging something someone "Optimized". EDIT: An interesting thing happened in this thread. Check the #1 answer, it's an example of how powerful the compiler is at optimizing things. The test is completely invalid because the non-reflective instantiation can be completely factored out. Lesson? Don't EVER optimize until you've written a clean, neatly coded solution and proven it to be too slow.
Java Reflection Performance
[ "", "java", "performance", "optimization", "reflection", "" ]
I am designing a psychology experiment with java applets. I have to make my java applets full screen. What is the best way of doing this and how can I do this. Since I haven't been using java applets for 3 years(The last time I've used it was for a course homework :) ) I have forgotten most of the concepts. I googled and found that link: [Dani web](http://www.daniweb.com/forums/thread101963.html) But in the method described in above link you have to put a JFrame inside the applet which I have no idea how to do it. Whatever I need a quick and dirty method b'cause I don't have much time and this is the reason why I asked it here. Thanx in advance
I think you want to use WebStart. You can deploy from a browser but it is otherwise a full blown application. There are a few browserish security restrictions, but, as you're using an Applet currently, I think I can assume they're not a problem.
The obvious answer is don't use applets. Write an application that uses a JFrame or JWindow as its top-level container. It's not a huge amount of work to convert an applet into an application. Applets are designed to be embedded in something else, usually a web page. If you already have an applet and want to make it full screen, there's two quick and dirty hacks: 1). If you know the screen resolution, just set the applet parameters to be that size in the HTML and then run the browser in full screen mode. 2). Run the applet in appletviewer, rather than a web page, and maximise the appletviewer window.
How to make full screen java applets?
[ "", "java", "applet", "fullscreen", "" ]
I have a program that uses [JAMA](http://math.nist.gov/javanumerics/jama/) and need to test is a matrix can be inverted. I know that I can just try it and catch an exception but that seems like a bad idea (having a catch block as part of the "normal" code path seems to be bad form). A test that also returns the inverse (or run in a better O() than the inverse operation) would be preferred.
In general, if you can't solve the matrix, it's singluar (non-invertable). I believe the way that JAMA does this is to try to solve the matrix using LU factorization, and if it fails, it returns "true" for isSingular(). There isn't really a general way to just look at the elements of a matrix and determine if it is singular - you need to check each column to see if it is orthogonal with the others (i.e. the nullspace for the matrix is 0). LU factorization is quite fast, usually... there are times where it takes the bulk of an operation, however. Do you have an actual speed problem you're trying to overcome?
sounds like you would like to estimate the reciprocal of the condition number. [This site](http://www.alglib.net/matrixops/general/rcond.php) looks somewhat promising... See also [Golub and Van Loan, p. 128-130](http://books.google.com/books?id=mlOa7wPX6OYC&pg=PA128). (If you don't have a copy of it, get one.) ...or [Higham](http://books.google.com/books?id=epilvM5MMxwC&pg=PA287), who's an authority on numerical methods. Except that it's kind of hard to parse the math... like walking through a thicket of raspberry bushes. :/ Or maybe check the Octave sources for their version of [MATLAB's `rcond()`](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/rcond.html). I found [this post](http://www.nabble.com/rcond,-condest,-and-a-block-1-norm-estimator-td13886035.html).
Test for invertability using Jama.Matrix
[ "", "java", "linear-algebra", "jama", "matrix-inverse", "" ]
I want to be able to close an alert box automatically using Javascript after a certain amount of time or on a specific event (i.e. `onkeypress`). From my research, it doesn't look like that's possible with the built-in `alert()` function. Is there a way to override it and have control over the dialog box that it opens? Also, I don't want an override that shows a hidden div as the alert. I need an actual dialog box.
As mentioned previously you really can't do this. You can do a modal dialog inside the window using a UI framework, or you can have a popup window, with a script that auto-closes after a timeout... each has a negative aspect. The modal window inside the browser won't create any notification if the window is minimized, and a programmatic (timer based) popup is likely to be blocked by modern browsers, and popup blockers.
Appears you can somewhat accomplish something similar with the [Notification](https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API) API. You can't control how long it stays visible (probably an OS preference of some kind--unless you specify requireInteraction true, then it stays up forever or until dismissed or until you close it), and it requires the user to click "allow notifications" (unfortunately) first, but here it is: If you want it to close after 1s (all OS's leave it open 1s at least): ``` var notification = new Notification("Hi there!", {body: "some text"}); setTimeout(function() {notification.close()}, 1000); ``` If you wanted to show it longer than the "default" you could bind to the onclose callback and show another repeat notification I suppose, to replace it. Ref: inspired by [this](https://stackoverflow.com/a/19651500/32453) answer, though that answer doesn't work in modern Chrome anymore, but the Notification API does.
Javascript close alert box
[ "", "javascript", "dialog", "alert", "dom-events", "" ]
I have been playing with javascript arrays and I have run into, what I feel, are some inconsistencies, I hope someone can explain them for me. Lets start with this: ``` var myArray = [1, 2, 3, 4, 5]; document.write("Length: " + myArray.length + "<br />"); for( var i in myArray){ document.write( "myArray[" + i + "] = " + myArray[i] + "<br />"); } document.write(myArray.join(", ") + "<br /><br />"); ``` ``` Length: 5 myArray[0] = 1 myArray[1] = 2 myArray[2] = 3 myArray[3] = 4 myArray[4] = 5 1, 2, 3, 4, 5 ``` There is nothing special about this code, but I understand that a javascript array is an object, so properities may be add to the array, the way these properities are added to an array seems inconsistent to me. Before continuing, let me note how string values are to be converted to number values in javascript. * Nonempty string -> Numeric value of string or NaN * Empty string -> 0 So since a javascript array is an object the following is legal: ``` myArray["someThing"] = "someThing"; myArray[""] = "Empty String"; myArray["4"] = "four"; ``` for( var i in myArray){ document.write( "myArray[" + i + "] = " + myArray[i] + "<br />"); } document.write(myArray.join(", ") + "<br /><br />"); ``` Length: 5 myArray[0] = 1 myArray[1] = 2 myArray[2] = 3 myArray[3] = 4 myArray[4] = four myArray[someThing] = someThing myArray[] = Empty String 1, 2, 3, 4, four ``` The output is unexpected. The non empty string "4" is converted into its numeric value when setting the property myArray["4"], this seems right. However the empty string "" is not converted into its numeric value, 0, it is treated as an empty string. Also the non empty string "something" is not converted to its numeric value, NaN, it is treated as a string. So which is it? is the statement inside myArray[] in numeric or string context? Also, why are the two, non numeric, properities of myArray not included in myArray.length and myArray.join(", ")?
The keys of a JavaScript array are actually strings. For details and an implementation of a map type for arbitrary keys, check [this answer](https://stackoverflow.com/questions/368280/javascript-hashmap-equivalent#383540). --- To clarify and add to what Jason posted: JavaScript arrays are objects. Objects have properties. A property name is a string value. Therefore, array indices are converted to strings as well before anything more can happen. A property name P will be treated as an array index (ie the special array-magic will be invoked) if the following holds (ECMA-262, 15.4): > ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32 − 1 That numeric indices will be converted to strings (and not the other way around) can be easily verified: ``` var array = []; array[1] = 'foo'; array['1'] = 'bar'; array['+1'] = 'baz'; document.writeln(array[1]); // outputs bar ``` --- Also, its bad practice to iterate over an array's entries with a `for..in` loop - you might get unexpected results if someone messed with some prototypes (and it's not really fast, either). Use the standard `for(var i= 0; i < array.length; ++i)` instead.
(edit: the following is not quite right) The keys of a JavaScript *Object* are actually strings. A Javascript *Array* by itself has numeric indices. If you store something with an index that can be interpreted as a nonnegative integer, it will try to do so. If you store something with an index that is not a nonnegative integer (e.g. it's alphanumeric, negative, or a floating-point number with a fractional piece), it will fail on the array-index store, and default to the *Object* (which is Array's base class) store, which then converts the argument to a string and stores by string index -- but these stored properties are not seen by the Array class and therefore are not visible to its methods/properties (length, join, slice, splice, push, pop, etc). edit: the above is not quite right (as Christopher's foo/bar/baz example shows). The actual storage indices according to the [ECMAscript spec](http://www.ecma-international.org/publications/standards/Ecma-262.htm) are, in fact, strings, but if they are valid array indices (nonnegative integers) then the Array object's `[[Put]]` method, which is special, makes those particular values visible to the Array's "array-ish" methods.
Arrays keys number and "number" are unexpectedly considered the same
[ "", "javascript", "arrays", "type-conversion", "" ]
I'm wondering how others handle this situation... and how to apply the Don't Repeat Yourself (DRY) principle to this situation. I find myself constantly PIVOTing or writing CASE statements in T-SQL to present Months as columns. I generally have some fields that will include (1) a date field and (2) a value field. When I present this back to a user through an ASPX page or Reporting Services I need to have the last right-most 14 columns to have this pattern: [Year],[Jan],[Feb],[Mar],[Apr],[May],[Jun],[Jul],[Aug],[Sep],[Oct],[Nov],[Dec],[Total] Where year is the year as an int and every other field is the value field summed for that month (except for [Total] which is the total value field for the year). I'd like to find one re-usable way to handle this. Open to all suggestions (T-SQL / ANSI SQL)
This isn't exactly what you're looking for, but I've done a lot of repetitive `UNPIVOT`, and typically, I would code-gen this, with some kind of standardized naming and use CTEs heavily: ``` WITH P AS ( SELECT Some Data ,[234] -- These are stats ,[235] FROM Whatever ) ,FINAL_UNPIVOTED AS ( SELECT Some Data ,[STAT] FROM P UNPIVOT ( STAT FOR BASE IN ([234], [235]) ) AS unpvt WHERE STAT <> 0 ) SELECT Some Data ,CONVERT(int, FINAL_UNPIVOTED.[BASE]) AS [BASE] ,FINAL_UNPIVOTED.[STAT] FROM FINAL_UNPIVOTED ``` You can codegen by inspecting a table or view and using something like this: ``` DECLARE @sql_unpivot AS varchar(MAX) SELECT @sql_unpivot = COALESCE(@sql_unpivot + ',', '') + COLUMN_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'whatever' ``` And templatizing the code: ``` SET @template = ' WITH P AS ( SELECT Some Data ,{@sql_unpivot} FROM Whatever ) ,FINAL_UNPIVOTED AS ( SELECT Some Data ,[STAT] FROM P UNPIVOT ( STAT FOR BASE IN ({@sql_unpivot}) ) AS unpvt WHERE STAT <> 0 ) SELECT Some Data ,CONVERT(int, FINAL_UNPIVOTED.[BASE]) AS [BASE] ,FINAL_UNPIVOTED.[STAT] FROM FINAL_UNPIVOTED ' SET @sql = REPLACE(@template, '{@sql_unpivot}', @sql_unpivot) ``` etc. Of course, it's possible to run this code dynamically or create and SP and you can swap out a view or table you created temporarily just to pick up metadata for something inline. See comments regarding table-valued functions and OUTER APPLY technique.
``` /* I leave year and month separate so you can use "real" Months or Fiscal Months */ CREATE FUNCTION [dbo].[fn_MonthValueColumns] ( @year int, @month int, @measure int ) RETURNS TABLE AS RETURN ( SELECT @year as [Year], CASE WHEN @month = 1 THEN @measure ELSE 0 END AS [Jan], CASE WHEN @month = 2 THEN @measure ELSE 0 END AS [Feb], CASE WHEN @month = 3 THEN @measure ELSE 0 END AS [Mar], CASE WHEN @month = 4 THEN @measure ELSE 0 END AS [Apr], CASE WHEN @month = 5 THEN @measure ELSE 0 END AS [May], CASE WHEN @month = 6 THEN @measure ELSE 0 END AS [Jun], CASE WHEN @month = 7 THEN @measure ELSE 0 END AS [Jul], CASE WHEN @month = 8 THEN @measure ELSE 0 END AS [Aug], CASE WHEN @month = 9 THEN @measure ELSE 0 END AS [Sep], CASE WHEN @month = 10 THEN @measure ELSE 0 END AS [Oct], CASE WHEN @month = 11 THEN @measure ELSE 0 END AS [Nov], CASE WHEN @month = 12 THEN @measure ELSE 0 END AS [Dec], @measure AS [Total] ) /* use a group by after your own CROSS APPLY to roll-up SUMs for the last 13 fields. this function and a CROSS APPLY against 100000 records ran in 3 seconds. for what I am doing, I can live with that performance. */ ```
How to apply the DRY principle to SQL Statements that Pivot Months
[ "", "sql", "sql-server", "t-sql", "dry", "pivot", "" ]
I am using python-ldap to try to authenticate against an existing Active Directory, and when I use the following code: ``` import ldap l = ldap.initialize('LDAP://example.com') m = l.simple_bind_s(username@example.com,password) ``` I get the following back: ``` print m (97, []) ``` What does the 97 and empty list signify coming from a Microsoft Active Directory server? I gather this is a successful authentication since it doesn't error (which it does if you use the wrong password or non-existent username), but I'd like to know if the tuple means something useful.
According to the [documentation](http://support.microsoft.com/kb/218185), this is: ``` LDAP_REFERRAL_LIMIT_EXCEEDED 0x61 The referral limit was exceeded. ``` Probably ``` ldap.set_option(ldap.OPT_REFERRALS, 0) ``` could help.
The first item is a status code (97=success) followed by a list of messages from the server. See [here](http://www.packtpub.com/article/installing-and-configuring-the-python-ldap-library-and-binding-to-an-ldap-directory) in the section **Binding**.
What does the LDAP response tuple (97, []) mean?
[ "", "python", "active-directory", "ldap", "" ]
I have a MySQL query like this: ``` SELECT *, SUM(...some SQL removed for brevety) AS Occurrences FROM some_table AS q WHERE criterion="value" GROUP BY q.P_id ORDER BY Occurrences DESC LIMIT 10; ``` I want to restrict the results to rows where Occurrences>0. This seems very simple to me, but I can't seem to make it work. No matter what I try, WHEREs or HAVINGs, whenever I try to add this restriction I get NO ROWS in return. I'm positive that there is data in my table that should be returned. Does anyone know how to accomplish what I'm doing? --- I've tried this, but it still doesn't work. Any ideas why it still won't work? ``` SELECT *, SUM(...some SQL removed for brevety) AS Occurrences FROM some_table AS q WHERE criterion="value" HAVING SUM(...some SQL removed for brevety)>0 GROUP BY q.P_id ORDER BY Occurrences DESC LIMIT 10; ```
I am not as familiar with MySQL as I am with SQL Server, but in T-SQL, you can't use aliases in GROUP BY clauses (I originally thought ORDER BY clauses as well, but that has since been shown to be incorrect). In this case, you want to filter based on the results of a GROUP BY, so I would use a HAVING clause as follows: ``` SELECT *, SUM(... some SQL removed for brevity ...) AS Occurrences FROM some_table AS q WHERE criterion = 'value' GROUP BY q.P_id HAVING SUM(... some SQL removed for brevity ...) > 0 ORDER BY Occurrences DESC LIMIT 10; ```
This query works for me... ``` select order_id, sum(qty_ordered) as total_qty from sales_flat_order_item group by order_id having total_qty > 10 order by total_qty desc ```
How to use an aliased column in a MySQL WHERE clause?
[ "", "sql", "mysql", "where-clause", "having", "" ]
I'm looking for a way to display a VNC viewer in a thick/rich java client (specifically, I'm using SWT, but if I can get it into AWT/Swing, I can integrate that specifically.) This is not an applet, but a real, live, thick java client. [TightVNC](http://www.tightvnc.com/download.html) is probably sufficient; however, its GPL license is too restrictive for my needs. Is anyone aware of a Java VNC library available under a less restrictive license?
A quick survey of the options thus far (I haven't found a satisfactory answer as of this writing): * **[vncjlgpl](http://sourceforge.net/projects/vncjlgpl)** - Server only. Perhaps I could use the knowledge captured here to roll my own, which would make it a derivative work, which could be LGPL'd. * **[TightVNC](http://www.tightvnc.com)** - Provides a Java-based viewer. I haven't looked at the source yet, but I'm assuming it could be reused suitably. However; it's GPL license prevents reuse in my pseudo-commerical product. * **[RealVNC](http://www.realvnc.com/support/javavncviewer.html)** - Provides a Java application that is a VNC viewer. Commerical product. No source available. A publicly available installation of the .jar (launchable via webstart) is [here](http://danielwebb.us/software/vnc/).
I don't know if you still need something for this, but I've found the MetaVNC (on sourceforge) java viewer is pretty simple to work with. Last mods were in 2007 so it doesn't look like it's being maintained, but it might give you basic functionality.
How can I display a VNC Viewer in a Java rich client (LGPL, Apache, MIT license)?
[ "", "java", "open-source", "" ]
Is there a way to do the following preprocessor directives in Python? ``` #if DEBUG < do some code > #else < do some other code > #endif ```
There's `__debug__`, which is a special value that the compiler does preprocess. ``` if __debug__: print "If this prints, you're not running python -O." else: print "If this prints, you are running python -O!" ``` `__debug__` will be replaced with a constant 0 or 1 by the compiler, and the optimizer will remove any `if 0:` lines before your source is interpreted.
I wrote a python preprocessor called pypreprocessor that does exactly what you're describing. [The source and documentation is available on GitHub](https://github.com/interpreters/pypreprocessor). [The package can also be downloaded/installed through the PyPI](http://pypi.python.org/pypi/pypreprocessor/). Here's an example to accomplish what you're describing. ``` from pypreprocessor import pypreprocessor pypreprocessor.parse() #define debug #ifdef debug print('The source is in debug mode') #else print('The source is not in debug mode') #endif ``` pypreprocessor is capable of a lot more than just on-the-fly preprocessing. To see more use case examples check out the project on Google Code. **Update: More info on pypreprocessor** The way I accomplish the preprocessing is simple. From the example above, the preprocessor imports a pypreprocessor object that's created in the pypreprocessor module. When you call parse() on the preprocessor it self-consumes the file that it is imported into and generates a temp copy of itself that comments out all of the preprocessor code (to avoid the preprocessor from calling itself recursively in an infinite loop) and comments out all of the unused portions. Commenting out the lines is, as opposed to removing them, is necessary to preserve line numbers on error tracebacks if the module throws an exception or crashes. And I've even gone as far as to rewrite the error traceback to report reflect the proper file name of the module that crashed. Then, the generated file containing the postprocessed code is executed on-the-fly. The upside to using this method over just adding a bunch of if statements inline in the code is, there will be no execution time wasted evaluating useless statements because the commented out portions of the code will be excluded from the compiled .pyc files. The downside (and my original reason for creating the module) is that you can't run both python 2x and python 3x in the same file because pythons interpreter runs a full syntax check before executing the code and will reject any version specific code before the preprocessor is allowed to run ::sigh::. My original goal was to be able to develop 2x and 3x code side-by-side in the same file that would create version specific bytecode depending on what it is running on. Either way, the preprocessor module is still very useful for implementing common c-style preprocessing capabilities. As well as, the preprocessor is capable of outputting the postprocessed code to a file for later use if you want. Also, if you want to generate a version that has all of the preprocessor directives as well as any of the #ifdefs that are excluded removed it's as simple as setting a flag in the preprocessor code before calling parse(). This makes removing unwanted code from a version specific source file a one step process (vs crawling through the code and removing if statements manually).
How would you do the equivalent of preprocessor directives in Python?
[ "", "python", "preprocessor", "equivalent", "directive", "" ]
I have a temp table I am creating a query off of in the following format. That contains a record for every CustomerID, Year, and Month for several years. ## #T Customer | CustomerID | Year | Month ex. ``` Foo | 12345 | 2008 | 12 Foo | 12345 | 2008 | 11 Bar | 11224 | 2007 | 7 ``` When I join this temp table to another table of the following format I get many more results than I am expecting. ## Event EventID | CustomerID | DateOpened ex. ``` 1100 | 12345 | '2008-12-11 10:15:43' 1100 | 12345 | '2008-12-11 11:25:17' ``` I am trying to get a result set of the count of events along with the Customer, Year, and Month like this. ``` SELECT COUNT(EventID), Customer, Year, Month FROM [Event] JOIN #T ON [Event].CustomerID = #T.CustomerID WHERE [Event].DateOpened BETWEEN '2008-12-01' AND '2008-12-31' GROUP BY Customer, Year, Month ORDER BY Year, Month ``` I am getting a record for every Year and Month instead of only for December 2008.
You're specifying the date on the event table but not on the join -- so it's joining all records from the temp table with a matching customerid. Try this: ``` SELECT COUNT(e.EventID), T.Customer, T.Year, T.Month FROM [Event] e INNER JOIN #T T ON ( T.CustomerID = e.CustomerID and T.Year = year(e.DateOpened) and T.Month = month(e.DateOpened) ) WHERE T.Year = 2008 and T.Month = 12 GROUP BY T.Customer, T.Year, T.Month ORDER BY T.Year, T.Month ```
Perhaps what you mean is: ``` SELECT COUNT(EventID) ,Customer ,Year ,Month FROM [Event] INNER JOIN #T ON [Event].CustomerID = #T.CustomerID AND YEAR([Event].DateOpened) = #T.YEAR AND MONTH([Event].DateOpened) = #T.MONTH WHERE [Event].DateOpened >= '2008-12-01' AND [Event].DateOpened < '2009-01-01' GROUP BY Customer ,Year ,Month ORDER BY Year ,Month ``` Note, I've fixed another latent bug in your code: your `BETWEEN` is going to exclude datetimes like `'2008-12-31 10:15:43'` You can use this or similar technique.
SQL Join Not Returning What I Expect
[ "", "sql", "sql-server", "t-sql", "" ]
In the past, when one made a `JPopupMenu` visible it's first item would get selected by default: <http://weblogs.java.net/blog/alexfromsun/archive/2008/02/jtrayicon_updat.html> Nowadays the default behavior is to pop up the menu without any item selected. I would like create a `JPopupMenu` with a single item that will pop up selected and centered under the mouse pointer. I have managed to get the item to pop up centered under the mouse but I the `JMenuItem` refuses to render as if it is selected. If I move the mouse out of the item and back in it selects properly. Any ideas? Here is my testcase: ``` import java.awt.Component; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; public class Test extends JFrame { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(800, 600); frame.getContentPane().addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) popupTriggered(e); } @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) popupTriggered(e); } private void popupTriggered(MouseEvent e) { JPopupMenu menu = new JPopupMenu(); final JMenuItem item = new JMenuItem("This is a JMenuItem"); menu.add(item); Point point = e.getPoint(); int x = point.x - (item.getPreferredSize().width / 2); int y = point.y - (item.getPreferredSize().height / 2); menu.show((Component) e.getSource(), x, y); } }); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setVisible(true); } } ```
> Nowadays the default behavior is to pop up the menu without any item selected. Actually, I would argue that this is the correct behavior, at least in Windows. Other non-Java applications do this too. I don't think it's worth breaking this convention even if there is only one item in the menu. If you feel otherwise, you can set the selection index as in [sean.bright's answer](https://stackoverflow.com/questions/482041/how-to-select-first-item-in-jpopupmenu#482047). --- So, I finally got the chance to try it out on Java `1.6.0_11`, and found some inconsistent behavior: If the popup menu juts out of the parent frame, the item is automatically selected; if the popup menu appears entirely within the parent frame, nothing is selected. Sounds like a Swing bug, which at least warrants an RFE for consistent behavior.
Secret turns out to be `MenuSelectionManager.defaultManager().setSelectedPath(new MenuElement[]{menu, ...});` ``` import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.MenuElement; import javax.swing.MenuSelectionManager; import javax.swing.SwingUtilities; /** * Demonstrates programmatic {@link JMenuItem} selection; * specifically how to make the first item selected by default */ public class TestPopup extends JFrame { public static void main(String[] args) { final JFrame frame = new JFrame("TestPopup"); frame.setSize(640, 480); frame.getContentPane().addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { popupTriggered(e); } } private void popupTriggered(MouseEvent e) { final JPopupMenu menu = new JPopupMenu(); final JMenuItem item0 = new JMenuItem("JMenuItem 0"); final JMenuItem item1 = new JMenuItem("JMenuItem 1"); menu.add(item0); menu.add(item1); menu.pack(); // use invokeLater or just do this after the menu has been shown SwingUtilities.invokeLater(new Runnable() { public void run() { MenuSelectionManager.defaultManager().setSelectedPath(new MenuElement[]{menu, item0}); } }); int x = (int) ((int) (frame.getSize().width - (menu.getPreferredSize().width / 2.)) / 2.); int y = (int) ((int) (frame.getSize().height - (menu.getPreferredSize().height / 2.)) / 2.); menu.show(frame, x, y); // doesn't work: //item0.setSelected(true); // doesn't work: //menu.getSelectionModel().setSelectedIndex(0); // bingo; see also MenuKeyListener / MenuKeyEvent // MenuSelectionManager.defaultManager().setSelectedPath(new MenuElement[]{menu, item0}); } }); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); } } ```
How to select first item in JPopupMenu?
[ "", "java", "swing", "jmenupopup", "" ]
I am having a few issues when people are trying to access a MySQL database and they are trying to update tables with the same information. I have a webpage written using PHP. In this webpage is a query to check if certain data has been entered into the database. If the data hasn't, then i proceed to insert it. The trouble is that if two people try at the same time, the check might say the data has not been entered yet but when the insert takes place it has been by the other person. What is the best way to handle this scenario? Can i lock the database to only process my queries first then anothers?
You're looking for `LOCK`. <http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html> This can be run as a simple `mysql_query` (or `MySQLi::query/prepare`). I'd say it's better to lock specific tables (although you can probably try `LOCK TABLES *`) that need to be locked rather than the whole database - as nothing will be able to be read. I think you're looking for something like: ``` LOCK TABLES items; START TRANSACTION; INSERT INTO items (name, label) VALUES ('foo', 'bar'); UNLOCK TABLES; ``` Or in PHP: ``` mysql_query('LOCK TABLES items'); mysql_query("INSERT INTO items (name, label) VALUES ('foo', 'bar')"); mysql_query('UNLOCK TABLES'); ```
Read up on [database transactions](http://en.wikipedia.org/wiki/Database_transaction). That's probably a better way to handle what you need than running LOCK TABLES.
Locking a MySQL database so only one person at once can run a query?
[ "", "php", "mysql", "concurrency", "" ]
I work at a small LAMP Development Studio where the idea has been to just get the code done and go on to the next item on the list. The team works in Zend Studio 5.5 connected to the Live server via FTP or SFTP. What they love about this is the speed of their deployment of code (since its just modifying live code). But of course this is not good due to many obvious reasons. I would like to move them to a Versioning System (CVS, SVN or any other tool) but the catch is, I am not their senior so I need a carrot for them to start using this. What kind of setup would I need to build on their machine so they can code along as usual? What I would do is create this setup on my machine and then show them. I know this is kinda unusual but it's turned into a passion of mine to change their way of thinking from the usual hacking of code to structure and elegance. Thanks. UPDATE (for Jonathan Leffler's answer): 1. Yes 2. No 3. Yes, they really do Question also, the studio makes a centralized CMS system that is hosted on hundreds of sites, they need to modify individual sites, should the sites be in the main compository or within their own one?
Questions: 1. Have you (they) never had a disaster where you (they) needed to revert to a previous version of the web site but couldn't because they'd broken it? 2. Do they use a staging web server to test changes? 3. Surely they don't modify the code in the production server without some testing somewhere? I suspect the answer to the first is "yes (they have had disasters)" and the second "no", and I hesitate to guess the answer for the third (but. from the sounds of it, the answer might be "yes, they really do"). If that's correct, I admire their bravado and am amazed that they never make a mistake. I'd never risk making changes direct on a live web site. I would recommend using a version control system or VCS (any VCS) yourself. Work out the wrinkles for the code you look after, and develop the slick distribution that makes it easy (probably still using SFTP) to distribute the VCS code to the web site. But also show that preserving the previous versions has its merits - because you can recover who did what when. To start with, you might find that you need to download the current version of whatever page (file) you need to work on and put that latest version into the VCS before you start modifying the page, because someone else may have modified it since it was last updated in your master repository. You might also want to do a daily 'scrape' of the files to get the current versions - and track changes. You wouldn't have the 'who', nor exactly 'when' (better than to the nearest day), nor the 'why', but you would have the (cumulative) 'what' of the changes. --- In answer to comments in the question, Ólafur Waage clarified that they've had disasters because of the lack of a VCS. That usually makes life much easier. They goofed; they couldn't undo the goof - they probably had annoyed customers, and they should have been incredibly annoyed with themselves. A VCS makes it much easier to recover from such mistakes. Obviously, for any given customized site, you need the (central) backup of the 'correct' or 'official' version of that site available in the VCS. I'd probably go for a single repository for all customers, using a VCS that has good support for branching and merging. That may be harder to deal with at first (while people are getting used to using a VCS), but probably leads to better results in the long term. I'd seriously consider using on of the modern distributed VCS (for example, [git](http://git.kernel.org/)), though lots of people use SVN too (even though it is not a distributed VCS).
Here's one trick that everyone will love: I include this 'plugin' in most of my production sites: Ofcourse, you need to create a limited-rights robot svn account for this first and svn must be installed on the server. ``` echo(' updating from svn<br>' ); $username = Settings::Load()->Get('svn','username'); $password = Settings::Load()->Get('svn','password'); echo(" <pre>" ); $repos = Settings::Load()->Get('svn' , 'repository'); echo system ("svn export --username={$username} --password {$password} {$repos}includes/ ".dirname(__FILE__)."/../includes --force"); echo system("svn export --username={$username} --password {$password} {$repos}plugins/ ".dirname(__FILE__)."/../plugins --force"); die(); ``` Make sure you put this behind a .htpasswded site ofcourse, and make sure you do not update the 'production settings' from SVN. Et voila, You update your complete code base with one HTTP query to your site :) SVN overwrites the files automatically, there's no hidden files or folders left behind and its easily adapted to update or revert to a specific version. Now all your team needs to do is commit to their SVN repository, run this piece of code on the testing environment, make sure everything works and then run it on production :)
Converting a development team from FTP to a Versioning System
[ "", "php", "version-control", "development-environment", "" ]
I have a form with 3 panels, the panels are created because at certain times I need certain groups of controls hidden/shown. Until now, it worked fine - that is until I was asked to have a specific way to navigate the form with TAB key. First of all, I noticed that there is no TabIndex property in the Panel object and, most importantly, I don't want to follow a nested navigation algorithm, I just want to set my own sequence. From what I have read online so far, this is not possible with panels. My only alternative is to put all the controls on the form in the same panel. Any thoughts? I don't feel like re-arranging the app, and start hiding and showing individual controls.
Pressing the TAB key will move the focus to the next control in the ControlCollection. Since the focus is always in a control within the Panel and not in the panel itself, how could you expect that a Panel supports tab index? I suggest that you think again what you are trying to do. When a specific panel is visible, TAB should navigate you around the controls in it. It doesn't make sense for TAB to move you in the next panel. This is usually done with a button or some other control. Users expect that TAB moves the focus and not performing an action. Moreover, if you want to have TAB to move you around the panels, then you need to set the Tab Stop property of all controls to false.
I had the same issue. My solution was to put all controls in subpanels on the form. The tabbing of .net algorithm is to tab within the 'current' container using the TabIndex. If any of the TabIndexes within a container are the same, the first one in z-order will be first, etc. Once in a container (a form is a container), all controls other than containers(panels) are tabbed to first. When leaving the last non-container control the panels are recursed into. Thus, if all controls are placed in containers/panels at the same level, your tabbing will be done as you expect. Example Problem: ``` Form control1 Tabindex=1 panel1 control2 Tabindex=2 control3 Tabindex=2 panel2 control4 Tabindex=4 control5 Tabindex=5 control6 Tabindex=6 ``` Tabbing will be in the following order (not what you expected): ``` Control1 Control6 <-- not what you wanted/expected Control2 Control3 Control4 Control5 ``` To get it to tab correctly, layout in the following pattern: ``` Form panel0 control1 Tabindex=1 panel1 control2 Tabindex=2 control3 Tabindex=2 panel2 control4 Tabindex=4 control5 Tabindex=5 panel3 control6 Tabindex=6 ```
Setting TabIndex in CF .net framework
[ "", "c#", ".net", "compact-framework", "tabindex", "" ]
Some people don't like sequences on Oracle. Why? I think they are very easy to use and so nice. You can use them in select, inserts, update,...
I don't. I should point out that sometimes people hate what they don't understand. Sequences are incredibly important for generating unique IDs. Conceptually, it's useful to have a method of generating an ID that does not depend on the contents of a table. You don't need to lock a table in order to generate a unique number. Sequences can also be useful for generating keys across multiple tables that need to be unique. For instance, if I have a new item entering a system and I want to put a row in several tables at once, I can grab an ID from a sequence are reuse it when I insert into any number of tables. Done properly, I know the ID will not conflict with a value already in the tables and that each row will have the same ID. I would assume these things are also possible with auto-increment columns as well.
To sum it up, I like sequences, but I'd like an autoincrement keyword for columns even more.
Why do you hate sequences on Oracle?
[ "", "sql", "oracle", "sequences", "" ]
Suppose we have the following class hierarchy: ``` class Base { ... }; class Derived1 : public Base { ... }; class Derived2 : public Base { ... }; ``` Given a `Base*` which could point to either a `Derived1` or `Derived2` object how can I make a copy of the actual object given that it's concrete type is unknown. I thought of defining copy constructors but I don't think this is possible without knowing the actual types involved. The only solution I can think of is defining a `clone()` method on each type in the hierarchy. Can anybody think of something more elegant?
Unfortunately a virtual clone/copy pattern is your only real choice. There are variations of this, but essentially they all come down to writing functions for each type that can return a new copy.
You need to implement the virtual clone method on every object in the hierarchy. How else would your object of undefined type know how to copy itself? In order to make this more obvious to people writing derived classes, you might think about making the clone method abstract in your base class as well, to force people to at least write something. In several places for my code, I also test to make sure that the to\_string() method is implemented correctly to serialize an object to a string. The specific test that I've used in my class to test clone and to\_string simultaneously looks like this: ``` Base *obj1, *obj2; # initialize obj1 in a reasonable manner obj2 = obj1->clone(); assert( obj1->to_string() == obj2->to_string() ); ``` This is testing both the clone method() and object serialization to strings (so it's not strictly a unit test), but it's a paradigm that simple to wrap in a loop around all of the objects in a factory to make sure that they're following some minimum standard of implementing clone() and to\_string(). Edit: Updated code with correction from strager's comment. Thanks!
Make a copy of an unknown concrete type in c++
[ "", "c++", "inheritance", "polymorphism", "" ]
When I'm debugging, I often have to deal with methods that does not use an intermediate variable to store the return value : ``` private int myMethod_1() { return 12; } private int myMethod_2() { return someCall( someValue ); } ``` Well, in order to recreate a bug, I often have to change values on the fly. Here, I could want to see what happens when `myMethode_1` return zero. Same thing for `myMethod_2`. Is there a way to do that *without modifying the code* ? What I would like to do, it's to place a breakpoint on the return line (or on the closing bracket) and type-in a new return value. Note : I'm using Visual Studio 2005 and Visual Studio 2008. Thank !
**For those who are looking for a solution to this in VB.NET:** It was so simple, I can't believe I did not see it : To look at the value a function will return : just place the pointer over the function's name. The value will be shown in a tool tip. The change the value : just click on this tool tip, change the value and hit enter. Visual Studio is very cool ! Note : I tested it in VB.NET on Visual Studio Team System 2008. Just tried using C#, but it does not work... :-(
Return values from functions are usually returned in the EAX register. If you set a breakpoint just at the end of the function then there's a chance that changing EAX would change the return value. You can change and view any register in visual studio simply by writing its name in the watch window. This is likely to fail if you have optimization on or even if the function is something simple like `return 12`. it's probably also not going to work if you're returning something that doesn't fit in a 32 bit register. In the least it's worth trying.
Visual Studio - How to change the return value of a method in the debugger?
[ "", "c#", ".net", "vb.net", "visual-studio", "debugging", "" ]
I'm new to python, and have a list of longs which I want to join together into a comma separated string. In PHP I'd do something like this: ``` $output = implode(",", $array) ``` In Python, I'm not sure how to do this. I've tried using join, but this doesn't work since the elements are the wrong type (i.e., not strings). Do I need to create a copy of the list and convert each element in the copy from a long into a string? Or is there a simpler way to do it?
You have to convert the ints to strings and then you can join them: ``` ','.join([str(i) for i in list_of_ints]) ```
You can use map to transform a list, then join them up. ``` ",".join( map( str, list_of_things ) ) ``` BTW, this works for any objects (not just longs).
How to convert a list of longs into a comma separated string in python
[ "", "python", "" ]
Using POSIX threads & C++, I have an "Insert operation" which can only be done safely one at a time. If I have multiple threads waiting to insert using pthread\_join then spawning a new thread when it finishes. Will they all receive the "thread complete" signal at once and spawn multiple inserts or is it safe to assume that the thread that receives the "thread complete" signal first will spawn a new thread blocking the others from creating new threads. ``` /* --- GLOBAL --- */ pthread_t insertThread; /* --- DIFFERENT THREADS --- */ // Wait for Current insert to finish pthread_join(insertThread, NULL); // Done start a new one pthread_create(&insertThread, NULL, Insert, Data); ``` --- Thank you for the replies The program is basically a huge hash table which takes requests from clients through Sockets. Each new client connection spawns a new thread from which it can then perform multiple operations, specifically lookups or inserts. lookups can be conducted in parallel. But inserts need to be "re-combined" into a single thread. You could say that lookup operations could be done without spawning a new thread for the client, however they can take a while causing the server to lock, dropping new requests. The design tries to minimize system calls and thread creation as much as possible. But now that i know it's not safe the way i first thought I should be able to cobble something together Thanks
From [opengroup.org on pthread\_join](http://opengroup.org/onlinepubs/007908799/xsh/pthread_join.html): > The results of multiple simultaneous calls to pthread\_join() specifying the same target thread are undefined. So, you really should not have several threads joining your previous insertThread. First, as you use C++, I recommend [boost.thread](http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html). They resemble the POSIX model of threads, and also work on Windows. And it helps you with C++, i.e. by making function-objects usable more easily. Second, why do you want to start a new thread for inserting an element, when you always have to wait for the previous one to finish before you start the next one? Seems not to be classical use of multiple-threads. Although... One classical solution to this would be to have one worker-thread getting jobs from an event-queue, and other threads posting the operation onto the event-queue. If you really just want to keep it more or less the way you have it now, you'd have to do this: * Create a condition variable, like `insert_finished`. * All the threads which want to do an insert, wait on the condition variable. * As soon as one thread is done with its insertion, it fires the condition variable. * As the condition variable requires a mutex, you can just notify *all* waiting threads, they all want start inserting, but as only one thread can acquire the mutex at a time, all threads will do the insert sequentially. But you should take care that your synchronization is not implemented in a too ad-hoc way. As this is called `insert`, I suspect you want to manipulate a data-structure, so you probably want to implement a thread-safe data-structure first, instead of sharing the synchronization between data-structure-accesses and all clients. I also suspect that there will be more operations then just `insert`, which will need proper synchronization...
According to the Single Unix Specifcation: "The results of multiple simultaneous calls to pthread\_join() specifying the same target thread are undefined." The "normal way" of achieving a single thread to get the task would be to set up a condition variable (don't forget the related mutex): idle threads wait in pthread\_cond\_wait() (or pthread\_cond\_timedwait()), and when the thread doing the work has finished, it wakes up one of the idle ones with pthread\_cond\_signal().
pthread_join - multiple threads waiting
[ "", "c++", "multithreading", "posix", "" ]
When I try this code: ``` class MyStuff: def average(a, b, c): # Get the average of three numbers result = a + b + c result = result / 3 return result # Now use the function `average` from the `MyStuff` class print(MyStuff.average(9, 18, 27)) ``` I get an error that says: ``` File "class.py", line 7, in <module> print(MyStuff.average(9, 18, 27)) TypeError: unbound method average() must be called with MyStuff instance as first argument (got int instance instead) ``` What does this mean? Why can't I call `average` this way?
You can instantiate the class by declaring a variable and calling the class as if it were a function: ``` x = mystuff() print x.average(9,18,27) ``` However, this won't work with the code you gave us. When you call a class method on a given object (x), it always passes a pointer to the object as the first parameter when it calls the function. So if you run your code right now, you'll see this error message: ``` TypeError: average() takes exactly 3 arguments (4 given) ``` To fix this, you'll need to modify the definition of the average method to take four parameters. The first parameter is an object reference, and the remaining 3 parameters would be for the 3 numbers.
From your example, it seems to me you want to use a static method. ``` class mystuff: @staticmethod def average(a,b,c): #get the average of three numbers result=a+b+c result=result/3 return result print mystuff.average(9,18,27) ``` Please note that an heavy usage of static methods in python is usually a symptom of some bad smell - if you really need functions, then declare them directly on module level.
Why do I get a TypeError if I try to call a method directly from the class, supplying all arguments?
[ "", "python", "python-3.x", "class", "methods", "" ]
Let's say I have a couple composite shapes (`<g>`). I want to be able to click and drag them, but I want the one I happen to be dragging at the moment to be on TOP of the other one in the Z order, so that if I drag it over the OTHER one, the other one should be eclipsed.
Z index in SVG is defined by the order the elements appear in the document (subsequent elements are painted on top of previous elements). You will have to change the element order if you want to bring a specific shape to the top.
An alternative to moving elements in the tree is to use `<use>` elements where you change the `xlink:href` attribute so that it gives you the z ordering you want. Here's an [old thread](http://tech.groups.yahoo.com/group/svg-developers/message/59312) on svg-developers mailinglist discussing this topic in context of wanting to animate some shapes. **Update:** ``` <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="width:100%; height: 100%"> <circle id="c1" cx="50" cy="50" r="40" fill="lime" /> <rect id="r1" x="4" y="20" width="200" height="50" fill="cyan" /> <circle id="c2" cx="70" cy="70" r="50" fill="fuchsia" /> <use id="use" xlink:href="#c1" /> </svg> ``` In this example the <use> element is the last one, which makes it the frontmost element. We can choose any of the other elements to act as frontmost simply by changing the `xlink:href` attribute. In the above example we picked the circle with `id="c1"`, which makes it appear as the topmost element. See [fiddle](http://jsfiddle.net/hkSFf/).
With JavaScript, can I change the Z index/layer of an SVG <g> element?
[ "", "javascript", "svg", "" ]
So, I have a method that performs a parametrised LIKE query. The method takes in the search parameter/value in and then it is added to the command ready for the query. It is not working. It should work, and when I code the value to search for directly into the SQL string, sans parametrisation, it does work! When I have it as a parameter is does not! Any ideas. Here is some (fake, I have changed the names) example code. ``` myDataReader = SQLExecute("SELECT * FROM TableOfAwesomeness WHERE BestTVShow LIKE 'Arrested Development%'") ``` Would work. However ``` Function MethodOfReturningHorror(ByVal TVShow as String) as SqlDataReader { dim command as new SQLCommand command.connection = sqlconnection command.CommandText = "SELECT * FROM TableOfAwesomeness WHERE BestTVShow LIKE '@tvShow%'" command.Parameters.Add("tvShow",TVShow) return command.ExecuteReader() } ``` I have missed out code unrelated to the question for the sake of laziness/conciseness. So ignore the return bit and and stuff, all that is important is that the data reader contains nothing, while It does in the first example. I am sure it's to do with the parametrisation of the LIKE clause . Thanks!
Try this: ``` command.CommandText = "SELECT * FROM TableOfAwesomeness WHERE BestTVShow LIKE @tvShow + '%'" ```
Try appending the '%' to the end of the parameter string rather than embedding it in the sql.
Parameterised query breaks when doing LIKE condition. Why?
[ "", "sql", ".net", "parameters", "sql-like", "" ]
While looking for an SFTP client in C# SSH File Transfer Protocol (SFTP), I've come across these two suitable projects - [one](http://sourceforge.net/projects/sharpssh) and [two](http://granados.sourceforge.net/). While trying to understand the basics, I came across this confusing [Wikipedia article](http://en.wikipedia.org/wiki/FTP_over_SSH#FTP_over_SSH_.28not_SFTP.29). What is difference between SFTP and FTP over SSH? No library seems to give support for "FTP over SSH", if it is different.
Here is the difference: * [SFTP](http://en.wikipedia.org/wiki/SSH_File_Transfer_Protocol) (SSH file transfer protocol) is a protocol that provides file transfer and manipulation capabilities. It can work over any reliable data stream, but is typically used with SSH * "FTP over SSH" uses the regular old FTP protocol, but an [SSH tunnel](http://en.wikipedia.org/wiki/Tunneling_protocol#SSH_tunneling) is placed between client and server. You probably won't find libraries for "FTP over SSH" because typically the tunnel is set up by running an SSH command, and once it is set up, clients and servers don't need to know about the tunnel; they just open ports and transfer data they way they would without a tunnel. BTW, yet another option for you might be [FTP over SSL (FTPS)](http://en.wikipedia.org/wiki/FTPS), which is supported by .NET. (See <http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.enablessl.aspx>.)
Basically, there are the following file transfer protocols around: * FTP – the plain old FTP protocol that has been around since 1970s. The acronym stands for "File Transfer Protocol". It usually runs over TCP port 21. * SFTP – another, completely different file transfer protocol that has nothing to do with FTP. SFTP runs over an SSH session, usually on TCP port 22. It has been around since late 1990s. The acronym actually stands for "SSH File Transfer Protocol". * FTP over SSH - 1) possible, but extremely rare example of FTP protocol tunneled through a SSH channel 2) incorrectly named SFTP (for details see "[Secure FTP, FTP/SSL, SFTP, FTPS, FTP, SCP... What's the difference?](https://www.rebex.net/kb/secure-ftp/)" page at [Rebex](http://www.rebex.net)) Disclaimer: I work for Rebex
Differences between SFTP and "FTP over SSH"
[ "", "c#", "ftp", "ssh", "sftp", "" ]
> **Possible Duplicate:** > [JavaScript data formatting/pretty printer](https://stackoverflow.com/questions/130404/javascript-data-formatting-pretty-printer) I am getting a bit tired of looking at unformatted json blobs in FireBug. Does anyone know an equivalent to PHP's print\_r() for jQuery? Something that would recursively make a display string from an object or array, that I could display on the page for quick debugging? Thanks!
[`console.log`](http://getfirebug.com/wiki/index.php/Console_API#console.log.28object.5B.2C_object.2C_....5D.29) is what I most often use when debugging. I was able to find this [`jQuery extension`](http://plugins.jquery.com/taxonomy/term/471) though.
You could use very easily [reflection](http://pietschsoft.com/post/2008/02/Simple-JavaScript-Object-Reflection-API-(NET-Style).aspx) to list all properties, methods and values. For Gecko based browsers you can use the .toSource() method: ``` var data = new Object(); data["firstname"] = "John"; data["lastname"] = "Smith"; data["age"] = 21; alert(data.toSource()); //Will return "({firstname:"John", lastname:"Smith", age:21})" ``` But since you use Firebug, why not just use console.log?
jQuery: print_r() display equivalent?
[ "", "php", "jquery", "debugging", "" ]
Actually what i am trying to build is like a kind of firewall. It should be able to get to know all the requests going from my machine. It should be able to stop selected ones. I am not sure how to even start about with this. I am having VS 2008/2005 with framework 2.0. Please let me know if there is any particular class i can start with and is there any samples i can get.
Firewalls really should be implemented fairly low in the networking stack; I'd strongly suggest NDIS. [This article](http://www.codeproject.com/KB/IP/drvfltip.aspx) may be of interest.
Something like this may help you get started: <http://www.mentalis.org/soft/projects/pmon/> > This C# project allows Windows NT administrators to intercept IP packets sent through one of the network interfaces on the computer. This can be very handy to debug network software or to monitor the network activity of untrusted applications.
How to build a kind of firewall
[ "", "c#", "visual-studio", "firewall", "" ]
I attempted to open a Java bug last Halloween. I immediately got a response that my submission was accepted, and have heard nothing since. Looking at Sun's web pages, I can't found any contact information where I can inquire. Almost two weeks ago I made a post in the [Sun forums](http://forums.sun.com/thread.jspa?threadID=5361055) in what appears to be the most appropriate area and have no response there either. Has anyone had success getting Sun to open a bug report after a long period of non-response? Does anyone know who I can contact to find out the current status of my bug report? For what it's worth, the internal review ID I was given is 1380005. Edit, added later: For the curious: What is the bug? The Java Web Start client, when downloading JAR files (or anything else), **always** adds an `If-Modified-Since` header (with a time-date equivalent of "`-1`" -- 1 second before midnight 1-1-1970 -- no matter whether the Java cache is empty or full) and **always** adds a `No-Cache` header. Note: This is the **client** side that supplies the `No-Cache` header!
I've had mixed results when submitting bug reports. I've submitted quite a few bug reports/RFE's related to the `java.util.regex` package; they always appeared in the public database within a few weeks, and were usually resolved to my satisfaction fairly quickly. But that's probably because the regex package is small and largely self-contained. I've also submitted a few Swing-related bug reports, and they always took ages to go through, if they went through at all. But I discovered two things I could do to speed things up: post questions about the bugs in the [JavaDesktop forums](http://forums.java.net/jive/category.jspa?categoryID=53), and submit patches. It's been a year or more since I was there last, but back then there were actual Sun employees participating those forums, and if they saw merit in your bug report, they could shepherd it through the system--especially if you submitted a patch.
Did you get an email telling you that your bug report will appear in the [Bug Database](http://bugs.sun.com/) soon? I filed a report once and it took about a week before appearing in the public database. There are also some caveats regarding bugs that will not be on the public database because of "[security reasons](http://developers.sun.com/resources/bugsFAQ.html)".
How does one successfully open a Java bug if Sun doesn't respond?
[ "", "java", "bug-tracking", "no-response", "" ]
I have a script that loops through a series of four (or less) characters strings. For example: ``` aaaa aaab aaac aaad ``` If have been able to implement it with nested for loops like so: ``` chars = string.digits + string.uppercase + string.lowercase for a in chars: print '%s' % a for b in chars: print '%s%s' % (a, b) for c in chars: print '%s%s%s' % (a, b, c) for d in chars: print '%s%s%s%s' % (a, b, c, d) ``` Is this sort of loop nesting a bad thing, and if so, what would be a better way of accomplishing what I am doing?
``` import string import itertools chars = string.digits + string.letters MAX_CHARS = 4 for nletters in range(MAX_CHARS): for word in itertools.product(chars, repeat=nletters + 1): print (''.join(word)) ``` That'll print all **`15018570`** words you're looking for. If you want more/less words just change the `MAX_CHARS` variable. It will still have just two `for`s for any number of chars, and you don't have to repeat yourself. And is pretty readable. .
I'm going to submit my answer as the most readable and least scalable :) ``` import string chars = [''] + list(string.lowercase) strings = (a+b+c+d for a in chars for b in chars for c in chars for d in chars) for string in strings: print string ``` EDIT: Actually, this is incorrect, as it will produce duplicates of all strings of length<4. Removing the empty string from the `chars` array would just produce 4-char strings. Normally I'd delete this answer, but I still kinda like it if you need to generate strings of the same length.
Replace Nested For Loops... or not
[ "", "python", "loops", "for-loop", "nested-loops", "" ]
I have a template I made that sets variables that rarely change, call my headers, calls my banner and sidebar, loads a variable which shows the individual pages, then calls the footer. In one of my headers, I want the URL of the page in the user's address bar. Is there a way to do this? Currently: ``` <?php $title = "MySite - Contacts"; include("header.php"); . . . ?> ```
The main variables you'll be intersted in is: `$_SERVER['REQUEST_URI']` Holds the path visited, e.g. `/foo/bar` `$_SERVER['PHP_SELF']` is the path to the main PHP file (*NOT* the file you are in as that could be an include but the actual base file) There are a ton of other useful variables worth remembering in $\_SERVER, so either just: ``` print_r($_SERVER); ``` or just visit the doc at <http://php.net/manual/en/reserved.variables.server.php>
the Web address of the Page being called, can be obtained from the following function :: ``` function curPageURL() { $pageURL = 'http'; if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";} $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; } else { $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; } return $pageURL; } ``` I have been using this in many places, found on google.
PHP - Find URL of script that included current document
[ "", "php", "url", "include", "" ]
What's the best way in PHP to sort an array of arrays based on array length? e.g. ``` $parent[0] = array(0, 0, 0); $parent[2] = array("foo", "bar", "b", "a", "z"); $parent[1] = array(4, 2); $sorted = sort_by_length($parent) $sorted[0] = array(4, 2); $sorted[1] = array(0, 0, 0); $sorted[2] = array("foo", "bar", "b", "a", "z"); ```
This will work: ``` function sort_by_length($arrays) { $lengths = array_map('count', $arrays); asort($lengths); $return = array(); foreach(array_keys($lengths) as $k) $return[$k] = $arrays[$k]; return $return; } ``` Note that this function will preserve the numerical keys. If you want to reset the keys, wrap it in a call to [array\_values()](http://www.php.net/array_values).
I'm upvoting Peter's but here's another way, I think: ``` function cmp($a1, $a2) { if (count($a1) == count($a2)) { return 0; } return (count($a1) < count($a2)) ? -1 : 1; } usort($array, "cmp"); ```
Sorting an array of arrays by the child array's length?
[ "", "php", "arrays", "sorting", "" ]
Ran across this line of code: ``` FormsAuth = formsAuth ?? new FormsAuthenticationWrapper(); ``` What do the two question marks mean, is it some kind of ternary operator? It's hard to look up in Google.
It's the null coalescing operator, and quite like the ternary (immediate-if) operator. See also [?? Operator - MSDN](https://learn.microsoft.com/en-in/dotnet/csharp/language-reference/operators/null-coalescing-operator). ``` FormsAuth = formsAuth ?? new FormsAuthenticationWrapper(); ``` expands to: ``` FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper(); ``` which further expands to: ``` if(formsAuth != null) FormsAuth = formsAuth; else FormsAuth = new FormsAuthenticationWrapper(); ``` In English, it means "If whatever is to the left is not null, use that, otherwise use what's to the right." Note that you can use any number of these in sequence. The following statement will assign the first non-null `Answer#` to `Answer` (if all Answers are null then the `Answer` is null): ``` string Answer = Answer1 ?? Answer2 ?? Answer3 ?? Answer4; ``` --- Also it's worth mentioning while the expansion above is conceptually equivalent, the result of each expression is only evaluated once. This is important if for example an expression is a method call with side effects. (Credit to @Joey for pointing this out.)
Just because no-one else has said the magic words yet: it's the **null coalescing operator**. It's defined in section 7.12 of the [C# 3.0 language specification](http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc). It's very handy, particularly because of the way it works when it's used multiple times in an expression. An expression of the form: ``` a ?? b ?? c ?? d ``` will give the result of expression `a` if it's non-null, otherwise try `b`, otherwise try `c`, otherwise try `d`. It short-circuits at every point. Also, if the type of `d` is non-nullable, the type of the whole expression is non-nullable too.
What do two question marks together mean in C#?
[ "", "c#", "null-coalescing-operator", "" ]
I have my resource and they typical overridden method to handle POST requests. ``` public void acceptRepresentation(Representation rep) { if (MediaType.APPLICATION_XML.equals(rep.getMediaType())) { //Do stuff here } else { //complain! } } ``` What I want to know is the best practice to handle my packet of XML. I see a lot of examples using a Form - but surely there is a way to work with the Representation object itself or cast it to some useful XML object??? Any help on how you should and do parse incoming XML in your resource is much appreciated.
This is more of the kind of response I was looking for. Thanks to [Thierry Boileau](http://restlet.tigris.org/ds/viewMessage.do?dsForumId=4447&dsMessageId=1024110) for the answer: > You can use two kinds of "XML > representations": DomRepresentation > and SaxRepresentation. You can > instantiate both of them with the > posted representation. E.g.: > DomRepresentation xmlRep = new > DomRepresentation(rep); > > The DomRepresentation gives you access > to the Dom document. The > SaxRepresentation allows you to parse > the XML doc with your own > contentHandler. See the javadocs here > 1 and here 2. > > 1. [http://www.restlet.org/documentation/1.1/api/org/restlet/res​ource/DomRepresentat​ion.html](http://www.restlet.org/documentation/1.1/api/org/restlet/res%E2%80%8Bource/DomRepresentat%E2%80%8Bion.html) > 2. [http://www.restlet.o​rg/documentation/1.1​/api/org/restlet/res​ource/SaxRepresentat​ion.html](http://www.restlet.o%E2%80%8Brg/documentation/1.1%E2%80%8B/api/org/restlet/res%E2%80%8Bource/SaxRepresentat%E2%80%8Bion.html)
We currently do this using RESTeasy, which is an alternative JAX-RS implementation. We use JAXB bindings (annotations) to map between the XML and our model POJOs, and specify a *JAXB provider* to JAX-RS so it knows how. This is described in our [RESTful web services in Java EE with RESTEasy (JAX-RS) article](http://www.lunatech-research.com/archives/2008/03/20/restful-web-sevices-resteasy-jax-rs), which may help. Update: for Restlet, the [JAXB extension](http://wiki.restlet.org/docs_1.1/13-restlet/28-restlet/67-restlet.html) might be what you need.
REST web service accepting a POST using Restlet - Best Practice
[ "", "java", "web-services", "rest", "post", "restlet", "" ]
Looking at the [unicode standard](http://www.unicode.org/versions/Unicode5.0.0/ch05.pdf#G23927), they recommend to use plain `char`s for storing UTF-8 encoded strings. Does this work as expected with C++ and the basic `std::string`, or do cases exist in which the UTF-8 encoding can create problems? For example, when computing the length, it may not be identical to the number of bytes - how is this supposed to be handled? Reading the standard, I'm probably fine using a `char` array for storage, but I'll still need to write functions like `strlen` etc. on my own, which work on encoded text, cause as far as I understand the problem, the standard routines are either ASCII only, or expect wide literals (16bit or more), which are not recommended by the unicode standard. So far, the best source I found about the encoding stuff is a post on [Joel's on Software](http://www.joelonsoftware.com/articles/Unicode.html), but it does not explain what we poor C++ developer should use :)
There's a library called "[UTF8-CPP](http://utfcpp.sourceforge.net/)", which lets you store your UTF-8 strings in standard std::string objects, and provides additional functions to enumerate and manipulate utf-8 characters. I haven't tested it yet, so I don't know what it's worth, but I am considering using it myself.
An example with [ICU library](http://icu-project.org/) (C, C++, Java): ``` #include <iostream> #include <unicode/unistr.h> // using ICU library int main(int argc, char *argv[]) { // constructing a Unicode string UnicodeString ustr1("Привет"); // using platform's default codepage // calculating the length in characters, should be 6 int ulen1=ustr1.length(); // extracting encoded characters from a string int const bufsize=25; char encoded[bufsize]; ustr1.extract(0,ulen1,encoded,bufsize,"UTF-8"); // forced UTF-8 encoding // printing the result std::cout << "Length of " << encoded << " is " << ulen1 << "\n"; return 0; } ``` building like ``` $ g++ -licuuc -o icu-example{,.cc} ``` running ``` $ ./icu-example Length of Привет is 6 ``` Works for me on Linux with GCC 4.3.2 and libicu 3.8.1. Please note that it prints in UTF-8 no matter what the system locale is. You won't see it correctly if yours is not UTF-8.
What is the best way to store UTF-8 strings in memory in C/C++?
[ "", "c++", "unicode", "" ]
Does anyone know how to maintain text formatting when using XPath to extract data? I am currently extracting all blocks `<div class="info"> <h5>title</h5> text <a href="somelink">anchor</a> </div>` from a page. The problem is when I access the nodeValue, I can only get plain text. How can I capture the contents including formatting, i.e. the h5 and a still in the code? Thanks in advance. I have searched every combination imaginable on Google and no luck.
If you have it as a DomElement $element as part of a DomDocument $dom then you will want to do something like: ``` $string = $dom->saveXml($element); ``` The NodeValue of an element is really the textual value, not the structured XML.
I would like to add to Ciaran McNulty answer You can do the same in SimpleXml like: ``` $simplexml->node->asXml(); // saveXml() is now an alias ``` And to expand on the quote > The NodeValue of an element is really the textual value, not the structured XML. You can think of your node as follows: ``` <div class="info"> <__toString()> </__toString()> <h5>title</h5> <__toString()> text </__toString()> <a href="somelink">anchor</a> <__toString()> </__toString()> </div> ``` Where the call to `$element->nodeValue` is like calling `$element->__toString()` which would only get the \_\_toString() elements. The imaginary `__toString()` I created is officially defined as an [`XML_TEXT_NODE`](http://us.php.net/manual/en/domxml.constants.php).
Screen Scraping with PHP and XPath
[ "", "php", "xpath", "screen-scraping", "" ]
Is it possible to use the `__call` magic method when calling functions statically?
Not yet, there is a proposed (now available) [`__callStatic`*Docs*](http://php.net/language.oop5.overloading#object.callstatic) method in the pipeline last I knew. Otherwise `__call` and the other `__` magic methods are not available for use by anything but the instance of a object.
You have to use the *other* magic method, [`__callStatic`](https://www.php.net/language.oop5.overloading) - this is only available in PHP >= 5.3, which hasn't actually been released yet.
Using __call with static classes?
[ "", "php", "oop", "static", "magic-methods", "" ]
< backgound> I'm at a point where I really need to optimize C++ code. I'm writing a library for molecular simulations and I need to add a new feature. I already tried to add this feature in the past, but I then used virtual functions called in nested loops. I had bad feelings about that and the first implementation proved that this was a bad idea. However this was OK for testing the concept. < /background> Now I need this feature to be as fast as possible (well without assembly code or GPU calculation, this still has to be C++ and more readable than less). Now I know a little bit more about templates and class policies (from Alexandrescu's excellent book) and I think that a compile-time code generation may be the solution. However I need to test the design before doing the *huge* work of implementing it into the library. The question is about the best way to test the efficiency of this new feature. Obviously I need to turn optimizations on because without this g++ (and probably other compilers as well) would keep some unnecessary operations in the object code. I also need to make a heavy use of the new feature in the benchmark because a delta of 1e-3 second can make the difference between a good and a bad design (this feature will be called million times in the real program). The problem is that g++ is sometimes "too smart" while optimizing and can remove a whole loop if it consider that the result of a calculation is never used. I've already seen that once when looking at the output assembly code. If I add some printing to stdout, the compiler will then be forced to do the calculation in the loop but I will probably mostly benchmark the iostream implementation. So how can I do a **correct** benchmark of a little feature extracted from a library ? Related question: is it a correct approach to do this kind of *in vitro* tests on a small unit or do I need the whole context ? Thanks for advices ! --- There seem to be several strategies, from compiler-specific options allowing fine tuning to more general solutions that should work with every compiler like `volatile` or `extern`. I think I will try all of these. Thanks a lot for all your answers!
If you want to force *any* compiler to not discard a result, have it write the result to a volatile object. That operation cannot be optimized out, by definition. ``` template<typename T> void sink(T const& t) { volatile T sinkhole = t; } ``` No iostream overhead, just a copy that has to remain in the generated code. Now, if you're collecting results from a lot of operations, it's best not to discard them one by one. These copies can still add some overhead. Instead, somehow collect all results in a single non-volatile object (so all individual results are needed) and then assign that result object to a volatile. E.g. if your individual operations all produce strings, you can force evaluation by adding all char values together modulo 1<<32. This adds hardly any overhead; the strings will likely be in cache. The result of the addition will subsequently be assigned-to-volatile so each char in each sting must in fact be calculated, no shortcuts allowed.
**edit**: the easiest thing you can do is simply use the data in some spurious way after the function has run and outside your benchmarks. Like, ``` StartBenchmarking(); // ie, read a performance counter for (int i=0; i<500; ++i) { coords[i][0] = 3.23; coords[i][1] = 1.345; coords[i][2] = 123.998; } StopBenchmarking(); // what comes after this won't go into the timer // this is just to force the compiler to use coords double foo; for (int j = 0 ; j < 500 ; ++j ) { foo += coords[j][0] + coords[j][1] + coords[j][2]; } cout << foo; ``` --- What sometimes works for me in these cases is to hide the *in vitro* test inside a function and pass the benchmark data sets through **volatile** pointers. This tells the compiler that it must not collapse subsequent writes to those pointers (because they might be *eg* memory-mapped I/O). So, ``` void test1( volatile double *coords ) { //perform a simple initialization of all coordinates: for (int i=0; i<1500; i+=3) { coords[i+0] = 3.23; coords[i+1] = 1.345; coords[i+2] = 123.998; } } ``` For some reason I haven't figured out yet it doesn't always work in MSVC, but it often does -- look at the assembly output to be sure. Also remember that **volatile** will foil some compiler optimizations (it forbids the compiler from keeping the pointer's contents in register and forces writes to occur in program order) so this is only trustworthy if you're using it for the final write-out of data. In general in vitro testing like this is very useful so long as you remember that it is not the whole story. I usually test my new math routines in isolation like this so that I can quickly iterate on just the cache and pipeline characteristics of my algorithm on consistent data. The difference between test-tube profiling like this and running it in "the real world" means you will get wildly varying input data sets (sometimes best case, sometimes worst case, sometimes pathological), the cache will be in some unknown state on entering the function, and you may have other threads banging on the bus; so you should run some benchmarks on this function *in vivo* as well when you are finished.
How to correctly benchmark a [templated] C++ program
[ "", "c++", "optimization", "benchmarking", "" ]
I've been thinking about playing with [Java3D](https://java3d.dev.java.net/). But first I would like to know if anyone has done much with it? What types of projects have you done and what tutorials/examples/guides did you use to learn it? What are your general thoughts about the API? Is it well developed? Can you program games or do any physical modeling with it? Thanks for your input. Also, not sure what good tags are so feel free to change them as you see fit.
I have tried to develop in it about 4-5 years ago, and my impression is that while it was initially a great idea and had some good design going for it, Sun eventually stopped working on it and moved it to the purgatory of a "community project" where it has slowly been dying. I was working at the time on a 3D conferencing application and kept running around barriers in the implementation on my platform, with other mechanisms (e.g., 3D sound), rendering options, embedding, etc... The API is simply not rich enough compared to what you could get with things like DirectX or OpenGL and isn't sufficiently supported.
If you want to experiment with 3D, it's far easier to get up and running than to try to do anything with DirectX (although the DirectX API more closely matches what game developers actually do, of course). The fact that it's community-supported does mean you won't get a lot of richness today, but for a lot of tools, it's still plenty capable. For instance, a simple data visualization tool for business - not for games - is easy to do in Java3D (this is what I use it for, mostly).
Java3D: Tutorials, Projects, General 3D Programming
[ "", "java", "java-3d", "" ]
I'm using the [jQuery Validation plugin](http://docs.jquery.com/Plugins/Validation) and I've got a textbox with the class `digits` to force it to be digits only, but not required. When I call validate on the form it works fine, but if I call `valid()` on the textbox when it's empty, it returns 0, despite no error message showing and required not being set. Does anyone know why it would be returning this for a seemingly valid input value? Here is the code: ``` <input type="text" value="" name="kiloMetresTravelled" id="kiloMetresTravelled" class="digits"/> ``` and the script ``` <script type="text/javascript'> var isvalid = jQuery('#kiloMetresTravelled').valid(); //isvalid == 0 when kiloMetresTravelled is blank </script> ```
Check this, from the [documentation](http://docs.jquery.com/Plugins/Validation/Methods/digits): > Makes "field" required and digits > only. You could do something like this: ``` var isValid = jQuery('#kiloMetresTravelled').valid() || jQuery('#kiloMetresTravelled').val() == ""; ```
I think this works: ``` var e="#whatever"; var isValid = $(e).valid() || $(e).val()== "" && !$(e).hasClass('required'); ```
The jQuery Validation `valid()` method returns 0 when required is not true
[ "", "javascript", "jquery", "validation", "jquery-validate", "" ]
I consider myself quite fluent in PHP and am rather familiar with nearly all of the important aspects and uses, as well as its pratfalls. This in mind, I think the major problem in taking on Perl is going to be with the syntax. Aside from this (a minor hindrance, really, as I'm rather sold on the fact that Perl's is far more readable), what are some key differences you think I should make myself aware of prior to taking on the language?
some different things worth a read about: * packages * lexical scopes * regular expression syntax * hashes, arrays and lists (all the same in PHP, all different in Perl) * CPAN
After you learn the basics of Perl, I highly recommend the book "[Perl Best Practices](http://oreilly.com/catalog/9780596001735/)" by Damian Conway. It really changes your writing style, and the way you think about programming, and in particular, makes your Perl programs much more readable, and maintainable.
As a PHP developer thinking of making Perl a secondary strong suit, what do I need to know?
[ "", "php", "perl", "" ]
Given a string with replacement keys in it, how can I most efficiently replace these keys with runtime values, using **Java**? I need to do this often, fast, and on reasonably long strings (say, on average, 1-2kb). The form of the keys is my choice, since I'm providing the templates here too. Here's an example (please don't get hung up on it being XML; I want to do this, if possible, cheaper than using XSL or DOM operations). I'd want to replace all `@[^@]*?@` patterns in this with property values from bean properties, true `Property` properties, and some other sources. The key here is *fast*. Any ideas? ``` <?xml version="1.0" encoding="utf-8"?> <envelope version="2.3"> <delivery_instructions> <delivery_channel> <channel_type>@CHANNEL_TYPE@</channel_type> </delivery_channel> <delivery_envelope> <chan_delivery_envelope> <queue_name>@ADDRESS@</queue_name> </chan_delivery_envelope> </delivery_envelope> </delivery_instructions> <composition_instructions> <mime_part content_type="application/xml"> <content><external_uri>@URI@</external_uri></content> </mime_part> </composition_instructions> </envelope> ``` The naive implementation is to use `String.replaceAll()` but I can't help but think that's less than ideal. If I can avoid adding new third-party dependencies, so much the better.
The appendReplacement method in [Matcher](http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html) looks like it might be useful, although I can't vouch for its speed. Here's the sample code from the Javadoc: ``` Pattern p = Pattern.compile("cat"); Matcher m = p.matcher("one cat two cats in the yard"); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, "dog"); } m.appendTail(sb); System.out.println(sb.toString()); ``` **EDIT:** If this is as complicated as it gets, you could probably implement your own state machine fairly easily. You'd pretty much be doing what appendReplacement is already doing, although a specialized implementation might be faster.
It's premature to leap to writing your own. I would start with the naive replace solution, and actually benchmark that. Then I would try a third-party templating solution. THEN I would take a stab at the custom stream version. Until you get some hard numbers, how can you be sure it's worth the effort to optimize it?
I need a fast key substitution algorithm for java
[ "", "java", "algorithm", "optimization", "string", "" ]
I have written some code that works pretty well, but I have a strange bug Here is an example... --- ## **[PLEASE WATCH MY COMBOBOX BUG VIDEO](http://vimeo.com/3112710)** --- Like I said, this works well every time datachanged fires - the right index is selected and the displayField is displayed but, everytime after I type some text in the combobox, later, when the "datachanged" fires, it wont display the displayField. Instead, it displays the value from the setValue method I launch. The strange thing is that if I don't ever type text and change the selection with the mouse there is no bug. Finally, this appears only when I type text in the combobox. Has anyone heard of this bug, have a solution, or some wise advice? ## The Code ! **Two data stores** : ``` ficheDataStore = new Ext.data.Store({ id: 'ficheDataStore', autoLoad: true, proxy: new Ext.data.HttpProxy({ url: 'ficheDetail.aspx', // File to connect to method: 'GET' }), baseParams: { clientId: clientId, Type: 'Fiche' }, // this parameter asks for listing reader: new Ext.data.JsonReader({ // we tell the datastore where to get his data from root: 'results' }, [ { name: 'GUID', type: 'string', mapping: 'GUID' }, { name: 'TagClient', type: 'string', mapping: 'TagClient' }, { name: 'Nom', type: 'string', mapping: 'Nom' }, { name: 'Compteur', type: 'string', mapping: 'CompteurCommunes' }, { name: 'CompteurCommunesFacturation', type: 'string', mapping: 'CompteurCommunesFacturation' }, { name: 'AdresseFacturation', type: 'string', mapping: 'AdresseFacturation' }, { name: 'Codes', type: 'string', mapping: 'Codes' }, { name: 'Observations', type: 'string', mapping: 'Observations' }, { name: 'Adresse', type: 'string', mapping: 'Adresse' } ]) }); communesDataStore = new Ext.data.Store({ autoLoad: true, proxy: new Ext.data.HttpProxy({ url: 'ficheDetail.aspx?Type=Communes' }), reader: new Ext.data.JsonReader({ root: 'results' }, [{ name: 'Compteur' }, { name: 'Localisation'}]) }); ``` --- > Who return something like this for the > first: ``` {results:[{"Nom":"cercle interieur"},{"Observations":""},{"Codes":" "},{"Adresse":"dd"},{"CompteurCommunes" :"1"},{"TagClient":"3-56"},{"GUID":"443609c6-d064-4676-a492-7baa7b4288d1"},{"AdresseFacturation":""} ,{"CompteurCommunesFacturation":"1"}]} ``` > For the latter : ``` {"results":[{ "Compteur" : "1","Localisation" : "6200 ST ISIDORE"},{ "Compteur" : "2","Localisation" : "21340 CHANGE"},{ "Compteur" : "3","Localisation" : "1200 ELOISE"},{ "Compteur" : "4","Localisation" : "1200 ST GERMAIN SUR RHONE"},{ "Compteur" : "5","Localisation" : "75000 PARIS"},{ "Compteur" : "6" ,"Localisation" : "75001 PARIS 1ER ARRONDISSEMENT"}]} ``` --- **a `Combobox`** : ``` var comb = new Ext.form.ComboBox( { store: communesDataStore, fieldLabel: 'Code postal', // hiddenName: 'Compteur', name: 'CompteurCommune', id: 'CompteurCommunes', width: 300, typeAhead: true, mode: 'local', minChars: 0, selecOnFocus: true, forceSelection: true, valueField: 'Compteur', displayField: 'Localisation', autocomplete: true, emptyText: 'Selectionnez un code postal', triggerAction: 'all', value: '' }); ``` in a **`datachanged`** event i set the new value of the **`Combobox`** "CompteurCommunes" : ``` ficheDataStore.addListener('datachanged', handleDatachangedEvent); function handleDatachangedEvent() { try { comb.setValue(ficheDataStore.getAt(4).data.Compteur); } catch (err) { } } ```
It's probably because when you type random data into combo, it may not locate correct fieldValue every time. Then it *stucks* at the last non-existing value. Try to set ComboBox to any *existing* value (in combo's datastore) before doing new setValue() in your datachanged event handler. Or you can try to use clearValue() method to reset the previous (undefined) valueField. There also initList() method existing to reset combo to initial state. EDIT: After some testing, I found that: **combo.store.clearFilter();** must be used before setValue in the external event handler.
``` function formatComboBox(value, metaData, record, rowIndex, colIndex, store) { myStore = Ext.getCmp('myComboBox'); myStore.clearFilter(); var idx = myStore.find('value',value); return (idx != '-1') ? myStore.getAt(idx).data.label : value; } ```
EXTJS Combobox not selecting by valueField after expand
[ "", "javascript", "combobox", "extjs", "" ]
The Java [`Collections.max`](https://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#max(java.util.Collection)) method takes only a collection of a sortable ([`Comparable`](https://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html)) object. However since the collection is not necessarily sorted, I don't see any reason not to implement the same max function for [`Iterable`](https://docs.oracle.com/javase/6/docs/api/java/lang/Iterable.html) types. Is there a max method for `Iterable<T extends Comparable<? super T>>` in Java's standard library?
`Collections.max` was introduced in 1.2. `Iterable` was introduced in 1.5. It's rare to have an `Iterable` that is not a `Collection`. If you do then it's straightforward to implement (be careful to read the spec). If you think it is really important you can submit an RFE in the [Java Bug Database](https://bugs.java.com/bugdatabase/) (or vote if there is already one there).
While Guava is not Java's standard library, it's close enough... [`E com.google.common.collect.Ordering#max(Iterable<E> iterable)`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Ordering.html#max%28java.lang.Iterable%29) e.g. `T max = Ordering.natural().max(myIterable);` As to why the standard library does not implement it, it may be because [a Collection must be finite](http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#size()), but [an Iterable need not be](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Iterables.html#cycle%28T...%29)—and, arguably, one should *never* accept an Iterable if a non-terminating Iterable would cause your code to loop forever.
Collections.max function for Iterable<Integer> in Java
[ "", "java", "collections", "max", "standard-library", "" ]
As someone new to GUI development in Python (with pyGTK), I've just started learning about threading. To test out my skills, I've written a simple little GTK interface with a start/stop button. The goal is that when it is clicked, a thread starts that quickly increments a number in the text box, while keeping the GUI responsive. I've got the GUI working just fine, but am having problems with the threading. It is probably a simple problem, but my mind is about fried for the day. Below I have pasted first the trackback from the Python interpreter, followed by the code. You can go to <http://drop.io/pxgr5id> to download it. I'm using bzr for revision control, so if you want to make a modification and re-drop it, please commit the changes. I'm also pasting the code at <http://dpaste.com/113388/> because it can have line numbers, and this markdown stuff is giving me a headache. Update 27 January, 15:52 EST: Slightly updated code can be found here: <http://drop.io/threagui/asset/thread-gui-rev3-tar-gz> **Traceback** ``` crashsystems@crashsystems-laptop:~/Desktop/thread-gui$ python threadgui.pybtnStartStop clicked Traceback (most recent call last): File "threadgui.py", line 39, in on_btnStartStop_clicked self.thread.stop() File "threadgui.py", line 20, in stop self.join() File "/usr/lib/python2.5/threading.py", line 583, in join raise RuntimeError("cannot join thread before it is started") RuntimeError: cannot join thread before it is started btnStartStop clicked threadStop = 1 btnStartStop clicked threadStop = 0 btnStartStop clicked Traceback (most recent call last): File "threadgui.py", line 36, in on_btnStartStop_clicked self.thread.start() File "/usr/lib/python2.5/threading.py", line 434, in start raise RuntimeError("thread already started") RuntimeError: thread already started btnExit clicked exit() called ``` **Code** ``` #!/usr/bin/bash import gtk, threading class ThreadLooper (threading.Thread): def __init__ (self, sleep_interval, function, args=[], kwargs={}): threading.Thread.__init__(self) self.sleep_interval = sleep_interval self.function = function self.args = args self.kwargs = kwargs self.finished = threading.Event() def stop (self): self.finished.set() self.join() def run (self): while not self.finished.isSet(): self.finished.wait(self.sleep_interval) self.function(*self.args, **self.kwargs) class ThreadGUI: # Define signals def on_btnStartStop_clicked(self, widget, data=None): print "btnStartStop clicked" if(self.threadStop == 0): self.threadStop = 1 self.thread.start() else: self.threadStop = 0 self.thread.stop() print "threadStop = " + str(self.threadStop) def on_btnMessageBox_clicked(self, widget, data=None): print "btnMessageBox clicked" self.lblMessage.set_text("This is a message!") self.msgBox.show() def on_btnExit_clicked(self, widget, data=None): print "btnExit clicked" self.exit() def on_btnOk_clicked(self, widget, data=None): print "btnOk clicked" self.msgBox.hide() def on_mainWindow_destroy(self, widget, data=None): print "mainWindow destroyed!" self.exit() def exit(self): print "exit() called" self.threadStop = 1 gtk.main_quit() def threadLoop(self): # This will run in a thread self.txtThreadView.set_text(str(self.threadCount)) print "hello world" self.threadCount += 1 def __init__(self): # Connect to the xml GUI file builder = gtk.Builder() builder.add_from_file("threadgui.xml") # Connect to GUI widgets self.mainWindow = builder.get_object("mainWindow") self.txtThreadView = builder.get_object("txtThreadView") self.btnStartStop = builder.get_object("btnStartStop") self.msgBox = builder.get_object("msgBox") self.btnMessageBox = builder.get_object("btnMessageBox") self.btnExit = builder.get_object("btnExit") self.lblMessage = builder.get_object("lblMessage") self.btnOk = builder.get_object("btnOk") # Connect the signals builder.connect_signals(self) # This global will be used for signaling the thread to stop. self.threadStop = 1 # The thread self.thread = ThreadLooper(0.1, self.threadLoop, (1,0,-1)) self.threadCounter = 0 if __name__ == "__main__": # Start GUI instance GUI = ThreadGUI() GUI.mainWindow.show() gtk.main() ```
Threading with PyGTK is bit tricky if you want to do it right. Basically, you should not update GUI from within any other thread than main thread (common limitation in GUI libs). Usually this is done in PyGTK using mechanism of queued messages (for communication between workers and GUI) which are read periodically using timeout function. Once I had a presentation on my local LUG on this topic, you can grab example code for this presentation from [Google Code repository](http://code.google.com/p/leechfm/). Have a look at `MainWindow` class in `forms/frmmain.py`, specially for method `_pulse()` and what is done in `on_entry_activate()` (thread is started there plus the idle timer is created). ``` def on_entry_activate(self, entry): text = entry.get_text().strip() if text: store = entry.get_completion().get_model() if text not in [row[0] for row in store]: store.append((text, )) thread = threads.RecommendationsFetcher(text, self.queue)# <- 1 self.idle_timer = gobject.idle_add(self._pulse)# <- 2 tv_results = self.widgets.get_widget('tv_results') model = tv_results.get_model() model.clear() thread.setDaemon(True)# <- 3 progress_update = self.widgets.get_widget('progress_update') progress_update.show() thread.start()# <- 4 ``` This way, application updates GUI when is "idle" (by GTK means) causing no freezes. * 1: create thread * 2: create idle timer * 3: daemonize thread so the app can be closed without waiting for thread completion * 4: start thread
Generally it's better to avoid threads when you can. It's very difficult to write a threaded application correctly, and even more difficult to know you got it right. Since you're writing a GUI application, it's easier for you to visualize how to do so, since you already have to write your application within an asynchronous framework. The important thing to realize is that a GUI application is doing a whole lot of nothing. It spends most of its time waiting for the OS to tell it that something has happened. You can do a lot of stuff in this idle time as long as you know how to write long-running code so it doesn't block. You can solve your original problem by using a timeout; telling your GUI framework to call back some function after a delay, and then resetting that delay or starting another delayed call. Another common question is how to communicate over the network in a GUI application. Network apps are like GUI apps in that they do a whole lot of waiting. Using a network IO framework (like [Twisted](http://twistedmatrix.com/)) makes it easy to have both parts of your application wait cooperatively instead of competitively, and again alleviates the need for extra threads. Long-running calculations can be written iteratively instead of synchronously, and you can do your processing while the GUI is idle. You can use a generator to do this quite easily in python. ``` def long_calculation(param, callback): result = None while True: result = calculate_next_part(param, result) if calculation_is_done(result): break else: yield callback(result) ``` Calling `long_calculation` will give you a generator object, and calling `.next()` on the generator object will run the generator until it reaches either `yield` or `return`. You would just tell the GUI framework to call `long_calculation(some_param, some_callback).next` when it has time, and eventually your callback will be called with the result. I don't know GTK very well, so I can't tell you which gobject functions you should be calling. With this explanation, though, you should be able to find the necessary functions in the documentation, or at worst, ask on a relevant IRC channel. Unfortunately there is no good general-case answer. If you clarify with exactly what you're trying to do, it would be easier to explain why you don't need threads in that situation.
Beginner-level Python threading problems
[ "", "python", "multithreading", "pygtk", "" ]
I have a long sequence of hex digits in a string, such as > 000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44 only much longer, several kilobytes. Is there a builtin way to convert this to a bytes object in python 2.6/3?
``` result = bytes.fromhex(some_hex_string) ```
Works in Python 2.7 and higher including python3: ``` result = bytearray.fromhex('deadbeef') ``` **Note:** There seems to be a bug with the `bytearray.fromhex()` function in Python 2.6. The python.org documentation states that the function accepts a string as an argument, but when applied, the following error is thrown: ``` >>> bytearray.fromhex('B9 01EF') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: fromhex() argument 1 must be unicode, not str` ```
How to create python bytes object from long hex string?
[ "", "python", "hex", "byte", "" ]
Can I pass "this" to a function as a pointer, from within the class constructor, and use it to point at the object's members before the constructor returns? Is it safe to do this, so long as the accessed members are properly initialized before the function call? As an example: ``` #include <iostream> class Stuff { public: static void print_number(void *param) { std::cout << reinterpret_cast<Stuff*>(param)->number; } int number; Stuff(int number_) : number(number_) { print_number(this); } }; void main() { Stuff stuff(12345); } ``` I thought this wouldn't work, but it seems to. Is this standard behavior, or just undefined behavior going my way?
When you instantiate an object in C++, the code in the constructor is the last thing executed. All other initialization, including superclass initialization, superclass constructor execution, and memory allocation happens beforehand. The code in the constructor is really just to perform additional initialization once the object is constructed. So it is perfectly valid to use a "this" pointer in a class' constructor and assume that it points to a completely constructed object. Of course, you still need to beware of uninitialized member variables, if you haven't already initialized them in your constructor code.
You can find a good answer to this [here](https://isocpp.org/wiki/faq/ctors#using-this-in-ctors) (C++ FAQ). All inherited members and members of the calling class are guaranteed to have been constructed at the start of the constructor's code execution and so can be referenced safely within it. The main gotcha is that you should not call virtual functions on `this`. Most times I've tried this it just ends up calling the base class's function, but I believe the standard says the result is undefined.
Passing "this" to a function from within a constructor?
[ "", "c++", "constructor", "this", "" ]
I am trying to use the axis-java2wsdl ant task to create a wsdl from one of my java classes, but I cannot get the classpath correct. I am using Ubuntu's libaxis-java package which installs axis-ant.jar in $ANT\_HOME/lib and axis.jar in /usr/share/java. The interesting parts of my build.xml look like this: ``` <property name="library.dir" value="lib"/> <property name="system.library.dir" value="/usr/share/java"/> <path id="libraries"> <fileset dir="${library.dir}"> <include name="*.jar"/> </fileset> <fileset dir="${system.library.dir}"> <include name="*.jar"/> </fileset> </path> <target name="genwsdl" depends="compile"> <taskdef resource="axis-tasks.properties" classpathref="libraries"/> <axis-java2wsdl> details omitted </axis-java2wsdl> </target> ``` Running `ant genwsdl` results in: ``` /build.xml:50: taskdef A class needed by class org.apache.axis.tools.ant.wsdl.Wsdl2javaAntTask cannot be found: org/apache/axis/utils/DefaultAuthenticator ``` Ant is able to find the definition of the axis-java2wsdl task, because axis-ant.jar is in $ANT\_HOME/lib, but it cannot find classes in axis.jar, even though that jar is on the path defined by "libraries" I know it's a classpath issue because I was able to get past DefaultAuthenticator to other class's not found by symlinking axis.jar into $ANT\_HOME/lib. How can I get the taskdef to recognize jar files in /usr/share/lib or my project's local lib directory without symlinking everything into $ANT\_HOME/lib? EDIT: I was finally able to successfully generate the wsdl with this line: ``` ant -lib /usr/share/java/axis.jar -lib /usr/share/java/jaxrpc.jar -lib /usr/share/java/wsdl4j.jar -lib /usr/share/java/commons-logging.jar -lib /usr/share/java/commons-discovery.jar -lib build genwsdl ``` I would still very much appreciate if somebody could tell me what I'm doing wrong in not being able to define those libraries in build.xml
In general, this works. But you need to check very carefully which classes are where. **If your task class can be loaded in a classloader higher up in the classloader hierarchy (like CLASSPATH or ANT\_HOME/lib) then your classpathref will simply get ignored**. Read the [FAQ entry](http://ant.apache.org/faq.html#delegating-classloader) for more details. > Ant's class loader implementation uses [Java's delegation model](http://java.sun.com/products/jdk/1.2/docs/api/java/lang/ClassLoader.html) > > The ClassLoader class uses a delegation model to search for classes and resources. Each instance of ClassLoader has an associated parent class loader. When called upon to find a class or resource, a ClassLoader instance will delegate the search for the class or resource to its parent class loader before attempting to find the class or resource itself. The virtual machine's built-in class loader, called the bootstrap class loader, does not itself have a parent but may serve as the parent of a ClassLoader instance. Note: running `ant -diagnostics` [can help too](http://www.nabble.com/Ant-Diagnostic-td17856450.html).
Ant [mechanism](http://ant.apache.org/manual/using.html#external-tasks) for adding libraries is: * via command line argument -lib * adding to ${user.home}/.ant/lib * adding to ${ant.home}/lib Only. The [manual](http://ant.apache.org/manual) doesn't mention anything about using the *system.library.dir* property. Probably it pretty much ignored for this purpose. Also, run ant in verbose mode ( and -verbose ) to see what is doing under the hood.
Ant cannot find a class needed by an externally defined taskdef
[ "", "java", "ant", "classpath", "axis", "" ]
I would like to change the contents of the list of a `JComboBox` (like adding another list in place of and older one). Is there any way I might be able to do that? Thanks in advance!
If you want to be able to add and remove items from an existing combo box at runtime, the underlying data model for the combo box needs to be a MutableComboBoxModel Google for that class for interface information and for examples of how to use it. Note that if you want the user to type in new values, you also need to make the box editable. You can find some links to examples [here](http://www.javadocexamples.com/javax/swing/javax.swing.MutableComboBoxModel.html).
I found this thread and came up with a quick (and probably dirty) solution: ``` oldComboBox.setModel(new JComboBox<>(new_items).getModel()); ```
Changing the Contents of the JComboBox
[ "", "java", "swing", "jcombobox", "" ]
It's possible to declare variables with the below structure in C++ ``` private: public: protected: float bla1; float bla2; float bla3; ``` Is there an equivalent in C#? It seems rather tedious having to repeat yourself; ``` protected float bla1; protected float bla2; protected float bla3; ```
No there isn't such a thing. In fact, it's designed to be like that to make code more readable. This applies to both C# and Java.
No. The access is specified on each declaration. The benefit of this is that a method's location within the source file has no effect on the behaviour. That means you can move methods and properties around (e.g. to cluster related methods together) with impunity. The same isn't *quite* true of fields - it's possible to make the declaration order of fields matter. Admittedly it's best not to do that in the first place...
Is there a C# equivalent to access-modifier regions in C++
[ "", "c#", "access-modifiers", "" ]
I am trying to compare the performance of boost::multi\_array to native dynamically allocated arrays, with the following test program: ``` #include <windows.h> #define _SCL_SECURE_NO_WARNINGS #define BOOST_DISABLE_ASSERTS #include <boost/multi_array.hpp> int main(int argc, char* argv[]) { const int X_SIZE = 200; const int Y_SIZE = 200; const int ITERATIONS = 500; unsigned int startTime = 0; unsigned int endTime = 0; // Create the boost array typedef boost::multi_array<double, 2> ImageArrayType; ImageArrayType boostMatrix(boost::extents[X_SIZE][Y_SIZE]); // Create the native array double *nativeMatrix = new double [X_SIZE * Y_SIZE]; //------------------Measure boost---------------------------------------------- startTime = ::GetTickCount(); for (int i = 0; i < ITERATIONS; ++i) { for (int y = 0; y < Y_SIZE; ++y) { for (int x = 0; x < X_SIZE; ++x) { boostMatrix[x][y] = 2.345; } } } endTime = ::GetTickCount(); printf("[Boost] Elapsed time: %6.3f seconds\n", (endTime - startTime) / 1000.0); //------------------Measure native----------------------------------------------- startTime = ::GetTickCount(); for (int i = 0; i < ITERATIONS; ++i) { for (int y = 0; y < Y_SIZE; ++y) { for (int x = 0; x < X_SIZE; ++x) { nativeMatrix[x + (y * X_SIZE)] = 2.345; } } } endTime = ::GetTickCount(); printf("[Native]Elapsed time: %6.3f seconds\n", (endTime - startTime) / 1000.0); return 0; } ``` I get the following results: ``` [Boost] Elapsed time: 12.500 seconds [Native]Elapsed time: 0.062 seconds ``` I can't believe multi\_arrays are that much slower. Can anyone spot what I am doing wrong? I assume caching is not an issue since I am doing writes to memory. EDIT: This was a debug build. Per Laserallan's suggest I did a release build: ``` [Boost] Elapsed time: 0.266 seconds [Native]Elapsed time: 0.016 seconds ``` Much closer. But 16 to 1 still seems to high to me. Well, no definitive answer, but I'm going to move on and leave my real code with native arrays for now. Accepting Laserallan's answer because it was the biggest flaw in my test. Thanks to all.
Are you building release or debug? If running in debug mode, the boost array might be really slow because their template magic isn't inlined properly giving lots of overhead in function calls. I'm not sure how multi array is implemented though so this might be totally off :) Perhaps there is some difference in storage order as well so you might be having your image stored column by column and writing it row by row. This would give poor cache behavior and may slow down things. Try switching the order of the X and Y loop and see if you gain anything. There is some info on the storage ordering here: <http://www.boost.org/doc/libs/1_37_0/libs/multi_array/doc/user.html> EDIT: Since you seem to be using the two dimensional array for image processing you might be interested in checking out boosts image processing library [gil](http://www.boost.org/doc/libs/1_37_0/libs/gil/doc/index.html). It might have arrays with less overhead that works perfectly for your situation.
On my machine using ``` g++ -O3 -march=native -mtune=native --fast-math -DNDEBUG test.cpp -o test && ./test ``` I get ``` [Boost] Elapsed time: 0.020 seconds [Native]Elapsed time: 0.020 seconds ``` However changing `const int ITERATIONS` to `5000` I get ``` [Boost] Elapsed time: 0.240 seconds [Native]Elapsed time: 0.180 seconds ``` then with `ITERATIONS` back to `500` but `X_SIZE` and `Y_SIZE` set to `400` I get a much more significant difference ``` [Boost] Elapsed time: 0.460 seconds [Native]Elapsed time: 0.070 seconds ``` finally inverting the inner loop for the `[Boost]` case so it looks like ``` for (int x = 0; x < X_SIZE; ++x) { for (int y = 0; y < Y_SIZE; ++y) { ``` and keeping `ITERATIONS`, `X_SIZE` and `Y_SIZE` to `500`, `400` and `400` I get ``` [Boost] Elapsed time: 0.060 seconds [Native]Elapsed time: 0.080 seconds ``` If I invert the inner loop also for the `[Native]` case (so it is in the wrong order for that case), I get, unsurprisingly, ``` [Boost] Elapsed time: 0.070 seconds [Native]Elapsed time: 0.450 seconds ``` I am using `gcc (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5` on Ubuntu 10.10 So in conclusion: * With *proper optimization* boost::multi\_array does its job as expected * The order on which you access your data *does matter*
Boost::multi_array performance question
[ "", "c++", "performance", "boost", "boost-multi-array", "" ]
My current code to the effect of: ``` if( objectPointer != NULL){ delete objectPointer; } ``` doesn't work because the pointers are getting set to invalid hex numbers by the compiler such as: * 0xbaadf00d * 0xdeadbeef etc.... So what's the best way to check for an invalid pointer before trying to delete the object?
Always initialize your pointers to NULL (that is, 0). From <http://www.lysator.liu.se/c/c-faq/c-1.html>: > A null pointer is conceptually different from an uninitialized pointer. A null pointer is known not to point to any object; an uninitialized pointer might point anywhere.
You don't need to check for not-NULL when calling delete. It is explicitly defined to do nothing. ``` delete NULL; // this is allowed ``` Any correct code you are writing would not be affected by these weird values the compiler is putting into your uninitialised or already freed memory. It puts those values there in order to help you find bugs. Ergo, you have a bug.
How do you check for an invalid pointer?
[ "", "c++", "pointers", "" ]
I am taking a beginning C++ class, and would like to convert letters between hex representations and binary. I can manage to print out the hex numbers using: ``` for(char c = 'a'; c <= 'z'; c++){ cout << hex << (int)c; } ``` But I can't do the same for binary. There is no `std::bin` that I can use to convert the decimal numbers to binary.
Like so: ``` for(char c = 'a'; c <= 'z'; c++){ std::bitset<sizeof(char) * CHAR_BIT> binary(c); //sizeof() returns bytes, not bits! std::cout << "Letter: " << c << "\t"; std::cout << "Hex: " << std::hex << (int)c << "\t"; std::cout << "Binary: " << binary << std::endl; } ```
There isn't a binary io manipulator in C++. You need to perform the coversion by hand, probably by using bitshift operators. The actual conversion isn't a difficult task so should be within the capabilities of a beginner at C++ (whereas the fact that it's not included in the standard library may not be :)) Edit: A lot of others have put up examples, so I'm going to give my preferred method ``` void OutputBinary(std::ostream& out, char character) { for (int i = sizeof(character) - 1; i >= 0; --i) { out << (character >> i) & 1; } } ``` This could also be potentially templated to any numeric type.
How can I convert hexadecimal numbers to binary in C++?
[ "", "c++", "binary", "hex", "" ]
Why can't enum's constructor access static fields and methods? This is perfectly valid with a class, but is not allowed with an enum. What I'm trying to do is store my enum instances in a static Map. Consider this example code which allows lookup by abbreivation: ``` public enum Day { Sunday("Sun"), Monday("Mon"), Tuesday("Tue"), Wednesday("Wed"), Thursday("Thu"), Friday("Fri"), Saturday("Sat"); private final String abbreviation; private static final Map<String, Day> ABBREV_MAP = new HashMap<String, Day>(); private Day(String abbreviation) { this.abbreviation = abbreviation; ABBREV_MAP.put(abbreviation, this); // Not valid } public String getAbbreviation() { return abbreviation; } public static Day getByAbbreviation(String abbreviation) { return ABBREV_MAP.get(abbreviation); } } ``` This will not work as enum doesn't allow static references in its constructor. It however works just find if implemented as a class: ``` public static final Day SUNDAY = new Day("Sunday", "Sun"); private Day(String name, String abbreviation) { this.name = name; this.abbreviation = abbreviation; ABBREV_MAP.put(abbreviation, this); // Valid } ```
The constructor is called before the static fields have all been initialized, because the static fields (including those representing the enum values) are initialized in textual order, and the enum values always come before the other fields. Note that in your class example you haven't shown where ABBREV\_MAP is initialized - if it's *after* SUNDAY, you'll get an exception when the class is initialized. Yes, it's a bit of a pain and could probably have been designed better. However, the usual answer in my experience is to have a `static {}` block at the end of all the static initializers, and do all static initialization there, using `EnumSet.allOf` to get at all the values.
Quote from [JLS, section "Enum Body Declarations"](https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9.2): > Without this rule, apparently reasonable code would fail at run time > due to the initialization circularity inherent in enum types. (A > circularity exists in any class with a "self-typed" static field.) > Here is an example of the sort of code that would fail: > > ``` > enum Color { > RED, GREEN, BLUE; > static final Map<String,Color> colorMap = new HashMap<String,Color>(); > > Color() { > colorMap.put(toString(), this); > } > } > ``` > > Static initialization of this enum type would throw a *NullPointerException* because the static variable colorMap is > uninitialized when the constructors for the enum constants run. The > restriction above ensures that such code won’t compile. > > Note that the example can easily be refactored to work properly: > > ``` > enum Color { > RED, GREEN, BLUE; > static final Map<String,Color> colorMap = new HashMap<String,Color>(); > > static { > for (Color c : Color.values()) > colorMap.put(c.toString(), c); > } > } > ``` > > The refactored version is clearly correct, as static initialization occurs top to bottom.
Why can't enum's constructor access static fields?
[ "", "java", "enums", "" ]
Ok so I have this regex that I created and it works fine in RegexBuddy but not when I load it into php. Below is an example of it. Using RegexBuddy I can get it to works with this: ``` \[code\](.*)\[/code\] ``` And checking the dot matches newline, I added the case insensitive, but it works that way as well. Here is the php: ``` $q = "[code]<div>html code to display on screen</div>[/code]"; $pattern = '/\[code\](.*)\[/code\]/si'; $m = preg_match($pattern, $q, $code); ``` So you can see I am using [code][/code] and then once I can extract this I will run htmlentities() on it to display instead of render html code.
You're including the forward slash in the middle of your pattern (/code). Either escape it or delimit your pattern with something else (I prefer !).
When transferring your regular expression from RegexBuddy to PHP, either generate a source code snippet on the Use tab, or click the Copy button on the toolbar at the top, and select to copy as a PHP preg string. Then RegexBuddy will automatically add the delimiters and flags that PHP needs, without leaving anything unescaped.
preg_match works in regexbuddy, not in php
[ "", "php", "regex", "pcre", "regexbuddy", "" ]
I have threaded code where each thread needs to write to the same file. To prevent concurrency issues, I am using a Lock object. My question is whether I am using the Lock correctly. If I set the lock from within each thread, is that lock global or only specific to that specific thread? Basically, should I create a Lock first and pass its reference to each thread, or is it ok to set it from within the thread like I do here: ``` import time from threading import Thread, Lock def main(): for i in range(20): agent = Agent(i) agent.start() class Agent(Thread): def __init__(self, thread_num): Thread.__init__(self) self.thread_num = thread_num def run(self): while True: print 'hello from thread %s' % self.thread_num self.write_result() def write_result(self): lock = Lock() lock.acquire() try: f = open('foo.txt', 'a') f.write('hello from thread %s\n' % self.thread_num) f.flush() f.close() finally: lock.release() if __name__ == '__main__': main() ```
Create the lock outside the method. ``` class Agent(Thread): mylock = Lock() def write_result(self): self.mylock.acquire() try: ... finally: self.mylock.release() ``` or if using python >= 2.5: ``` class Agent(Thread): mylock = Lock() def write_result(self): with self.mylock: ... ``` To use that with python 2.5 you must import the statement from the future: ``` from __future__ import with_statement ```
For your use case one approach could be to write a `file` subclass that locks: ``` class LockedWrite(file): """ Wrapper class to a file object that locks writes """ def __init__(self, *args, **kwds): super(LockedWrite, self).__init__(*args, **kwds) self._lock = Lock() def write(self, *args, **kwds): self._lock.acquire() try: super(LockedWrite, self).write(*args, **kwds) finally: self._lock.release() ``` To use in your code just replace following functions: ``` def main(): f = LockedWrite('foo.txt', 'a') for i in range(20): agent = Agent(i, f) agent.start() class Agent(Thread): def __init__(self, thread_num, fileobj): Thread.__init__(self) self.thread_num = thread_num self._file = fileobj # ... def write_result(self): self._file.write('hello from thread %s\n' % self.thread_num) ``` This approach puts file locking in the file itself which seems cleaner IMHO
Multithreaded Resource Access - Where Do I Put My Locks?
[ "", "python", "multithreading", "locking", "" ]
I'm looking for the equivalent of a [urlencode](http://docs.python.org/library/urllib.html#urllib.quote_plus) for terminal output -- I need to make sure that garbage characters I (may) print from an external source don't end up doing funky things to my terminal, so a prepackaged function to escape special character sequences would be ideal. I'm working in Python, but anything I can readily translate works too. TIA!
``` $ ./command | cat -v $ cat --help | grep nonprinting -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB ``` Here's the same in py3k based on [android/cat.c](http://www.google.com/codesearch/p?hl=en#2wSbThBwwIw/toolbox/cat.c&q=file:%5Cbcat.c&l=-1): ``` #!/usr/bin/env python3 """Emulate `cat -v` behaviour. use ^ and M- notation, except for LFD and TAB NOTE: python exits on ^Z in stdin on Windows NOTE: newlines handling skewed towards interactive terminal. Particularly, applying the conversion twice might *not* be a no-op """ import fileinput, sys def escape(bytes): for b in bytes: assert 0 <= b < 0x100 if b in (0x09, 0x0a): # '\t\n' yield b continue if b > 0x7f: # not ascii yield 0x4d # 'M' yield 0x2d # '-' b &= 0x7f if b < 0x20: # control char yield 0x5e # '^' b |= 0x40 elif b == 0x7f: yield 0x5e # '^' yield 0x3f # '?' continue yield b if __name__ == '__main__': write_bytes = sys.stdout.buffer.write for bytes in fileinput.input(mode="rb"): write_bytes(escape(bytes)) ``` Example: ``` $ perl -e"print map chr,0..0xff" > bytes.bin $ cat -v bytes.bin > cat-v.out $ python30 cat-v.py bytes.bin > python.out $ diff -s cat-v.out python.out ``` It prints: ``` Files cat-v.out and python.out are identical ```
Unfortunately "terminal output" is a very poorly defined criterion for filtering (see [question 418176](https://stackoverflow.com/questions/418176/why-does-pythons-string-printable-contains-unprintable-characters)). I would suggest simply whitelisting the characters that you want to allow (which would be most of string.printable), and replacing all others with whatever escaped format you like (\FF, %FF, etc), or even simply stripping them out.
Safe escape function for terminal output
[ "", "python", "terminal", "escaping", "" ]
I need to get the path to the native (rather than the WOW) program files directory from a 32bit WOW process. When I pass CSIDL\_PROGRAM\_FILES (or CSIDL\_PROGRAM\_FILESX86) into SHGetSpecialFolderPath it returns the WOW (Program Files (x86)) folder path. I'd prefer to avoid using an environment variable if possible. I want to compare some values I read from the registry, if the values point to the path of either the WOW or native version of my app then my code does something, if not it does something else. To figure out where the native and WOW versions of my app are expected to be I need to get the paths to "Program Files (x86)" and "Program Files".
I appreciate all the help and, especially, the warnings in this thread. However, I really do need this path and this is how I got it in the end: (error checking removed for clarity, use at your own risk, etc) ``` WCHAR szNativeProgramFilesFolder[MAX_PATH]; ExpandEnvironmentStrings(L"%ProgramW6432%", szNativeProgramFilesFolder, ARRAYSIZE(szNativeProgramFilesFolder); ```
Let me quote **Raymond Chen**'s [excellent blogpost](http://blogs.msdn.com/oldnewthing/archive/2008/12/22/9244582.aspx) on the issue: > On 64-bit Windows, 32-bit programs run > in an emulation layer. This emulation > layer simulates the x86 architecture, > virtualizing the CPU, the file system, > the registry, the environment > variables, the system information > functions, all that stuff. If a 32-bit > program tries to look at the system, > it will see a 32-bit system. For > example, if the program calls the > GetSystemInfo function to see what > processor is running, it will be told > that it's running on a 32-bit > processor, with a 32-bit address > space, in a world with a 32-bit sky > and 32-bit birds in the 32-bit trees. > > And that's the point of the emulation: > To keep the 32-bit program happy by > simulating a 32-bit execution > environment. > > ... > > The question is "What is the way of > finding the x64 Program Files > directory from a 32-bit application?" > > The answer is "**It is better to work > with the system than against it.**" If > you're a 32-bit program, then you're > going to be fighting against the > emulator each time you try to interact > with the outside world. Instead, just > recompile your installer as a 64-bit > program. Have the 32-bit installer > detect that it's running on a 64-bit > system and launch the 64-bit installer > instead. The 64-bit installer will not > run in the 32-bit emulation layer, so > when it tries to copy a file or update > a registry key, it will see the real > 64-bit file system and the real 64-bit > registry. If you still want to do this, I recommend reading the comments on this blogpost as they contain some good hints.
How to get Program Files folder path (not Program Files (x86)) from 32bit WOW process?
[ "", "c++", "windows", "64-bit", "" ]
I'm looking to implement user login onto my site for the first time. I'm happy to either build my own solution, or implement something open source, however no package has been an obvious choice in my search so far. Equally, I'm fully aware that as an intermediate php programmer at best, I am highly likely to miss something obvious if I roll my own solution, and leave the doors well and truly open. Any suggestions? We're not talking super sensitive or payment data here, but equally, I'm keen not to have people mess up my site! requirements are - php based - simple as possible, not need for fancy bells and whistles - not Zend framework, since i've now rolled my own very basic frameworkthanks to [this post](https://stackoverflow.com/questions/422250/php-framework-or-template-engine-or-something-else) Thanks for your input.
A few good security gotcha's are * **never** store the an un-encrypted users password in the database * **never** store the users password or even a hash of the password in session or cookie data. * If you need to have ensure that the login is secure you have to use https. I found these article very helpful in building login systems with cookies: * [blog post on the fishbowl](http://fishbowl.pastiche.org/2004/01/19/persistent_login_cookie_best_practice/). * [Improved Persistent Login Cookie Best Practice](http://jaspan.com/improved_persistent_login_cookie_best_practice)
"You'll put your eye out kid." Security is hard. I hate to say this, but the odds of you making a simple authorization scheme that is secure are quite slim. There is no easy mode here. So you might want to start by reading through a bunch of authentication code in the various frameworks/cmses, and other places where you can see how others have done it, and begin researching. Here are some links: <http://www.topmost.se/personal/articles/casual-cryptography-for-web-developers.htm> <http://pear.php.net/packages.php?catpid=1>
simple authorisation / login capability in php
[ "", "php", "security", "authentication", "" ]
If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week? Many thanks
``` >>> import time >>> time.asctime(time.strptime('2008 50 1', '%Y %W %w')) 'Mon Dec 15 00:00:00 2008' ``` Assuming the first day of your week is Monday, use `%U` instead of `%W` if the first day of your week is Sunday. See the documentation for [strptime](http://docs.python.org/library/time.html#time.strptime) for details. **Update:** Fixed week number. The `%W` directive is 0-based so week 51 would be entered as 50, not 51.
PEZ's and Gerald Kaszuba's solutions work under assumption that January 1st will always be in the first week of a given year. This assumption is not correct for ISO calendar, see [Python's docs](http://docs.python.org/library/datetime.html#datetime.date.isocalendar) for reference. For example, in ISO calendar, week 1 of 2010 actually starts on Jan 4, and Jan 1 of 2010 is in week 53 of 2009. An ISO calendar-compatible solution: ``` from datetime import date, timedelta def week_start_date(year, week): d = date(year, 1, 1) delta_days = d.isoweekday() - 1 delta_weeks = week if year == d.isocalendar()[0]: delta_weeks -= 1 delta = timedelta(days=-delta_days, weeks=delta_weeks) return d + delta ```
In Python, how do I find the date of the first Monday of a given week?
[ "", "python", "datetime", "" ]
When i give wrong number of parameters in a function , i get errors. How do I handle it? I gave ``` def fun_name(...): try: ... except TypeError: print 'Wrong no of arg' ``` It is not working. Help please.
The caller triggers this exception, not the receiver. If you want the receiving function to explicitly check argument count you'll need to use varargs: ``` def fun_name(*args): if len(args) != 2: raise TypeError('Two arguments required') ```
You need to handle it where you call the function. ``` try: fun_name(...) except TypeError: print "error!" ```
How to handle the error that occurs on giving wrong number of parameters in a function call in Python?
[ "", "python", "function-call", "" ]
OSGi has a problem with split packages, i.e. same package but hosted in multiple bundles. Are there any edge cases that split packages might pose problems in plain java (without OSGi) ? Just curious.
For OSGi packages in different bundles are different, regardless of their name, because each bundle uses its own class loader. It is not a problem but a feature, to ensure encapsulation of bundles. So in plain Java this is normally not a problem, until you start using some framework that uses class loaders. That is typically the case when components are loaded.
## Where split packages come from *Split packages* (in OSGi) occur when the manifest header `Require-Bundle` is used (as it is, I believe, in Eclipse's manifests). `Require-Bundle` names other bundles which are used to search for classes (if the package isn't `Import`ed). The search happens before the bundles own classpath is searched. This allows the classes for a single package to be loaded from the exports of *multiple* bundles (probably distinct jars). The OSGi spec (4.1) section 3.13 describes `Require-Bundle` and has a long list of (unexpected) consequences of using this header (ought this header be deprecated?), one section of which is devoted to *split packages*. Some of these consequences are bizarre (and rather OSGi-specific) but most are avoided if you understand one thing: * if a ***class*** (in a package) is provided by more than one bundle then you are in trouble. If the package pieces are disjoint, then all should be well, except that you might not have the classes *visible* everywhere and package visibility members might appear to be private if viewed from a "wrong" part of a split package. [Of course that's too simple—multiple versions of packages can be installed—but from the application's point of view *at any one time* all classes from a package should be sourced from a single module.] ## What happens in 'standard Java' In standard Java, without fancy class-loaders, you have a classpath, and the order of searching of jars (and directories) for classes to load is fixed and well-defined: what you get is what you get. (But then, we give up manageable modularity.) Sure, you can have split packages—it's quite common in fact—and it is an indication of poor modularity. The symptoms can be obscure compile/build-time errors, but in the case of multiple class implementations (one over-rides the rest in a single class-path) it most often produces obscure run-time behaviour, owing to subtly-different semantics. If you are ***lucky*** you end up looking at the wrong code—without realising it—and asking yourself "but how can that possibly be doing *that*?" If you are ***unlucky*** you are looking at the right code and asking exactly the same thing—because something else was producing unexpected answers. This is not entirely unlike the old database adage: "if you record the same piece of information in two places, pretty soon it won't be the same anymore". Our problem is that 'pretty soon' isn't normally soon enough.
Split packages in plain java
[ "", "java", "osgi", "package", "" ]
I am implementing an HTML form with some checkbox input elements, and I want to have a Select All or DeSelect All button. However, *I do not want to rely on the name* of the input element (like [this example](http://www.plus2net.com/javascript_tutorial/checkbox-checkall.php)) but rather the **type** because I have multiple checkbox groups with different names. Is there a way to check and uncheck all checkbox input elements within a form with JavaScript by relying on the type instead of the name? Edit: We rely on YUI libraries, so I have access YUI if that provides a solution.
This should do it: ``` <script> function checkUncheck(form, setTo) { var c = document.getElementById(form).getElementsByTagName('input'); for (var i = 0; i < c.length; i++) { if (c[i].type == 'checkbox') { c[i].checked = setTo; } } } </script> <form id='myForm'> <input type='checkbox' name='test' value='1'><br> <input type='checkbox' name='test' value='1'><br> <input type='checkbox' name='test' value='1'><br> <input type='checkbox' name='test' value='1'><br> <input type='checkbox' name='test' value='1'><br> <input type='button' onclick="checkUncheck('myForm', true);" value='Check'> <input type='button' onclick="checkUncheck('myForm', false);" value='Uncheck'> </form> ```
iterate through the form.elements collection and check .type == "checkbox". ``` var button = getSelectAllButtonInFormSomeHow(); /*all formelements have a reference to the form. And the form has an elements-collection.*/ var elements = button.form.elements; for(var i = 0; i < elements.length;i++) { var input = elements[i]; if (input.tagName == "input" && input.type == "checkbox") input.checked = true; } ```
Using JavaScript to manipulate HTML input (checkbox) elements via type instead of name
[ "", "javascript", "html", "" ]
I wrote an Oracle SQL expression like this: ``` SELECT ... FROM mc_current_view a JOIN account_master am USING (account_no) JOIN account_master am_loan ON (am.account_no = am_loan.parent_account_no) JOIN ml_client_account mca USING (account_no) ``` When I try to run it, Oracle throws an error in the line with "ON" self-join saying: "ORA-25154: column part of USING clause cannot have qualifier". If I omit the "am" qualifier, it says: "ORA-00918: column ambiguously defined". What's the best way to resolve this?
The error message is actually (surprise!) telling you exactly what the problem is. Once you use the USING clause for a particular column, you cannot use a column qualifier/table alias for that column name in any other part of your query. The only way to resolve this is to not use the USING clause anywhere in your query, since you have to have the qualifier on the second join condition: ``` SELECT ... FROM mc_current_view a JOIN account_master am ON (a.account_no = am.account_no) JOIN account_master am_loan ON (am.account_no = am_loan.parent_account_no) JOIN ml_client_account mca ON (a.account_no = mca.account_no); ```
My preference is never to use **USING**; always use **ON**. I like to my SQL to be very explicit and the **USING** clause feels one step removed in my opinion. In this case, the error is coming about because you have `account_no` in `mc_current_view`, `account_master`, and `ml_client_account` so the actual join can't be resolved. Hope this helps.
Mixing "USING" and "ON" in Oracle ANSI join
[ "", "sql", "oracle", "ora-00918", "" ]
Wouldn't it be nice to just do a keystroke and have eclipse organize all imports in all java classes instead of just the one you are looking at? Is this possible? Is there a keystroke for it?
Select the project in the package explorer and press `Ctrl` + `Shift` + `O` (same keystroke as the single class version). Should work for packages, etc.
You can edit the clean up options on save to make it organize imports. That way all of your imports will always be organized. In eclipse 3.4 just go into Window - Preferences. In the tree view look under Java -- Editor -- Save Actions. This is how I keep my imports organized all of the time.
Can you organize imports for an entire project in eclipse with a keystroke?
[ "", "java", "eclipse", "keyboard-shortcuts", "" ]
Why do PHP regexes have the surrounding delimiters? It seems like it would be more clear if any pattern modifiers were passed in as a parameter to whatever function was being used.
There is no technical reason why it has to be like this. As noted in a comment, the underlying library does not require that flags be passed as part of the regexp - in fact, the extension has to strip these off and pass them as a separate argument. It appears as though the original implementer was trying to make it look like grep/sed/awk/perl/etc so that it is more familiar to programmers coming from those tools.
The reason for the delimiter is to put flags after the pattern. Arguably flags could be passed as a separate parameter (Java can do it this way) but that's the way Perl did it originally (and sed/awk/vi before it) so that's how it's done now. Don't use forward slashes: they're too common. Personally I nearly always use the ! character. I'm hardly ever looking for that.
PHP regex delimiter, what's the point?
[ "", "php", "regex", "" ]
Maybe there are VB.net and other language that related with .Net framework. When I install the Visual C++ 2008 ,I have to install the .Net framework 3.5. However,why people think .Net gets mainly related with C# language?
The easiest way of putting this is to compare it to the C languages. The C language is known as the "scripting language of the Von Neuman machine". It is this most expressive of what happens in the underlying machine code. C# is basically the scripting language of the .Net framework. The .Net framework was designed with C# in mind as its main language, partially because Anders, who designed C# (also Turbo Pascal and Delphi in the past for Borland), was one of the main designers of the .Net framework. The .Net framework was designed with having high language compatibility in mind, but C# will probably always be the language that is "closest to the metal".
Because people love {curly braces}! As the [top three most popular programming languages](http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html) are all curly-braced, it is easy for most programmers to understand and code C# quickly. C# was also built from the ground up to be .NET language. While VB.NET, in my point of view, is initially created for the existing VB Classic programmers to move to .NET world quickly, and to expand the brand of Visual Basic which people know and love.
Why C# get so related with .NET framework?
[ "", "c#", ".net", "" ]
I plan on installing Multiple Instances of MS SQL EXPRESS on my Development Server. I am hoping this will let me get around the [limitations](http://msdn.microsoft.com/en-us/library/cc645993.aspx) of SQL EXPRESS: * 1 GB of RAM, * 1 CPU * Database size max 4 GB [I understand and wish that I could afford a full licence version of SQL Server.] So, would this work? Would each instance have their own independent limitations?
If you have an MSDN subscription then you can install the Development version and I don't believe that has any restrictions...of course it's for development purposes only. You can purchase SQL Server Developer Edition from Microsoft at this link...it's $50 <http://store.microsoft.com/microsoft/SQL-Server-2008-Developer-Edition/product/C5EA00C9> --- As of 2016 (?) SQL Server Developer Edition is **Free**, downloadable at [microsoft.com/sqlserver](http://go.microsoft.com/fwlink/?LinkID=799009).
The answer to your question is yes. All instances will have their own independent limitations. Problems that you will face are: * Obvious performance issue. * OS will decide which processor they will use, and there is a good chance that they will all use the same one. You need to try that. * Servers need to listen on separate ports. * Separate master databases, separate collations, no easy cross-database queries.
Limitations of Running Multiple Instances of MS SQL EXPRESS
[ "", "sql", "sql-server-express", "" ]
I will be building a set of applications. One of these apps is unattended application (written in VB6) which will write data it receives from various sources to a local database. All the other applications (will be written in VS 2008/c# 3.0) will read this data for mostly reporting reasons. I don't want SQL Server/MySql/Sybase or even its express editions, because distributing it is a problem (e.g. requires separate install, etc...). I am looking for a local database that has drivers for both VB6 (so probably OLEDB, or ODBC if I have to settle for it) and ADO.NET. It would also be nice, if the database had support for ORMs, like NHibernate or at least 1-to-1 mappers, like Subsonic, but that's not a deal breaker. But my main requirement is that the database should be massively solid, so that I don't have to waste time fiddling with it, recovering lost data, etc... I have experience with MS Access from back in the day and don't have too many good recollections (nor was it bad either). I've heard of SQLite, SQL Server Compact Edition, VistaDB, etc... but have zero experience with them and I don't know anyone who has actually used it. What's out there that best fits my situation?
[SQLite](http://www.sqlite.org/) might just fit the bill. Make sure you [check out all the available wrappers](http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers) as well.
Have you thought of [FireBird SQL](http://firebirdsql.org/dotnetfirebird/blog/2005/02/embedded-firebird-and-microsoft-sql.html)?
Which local database fits my situation?
[ "", "c#", "database", "vb6", "embedded-database", "" ]
When implementing a singleton in C++, is it better for GetInstance() to return a pointer to the singleton object, or a reference? Does it really matter?
I prefer a reference. I use reference instead of a pointer whenever I want to document that: * It can't be null * It won't be changed (to point to something else) * It mustn't be deleted
I think it would be safer to return a reference, but don't forget about "copy protection" of your singleton object.
C++ singleton GetInstance() return
[ "", "c++", "reference", "singleton", "pointers", "" ]
I have a C# Application I am creating that stores all data in SQL Server. Sometimes it's easier for me to make data changes programmatically and sometimes it's easier to have stored procedures and functions in the SQL Server database and call them. I am rather new to programming and I don't know what the subtle advantages and/or disadvantages of each method are. I figure I should probably be doing things one way or the other instead of using several methods. My code is starting to look like a random collection of thoughts all just shoved into one spot. No offense to Joel Spolsky. I love his books. This is a solo project, so I can refactor any amount of code I want to make it better. All options are on the table. Thanks, J3r3myK
Well, Stored Procs can be an additional level of abstraction or a set of functions/methods if you look at the database like an object or service. This can be beneficial, since you can hide underlying implementation details and change it when need be without breaking the app (as long as you leave the interface, e.g. the stored proc parameters, alone). Also, if you can hide your table details behind a set of stored procs, no matter how someone gets access to your database, they'll only be able to interact with it using the methods you designed and wrote for it --> there's less risk of someone firing up Excel and hacking into your database. On the other hand, Stored Proc require extensive T-SQL knowledge and you'll be spreading your business and app logic across two sets of code bases, which can be a downside. Anything you can do in a stored proc can also be done in ADO.NET with straight SQL statements, and it's not even slower anymore. A further plus for Stored Procs is the fact that if something is wrong in your proc, you can fix it merely by deploying the proc with the fix - you don't need to touch your C# app. This can be a great plus in a "hosted" environment if you only get 3 releases per year - applying a hotfix by means of fixing an Stored Proc can be your live-saver then! :-) All in all: there are lots of pros and cons for or against stored procs; I'd suggest, if you feel comfortable with writing T-SQL, why not give it a try and see how it works for you. If it feels to cumbersome or too inflexible or like too much work in the long run, you can always switch back to using straight SQL in your C# app. Just my $0.02. Marc
Two points that haven't been covered yet: SProcs can be placed in a schema, and impersonate a different schema. This means that you can lock down the database access and give users permissions ONLY to execute your SProcs, not to select update etc, which is a very nice security bonus. Secondly, the sproc can be SIGNIFICANTLY faster depending on what operations your doing. If your constrained by network IO and your able to perform set operations on your data, doing so in a single stored procedure instead of doing a fetch of the ENTIRE dataset, processing it, then transmitting the change will give you a nice speed increase. Same goes for transactions, if you need to perform operations serially (i.e change a value in two tables at once which involves some logic) then you will need to hold a transaction for the time it takes for you to compute the value and transmit back in two SQL queries, whereas the stored procedure can do it in a single procedure.
C# Application - Should I Use Stored Procedures or ADO.NET with C# Programming Techniques?
[ "", "c#", ".net", "sql-server", "ado.net", "" ]
I did some timing tests and also read some articles like [this one](http://www.cincomsmalltalk.com/userblogs/buck/blogView?showComments=true&title=Smalltalk+performance+vs.+C%23&entry=3354595110#3354595110) (last comment), and it looks like in Release build, float and double values take the same amount of processing time. How is this possible? When float is less precise and smaller compared to double values, how can the CLR get doubles into the same processing time?
On x86 processors, at least, `float` and `double` will each be converted to a 10-byte real by the FPU for processing. The FPU doesn't have separate processing units for the different floating-point types it supports. The age-old advice that `float` is faster than `double` applied 100 years ago when most CPUs didn't have built-in FPUs (and few people had separate FPU chips), so most floating-point manipulation was done in software. On these machines (which were powered by steam generated by the lava pits), it *was* faster to use `float`s. Now the only real benefit to `float`s is that they take up less space (which only matters if you have millions of them).
It depends on **32-bit** or **64-bit** system. If you compile to 64-bit, double will be faster. Compiled to 32-bit on 64-bit (machine and OS) made float around 30% faster: ``` public static void doubleTest(int loop) { Console.Write("double: "); for (int i = 0; i < loop; i++) { double a = 1000, b = 45, c = 12000, d = 2, e = 7, f = 1024; a = Math.Sin(a); b = Math.Asin(b); c = Math.Sqrt(c); d = d + d - d + d; e = e * e + e * e; f = f / f / f / f / f; } } public static void floatTest(int loop) { Console.Write("float: "); for (int i = 0; i < loop; i++) { float a = 1000, b = 45, c = 12000, d = 2, e = 7, f = 1024; a = (float) Math.Sin(a); b = (float) Math.Asin(b); c = (float) Math.Sqrt(c); d = d + d - d + d; e = e * e + e * e; f = f / f / f / f / f; } } static void Main(string[] args) { DateTime time = DateTime.Now; doubleTest(5 * 1000000); Console.WriteLine("milliseconds: " + (DateTime.Now - time).TotalMilliseconds); time = DateTime.Now; floatTest(5 * 1000000); Console.WriteLine("milliseconds: " + (DateTime.Now - time).TotalMilliseconds); Thread.Sleep(5000); } ```
Float vs Double Performance
[ "", "c#", ".net", "clr", "performance", "" ]
We have started using Spring framework in my project. After becoming acquainted with the basic features (IoC) we have started using spring aop and spring security as well. The problem is that we now have more than 8 different context files and I feel we didn't give enough thought for the organization of those files and their roles. New files were introduced as the project evolved. We have different context files for: metadata, aop, authorization, services, web resources (it's a RESTful application). So when a developer wants to add a new bean it's not always clear in which file he should add it. We need methodology. The question: Is there a best practice for spring files organization? Should the context files encapsulate layers (DAL , Business Logic, Web) or use cases ? or Flows?
If you're still reasonably early in the project I'd advice you strongly to look at annotation-driven configuration. After converting to annotations we only have 1 xml file with definitions and it's really quite small, and this is a large project. Annotation driven configuration puts focus on your implementation instead of the xml. It also more or less removes the fairly redundant abstraction layer which is the spring "bean name". It turns out the bean name exists mostly *because* of xml (The bean name still exists in annotation config but is irrelevant in most cases). After doing this switch on a large project everyone's 100% in agreement that it's a *lot* better and we also have fairly decent evidence that it's a more productive environment. I'd really recommend *anyone* who's using spring to switch to annotations. It's possible to mix them as well. If you need transitional advice I suppose it's easy to ask on SO ;)
Start with applicationContext.xml and separate when there's a lot of beans which have something in common. To give you some idea of a possible setup, in the application I'm currently working on, here's what I have in server: * applicationContext.xml * securityContext.xml * schedulingContext.xml * dataSourcecontext.xml * spring-ws-servlet.xml (Spring Web Services related beans) For GUI clients, since this project has several, there is one folder with shared context files, and on top of that, each client has its own context folder. Shared context files: * sharedMainApplicationContext.xml * sharedGuiContext.xml * sharedSecurityContext.xml App-specific files: * mainApplicationContext.xml and * guiContext.xml and * commandsContext.xml (menu structure) * sharedBusinessLayerContext.xml (beans for connecting to server)
Spring context files organization and best practices
[ "", "java", "spring", "jakarta-ee", "" ]
Per the example array at the very bottom, i want to be able to append the depth of each embedded array inside of the array. for example: ``` array ( 53 => array ( 'title' => 'Home', 'path' => '', 'type' => '118', 'pid' => 52, 'hasChildren' => 0, ), ``` Has a depth of one according to the sample array shown below so it should now look like this: ``` array ( 53 => array ( 'title' => 'Home', 'path' => '', 'type' => '118', 'pid' => 52, 'hasChildren' => 0, 'depth' => 1, ), ``` and so on... All of the recursive array function attempts i have made are pretty embarrassing. However I have looked at RecursiveArrayIterator which has the getDepth function. I'm confused on how to append it to the current array... any help is VERY much appreciated, thank you. ``` array ( 'title' => 'Website Navigation', 'path' => '', 'type' => '115', 'pid' => 0, 'hasChildren' => 1, 'children' => array ( 53 => array ( 'title' => 'Home', 'path' => '', 'type' => '118', 'pid' => 52, 'hasChildren' => 0, ), 54 => array ( 'title' => 'Features', 'path' => 'features', 'type' => '374', 'pid' => 52, 'hasChildren' => 1, 'children' => array ( 59 => array ( 'title' => 'artistic', 'path' => 'features/artistic', 'type' => '374', 'pid' => 54, 'hasChildren' => 1, 'children' => array ( 63 => array ( 'title' => 'galleries', 'path' => 'features/artistic/galleries', 'type' => '374', 'pid' => 59, 'hasChildren' => 1, 'children' => array ( 65 => array ( 'title' => 'graphics', 'path' => 'features/artistic/galleries/graphics', 'type' => '118', 'pid' => 63, 'hasChildren' => 0, ), 67 => array ( 'title' => 'mixed medium', 'path' => 'features/artistic/galleries/mixed-medium', 'type' => '118', 'pid' => 63, 'hasChildren' => 0, ), 64 => array ( 'title' => 'overview', 'path' => 'features/artistic/galleries', 'type' => '118', 'pid' => 63, 'hasChildren' => 0, ), 68 => array ( 'title' => 'photography', 'path' => 'features/artistic/galleries/photography', 'type' => '118', 'pid' => 63, 'hasChildren' => 0, ), 66 => array ( 'title' => 'traditional', 'path' => 'features/artistic/galleries/traditional', 'type' => '118', 'pid' => 63, 'hasChildren' => 0, ), ), ), 62 => array ( 'title' => 'overview', 'path' => 'features/artistic', 'type' => '118', 'pid' => 59, 'hasChildren' => 0, ), 69 => array ( 'title' => 'tutorials', 'path' => 'features/artistic/tutorials', 'type' => '374', 'pid' => 59, 'hasChildren' => 1, 'children' => array ( 71 => array ( 'title' => 'by category', 'path' => 'features/artistic/tutorials/by-category/', 'type' => '118', 'pid' => 69, 'hasChildren' => 0, ), 72 => array ( 'title' => 'by date', 'path' => 'features/artistic/tutorials/by-date/', 'type' => '118', 'pid' => 69, 'hasChildren' => 0, ), 70 => array ( 'title' => 'overview', 'path' => 'features/artistic/tutorials', 'type' => '118', 'pid' => 69, 'hasChildren' => 0, ), ), ), ), ), 58 => array ( 'title' => 'overview', 'path' => 'features', 'type' => '118', 'pid' => 54, 'hasChildren' => 0, ), 61 => array ( 'title' => 'projects / labs', 'path' => 'features/projects-labs/', 'type' => '374', 'pid' => 54, 'hasChildren' => 0, ), 60 => array ( 'title' => 'web development', 'path' => 'features/web-development', 'type' => '374', 'pid' => 54, 'hasChildren' => 1, 'children' => array ( 74 => array ( 'title' => 'articles', 'path' => 'features/web-development/articles/', 'type' => '374', 'pid' => 60, 'hasChildren' => 0, ), 73 => array ( 'title' => 'overview', 'path' => 'features/web-development', 'type' => '118', 'pid' => 60, 'hasChildren' => 0, ), 75 => array ( 'title' => 'tutorials', 'path' => 'features/web-development/tutorials', 'type' => '374', 'pid' => 60, 'hasChildren' => 0, ), ), ), ), ), 55 => array ( 'title' => 'Activity', 'path' => 'activity', 'type' => '374', 'pid' => 52, 'hasChildren' => 0, ), 56 => array ( 'title' => 'Blog', 'path' => 'blog', 'type' => '374', 'pid' => 52, 'hasChildren' => 0, ), 57 => array ( 'title' => 'About', 'path' => 'about', 'type' => '374', 'pid' => 52, 'hasChildren' => 1, 'children' => array ( 76 => array ( 'title' => 'the author', 'path' => 'about/the-author', 'type' => '118', 'pid' => 57, 'hasChildren' => 0, ), 77 => array ( 'title' => 'the website', 'path' => 'about/the-website', 'type' => '118', 'pid' => 57, 'hasChildren' => 0, ), ), ), ), ), ); print_r($example); ?> ```
I assume there is another array( at the top not included in your example code. Something like this? ``` function array_set_depth($array, $depth = -1) { $subdepth = $depth + 1; if ($depth < 0) { foreach ($array as $key => $subarray) { $temp[$key] = array_set_depth(($subarray), $subdepth); } } if ($array['hasChildren'] && isset($array['children'])) { foreach ($array['children'] as $key => $subarray) { $temp[$key] = array_set_depth($subarray, $subdepth); } $array['children'] = $temp; } $array['depth'] = $depth; return $array; } ``` Example usage, I set your array to the value $a: ``` $b = array_set_depth($a); print_r($b); ``` Edit: To set depth before the children for nice printing you can do this: ``` function array_set_depth($array, $depth = -1) { $subdepth = $depth + 1; if ($depth < 0) { foreach ($array as $key => $subarray) { $temp[$key] = array_set_depth(($subarray), $subdepth); } return $temp; } $array['depth'] = $depth; if ($array['hasChildren'] && isset($array['children'])) { foreach ($array['children'] as $key => $subarray) { $temp[$key] = array_set_depth($subarray, $subdepth); } unset($array['children']); $array['children'] = $temp; } return $array; } ```
A recursive function like this should do it? ``` function setDepth(&$a, $depth) { $a['depth']=$depth; foreach($a as $key=>$value) { if (is_array($value)) setDepth($a[$key], $depth+1); } } ``` The thing to note is that the array is passed by reference, so that we can modify it. Note that we also use this reference in the recursive call to setDepth. Although I used foreach for convenience, the $value variable is a copy, and passing that to setDepth would only make short lived changes within the scope of the foreach loop.
PHP Arrays, appending depth of array item recursively to an array with the key of 'depth'
[ "", "php", "arrays", "recursion", "associative-array", "" ]
I heard lots of reviews on the book Linq in Action, but it does not cover Linq to Entities. Please provide your feedback on the books you may have read.
Check this, it may help till a good book appear: <http://weblogs.asp.net/zeeshanhirani/archive/2008/12/05/my-christmas-present-to-the-entity-framework-community.aspx>
[LINQ in Action](http://www.manning.com/marguerie/) is a good book for understanding the principles of LINQ, and LINQ-to-SQL in particular. [C# in Depth](http://manning.com/skeet/) is good for understand how LINQ works at the language level, including query syntax, extension methods and expression trees. EF... trickier. One problem is that it is likely to change quite a bit between now and the next version due to the ["thunderdome" scenario](http://codebetter.com/blogs/ian_cooper/archive/2008/11/03/linq-to-sql-ef-and-the-thunderdome-solution.aspx).
Which is the best book out there to learn Linq, including Linq to Entities?
[ "", "c#", "linq", "entity-framework", "linq-to-entities", ".net-3.5", "" ]
I have a table with arbitrary columns and rows. This fact is irrelevant though really, all I want to do is develop a function that will turn a row (or multiple rows) into a series of text inputs containing the data in the table (or empty if no data in cell). I can't find any examples of people explicitly doing this, so I wondered what people here think is the best way to find a solution.
Iterate over the table cells in the rows, and replace the contents with text inputs: ``` function editRow(row) { $('td',row).each(function() { $(this).html('<input type="text" value="' + $(this).html() + '" />'); }); } ``` You need to pass the relevant row/rows into the function obviously.
use <http://code.google.com/p/jquery-inline-editor/>, it does exactly what you need
jQuery - Edit a table row inline
[ "", "javascript", "jquery", "html-table", "rows", "inline-editing", "" ]
I have a page where some event listeners are attached to input boxes and select boxes. Is there a way to find out which event listeners are observing a particular DOM node and for what event? Events are attached using: 1. [Prototype's](http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework) `Event.observe`; 2. DOM's `addEventListener`; 3. As element attribute `element.onclick`.
If you just need to inspect what's happening on a page, you might try the [Visual Event](http://www.sprymedia.co.uk/article/Visual+Event) bookmarklet. **Update**: [Visual Event 2](http://www.sprymedia.co.uk/article/Visual+Event+2) available.
Chrome, Vivaldi and Safari support `getEventListeners(domElement)` in their Developer Tools console. For majority of the debugging purposes, this could be used. Below is a very good reference to use it: [getEventListeners function](https://developer.chrome.com/docs/devtools/console/utilities/#getEventListeners-function) --- Highly voted tip from Clifford Fajardo from the comments: `getEventListeners($0)` will get the event listeners for the element you have focused on in the Chrome dev tools.
How to find event listeners on a DOM node in JavaScript or in debugging?
[ "", "javascript", "events", "dom", "" ]
I would like to use RNGCryptoServiceProvider as my source of random numbers. As it only can output them as an array of byte values how can I convert them to 0 to 1 double value while preserving uniformity of results?
``` byte[] result = new byte[8]; rng.GetBytes(result); return (double)BitConverter.ToUInt64(result,0) / ulong.MaxValue; ```
This is how I would do this. ``` private static readonly System.Security.Cryptography.RNGCryptoServiceProvider _secureRng; public static double NextSecureDouble() { var bytes = new byte[8]; _secureRng.GetBytes(bytes); var v = BitConverter.ToUInt64(bytes, 0); // We only use the 53-bits of integer precision available in a IEEE 754 64-bit double. // The result is a fraction, // r = (0, 9007199254740991) / 9007199254740992 where 0 <= r && r < 1. v &= ((1UL << 53) - 1); var r = (double)v / (double)(1UL << 53); return r; } ``` > Coincidentally `9007199254740991 / 9007199254740992 is ~= 0.99999999999999988897769753748436` which is what the `Random.NextDouble` method will return as it's maximum value (see <https://msdn.microsoft.com/en-us/library/system.random.nextdouble(v=vs.110).aspx>). In general, the standard deviation of a continuous uniform distribution is (max - min) / sqrt(12). With a sample size of 1000 I'm reliably getting within a 2% error margin. With a sample size of 10000 I'm reliably getting within a 1% error margin. Here's how I verified these results. ``` [Test] public void Randomness_SecureDoubleTest() { RunTrials(1000, 0.02); RunTrials(10000, 0.01); } private static void RunTrials(int sampleSize, double errorMargin) { var q = new Queue<double>(); while (q.Count < sampleSize) { q.Enqueue(Randomness.NextSecureDouble()); } for (int k = 0; k < 1000; k++) { // rotate q.Dequeue(); q.Enqueue(Randomness.NextSecureDouble()); var avg = q.Average(); // Dividing by n−1 gives a better estimate of the population standard // deviation for the larger parent population than dividing by n, // which gives a result which is correct for the sample only. var actual = Math.Sqrt(q.Sum(x => (x - avg) * (x - avg)) / (q.Count - 1)); // see http://stats.stackexchange.com/a/1014/4576 var expected = (q.Max() - q.Min()) / Math.Sqrt(12); Assert.AreEqual(expected, actual, errorMargin); } } ```
How to get random double value out of random byte array values?
[ "", "c#", ".net", "random", "" ]
Youll need a 64bit machine if you want to see the actuall exception. I've created some dummy classes that repro's the problem. ``` [StructLayout(LayoutKind.Sequential, Pack = 1)] public class InnerType { char make; char model; UInt16 series; } [StructLayout(LayoutKind.Explicit)] public class OutterType { [FieldOffset(0)] char blah; [FieldOffset(1)] char blah2; [FieldOffset(2)] UInt16 blah3; [FieldOffset(4)] InnerType details; } class Program { static void Main(string[] args) { var t = new OutterType(); Console.ReadLine(); } } ``` If I run this on the 64 clr, I receive a type load exception, ``` System.TypeLoadException was unhandled Message="Could not load type 'Sample.OutterType' from assembly 'Sample, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it contains an object field at offset 4 that is incorrectly aligned or overlapped by a non-object field." ``` If i force the target cpu to 32, it works fine. Also, if i change InnerType from a class to a struct it also works. Can someone explain whats going on or what I am doing wrong ? thanks
The part about overlapping types is misleading here. The problem is that in .Net reference types must always be aligned on pointer size boundaries. Your union works in x86 since the field offset is 4 bytes which is the pointer size for a 32 bit system but fails on x64 since there it must be offset a multiple of 8. The same thing would happen if you set the offset to 3 or 5 on the x86 platform. EDIT: For the doubters - I couldn't find a ready reference on the internet but check out [Expert .NET 2.0 IL Assembler By Serge Lidin](https://rads.stackoverflow.com/amzn/click/com/1590596463) page 175.
I have also noticed that you are packing your char data type into 1 byte. Char types in .NET are 2 bytes in size. I cannot verify if this is the actual issue, but I would double-check that.
TypeLoadException on x64 but is fine on x86 with structlayouts
[ "", "c#", ".net", "x86", "64-bit", "" ]
I know how package level protection in java works. I *read* a lot of code (including lots of open source stuff) and no-one seem to be using it. The whole protection level seems slightly faulty to me (I'd have c#'s internal any day of the week). Are there any legit real-world use-cases that are in common use ? Edit: A little too late after asking this question I realized I'd forgotten to exclude the "standard" pattern of package protected implementation classes, possibly providing implementations of public interfaces. Everyone uses those, as has been noted several times in the replies. I still think there are a large number of nice replies to this question.
There are two good uses for package level visibility (in my experience): 1) Defining "internal" classes in a public API. Commonly you would define your interfaces and core factories as public and the "internal" implementations as package level. Then the public factories can construct the package level implementation classes and return them as instances of the public interfaces. This nicely allows users to only access the stuff they should. The downside is that you have to have all this stuff in the same package, which almost never is a good idea for any reasonably-sized API. [JSR 294](http://tech.puredanger.com/java7#jsr294)/modules/[Project Jigsaw](http://tech.puredanger.com/java7#jigsaw) in Java 7 will hopefully provide an alternative by specifying a new visibility modifier (`module`) that can be used to access classes within a module across packages without making them visible outside the module. You can find an example of how this would work [in this article](http://www.javaworld.com/javaworld/jw-12-2008/jw-12-year-in-review-2.html). 2) Unit testing is the other common use case. Frequently you'll see a src tree and a test tree and stuff that would otherwise be private is instead package level so that unit tests in the same (parallel) package are able to access otherwise hidden methods to check or manipulate state.
Are you talking about package-private protection in Java? That's the protection that is in effect by default for class members. It's useful occasionally if you got classes that interact intimately in a way that requires additional information or methods to be visible. Say you have a Sink class, and several classes can write to that. The Sink has a public method that accepts basic data-types, and a package private method that accepts raw byte arrays. You don't want to make that method public, because you consider it too low-level for its users, but you want to make your other classes (in the package of the Sink) writing to that Sink use it. So you make the method accepting the byte array package private, and classes of your package such as ByteStreamSource could use it. Now, your protection looks like this: ``` User Code using the package User ------ | -----------------------------|----- package public Interface | | Sink <- package priv. iface -> Sources ``` The package private interface is orthogonal to the public interface established by the public methods. Package private'ness increases encapsulation, because it encourages you *not* to make public what shouldn't be public. It's similar to the `friend` keyword in C++ and the `internal` keyword in C#.
What is the use of package level protection in java?
[ "", "java", "" ]
I'm trying to call a stored procedure (on a SQL 2005 server) from C#, .NET 2.0 using `DateTime` as a value to a `SqlParameter`. The SQL type in the stored procedure is 'datetime'. Executing the sproc from SQL Management Studio works fine. But everytime I call it from C# I get an error about the date format. When I run SQL Profiler to watch the calls, I then copy paste the `exec` call to see what's going on. These are my observations and notes about what I've attempted: 1) If I pass the `DateTime` in directly as a `DateTime` or converted to `SqlDateTime`, the field is surrounding by a PAIR of single quotes, such as ``` @Date_Of_Birth=N''1/8/2009 8:06:17 PM'' ``` 2) If I pass the `DateTime` in as a string, I only get the single quotes 3) Using `SqlDateTime.ToSqlString()` does not result in a UTC formatted datetime string (even after converting to universal time) 4) Using `DateTime.ToString()` does not result in a UTC formatted datetime string. 5) Manually setting the `DbType` for the `SqlParameter` to `DateTime` does not change the above observations. So, my questions then, is how on earth do I get C# to pass the properly formatted time in the `SqlParameter`? Surely this is a common use case, why is it so difficult to get working? I can't seem to convert `DateTime` to a string that is SQL compatable (e.g. '2009-01-08T08:22:45') **EDIT** RE: BFree, the code to actually execute the sproc is as follows: ``` using (SqlCommand sprocCommand = new SqlCommand(sprocName)) { sprocCommand.Connection = transaction.Connection; sprocCommand.Transaction = transaction; sprocCommand.CommandType = System.Data.CommandType.StoredProcedure; sprocCommand.Parameters.AddRange(parameters.ToArray()); sprocCommand.ExecuteNonQuery(); } ``` To go into more detail about what I have tried: ``` parameters.Add(new SqlParameter("@Date_Of_Birth", DOB)); parameters.Add(new SqlParameter("@Date_Of_Birth", DOB.ToUniversalTime())); parameters.Add(new SqlParameter("@Date_Of_Birth", DOB.ToUniversalTime().ToString())); SqlParameter param = new SqlParameter("@Date_Of_Birth", System.Data.SqlDbType.DateTime); param.Value = DOB.ToUniversalTime(); parameters.Add(param); SqlParameter param = new SqlParameter("@Date_Of_Birth", SqlDbType.DateTime); param.Value = new SqlDateTime(DOB.ToUniversalTime()); parameters.Add(param); parameters.Add(new SqlParameter("@Date_Of_Birth", new SqlDateTime(DOB.ToUniversalTime()).ToSqlString())); ``` **Additional EDIT** The one I thought most likely to work: ``` SqlParameter param = new SqlParameter("@Date_Of_Birth", System.Data.SqlDbType.DateTime); param.Value = DOB; ``` Results in this value in the exec call as seen in the SQL Profiler ``` @Date_Of_Birth=''2009-01-08 15:08:21:813'' ``` If I modify this to be: ``` @Date_Of_Birth='2009-01-08T15:08:21' ``` It works, but it won't parse with pair of single quotes, and it wont convert to a `DateTime` correctly with the space between the date and time and with the milliseconds on the end. **Update and Success** I had copy/pasted the code above after the request from below. I trimmed things here and there to be concise. Turns out my problem was in the code I left out, which I'm sure any one of you would have spotted in an instant. I had wrapped my sproc calls inside a transaction. Turns out that I was simply not doing `transaction.Commit()`!!!!! I'm ashamed to say it, but there you have it. I still don't know what's going on with the syntax I get back from the profiler. A coworker watched with his own instance of the profiler from his computer, and it returned proper syntax. Watching the very SAME executions from my profiler showed the incorrect syntax. It acted as a red-herring, making me believe there was a query syntax problem instead of the much more simple and true answer, which was that I need to commit the transaction! I marked an answer below as correct, and threw in some up-votes on others because they did, after all, answer the question, even if they didn't fix my specific (brain lapse) issue.
How are you setting up the [`SqlParameter`](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.aspx)? You should set the [`SqlDbType` property](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.sqldbtype.aspx) to [`SqlDbType.DateTime`](http://msdn.microsoft.com/en-us/library/system.data.sqldbtype.aspx) and then pass the [`DateTime`](http://msdn.microsoft.com/en-us/library/system.datetime.aspx) directly to the parameter (do NOT convert to a string, you are asking for a bunch of problems then). You should be able to get the value into the DB. If not, here is a very simple example of how to do it: ``` static void Main(string[] args) { // Create the connection. using (SqlConnection connection = new SqlConnection(@"Data Source=...")) { // Open the connection. connection.Open(); // Create the command. using (SqlCommand command = new SqlCommand("xsp_Test", connection)) { // Set the command type. command.CommandType = System.Data.CommandType.StoredProcedure; // Add the parameter. SqlParameter parameter = command.Parameters.Add("@dt", System.Data.SqlDbType.DateTime); // Set the value. parameter.Value = DateTime.Now; // Make the call. command.ExecuteNonQuery(); } } } ``` I think part of the issue here is that you are worried that the fact that the time is in UTC is not being conveyed to SQL Server. To that end, you shouldn't, because SQL Server doesn't know that a particular time is in a particular locale/time zone. If you want to store the UTC value, then convert it to UTC before passing it to SQL Server (unless your server has the same time zone as the client code generating the `DateTime`, and even then, that's a risk, IMO). SQL Server will store this value and when you get it back, if you want to display it in local time, you have to do it yourself (which the `DateTime` struct will easily do). All that being said, if you perform the conversion and then pass the converted UTC date (the date that is obtained by calling the [`ToUniversalTime` method](http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx), not by converting to a string) to the stored procedure. And when you get the value back, call the [`ToLocalTime` method](http://msdn.microsoft.com/en-us/library/system.datetime.tolocaltime.aspx) to get the time in the local time zone.
Here is how I add parameters: ``` sprocCommand.Parameters.Add(New SqlParameter("@Date_Of_Birth",Data.SqlDbType.DateTime)) sprocCommand.Parameters("@Date_Of_Birth").Value = DOB ``` I am assuming when you write out DOB there are no quotes. Are you using a third-party control to get the date? I have had problems with the way the text value is generated from some of them. Lastly, does it work if you type in the .Value attribute of the parameter without referencing DOB?
Using DateTime in a SqlParameter for Stored Procedure, format error
[ "", "c#", "sql-server", "datetime", "stored-procedures", ".net-2.0", "" ]
Consider [System.Windows.Forms.StatusStrip](https://msdn.microsoft.com/en-us/library/system.windows.forms.statusstrip%28v=vs.110%29.aspx). I have added a StatusStrip to my Windows Forms application, but I am having a few problems. I would like to have a label anchored at the left and a progressbar anchored on the right in the StatusStrip, but I can't find a way to set these properties. I then thought that I may need to create two StatusStrips and anchor them on either side of the bottom of the form... That didn't pan out; besides that, it just doesn't feel right.
Just set the `Spring` property on the label control to `True` and you should be good to go.
What you have to do is set the alignment property of your progressbar to right. Then set the LayoutStyle of the StatusStrip to HorizontalStackWithOverflow. ``` private void InitializeComponent() { this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripProgressBar1 = new System.Windows.Forms.ToolStripProgressBar(); this.statusStrip1.SuspendLayout(); this.SuspendLayout(); // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripStatusLabel1, this.toolStripProgressBar1}); this.statusStrip1.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow; this.statusStrip1.Location = new System.Drawing.Point(0, 250); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(467, 22); this.statusStrip1.TabIndex = 0; this.statusStrip1.Text = "statusStrip1"; // // toolStripStatusLabel1 // this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; this.toolStripStatusLabel1.Size = new System.Drawing.Size(117, 17); this.toolStripStatusLabel1.Text = "toolStripStatusLabel1"; // // toolStripProgressBar1 // this.toolStripProgressBar1.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.toolStripProgressBar1.Name = "toolStripProgressBar1"; this.toolStripProgressBar1.Size = new System.Drawing.Size(100, 16); } private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; private System.Windows.Forms.ToolStripProgressBar toolStripProgressBar1; ```
Using StatusStrip in C#
[ "", "c#", "winforms", "anchor", "statusstrip", "" ]
I need some mind reading here, since I am trying to do what I do not completely understand. There is a 32-bit application (electronic trading application called CQG) which provides a COM API for external access. I have sample programs and scripts which access this API from Excel, .NET (C++, VB and C#) and shell VBScript. I have these .NET applications as source code and as compiled executables (32-bit, compiled on Windows XP). Now I have Windows Vista Home 64-bit which makes my head to spin. Excel examples work just fine (in Excel 2003). Compiled .NET sample executables work as well. But when I am trying to run .NET C# sample converted to and compiled by Visual Studio C# Expression, or run the VBScript script, I am getting error 80004005 when trying to create an object. Initially the .NET application also gave me 80040154 but then I figured how to make it produce 32-bit code and not 64-bit, so now the errors in C# and VBScript applications are the same. That's all the progress I got for now. And yes, I tried running 32-bit versions of cscript.exe/WScript from SysWOW64 folder on my VBS, but still the result is the same (80004005). How to solve this problem? I am almost ready to believe it is practically impossible, but the fact that Excel VBA works and .NET executables compiled on Windows XP run just fine just makes me angry. There should be a way to beat this thing (some secret which probably only Windows Vista developers know)! I will appreciate any help! PS: I believe code samples do not make much sense here, but this is the line of VBScript which fails: ``` Set CEL = WScript.CreateObject("CQG.CQGCEL.4.0", "CEL_") ``` And this is C#: ``` CQGCEL CEL = new CQGCEL(); ``` Update: Forgot to say [UAC](http://en.wikipedia.org/wiki/User_Account_Control) is off, of course. And I am working from account with administrator priviledges. I also tried watching which registry keys are read using Process Monitor but everything looks OK for GUIDs of this object. I could not recognize some other GUIDs so I am not sure whether they were critical or not. Is there a chance that this COM object uses Internet Explorer and gets the wrong one (like Internet Explorer 7 instead of Internet Explorer 6 engine or something)?
There are a number of things you have to remember with a 64 bit machine. These are some things that have caught me out in the past. 1. Building for Any CPU in [.NET](http://en.wikipedia.org/wiki/.NET_Framework) means it will run as 64 bit on a 64 bit machine. 2. Lots of COM components seem to be 32 bit only (I know this is a generalisation, but is often the case). In order to use them, you need to build your application as 32 bit (x86). 3. 64 bit Windows has different 32 and 64 bit registry nodes. For example, if you run regedit as 64 bit, you will see HKLM\Software\Wow6432Node and HKCU\Software\Wow6432Node. This contains all the information for 32 bit applications. My suggestion would be to build as a 32 bit application and see what happens.
The problem is probably DEP. I had the exact same problem as you, and got some help from tech support at CQG. Data Execution Prevention is turned on by Windows Vista & Windows 7 by default. You can turn it off with in command prompt with admin rights using ``` bcdedit.exe /set {current} nx AlwaysOff ``` Later, if you need, you can turn it back on with ``` bcdedit.exe /set {current} nx AlwaysOn ``` Reboot is not prompted, but is necessary. You can check your DEP policy using ``` wmic OS Get DataExecutionPrevention_SupportPolicy ``` where `0` is `Always off`, `1` is `Always On`, `2` is `Opt in` (and the default value), and `3` is `Opt Out`. After changing mine to Always Off and rebooting, I was able to compile without throwing the 80004005 error.
Using 32-bit COM object from C# or VBS on Vista 64-bit and getting error 80004005
[ "", "c#", ".net", "com", "64-bit", "wsh", "" ]
I'm trying to use protobuf in a C# project, using protobuf-net, and am wondering what is the best way to organise this into a Visual Studio project structure. When manually using the protogen tool to generate code into C#, life seems easy but it doesn't feel right. I'd like the .proto file to be considered to be the primary source-code file, generating C# files as a by-product, but before the C# compiler gets involved. The options seem to be: 1. Custom tool for proto tools (although I can't see where to start there) 2. Pre-build step (calling protogen or a batch-file which does that) I have struggled with 2) above as it keeps giving me "The system cannot find the file specified" unless I use absolute paths (and I don't like forcing projects to be explicitly located). Is there a convention (yet) for this? --- ***Edit:*** Based upon @jon's comments, I retried the pre-build step method and used this (protogen's location hardcoded for now), using Google's address-book example: ``` c:\bin\protobuf\protogen "-i:$(ProjectDir)AddressBook.proto" "-o:$(ProjectDir)AddressBook.cs" -t:c:\bin\protobuf\csharp.xslt ``` --- ***Edit2:*** Taking @jon's recommendation to minimise build-time by not processing the .proto files if they haven't changed, I've knocked together a basic tool to check for me (this could probably be expanded to a full Custom-Build tool): ``` using System; using System.Diagnostics; using System.IO; namespace PreBuildChecker { public class Checker { static int Main(string[] args) { try { Check(args); return 0; } catch (Exception e) { Console.WriteLine(e.Message); return 1; } } public static void Check(string[] args) { if (args.Length < 3) { throw new ArgumentException( "Command line must be supplied with source, target and command-line [plus options]"); } string source = args[0]; string target = args[1]; string executable = args[2]; string arguments = args.Length > 3 ? GetCommandLine(args) : null; FileInfo targetFileInfo = new FileInfo(target); FileInfo sourceFileInfo = new FileInfo(source); if (!sourceFileInfo.Exists) { throw new ArgumentException(string.Format( "Source file {0} not found", source)); } if (!targetFileInfo.Exists || sourceFileInfo.LastWriteTimeUtc > targetFileInfo.LastAccessTimeUtc) { Process process = new Process(); process.StartInfo.FileName = executable; process.StartInfo.Arguments = arguments; process.StartInfo.ErrorDialog = true; Console.WriteLine(string.Format( "Source newer than target, launching tool: {0} {1}", executable, arguments)); process.Start(); } } private static string GetCommandLine(string[] args) { string[] arguments = new string[args.Length - 3]; Array.Copy(args, 3, arguments, 0, arguments.Length); return String.Join(" ", arguments); } } } ``` My pre-build command is now (all on one line): ``` $(SolutionDir)PreBuildChecker\$(OutDir)PreBuildChecker $(ProjectDir)AddressBook.proto $(ProjectDir)AddressBook.cs c:\bin\protobuf\protogen "-i:$(ProjectDir)AddressBook.proto" "-o:$(ProjectDir)AddressBook.cs" -t:c:\bin\protobuf\csharp.xslt ```
As an extension of Shaun's code, I am pleased to announce that protobuf-net now has Visual Studio integration by way of a Custom Tool. The msi installer is available from the [project page](http://code.google.com/p/protobuf-net/). More complete information here: [protobuf-net; now with added Orcas](http://marcgravell.blogspot.com/2009/07/protobuf-net-now-with-added-orcas.html). ![Visual Studio with protobuf-net as a Custom Tool](https://lh6.ggpht.com/_feJtUp7IGuI/Sl7rs9FkdHI/AAAAAAAAAJY/zoDaMfuthIw/proto-vs_thumb%5B1%5D.png?imgmax=800)
Calling a pre-build step but using project variables (e.g. `$(ProjectPath)`) to create absolute filenames without having them actually in your solution would seem a reasonable bet to me. One thing you might want to consider, based on my past experience of code generators: you might want to write a wrapper for protogen which generates code to a different location, then checks whether the newly generated code is the same as the old code, and doesn't overwrite it if so. That way Visual Studio will realise nothing's changed and not force that project to be rebuilt - this has cut build times *dramatically* for me in the past. Alternatively, you could keep an md5 hash of the .proto file the last time protogen was executed, and only execute protogen if the .proto file has changed - even less to do on each build! Thanks for raising this as a question though - it clearly suggests I should work out a way to make this an easy pre-build step for my own port.
Protocol buffers in C# projects using protobuf-net - best practices for code generation
[ "", "c#", "visual-studio", "protocol-buffers", "protobuf-net", "" ]
How do we combine [How to request a random row in SQL?](https://stackoverflow.com/questions/19412/how-to-request-a-random-row-in-sql) and [Multiple random values in SQL Server 2005](https://stackoverflow.com/questions/183124/multiple-random-values-in-sql-server-2005) to select N random rows using a single pure-SQL query? Ideally, I'd like to avoid the use of stored procedures if possible. Is this even possible? **CLARIFICATIONS**: 1. Pure SQL refers to as close as possible to the ANSI/ISO standard. 2. The solution should be "efficient enough". Granted ORDER BY RAND() might work but as others have pointed out this isn't feasible for medium-sized tables.
I don't know about pure ANSI, and it's not simple, but you can check out my answer to a similar question here: [[Simple Random Samples from a Sql database](https://stackoverflow.com/questions/249301/simple-random-samples-from-a-mysql-database)](https://stackoverflow.com/questions/249301/simple-random-samples-from-a-mysql-database)
The answer to your question is in the second link there: ``` SELECT * FROM table ORDER BY RAND() LIMIT 1 ``` Just change the limit, and/or rewrite for SQL Server: ``` SELECT TOP 1 * FROM table ORDER BY newid() ``` Now, this *strictly* answers your question, but you really shouldn't be using this solution. Just try it on a large table and you'll see what I mean. If your key-space is sequential, either without holes, or with very few holes, and if it has very few holes, you're not too concerned that some rows have a slightly higher chance of being picked than others, then you can use a variation where you calculate which key you want to retrieve randomly, ranging from 1 to the highest key in your table, and then retrieve the first row that has a key equal to or higher than the number you calculated. You only need the "higher than" part if your key-space has holes. This SQL is left as an excercise for the reader. --- **Edit**: Note, a comment to another answer here mentions that perhaps *pure SQL* means ANSI standard SQL. If that is the case, then there is no way, since there is no standardized random function, nor does every database engine treat the random number function the same way. At least one engine I've seen "optimizes" the call by calling it once and just repeating the calculated value for all rows.
How to select N random rows using pure SQL?
[ "", "sql", "random", "" ]
Just wondering: When I add restrict to a pointer, I tell the compiler that the pointer is not an alias for another pointer. Let's assume I have a function like: ``` // Constructed example void foo (float* result, const float* a, const float* b, const size_t size) { for (size_t i = 0; i < size; ++i) { result [i] = a [0] * b [i]; } } ``` If the compiler has to assume that `result` might overlap with `a`, it has to refetch a each time. But, as `a` is marked `const`, the compiler could also assume that a is fixed, and hence fetching it once is ok. Question is, in a situation like this, what is the recommend way to work with restrict? I surely don't want the compiler to refetch `a` each time, but I couldn't find good information about how `restrict` is supposed to work here.
Your pointer is const, telling anyone calling your function that you won't touch the data which is pointed at through that variable. Unfortunately, the compiler still won't know if result is an alias of the const pointers. You can always use a non-const pointer as a const-pointer. For example, a lot of functions take a const char (i.e. string) pointer as a parameter, but you can, if you wish, pass it a non-const pointer, the function is merely making you a promise that it wont use that particular pointer to change anything. Basically, to get closer to your question, you'd need to add restrict to a and b in order to 'promise' the compiler that whoever uses this function won't pass in result as an alias to a or b. Assuming, of course, you're able to make such a promise.
Yes, you need restrict. **Pointer-to-const doesn't mean that nothing can change the data, only that you can't change it through that pointer**. `const` is mostly just a mechanism to ask the compiler to help you keep track of which stuff you want functions to be allowed to modify. **`const` is not a promise to the compiler that a function really won't modify data**. Unlike `restrict`, using pointer-to-`const` to mutable data is basically a promise to other humans, not to the compiler. Casting away `const` all over the place won't lead to wrong behaviour from the optimizer (AFAIK), unless you try to modify something that the compiler put in read-only memory (see below about `static const` variables). If the compiler can't see the definition of a function when optimizing, it has to assume that it casts away `const` and modifies data through that pointer (i.e. that the function doesn't respect the `const`ness of its pointer args). The compiler does know that `static const int foo = 15;` can't change, though, and will reliably inline the value even if you pass its address to unknown functions. (This is why `static const int foo = 15;` is not slower than `#define foo 15` for an optimizing compiler. Good compilers will optimize it like a `constexpr` whenever possible.) --- **Remember that `restrict` is a promise to the compiler that things you access through that pointer don't overlap with anything else**. If that's not true, your function won't necessarily do what you expect. e.g. don't call `foo_restrict(buf, buf, buf)` to operate in-place. In my experience (with gcc and clang), `restrict` is mainly useful on pointers that you store through. It doesn't hurt to put `restrict` on your source pointers, too, but usually you get all the asm improvement possible from putting it on just the destination pointer(s), if *all* the stores your function does are through `restrict` pointers. If you have any function calls in your loop, `restrict` on a source pointer does let clang (but not gcc) avoid a reload. See [these test-cases on the Godbolt compiler explorer](https://gcc.godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,source:'void+maybe_cast_away_const(const+int+*,+int)%3B%0Avoid+value_only(int)%3B%0A%0A//+The+address+of+these+static+variables+only+escapes+the+compilation+unit+as+a+pointer-to-const.%0A//+so+the+compiler+knows+that+maybe_cast_away_const+can!'t+find+a+pointer+to+them+in+a+global.%0Astatic+int+static_data+%3D+11%3B%0Aconst+static+int+static_const_data+%3D+10%3B%0Aint+pointer_to_static(void)%0A%7B%0A++++//+passing+the+value+forces+a+load+before+the+call%0A%0A++++maybe_cast_away_const(%26static_data,+static_data)%3B%0A++++//value_only(static_data)%3B++//+with+this,+static_data+is+optimized+away+as+a+constant%0A++++//maybe_cast_away_const(%26static_const_data,+static_const_data)%3B+//+still+optimized+away,+compiler+knows+that+a+static+const+is+really+read-only+(e.g.+casting+away+const+would+segfault)%0A%0A++++//+and+this+forces+the+compiler+to+have+it+in+a+reg+after%0A++++return+5+%2B+static_data%3B%0A%7D%0A%0A%0A//+Without+__restrict__,+the+compiler+has+to+assume+that+value_only+might+modify+*src+as+a+side-effect%0A//+since+our+caller+might+have+stored+src+in+a+global+that+value_only+can+see.%0A//+clang+takes+advantage+of+this,+gcc+reloads+anyway.%0Aint+arg_pointer_valonly(const+int+*__restrict__+src)%0A%7B%0A++++value_only(*src)%3B%0A++++return+5+%2B+*src%3B++//+clang:+no+reload+because+of+__restrict__%0A%7D%0A%0Aint+arg_pointer_escape(const+int+*__restrict__+src)%0A%7B%0A++++maybe_cast_away_const(src,+*src)%3B%0A++++return+5+%2B+*src%3B%0A%7D%0A'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:36.21252948964307,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:clang400,filters:(b:'0',commentOnly:'0',directives:'0',intel:'0'),options:'-xc+-O3+-std%3Dc11+-Wall+-fno-tree-vectorize+-fno-unroll-loops++-march%3Dhaswell',source:1),l:'5',n:'0',o:'x86-64+clang+4.0.0+(Editor+%231,+Compiler+%231)',t:'0')),k:29.885115337785457,l:'4',m:100,n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:g63,filters:(b:'0',commentOnly:'0',directives:'0',intel:'0'),options:'-xc+-O3+-std%3Dc11+-Wall+-fno-tree-vectorize++-march%3Dhaswell',source:1),l:'5',n:'0',o:'x86-64+gcc+6.3+(Editor+%231,+Compiler+%232)',t:'0')),k:33.90235517257147,l:'4',n:'0',o:'',s:0,t:'0')),l:'2',n:'0',o:'',t:'0')),version:4), specifically this one: ``` void value_only(int); // a function the compiler can't inline int arg_pointer_valonly(const int *__restrict__ src) { // the compiler needs to load `*src` to pass it as a function arg value_only(*src); // and then needs it again here to calculate the return value return 5 + *src; // clang: no reload because of __restrict__ } ``` gcc6.3 (targeting the x86-64 SysV ABI) decides to keep `src` (the pointer) in a call-preserved register across the function call, and reload `*src` after the call. Either gcc's algorithms didn't spot that optimization possibility, or decided it wasn't worth it, or the gcc devs on purpose didn't implement it because they think it's not safe. IDK which. But since clang does it, I'm guessing it's *probably* legal according to the C11 standard. clang4.0 optimizes this to only load `*src` once, and keep the value in a call-preserved register across the function call. Without `restrict`, it doesn't do this, because the called function might (as a side-effect) modify `*src` through another pointer. **The caller of this function might have passed the address of a global variable, for example**. But any modification of `*src` other than through the `src` pointer would violate the promise that `restrict` made to the compiler. Since we don't pass `src` to `valonly()`, the compiler can assume it doesn't modify the value. The GNU dialect of C allows using [`__attribute__((pure))` or `__attribute__((const))` to declare that a function has no side-effects](https://stackoverflow.com/questions/29117836/attribute-const-vs-attribute-pure-in-gnu-c), allowing this optimization without `restrict`, but there's no portable equivalent in ISO C11 (AFAIK). Of course, allowing the function to inline (by putting it in a header file or using LTO) also allows this kind of optimization, and is much better for small functions especially if called inside loops. --- Compilers are generally pretty aggressive about doing optimizations that the standard allows, even if they're surprising to some programmers and break some existing unsafe code which happened to work. (C is so portable that many things are undefined behaviour in the base standard; most nice implementations do define the behaviour of lots of things that the standard leaves as UB.) C is not a language where it's safe to throw code at the compiler until it does what you want, without checking that you're doing it the right way (without signed-integer overflows, etc.) --- **If you look at the x86-64 asm output for compiling your function (from the question), you can easily see the difference. I put it on [the Godbolt compiler explorer](https://gcc.godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,source:'%23include+%3Cstdlib.h%3E%0A%0A//+I+used+-fno-tree-vectorize+-fno-unroll-loops%0A//+only+so+the+asm+is+easy+to+read.++(Clang+likes+to+unroll+by+4+even+when+not+vectorizing)%0A%0A//+When+auto-vectorizing+without+__restrict__,%0A//+gcc+and+clang+check+for+overlap+(with+a+bunch+of+integer+code)%0A//+before+running+the+vectorized+loop%0A%0Avoid+foo_norestrict+(float*+result,+const+float*+a,+const+float*+b,+const+size_t+size)%0A%7B%0A++++//+a%5B0%5D+is+reloaded+inside+the+loop%0A+++++for+(size_t+i+%3D+0%3B+i+%3C+size%3B+%2B%2Bi)+%7B%0A+++++++++result%5Bi%5D+%3D+a%5B0%5D+*+b%5Bi%5D%3B%0A+++++%7D%0A%7D%0A%0Avoid+foo_restrict_dst+(float*__restrict__+result,+const+float*+a,+const+float*+b,+const+size_t+size)%0A%7B%0A++++//+The+load+of+a%5B0%5D+is+hoisted+out+of+the+loop%0A+++++for+(size_t+i+%3D+0%3B+i+%3C+size%3B+%2B%2Bi)+%7B%0A+++++++++result%5Bi%5D+%3D+a%5B0%5D+*+b%5Bi%5D%3B%0A+++++%7D%0A%7D%0A%0A%0Avoid+foo_restrict_src+(float*+result,+const+float*__restrict__+a,+const+float*+b,+const+size_t+size)%0A%7B%0A++++//+The+load+of+a%5B0%5D+is+hoisted+out+of+the+loop,%0A++++//+since+__restrict__+promises+that+it+doesn!'t+overlap+with+result%5Bi%5D%0A+++++for+(size_t+i+%3D+0%3B+i+%3C+size%3B+%2B%2Bi)+%7B%0A+++++++++result%5Bi%5D+%3D+a%5B0%5D+*+b%5Bi%5D%3B%0A+++++%7D%0A%7D%0A'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:38.96274343585585,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:clang400,filters:(b:'0',commentOnly:'0',directives:'0',intel:'0'),options:'-O3+-std%3Dc%2B%2B11+-Wall+-fno-tree-vectorize+-fno-unroll-loops++-march%3Dhaswell',source:1),l:'5',n:'0',o:'x86-64+clang+4.0.0+(Editor+%231,+Compiler+%231)',t:'0')),k:36.87541633523677,l:'4',m:100,n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:g63,filters:(b:'0',commentOnly:'0',directives:'0',intel:'0'),options:'-O3+-std%3Dc%2B%2B11+-Wall+-fno-tree-vectorize++-march%3Dhaswell',source:1),l:'5',n:'0',o:'x86-64+gcc+6.3+(Editor+%231,+Compiler+%232)',t:'0')),k:24.161840228907373,l:'4',n:'0',o:'',s:0,t:'0')),l:'2',n:'0',o:'',t:'0')),version:4)**. In this case, putting `restrict` on `a` is sufficient to let clang hoist the load of `a[0]`, but not gcc. With `float *restrict result`, both clang and gcc will hoist the load. e.g. ``` # gcc6.3, for foo with no restrict, or with just const float *restrict a .L5: vmovss xmm0, DWORD PTR [rsi] vmulss xmm0, xmm0, DWORD PTR [rdx+rax*4] vmovss DWORD PTR [rdi+rax*4], xmm0 add rax, 1 cmp rcx, rax jne .L5 ``` vs. ``` # gcc 6.3 with float *__restrict__ result # clang is similar with const float *__restrict__ a but not on result. vmovss xmm1, DWORD PTR [rsi] # outside the loop .L11: vmulss xmm0, xmm1, DWORD PTR [rdx+rax*4] vmovss DWORD PTR [rdi+rax*4], xmm0 add rax, 1 cmp rcx, rax jne .L11 ``` So in summary, **put `__restrict__` on all pointers that are guaranteed not to overlap with something else**. --- BTW, `restrict` is only a keyword in C. Some C++ compilers support `__restrict__` or `__restrict` as an extension, so you should `#ifdef` it away on unknown compilers. Since
Does restrict help in C if a pointer is already marked const?
[ "", "c++", "c", "optimization", "restrict-qualifier", "" ]
I am parsing a XML file in Java using the W3C DOM. I am stuck at a specific problem, I can't figure out how to get the whole inner XML of a node. The node looks like that: ``` <td><b>this</b> is a <b>test</b></td> ``` What function do I have to use to get that: ``` "<b>this</b> is a <b>test</b>" ```
You have to use the transform/xslt API using your <b> node as the node to be transformed and put the result into a new StreamResult(new StringWriter()); . See [how-to-pretty-print-xml-from-java](https://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java)
I know this was asked long ago but for the next person searching (was me today), this works with JDOM: ``` JDOMXPath xpath = new JDOMXPath("/td"); String innerXml = (new XMLOutputter()).outputString(xpath.selectNodes(document)); ``` This passes a list of all child nodes into outputString, which will serialize them out in order.
Java/DOM: Get the XML content of a node
[ "", "java", "xml", "dom", "" ]
My attempts to query MySQL from PHP with a create statement of a store procedure (SP) have all failed. Is this not possible ? If indeed possible, please give an example.
The MySQL manual has a clear overview about [how to create stored procedures (*13.1.15. `CREATE PROCEDURE` and `CREATE FUNCTION` Syntax*)](http://dev.mysql.com/doc/refman/5.1/en/create-procedure.html). The next question is: does the account you use to access the MySQL database the propper rights to actually create a procedure? Details about this question can be found here: [*19.2.2. Stored Routines and MySQL Privileges*](http://dev.mysql.com/doc/refman/5.1/en/stored-routines-privileges.html)
Besides of the privileges, what quite probably might cause your problem is, that actually mysql\_query($query) can only work one command per call ! So what you have to do is to split up the commands into sevaral mysql\_query($query) -calls. What i mean is something like this: ``` $query = "DROP FUNCTION IF EXISTS fnElfProef (accountNr INT)"; mysql_query($query); $query = "CREATE FUNCTION fnElfProef (accountNr INT) RETURNS BOOLEAN BEGIN DECLARE i, totaal INT DEFAULT 0; WHILE i < 9 DO SET i = i+1; SET totaal = totaal+(i*(accountNr%10)); SET accountNr = FLOOR(accountNr/10); END WHILE; RETURN (totaal%11) = 0; END"; mysql_query($query); $query = "SELECT * FROM mytable"; mysql_query($query); ```
How to create a MySQL stored procedure from PHP?
[ "", "php", "mysql", "stored-procedures", "" ]
I have a file listing in my application and I would like to allow people to right-click on an item and show the Windows Explorer context menu. I'm assuming I would need to use the IContextMenu interface, but I'm not really sure where to start.
There's a very good tutorial (albeit in C++) about hosting an IContextMenu on Raymond Chen's blog in 11 parts (in order): 1. [Initial foray](https://devblogs.microsoft.com/oldnewthing/20040920-00/?p=37823) 2. [Displaying the context menu](https://devblogs.microsoft.com/oldnewthing/20040922-00/?p=37793) 3. [Invocation location](https://devblogs.microsoft.com/oldnewthing/20040923-00/?p=37773) 4. [Key context](https://devblogs.microsoft.com/oldnewthing/20040924-00/?p=37753) 5. [Handling menu messages](https://devblogs.microsoft.com/oldnewthing/20040927-00/?p=37733) 6. [Displaying menu help](https://devblogs.microsoft.com/oldnewthing/20040928-00/?p=37723) 7. [Invoking the default verb](https://devblogs.microsoft.com/oldnewthing/20040930-00/?p=37693) 8. [Optimizing for the default command](https://devblogs.microsoft.com/oldnewthing/20041001-00/?p=37683) 9. [Adding custom commands](https://devblogs.microsoft.com/oldnewthing/20041004-00/?p=37673) 10. [Composite extensions - groundwork](https://devblogs.microsoft.com/oldnewthing/20041006-00/?p=37643) 11. [Composite extensions - composition](https://devblogs.microsoft.com/oldnewthing/20041007-00/?p=37633)
I have written a library that might be able to help you. You could use the controls provided by the library, or if you don't want to do that, looking through the code may give you an answer. You can find the library at: <http://gong-shell.sourceforge.net/> Please let me know if this helped!
How do you show the Windows Explorer context menu from a C# application?
[ "", "c#", "contextmenu", "explorer", "" ]
So in Ruby there is a trick to specify infinity: ``` 1.0/0 => Infinity ``` I believe in Python you can do something like this ``` float('inf') ``` These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance ``` (0..1.0/0).include?(number) == (number >= 0) # True for all values of number => true ``` To summarize, what I'm looking for is a real world reason to use Infinity. **EDIT**: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people *actually* used it.
Dijkstra's Algorithm typically assigns infinity as the initial edge weights in a graph. This doesn't *have* to be "infinity", just some arbitrarily constant but in java I typically use Double.Infinity. I assume ruby could be used similarly.
Off the top of the head, it can be useful as an initial value when searching for a minimum value. For example: ``` min = float('inf') for x in somelist: if x<min: min=x ``` Which I prefer to setting `min` initially to the first value of `somelist` Of course, in Python, you should just use the min() built-in function in most cases.
In what contexts do programming languages make real use of an Infinity value?
[ "", "python", "ruby", "language-agnostic", "idioms", "infinity", "" ]
We've been having an problem recently where other sites are running our e-commerce site inside a frameset where our site (with the offenders affiliate id tacked on) is the only content in a single full width frame. So essentially it looks and feels like our site with their URL at the top. We can cut off their affiliate id, which would make it pointless for them to do, but this doesn't prevent future offenders from doing the same thing until we find out about it. Is there a generic way (through JavaScript that appears on every page perhaps?) to prevent this from happening? Note that adding targets to to all links is not feasible, but adding a snippet of JS to all pages is, since the header and footer portions are shared sitewide from a single source. Another possibility would be at the Apache level (if there is anything we could do server side) as we do pass all requests through mod-rewrite. Note that it would be essential to sill allow pages to load inside an IFrame if the parent page originates from our domain, as we make valid use of IFrames
I believe the proper modern method to achieve this is with [The X-Frame-Options response header](https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options). From the MDN: > The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a frame or iframe. Sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites. Take a look at: [How to prevent IFRAME from redirecting top-level window](https://stackoverflow.com/questions/369498/how-to-prevent-iframe-from-redirecting-top-level-window?rq=1)
I've heard of solutions to this problem being referred to as a "frame popper script". A quick google comes up with [this thread](http://www.webmasterworld.com/google/3226698.htm). Looks like this is one of the simplest: ``` if (window != top) top.location.href = location.href; ```
Possible to prevent our website from running inside another domain's frameset or IFrame?
[ "", "javascript", "dns", "frame", "frameset-iframe", "" ]
I have an app that, while running, needs to poll its own memory usage. It would be ideal if it could list out the memory usage for each object instantiated. I know this can be achieved by WMI, but I was hoping for something that doesn't rely on WMI.
Two functions you might find useful are: ``` GC.GetTotalMemory(); Process.PagedMemorySize64(); ``` My experience has been that GC.GetTotalMemory() is not terribly reliable. It often reports memory usage that is much smaller than the actual memory usage. I've seen it report that I'm using only 8 gigabytes when my program runs out of memory on a 16 gigabyte machine. I haven't yet tested Process.PagedMemorySize64, although it does look promising.
``` Process proc = Process.GetCurrentProcess(); Logger.Info(proc.PeakWorkingSet64/1024 + "kb"); ```
Poll C# app's memory usage at runtime?
[ "", "c#", "runtime", "memory-management", "" ]
For C++, there are lots of good unit test frameworks out there, but I couldn't find a good one for [functional testing](http://en.wikipedia.org/wiki/Functional_testing). With functional testing, I mean stuff which touches the disk, requires the whole application to be in place etc. Point in case: What framework helps with testing things like whether your I/O works? I've got a hand-rolled system in place, which creates temporary folders, copies around a bunch of data, so the tests are always done in the same environment, but before I spend more time on my custom framework -- is there a good one out there already?
I wrote one from scratch three times already - twice for testing C++ apps that talked to exchanges using FIX protocol, once for a GUI app. The problem is, you need to emulate the outside world to do proper system testing. I don't mean "outside of your code" - outside of your application. This involves emulating end users, outside entities, the Internet and so on. I usually use perl to write my system testing framework and tests, mostly because it's good with accessing all sorts of OS facilities and regexps are first-class citizens. Some tips: make sure your logs are easy to parse, detailed but not too verbose. Have a sane default configuration. Make it easy to "reset" the application - you need to do it after each test. The approach I usually use is to have some sort of "adapter" that turns the application's communications with the outside world into stdin/stdout of some executable. Then I build a perl framework on top of that, and then the test cases use the framework.
Below I list a couple of tools and larger testing applications of which I am aware. If you provide more information on your platform (OS, etc.) we can probably provide better answers. For part of what you require, Microsoft provides the [Application Verifier](http://technet.microsoft.com/en-us/library/bb457063.aspx): > Application Verifier (AppVerifier) is a runtime verification tool used in testing applications for compatibility with Microsoft Windows XP. This tool can be used to test for a wide variety of known compatibility issues while the application is running. This article details the steps for using AppVerifier as an effective addition to the application development and testing cycles. Application Verifier can be useful for testing out low memory conditions, other low resources, and other API usage. Another part of the puzzle, is the Microsoft Detours package, which can be used to replace API calls with your own code (useful for say, returning error codes for tests that are hard to set up). > Detours is a library for instrumenting arbitrary Win32 functions on x86, x64, and IA64 machines. Detours intercepts Win32 functions by re-writing the in-memory code for target functions. The Detours package also contains utilities to attach arbitrary DLLs and data segments (called payloads) to any Win32 binary. There are other, larger (and more expensive) comprehensive packages available too. Borland makes [Silk](http://www.borland.com/us/products/silk/silktest/index.html). Automated Software makes [TestComplete](http://www.automatedqa.com/products/testcomplete/index.asp). The selection of one of these tools would be up to your needs for your applications. IBM/Rational provides the [Rational Functional Tester](http://www-01.ibm.com/software/awdtools/tester/functional/), which is available across many platforms, and feature-rich.
Testing framework for functional/system testing for C/C++?
[ "", "c++", "c", "testing", "system-testing", "" ]