Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
has any body used this [Visual Web Gui](http://www.visualwebgui.com) , and are their claims right ? i have been reading on their site and it seems amazing that you can make Web/Desktop App in same time, plus they say you don't have to worry anymore about update panel, AJAX, it is all on the server, plus they have wrappers for 3rd Party controls. i mean all in all it looks theoretically great, but what about reality ?
We have a production commercial software application that was built using Visual Web GUI. We could not have built this system using a traditional stack like aspx. Our web site is <http://www.hrtms.com> VWG is best suited to a line-of-business applications.. not Web 2.0/bouncing ball/youtube/video or social networking types of apps. Here is what we have learned: 1. Don't try to scale to 1000s of users.. there is a server-side statefull component for each user, so intuitively, this will limit the number of users compared to a traditional application that is stateless. 2. Best used for Business applications with lots of complex business rules and data (definitely ours!) 3. Best for applications that can use the standard look and feel that comes with VWG.. so you really can't build Facebook with it. Most VWG apps look like Outlook. 4. Of course you must use .Net stack On the positive side: 1. You can knock out a huge amount of your system very fast... since the framework is based on the Winform model. You do need to handle modal forms differently, but for the most part, the code looks and feels like winform code. 2. The network traffic is minimal.. once the client has downloaded the javascript engine the network is just used to post commands and data. 3. Stateful programming on the server for web apps is far far easier that stateless. You can load complex object trees and know they will be there when the user is interacting with you system.. 4. No more agony working with html/javascript/css. VWG maps it according to the browser being used. Ok, on the negative side: 1. Scalability.. you need to plan on throwing lots of hardware at these apps.. I figure about 200 -300 concurrent users per box. Good news: hardware is cheap.. 2. Until 6.4 comes out, we are still dealing with pesky version problems with some browsers... so the support beyond IE right now is not 100% 3. Silverlight plugin support is on hold right now.. they want to support that when SL stabilizes. Overall.. its a great tool. There's no magic.. Its a smart ajax app.. Try it out. By the way.. i am not an employee or agent for this tool. Mitch
I have an inherant distrust for any product that claims it will do all of my work for me. Frequently, that means 1 or two things: 1. It does everything *it* thinks I should be doing and ignores all the fine details that I need to do *in addition* to the primary task 2. It can handle all the details but entails more work to get it installed, configured, or to use than if I just did it myself That said, I have never used this product and can't really give an opinion beyond my own suspicions.
Advice about Visual Web GUi
[ "", "c#", "asp.net", "frameworks", "" ]
so i am using a filter to catch servlet exception (because we are using a mix of jsf/plain servlets) when catching the ServletException and calling printstacktrace most of the information is lost. the "true" root exception seems to be hidden behind the "funny" expression ``` ((ServletException) e.getRootCause().getCause()).getRootCause().getCause().getCause().getCause() ``` this is clearly not the way to do it. is the an easy way to print the "full" information of such an exception. can someone explain me why the exception is wrapped this way?
Take a look at the [ExceptionUtils](http://commons.apache.org/lang/api-release/org/apache/commons/lang/exception/ExceptionUtils.html) class from commons-lang. It contains several useful methods for printing the entire chain of exceptions.
after i had a look at ExceptionUtils, this solved the problem! ``` final StringWriter stacktrace = new StringWriter(); ExceptionUtils.printRootCauseStackTrace(throwable,new PrintWriter(stacktrace)); msg.append(stacktrace.getBuffer()); ``` this prints out the full stacktrace with every piece of information that is relevant.
correctly printstacktrace of servlet exception
[ "", "java", "exception", "servlets", "stack-trace", "" ]
Referring to Brian Goetz's article [Are all stateful Web applications broken?](http://www.ibm.com/developerworks/library/j-jtp09238.html) for IBM developerWorks, I want to refer to this piece of code ``` HttpSession session = request.getSession(true); ShoppingCart cart = (ShoppingCart)session.getAttribute("shoppingCart"); if (cart == null) { cart = new ShoppingCart(...); session.setAttribute("shoppingCart", cart); } doSomethingWith(cart); ``` From my available understanding, this code is not thread-safe because it uses the **check-then-act** pattern. But I have a doubt: Isn't the creation or retrieval of the `HttpSession` in the first line totally atomic? By atomic, I mean that if two Threads call `request.getSession()`, one will block. Although both will return the same `HttpSession` instance. Thus, if a client (mobile/web browsers) makes two or make calls to the same Servlet (that executes the snippet above), you will never get a situation in which different threads see different values for `cart`. Assuming I am convinced that it is **NOT** thread safe, how would one make this thread safe? Would an `AtomicReference` work? e.g.: ``` HttpSession session = request.getSession(true); AtomicReference<ShoppingCart> cartRef = (<AtomicReference<ShoppingCart>)session.getAttribute("shoppingCart"); ShoppingCart cart = cartRef.get(); if (cart == null) { cart = new ShoppingCart(...); session.setAttribute("shoppingCart", new AtomicReference<ShoppingCart>(cart)); } doSomethingWith(cart); ``` Merci!
Your code is still not Thread-safe: ``` ShoppingCart cart = cartRef.get(); if (cart == null) { cart = new ShoppingCart(...); session.setAttribute("shoppingCart", new AtomicReference<ShoppingCart>(cart)); } ``` This is because two Threads can both get a `cart` of null, create new shopping cart objects, and insert them into the session. One of them will "win," meaning one will set the object used by future requests, but the other will -- for this request -- use a totally different `cart` object. To make this Thread-safe, you would need to do something like this, following the idiom from the article you referenced: ``` while (true) { ShoppingCart cart = cartRef.get(); if (cart != null) { break; } cart = new ShoppingCart(...); if (cartRef.compareAndSet(null, cart)) break; } ``` With the above code, if two Threads using the same `HttpSession` enter the `while` loop at the same time, there is no data race that can cause them to use different `cart` objects. To address the part of the problem that Brian Goetz doesn't address in the article, namely how do you get the `AtomicReference` into the session in the first place, there's an easy and *probably* (but not guaranteed) thread-safe way to do this. Namely, implement a session listener and put the empty `AtomicReference` objects into the session in its `sessionCreated` method: ``` public class SessionInitializer implements HttpSessionListener { public void sessionCreated(HttpSessionEvent event){ HttpSession session = event.getSession(); session.setAttribute("shoppingCart", new AtomicReference<ShoppingCart>()); } public void sessionDestroyed(HttpSessionEvent event){ // No special action needed } } ``` This method will be called once for each session, only when it is created, so this is an appropriate place to do any initialization that is needed for a session. Unfortunately, the Servlet spec does not require that there is a *happens-Before* relationship between calling `sessionCreated()` in your listener and calling your `service()` method. So this is apparently not guaranteed to be thread safe, and can potentially vary in behavior between different Servlet containers. Thus, if there is even a **small** chance that a given session can have more than one request in flight at a time, this is not safe enough. Ultimately, in this case, you need to use a lock of some sort to initialize the session. You could do something like this: ``` HttpSession session = request.getSession(true); AtomicReference<ShoppingCart> cartRef; // Ensure that the session is initialized synchronized (lock) { cartRef = (<AtomicReference<ShoppingCart>)session.getAttribute("shoppingCart"); if (cartRef == null) { cartRef = new AtomicReference<ShoppingCart>(); session.setAttribute("shoppingCart", cartRef); } } ``` After the above code has executed, your Session is initialized. The `AtomicReference` is guaranteed to be in the session, and in a thread-safe manner. You can either update the shopping cart object in the same synchronized block (and dispense with the `AtomicReference` all together -- just put the cart itself into the session), or you can update the `AtomicReference` with code shown earlier above. Which is better depends on how much initialization you need to do, how long it will take to perform this initialization, on whether doing *everything* in the synchronized block will hurt performance too much (which is best determined with a profiler, not with a guess), and so on. Normally, in my own code, I just use a synchronized block and don't use Goetz's `AtomicReference` trick. If I ever determined that synchronization was causing a liveness problem in my applications, then I would potentially move some more expensive initializations out of synchronized blocks by using tricks like the `AtomicReference` trick. See also: [Is HttpSession thread safe, are set/get Attribute thread safe operations?](https://stackoverflow.com/questions/616601/)
> Isn't the creation or retrieval of the > HttpSession in the first line totally > atomic? By atomic, I mean that if two > Threads call request.getSession(), one > will block. Even if `getSession` blocks, as soon as one thread returned with the session, the lock is relinquished. While it is creating the new cart, other threads are able to acquire the lock, obtain the session, and find that there is, as yet, no cart in the session. So, this code is not thread-safe. There is a race condition that could easily lead to multiple `ShoppingCarts` being created for a single session. Unfortunately, your proposed solution is doing exactly the same thing: checking for an object in the session, and publishing one if needed, but without any locking. The fact that the session attribute is an `AtomicReference` doesn't matter. To do this safely, you can use something like [Goetz' "Listing 5"](http://www.ibm.com/developerworks/library/j-jtp09238.html#listing5), where the reads and writes to the session attribute are performed while synchronized on a common lock. ``` HttpSession session = request.getSession(); ShoppingCart cart; synchronized (lock) { cart = (ShoppingCart) session.getAttribute(ATTR_CART); if (cart == null) { cart = new ShoppingCart(); session.setAttribute(ATTR_CART, cart); } } ``` Note that this example assumes that `ShoppingCart` is mutable and thread-safe.
Understanding Goetz's article on Thread safety of HttpSession
[ "", "java", "multithreading", "servlets", "concurrency", "" ]
I am trying to make a webpage with Ajax. Example: 1. I create a Perl/CGU file that triggers a simple post; File: ..test.cgi?name=Thomas Text back: Your name is Thomas! 2. I create a html file that can use the post, but then the page have to reload. I use text input and a button. How can I use Ajax, Perl and JSON easy together? This is how it should work together, but how? Html + Ajax/JavaScript CALL Perl + "JSON-perl-string" RETURN-TO Ajax CONVERT-JSON -> Html
For JSON try the [CPAN JSON module](http://search.cpan.org/~makamaka/JSON-2.14/lib/JSON.pm). For using the XMLHttpRequest I recommend these wonderful tutorials from IBM. [Mastering Ajax, Part 1: Introduction to Ajax](http://www.ibm.com/developerworks/web/library/wa-ajaxintro1.html?S_TACT=105AGX08&S_CMP=EDU) The two articles you'll probably be most interested in are these two: [Mastering Ajax, Part 10: Using JSON for data transfer](http://www.ibm.com/developerworks/web/library/wa-ajaxintro10/index.html?S_TACT=105AGX08&S_CMP=EDU) [Mastering Ajax, Part 11: JSON on the server side](http://www.ibm.com/developerworks/web/library/wa-ajaxintro11.html?S_TACT=105AGX08&S_CMP=EDU) You can get the entire 11 Part series [using this search link](http://www.ibm.com/developerworks/views/web/libraryview.jsp?search_by=Mastering+Ajax).
You just need to have your application return JSON (you can just use the [JSON](http://search.cpan.org/perldoc?JSON) module on CPAN for this) instead of HTML. This means you need a Content-type header of application/json instead of text/html and then you need to use that JSON in your Javascript (using a Javascript library like jQuery or Prototype is your best bet here).
How can I use Ajax, perl and JSON easy together?
[ "", "javascript", "html", "ajax", "perl", "json", "" ]
I'm developing an user control in .NET 3.5. As reaction to some event, I would like to show a simple bubble containing a short text on this control, similar to the well-known system tray notification bubbles. I'm sure this is a very easy task, could you give me a quick hint?
use [ToolTip](http://msdn.microsoft.com/en-us/library/system.windows.forms.tooltip.aspx) ``` System.Windows.Forms.ToolTip myToolTip = new System.Windows.Forms.ToolTip(); myToolTip.IsBalloon = true; myToolTip.Show("Some text", this.WhereToShow); ```
Use the `ToolTip` class -- set `IsBalloon` = `true` to get the bubble effect.
C# How to show a text bubble on a user control?
[ "", "c#", ".net", "winforms", "user-interface", "" ]
What is the intended use of the optional `else` clause of the `try` statement?
The statements in the `else` block are executed if execution falls off the bottom of the `try` - if there was no exception. Honestly, I've never found a need. However, [Handling Exceptions](http://docs.python.org/tutorial/errors.html#handling-exceptions) notes: > The use of the else clause is better > than adding additional code to the try > clause because it avoids accidentally > catching an exception that wasn’t > raised by the code being protected by > the try ... except statement. So, if you have a method that could, for example, throw an `IOError`, and you want to catch exceptions it raises, but there's something else you want to do if the first operation succeeds, and you *don't* want to catch an IOError from that operation, you might write something like this: ``` try: operation_that_can_throw_ioerror() except IOError: handle_the_exception_somehow() else: # we don't want to catch the IOError if it's raised another_operation_that_can_throw_ioerror() finally: something_we_always_need_to_do() ``` If you just put `another_operation_that_can_throw_ioerror()` after `operation_that_can_throw_ioerror`, the `except` would catch the second call's errors. And if you put it after the whole `try` block, it'll always be run, and not until after the `finally`. The `else` lets you make sure 1. the second operation's only run if there's no exception, 2. it's run before the `finally` block, and 3. any `IOError`s it raises aren't caught here
There is one **big** reason to use `else` - style and readability. It's generally a good idea to keep code that can cause exceptions near the code that deals with them. For example, compare these: ``` try: from EasyDialogs import AskPassword # 20 other lines getpass = AskPassword except ImportError: getpass = default_getpass ``` and ``` try: from EasyDialogs import AskPassword except ImportError: getpass = default_getpass else: # 20 other lines getpass = AskPassword ``` The second one is good when the `except` can't return early, or re-throw the exception. If possible, I would have written: ``` try: from EasyDialogs import AskPassword except ImportError: getpass = default_getpass return False # or throw Exception('something more descriptive') # 20 other lines getpass = AskPassword ``` **Note:** Answer copied from recently-posted duplicate [here](https://stackoverflow.com/questions/14590146/why-use-pythons-else-clause-in-try-except-block/14590276#comment20366594_14590276), hence all this "AskPassword" stuff.
What is the intended use of the optional "else" clause of the "try" statement in Python?
[ "", "python", "exception", "" ]
I've been searching for a while and everybody seems to think this is not possible using just Java, so I'll give SO a shot ;) Is there any way to have my Java application listen for events (key events in particular) while another unrelated application has window focus? In my situation, I'm looking to detect when the user has pressed the 'Pause' key on the keyboard even though my Java application does not have focus. I've heard some people mention that the only way is to write some C code and use JNI. Just curious if anybody knew of a way to avoid that? Or, if not, at least a really nice tutorial on the c/JNI stuff? Thanks
It's my understanding that this can't be done. At a fundamental level, the JVM only generates events for O/S events it receives, and it only receives O/S input events when it has focus. I am sure you *could* use JNI to trigger the O/S to generate events for all input, but that would be very O/S dependent.
Here is the best answer I've found: " There is a library to handle native keyboard and mouse control: <https://github.com/kwhat/jnativehook>) "
Event listener in Java without app having focus? (Global keypress detection)
[ "", "java", "java-native-interface", "listener", "keylistener", "" ]
In C#, when should you use interfaces and when should you use abstract classes? What can be the deciding factor?
***Update: C# 8.0 New Feature:* Beginning with C# 8.0, an interface may define a default implementation for members, including properties. Defining a default implementation for a property in an interface is rare because interfaces may not define instance data fields.** The advantages of an abstract class are: * Ability to specify default implementations of methods * Added invariant checking to functions * Have slightly more control in how the "interface" methods are called * Ability to provide behavior related or unrelated to the interface for "free" Interfaces are merely data passing contracts and do not have these features. However, they are typically more flexible as a type can only be derived from one class, but can implement any number of interfaces.
Abstract classes and interfaces are semantically different, although their usage can overlap. An abstract class is generally used as a building basis for similar classes. Implementation that is common for the classes can be in the abstract class. An interface is generally used to specify an ability for classes, where the classes doesn't have to be very similar.
Interfaces vs. abstract classes
[ "", "c#", "inheritance", "interface", "abstract-class", "" ]
Any help would be appreciated, I'm trying to convert the code below to C#, I've never used VB.NET so ReDim is a new one to me. Thanks ``` Dim inFile As System.IO.FileStream Dim binaryData() As Byte Dim strFileName As String strFileName = "C:\MyPicture.jpeg" inFile = New System.IO.FileStream(strFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read) ''//Retrive Data into a byte array variable ReDim binaryData(inFile.Length) Dim bytesRead As Long = inFile.Read(binaryData, 0, CInt(inFile.Length)) inFile.Close() ```
The code could be converted verbatim, but there's a much easier way to achieve what this is doing (read all bytes from a file), i.e. ``` var binaryData = File.ReadAllBytes(strFileName); ``` Personally I'd rename `strFileName` to just `fileName` as Hungarian notation is frowned upon in .NET code... but that's another matter!
This very easy to convert to C#. ``` FileStream inFile; byte[] binaryData; string strFileName; strFileName = @"C:\MyPicture.jpeg"; inFile = new System.IO.FileStream(strFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); binaryData = new byte[inFile.Length]; int bytesRead = inFile.Read(binaryData, 0, binaryData.Length); inFile.Close(); ``` But there is a much better way to write this. ``` string fileName = @"C:\MyPicture.jpeg"; byte[] binaryData = File.ReadAllBytes(fileName); ```
C# Help converting this code from VB.NET to C#
[ "", "c#", "vb.net", "" ]
OK, this is more of a follow-up question: [How to compute optimal paths for traveling salesman bitonic tour?](https://stackoverflow.com/questions/874982/how-to-compute-optimal-paths-for-traveling-salesman-bitonic-tour) First of all, for the bitonic tour of the traveling salesman problem I have the following recurrence relation: ``` (a) When i = 1 and j = 2, l(i; j) = dist(pi; pj ) (b) When i < j - 1; l(i; j) = l(i; j - 1) + dist(pj-1; pj) (c) When i = j - 1 and j > 2, min 1<=k<i (l(k; i) + dist(pk; pj )) ``` `l` is a table of previous results. My question is with part C: Assuming `l(k,i)` and `dist(pk,pj)` are defined, how would I implement part C in Java? My initial thought was that I iterate over `k` from `1` to `i` and store the minimum result of `(l(k,i) + dist(pk,pj))`, but I don't think that is right. for example: ``` for (int k = 1; k < i; ++k) { tmp = l(k,i) + dist(pk,pj); if (tmp < min) { min = tmp; } } // min is the result ``` This may seem like a stupid question (and probably is, I am severely lacking sleep), but I am hoping someone can help out.
One obvious optimization is to pre compute your `dist(pk,pj)` values before the loop for example ``` dist_pk_pj = dist(pk,pj); /* then do as you did before */ for (int k = 1; k < i; ++k) { tmp = l(k,i) + dist_pk_pj; if (tmp < min) { min = tmp; } } ``` Note I didn't do a similar optimization for l (as in precompute a table of l) because you stated that it was already a precomputed table. If it wasn't then I would perform the same optimization :) But as the previous comment stated the Java compiler could very well do that optimization for you. I'm no expert on what optimizations the Java Compiler performs though so take that last comment with a grain of salt :) Finally are there any special properties that the `l(k,i)` table has? For example some symmetry `l(i,k) = l(k,i)` (I am just guessing here because I don't know much about the problem so Ignore this comment if it sounds wacky). If there are any special properties post them and we could come up with further optimizations.
I think Java compiler will optimize your loop in its way. And it is ok.
How can I implement this equation in Java?
[ "", "java", "algorithm", "dynamic-programming", "recurrence", "" ]
How can I check if a date is between two other dates, in the case where all three dates are represented by instances of `java.util.Date`?
If you don't know the order of the min/max values ``` Date a, b; // assume these are set to something Date d; // the date in question return a.compareTo(d) * d.compareTo(b) > 0; ``` If you want the range to be inclusive ``` return a.compareTo(d) * d.compareTo(b) >= 0; ``` You can treat `null` as unconstrained with ``` if (a == null) { return b == null || d.compareTo(b) < 0; } else if (b == null) { return a.compareTo(d) < 0; } else { return a.compareTo(d) * d.compareTo(b) > 0; } ```
This might be a bit more readable: ``` Date min, max; // assume these are set to something Date d; // the date in question return d.after(min) && d.before(max); ```
How can I determine if a date is between two dates in Java?
[ "", "java", "date", "" ]
Right now I have this SQL query which is valid but always times out: ``` SELECT ( SELECT (MAX(WP_ODOMETER) - MIN(WP_ODOMETER)) / DATEDIFF(DAY, MIN(WP_DATETIME), MAX(WP_DATETIME)) FROM WAYPOINTS WHERE WP_DATETIME BETWEEN DATEADD(DAY,-14,GETDATE()) AND GETDATE() AND WP_VTDID = 'L088' ) AS MAXD, ( SELECT MAX(WP_ODOMETER) FROM WAYPOINTS WHERE WP_DATETIME BETWEEN DATEADD(DAY,-14,GETDATE()) AND GETDATE() AND WP_VTDID = 'L088' ) AS MD ``` I want to create a view based on the above SQL query. Something like this: ``` SELECT L_VTDID ( SELECT (MAX(WP_ODOMETER) - MIN(WP_ODOMETER)) / DATEDIFF(DAY, MIN(WP_DATETIME), MAX(WP_DATETIME)) FROM WAYPOINTS WHERE WP_DATETIME BETWEEN DATEADD(DAY,-14,GETDATE()) AND GETDATE() AND WP_VTDID = LOCOMOTIVES.L_VTDID ) AS MAXD, ( SELECT MAX(WP_ODOMETER) FROM WAYPOINTS WHERE WP_DATETIME BETWEEN DATEADD(DAY,-14,GETDATE()) AND GETDATE() AND WP_VTDID = LOCOMOTIVES.L_VTDID ) AS MD FROM LOCOMOTIVES ```
Since they have the same where clause, you could combine them: ``` SELECT MAX(WP_ODOMETER), (MAX(WP_ODOMETER) - MIN(WP_ODOMETER)) / DATEDIFF(DAY, MIN(WP_DATETIME), MAX(WP_DATETIME)) FROM WAYPOINTS WHERE WP_DATETIME BETWEEN DATEADD(DAY,-14,GETDATE()) AND GETDATE() AND WP_VTDID = 'L088' ``` An index on WP\_VTDID, WP\_DATETIME can speed this up. You could also include WP\_ODOMETER in the index, to save the bookmark lookup from the index to the table itself. If the timeout occurs because someone else is locking the table, try to change the from statement to: ``` FROM WAYPOINTS (NOLOCK) ``` If the query runs fine with NOLOCK, another process is using the table and preventing your query from locking rows.
Believe it or not, client side languages are actually quite capable of doing subtraction and division, etc. So, were it up to me, I would simplify the query (especially since this version gives trouble): ``` SELECT MAX(WP_ODOMETER) AS MAX_ODO, MIN(WP_ODOMETER) AS MIN_ODO, MIN(WP_DATETIME) AS MIN_DATE, MAX(WP_DATETIME) AS MAX_DARE FROM WAYPOINTS WHERE WP_DATETIME BETWEEN DATEADD(DAY,-14,GETDATE()) AND GETDATE() AND WP_VTDID = 'L088' ``` If there is a major problem with handling date computations on the client side, then I'd concede that you might need to generate the difference between MAX\_DATE and MIN\_DATE on the server, but it might be better to get a host language that allows you to do date computations.
How can I optimize this SQL query?
[ "", "sql", "sql-server-2005", "t-sql", "" ]
I program Django/Python in emacs, and I would like things like {% comment %} FOO {% endcomment %} to turn orange. How can I set up some colors for important Django template tags?
You could use dedicated modes like [django-mode](http://code.djangoproject.com/wiki/Emacs) or [MuMaMo](http://www.emacswiki.org/emacs/MuMaMo). If you want something very basic, and assuming you're editing in `html-mode`, you could try the following: ``` (defun django-highlight-comments () (interactive "p") (highlight-regexp "{%.*?%}" 'hi-orange)) (add-hook 'html-mode-hook 'django-highlight-comments) ``` (Just add the above lines to your `.emacs` or `init.el`, and eval it or restart emacs).
Here's what I do. It's a little more general than the code above, and it uses the built-in font-lock mechanisms. ``` (defvar django-tag-face (make-face 'django-tag-face)) (defvar django-variable-face (make-face 'django-variable-face)) (set-face-background 'django-tag-face "Aquamarine") (set-face-foreground 'django-tag-face "Black") (set-face-background 'django-variable-face "Plum") (set-face-foreground 'django-variable-face "Black") (font-lock-add-keywords 'html-mode '(("\\({%[^%]*%}\\)" 1 django-tag-face prepend) ("\\({{[^}]*}}\\)" 1 django-variable-face prepend))) ```
How can I color certain things in Emacs?
[ "", "python", "django", "emacs", "syntax-highlighting", "" ]
Becase I've seen (and used) situations like this: In header.h: ``` class point { public: point(xpos, ypos); int x; int y; }; ``` In def.cpp: ``` #include"header.h" point::point(xpos, ypos) { x = xpos; y = ypos; } ``` In main.cpp: ``` #include"header.h" int main() { point p1(5,6); return 0; } ``` I know the program executes from main, but how does the compiler know what order to compile .cpp files? (Particularily if there are more than one non-main .cpp files).
The **compiler** doesn't care - it compiles each .cpp file into .obj file, and the .obj files each contain a list of missing symbols. So in this case, main.obj says "I'm missing `point::point`". It's then the **linker**'s job to take all the .obj files, combine them together into an executable, and make sure that each .obj file's missing symbols are available from one of the other .obj files - hence the term "linker".
If you include them in two different cpp-files it's no problem. If you include the same header twice, you get errors for duplicated definitions. You should use include guards to circumvent that. On top of your file, before any code: ``` #ifndef HEADER_H_ //every header gets it's own name #define HEADER_H_ ``` On the bottom: ``` #endif ```
What happens if more than one .cpp file is #included?
[ "", "c++", "include", "" ]
I have a script that checks something on my PC every 5 minutes and I don't want Python to show on my task tray. I use Windows as my operating system. Is there any way to make Python run in the background and force it to not show in my task tray?
Look for Schedule Tasks in the control panel.
If you run a console script using `pythonw.exe`, it will neither display a window nor appear in the task bar. For example, I use the following command to launch [ntlmaps](http://ntlmaps.sourceforge.net/) on startup: ``` C:\BenBlank\Python2.6\pythonw.exe scripts/ntlmaps ``` Be aware, however, that there is no way to interact with the script, nor to terminate it save via the Task Manager.
How to run a python script in the background?
[ "", "python", "windows", "backgrounding", "" ]
I am looking to start working on a personal site using C#. I work as a web developer and have used VBScript previously and am using Coldfusion now at work. I use Dreamweaver for development in these languages. I have read a lot of people recommending that you should use a MS IDE to develop in .net and that C# is the way to go in terms of the language. I would like to stick with Dreamweaver as I feel I would be taking on a bit too much to learn how to use a new IDE and a new language at the same time. Will using something like Visual Studio help with developing in .net so much that it is worth the effort of changing from Dreamweaver? If so which IDE would be best to learn with? If I choose to stick with Dreamweaver is there any recommendations you can make as to how to best setup Dreamweaver for easy development?
I believe not. Dreamweaver is not a good tool for developing *code*. This is what you need in ASP.NET. You'll need debugging. You'll enjoy IntelliSense, and you can always open single files in Dreamweaver occasionally (which I doubt you would, anyway). Grab [Visual Studio Express 2013 for Web](http://www.visualstudio.com/downloads/download-visual-studio-vs#d-express-web) (which is free) and enjoy. It's a Windows app, like many other Windows apps! You don't need professional training to use it.
As someone who formerly coded PHP in Dreamweaver, I would strongly suggest the use of the Visual Studio IDE for C# ASP.NET applications. The benefits are numerous: * **Intellisense** - where any object, property, method, etc. that you create will automatically appear in an auto-complete box, drastically reducing syntax errors * **Project templates** - starting a web application from scratch is going to be very very tricky if you have to do it all via source code * **Debugging** - errors can be caught and debugged directly in the source code * **Add-ins** - my favorite being the [Configuration Section Designer](http://csd.codeplex.com) I'm sure there are even more reasons, these are just the biggest ones.
Where to start with ASP.net in C# and Dreamweaver?
[ "", "c#", "asp.net", "ide", "dreamweaver", "" ]
I am a recently converted VB developer to C#, but there is one thing thus far that I haven't been able to find. In VB when I setup a new project I can specify the namespaces used in the project and add them to the default imports for all classes (so everything automatically has them as if I added "Imports System.Data.OracleClient" to each class). With C# I've found that I'm always typing these in for each new class. Is there a way to setup defaults for projects so it at least appends those to every class file for me automatically?
With C# 10 this answer has changed. C# 10 introduces [Global using directives](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10#global-using-directives): > ##### Global using directives > > You can add the global modifier to any using directive to instruct the compiler that the directive applies to all source files in the compilation. This is typically all source files in a project.
No there is no way. C# does not support the concept of project level imports or project level namespaces. The only thing you can do is alter the item template you are using (Class.cs or Code.cs) to have the namespaces you would like. These files are located under the following directory > %ProgramFiles%\Microsoft Visual Studio 9.0\Common7\IDE\itemtemplatescache\CSharp\Code\1033 Under here you should see a Class.zip and Code.zip directory each with a .cs file under them. This is the template file used when you do an "Add New Item" operation in Visual Studio. You can change these to meet your needs and have the default namespaces you'd like. A slightly easier solution though is adding a per-user code file for the particular project you'd like. Simply create a code file you want to be the template for your application and then place it in the following directory. > C:\Users\YourUserName\Documents\Visual Studio 2008\Templates\ItemTemplates\Visual C# This file will now show up whenever you do a "Add New Item" operation.
Does C# Support Project-Wide Default Namespace Imports Like VB.NET?
[ "", "c#", "namespaces", "" ]
From wikipedia: ``` // A class template to express an equality comparison interface. template<typename T> class equal_comparable { friend bool operator==(T const &a, T const &b) { return a.equal_to(b); } friend bool operator!=(T const &a, T const &b) { return !a.equal_to(b); } }; class value_type // Class value_type wants to have == and !=, so it derives from // equal_comparable with itself as argument (which is the CRTP). : private equal_comparable<value_type> { public: bool equal_to(value_type const& rhs) const; // to be defined }; ``` This is supposed to be the [Barton-Nackman](http://en.wikipedia.org/wiki/Barton-Nackman_trick), that could achieve compile-time dimensional analysis (checking if some operations applied to variables end up in comparable numbers, like speed comparable to space/time but no acceleration). Could anyone explain me how, or at least explain me what are the NON-TEMPLATE members? Thanks
The rules of the language have changed since the pattern was invented, although care was taken not to break it. In other words, as far as I can tell, it still works but for different reasons than it originally did. I don't think I would base an attempt at dimensional analysis on this pattern as I think there are better ways of doing that today. I also think the example is too trivial to be helpful. As already stated the instantiation of `equal_comparable<value_type>` causes `operator==` and `operator!=` for `value_type` to appear. Since they are non-members it doesn't matter that the inheritance is private, they're still eligable for selection when resolving a call. It's just hard to see the point in this example. Let's say however, that you add a template parameter to `equal_comparable` and a few other things: ``` template<typename U, typename V> class equal_comparable { friend bool operator==(U const &a, V const &b) { return a.equal_to(b); } friend bool operator!=(U const &a, V const &b) { return !a.equal_to(b); } }; class some_other_type { bool equal_to(value_type const& rhs) const; }; class value_type : private equal_comparable<value_type>, // value_type comparable to itself private equal_comparable<some_other_type> // value_type comparable to some_other_type { public: bool equal_to(value_type const& rhs) const; bool equal_to(some_other_type const& rhs) const; }; ``` Disclaimer: I have no idea if this is the way it's *supposed* to be used but I'm reasonably sure that it would work as described.
These are actually nontemplate nonmembers - the comparison operators in the base template - they get used by the ADL for the derived class. A template member would be something like: ``` class C { ... template < typename T > void DoGreatStuff( T t ) { ... } ... }; ```
What are C++ non-template members as used in the Barton-Nackman trick?
[ "", "c++", "design-patterns", "templates", "" ]
Does anyone know of a "similar words or keywords" algorithm available in open source or via an API? I am looking for something sort of like a thesaurus but smarter. So for example: > intel returns: > processor, > i7 core chip, > quad core chip, > .. etc Any ideas or even something to point me in the right direction in C#? --- ### Edit: I would love to hear your thoughts, but why cant we just use the Google Adwords API to generate keywords relevant to those entered?
Why not send a search query out to Google and parse what it returns? Also, check out [Google Sets](http://labs.google.com/sets).
There is no algorithm for such a thing. You are going to have to acquire data for a Thesaurus, and load it into a data structure then it is a simple dictionary lookup (you can use the C# Dictionary class for that). Maybe you can look at [Wordnet](http://wordnet.princeton.edu/obtain), or [Moby Thesaurus](http://www.gutenberg.org/etext/3202) as a source for data. Other options are using a [Thesaurus server](http://www.alexandria.ucsb.edu/thesaurus/) and getting the information online as needed.
What can I use to determine similar words or keywords?
[ "", "c#", "algorithm", "" ]
So this should be a real easy question but I can't seem to find a simple answer anywhere. I'm patching up some PHP code (I'm not a PHP'er) and I have this variable $orderDate. How do I print this variable so that its just M/d/yy h:mm tt? Update: So I looked around and saw what $orderDate is. Here's the code: ``` global $orderDate; $orderDate = strftime('%c'); print("Order Date: ".date("M/d/Y h:M", $orderdate)."<br />"); ``` so I get this for output: > Dec/31/1969 06:Dec and should be getting today's date....
``` echo date("m/d/Y h:m", $orderDate); echo date("m/d/Y h:m", strtotime($orderDate)); // or this ``` Depends on what $orderDate contains. Look into [date()](http://is.php.net/manual/en/function.date.php) since it has there plenty of examples and is pretty simple to use. UPDATE: ``` $orderDate = date("M/d/Y h:M"); print("Order Date: ".orderDate ."<br />"); ``` Also check out to see if this works for you.
[`date` function](http://php.net/date) will do that for you.
PHP Print Date Variable Format
[ "", "php", "" ]
I'm using SS 2005 if that I've seen sample code like ``` DECLARE @restore = SELECT @@DATEFIRST SET DATEFIRST 1 SELECT datepart(dw,ADateTimeColumn) as MondayBasedDate,.... FROM famousShipwrecks -- SET DATEFIRST @restore ``` Suppose while the query is running another query sets DATEFIRST? If another query relies on datefirst being 7 (for example) and doesn't set it, and runs while my query is running, that's his problem for not setting it? or is there a better way to write queries that depend on a given day being day number 1.
@@DATEFIRST is local to your session. You can verify it by opening to tabs in Sql Server Management Studio (SSMS). Execute this code in the first tab: ``` SET DATEFIRST 5 ``` And verify that it doesn't affect the other tab with: ``` select @@datefirst ``` See this [MSDN article](http://msdn.microsoft.com/en-us/library/ms187766.aspx).
You can forget about `DATEPART(weekday, DateColumn)` and `@@DATEFIRST` and instead calculate the day of the week yourself. For Monday based weeks (Europe) simplest is: ``` SELECT DATEDIFF(day, '17530101', ADateTimeColumn) % 7 + 1 AS MondayBasedDay FROM famousShipwrecks ``` For Sunday based weeks (America) use: ``` SELECT DATEDIFF(day, '17530107', ADateTimeColumn) % 7 + 1 AS SundayBasedDay FROM famousShipwrecks ``` This works fine ever since January 1st respectively 7th, 1753.
SQL Server SET DATEFIRST scope
[ "", "sql", "sql-server", "" ]
How do I build a URL or a URI in Java? Is there an idiomatic way, or libraries that easily do this? I need to allow starting from a request string, parse/change various URL parts (scheme, host, path, query string) and support adding and automatically encoding query parameters.
Using HTTPClient worked well. ``` protected static String createUrl(List<NameValuePair> pairs) throws URIException{ HttpMethod method = new GetMethod("http://example.org"); method.setQueryString(pairs.toArray(new NameValuePair[]{})); return method.getURI().getEscapedURI(); } ```
As of Apache HTTP Component HttpClient 4.1.3, from the official [tutorial](http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html): ``` public class HttpClientTest { public static void main(String[] args) throws URISyntaxException { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("q", "httpclient")); qparams.add(new BasicNameValuePair("btnG", "Google Search")); qparams.add(new BasicNameValuePair("aq", "f")); qparams.add(new BasicNameValuePair("oq", null)); URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search", URLEncodedUtils.format(qparams, "UTF-8"), null); HttpGet httpget = new HttpGet(uri); System.out.println(httpget.getURI()); //http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq= } } ``` Edit: as of v4.2 `URIUtils.createURI()` has been deprecated in favor of `URIBuilder`: ``` URI uri = new URIBuilder() .setScheme("http") .setHost("www.google.com") .setPath("/search") .setParameter("q", "httpclient") .setParameter("btnG", "Google Search") .setParameter("aq", "f") .setParameter("oq", "") .build(); HttpGet httpget = new HttpGet(uri); System.out.println(httpget.getURI()); ```
What is the idiomatic way to compose a URL or URI in Java?
[ "", "java", "url", "" ]
Whilst asynchronous IO (non-blocking descriptors with select/poll/epoll/kqueue etc) is not the most documented thing on the web, there are a handful of good examples. However, all these examples, having determined the handles that are returned by the call, just have a '`do_some_io(fd)`' stub. They don't really explain how to best approach the actual asynchronous IO in such a method. Blocking IO is very tidy and straightforward to read code. Non-blocking, async IO is, on the other hand, hairy and messy. What approaches are there? What are robust and readable? ``` void do_some_io(int fd) { switch(state) { case STEP1: ... async calls if(io_would_block) return; state = STEP2; case STEP2: ... more async calls if(io_would_block) return; state = STEP3; case STEP3: ... } } ``` or perhaps (ab)using GCC's computed gotos: ``` #define concatentate(x,y) x##y #define async_read_xx(var,bytes,line) \ concatentate(jmp,line): \ if(!do_async_read(bytes,&var)) { \ schedule(EPOLLIN); \ jmp_read = &&concatentate(jmp,line); \ return; \ } // macros for making async code read like sync code #define async_read(var,bytes) \ async_read_xx(var,bytes,__LINE__) #define async_resume() \ if(jmp_read) { \ void* target = jmp_read; \ jmp_read = NULL; \ goto *target; \ } void do_some_io() { async_resume(); async_read(something,sizeof(something)); async_read(something_else,sizeof(something_else)); } ``` Or perhaps C++ exceptions and a state machine, so worker functions can trigger the abort/resume bit, or perhaps a table-driven state-machine? Its not how to make it work, its how to make it maintainable that I'm chasing!
I suggest take a look on: <http://www.kegel.com/c10k.html>, second take a look on existing libraries like libevent, Boost.Asio that already do the job and see how they work. The point is that the approach may be different for each type of system call: * select is simple reactor * epoll have both edge or level triggered interface that require different approach * iocp is proactor require other approach Suggestion: use good existing library like Boost.Asio for C++ or libevent for C. EDIT: This is how ASIO handles this ``` class connection { boost::asio:ip::tcp::socket socket_; public: void run() { // for variable length chunks async_read_until(socket_,resizable_buffer,'\n', boost::bind(&run::on_line_recieved,this,errorplacehplder); // or constant length chunks async_read(socket_,buffer(some_buf,buf_size), boost::bind(&run::on_line_recieved,this,errorplacehplder); } void on_line_recieved(error e) { // handle it run(); } }; ``` Because ASIO works as proactor it notifies you when operation is complete and handles EWOULDBLOCK internally. If you word as reactor you may simulate this behavior: ``` class conn { // Application logic void run() { read_chunk(&conn::on_chunk_read,size); } void on_chunk_read() { /* do something;*/ } // Proactor wrappers void read_chunk(void (conn::*callback),int size, int start_point=0) { read(socket,buffer+start,size) if( complete ) (this->*callback() else { this -> tmp_size-=size-read; this -> tmp_start=start+read; this -> tmp_callback=callback your_event_library_register_op_on_readable(callback,socket,this); } } void callback() { read_chunk(tmp_callback,tmp_size,tmp_start); } } ``` Something like that.
State machines are one nice approach. It's a bit of complexity up front that'll save you headaches in the future, where the future starts really, really soon. ;-) Another method is to use threads and do blocking I/O on a single fd in each thread. The trade-off here is that you make I/O simple but *may* introduce complexity in synchronization.
tidy code for asynchronous IO
[ "", "c++", "c", "asynchronous", "io", "" ]
ZODB provides a `PersistentList` and a `PersistentMapping`, but I'd like a `PersistentSet`. I wrote a quick class that mirrors the ancient [`PersistentList`](http://sysinf0.klabs.be/usr/share/zope2.7/lib/python/ZODB/PersistentList.py?f=view) from ZODB 2. Because there's no `UserSet` in Python, I had to extend from the C-based built-in `set`. ``` class PersistentSet(UserSet, Persistent): def __iand__(self, other): set.__iand__(other) self._p_changed = 1 ... ... ... def symmetric_difference_update(self, other): set.symmetric_difference_update(other) self._p_changed = 1 ``` The code produced a "multiple bases have instance lay-out conflict" [error](https://stackoverflow.com/questions/309129/why-cant-i-inherit-from-dict-and-exception-in-python). I tried creating a `UserSet` wrapper around `set`, but that didn't solve the problem either. ``` class UserSet(set): def __init__(self): self.value = set def __getattribute__(self, name): return self.value.__getattribute__(name ``` Finally, I imported `sets.Set` (superseded by the built-in `set`), but that seems to be implemented in C, too. I didn't find any set implementations on PyPI so I'm at a dead end now. **What are my options?** I may have to implement a set from scratch or use `UserDict` and throw away all the `value`s.
Why don't you use the persistent set class provided with the [BTree](http://www.zodb.org/documentation/guide/modules.html#btrees-package) libraries in ZODB. There are 4 such classes available. IITreeSet and IOTreeSet manage sets of integers and OITreeSet and OOTreeSet manage set of arbitrary objects. They correspond to the four BTree classes IIBTree, IOBTree, OIBTree and OOBTree respectively. Their advantages over the set implementation built into Python are their fast lookup mechanism (thanx to the underlying BTree) and their persistence support. Here is some sample code: ``` >>> from BTrees.IIBTree import IITreeSet, union, intersection >>> a = IITreeSet([1,2,3]) >>> a <BTrees._IIBTree.IITreeSet object at 0x00B3FF18> >>> b = IITreeSet([4,3,2]) >>> list(a) [1, 2, 3] >>> list(b) [2, 3, 4] >>> union(a,b) IISet([1, 2, 3, 4]) >>> intersection(a,b) IISet([2, 3]) ```
Forward all attribute requests to the internal set: ``` class PersistentSet(Persistent): def __init__(self): self.inner_set = set() def __getattribute__(self, name): try: inner_set = Persistent.__getattribute__(self, "inner_set") output = getattr(inner_set, name) except AttributeError: output = Persistent.__getattribute__(self, name) return output ```
PersistentSet in ZODB 3
[ "", "python", "set", "zodb", "" ]
I would like to reflect the XML tree in my object structure, but I am quite a beginner in LINQ to XML I have an XML with following structure: ``` <questions> <question id="q1"> <number>1</number> <text>some text11</text> <answers> <answer> <v>some text11</v> </answer> <answer> <v>some text11</v> </answer> </answers> </question> <question id="q2"> <number>2</number> <text>some text2</text> <answers> <answer> <v>some text22</v> </answer> <answer> <v>some text22</v> </answer> </answers> </question> <question id="q3"> <number>3</number> <text>some text3</text> <answers> <answer> <v>some text33</v> </answer> <answer> <v>some text33</v> </answer> <answer> <v>some text33</v> <addDescription>some text333</addDescription> <textBox/> </answer> </answers> </question> </questions> ``` ...and I have following classes: ``` public class Question { public string text { get; set; } public IList<Anwser> anwsers = new List<Anwser>(); } public class Anwser { public string content { get; set; } } ``` ... and I have build a following (wrong) Linq query: ``` List<Question> questions = (from xml in xdoc.Element("survey").Elements("questions").Elements("question") select new Question() { text = xml.Element("text").Value, anwsers = (from anwsers in xdoc.Element("survey").Elements("questions").Elements("question").Elements( "answers").Elements( "answer") select new Anwser() { content = anwsers.Element("v").Value } ).ToList() }).ToList(); ``` Of course this way I get each time all anwsers from all questions added to each list. How to solve this? I can imagine that this is simple but I have no idea :) Thank you in advance!
Your code isn't working because you are getting back all the answer elements because you didn't restrict them based on the question they came from. You could add this restriction or instead of a subquery based on the document, you can make the subquery based on the question element itself. ``` List<Question> questions = (from question in xdoc.Element("survey").Element("questions").Elements("question") select new Question { text = question.Element("text").Value, anwsers = (from answer in question.Element("answers").Elements("answer") select new Anwser { content = answer.Element("v").Value }).ToList() }).ToList(); ```
You were very close. In the select new parts you don't need () after the class names. Also you want to use .Descendents() instead of .Elements(). The only other part was the answers should be using the xml var not going back to the original document, this gives you the answers associated with the question. ``` List<Question> questions = (from xml in xdoc.Descendants("question") select new Question { text = xml.Element("text").Value, answers = (from anwsers in xml.Descendants("answer") select new Answer { Content = anwsers.Element("v").Value } ).ToList() }).ToList(); ```
Trying to parse XML tree with Linq to XML (C#)
[ "", "c#", ".net", "xml", "linq", "linq-to-xml", "" ]
I have several pages to do with several table on each page. I've got the JQUERY to do zebra stripes on even lines and change colour on hover. but, here it comes, it changes colour on THEAD and TFOOT and i can't apply css to TFOOT to change colour. here's the code ``` <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $(function() { $('tr').hover(function() { $(this).css('background-color', '#FFFF99'); }, function() { $(this).css('background-color', ''); }); }); }); $(function() { $("table.tiger-stripe tr:odd").addClass("oddrow"); }); </script> ```
apply the striping to table tbody only ``` $(function() { $('table.tiger-stripe tbody tr').hover( function() { $(this).css('background-color','#FFFF99'); }, function() { $(this).css('background-color', '#000000');} ); $("table.tiger-stripe tbody tr:odd").addClass("oddrow"); }); ```
Please can we see your code for a table? Are you sure there is more than one tr row in the tfoot because :odd will only trigger on alternate rows so a minimum of two rows must be present. Oh did you mean that you *didn't* want tfoot to trigger? In that case just use `$('tbody tr:odd')` as your selector.
Table highlights only in tbody
[ "", "javascript", "jquery", "css", "" ]
I try to get to a page straight from Bash at <http://www.ocwconsortium.org/>. The page appears when you write mathematics to the field at the top right corner. I tested > open <http://www.ocwconsortium.org/#mathematics> but it leads to the main page. It is clearly some javascript thing. How can I get the results straight from Bash on the first page? **[Clarification]** Let's take an example. I have the following lines for a Math search engine in .bashrc: ``` alias mathundergradsearch='/Users/user/bin/mathundergraduate' ``` Things in a separate file: ``` #!/bin/sh q=$1 w=$2 e=$3 r=$4 t=$5 open "http://www.google.com/cse?cx=007883453237583604479%3A1qd7hky6khe&ie=UTF-8&q=$q+$w+$e+$r+$t&hl=en" ``` Now, I want something similar to the example. The difference is that the other site contains javascript or something that does not allow me to see the parameters. How could I know where to put the search parameters as I cannot see the details?
``` open "http://www.ocwconsortium.org/index.php?q=mathematics&option=com_coursefinder&uss=1&l=&s=&Itemid=166&b.x=0&b.y=0&b=search" ``` You need quotes because the URL contains characters the shell considers to be special.
The [Links web browser](http://links.sourceforge.net/) more or less runs from the commandline (like lynx) and supports basic javascript. Even though the title of the post sounds general, your question is very specific. It's unclear to me what you're trying to achieve in the end. Clearly you can access sites that rely heavily on javascript (else you wouldn't be able to post your question here), so I'm sure that you can open the mentioned site in a normal browser. If you just want to execute javascript from the commandline (as the title suggests), it's easy if you're running bash via cygwin. You just call cscript.exe and provide a .js scriptname of what you wish to execute.
How can I execute javascript in Bash?
[ "", "javascript", "bash", "" ]
In this code (from the [WCF REST starterkit](http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24644) - preview2): ``` protected override SampleItem OnAddItem(SampleItem initialValue, out string id) { // TODO: Change the sample implementation here id = Guid.NewGuid().ToString(); this.items.Add(id, initialValue); return initialValue; } ``` Am I getting back id as String, or the initialValue as SampleItem? Edit: Looks like I get both back, so what would a simple example of the method call look like assigned to a couple of variables?
You will get back id in the string that you pass as a parameter to the method. Also, the method will return the SampleItem instance. ``` SampleItem myItem = new SampleItem(); string newId = string.Empty; myItem = OnAddItem(myItem, out newId); // now myItem will be assigned with SampleItem returned from the // OnAddItem method, and newId will be updated with the id assigned // within that method ```
You're getting both.
Question about Out and Return?
[ "", "c#", ".net", "" ]
I'm using Apache Commons Logging and SLF4J with log4j, but I also want to use the log4j.properties in a custom place like conf/log4.properties. Here is the problem: If i use ``` PropertyConfigurator.configure("conf/log4j.properties"); ``` then my app is tied to log4j and defeats the purpose of having ACL and SLF4J. What is the best way to configure it without the app ever knowing what the logging implementation is?
I think the easiest thing to do is specify the location of the file using the *log4j.configuration* system property. Adopting the example in the [Log4J manual](http://logging.apache.org/log4j/1.2/manual.html): ``` java -Dlog4j.configuration=conf/log4j.properties -classpath ... ``` I believe that Log4J will find a file named "log4j.properties" anywhere on the classpath, but may be hallucinating. Worth trying, however.
As you state, by invoking `PropertiesConfigurator`, you are tying your application to log4j. However, the extend of this tie is quite limited. You could very easily remove the line invoking `PropertiesConfigurator` and recompile your code. After that is done, assuming you are using the SLF4J API for logging, you could repalce log4j with another logging framework, say logback-classic or j.u.l. just by replacing jar files. Thus, SLF4J still serves its purpose to a large extend. I would not throw the baby out with the bath water.
Log4j Properties in a Custom Place
[ "", "java", "properties", "log4j", "propertyconfigurator", "" ]
### Duplicate: > * [Best javascript compressor](https://stackoverflow.com/questions/28932/best-javascript-compressor) > * [Which javascript minification library produces better results?](https://stackoverflow.com/questions/360818/which-javascript-minification-library-produces-better-results) > * [What is the best method to reduce the size of my Javascript and CSS files?](https://stackoverflow.com/questions/65491/what-is-the-best-method-to-reduce-the-size-of-my-javascript-and-css-files) --- So far I have seen these tools to compress javascript files * [Packer](http://svn.offwhite.net/trac/SmallSharpTools.Packer/wiki) * [JSMin](http://www.crockford.com/javascript/jsmin.html) * [Yahoo Compressor](http://developer.yahoo.com/yui/compressor/) On Packer page there is a section "Packer versus JSMin" which says that JSMin can be more efficient than Packer. On Yahoo Compressor page it states that Yahoo compressor is more efficient than JSMin, so it looks like Yahoo compressor might be a best candidate. What is the best option for compressing javascript files?
Yahoo's compressor, for a combination of safety, and decent compression. It uses a real JavaScript parser, rather than using a set of regular expressions. It is able to do the same kind of variable renaming that Packer can, but is much safer. It won't break if you forget to put a semicolon at the end of a function definition. Packer does have an encoding feature that generates an even smaller file. However, it's only effective if your web server does not support gzip or deflate compression. With gzip / deflate, YUI and Packer generate files that are about the same size.
I use YUICompressor exclusively because it intelligently minifies removing whitespace and reducing internal variables down whilst maintaining external refs properly and has yet to break my code and it also does CSS to boot! After that we serve up on a GZip HTTP connection and voila!
Ways to compress/minify javascript files
[ "", "javascript", "compression", "minify", "jscompress", "" ]
I am trying to gather a list (array) of ids in a sector ``` <div id="mydiv"> <span id='span1'> <span id='span2'> </div> $("#mydiv").find("span"); ``` gives me a jQuery object, but not a real array; I can do ``` var array = jQuery.makeArray($("#mydiv").find("span")); ``` and then use a for loop to put the id attributes into another array or I can do ``` $("#mydiv").find("span").each(function(){}); //but i cannot really get the id and assign it to an array that is not with in the scope?(or can I) ``` Anyhow, I just wanna see if there is a shorthand in jQuery to do that;
> //but i cannot really get the id and assign it to an array that is not with in the scope?(or can I) Yes, you can! ``` var IDs = []; $("#mydiv").find("span").each(function(){ IDs.push(this.id); }); ``` This is the beauty of [closures](https://stackoverflow.com/questions/tagged/closures%20javascript). Note that while you were on the right track, [sighohwell](https://stackoverflow.com/questions/827294/how-to-get-all-of-the-ids-with-jquery/827320#827320) and [cletus](https://stackoverflow.com/questions/827294/how-to-get-all-of-the-ids-with-jquery/827329#827329) both point out more reliable and concise ways of accomplishing this, taking advantage of [attribute filters](http://docs.jquery.com/Selectors/attributeHas#attribute) (to limit matched elements to those with IDs) and jQuery's built-in [`map()`](https://api.jquery.com/jQuery.map/) function: ``` var IDs = $("#mydiv span[id]") // find spans with ID attribute .map(function() { return this.id; }) // convert to set of IDs .get(); // convert to instance of Array (optional) ```
The .get() method will return an array from a jQuery object. In addition you can use .map to project to something before calling get() ``` var idarray = $("#myDiv") .find("span") //Find the spans .map(function() { return this.id; }) //Project Ids .get(); //ToArray ```
How to get all of the IDs with jQuery?
[ "", "javascript", "jquery", "" ]
I am using Google Maps API to display a map on a certain page. Problem is that the file `http://maps.google.com/maps?file=api.....` sometimes happens to load very slow - decreasing the page's performance, because the rest of the JavaScript is first loaded on document ready, which its rarely reaches - because the browser locks up waiting for the file from Google. I have tried to move the JavaScript file from the `<head>` tag to under my content. But the rest of the JavaScript is never fired because the browser waits for the file from Google. Is there a way around this, or have anyone else experienced same problem? It began recently, and I have no idea why. This is my code, if anyone is interested: ``` <script type="text/javascript" src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=true&amp;key=ABQIAAAAa24xicak8_ghHX58i7La7hRFh9iM79SNC94rOejOtdMRvQmJiBS6Uv5F_1BNSh9ZuSzFXyekHISgew"> </script> <script type="text/javascript" src="/js/maps.js"></script> <script type="text/javascript"> $(document).ready(function() { // Google Maps initialize(); // Other JavaScript comes here.... }); </script> ``` If I access ``` http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=true&amp;key=ABQIAAAAa24xicak8_ghHX58i7La7hRFh9iM79SNC94rOejOtdMRvQmJiBS6Uv5F_1BNSh9ZuSzFXyekHISgew ``` The file loads instantly.
This is a rather old question now - the solution was to disable firebug (atleast for me).
Use Google's Ajax APIs. From some time past, all of Google's services can be accessed through the JavaScript API. It's a modular system, you only have to include the JSAPI library, and then you can dynamically load the modules you need—it won't block your site. ``` <script type="text/javascript" src="http://www.google.com/jsapi?key=ABCDEFG"></script> <script type="text/javascript"> google.load("maps", "2"); google.setOnLoadCallback(function() { // Your logic goes here. // It will be run right after the maps module was loaded. }); </script> ``` For further details, see [JSAPI's developer documentation](http://code.google.com/apis/ajax/documentation/).
Google Maps API - Slow loading javascript
[ "", "javascript", "google-maps", "" ]
I need to import some Excel spreadsheets into Java objects. I will use POI to do the task (an old version of it unfortunately). However I wonder if there is some high-level framework to do the same task but declaratively. I'm thinking in Castor and XML. The mapping Excel-Class will be stored in a resource (e.g. an XML file). Yes, I'm a lazy bones. But I don't like having lots of hard-coded POI statements when the user decides to change the input format. Thanks
I like [JExcelApi](http://jexcelapi.sourceforge.net/) very much, it is simple and powerful
There are open source libraries that allow you to treat a spreadsheet like a database and access it via JDBC. Googling for "excel jdbc driver" should help you get started.
Tool for importing Excel spreadsheets
[ "", "java", "excel", "apache-poi", "castor", "" ]
I work in a group that does a large mix of research development and full shipping code. Half the time I develop processes that run on our real time system ( somewhere between soft real-time & hard real-time, medium real-time? ) The other half I write or optimize processes for our researchers who don't necessarily care about the code at all. Currently I'm working on a process which I have to fork into two different branches. There is a research version for one group, and a production version that will need to occasionally be merged with the research code to get the latest and greatest into production. To test these processes you need to setup a semi complicated testing environment that will send the data we analyze to the process at the correct time (real time system). I was thinking about how I could make the: 1. Idea 2. Implement 3. Test 4. GOTO #1 Cycle as easy, fast and pain free as possible for my colleagues. One Idea I had was to embed a scripting language inside these long running processes. So as the process run's they could tweak the actual algorithm & it's parameters. Off the bat I looked at embedding: * Lua (useful [guide](http://csl.sublevel3.org/lua/)) * Python (useful [guide](http://docs.python.org/extending/extending.html)) These both seem doable and might actually fully solve the given problem. Any other bright idea's out there? Recompiling after a 1-2 line change, redeploying to the test environment and restarting just sucks. The system is fairly complicated and hopefully I explained it half decently.
If you can change enough of the program through a script to be useful, without a full recompile, maybe you should think about breaking the system up into smaller parts. You could have a "server" that handles data loading etc and then the client code that does the actual processing. Each time the system loads new data, it could check and see if the client code has been re-compiled and then use it if that's the case. I think there would be a couple of advantages here, the largest of which would be that the whole system would be much less complex. Now you're working in one language instead of two. There is less of a chance that people can mess things up when moving from python or lua mode to c++ mode in their heads. By embedding some other language in the system you also run the risk of becoming dependent on it. If you use python or lua to tweek the program, those languages either become a dependency when it becomes time to deploy, or you need to back things out to C++. If you choose to port things to C++ theres another chance for bugs to crop up during the switch.
Embedding Lua is much easier than embedding Python. * Lua was designed from the start to be embedded; Python's embeddability was grafted on after the fact. * Lua is about 20x smaller and simpler than Python. You don't say much about your build process, but building and testing can be simplified significantly by using a really powerful version of make. I use Andrew Hume's [mk](http://swtch.com/plan9port/unix/), but you would probably be even better off investing the time to master Glenn Fowler's [nmake](http://www.research.att.com/~gsf/nmake/nmake.html), which can add dependencies on the fly and eliminate the need for a separate configuration step. I don't ordinarily recommend nmake because it is somewhat complicated, but it is very clear that Fowler and his group have built into nmake solutions for *lots* of scaling and portability problems. For your particular situation, it may be worth the effort to master it.
Simplifying algorithm testing for researchers.
[ "", "c++", "scripting", "real-time", "" ]
I have been writing C++ Console/CMD-line applications for about a year now and would like to get into windows GUI apps. For those of you who have taken this road before, what advice/tips can you give me. Ex: good readings, tutorials, approach tactics, etc... I know this is a really broad question, but i really don't know how/where to start, thus not knowing how to ask this question properly.
I highly recommend the use of the [Qt Libraries](https://www.qt.io/) for several reasons: 1. The Framework is **freely** available for Windows, Linux, MacOS X, and a couple of mobile systems. Since version 4.5 the license is LGPL, which basically means that you can use Qt even in commercial applications. 2. The **design** of Qt is out-standing, e.g. they use modern design patterns and a very consistent interface design (I don't know many other libraries that use object-oriented ideas in such perfection). Using Qt is the same as using Boost: it will improve your own programming skills, because they use such beautiful concepts! 3. They are bloody fast, for instance in **rendering** (due to the different back-end for OpenGL, DirectX, etc.). Just have a look on [this video](http://www.youtube.com/watch?v=MXS3xKV-UM0&feature=channel_page) and you see what can easily be done with Qt but is hard to achieve with native Windows, Mac, or Linux programming. 4. They have a really **great documentation**, with tons of tutorials and a very good reference. You can start learning Qt easily with the given docs! The documentation is also [available online](https://doc.qt.io/qt-5.7/index.html), so have a look and see by yourself. 5. As mentioned before, Qt is **cross-platform**; you have one source-base that works on all the important operating systems. Why will you limit yourself to Windows, when you can also have Mac and Linux "for free"? 6. Qt is so **much more** than "just" the user interface; they also offer network and database functionality, OpenGL bindings, a full-working web-browser control (based on WebKit), a multimedia playback library, and much much much more. Honestly, I wasted a couple of years by developing software *natively* for Windows, while I could have been so much more productive.
For C++ you have two choices, Native or Managed. For native development, my team (at Microsoft, in Windows) uses the [Windows Template Library](http://en.wikipedia.org/wiki/Windows_Template_Library). It works very well for us. You should learn the basics of Win32 and how Windowing works. The canonical tome is [Programming Windows®](https://rads.stackoverflow.com/amzn/click/com/157231995X) For Managed development you can use C++ with [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms). However, windows forms has been supplanted by [Windows Presentation Foundation (WPF)](http://en.wikipedia.org/wiki/Windows_Presentation_Foundation). * [Here is a good site](http://windowsclient.net/) that can get you up to speed. * [This tutorial is useful](http://msdn.microsoft.com/en-us/library/aa733747(VS.60).aspx) * You can use V[isual C++ 2008 Express Edition](http://www.microsoft.com/Express/vc/) for your tools (they are free).
Advice for C++ GUI programming
[ "", "c++", "visual-c++", "" ]
I have some Java code which performs bitwise operations on a BitSet. I have a list of operations and can "interpret" them by looping over them, but it's important to me that I can perform these operations as quickly as possible, so I've been trying to dynamically generate code to apply them. I generate Java source to perform the operations and compile a class implementing those operations using Javassist. Unfortunately, my dynamically-generated code runs slower than the interpreted code. It appears that this is because HotSpot is optimizing the interpreted code but isn't optimizing the compiled code: After I run it a few thousand times, my interpreted code runs twice as fast as it did initially, but my compiled code shows no speedup. Consistent with this hypothesis, my interpreted code is initially slower than the compiled code, but is eventually faster. I'm not sure why this is happening. My guess is that maybe Javassist uses a class loader whose classes HotSpot doesn't touch. But I'm not expert on class loading in Java, so I'm not sure if this is a reasonable guess or how to go about testing it. Here's how I'm creating and loading the class with Javassist: ``` ClassPool pool = ClassPool.getDefault(); CtClass tClass = pool.makeClass("foo"); // foo implements MyInterface, with one method tClass.addInterface(pool.get(MyInterface.class.getName())); // Get the source for the method and add it CtMethod tMethod = CtNewMethod.make(getSource(), tClass); tClass.addMethod(tMethod); // finally, compile and load the class return (MyInterface)tClass.toClass().newInstance(); ``` Does anyone have an idea as to what's going on here? I'd really appreciate whatever help you can give. I'm using the Sun 1.6 server JVM on Windows XP 32-bit.
HotSpot doesn't care where the code comes from. For instance, it'll happily inline code called through a virtual method call with an implementation loaded by a different class loader. I suggest you write out in source code the operations you are trying to perform for this benchmark, and then benchmark that. It's usually easier to write out an example of generated code rather than writing the generator anyway. There a number of reasons why HotSpot might not optimise code as hard as it might. For instance very long methods will tend not to be inlined or have method inlined into them.
I think I understand what was going on here. My first mistake was generating methods which were too long. After I fixed that, I noticed that although my generated code was still slower, it eventually approached the speed of the interpreted code. I think that the biggest speedup here comes from HotSpot optimizing my code. In the interpreted version, there's very little code to optimize, so HotSpot quickly takes care of it. In the generated version, there's a lot of code to optimize, so HotSpot takes longer to work its magic over all the code. If I run my benchmarks for long enough, I now see my generated code performing just slightly better than the interpreted code.
Why does Java code generated to perform an operation run more slowly than an "interpreter loop"?
[ "", "java", "optimization", "code-generation", "jvm-hotspot", "" ]
In my SQL Server 2000 database, I have a timestamp (in function not in data type) column of type `DATETIME` named `lastTouched` set to `getdate()` as its default value/binding. I am using the Netbeans 6.5 generated JPA entity classes, and have this in my code ``` @Basic(optional = false) @Column(name = "LastTouched") @Temporal(TemporalType.TIMESTAMP) private Date lastTouched; ``` However when I try to put the object into the database I get, ``` javax.persistence.PersistenceException: org.hibernate.PropertyValueException: not-null property references a null or transient value: com.generic.Stuff.lastTouched ``` I've tried setting the `@Basic` to `(optional = true)`, but that throws an exception saying the database doesn't allow `null` values for the `TIMESTAMP` column, which it doesn't by design. ``` ERROR JDBCExceptionReporter - Cannot insert the value NULL into column 'LastTouched', table 'DatabaseName.dbo.Stuff'; column does not allow nulls. INSERT fails. ``` I previously got this to work in pure Hibernate, but I have since switched over to JPA and have no idea how to tell it that this column is supposed to be generated on the database side. Note that I am still using Hibernate as my JPA persistence layer.
I fixed the issue by changing the code to ``` @Basic(optional = false) @Column(name = "LastTouched", insertable = false, updatable = false) @Temporal(TemporalType.TIMESTAMP) private Date lastTouched; ``` So the timestamp column is ignored when generating SQL inserts. Not sure if this is the best way to go about this. Feedback is welcome.
I realize this is a bit late, but I've had success with annotating a timestamp column with ``` @Column(name="timestamp", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP") ``` This should also work with `CURRENT_DATE` and `CURRENT_TIME`. I'm using JPA/Hibernate with Oracle, so YMMV.
Setting a JPA timestamp column to be generated by the database?
[ "", "java", "jpa", "persistence", "annotations", "timestamp", "" ]
I'm working on a part of a website where I generate PDFs, attach them to an email and send it off. Right now I am not tracking the current sum of the sizes of all the PDFs to be attached to the email, but I suspect at one point that I should. My question boils down to: What is a good theoretical *MAX\_SIZE* that you should go by when managing attachments to emails. For example, when the sum of the sizes of the PDFs I am generating reaches *MAX\_SIZE*, I would add those PDFs to an email and then send it off. Then I would create a new email, add the remaining PDF attachments to it and send it off. Repeat ad nauseam until all PDFs are sent.
Given the answers you've seen and my experience, it comes down to knowing your users. Are your users on your intranet? Check the attachment policy of the user set. Are the users anywhere on the internet? Then I recommend you examine your user base and decide the % threshold you're willing to risk refusals from. For example, if you have, say 50% AOL users, 20% gmail users, 20% hotmail, 5% yahoo, 5% misc. - you could argue you are willing to risk that 5% of your emails are rejected - so take the minimum size allowed by AOL, gmail, hotmail, and yahoo. The other thing you might consider is ensuring that you have a way to monitor the messages that are rejected due to attachment size - then communicate with those people to let them know they need larger attachment limits to use your service. Etc. etc... in summary, break the problem down, research the acceptable tolerances, and try to handle the outliers in a way that does not degrade the experience of your main audience. Good luck, -james
GMail [has 20MB limit](http://mail.google.com/support/bin/answer.py?hl=en&answer=8770). I find that to be fair for general use. The size isn't so large that it takes forever on most connections, but is large enough to send most PDF documents whole.
What's a good theoretical MAX_SIZE when managing email attachments?
[ "", "php", "email", "pdf", "email-attachments", "" ]
Upon reviewing a bunch of MVC style web applications, I'm noticing that it's common to have a very large service interface sitting in front of the business layer. The implementation of this interface usually includes a bunch of DAOs. So you have something like: ``` public class FoodServiceImpl implements FoodService { private FruitDAO fruitDAO; private VegetableDAO vegetableDAO; private MeatDAO meatDAO; // ... DAO injection stuff public List<Meat> getMeat() { return meatDAO.getMeat(); } public void addMeat(Meat meat) { meatDAO.add(meat); } public List<Fruit> getFruit() { return fruitDAO.getFruit(); } // ... tons of methods that mostly just delegate to DAOs } ``` Assuming that your DAOs aren't concrete in the first place, why not just expose the DAOs to the next level up? So instead of: ``` // assume foodService is injected at runtime public void controllerMethod() { foodService.getFruit(); foodService.getMeat(); } ``` You just have ``` // assume DAOs are injected at runtime public void controllerMethod() { fruitDAO.getFruit(); meatDAO.getMeat(); } ``` On one hand it looks kinda nice to have the entire guts of the application wrapped up in a single interface.... on the other hand you can end up with a giant interface whose implementation does nothing much more than delegating to DAOs. I can see that it's nice to manage all of the DAOs in one place. I can also imagine that this pattern would be useful if the same DAOs were going to be used via multiple services. Is this considered a "best practice" when starting a web application, or does it only apply when a certain level and type of complexity is expected?
I think it makes more sense to inject a service layer because it knows about units of work. If your use case requires more than one DAO to participate in a unit of work, a service is required to "own" the transaction. Besides, it's the essence of service oriented architecture. Forget about WS-\*; services map to use cases and business processes.
Assuming the entire backend isn't just one giant CRUD API, you will often see business logic invoked in the service layer. The business logic might be directly in the service methods themselves (a.k.a. "Anemic Domain Model") or the service layer must just be responsible for invoking business methods on the entities passed to/from the DAO layer ("Rich Domain Model"). You might also see things like security or auditing and other kind being done in the service layer. Alternatively, cross-cutting concerns such as security or auditing might be applied to the service layer via Aspect-Oriented Programming (AOP).
Hiding DAOs behind service, why?
[ "", "java", "web-applications", "oop", "" ]
I've read all the answers on to this questions and none of the solutions seem to work. Also, I am getting the vibe that triggering keypress with special characters does not work at all. Can someone verify who has done this?
If you want to trigger the keypress or keydown event then all you have to do is: ``` var e = jQuery.Event("keydown"); e.which = 50; // # Some key code value $("input").trigger(e); ```
Slightly more concise now [with jQuery 1.6+](http://api.jquery.com/category/events/event-object/) and [jQuery UI](https://jqueryui.com/): ``` var e = jQuery.Event( 'keydown', { which: $.ui.keyCode.ENTER } ); $('input').trigger(e); ``` (If you're not using jQuery UI, sub in the appropriate keycode instead.)
Definitive way to trigger keypress events with jQuery
[ "", "javascript", "jquery", "events", "triggers", "keypress", "" ]
I need a function that can return the difference between the below two dates as 24. ``` DateTime a = new DateTime(2008, 01, 02, 06, 30, 00); DateTime b = new DateTime(2008, 01, 03, 06, 30, 00); ```
You can do the following: ``` TimeSpan duration = b - a; ``` There's plenty of built in methods in the timespan class to do what you need, i.e. ``` duration.TotalSeconds duration.TotalMinutes ``` More info can be found [here](http://msdn.microsoft.com/en-us/library/system.timespan.aspx).
Try the following ``` double hours = (b-a).TotalHours; ``` If you just want the hour difference excluding the difference in days you can use the following ``` int hours = (b-a).Hours; ``` The difference between these two properties is mainly seen when the time difference is more than 1 day. The Hours property will only report the actual hour difference between the two dates. So if two dates differed by 100 years but occurred at the same time in the day, hours would return 0. But TotalHours will return the difference between in the total amount of hours that occurred between the two dates (876,000 hours in this case). The other difference is that TotalHours will return fractional hours. This may or may not be what you want. If not, Math.Round can adjust it to your liking.
Difference between two DateTimes C#?
[ "", "c#", "date", "datediff", "" ]
Is there a java library or framework (other than the javax.comm provided by Sun) that is easy to use when accessing serial and parallel ports ( especially RS-232 ). I need something free that will work both on Windows and Linux.
As andri pointed out [RXTX](http://rxtx.qbang.org/) is pretty much your best choice. There is an article on [getting started with RXTX on Windows here](http://kuligowski.pl/java/rs232-in-java-for-windows,1) (relating to RXTX 2.1).
The most common framework used for this is [rxtx](http://rxtx.qbang.org/).
Is there Java library or framework for accessing Serial ports?
[ "", "java", "serial-port", "" ]
I'm currently maintaining an "old" system written in C# .NET, removing some obsolete features and doing some refactoring. The previous guy wrote some unit tests (MSTests). I quite comfortable with JUnit tests but didn't do much yet with MSTests. The test methods have a `DeploymentItem` attribute, specifying a text file which is parsed by the method with business logic that is being tested and a 2nd `DeploymentItem` where just a path has been specified containing a bunch of TIF files that have to be deployed too. ``` [TestMethod()] [DeploymentItem(@"files\valid\valid_entries.txt")] [DeploymentItem(@"files\tif\")] public void ExistsTifTest() { ... } ``` The tests worked before, but now I had to change the names of the TIF files contained in the \files\tif directory. According to a rule, the TIF filenames have to match a certain pattern which is also checked by the `ExistsTifTest()` method. Now I had to change the filenames in order to adapt them to the new requirements and suddently the TIF files are no more being deployed as before. Can someone give me a hint why this happens or what may be the cause? The same thing happens also if I add a new text-file say "my2ndTest.txt" beside the "valid\_entries.txt" in the \files\valid\ directory with the according DeploymentItem attribute on the test method. The file doesn't get deployed? I got the images now deployed by defining the deployment path directly in the testrunconfig, but I'd like to understand why these things happen or why for instance my new file "my2ndTest.txt" doesn't get deployed while the others do.
`DeploymentItem` is a bit of a mess. Each file in your solution will have a "Copy To Output Folder" setting in VS.NET. You need this to be "Copy Always" (or similar) in order to get the files into the output folder. Check that you've got this set for the new files. If you don't have this set then the files won't get copied to the output folder, and then they can't be deployed from the output folder to the folder where MSTest does it stuff. Personally, if I have files that I need for my unit tests I've found that embedding those files as resources into an assembly, and having that assembly "unpack" itself during the tests is a more predictable way of doing things. YMMV. **note:** These comments are based upon my experience with VS2010. Comments to my answer would suggest that this is not problem with VS2012. I still stand by comments that using embedded resources involves less "magic" and, for me, makes the "arrange" stage of my unit tests much more explicit.
In VS2010, my Local.testsettings had the "Enable Deployment" unchecked and the DeploymentItem attribute was not working. I checked it and everything worked fine. I hope this helps!
Problems with DeploymentItem attribute
[ "", "c#", "visual-studio", "unit-testing", "mstest", "deploymentitem", "" ]
Does anyone know of a way to set the default module dynamically in Zend Framework and not run into namespace issues? For example, what I want to do is have a table of modules that are allowed to be loaded, with one of them set as the default module. For example, I may have: ``` admin blog calendar ``` as modules that can be loaded. If I have 'blog' as the default module, then 'admin' and 'calendar' have to have their controllers namespaced (Admin\_IndexController, Calendar\_IndexController) while 'blog' isn't (IndexController). If I change 'calendar' to be the default module, ZF can no longer find the classes because of the namespacing. How do you get around that? I'm currently using the following code: ``` $modules = new Modules(); $activeModules = $modules->fetchActive(); foreach($activeModules as $mod) { $loadedModules[$mod->name] = '..application/modules/' . $mod->name . '/controllers'; if($mod->default) { $defaultModule = $mod->name; } } $frontController->setControllerDirectory($loadedModules); $frontController->setDefaultModule($defaultModule); ```
If you plan on changing the default module, it is probably best to namespace **ALL** modules, and then specify that the default module should be prefixed: First change the "blog" module to use namespacing: ``` <?php // Used to be "class IndexController" class Blog_IndexController extends Zend_Controller_Action { } ``` Then, call **setParam** for **prefixDefaultModule** option on your instance of Zend\_Controller\_Front: ``` <?php // Allow your default module to be prefixed $frontController->setParam('prefixDefaultModule', true); ``` See [bug # 1831](http://framework.zend.com/issues/browse/ZF-1831) for an explanation.
use application.ini: resources.frontController.prefixDefaultModule = true resources.frontController.defaultModule = default
Dynamic Default Module in Zend Framework
[ "", "php", "zend-framework", "module", "" ]
In my career I have seen literally dozens of ways that people choose to handle implementing state and country data (as in NY or USA). I've seen enumerations, multi-dimensional arrays, data driven classes from XML docs or databases, and good old-fashioned strings. So, I'm wondering, what do people consider the "best way" to handle this very common implementation? I know that most of the answers will be based primarily on opinion and preference; but, I'm curious to hear arguments as a recent discussion for an app I'm working on has resulted in a small debate.
If you consider the number of states in the united states to be unchanging then what you have is a finite, small, fixed set of values which can easily be associated with a number. For that type of data structure an enumeration works great. My choice then would be an enumeration as they have good compile time validation and typing something like the following reads nicely. ``` var state = GetStateInfo(States.Nebraska); ``` However if you consider the number of states to be a changing value then an enumeration may not be the best choice. The framework design guidelines ([link](http://msdn.microsoft.com/en-us/library/ms229058.aspx)) reccomend you do not use an enumeration for a set of values which is considered to be open (changing). The reason why is that if the value does change you risk breaking already shipped code. Instead I would go with a static class and string constants for the name.
I would pick a standard for enumerating the geogrpahical areas and then associate keys in a table. In the past I have used [FIPS 5-2 place codes](http://en.wikipedia.org/wiki/FIPS_place_code). Its a federal standard and the numbers and abbreviations are reasonablly well known. for international country codes we use [FIPS 10-4](http://en.wikipedia.org/wiki/FIPS_10-4) for encoding places. There are some iso standards such as ISO 3166 that may also be appealing, but this is more preference and taste.
Handling states and countries (or provinces): best way to implement
[ "", "c#", ".net", "vb.net", "" ]
I need to find a way to spin off a thread from a static call and not wait for the thread to complete. Basically, a "fire and forget" approach. Can someone supply me with a simple example of how this can be accomplished?
``` Thread t = new Thread(new YourClassThatImplementsRunnable()); t.start(); // JDK 8 new Thread(() -> methodYouWantToRun()).start(); ```
If it's a long-lived thread that has a similar lifecycle to your app itself, and is going to be spending a lot of its time waiting on other threads: ``` new Thread(new yourLongRunningProcessThatImplementsRunnable()).start(); ``` If it's a short-lived, CPU-bound task: ``` ExecutorService es = Executors.newFixedThreadPool(Runtime.availableProcessors()); es.submit(new yourTaskThatImplementsRunnable()); ``` Though, in most cases like this, you will be submitting a number of tasks to that same `ExecutorService`. # See: * [Java Concurrency Tutorial](http://java.sun.com/docs/books/tutorial/essential/concurrency/) * [ExecutorService](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html) * [ExecutorCompletionService](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorCompletionService.html) * [Runnable](http://java.sun.com/javase/6/docs/api/java/lang/Runnable.html) * [Thread](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html) * [Future](http://java.sun.com/javase/6/docs/api/java/util/concurrent/Future.html)
Java, Don't wait for a thread to complete
[ "", "java", "multithreading", "" ]
In need to serialize an object and it's possible that the assembly version changed while deserialization. Additionally it can happen, that the object changes a bit. The XmlSerializer does not store type information and if the object changes a bit, it just does not fail, but the XmlSerializer can not serialize private or internal properties from a super class I can not mark with attributes. So I had a look at the DataContractSerializer. It looks fine so fare, the problem with the private / internal properties of the super class would be solved, all properties have to be marked and I don't need them, but what about the type information? And how does the DataContractSerializer behave, if some properties are removed, renamed or added?
I made a test with the DataContractSerializer and it seems as the DataContractSerializer is very tolerant against object changes, so I'll use the approach.
This isn't marked as a WCF question, but the fact you are talking about DataContractSerializer makes me think that you are working within WCF. If that is the case it might be worhtwhile looking into the IExtensibleDataObject interface. Refer: <http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iextensibledataobject.aspx> and <http://msdn.microsoft.com/en-us/library/ms731138.aspx>
Which One Better Handles Versioning? XmlSerializer vs. DataContractSerializer?
[ "", "c#", "xml-serialization", "" ]
In python we can use multiprocessing modules. If there is a similar library in Perl and Ruby, would you teach it? I would appreciate it if you can include a brief sample.
With Perl, you have options. One option is to use processes as below. I need to look up how to write the analogous program using threads but <http://perldoc.perl.org/perlthrtut.html> should give you an idea. ``` #!/usr/bin/perl use strict; use warnings; use Parallel::ForkManager; my @data = (0 .. 19); my $pm = Parallel::ForkManager->new(4); for my $n ( @data ) { my $pid = $pm->start and next; warn sprintf "%d^3 = %d\n", $n, slow_cube($n); $pm->finish; } sub slow_cube { my ($n) = @_; sleep 1; return $n * $n * $n; } __END__ ``` The following version using threads does not use a limit on the number of threads created (because I do not know how): ``` #!/usr/bin/perl use strict; use warnings; use threads; my @data = (0 .. 19); my @threads = map { threads->new( {context => 'list' }, \&slow_cube, $_ ) } @data; for my $thr ( @threads ) { my ( $n, $ncubed ) = $thr->join; print "$n^3 = $ncubed\n"; } sub slow_cube { my ($n) = @_; sleep 1; return $n, $n * $n * $n; } __END__ ``` Interestingly: ``` TimeThis : Command Line : t.pl TimeThis : Elapsed Time : 00:00:01.281 ```
**Ruby:** * [Working with multiple processes in Ruby](https://stackoverflow.com/questions/710785/working-with-multiple-processes-in-ruby) * [Concurrency is a Myth in Ruby](http://www.igvita.com/2008/11/13/concurrency-is-a-myth-in-ruby/) **Perl:** * [Harnessing the power of multicore](http://computationalbiologynews.blogspot.com/2008/07/harnessing-power-of-multicore.html) * [Why Perl Is a Great Language for Concurrent Programming](http://t-a-w.blogspot.com/2006/10/why-perl-is-great-language-for.html) Also, Perl's threads are native operating system threads, so you can just use those to take advantage of multiple cores.
Please introduce a multi-processing library in Perl or Ruby
[ "", "python", "ruby", "perl", "" ]
Say I have the following: ``` namespace SomeProject { public interface ISomething { string SomeMethod(); } } namespace SomeService { [DataContract] public class CompositeType { [DataMember] public ISomething Something { get; set; } } } ``` Now, in my calling code I want to be able to do this: ``` SomeService service = new SomeService(); service.Something.SomeMethod(); ``` `SomeMethod()` is not available unless I return the DataMember as the implementation rather than the interface. Is there a way to do this?
This is not how you want to use your WCF service. WCF is about transferring data, not implementation. You are confusing your client and your service layers by doing this. However, **if you really want to do this**, you can tell the proxy generator in the client to re-use any existing types... this means that you can 1. reference the "SomeProject" dll in your client 2. add the service reference 3. choose "Advanced" 4. Select "Reuse types in referenced assemblies" 5. Choose where you want to get the types from **Again, I do not recommend doing it this way.**
Your WCF "DataContract" is exactly that - a data contract. On your client side you have a proxy object that implements all of the data members, but none of the methods. You'd have to have the original class/interface definitions and reconstruct the full object on the client side in order to do something like this.
reference methods from interface through a WCF service
[ "", "c#", "wcf", "" ]
I've started working on integrated Facebook Connect with my app. I have a slight lack of knowledge problem though. I can perfectly make it so you log into Facebook Connect on my site, etc, shows your details all FB Connect functions work. But, how do I make it so I can store the facebook user ID into my MySQL database as part of the current users information? So how I can auto log them into Facebook Connect if they have granted access? Thanks!
Using the PHP Facebook client library, you should be able to add something this at the top of "the page": ``` $api_key = "YOUR APP API KEY"; $api_secret = "YOUR API SECRET KEY"; $facebook = new Facebook($api_key, $api_secret); $facebook_id = $facebook->get_loggedin_user(); ``` If the user is logged in, $facebook\_id will be set to their facebook id (BIGINT). If not, it'll be null. Mind that users need to have third-party cookies enabled in their browser for this to work past the intial "connect" call. In that case you can use the API to get the logged in user: ``` $facebook->api_client->users_getLoggedInUser(); ``` So basically (pseudo): ``` if (!is_null($facebook_id)) { // authenticate user on your site with local cookie or session // pull user data from users table by "$facebook_id" // if user isn't in the database, create a new row with their facebook id } else { // show the connect button? } ```
You have to create new users into your site during the facebook login process, so you can use the data saved next times. You have to modify your user table and add some fields for new data (such as the facebook id). I wrote a tutorial about it wiht PHP and MySql: > <http://www.barattalo.it/facebook-connect-tutorial/>
Linking Facebook Connect
[ "", "php", "mysql", "facebook", "" ]
I want code to run whenever I create a new object. For example, see this: ``` <?php class Test { echo 'Hello, World!'; } $test = new Test; ?> ``` I want it to echo "Hello, World!" whenever I create a new instance of this object, without calling a function afterward. Is this possible?
You should read about [constructor](http://www.php.net/manual/en/language.oop5.decon.php) ``` <?php class MyClass { public function __construct() { echo "This code is executed when class in instanciated."; } } ?> ```
``` class Test { function __construct(){ echo 'Hello, World!'; } } ```
Run code on creation of a PHP class instance?
[ "", "php", "class", "object", "" ]
I have people posting their website address but variations are posted such as: * theirsite.com * www.theirsite.com * <http://theirsite.com> * <http://www.theirsite.com> When I link to an address without http:// it takes the link as internal ``` <a href="theirsite.com">their site</a> ``` sending people to something like: <http://mysite.com/thiersite.com> Another option I've tried is linking to something like mysite.com/?link=theirsite.com - This way I can do some link tracking etc then redirect people to the link but it has the same problem: ``` //do some tracking etc here $link =$_GET['link']; header("Location: $link"); ```
No need to use regular expressions here. PHP has URL validation built in. [Filter Var](http://uk.php.net/manual/en/function.filter-var.php) ``` var_dump((bool) filter_var('http://www.website.com', FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)); var_dump((bool) filter_var('http://website.com', FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)); var_dump((bool) filter_var('www.website.com', FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)); var_dump((bool) filter_var('website.com', FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)); ``` Output ``` bool(true) bool(true) bool(false) bool(false) ``` Please do not jump straight to regular expressions for validation, PHP has a lot of methods built in to deal with these scenarios. -Mathew
put "http://" in the field by default, then validate the URL with something like ``` if(eregi("^((http|https)://)?([[:alnum:]-])+(\.)([[:alnum:]]){2,4}([[:alnum:]/+=%&_.~?-]*)$", stripslashes(trim($_POST['link'])))){ //link is valid } ``` if link does not validate, just print them a message saying "the link you entered is invalid, make sure it starts with 'http://'"
Making sure http appears in a web address
[ "", "php", "http", "hyperlink", "href", "" ]
On a django site, I want to generate an excel file based on some data in the database. I'm thinking of using [xlwt](http://pypi.python.org/pypi/xlwt), but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library? I've also found this [snippet](http://www.djangosnippets.org/snippets/1151/) but it doesn't do what I need. All I want is a way to get the stream from the xlwt object to the response object (without writing to a temporary file)
neat package! i didn't know about this According to the doc, the `save(filename_or_stream)` method takes either a filename to save on, or a file-like stream to write on. And a Django response object happens to be a file-like stream! so just do `xls.save(response)`. Look the Django docs about [generating PDFs](http://docs.djangoproject.com/en/dev/howto/outputting-pdf/#complex-pdfs) with ReportLab to see a similar situation. **edit:** (adapted from ShawnMilo's comment): ``` def xls_to_response(xls, fname): response = HttpResponse(mimetype="application/ms-excel") response['Content-Disposition'] = 'attachment; filename=%s' % fname xls.save(response) return response ``` then, from your view function, just create the `xls` object and finish with ``` return xls_to_response(xls,'foo.xls') ```
\*\*\*UPDATE: django-excel-templates no longer being maintained, instead try Marmir <http://brianray.github.com/mm/> Still in development as I type this but <http://code.google.com/p/django-excel-templates/> Django excel templates project aims to do what your asking. Specifically look at the tests. Here is a simple case: ``` # from django_excel_templates import * from django_excel_templates.color_converter import * from models import * from django.http import HttpResponse def xls_simple(request): ## Simple ## testobj = Book.objects.all() formatter = ExcelFormatter() simpleStyle = ExcelStyle(vert=2,wrap=1) formatter.addBodyStyle(simpleStyle) formatter.setWidth('name,category,publish_date,bought_on',3000) formatter.setWidth('price',600) formatter.setWidth('ebook',1200) formatter.setWidth('about',20000) simple_report = ExcelReport() simple_report.addSheet("TestSimple") filter = ExcelFilter(order='name,category,publish_date,about,bought_on,price,ebook') simple_report.addQuerySet(testobj,REPORT_HORZ,formatter, filter) response = HttpResponse(simple_report.writeReport(),mimetype='application/ms-excel') response['Content-Disposition'] = 'attachment; filename=simple_test.xls' return response ```
django excel xlwt
[ "", "python", "django", "excel", "xlwt", "" ]
I have a string like this: ``` String A: [ 12234_1_Hello'World_34433_22acb_4554344_accCC44 ] ``` I would like to encrypt String A to be used in a clean URL. something like this: ``` String B: [ cYdfkeYss4543423sdfHsaaZ ] ``` Is there a encode API in python, given String A, it returns String B? Is there a decode API in python, given String B, it returns String A?
One way of doing the encode/decode is to use the package base64, for an example: ``` import base64 import sys encoded = base64.b64encode(sys.stdin.read()) print encoded decoded = base64.b64decode(encoded) print decoded ``` Is it what you were looking for? With your particular case you get: input: 12234\_1\_Hello'World\_34433\_22acb\_4554344\_accCC44 encoded: MTIyMzRfMV9IZWxsbydXb3JsZF8zNDQzM18yMmFjYl80NTU0MzQ0X2FjY0NDNDQ= decoded: 12234\_1\_Hello'World\_34433\_22acb\_4554344\_accCC44
note that theres a huge difference between encoding and encryption. if you want to send sensitive data, then dont use the encoding mentioned above ;)
How does one encode and decode a string with Python for use in a URL?
[ "", "python", "string", "hash", "urlencode", "clean-urls", "" ]
I looked through some code and noticed that the convention was to turn pointer types like ``` SomeStruct* ``` into ``` typedef SomeStruct* pSomeStruct; ``` Is there any merit to this?
This can be appropriate when the pointer itself can be regarded as a "black box", that is, a piece of data whose internal representation should be irrelevant to the code. Essentially, if your code will *never* dereference the pointer, and you just pass it around API functions (sometimes by reference), then not only does the typedef reduce the number of `*`s in your code, but also suggests to the programmer that the pointer shouldn't really be meddled with. This also makes it easier to change the API in the future if the need arises. For instance, if you change to using an ID rather than a pointer (or vice versa) existing code won't break because the pointer was never supposed to be dereferenced in the first place.
Not in my experience. Hiding the '`*`' makes the code hard to read.
Is it a good idea to typedef pointers?
[ "", "c++", "c", "pointers", "typedef", "conventions", "" ]
We've got a C++ Project that currently uses Make on Linux to build. I'd like to automate it similar to a Java Project under CruiseControl. 1) Is there a project similar to CruiseControl for C++ projects? OR 2) Is there a good "how-to" on using CruiseControl for C++ Projects?
I've been looking at setting up CruiseControl for C++ projects on Linux but came across [Hudson](http://hudson-ci.org/). It has a one file/one command line setup and you're up and running. The management access is via nice web interface. I highly recommend it. Hudson compared to CC seems easier to setup and manage plus you have access to build statics, errors/warnings via plugins (drop in directory and they are available) and you can set it up to automatically email when build fails. I've created shell script that invokes make for each project directory. I pointed Hudson to run that scrip. The build is setup via cron like settings - setup via web interface. I have it checking every 30 minutes for code changes and getting build from perforce and recompiling. If you're not sure give it a try. It takes only couple of minutes to get up and running. I've downloaded it because I wanted to see what is possible with our current build setup and I've never looked back, it's been running for nearly a year without any problems.
I don't know CruiseControl since we're using TeamCity, but CruiseControl should be able to perform a command line build, i.e. just call Make. There's nothing wrong with that. In TeamCity, it's even easy to add progress notifications to the make file (just output in a specific format), so it doesn't feel very different from "native" projects. I don't know how far CruiseControl goes in this regard. We have a large C++ project, built with CMake, running on command line and it even reports the unit test results (with Boost::Test) correctly. Oh, and if CruiseControl does not support a command line runner or project types other than Java, you should have a look at [TeamCity](http://www.jetbrains.com/teamcity) as a replacement.
"CruiseControl" Automation for C++ projects?
[ "", "c++", "automation", "continuous-integration", "hudson", "cruisecontrol", "" ]
After highlighting text, I would like to obtain the paragraph in which the selected text resides. ``` var select = window._content.document.getSelection(); ``` Any pointers please?
This is actually rather hard to do because you have to consider six cases: 1. The selection is not within a paragraph (easy); 2. The entire selection is within one paragraph (easy); 3. The entire selection crosses one or more sibling paragraphs (harder); 4. The selection starts or ends in an element not within a paragraph (harder); 5. The paragraphs spanned are at different levels eg one is within a list item while two others are siblings of the list (even harder); and 6. Some combination of the above. So firstly you have to decide how complete you want the solution to be. I'll only cover the simplest cases of (1) and (2). ``` function getSelectedParagraphText() { if (window.getSelection) { selection = window.getSelection(); } else if (document.selection) { selection = document.selection.createRange(); } var parent = selection.anchorNode; while (parent != null && parent.localName != "P") { parent = parent.parentNode; } if (parent == null) { return ""; } else { return parent.innerText || parent.textContent; } } ``` **Note:** If you're after tags too replace textContent with innerHTML. **Edit:** Better version put in, including better browser compatibility.
I found this useful [example](http://www.codetoad.com/javascript_get_selected_text.asp). It seems that some browsers support window.getSelection() while others support document.getSelection(). The example handle all these cases.
javascript to get paragraph of selected text in web page
[ "", "javascript", "window", "document", "html", "paragraph", "" ]
Code ``` static void MyClass::ThreadEntryStatic() { //... } void MyClass::Begin() { CreateThread(..,ThreadEntryStatic,..); } ``` In which condition we should use the static in class ?
There are three places that the keyword static can be used. One is in the declaration of a struct/class when that context means that the method is a class method instead of an instance method. This means that this method is called directly and you don't need an instance. From this static method, you can not access instance variables. In MyClass.h ``` struct MyClass { static void ThreadEntryStatic(); void Begin(); }; ``` In MyClass.cpp ``` void MyClass::ThreadEntryStatic() { } void MyClass::Begin() { CreateThread(.., MyClass::ThreadEntryStatic, ...); } ``` A second case where the static keyword is use is in the scope of a file where you don't want the visibility of the variable declared to be visible outside the file. You can also use an anonymous namespace for this as well. A third case where the static keyword is used is in the scope of a method and the value is retained between executions of the function (and initialized with the assignment the first time).
If you are running static methods on multiple threads you need to be paying very close attention to synchronizing your code. In my opinion, when doing multithreaded programming, I try to use a separate instance of my object or work item per thread, and avoid any type of static or shared data at all. Of course this is not always possible, so threading remains one of the trickiest programming areas to deal with.
When to use the keyword "static" in C++class?
[ "", "c++", "multithreading", "static", "" ]
There are many conflicting statements around. What is the best way to get the row count using PDO in PHP? Before using PDO, I just simply used `mysql_num_rows`. `fetchAll` is something I won't want because I may sometimes be dealing with large datasets, so not good for my use. Do you have any suggestions?
When you need only the number of rows, but not the data itself, such a function shouldn't be used anyway. Instead, ask the database to do the count, with a code like this: ``` $sql = "SELECT count(*) FROM `table` WHERE foo = ?"; $result = $con->prepare($sql); $result->execute([$bar]); $number_of_rows = $result->fetchColumn(); ``` For getting the number of rows along with the data retrieved, PDO has `PDOStatement::rowCount()`, which apparently **does** work in MySql with [buffered queries](https://www.php.net/manual/en/mysqlinfo.concepts.buffering.php) (enabled by default). But it's not guaranteed for other drivers. From the PDO Doc: > For most databases, > PDOStatement::rowCount() does not > return the number of rows affected by > a SELECT statement. Instead, use > PDO::query() to issue a SELECT > COUNT(\*) statement with the same > predicates as your intended SELECT > statement, then use > PDOStatement::fetchColumn() to > retrieve the number of rows that will > be returned. Your application can then > perform the correct action. But in this case you can use the data itself. Assuming you are selecting a reasonable amount of data, it can be fetched into array using PDO::fetchAll(), and then count() will give you the number of rows. EDIT: The above code example uses a prepared statement, but if a query doesn't use any variables, one can use query() function instead: ``` $nRows = $pdo->query('select count(*) from blah')->fetchColumn(); echo $nRows; ```
As I wrote previously in [an answer to a similar question](https://stackoverflow.com/questions/769767/pdos-rowcount-not-working-on-php-5-2-6/770045#770045), the only reason `mysql_num_rows()` worked is because it was internally fetching all the rows to give you that information, even if it didn't seem like it to you. So this behavior is replicated in `pdo_mysql` driver as well (for the buffered queries that are used by default). Which means that with MySQL you can use `PDO::rowCount()` the same way as `mysql_num_rows()` (i.e. almost never, as this function is really useless). For the other drivers, that don't support returning the number of rows found but the SELECT query (or with MySQL but when unbuffered query is used), your options are: 1. Use PDO's [`fetchAll()`](http://php.net/manual/en/pdostatement.fetchall.php) function to fetch all the rows into an array, then use `count()` on it. 2. Do an extra query to `SELECT COUNT(*)`, as karim79 suggested. 3. Use MySQL's [`FOUND_ROWS()`](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_found-rows) function **UNLESS** the query had `SQL_CALC_FOUND_ROWS` or a `LIMIT` clause (in which case the number of rows that were returned by the query and the number returned by `FOUND_ROWS()` may differ). However, this function is deprecated and will be removed in the future.
Row count with PDO
[ "", "php", "mysql", "pdo", "" ]
For example, if let's say I have a database of users. I have a class that gets information form the database about these users. I want to make the class "self aware" of it's own name, like this: ``` <?php class UserData { //[code that fetches the ID number from the variable name, and queries the database for info] } $user24 = new UserData; echo 'Welcome, '.$user24->name.'!'; ?> ``` This code would, ideally, output something like "Welcome, Bob!", and would change depending on what I named it. Is this possible?
Even if it's possible (I don't think so), you shouldn't. Others would just see a lot of magic and it would be hard to debug. Stick to the standards and known ideas / patterns whenever possible. Why don't you want to use: ``` $user = new UserData(24); ``` Or even better (because you shouldn't do any blocking operations in the constructor): ``` $user = UserData::getById(24); ```
Since a given object may have multiple names, this is not a generally valid technique in modern programming languages. For example, assuming user 25 has a different name from user 24, what would you expect the following code to print? ``` $user24 = new UserData; echo 'Welcome, '.$user24->name.'!'; $user25 = $user24; echo 'Welcome, '.$user25->name.'!'; ``` Not only that, but you can have objects with no name: ``` echo 'Welcome, '.(new UserData)->name.'!'; ``` A more typical implementation would have the object constructor take a parameter which tells it which user you're dealing with, like this: ``` $user = new UserData(24); echo 'Welcome, '.$user->name.'!'; ```
Make PHP Object do different actions depending on variable name
[ "", "php", "class", "" ]
Say I have a class definition: ``` class CustomClass { int member; }; ``` Why is the following variable definition compiling and working correctly: ``` CustomClass CustomClass; // the variable is properly constructed ``` Should't this confuse the compiler and cause it to indicate an error?
Class names and variable names occupy two separate namespaces. The compiler is able to figure out that the first `CustomClass` is a type and the second `CustomClass` is a variable name.
The requested doubt is not necessarily about the case sensitive mode of C++ , it's the variable declaration that has the same name as the class defined above. I'm thinking that your c++ compiler is smart enough to deduce the type of the token that it's parsing ..
Why is ClassName ClassName variable definition in C++ compiling and working properly?
[ "", "c++", "compiler-construction", "definition", "" ]
I have a list of floating-point values in Python: ``` floats = [3.14, 2.7, 0.0, -1.0, 1.1] ``` I would like to write these values out to a binary file using IEEE 32-bit encoding. What is the best way to do this in Python? My list actually contains about 200 MB of data, so something "not too slow" would be best. Since there are 5 values, I just want a 20-byte file as output.
Alex is absolutely right, it's more efficient to do it this way: ``` from array import array output_file = open('file', 'wb') float_array = array('d', [3.14, 2.7, 0.0, -1.0, 1.1]) float_array.tofile(output_file) output_file.close() ``` And then read the array like that: ``` input_file = open('file', 'rb') float_array = array('d') float_array.fromstring(input_file.read()) ``` `array.array` objects also have a `.fromfile` method which can be used for reading the file, if you know the count of items in advance (e.g. from the file size, or some other mechanism)
See: [Python's struct module](http://docs.python.org/library/struct.html) ``` import struct s = struct.pack('f'*len(floats), *floats) f = open('file','wb') f.write(s) f.close() ```
How to output list of floats to a binary file in Python
[ "", "python", "file-io", "" ]
I want to make it as easy as possible for our designers to localise strings in views, which means that I want to do this: ``` ... <p><?php echo $this->_("Hello, world!"); ?></p> ... ``` The underscore notation here is necessary to allow Poedit to automagically extract all strings for localisation. The implementation is trivial: ``` public function _($string) { return Zend_Registry::get('Zend_Translate')->_($string); } ``` At the moment, I've put this directly in `Zend_View_Abstract`, which is bad (I don't want to do this by modifying any of the Zend library). Ideally, then, I'd extend `Zend_View_Abstract` to allow me to implement other concrete functions that we require, but I don't know how to set this up. An alternative might be to implement a View Helper, but the only way that I know how to do this makes the code in the view more verbose. Any pointers (no, not those kind) would be much appreciated. Thanks!
Obviously ignore my paths for your own... 1. Extend `Zend_View` 2. Put your method in this extended class 3. Instantiate the class (in your bootstrap for instance) 4. Assign it to the ViewRenderer 5. Pass that viewrenderer to `Zend_Controller_Action_HelperBroker's` addHelper method 6. Use it in your view In /library/MegaHAL/Zend/ create View.php: ``` class MegaHAL_Zend_View extends Zend_View { public function _($string) { return Zend_Registry::get('translate')->_($string); } } ``` In your bootstrap: ``` require_once APPLICATION_PATH.'../library/MegaHAL/Zend/View.php'; $view = new MegaHAL_Zend_View(); $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer(); $viewRenderer->setView($view); Zend_Controller_Action_HelperBroker::addHelper($viewRenderer); ``` In your view: ``` <p><?php echo $this->_("Hello");?></p> ``` I believe that will do what you want, yes?
I think that you're looking for a way to create [custom view helpers](http://framework.zend.com/manual/en/zend.view.helpers.html#zend.view.helpers.custom). Example: ``` class My_View_Helper extends Zend_View_Helper_Abstract { public function translate($string) { //... } } ``` ... ``` $view->setHelperPath('/path/to/helpers', 'My_View_Helper'); ``` ... Then in your views you can use it: ``` echo $this->translate("Hello, World!"); ```
How do I Extend Zend View to Implement a Concrete Function?
[ "", "php", "zend-framework", "localization", "" ]
I have a weird requirement where I need to take some xml and re-write it so that the text nodes are wrapped in CDATA (this is for a client that won't allow normal escaping). It doesn't seem like any of the normal XML libraries dom4j, jdom, java xml, have any built in support for this. Any ideas? Can I use XSLT for this? I wasn't very clear. Here is what I'll start with: ``` <foo>This has an &amp; escaped value</foo> ``` What I need to do is convert this to: ``` <foo><![CDATA[This has an & escaped value]]></foo> ``` -Dave
You can use XSLT to accomplish this, as long as a) all of the text you need to output is in elements, b) you only care about text nodes, c) you know the names of all the elements that contain text, and d) it's okay to emit any text in all of those output elements as CDATA. If all of those cases are true, then you could write an identity transform and add this element to it: ``` <xsl:output method="xml" cdata-section-elements="elm1 elm2 elm3..."/> ``` See [the W3C XSLT recommendation](http://www.w3.org/TR/xslt#section-XML-Output-Method) on this subject.
Thanks for all of your answers. I found a way to do this using dom4j. My implementation does not work if elements have "mixed" children (i.e. text element), but in my case this isn't a problem. It works because dom4j will output CDATA if you add CDATA nodes: ``` public void replaceTextWithCdataNoMixedText(Document doc) { if( doc == null ) return; replaceTextWithCdata(doc.content()); } private void replaceTextWithCdata(List content) { if (content == null) return; for (Object o : content) { if (o instanceof Element) { Element e = (Element) o; String t = e.getTextTrim(); if (textNeedsEscaping(t)) { e.clearContent(); e.addCDATA(t); } else { List childContent = e.content(); replaceTextWithCdata(childContent); } } } } private boolean textNeedsEscaping(String t) { if (t == null) return false; for (int i = 0; i < t.length(); i++) { char c = t.charAt(i); if (c == '<' || c == '>' || c == '&') { return true; } } return false; } ```
Best way to convert xml to have CDATA around text (in java)
[ "", "java", "xml", "" ]
Is there any advantage of using int vs varbinary for storing bit masks in terms of performance or flexibility. For my purposes, I will always be doing reads on these bit masks (no writes or updates).
You should definitely use an `INT` (if you need 32 flags) or `BIGINT` (for 64 flags). If you need more flags you could use [`BINARY`](http://technet.microsoft.com/en-us/library/ms188362.aspx) (but you should probably also ask yourself why you need so many flags in your application). Besides, if you use an integral type, you can use standard [bitwise operators](http://msdn.microsoft.com/en-us/library/ms176122.aspx) directly without converting a byte array to an integral type. If you do need more flags and have to use `BINARY` you lose native support for bitwise operators and therefore easy support for checking flag values. I would probably move checking for flag values to a client application but if you're comfortable programming in T-SQL that's an option as well. If you're using C# you have a [`BitArray`](http://msdn.microsoft.com/en-us/library/system.collections.bitarray.aspx) class with the necessary operations and in Java you have a [`BitSet`](http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html) class.
It is generally considered preferable to use a bunch of bit columns instead of a bit mask. They will get packed together in the page, so they won't take any more room. Although I too always seem to go with an int or bigint column to avoid all of the column name typing.. but with intellisense I would probably go with the bit columns.
SQL Server: varbinary or int to store a bit mask?
[ "", "sql", "sql-server", "database-design", "bitmask", "" ]
I've created a site for an artist friend of mine, and she wants the layout to stay the same, but she also wants new paintings she'd produced to be mixed into the current layout. So I have 12 thumbnails (thumb1 - thumb12) on the main gallery page and 18 images (img1 - img18) to place as well The approach I thought of was to create an array of all the images, randomize it, then simply scrape off the first 12 and load them into the thumb slots. Another approach would be to select 12 images randomly from the array. In the first case, I can't find a way to randomize the elements of an array. In the latter case, I can't wrap my brain around how to keep images from loading more than once, other than using a second array, which seems very inefficient and scary. I'm doing all of this in Javascript, by the way.
I wrote this a while ago and it so happens to fit what you're looking for. I believe it's the Fisher-Yates shuffle that ojblass refers to: ``` Array.prototype.shuffle = function() { var i = this.length; while (--i) { var j = Math.floor(Math.random() * (i + 1)) var temp = this[i]; this[i] = this[j]; this[j] = temp; } return this; // for convenience, in case we want a reference to the array }; ``` Note that modifying Array.prototype may be considered bad form. You might want to implement this as a standalone method that takes the array as an argument. Anyway, to finish it off: ``` var randomSubset = originalArray.shuffle().slice(0,13); ``` Or, if you don't want to actually modify the original: ``` var randomSubset = originalArray.slice(0).shuffle().slice(0,13); ```
You should implement the [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher-Yates_shuffle) (otherwise known as the Knuth shuffle). Look at the great answer provided [here](https://stackoverflow.com/questions/790083/does-qsort-demand-consistent-comparisons-or-can-i-use-it-for-shuffling/790097#790097).
Randomizing elements in an array?
[ "", "javascript", "algorithm", "arrays", "shuffle", "" ]
In one bit of code I'm working on, I need to pull a value from the database and check if it is `0`. Originally, I had written this as: ``` if ($myVal == 0) { ... ``` But when I looked at it again today, I realised a bug there: ``` var_dump("foo" == 0); // bool(true) // and while we're here... var_dump(intval("foo")); // int(0) ``` Since this value is coming from the database, that **usually** means it will be a string, so I suppose I could do this: ``` if ($myVal === "0") ``` but it seems counter-intuitive since I actually want to be dealing with an integer, and this would appear to show that we're working with strings. *(I hope that makes sense to you.)* Also, it shouldn't be unexpected that any given DB accessor would cast values to their appropriate type, given the field type. What method do you use to check for a value of 0 when it could be a string or an int?
Short version: ``` if ("$myVal" === '0') ``` or ``` if (strval($myVal) === '0') ``` Long version: ``` if ($myVal === 0 || $myVal === '0') ```
The best I've got currently is this: ``` is_numeric($myVal) && $myVal == 0 ```
How best to compare to 0 in PHP?
[ "", "php", "mysql", "comparison", "" ]
Some fancy websites show an error dialog when it is detected that an untrained shopper has entered a credit/debit card number as it is printed on their card with spaces. Is it possible in some way to write a Java web app that handles these numbers with spaces as if they were correct?
My view is that any Web app that rejects a credit card number with spaces isn't doing its job. When you receive a credit card number, it's easy enough to do: ``` String ccNumber = ccNumber.replaceAll("[\\s-]+", ""); ``` to remove spaces and dashes (some use those too). Then validate the result. You'll simply annoy your users if you force them to remove spaces you could just as easily do. As for **how** to validate, well that depends on a lot of things, such as which Web framework you're using and what validation options you've chosen. Struts 1 for example might or might not use Apache Commons Validator whereas Spring MVC will (probably) use Spring validation and so on. So I can't tell you exactly how to validate but I can tell you **what** to validate. The first thing is that a CC number with spaces should **not** be rejected. Most people will find: ``` 4123 0987 8876 2939 ``` **much** easier to read than: ``` 4123098788762939 ``` which is really important if the user misses or mistypes a digit and needs to find why his or her credit card number failed validation. The replaceAll() at the top of this post covers this situation. The second thing is that you display the credit card number (even when some of the digits are replaced with X for security reasons) in the correct way. I suggest you read through [Anatomy of Credit Card Numbers](http://www.merriampark.com/anatomycc.htm). That page gives you the rules for the number of digits and the valid prefixes. A robust Web application will implement these **so you can tell if a credit card number is invalid before you try and use it**. It can take up to 30 seconds (or possibly more) to submit credit card details to a payment gateway so you shouldn't do it until you are sure as you can be that the payment will be accepted. To do otherwise is to provide a really bad user experience. There is every chance the user will give up if it fails 1-2 times rather than wait. As for displaying them, that depends on the # of digits: * 16: 4 groups of 4 separated by a space; * 15: like an [American Express](http://globaldais.com/wp-images/American-Express-Titanium-Black-Card.jpg) card ie 4-6-5 with a space between each group; * 14: like a [Diners Club](http://www.asa.org.au/pageBANK/images/diners_person_cob_asa_e.jpg) card ie 4-6-4 with a space between each group; * 13: Never seen 13 but 4-5-4 or 4-4-5 or 5-4-4 (or possibly 3-3-3-4) springs to mind. The credit card number should be verified according to the checksum algorithm mentioned in the page *before submitting for processing* as part of a standard validation routine. That page has a Java implementation of that routine. **Every** website that accepts credit card payment should be doing all of the above as an **absolute minimum** or you're simply throwing away business as a percentage of your users get frustrated. So the short version is two simple rules: 1. Be as forgiving as possible with user input; and 2. Do absolutely everything possible to validate credit card details prior to submission.
I would go as far as stripping out all non-numeric characters then checking that the length is valid before running the user input through real validation like [Luhn's algorithm](http://en.wikipedia.org/wiki/Luhn_algorithm). ``` String ccNumber = input.replaceAll("\\D", ""); ``` strips out all the non-digits from `String input`.
How can I use credit card numbers containing spaces?
[ "", "java", "string", "usability", "" ]
i'd like to write a wrapper for a C++ framework. this framework is kinda buggy and not really nice and in C++. so i'd like to be able to call their methods from outside (via good old C file) of their framework by using just one shared lib. this sounds like the need for a wrapper that encapsulates the wanted framework methods for usage with C instead of C++. So far so good.... here is what i already did: **interface aldebaran.h** (this is in my include folder, the ultrasound methods should be called from outside of the framework): ``` #ifndef _ALDEBARAN_H #define _ALDEBARAN_H #ifdef __cplusplus extern "C" { #endif void subscribe_ultrasound(); void unsubscribe_ultrasound(); float read_ultrasound(); #ifdef __cplusplus } #endif #endif ``` now the wrapper: **cpp file aldebaran.cpp:** ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include "aldebaran.h" #include "alproxy.h" #include "../../include/aldebaran.h" /* * Ultrasound defines */ #define ULTRASOUND_RESERVATION_MAGIC "magic_foobar" #define ULTRASOUND_POLL_TIME 250 #define ULTRASOUND_READ_ATTEMPTS 50 #define ULTRASOUND_SLEEP_TIME 20 using namespace std; using namespace AL; /* * Framework proxies */ ALPtr<ALProxy> al_tts; ALPtr<ALProxy> al_led; ALPtr<ALProxy> al_motion; ALPtr<ALProxy> al_mem; ALPtr<ALProxy> al_us; ALPtr<ALProxy> al_cam; ALPtr<ALProxy> al_dcm; /* * Constructor */ Aldebaran::Aldebaran(ALPtr<ALBroker> pBroker, std::string pName): ALModule(pBroker, pName) { try { al_tts = this->getParentBroker()->getProxy("ALTextToSpeech"); al_led = this->getParentBroker()->getProxy("ALLeds"); al_motion = this->getParentBroker()->getProxy("ALMotion"); al_mem = this->getParentBroker()->getProxy("ALMemory"); al_us = this->getParentBroker()->getProxy("ALUltraSound"); al_cam = this->getParentBroker()->getProxy("NaoCam"); al_dcm = this->getParentBroker()->getProxy("DCM"); }catch(ALError& err){ std::cout << "XXX: ERROR: " << err.toString() << std::endl; return 1; } printf("XXX: module aldebaran initiated\n"); fflush(0); } /* * Destructor */ Aldebaran::~Aldebaran() { printf("XXX: module aldebaran destructed\n"); fflush(0); } /* * Subscribe to ultrasound module */ void subscribe_ultrasound() { ALValue param; param.arrayPush(ULTRASOUND_POLL_TIME); al_us->callVoid("subscribe", string(ULTRASOUND_RESERVATION_MAGIC), param); printf("XXX: ultrasound subscribed: %s\n", ULTRASOUND_RESERVATION_MAGIC); fflush(0); } /* * Unsubscribe to ultrasound module */ void unsubscribe_ultrasound() { al_us->callVoid("unsubscribe", string(ULTRASOUND_RESERVATION_MAGIC)); printf("XXX: ultrasound unsubscribed: %s\n", ULTRASOUND_RESERVATION_MAGIC); fflush(0); } /* * Read from ultrasound module */ float read_ultrasound() { int i; float val1, val2; float val_sum; ALValue distance; val_sum = .0f; for(i = 0; i < ULTRASOUND_READ_ATTEMPTS; ++i){ SleepMs(ULTRASOUND_SLEEP_TIME); distance = al_mem->call<ALValue>("getData", string("extractors/alultrasound/distances")); sscanf(distance.toString(AL::VerbosityMini).c_str(),"[%f, %f, \"object\"]", &val1, &val2); val_sum += val1; } return val_sum / (1.f * ULTRASOUND_READ_ATTEMPTS); } ``` **definition file for aldebaran.cpp:** ``` #ifndef ALDEBARAN_API_H #define ALDEBARAN_API_H #include <string> #include "al_starter.h" #include "alptr.h" using namespace AL; class Aldebaran : public AL::ALModule { public: Aldebaran(ALPtr<ALBroker> pBroker, std::string pName); virtual ~Aldebaran(); std::string version(){ return ALTOOLS_VERSION( ALDEBARAN ); }; bool innerTest(){ return true; }; }; #endif ``` So this should be a simple example for my wrapper and it compiles fine to libaldebaran.so. **now my test program in C:** ... now i'd like to call the interface aldebaran.h methods from a simple c file like this: ``` #include <stdio.h> /* * Begin your includes here... */ #include "../include/aldebaran.h" /* * End your includes here... */ #define TEST_OKAY 1 #define TEST_FAILED 0 #define TEST_NAME "test_libaldebaran" unsigned int count_all = 0; unsigned int count_ok = 0; const char *__test_print(int x) { count_all++; if(x == 1){ count_ok++; return "ok"; } return "failed"; } /* * Begin tests here... */ int test_subscribe_ultrasound() { subscribe_ultrasound(); return TEST_OKAY; } int test_unsubscribe_ultrasound() { unsubscribe_ultrasound(); return TEST_OKAY; } int test_read_ultrasound() { float i; i = read_ultrasound(); return (i > .0f ? TEST_OKAY : TEST_FAILED); } /* * Execute tests here... */ int main(int argc, char **argv) { printf("running test: %s\n\n", TEST_NAME); printf("test_subscribe_ultrasound: \t %s\n", __test_print(test_subscribe_ultrasound())); printf("test_read_ultrasound: \t %s\n", __test_print(test_read_ultrasound())); printf("test_unsubscribe_ultrasound: \t %s\n", __test_print(test_unsubscribe_ultrasound())); printf("test finished: %s has %u / %u tests passed\n\n", TEST_NAME, count_ok, count_all); return (count_all - count_ok); } ``` how can i manage to call these methods? i mean within my C file i have no possibility to create such an object-instance (that generated all the needed ALProxies), have i? help would be really appreciated... thx --- thank you very much so far!! as xtofl said.. i'd like to keep my interface as simple as possible (without another c++ object preferably): ``` #ifndef _ALDEBARAN_H #define _ALDEBARAN_H #ifdef __cplusplus extern "C" { #endif void subscribe_ultrasound(); void unsubscribe_ultrasound(); float read_ultrasound(); #ifdef __cplusplus } #endif #endif ``` the problem hereby is that functions like *subscribe\_ultrasound()* cannot be called without the instanciation of all the proxies... this is our precondition: ``` ... al_tts = this->getParentBroker()->getProxy("ALTextToSpeech"); al_led = this->getParentBroker()->getProxy("ALLeds"); al_motion = this->getParentBroker()->getProxy("ALMotion"); al_mem = this->getParentBroker()->getProxy("ALMemory"); al_us = this->getParentBroker()->getProxy("ALUltraSound"); al_cam = this->getParentBroker()->getProxy("NaoCam"); al_dcm = this->getParentBroker()->getProxy("DCM"); ... ``` if i don't have the code above called, all other will fail. within their framework it is possible to "autoload" my libaldebaran.so via a python script like this call: ``` myModule = ALProxy("Aldebaran", global_params.strRemoteIP, global_params.nRemotePort ); ``` The framework log then says: ``` May 10 15:02:44 Hunter user.notice root: XXX: module aldebaran initiated May 10 15:02:46 Hunter user.notice root: INFO: Registering module : 'Aldebaran' May 10 15:02:46 Hunter user.notice root: ______ End of loading libraries ______ ``` which is totally okay... it called the constructor of my module (so all other needed proxies got instanciated too). but of course this instance does not belong to my C program... maybe there is a possibility to share this to all other processes?
You said yourself to create a C wrapper API around an OO framework. This means you don't need any objects passing the wrapper API (as it appears from the decribed header). It seems all objects needed are created/destructed behind the wrapper API, out of view of your test program. The first seems the case. You don't need objects to test your wrapper API. In the end, all objects are bytes (in memory) that are accessed through a fixed set of functions. It doesn't matter much whether the functions are written as member-functions (C++) or as plain C functions, as long as they obey the intended semantics of your objects.
You might want to take a slightly different approach. Consider something like this for your C interface: ``` #ifdef __cplusplus extern "C" { #endif struct UltrasoundHandle; UltrasoundHandle* ultrasound_Create(); void ultrasound_Destroy(UltrasoundHandle *self): void ultrasound_Subscribe(UltrasoundHandle *self); void ultrasound_Unsubscribe(UltrasoundHandle *self); float ultrasound_Read(UltrasoundHandle *self); #ifdef __cplusplus } #endif ``` The `UltrasoundHandle` structure is purposefully opaque so that you can define it in the implementation to be whatever you want it to be. The other modification that I made was to add explicit creation and destruction methods akin to the constructor and destructor. The implementation would look something like: ``` extern "C" { struct UltrasoundHandle { UltrasoundHandle() { // do per instance initializations here } ~UltrasoundHandle() { // do per instance cleanup here } void subscribe() { } void unsubscribe() { } float read() { } }; static int HandleCounter = 0; UltrasoundHandle* ultrasound_Create() { try { if (HandleCounter++ == 1) { // perform global initializations here } return new UltrasoundHandle; } catch (...) { // log error } return NULL; } void ultrasound_Destroy(UltrasoundHandle *self) { try { delete self; if (--HandleCounter == 0) { // perform global teardown here } } catch (...) { // log error } } ``` The key is to wrapping C++ interfaces for C is to expose the OO concepts through free functions where the caller explicitly passes the object pointer (`this`) to the function and to explicitly expose the constructor and destructor in the same manner. The wrapper code can be almost mechanically generated from there. The other key points are that you never let exceptions propagate outward and steer clear of global object instances. I'm not sure if the latter will cause you grief, but I would be concerned about construction/destruction ordering problems.
Calling a C++ Shared Lib within a C program...how to manage?
[ "", "c++", "c", "" ]
How to strip off HTML tags from a string using plain JavaScript only, not using a library?
If you're running in a browser, then the easiest way is just to [let the browser do it for you...](http://jsfiddle.net/8JSZX/) ``` function stripHtml(html) { let tmp = document.createElement("DIV"); tmp.innerHTML = html; return tmp.textContent || tmp.innerText || ""; } ``` Note: as folks have noted in the comments, this is best avoided if you don't control the source of the HTML (for example, don't run this on anything that could've come from user input). For those scenarios, you can *still* let the browser do the work for you - [see Saba's answer on using the now widely-available DOMParser](https://stackoverflow.com/questions/822452/strip-html-from-text-javascript/47140708#47140708).
``` myString.replace(/<[^>]*>?/gm, ''); ```
Strip HTML tags from text using plain JavaScript
[ "", "javascript", "html", "string", "" ]
I've been investigating this issue that only seems to get worse the more I dig deeper. I started innocently enough trying to use this expression to split a string on HTML 'br' tags: ``` T = captions.innerHTML.split(/<br.*?>/g); ``` This works in every browser (FF, Safari, Chrome), except IE7 and IE8 with example input text like this: ``` is invariably subjective. <br /> The less frequently used warnings (Probably/Possibly) <br /> ``` Please note that the example text contains a space before the '/', and precedes a new line. Both of the following will match all HTML tags in every browser: ``` T = captions.innerHTML.split(/<.*?>/g); T = captions.innerHTML.split(/<.+?>/g); ``` However, surprisingly (to me at least), this *does not* work in FF and Chrome: ``` T = captions.innerHTML.split(/<br.+?>/g); ``` Edit: This (suggested several times in the responses below,) does not work on IE 7 or 8: ``` T = captions.innerHTML.split(/<br[^>]*>/g); ``` (It did work on Chrome and FF.) My question is: does anyone know an expression that works in all current browsers to match the 'br' tags above (but not other HTML tags). And can anyone confirm that the last example above should be a valid match since two characters are present in the example text before the '>'. PS - my doctype is HTML transitional. Edit: I think I have evidence this is specific to the string.split() behavior on IE, and not regex in general. You have to use split() to see this issue. I have also found a test matrix that shows a failure rate of about 30% for split() test cases when I ran it on IE. The same tests passed 100% on FF and Chrome: <http://stevenlevithan.com/demo/split.cfm> So far, I have still not found a solution for IE, and the library provided by the author of that test matrix did not fix this case.
The reason your code is not working is because IE parses the HTML and makes the tags uppercase when you read it through innerHTML. For example, if you have HTML like this: ``` <div id='box'> Hello<br> World </div> ``` And then you use this Javascript (in IE): ``` alert(document.getElementById('box').innerHTML); ``` You will get an alert box with this: ``` Hello<BR>World ``` Notice the `<BR>` is now uppercase. To fix this, just add the `i` flag in addition to the `g` flag to make the regex be case-insensitive and it will work as you expect.
Try this one: ``` /<br[^>]*>/gi ```
regular expression in javascript string split, browser compatibility issue
[ "", "javascript", "regex", "cross-browser", "" ]
I'm using nested sets (aka modified preorder tree traversal) to store a list of groups, and I'm trying to find a quick way to generate breadcrumbs (as a string, not a table) for ALL of the groups at once. My data is also stored using the adjacency list model (there are triggers to keep the two in sync). So for example: ``` ID Name ParentId Left Right 0 Node A 0 1 12 1 Node B 0 2 5 2 Node C 1 3 4 3 Node D 0 6 11 4 Node E 3 7 8 5 Node F 4 9 9 ``` Which represents the tree: * Node A + Node B - Node C + Node D - Node E - Node F I would like to be able to have a user-defined function that returns a table: ``` ID Breadcrumb 0 Node A 1 Node A > Node B 2 Node A > Node B > Node C 3 Node A > Node D 4 Node A > Node D > Node E 5 Node A > Node D > Node F ``` --- To make this slightly more complicated (though it's sort of out of the scope of the question), I also have user restrictions that need to be respected. So for example, if I only have access to id=3, when I run the query I should get: ``` ID Breadcrumb 3 Node D 4 Node D > Node E 5 Node D > Node F ``` I do have a user-defined function that takes a userid as a parameter, and returns a table with the ids of all groups that are valid, so as long as somewhere in the query ``` WHERE group.id IN (SELECT id FROM dbo.getUserGroups(@userid)) ``` it will work. --- I have an existing scalar function that can do this, but it just does not work on any reasonable number of groups (takes >10 seconds on 2000 groups). It takes a groupid and userid as a parameter, and returns a nvarchar. It finds the given groups parents (1 query to grab the left/right values, another to find the parents), restricts the list to the groups the user has access to (using the same WHERE clause as above, so yet another query), and then uses a cursor to go through each group and append it to a string, before finally returning that value. I need a method to do this that will run quickly (eg. <= 1s), on the fly. This is on SQL Server 2005.
What I ended up doing is making a large join that simply ties this table to itself, over and over for every level. First I populate a table @topLevelGroups with just the 1st level groups (if you only have one root you can skip this step), and then @userGroups with the groups that user can see. ``` SELECT groupid, (level1 + CASE WHEN level2 IS NOT NULL THEN ' > ' + level2 ELSE '' END + CASE WHEN level3 IS NOT NULL THEN ' > ' + level3 ELSE '' END )as [breadcrumb] FROM ( SELECT g3.* ,g1.name as level1 ,g2.name as level2 ,g3.name as level3 FROM @topLevelGroups g1 INNER JOIN @userGroups g2 ON g2.parentid = g1.groupid and g2.groupid <> g1.groupid INNER JOIN @userGroups g3 ON g3.parentid = g2.groupid UNION SELECT g2.* ,g1.name as level1 ,g2.name as level2 ,NULL as level3 FROM @topLevelGroups g1 INNER JOIN @userGroups g2 ON g2.parentid = g1.groupid and g2.groupid <> g1.groupid UNION SELECT g1.* ,g1.name as level1 ,NULL as level2 ,NULL as level3 FROM @topLevelGroups g1 ) a ORDER BY [breadcrumb] ``` This is a pretty big hack, and is obviously limited to a certain number of levels (for my app, there is a reasonable limit I can pick), with the problem that the more levels are supported, it increases the number of joins exponentially, and thus is much slower. Doing it in code is most certainly easier, but for me that is simply not always an option - there are times when I need this available directly from a SQL query. --- I'm accepting this as the answer, since it's what I ended up doing and it may work for other people -- however, if someone can come up with a more efficient method I'll change it to them.
here's the SQL that worked for me to get the "breadcrumb" path from any point in the tree. Hope it helps. ``` SELECT ancestor.id, ancestor.title, ancestor.alias FROM `categories` child, `categories` ancestor WHERE child.lft >= ancestor.lft AND child.lft <= ancestor.rgt AND child.id = MY_CURRENT_ID ORDER BY ancestor.lft ``` Kath
Finding breadcrumbs for nested sets
[ "", "sql", "sql-server-2005", "breadcrumbs", "nested-sets", "mptt", "" ]
Is there a better solution to the problem of looking up multiple known IDs in a table: ``` SELECT * FROM some_table WHERE id='1001' OR id='2002' OR id='3003' OR ... ``` I can have several hundreds of known items. Ideas?
``` SELECT * FROM some_table WHERE ID IN ('1001', '1002', '1003') ``` and if your known IDs are coming from another table ``` SELECT * FROM some_table WHERE ID IN ( SELECT KnownID FROM some_other_table WHERE someCondition ) ```
The first (naive) option: ``` SELECT * FROM some_table WHERE id IN ('1001', '2002', '3003' ... ) ``` However, we should be able to do better. `IN` is very bad when you have a lot of items, and you mentioned hundreds of these ids. What creates them? Where do they come from? Can you write a query that returns this list? If so: ``` SELECT * FROM some_table INNER JOIN ( your query here) filter ON some_table.id=filter.id ```
Alternative SQL ways of looking up multiple items of known IDs?
[ "", "sql", "" ]
DOes anyone have any good information with regards to when to log, I was thinking of logging an INFO type when i enter each c# method and recording another info when exiting.. Is this considered good or bad? Will i see a performance hit? If i do record an INFO when i enter a method, the idea would be to record the method name, and all variable and values Any idea how this can be done automatically without entering each value and name of method, i suppose i could use reflection but maybe i would see a slow down here? If reflection would slow things down, maybe i could just use the "REFLECTION" bit when there program FAILS hence i can write the stacktrace, all vars, and values. Any ideas or examples on this really appreciated Thanks
You could use the AOP (Aspect oriented programming) style of logging for method-level logging. There is a good framework called [Log4PostSharp](http://code.google.com/p/postsharp-user-plugins/wiki/Log4PostSharp). It's a plugin to PostSharp which writes to Log4Net It basically boils down to decorating your method with an attribute like this: ``` [Log(LogLevel.Info, "Doing something")] public void CountCharacters() { // do your logic here } ```
I would use even lower level for this - TRACE (if it's available in log4net). DEBUG is good for logging particular occasions of something while TRACE is better used for dumping method calls, parameters and stuff like this. Definitely not INFO, which is more suitable for logging functional stuff on higher level.
log4net when to log?
[ "", "c#", "reflection", "logging", "log4net", "" ]
my friend and I are creating a log parser for a series of games. We have written the frontend (web) in PHP/MySQL and the parser in Perl (also using MySQL, of course). Now we are having problems getting these two to communicate. All we wan't to do is this: one administration page online where you have the button "parse". When you click this a Perl script should start. Like "exec("perl /home/www/Init.pm -f games\_mp.log"). Is this possible? Remember, it's suppose to be easy to set up. We've tried everything from system/exec to .htaccess, but nothing seems to work out of the box. Not working at all really. Suggestions? laka =)
I'm sorry to say there's no easy way to set this up. Different servers come with different default apache configs. What you're probably looking to do is add the following line inside the either the server config, virtual host config, directory config, or, if properly setup, .htaccess. `AddHandler cgi-script .cgi .pl .pm` Your users will also need to chmod and chown the files appropriately. Thing is, this sounds like a long running process. If it is, then it might take so long to run the web browser will time out before it is done. If that's the case, you'll likely want to setup some kind of job queue and have a cron script exec based off that every 5 min or so.
Why not run the Perl script as if they were a web page from jQuery using mod\_perl?
How can I call Perl from my PHP page on apache?
[ "", "php", "perl", "cgi", "" ]
I want to use the Django admin interface for a very simple web application but I can't get around a problem that should not be that hard to resolve .. Consider the following: ``` class Contact(models.Model): name = models.CharField(max_length=250, blank=False) created_by = models.ForeignKey(User, blank=False) ``` I can't find a way to auto-populate the created\_by field and make the Django admin aware of it. Most of the method I've seen implies overloading the Object's save method and pass it the request user. They all requires to build your custom views and/or forms. Optimally the form to create new contacts *in the admin site* should not show the created\_by field (which is quite easy) and auto-populate it with the current user (which seems harder than it should).
<http://code.djangoproject.com/wiki/CookBookNewformsAdminAndUser> Involves implementing save methods on your ModelAdmin objects.
You need to specify a [default](http://docs.djangoproject.com/en/dev/ref/models/fields/#default) for the field, in this case a method call that gets the current user (see the auth documentation to get the current user).
Auto-populating created_by field with Django admin site
[ "", "python", "django", "django-models", "django-admin", "" ]
Is there a way to disable changing the value of a ComboBox in WPF without giving it the visual properties of a disabled ComboBox? For example, I know that for a text field you can set the IsReadOnly property to true. Doing this for a ComboBox however, does not prevent the user from selecting a different value.
Mr. Benages, I think setting IsHitTestVisible and Focusable to false on the ComboBox might do the trick. Hope this helps.
While I agree that a disabled control should look disabled you could just set the ComboBox ControlTemplate to the standard one (or one your using) removing any of the standard functionality eg This will give you a decent looking readonly combobox ``` <ComboBox> <ComboBox.Template> <ControlTemplate TargetType="{x:Type ComboBox}"> <Grid> <Microsoft_Windows_Themes:ListBoxChrome x:Name="Border" Height="23" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" RenderFocused="{TemplateBinding IsKeyboardFocusWithin}" RenderMouseOver="{TemplateBinding IsMouseOver}"/> <TextBlock FontSize="{TemplateBinding FontSize}" VerticalAlignment="Center" Text="Selected Item" Margin="5,0,0,0"></TextBlock> </Grid> </ControlTemplate> </ComboBox.Template> </ComboBox> ``` you'll need to include the following namespace ``` xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero" ```
Disable ComboBox Without Changing Appearance
[ "", "c#", "wpf", "combobox", "" ]
I have the following code: ``` using System; using System.Diagnostics; using System.IO; using PdfSharp.Pdf.Printing; namespace PrintPdfFile { class Program { [STAThread] static void Main(string[] args) { // Set Acrobat Reader EXE, e.g.: PdfFilePrinter.AdobeReaderPath = @"C:\\Documents and Settings\\mike.smith\\Desktop\\Adobe Reader 9.0.exe"; // -or- //PdfPrinter.AdobeReaderPath = @"C:\Program Files\Adobe\[...]\AcroRd32.exe"; //// Ony my computer (running a German version of Windows XP) it is here: //PdfFilePrinter.AdobeReaderPath = @"C:\\Documents and Settings\\mike.smith\\Desktop\\Adobe Reader 9.0.exe"; // Set the file to print and the Windows name of the printer. // At my home office I have an old Laserjet 6L under my desk. PdfFilePrinter printer = new PdfFilePrinter(@"C:\Documents and Settings\mike.smith\Desktop\Stuff\ReleaseNotesAndFolderList.pdf", " \\ny-dc-03\\IT-01"); try { printer.Print(); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } } } } ``` For the life of me i cannot get this to work and print out a single PDF. Anytime i go to print, i get the error "Cannot find the file specified". Does anybody have any idea if something is wrong with my code?? I'm using PDFSharp here...
One observation, in the following line: ``` PdfFilePrinter.AdobeReaderPath = @"C:\\Documents and Settings\\mike.smith\\Desktop\\Adobe Reader 9.0.exe"; ``` You are using the "@" to escape the string and also escaping the backslashes. Either remove the "@" or use a single backslash. Also make sure that is the correct path to your EXE. **UPDATE:** If you have confirmed that you have the correct path to your Acrobat Reader EXE, the next thing to look at is the "Printer Name" parameter that you are passing to the PdfFilePrinter constructor. You are passing `" \\ny-dc-03\\IT-01"` as the printer name. This needs to match the name of printer exactly as it appears in the list of Printers in Windows, not just an arbitrary IP printer. If this is correct, be sure to remove, the leading space: `"\\ny-dc-03\\IT-01"`.
This may be stating the obvious but is acrobat at: > C:\Documents and > Settings\mike.smith\Desktop\Adobe > Reader 9.0.exe It's just your user name implies that your name isn't Mike smith.
Printing PDFs with PDFSharp
[ "", "c#", "pdf", "printing", "pdfsharp", "" ]
I want to develop a web application, like an online scheduler. (Yes I know it's been done a million times.) Most of my experience is in Java, so I want to leverage that when considering technologies. I've primarily been a systems developer with little exposure to UI programming, so I think this is where I will need to do most of my learning. Do you have any suggestions on the technologies I should focus on? I want to focus on technologies that are marketable and easy to learn. So far this is what I think I need for a 3-tier architecture (from the ground up): * Database (likely MySQL or PostgreSQL) - SQL, JDBC * Back end server - Java * Web server (Tomcat) - JSP, Servlets * Web Framework - Tapestry (weak on this, any better alternatives?) * Browser technologies - HTML, Javascript, CSS (need to learn) I've heard about "Rich internet application" development tools such as Flex and Silverlight, but I'm not sure about the market for such technologies. Edit: Seems like there's a lot of mention of Spring/Hibernate, so I'll look into that. I appreciate the feedback.
I think you've got your bases covered pretty well. You'll probably want to look into some frameworks / libraries to make it easier on you. Web Framework - Wicket / Stripes / JSF / Tapestry (component vs request based frameworks) Javascript Library - JQuery / YUI / Dojo As for your template language you could use JSP / Velocity / Freemarker. Just study up on the frameworks and tools maybe try a few out and see which ones work best for you. Just FYI I'm currently using. * Apache - web server * Tomcat - servlet container * MySQL - database * Stripes - request based web framework * YUI - for ajax * Spring - dependency injection * Hibernate - Object Relational Mapping * jsp - to dynamically generate html
I'd personally add [Spring](http://springframework.org/) to this list. Dependency injection is definitely a great technology to learn, and Spring lets you use it as much or as little as you like, in my experience. You haven't explicitly mentioned unit testing, but that should certainly be part of the mix - I don't have much experience outside [JUnit](http://junit.org/) as an actual testing framework, but there's also [EasyMock](http://easymock.org) and [JMock](http://www.jmock.org/) (amongst others) for mocking of dependencies. None of that's web-specific, but still important stuff IMO :)
Technologies required to build an end to end web application?
[ "", "java", "architecture", "ria", "tapestry", "" ]
What's the best practice? * A single session for the whole app * A session per window * A session per thread, and detaching everything at random * Something else? I've googled around, and there's no consensus. Everyone says something, and then takes it back. I find lugging a session around stupid... So, what's the deal?
Maybe a session per event handling is the right approach. In web applications, we usually create one session per request (using all those OpenSessionInView stuff and etc). If we think through, every request in web application is a different interaction in the application, and in a Swing application, every fired event is a different interaction in the application. If we apply the same principles we apply in web applications in Swing applications, then we should create a session per event handling. But we must determinate if using Hibernate is the best option... The database you are accessing is a local or a remote database? Do other applications share the same database? You should consider creating an EJB\HTTP backend instead having your Swing applications directly accessing the database. Using Hibernate suggest that you have a not-so-simple database, so I think you should consider create a EJB\HTTP backend.
I've used Hibernate in a enterprise size Rich Internet Application, which by technique resembles a lot of a hibernate + swing combination. I spent quite a lot of time investigating the different design patterns for using hibernate in a 3-tier application. Hibernate isn't exactly meant for this kind of application, so there wasn't that much information available on this subject. I tried a different design patterns but most of them lead to memory leakage, problems with attaching and de-attaching objects in session(s), problems with transactions etc etc. The final solution was to use a session-per-request pattern. Basically, at every request you make from the UI logic to the business logic, you create a new hibernate session. Your business logic then performs whatever you want it to do and right before ending the business logic execution, you flush and close the open session. This way there won't be any memory leakage, objects will be correctly attached and de-attached from sessions. This isn't a perfect solution, as you will encounter some problems, such as with lazy loading and transactions. I'll briefly explain those problems and how to solve them. Transactions Because you terminate the hibernate session after each request, you cannot have transactions which live beyond one request. This can be somewhat problematic, for example, let's say you want to store 10 objects within the same transaction. You cannot make a save request separately for each object, as the transaction is terminated. Therefore you need to make a method which takes as input a list of objects and saves all those objects within the same transaction. If the transaction fails, then you rollback all the objects. Lazy loading Your objects' lazy loading will not work because they most likely not attached to a session (that is, if you lazy load something once the session has been terminated). For the lazy loading to work, you need to reattach the objects to the session. I came up with a workaround for this as well, which is a bit tricky when creating new entity objects, but works nicely in everyday development. The idea is to have duplicated getters and setters for a field which is lazy loaded. One pair is private and the other one is public. The idea is that the private getter/setter pair is what hibernate uses internally and the public getters and setter are transient and used by the developer. So, what happens is that when the developer calls on the public getter, the getter checks if the field has already been loaded, if not, then attach the object to a session, load the field and close the session. Voilá, everything works and the developer never noticed anything. Here's a small code to give you the idea: ``` @Entity public class Foo { List<Bar> bars = new ArrayList<Bar>(); @OneToMany private List<Bar> getBarsInternal() { return bars; } private void setBarsInternal(List<Bar> bars) { this.bars = bars; } @Transient public List<Bar> getBars() { // pseudo code if(check if bar is still lazy loaded) { // the field is still lazy loaded // attach the field to a session an initialize it // once the field is initialized, it can be returned } return getBarsInternal(); } public void setBars(List<Bar> bars) { setBarsInternal(bars); } } ```
Hibernate + Swing
[ "", "java", "hibernate", "swing", "" ]
Let's assume we have the following structure: ``` index.php config.inc.php \ lib \ lib \ common.php ``` Several parameters like database name, user & co are configured in `config.inc.php`. What is the proper way to access them i.e. from a function located in `\lib\common.php`. Do I really have to do an `include_once("config.inc.php")` within each function there? It doesn't seem to work if: * `config.inc.php` is included once once in index.php, before including `\lib\common.php` there * if `config.inc.php` defines all variables before including `\lib\common.php` and all other files (this way I would only have to include `config.inc.php` in all "central" files at the level of `index.php` * neither does it work if `config.inc.php` is included at the top of `\lib\common.php` Many thanks - I wasn't able to find a solution with Google! **Solution** I included `config.inc.php` once in `index.php` (as suggested by Galen) and used global (as suggested by David). Everything is working as I would expect it, many thanks! Later on I will definitely look into `auto_prepend` as suggested by n3rd, tkx for that as well!
You have to use the [`global`](https://www.php.net/manual/en/language.variables.scope.php) keyword to access variables which were defined outside of a function: ``` $var1 = "muh"; $var2 = "foo"; function test() { global $var1; echo "var1=$var1; var2=$var2\n"; } ``` will print `"var1=muh; var2="`.
You simply do: ``` include_once("..\\config.inc.php"); ``` at the top of common.php. Now there are a few things here - first the backslashes are annoying, and you can (even on windows, exchange them for forward slashes ("../config.inc.php"). If you have the directory where config.inc.php is contained within in your include path, you can even just do "config.inc.php". Last and not least, if the data in config.inc.php is required for common.php to work, i suggest you switch to [require\_once()](http://php.net/require_once) instead, as that will cause a call to [exit()](http://php.net/exit) or [die()](http://php.net/die) in case the file fails to be included, hence stopping further execution. EDIT: Ah I didn't spot what others said. To use variables that are declared outside of a function inside of a function, you need to let the function know that it needs to "pull" these variables inside the function scope by using the global keyword (as other have said). Consider the following example: ``` $var = "Hello World"; function changeVar(){ $var = "Bye World!"; echo $var . "\n"; } changeVar(); echo $var; ``` The output of above stated code, is NOT: ``` Bye World! Bye World! ``` but rather: ``` Bye World! Hello World ``` This is due to the fact that the $var INSIDE of the function is its own variable, different from the $var defined OUTSIDE of the function. Change this to: ``` $var = "Hello World"; function changeVar(){ global $var; $var = "Bye World!"; echo $var . "\n"; } changeVar(); echo $var; ``` And now you have the expected output: ``` Bye World! Bye World! ```
PHP include_once: handling of imports i.e. for configuration files
[ "", "php", "localization", "include", "" ]
What do you *(especially PHP)* guys think about a naming convention for classes in which the class name reflects the path to the file, related to the project directory? e.g: ``` # /project/Session/Abstract.php # /project/Session/Database.php class Session_Database extends Session_Abstract ... ``` I'm sure you get the idea. I'm also sure some of the pros are obvious.. but what do you think - is it worth it to lengthen class names in order to get pretty nice directory structure which is easy to navigate? This also allows for a one-liner \_\_autoload( $class ) definition in PHP: str\_replace( '\_', '/', $class ); I suppose some people will consider such convention to be stupid. I personally like it, but I haven't seen it in use by other people and I am not quite sure if it will work so well in practice. One of the cons might be that with the removal of include/require calls, all classes are dependent(glued together) on the autoload function, which some might argue, does not comply with their understanding of loose coupling. The only reference that is known to me so far about such approach is <http://softwareengineering.vazexqi.com/files/pattern.html> So, do you have an opinion on this one?
Then you haven't been looking. [PEAR](http://pear.php.net/manual/en/standards.naming.php) uses this approach. So does [Zend Framework](http://framework.zend.com/). It's a rather established standard in the PHP world. I don't know when I first encountered it, but I've personally used it and liked it for several years, both as part of my own framework and as part of publicly available frameworks such as ZF.
I use that convention aswell. Not only does it help have a pretty file structure, it also helps with namespacing issues. That naming convention helps prefixing classes to avoid duplicate class names. When PHP 5.3 comes out and finally has namespaces, i'll still be using this convention. The only thing I'll do differently is shorten my class names, convert my prefixes into proper namespaces and do adjustment in my autoloader.
What about file-path-in-class-name convention?
[ "", "php", "naming-conventions", "" ]
We have a desktop client application developed in Swing. This application interacts with backend server using Servlet. The new requirement is to make a web based client. I have read about JavaFX, Flex, ExtJS, etc. I would like to know which solution is best fit to replace a swing application? Does anyone have any experience of doing the same? --- **(EDIT based on comments)** The application is heavy weight in terms of widgets. Ofcourse we will redesign a bit when making a web based client.
You could consider using the Google Web Toolkit, GWT, to make a web based client. Making a user interface in GWT is somewhat similar to doing it in Java Swing, but the final result is a dynamic web client.
You know Swing can run in a web page! There are many other options including PHP, ASP, Ajax etc etc. How "heavy" is the Swing app i.e. are there lots of widgets? This is a very open ended question!
What are the options to replace Java Swing GUI?
[ "", "java", "swing", "apache-flex", "extjs", "richfaces", "" ]
I've had some success comparing strings using the PHP [levenshtein](https://www.php.net/levenshtein) function. However, for two strings which contain substrings that have swapped positions, the algorithm counts those as whole new substrings. For example: ``` levenshtein("The quick brown fox", "brown quick The fox"); // 10 differences ``` are treated as having *less in common* than: ``` levenshtein("The quick brown fox", "The quiet swine flu"); // 9 differences ``` I'd prefer an algorithm which saw that the *first two* were more similar. How could I go about coming up with a comparison function that can identify substrings which have switched position as being distinct to edits? One possible approach I've thought of is to put all the words in the string into alphabetical order, before the comparison. That takes the original order of the words completely out of the comparison. A downside to this, however, is that changing just the first letter of a word can create a much bigger disruption than a changing a single letter should cause. What I'm trying to achieve is to compare two facts about people which are free text strings, and decide how likely these facts are to indicate the same fact. The facts might be the school someone attended, the name of their employer or publisher, for example. Two records may have the same school spelled differently, words in a different order, extra words, etc, so the matching has to be somewhat fuzzy if we are to make a good guess that they refer to the same school. So-far it is working very well for spelling errors (I am using a phoenetic algorithm similar to metaphone on top of this all) but very poorly if you switch the order of words around which seem common in a school: "xxx college" vs "college of xxx".
### N-grams Use [N-grams](http://en.wikipedia.org/wiki/N-gram#n-grams_for_approximate_matching), which support **multiple-character transpositions across the whole text**. The general idea is that you split the two strings in question into all the possible 2-3 character substrings (n-grams) and treat the number of shared n-grams between the two strings as their similarity metric. This can be then normalized by dividing the shared number by the total number of n-grams in the longer string. This is trivial to calculate, but fairly powerful. For the example sentences: ``` A. The quick brown fox B. brown quick The fox C. The quiet swine flu ``` A and B share **18** *2-grams* A and C share only **8** *2-grams* out of **20** total possible. This has been discussed in more detail in the [Gravano et al. paper](http://www1.cs.columbia.edu/~pirot/publications/deb-dec2001.pdf). ### tf-idf and cosine similarity A not so trivial alternative, but grounded in information theory would be to use term [term frequency–inverse document frequency (tf-idf)](https://en.wikipedia.org/wiki/Tf%E2%80%93idf) to weigh the tokens, construct sentence vectors and then use [cosine similarity](https://en.wikipedia.org/wiki/Cosine_similarity) as the similarity metric. The algorithm is: 1. Calculate 2-character token frequencies (tf) per sentence. 2. Calculate inverse sentence frequencies (idf), which is a logarithm of a quotient of the number of all sentences in the corpus (in this case 3) divided by the number of times a particular token appears across all sentences. In this case *th* is in all sentences so it has zero information content (log(3/3)=0). ![idf formula](https://i.stack.imgur.com/Y6qe7.png) 3. Produce the tf-idf matrix by multiplying corresponding cells in the tf and idf tables. ![tfidf](https://i.stack.imgur.com/yfEzMm.png) 4. Finally, calculate cosine similarity matrix for all sentence pairs, where A and B are weights from the tf-idf table for the corresponding tokens. The range is from 0 (not similar) to 1 (equal). ![cosine similarity](https://i.stack.imgur.com/QiVH6m.png) ![similarity matrix](https://i.stack.imgur.com/EL8iMm.png) ### Levenshtein modifications and Metaphone Regarding other answers. [Damerau–Levenshtein](http://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance) modificication supports only the transposition of **two adjacent** characters. [Metaphone](http://en.wikipedia.org/wiki/Metaphone) was designed to match words that sound the same and not for similarity matching.
Its easy. Just use the [Damerau-Levenshtein](http://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance) distance on the words instead of letters.
Levenshtein distance: how to better handle words swapping positions?
[ "", "php", "algorithm", "levenshtein-distance", "similarity", "edit-distance", "" ]
I am writing a a report and was wondering if there is there any way to find items that join into identical sets? For example in the following query, I want to find all areas that join against the same set of products: ``` SELECT Area.Name, AggregateSetOfProductsId FROM Area INNER JOIN AreaToProduct ON AreaToProduct.AreaId = Area.Id GROUP BY Area.Id ``` The current best solution that I could think of was writing a custom aggregate that hashed the ProductId uniqueidentifiers together (something like shift right based on some byte then xor them together) it but I figured I'd ask if there was an easier way before going through it.
You can do this with set operations. Here I show you how to obtain all orderid's from northwind which contain exactly the same products (which is what you're after, right? the areas with exactly the same products) ``` select distinct o1.orderid from orders o1 inner join orders o2 on o1.orderid!=o2.orderid where not exists ( select * from [order details] od2 where od2.orderId=o2.Orderid and od2.ProductId NOT IN ( select productid from [order details] od1 where od1.OrderId=o1.OrderId ) ) and not exists ( select * from [order details] od1 where od1.orderId=o1.Orderid and od1.ProductId NOT IN ( select productid from [order details] od2 where od2.OrderId=o2.OrderId ) ) ``` The idea is basicly this: return order o1 for which an order o2 exists for which there aren't any products not in the list of products of o1 and where there aren't any products from o1 not in the list of products of o2.
You can easily do this using a Common Table Expression. You would employ FOR XML PATH to create an array, and then use that array to identify matching products. Like this: ``` ;WITH AreaProductSets AS ( SELECT a.AreaID, a.Name, SUBSTRING((SELECT (', ' + CAST(ap.ProductID AS varchar(20))) FROM AreaToProduct ap WHERE ap.AreaID = a.AreaID ORDER BY ap.ProductID FOR XML PATH ('')), 3, 2000) AS ProductArray FROM Area AS a ) SELECT SUBSTRING((SELECT (', ' + CAST(aps2.Name AS varchar(20))) FROM AreaProductSets aps2 WHERE aps2.ProductArray = aps.ProductArray ORDER BY aps2.AreaID FOR XML PATH('')), 3, 2000) AS MatchingAreas, aps.ProductArray FROM (SELECT DISTINCT ProductArray FROM AreaProductSets) AS aps ```
Determining items that join against the same set in T-SQL
[ "", "sql", "sql-server", "t-sql", "join", "set", "" ]
Trying to get parameters from a PUT request using HttpServlet#doPut: ``` public void doPut(HttpServletRequest request, HttpServletResponse response) { String name = request.getParameter("name"); // name is null } ``` Using curl to send the request: ``` curl -X PUT \ --data "name=batman" \ --header "Content-Type: text/plain" http://localhost:8080/sample.html ``` works fine with using doGet and GET curl request. Am I missing something?
Based on comments and further research I realized that the Servlet cannot assume anything about the data being put onto the server and therefore, will not parse name/value pairs. The following solution seems to be the proper way to handle any data passed via PUT, and can be parsed as XML, Name/Value, or whatever. ``` BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()); String data = br.readLine(); ```
Unlike in `doGet()` and `doPost()` methods, we are not able to get the request parameters using the `getParameter()` method in `doPut()` and `doDelete()` methods. We need to retrieve them manually from the input stream. The following method retrieves request parameters and returns them in a map: ``` public static Map<String, String> getParameterMap(HttpServletRequest request) { BufferedReader br = null; Map<String, String> dataMap = null; try { InputStreamReader reader = new InputStreamReader( request.getInputStream()); br = new BufferedReader(reader); String data = br.readLine(); dataMap = Splitter.on('&') .trimResults() .withKeyValueSeparator( Splitter.on('=') .limit(2) .trimResults()) .split(data); return dataMap; } catch (IOException ex) { Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); } finally { if (br != null) { try { br.close(); } catch (IOException ex) { Logger.getLogger(Utils.class.getName()).log(Level.WARNING, null, ex); } } } return dataMap; } ``` The example uses Google's Guava library to parse the parameters. For a complete example containing `doGet()`, `doPost()`, `doPut()` and `doDelete()` methods, you can read my [Using jsGrid tutorial](http://zetcode.com/articles/jsgridservlet/).
Servlet parameters and doPut
[ "", "java", "rest", "servlets", "" ]
Now I'm geting an error: 1>c:\development\document\_manager\document\_manager\storage\_manager.h(7) : error C2079: 'storage\_manager::db' uses undefined struct 'sqlite3' with ``` #pragma once #include "sqlite3.h" class storage_manager { sqlite3 db; sqlite3** db_pp; public: void open() { sqlite3_open("data.db", db_pp); } }; ``` Old Question: Hi everyone. I downloaded sqlite-amalgamation-3\_6\_13.zip from <http://www.sqlite.org/download.html>, but I'm not able to compile it in my project. I receive many errors like: ``` c:\pathtoproject\sqlite3.c(11337) : error C2440: '=' : cannot convert from 'void *' to 'char *' Conversion from 'void*' to pointer to non-'void' requires an explicit cast c:\pathtoproject\sqlite3.c(12023) : error C2440: '=' : cannot convert from 'void *' to 'sqlite3_int64 *' Conversion from 'void*' to pointer to non-'void' requires an explicit cast ``` What do I need to do to compile my project properly? Thanks! Edit: I don't want to compile the whole program as C, I just want to compile three files as c, is this possible? EDIT: FIXED! I created an new project.
It looks like you might be trying to compile a C program using a C++ compiler. While there is a lot of C code which is also valid C++, they are different languages. Your compiler may have some switch or setting to compile C code. Check your compiler documentation.
You need to compile the file as C code rather than C++. Right click on either the project or just the .c file, and in properties, make sure it is set to compile as C, rather than C++. (You may want to set this setting just for the file, not the entire project)
SQLite3 object not understood?
[ "", "c++", "sqlite", "" ]
I have DataSet which has 3 columns. ``` Name - insurance comp. name - treatmentDate Ali Boz SGK 12.04.09 Ali Boz SGK 14.04.09 Ali Boz SGK 16.04.09 Ali Boz SGK 18.04.09 Veli Aş AKBANK 10.04.09 Veli Aş AKBANK 11.04.09 Veli Aş AKBANK 12.04.09 Veli Aş AKBANK 13.04.09 Cuneyt Sel ING BANK 01.05.09 Cuneyt Sel ING BANK 02.05.09 Cuneyt Sel ING BANK 05.05.09 Cuneyt Sel ING BANK 19.05.09 ``` I want to firstly find only insurance comp. names ``` SGK AKBANK ING BANK ``` Then i want to sort by name and date But all those things in a DataSet (cause i want to retrive all rows from db). Do you have any advice to me?
If you can use LINQ, this will give you the insurance company names: ``` var Names = (from Row in YourDataSet.YourTable select Row.InsuranceCompanyName).Distinct(); ``` You could also add `.ToArray()` or `.ToList()` or `orderby` depending on your needs, if necessary. If you can't use LINQ or change the SQL call, it's [more complicated](http://www.brybot.ca/archives/select-distinct-from-dataset/).
Not sure what exactly your asking, but to retrieve insurance company names, you could simply execute the following: ``` SELECT DISTINCT [insurance comp. name] FROM [tablename] ``` To sort all records as you mentioned: ``` SELECT * FROM [tablename] ORDER BY [insurance comp. name], [name], [treatmentdate] ```
How to remove column in DataSet and distinct rows to find only group names?
[ "", "c#", "dataset", "distinct", "dataview", "" ]
And if so, why? and what constitutes "long running"? Doing magic in a property accessor seems like my prerogative as a class designer. I always thought that is why the designers of C# put those things in there - so I could do what I want. Of course it's good practice to minimize surprises for users of a class, and so embedding truly long running things - eg, a 10-minute monte carlo analysis - in a method makes sense. But suppose a prop accessor requires a db read. I already have the db connection open. Would db access code be "acceptable", within the normal expectations, in a property accessor?
Like you mentioned, it's a surprise for the user of the class. People are used to being able to do things like this with properties (contrived example follows:) ``` foreach (var item in bunchOfItems) foreach (var slot in someCollection) slot.Value = item.Value; ``` This looks very natural, but if `item.Value` actually is hitting the database every time you access it, it would be a minor disaster, and should be written in a fashion equivalent to this: ``` foreach (var item in bunchOfItems) { var temp = item.Value; foreach (var slot in someCollection) slot.Value = temp; } ``` Please help steer people using your code away from hidden dangers like this, and put slow things in methods so people know that they're slow. There are some exceptions, of course. Lazy-loading is fine as long as the lazy load isn't going to take some insanely long amount of time, and sometimes making things properties is really useful for reflection- and data-binding-related reasons, so maybe you'll want to bend this rule. But there's not much sense in violating the convention and violating people's expectations without some specific reason for doing so.
In addition to the good answers already posted, I'll add that the debugger automatically displays the values of properties when you inspect an instance of a class. Do you *really* want to be debugging your code and have *database fetches* happening *in the debugger* every time you inspect your class? Be nice to the future maintainers of your code and don't do that. Also, this question is extensively discussed in the **Framework Design Guidelines**; consider picking up a copy.
Is it true I should not do "long running" things in a property accessor?
[ "", "c#", "vb.net", "properties", "class-design", "" ]
I'm trying to get the values from a pointer to a float array, but it returns as c\_void\_p in python The C code ``` double v; const void *data; pa_stream_peek(s, &data, &length); v = ((const float*) data)[length / sizeof(float) -1]; ``` Python so far ``` import ctypes null_ptr = ctypes.c_void_p() pa_stream_peek(stream, null_ptr, ctypes.c_ulong(length)) ``` The issue being the null\_ptr has an int value (memory address?) but there is no way to read the array?!
My ctypes is rusty, but I believe you want POINTER(c\_float) instead of c\_void\_p. So try this: ``` null_ptr = POINTER(c_float)() pa_stream_peek(stream, null_ptr, ctypes.c_ulong(length)) null_ptr[0] null_ptr[5] # etc ```
To use ctypes in a way that mimics your C code, I would suggest (and I'm out-of-practice and this is untested): ``` vdata = ctypes.c_void_p() length = ctypes.c_ulong(0) pa_stream_peek(stream, ctypes.byref(vdata), ctypes.byref(length)) fdata = ctypes.cast(vdata, POINTER(float)) ```
Python double pointer
[ "", "python", "ctypes", "" ]
I'm writing a python script to extract data out of our 2GB Apache access log. Here's one line from the log. ``` 81.52.143.15 - - [01/Apr/2008:00:07:20 -0600] "GET /robots.txt HTTP/1.1" 200 29 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1) VoilaBot BETA 1.2 (http://www.voila.com/)" ``` I'm trying to get the date portion from that line, and regex is failing me, and I'm not sure why. Here's my python code: ``` l = 81.52.143.15 - - [01/Apr/2008:00:07:20 -0600] "GET /robots.txt HTTP/1.1" 200 29 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1) VoilaBot BETA 1.2 (http://www.voila.com/)" re.match(r"\d{2}/\w{3}/\d{4}", l) ``` returns nothing. Neither do the following: ``` re.match(r"\d{2}/", l) re.match(r"\w{3}", l) ``` or anything else I can thing of to even get *part* of the date. What am I misunderstanding?
match() looks for a match at the beginning of the string. Use search() to look for a match anywhere in the string. More info here: <http://docs.python.org/library/re.html#matching-vs-searching>
Or you can use one of already available python apache log parsers like : * Apachelogs * Logtools * Logrep (Wtop package)
Regex for finding date in Apache access log
[ "", "python", "regex", "" ]
Our application takes text from a web form and sends it via email to an appropriate user. However, when someone copy/pastes in the infamous "smart quotes" or other special characters from Word, things get hairy. The user types in > he said “hello” to me—isn’t that nice? But when the message appears in Outlook 2003, it comes out like this: > he said hello to meisnt that nice? The code for this was: ``` Session session = Session.getInstance(props, new MailAuthenticator()); Message msg = new MimeMessage(session); //removed setting to/from addresses to simplify msg.setSubject(subject); msg.setText(text); msg.setHeader("X-Mailer", MailSender.class.getName()); msg.setSentDate(new Date()); Transport.send(msg); ``` After a little research, I figured this was probably a character encoding issue and attempted to move things to UTF-8. So, I updated the code thusly: ``` Session session = Session.getInstance(props, new MailAuthenticator()); MimeMessage msg = new MimeMessage(session); //removed setting to/from addresses to simplify msg.setHeader("X-Mailer", MailSender.class.getName()); msg.addHeader("Content-Type", "text/plain"); msg.addHeader("charset", "UTF-8"); msg.setSentDate(new Date()); Transport.send(msg); ``` This got me closer, but no cigar: > he said “hello” to me—isnÂ’t that nice? I can't imagine this is an uncommon problem--what have I missed?
Is the page with your form also using UTF-8, or a different charset? If you don't specify the webpage charset, the format of data coming to your script is anyone's guess. --- Edit: the charset in the message should be set like this: ``` msg.addHeader("Content-Type", "text/plain; charset=UTF-8"); ``` since charset is not a separate header, but an option to Content-type
Why don't you replace the nice quotes with regular prime quotes?
Smart quotes in a MimeMessage not showing up correctly in Outlook
[ "", "java", "email", "character-encoding", "outlook", "mime-message", "" ]
Is there a way not to process fields with a “display:none” style ? The fields are dynamically hidden using javascript but are processed normally in PHP. I’m looking for a PHP solution (no javascript).
Depending on how your form is structured, it might be a viable method to remove the `name` attribute of the hidden inputs. in whatever Javascript you use to hide the input, add this line: ``` myInputElement.removeAttribute('name'); ``` Inputs without a name are not submitted with the form. If you might need to revert back (and show the inputs again), you might want to think about storing the name somewhere retrievable: perhaps use the same `name` as the `id` on each element, or store it into the element's `class` attribute somewhere. --- A better idea, as suggested by Colin, would be to disable the element instead. This will have the same effect as removing its name, however it would be much easier to revert, should you need to. ``` myInputElement.disabled = true; ```
My recollection is that input's that are [disabled](http://www.w3.org/TR/html401/interact/forms.html#adef-disabled) will not be submitted in the form data. So when you hide the field set the disabled attribute as well. No need to muck with names and ids. From the W3C: > In this example, the INPUT element is disabled. Therefore, it cannot receive user input nor will its value be submitted with the form. > > <INPUT disabled name="fred" value="stone">
How to process ‘only’ visible fields in an HTML Form?
[ "", "php", "html", "forms", "" ]
I have an ASP.NET 2.0 web application running on a shared server of a well known web hosting provider. Occasionally I seem to be getting errors like this: Could not find file 'C:\WINDOWS\TEMP\lxnmfrsz.dll'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.IO.FileNotFoundException: Could not find file 'C:\WINDOWS\TEMP\lxnmfrsz.dll'. I've searched around and it seems that this is a common problem. One solution is to clear out the temp folder or restart IIS. Since I don't have access to these things on a server I do not own, those are not really options. I've tried setting the temp directory to a different directory using a directive in web.config, but it still seems to be using the default temp directory. Is there some other way I can change the temp directory and/or resolve this problem?
If you always serialize the same type, you can try [pre-generating XmlSerializer binaries using sgen.exe](https://stackoverflow.com/questions/134224/generating-an-xml-serialization-assembly-as-part-of-my-build). In that case XmlSerializer won't go searching for them.
The only caveat here is that if generics are involved (e.g., a List < > of your type), it does not seem to be possible to use sgen to pregenerate the serializer assembly. A workaround for this is to derive from the List < MyType > with your own type, then include this in the pregenerated assembly.
XmlSerializer Could Not Find File C:\Windows\Temp\*.dll
[ "", "c#", "asp.net", "xml-serialization", "" ]
I'm a beginner with both Python and RegEx, and I would like to know how to make a string that takes symbols and replaces them with spaces. Any help is great. For example: ``` how much for the maple syrup? $20.99? That's ricidulous!!! ``` into: ``` how much for the maple syrup 20 99 That s ridiculous ```
One way, using [regular expressions](http://docs.python.org/library/re.html): ``` >>> s = "how much for the maple syrup? $20.99? That's ridiculous!!!" >>> re.sub(r'[^\w]', ' ', s) 'how much for the maple syrup 20 99 That s ridiculous ' ``` * `\w` will match alphanumeric characters and underscores * `[^\w]` will match anything that's *not* alphanumeric or underscore
Sometimes it takes longer to figure out the regex than to just write it out in python: ``` import string s = "how much for the maple syrup? $20.99? That's ricidulous!!!" for char in string.punctuation: s = s.replace(char, ' ') ``` If you need other characters you can change it to use a white-list or extend your black-list. Sample white-list: ``` whitelist = string.letters + string.digits + ' ' new_s = '' for char in s: if char in whitelist: new_s += char else: new_s += ' ' ``` Sample white-list using a generator-expression: ``` whitelist = string.letters + string.digits + ' ' new_s = ''.join(c for c in s if c in whitelist) ```
How to remove symbols from a string with Python?
[ "", "python", "regex", "string", "" ]
I'm trying to write a javascript function that adds some DOM nodes to the document in the place it was called, like this: ``` ... <div> <script type="text/javascript"> pushStuffToDOMHere(args); </script> </div> ... ``` i try to do it 'cleanly', without using node id property of the div, or innerHTML string manipulation. for that I need to know where in the document the script tag is located. is there a way to do it?
Talking about cleanly, I don't think your approach is particularly clean. It is a much better idea to give the div a unique id and execute your javascript when the DocumentReady-event fires.
Do you have an overriding reason for doing it this way? If not the suggestion to use a unique id makes the most sense. And you can always use a library like jQuery to make this even easier for yourself. However, the following quick test shows that if you use document.write() in the function then it writes the value into the place where the function was called from. ``` <html> <head> <script type="text/javascript"> function dosomething(arg){ document.write(arg); } </script> </head> <body> <div>The first Div</div> <div>The <script type="text/javascript"> dosomething("Second"); </script> Div </div> <div>The <script type="text/javascript"> dosomething("Third"); </script> Div </div> </body> </html> ``` But, again the question, are you sure this is what you want to do?
how does a function know where it is located in the DOM?
[ "", "javascript", "dom", "" ]
I have a table with a 'Wav' column that is of type 'VARBINARY(max)' (storing a wav file) and would like to be able to check if there is a wav from Linq to SQL. My first approach was to do the following in Linq: ``` var result = from row in dc.Table select new { NoWav = row.Wav != null }; ``` The problem with the code above is it will retreive all the binary content to RAM, and this isn't good (slow and memory hungry). Any idea how to have Linq query to translate into something like bellow in SQL? ``` SELECT (CASE WHEN Wav IS NULL THEN 1 ELSE 0 END) As NoWav FROM [Update] ```
Thanks for all the replies. They all make sense. Indeed, Linq *should* translate the != null correctly, but it didn't seem to effectively do it: running my code was very slow, so somehow my only explaination is that it got the binary data transfered over to the RAM.... but maybe I'm wrong. I think I found a work around anyway somewhere else on stackoverflow: [Create a computed column on a datetime](https://stackoverflow.com/questions/441869/create-a-computed-column-on-a-datetime) I ran the following query against my table: ``` ALTER TABLE [Table] ADD WavIsNull AS (CASE WHEN [Wav] IS NULL Then (1) ELSE (0) END) ``` Now I'll update my DBML to reflect that computed column and see how it goes.
Are you sure that this code will retrieve the data to RAM? I did some testing using **LINQPad** and the generated SQL was optimized as you suggest: ``` from c in Categories select new { Description = c.Description != null } SELECT (CASE WHEN [t0].[description] IS NOT NULL THEN 1 ELSE 0 END) AS [Description] FROM [Category] AS [t0] ```
How to make Linq to SQL translate to a derived column?
[ "", "sql", "linq-to-sql", "" ]
Is the following "From" header incorect? ``` // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Additional headers $headers .= 'From: Mail Master <mail@mailmaster.com>' . "\r\n"; if(sendEmailNow($email, $subject, $body, $headers)){ ``` I get the error from my mail server. It says "Mail from error: Syntax error". Thanks all for any help. ## Update I have stripped down the SendEmailNow function to the below and I get the same error: ``` //send an email function sendEmailNow($email, $subject, $body, $headers){ if (mail($email, $subject, $body, $headers)) { ##check email ##code to say email sent - compare with the number registered return true; } else { ##code to report an error return false; } } ``` ## Update 2 Problem solved. I am running this on a windows machine using PHP 5. Like the correct answer chosen and the comments have said. Some mail servers have trouble understanding what I had previously. But what worked for me was this: ``` $headers .= 'From: mail@mailmaster.com' . "\r\n"; ```
A Google search for the error message suggests that some SMTP servers fail to parse your syntax for the `From` header. Can you try the following syntax to rule out this possibility? ``` From: mail@mailmaster.com ```
Unless the body is empty, you may need an additional CRLF to terminate the headers. Without knowing the API I can't say much more.
Is my email header correct?
[ "", "php", "mime", "" ]
How do you define a specific ordering in Django `QuerySet`s? Specifically, if I have a `QuerySet` like so: `['a10', 'a1', 'a2']`. Regular order (using `Whatever.objects.order_by('someField')`) will give me `['a1', 'a10', 'a2']`, while I am looking for: `['a1', 'a2', 'a10']`. What is the proper way to define my own ordering technique?
As far as I'm aware, there's no way to specify database-side ordering in this way as it would be too backend-specific. You may wish to resort to good old-fashioned Python sorting: ``` class Foo(models.Model): name = models.CharField(max_length=128) Foo.objects.create(name='a10') Foo.objects.create(name='a1') Foo.objects.create(name='a2') ordered = sorted(Foo.objects.all(), key=lambda n: (n[0], int(n[1:]))) print ordered # yields a1, a2, 10 ``` If you find yourself needing this kind of sorting a lot, I'd recommend making a custom `models.Manager` subclass for your model that performs the ordering. Something like: ``` class FooManager(models.Manager): def in_a_number_order(self, *args, **kwargs): qs = self.get_query_set().filter(*args, **kwargs) return sorted(qs, key=lambda n: (n[0], int(n[1:]))) class Foo(models.Model): ... as before ... objects = FooManager() print Foo.objects.in_a_number_order() print Foo.objects.in_a_number_order(id__in=[5, 4, 3]) # or any filtering expression ```
@Jarret's answer (do the sort in Python) works great for simple cases. As soon as you have a large table and want to, say, pull only the first page of results sorted in a certain way, this approach breaks (you have to pull every single row from the database before you can do the sort). At that point I would look into adding a denormalized "sort" field which you populate from the "name" field at save-time, that you can sort on at the DB-level in the usual way.
Custom ordering in Django
[ "", "python", "django", "django-models", "" ]
I was developing an application using Entity Framework and storing data in a .mdf database. My code can read the data, apparently it can save too, but only apparently. It get no erros, while the program is running it act like the data was saved, I can for example save an object, dispose the context, create a new one, and then when I search my object it's there! But when I query the database to see the stored data there's nothing there. If I close the app and run it again, all data is gone. Here's a example code I wrote just to test: ``` using (DatabaseEntities e = new DatabaseEntities()) { for (int i = 0; i < 50; i++) { User u = new User(); u.Nome = "User" + i.ToString(); e.AddToUser(u); } int c = e.SaveChanges(true); List<User> us = e.User.Where<User>(x => x.ID < 50).ToList<User>(); foreach (User u in us) Console.WriteLine("ID: " + u.ID + " Hello from " + u.Nome); Console.ReadKey(); } ``` When I run this I get the 50 outputs, if I look the content of the c variable in the debug, there's 50 changes, everythings seems to be fine, but when I start my query browser and look in the content of my MDF database, there's nothing there. Probably it's something very simple but I can't see what it is, I need your help.
I just found what was going wrong, and I guess there's nothing wrong actually. I forced an error, and then I could see the database that I was accessing was in the bin directory, the Visual Studio copied my database to the bin directory everytime I run the app, so that's why if I add some data manually I could see it, but the saves in the runtime aren't persisted. I always worked with database in servers, it's my first time with local databases, so I messed up it, but thankz a lot for the help! --- ## Edit: Providing a Solution If you wish to disable copying the database on build, then you have to acces the `Copy to Output Directoy` from the `.mdf` file from your Solution Explorer. Simply change it to `Copy if newer` or `Do not copy`. **Be aware that `Copy if newer` holds some risks [when accesing a `.mdf` Database](https://msdn.microsoft.com/en-US/library/ms246989.aspx).**
A few things leap to mind: * double/treble-check your connection string; are you really talking to the file that you think you are? * are you using transactions anywhere and not committing them? * do you have the mdf file set to "Copy Always" (or whatever it is).... i.e. are you constantly overwriting the mdf whenever you hit build/play? Also - I don't think it'll matter in this case, but to verify data you should use a *different* entities/data-context: ``` using (DatabaseEntities e = new DatabaseEntities()) { for (int i = 0; i < 50; i++) { User u = new User(); u.Nome = "User" + i.ToString(); e.AddToUser(u); } int c = e.SaveChanges(true); } using (DatabaseEntities e = new DatabaseEntities()) { List<User> us = e.User.Where<User>(x => x.ID < 50).ToList<User>(); foreach (User u in us) Console.WriteLine("ID: " + u.ID + " Hello from " + u.Nome); } Console.ReadKey(); ``` Like I said - I doubt it'll matter here, but worth checking...
Entity Framework won't persist data in SQL Express (MDF)
[ "", "c#", "entity-framework", "persistence", "sql-server-express", "" ]