Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm looking for a javascript regex that will remove all content wrapped in quotes(and the qoutes too), in a string that is the outlook format for listing email addresses. Take a look at the sample below, I am a regex tard and really need some help with this one, any help/resources would be appreciated! ``` "Bill'sRestauraunt"BillsRestauraunt@comcast.net,"Rob&Julie"robjules@ntelos.net,"Foo&Bar"foobar@cstone.net ```
Assuming no nested quotes: ``` mystring.replace(/"[^"]*"/g, '') ```
Try this regular expression: ``` /(?:"(?:[^"\\]+|\\(?:\\\\)*.)*"|'(?:[^'\\]+|\\(?:\\\\)*.)*')/g ```
Javascript regular expression to strip out content between double quotes
[ "", "javascript", "regex", "" ]
I am setting up a table where I need the year and month. In MySQL I believe I have 2 options: (1) 2 fields: 1 for year, 1 for month or (2) a date field (the day would always be 1). The 2 fields has the advantage of being some what faster (I think) because MySQL doesn't have to convert the value from a date to an integer although this is probably negligible. The date field has the advantage of "automatic" validation: someone can't get data into the db with the the month being 13 or the year being 1. With a date field you can also do date calculations more easily (ie, months between). Which would you use? Or is there another you would use?
Use a date field. Since sql supports date fields natively, its easy to filter for specific dates by using the WHERE clause. > The 2 fields has the advantage of being some what faster [...] Your SELECT query is not your bottleneck so you shouldn't worry about this. Readability and a pragmatic program is more important than a "perceived bottleneck".
Think about it this way: One day someone will come to you with a requirement to enhance the application with the ability to not only save year and month, but also a day. Would you then add an extra column for a day? And then, next thing, they might want you to also save time. How easy would it be to enhance the functionality if you have separate columns for year/month/day? If you have a single date column? I would go for a date column for this reason alone.
In a database, would you use a date field or year and month fields if you only need year and month?
[ "", "sql", "mysql", "database-design", "database", "" ]
I am performing a search in an XML file, using the following code: ``` $result = $xml->xpath("//StopPoint[contains(StopName, '$query')]"); ``` Where $query is the search query, and StopName is the name of a bus stop. The problem is, it's case sensitive. And not only that, I would also be able to search with non-english characters like ÆØÅæøå to return Norwegian names. How is this possible?
In XPath 1.0 (which is, I believe, the best you can get with PHP SimpleXML), you'd have to use the `translate()` function to produce all-lowercase output from mixed-case input. For convenience, I would wrap it in a function like this: ``` function findStopPointByName($xml, $query) { $upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZÆØÅ"; // add any characters... $lower = "abcdefghijklmnopqrstuvwxyzæøå"; // ...that are missing $arg_stopname = "translate(StopName, '$upper', '$lower')"; $arg_query = "translate('$query', '$upper', '$lower')"; return $xml->xpath("//StopPoint[contains($arg_stopname, $arg_query)"); } ``` As a sanitizing measure I would either completely forbid or escape single quotes in `$query`, because they will break your XPath string if they are ignored.
In XPath 2.0 you can use [`lower-case()`](http://www.w3.org/TR/xpath-functions/#func-lower-case) function, which is unicode aware, so it'll handle non-ASCII characters fine. ``` contains(lower-case(StopName), lower-case('$query')) ``` To access XPath 2.0 you need XSLT 2.0 parser. For example [SAXON](http://saxon.sourceforge.net/). You can access it [from PHP](http://saxon.wiki.sourceforge.net/Saxon-from-PHP) via JavaBridge.
How can I use XPath to perform a case-insensitive search and support non-english characters?
[ "", "php", "xml", "xpath", "" ]
Are there any reasons why I shouldn't use Visual Studio 6 for C++ development? * Where can I find some resources why this would or wouldn't be a good idea? * Are there any lists of issues I would have with this?
1. `std::string` multicore/proc issues in the runtime, re: [KB813810](http://support.microsoft.com/kb/813810) 2. poor STL support 3. even poorer Standard C++ support Don't do it.
I wouldn't say that Visual Studio 6 should "never" be used for C++ development. I would say that it should "no longer" be used for C++ development. Reasons: 1. Microsoft's later compilers (particularly Visual Studio 2008) are much more compliant with the C++ specification. 2. Microsoft's later compilers add better warnings and errors. These are useful when looking for potential security problems with your code. 3. It's no longer supported. Newer releases of the Windows SDK don't work with Visual C++ 6, so you won't be able to use newer features in Windows without extra work. To summarise: stop using Visual C++ 6. If you have to use a Microsoft C++ compiler, use Visual Studio 2008.
Are there any reasons not to use Visual Studio 6 for C++?
[ "", "c++", "visual-c++-6", "" ]
In the Java APIs I can see Javadoc comments for packages. How/where do I place Javadoc comments to document a package?
As of 1.5 you can define a `package-info.java` file and provide a standard javadoc style comment for a package: com/foo/package-info.java: ``` /** * com.foo is a group of bar utils for operating on foo things. */ package com.foo; //rest of the file is empty ``` [Language specification for packages](http://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.4.1)
Up to and including Java 1.4, you had to provide a HTML file package.html, as described in the other answers. Since Java 1.5 you can also provide a `package-info.java`, which contains a regular Javadoc comment (no HTML). The latter is preferred, as it gives you some extra features (notably package annotations). Details: [Sun's docs for javadoc](http://java.sun.com/javase/6/docs/technotes/tools/solaris/javadoc.html#packagecomment)
How Do I Document Packages in Java?
[ "", "java", "package", "javadoc", "" ]
``` typedef unsigned char Byte; ... void ReverseBytes( void *start, int size ) { Byte *buffer = (Byte *)(start); for( int i = 0; i < size / 2; i++ ) { std::swap( buffer[i], buffer[size - i - 1] ); } } ``` What this method does right now is it reverses bytes in memory. What I would like to know is, is there a better way to get the same effect? The whole "size / 2" part seems like a bad thing, but I'm not sure. EDIT: I just realized how bad the title I put for this question was, so I [hopefully] fixed it.
The standard library has a [`std::reverse`](http://en.cppreference.com/w/cpp/algorithm/reverse) function: ``` #include <algorithm> void ReverseBytes( void *start, int size ) { char *istart = start, *iend = istart + size; std::reverse(istart, iend); } ```
A performant solution without using the STL: ``` void reverseBytes(void *start, int size) { unsigned char *lo = start; unsigned char *hi = start + size - 1; unsigned char swap; while (lo < hi) { swap = *lo; *lo++ = *hi; *hi-- = swap; } } ``` Though the question is 3 ½ years old, chances are that someone else will be searching for the same thing. That's why I still post this.
Is there a better way to reverse an array of bytes in memory?
[ "", "c++", "memory", "swap", "std", "" ]
I cooked up a pattern to create and extend html elements using their prototype. This works like a charm in non-ie browsers. Example code can be found @jsbin**1** The advantage of this pattern should be speed (the methods are in the elements prototype chain, so they are referenced once). You guessed right: IE no go. In IE < 8 the prototype of html elements is hidden/not accessible, so for every element you create, you have to reference the non standard methods again (leaving you with a lot of pointers if you use the pattern intensively). I have searched the web for solutions, but only found complex workarounds. Is there *really* no way to access a HTML elements prototype in IE? **1** Alas: the jsbin code is lost in clouds.
No, nor is it guaranteed you can fiddle with DOM objects' prototypes in JavaScript in general. The DOM objects are not part of the ECMAScript spec; they may not be (and traditionally speaking aren't) native JavaScript Objects at all, in any browser. This is why frameworks tend to have their own ‘container’ wrapper classes. Also you cannot rely on ‘t.el.constructor’ even if they were native JS Objects. ‘constructor’ is not a standard property, isn't available in IE, and even in Mozilla doesn't do what you might think it does. Avoid.
Yes there really is no way to do this. IE elements are based COM objects which actually don't allow arbitary members to be added to their interfaces (in COM, interfaces are a contract and should never change). Implementation of these interfaces cannot be extended by Javascript, the elements simply are not prototypal. IE adds a special interface designed to work with Javascript to allow the addition of new members to a specific instance but you cannot add a new member to 'class' since there is no prototype to fiddle with.
Is there really no way to expose the prototype of a html element in IE (<8)?
[ "", "javascript", "internet-explorer", "dom", "prototype-programming", "" ]
I have a bit of code, which I can't figure out properly. The problem is that the program is multithreaded and within there is a bit of code that should be synchronized so I wrote this: ``` lock (lockObject) { if (!Monitor.TryEnter(lockObject)) Monitor.Wait(lockObject); //do stuff... Monitor.PulseAll(lockObject); } Monitor.Exit(lockObject); ``` the problem I've got is that in some point in time all Threads seem to be sleeping - can someone tell why? The program keeps running along endlessly consuming nearly no cpu but no work is done - when tracing the program I found out that on some point no thread is active but a whole lot of them is sleeping. I know the error mostly (in case of a developer - always) sits 0.5m in front of the monitor - but I cannot figure it out myself... maybe in a few minutes ;) can someone please explain that to me - thanks in advance.
Is there a difference between `LockObject` and `lockObject`? It isn't clear... However! If they are different objects, then first: you can't `Wait` on a lock that you don't have... and `TryEnter` will only return false if you specify a timeout. What exactly is that code trying to do? Without more context, it isn't entirely clear what the `PulseAll` and `Wait` are designed to do; for example, [here](https://stackoverflow.com/questions/530211/creating-a-blocking-queuet-in-net/530228#530228) they are used to block the queue when it is too full (`Wait`), or release it when space becomes available (`PulseAll`), etc. It is hard to debug threading code without the full interactions between threads. It sounds like you might just need: ``` lock (lockObject) { // do stuff } ``` --- There are two immediate problems I can see; first, it isn't obvious that you always release the locks you take (i.e. exceptions). Try to just use `lock` for the `Enter/Exit` - it'll get it right. Second; if all the threads call `Wait`... who is going to wake them up? What are they waiting **for**? As presented: yes, they will all sleep indefinitely.
I'm assming the first lock statement is a typo and you meant lock(lockObject) (lowercase). I think you're misunderstanding locks a bit here. The if block in your code won't ever be true. The reason why is that lock(lockObject) actually exapands to the following ``` Monitor.Enter(lockObject); try { ... } finally{ Monitor.Exit(lockObject); ``` So by the time you hit the if block you already own the lock and TryEnter should always succeed.
C# Multithreading issue with Monitor-class - possible lifelock?
[ "", "c#", "multithreading", "deadlock", "monitor", "" ]
Going to create a small game with OpenGL as a side project. Going to be a top down shooter with emphasis on large numbers of enemies (the more the merrier) Thinking about having the resolution max out at 800x600 (for an old school feel) What language would you recommend, is C# capable of handling the number of entities I want on screen (60-100) or should I try out C or C++ or even some other language. Do you have any other suggestions when going for a project like this, special documentation you recommend etc.
C# is easily capable of handling a few hundred objects at once. The real speed issues come from rendering, which will not be in C# space, and possibly any computation you want to be done for each object, such as physics. Ideally you'd be using a library such as Box2D or Chipmunk for that anyway, making C# speed a non-issue there as well. I'd personally be willing to write a game such as this in even-higher level languages than C#. C# should easily suffice.
On the scripting languages tip, consider the excellent Pygame in python: <http://www.pygame.org/news.html> Or the newer LÖVE in Lua <http://love2d.org/> For a top-down shooter both are probably excellent choices.
OpenGL game with multiple entities on screen at once, what language to use?
[ "", "c#", "opengl", "programming-languages", "" ]
In the L2S designer I have dropped a table and a view. I tried adding an association between the 2 on their primary keys. This should be a one-to-one relationship, so I set the cardinality property of the association as such. But, when coding I can't access the child property. Any suggestions? # Edit I just created a view in sql server that has the fields I want, and dropped that into L2S. Much simpler.
In my experience Linq To SQL requires the Primary/Foreign key relationships established in the DB. Otherwise, you'll have to do a join. Not sure if this applies to your situation, but it may... [Linq To SQL Without Explicit Foreign Key Relationships](https://stackoverflow.com/questions/619231/linq-to-sql-without-explicit-foreign-key-relationships) **UPDATE:** It appears that you can get what you're looking for without establishing the Primary/Foreign key relationships in the database. In the LinqToSQL designer set primary keys on both columns on each table. I also had to turn off Auto-Sync on Parent Table's column that I assigned as a primary key. Auto-Sync is described here.. *Instructs the common language runtime (CLR) to retrieve the value after an insert or update operation.* Link: <http://msdn.microsoft.com/en-us/library/bb386971.aspx>
We had this problem with views. We simply defined the keys in the DBML editor and the property was finally defined.
LINQ to SQL - Problem with 1-to-1 association
[ "", "c#", "linq", "linq-to-sql", "oop", "orm", "" ]
I'd like to have a simple helper method for converting a string to an Enum. Something like the following, but it doesn't like T as the first argument in the Enum.Parse. The error is T is a Type Parameter but is used like a variable. ``` public static T StringToEnum<T>(String value) { return (T) Enum.Parse(T,value,true) ; } ```
Try this: ``` public static T StringToEnum<T>(String value) { return (T)Enum.Parse(typeof(T), value, true); } ```
``` public static T StringToEnum<T>(String value) { return (T) Enum.Parse(typeof(T),value,true) ; } ``` What you were doing is like using 'int' as a Type, but it is not a Type object. To get the Type object, you would use typeof(int).
C#, StringToEnum, can I make it a generic function out of this
[ "", "c#", "" ]
Is there any way that I could specify at runtime the configuration file I would like to use (other than App.config)? For example I would like to read a first argument from a command line that will be a path to the application's config and I would like my application to refer to it when I use ConfigurationManager.AppSettings (It's probably impossible but still it's worth asking). I did find this piece of code: ``` System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.File = myRuntimeConfigFilePath; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); ``` It works, but it overrides the original App.config's AppSettings section and my application isn't supposed to write anything.
I found this and it works. "path" is a path to configuration file. ``` AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path); ```
Not directly. Indirectly, you could: * spin up a second `AppDomain`, specify the config-file for that ([`AppDomainSetup.ConfigurationFile`](http://msdn.microsoft.com/en-us/library/system.appdomainsetup.configurationfile.aspx)), and execute the code in the app domain * have two exes; the first (`foo.exe`) simply copies the config (into `bar.exe.config`) and shells the 2nd exe (`bar.exe`) [warning: thread race]
.NET own configuration file
[ "", "c#", ".net", "app-config", "" ]
I'm using the code below to read a text file that contains foreign characters, the file is encoded ANSI and looks fine in notepad. The code below doesn't work, when the file values are read and shown in the datagrid the characters appear as squares, could there be another problem elsewhere? ``` StreamReader reader = new StreamReader(inputFilePath, System.Text.Encoding.ANSI); using (reader = File.OpenText(inputFilePath)) ``` Thanks **Update 1**: I have tried all encodings found under `System.Text.Encoding`. and all fail to show the file correctly. **Update 2**: I've changed the file encoding (resaved the file) to unicode and used `System.Text.Encoding.Unicode` and it worked just fine. So why did notepad read it correctly? And why didn't `System.Text.Encoding.Unicode` read the ANSI file?
Yes, it could be with the actual encoding of the file, probably unicode. Try UTF-8 as that is the most common form of unicode encoding. Otherwise if the file ASCII then standard ASCII encoding should work.
You may also try the Default encoding, which uses the current system's ANSI codepage. ``` StreamReader reader = new StreamReader(inputFilePath, Encoding.Default, true) ``` When you try using the Notepad "Save As" menu with the original file, look at the encoding combo box. It will tell you which encoding notepad guessed is used by the file. Also, if it is an ANSI file, the detectEncodingFromByteOrderMarks parameter will probably not help much.
C# Help reading foreign characters using StreamReader
[ "", "c#", "encoding", "" ]
Couldn't creatively shorten the title :) I have been using a variation of the below solution, however I always wondered if there is a better/cleaner way to implement it. I am looking for non-boost solution. We can, though, look at the implementation of boost and C++0x, as it will soon be relevant. ``` //Notice the use of template template parameter template <template <typename> class Callback> class A { Callback <A> m_func; public: A (Callback <A> func): m_func (func) {} void call () { m_func(*this);} }; template <typename T> struct MYCallback { void operator () (const T&t) {} }; void Test() { typedef A<MYCallback> AType; MYCallback<AType> callback; AType a (callback); a.call (); } ``` Another, a more suncinct way, is to use tr1::function, which will become defuct-to with new standardization: ``` #include <tr1/functional> class A { std::tr1::function <void (const A&)> m_func; public: template <class Callback> A (Callback func) : m_func (func) {} void call () { m_func(*this);} }; template <class T> struct My_callback { void operator () (const T&t) {} }; void Test () { My_callback <A> c; A a (c); a.call (); } ```
If you're just looking for clean-up advice, I'd suggest making 'My\_callback' a normal class, not a class template. There's not obvious need for it to be a template in this case. Instead, make its apply operator templated or fill in A directly if My\_callback only deals with A instances: ``` #include <tr1/functional> class A { std::tr1::function <void (const A&)> m_func; public: template <class Callback> A (Callback func) : m_func (func) {} void call () { m_func(*this);} }; struct My_callback { template <class T> void operator () (const T&t) {} }; int main () { My_callback c; A a (c); a.call (); } ``` Otherwise, It looks pretty good as is. Could you be more specific in how you hope to clean it up or simplify it?
I always believe that void\* is your friend when you want elegance in these things.
How to pass and then invoke generic callback functions without causing circular dependency
[ "", "c++", "boost", "callback", "" ]
I have tested this on Firefox, Opera and Seamonkey. It works fine. When it comes to Internet Explorer 7. It works but upto a certain point. I am making an AJAX call to a PHP script every few seconds. In IE7 it makes the first AJAX call and it retrieves the data but it doesn't do it again ever. Even though i have a setTimeout function in the else block. **WHY?** :( ``` startTime = setTimeout('getStatus()', 5000); }//function convertNow ``` function getStatus() { ``` $.ajax({ type: "GET", url: "fileReader.php", data: 'textFile=' + fileNameTxt, success: function(respomse){ textFileResponse = respomse.split(" "); $("#done").html("Downloading & Converting Video...<b style='font-size:17px;color:green;'>" + textFileResponse[0] + "</b><br /><b>" + properFileName + '</b>'); } });//ajax if(textFileResponse[0]=='100.0%'){ } else{ continueTime = setTimeout('getStatus();', 3000); alert('call end'); } ``` } Apologies if any frustration comes through this question. I've been running around like a headless chicken for the past 3 hours. Thank you for any help. ## EDIT 2 I have added the full function. The setTimeout seems to be working correctly. It must be the AJAX call, am just checking what is being returned. Even stranger! It keeps returning the same value from the AJAX request and its not getting any newer values!! I think Answer 2 might have something.It may be due with cache but how do you over come that?
Are you requesting the ajax call via HTTP GET as opposed to HTTP POST? IE tends to use cached results of ajax calls unless you use POST instead of GET. EDIT: Since you've updated your question, I can see that you are indeed using the GET verb. Change it to POST and I bet your issue will be resolved.
Not at all sure on this but are you missing the `;`? from: ``` setTimeout('getStatus()', 3000); ``` to: ``` setTimeout('getStatus();', 3000); ```
Wtf IE7 - AJAX calls using setTimeout
[ "", "javascript", "jquery", "ajax", "internet-explorer", "" ]
Working on .NET gives me good performance in general for the application itself but the initial load times for my application are quite large. A lot of it goes towards loading assemblies which is difficult to gauge. **Are there any optimizations that I can apply to my assemblies to make them faster to load without involving the GAC or Ngen and those are not available for ClickOnce?** This is a WinForms 2.0 project. I can upgrade it to a 3.5 but that limit my user base. I have .NET Framework 3.5 installed on my machine.
I have created a very small .exe that shows a splash screen asap. After that I initialize everything. The JIT-compiler loads modules that are called from the method that is being jitted. So you have to take care that the method that shows the splash screen, does not call methods in modules that you do not want loaded yet. Example: ``` internal sealed class Startup { // Call Startup.Run() from Program.Main to start the application internal void Run() { this.ShowSplash(); this.ContinueStartup(); } private void ShowSplash() { _splash = new Splash(); _splash.Show(); Application.DoEvents(); } [MethodImpl(MethodImplOptions.NoInlining)] private void ContinueStartup() { // Do the startup here } } ``` The [MethodImpl(MethodImplOptions.NoInlining)] is needed so the ContinueStartup() method does not get inlined by the jit, because that will cause the modules to be loaded too early.
You can use ILMerge to merge all your assemblies into one file. Reading one file into memory is faster then reading 10 files. Although I doubt you will see real improvement in load speed there. You can also remove all the references to other assemblies, load the ui to the user, and while he uses the UI (typing or something else) preload all the needed assemblies using Assembly.Load, get all the needed function pointers using reflection and store them in internal members. This way application will load much faster. But I don't think any sane person will do optimization like this.
.NET Application Load Optimizations
[ "", "c#", ".net", "cold-start", "" ]
As mentioned in [the docs](http://docs.python.org/library/optparse.html?highlight=indentedhelpformatter#creating-the-parser) the `optparse.OptionParser` uses an `IndentedHelpFormatter` to output the formatted option help, for which which I found some [API documentation](http://corebio.googlecode.com/svn/tags/0.5.0/apidocs/optparse.IndentedHelpFormatter-class.html). **I want to display a similarly formatted help text for the required, positional arguments** in the usage text. Is there an adapter or a simple usage pattern that can be used for similar positional argument formatting? ### Clarification Preferably only using the stdlib. Optparse does great except for this one formatting nuance, which I feel like we should be able to fix without importing whole other packages. :-)
The best bet would be to write a patch to the optparse module. In the meantime, you can accomplish this with a slightly modified OptionParser class. This isn't perfect, but it'll get what you want done. ``` #!/usr/bin/env python from optparse import OptionParser, Option, IndentedHelpFormatter class PosOptionParser(OptionParser): def format_help(self, formatter=None): class Positional(object): def __init__(self, args): self.option_groups = [] self.option_list = args positional = Positional(self.positional) formatter = IndentedHelpFormatter() formatter.store_option_strings(positional) output = ['\n', formatter.format_heading("Positional Arguments")] formatter.indent() pos_help = [formatter.format_option(opt) for opt in self.positional] pos_help = [line.replace('--','') for line in pos_help] output += pos_help return OptionParser.format_help(self, formatter) + ''.join(output) def add_positional_argument(self, option): try: args = self.positional except AttributeError: args = [] args.append(option) self.positional = args def set_out(self, out): self.out = out def main(): usage = "usage: %prog [options] bar baz" parser = PosOptionParser(usage) parser.add_option('-f', '--foo', dest='foo', help='Enable foo') parser.add_positional_argument(Option('--bar', action='store_true', help='The bar positional argument')) parser.add_positional_argument(Option('--baz', action='store_true', help='The baz positional argument')) (options, args) = parser.parse_args() if len(args) != 2: parser.error("incorrect number of arguments") pass if __name__ == '__main__': main() ``` And the output you get from running this: ``` Usage: test.py [options] bar baz Options: -h, --help show this help message and exit -f FOO, --foo=FOO Enable foo Positional Arguments: bar The bar positional argument baz The baz positional argument ```
Try taking a look at [argparse](https://docs.python.org/3/library/argparse.html). Documentation says it supports position arguments and nicer looking help messages.
How do I format positional argument help using Python's optparse?
[ "", "python", "command-line", "formatting", "command-line-arguments", "optparse", "" ]
I am trying to parse two values from a datagrid. The fields are numeric, and when they have a comma (ex. 554,20), I can't get the numbers after the comma. I've tried `parseInt` and `parseFloat`. How can I do this?
If they're meant to be separate values, try this: ``` var values = "554,20".split(",") var v1 = parseFloat(values[0]) var v2 = parseFloat(values[1]) ``` If they're meant to be a single value (like in French, where one-half is written 0,5) ``` var value = parseFloat("554,20".replace(",", ".")); ```
Have you ever tried to do this? :p ``` var str = '3.8';ie alert( +(str) + 0.2 ); ``` +(string) will cast string into float. Handy! So in order to solve your problem, you can do something like this: ``` var floatValue = +(str.replace(/,/,'.')); ```
How to convert string into float in JavaScript?
[ "", "javascript", "parsing", "floating-point", "" ]
Say I have 2 methods. One is an method triggered by the selected index changing in the listbox. The second method helps by clearing all textboxes, setting listbox index to -1, and setting the focus. Question: Method two executes, during the code it changes the selected index of the listbox to -1, thereby setting off the event trigger for the 1st method. Does Method 2 HALT it's own execution and transfer the process to the event, and then return back to its work after Method 1 is finished... OR does method 2 finish its entire codeblock then transfer to Method 1 since the selected index changes?
The first case. Let's leave threads out of it for a moment, particularly because they're not involved in your scenario. You're talking about properties and methods, but underneath it all, it's all just functions. When one function invokes another, control in your program transfers to the called function. When that function finishes running, control *returns* to the point where it was called. Your program automatically remembers where it needs to go back to, no matter how deeply functions call more functions.`*` When your second function sets the index, what really happens is that the compiler translates the property-set operation into a function call. (Properties are ultimately just "syntactic sugar" for functions.) That function calls a bunch of other functions that aren't important to the scenario, except that one of them is the one that invokes the "index changed" event handler. It sees that you have a method associated with that event, and it calls your first method. Your first method runs, and when it finishes, it returns to the "invoke the index-changed event handler" function. Eventually, that and all the other unimportant functions finish running (perhaps after making more function calls in sequence), and the "set the index property" function returns control to your second method. You can prove to yourself that your first suggestion is how it works. Display a message box in your first method, and display another message box *after* the point in your second method where you set the index property. (Use different messages!) You should see the first message appear, and after you dismiss the message box, you should see the second message appear, thus showing that the second method did not continue executing while the first one was running. `*` There *is* a limit, but it's rarely hit unless there's a bug in your program. When you have too many nested function calls, what happens is a *stack overflow*.
Assuming no multi-thread situation, the event will fire before he end of execution of the method. If you want to see this, code what you have suggested in a .NET language and examine the Il produced. You can do this with ILDASM, or Reflector, or even create your own relfletion application. You do have to understand the syntax of IL enough to see the branch, but it is not that difficult, as long as you understand programming concepts. Rob has labeled this "syntactical sugar", which I will agree with somewhat. It is really a compiler trick, but I guess it falls under the label "syntactical sugar" as it is commonly used.
Order of Precedence with methods?
[ "", "c#", "listbox", "operator-precedence", "method-call", "" ]
I've crossed this problem in, oh, every application I've ever written. I'd like a final consensus answer! Is this the most normalized/efficient/proper way to store contact methods or any other data along this pattern in a database? ``` Contact { PK ContactId, ... } ContactContactMethod {PK FK ContactId, PK FK ContactMethodId, Key, Comments } AddressContactMethod {PK FK ContactMethodId, Line1, Line2, City, State, Zip } EmailContactMethod {PK FK ContactMethodId, EmailAddress } InstantMessengerContactMethod {PK FK ContactMethodId, IMClient, IMAddress } PhoneContactMethod {PK FK ContactMethodId, ... } WebsiteContactMethod {PK FK ContactMethodId, ... } OtherContactMethod {PK FK ContactMethodId, ... } ``` Should I consider an Xml field for `ContactMethodData` on the `ContactContactMethod` table instead? Something just feels wrong about AddressContactMethod, EmailContactMethod, etc all sharing the same uniqueness of primary keys. Also thought about a key, value pair for contact data, but that would be even more of a pain to query than the Xml field. (Design guidelines: each contact may have more than one or none of each type of contact method, each with a non-unique "key" like "home, work, red car, etc" and comments but no other shared data elements between types)
Like you, I've seen more than my share of contact information database designs. I think yours is pretty reasonable, and locating the Key column separately from the \*Method tables is a nice touch, allowing grouping of "home" e-mail and postal addresses to be grouped after a fashion. However, I think most contact databases are over-architected. While I don't agree with Chris Lively's approach, I think you could simplify by just having types of contact information (e-mail, phone, web url, etc) and storing a simple text string for each. Trying to validate the separate types or breaking them up into sub-fields isn't usually worth the effort. For one thing, all telephone and address validation rules immediately go out the window if you allow for contacts outside of the US. Store the full address in a Unicode string, and hope for the best is my advice. That leaves a design something like this: ``` Contact { PK ContactId, ... } ContactType { PK ContactTypeId, ContactType } ContactMethod {PK FK ContactId, PK FK ContactTypeId, PK Key, Value, Comments } ``` The ContactMethod.Value is the text value. That seems similar to how Google tracks contacts at the very least. And if nothing else, they've likely thought through the problem of keeping track of zillions of contacts from every nation on Earth.
There is a name for this pattern. It's called "specialization generalization". In this case Contact Methods are specialized ways of contacting a Contact. A web search on "generalization specialization relational design" will lead you to some articles dealing with this pattern in a more general fashion. For an object orineted view of the same pattern, search on "generalization specialization object design".
How may I store contact methods (or similar typed data with different fields) in a normalized way?
[ "", "sql", "sql-server", "database", "database-design", "normalization", "" ]
Okay, so if I had a project that used: ``` import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Dimension; import java.awt.Font; import java.awt.Color; import java.awt.Polygon; ``` Would it make the Class file smaller to use: ``` import java.awt.* ``` I'm thinking against it because I'm importing a lot of things I don't need. I'm thinking for it cause it makes the file have a lot less characters.
No difference. These are a compile-time construct only.
No, there is no difference at all. According to [The Java Virtual Machine Specifications, Second Edition](http://java.sun.com/docs/books/jvms/second_edition/html/VMSpecTOC.doc.html), [Chapter 5: Loading, Linking and Initializing](http://java.sun.com/docs/books/jvms/second_edition/html/ConstantPool.doc.html) says the following: > The Java virtual machine dynamically > loads (§2.17.2), links (§2.17.3), and > initializes (§2.17.4) classes and > interfaces. Loading is the process of > finding the binary representation of a > class or interface type with a > particular name and creating a class > or interface from that binary > representation. Linking is the process > of taking a class or interface and > combining it into the runtime state of > the Java virtual machine so that it > can be executed. At compile time, there are no linking of classes, therefore, using wildcards for `import`ing makes no difference. Other classes are not included together into the resulting `class` file. In fact, if you look at the bytecode of the `class` file (via [`javap`](http://java.sun.com/javase/6/docs/technotes/tools/windows/javap.html) or such disassembler), you won't find any `import` statements, so having more or less numbers of `import` statements in your source won't affect the size of the `class` file. Here's a simple experiment: Try writing a program, and compiling with `import`s using wildcards, and another one with explicit imports. The resulting `class` file should be the same size. --- Using explicit `import` statements on specific classes are perhaps less readable (and troublesome, if one doesn't use an IDE like Eclipse which will write it for you), but will allow you to deal with overlaps of class names in two packages. For example, there is a `List` class in both the [`java.util`](http://java.sun.com/javase/6/docs/api/java/util/List.html) and [`java.awt`](http://java.sun.com/javase/6/docs/api/java/awt/List.html) packages. By importing both packages, there will be a conflict for the class named `List`: ``` import java.util.*; import java.awt.*; // ... snip ... // List l; // which "List" are we talking about? ``` By only importing the specific classes you need, these conflicts could be somewhat avoided: ``` import java.util.Hashmap; import java.awt.List; // .. snip ... // List l; // Now we know for sure it's java.awt.List ``` Of course, if you had to use both `java.util.List` and `java.awt.List` then you're out of luck; you'll need to explicitly use their fully-qualified class names.
Which would make a Class file bigger? import java.awt.*, or a bunch or single import statements?
[ "", "java", "class", "import", "size", "" ]
This question stems from watching [Rasmus Lerdorf's talk from Drupalcon](http://www.archive.org/details/simple_is_hard). This question and his talk have nothing specifically to do with Drupal, by the way... it was just given at their con. My own question also has nothing specific to do with PHP. It is the single entry point in general that I am curious about. These days it seems that most frameworks offer a single entry point for whatever you build with them. In his talk Rasmus mentions that he thinks this is bad. It seems to me that he would be correct in this thinking. If everyone hitting the site is coming in through the same entry point wouldn't things bog down after traffic reached a certain point? Wouldn't it be more efficient to allow people direct access to specific points in a site without having their request go through the same point? But perhaps the actual impact is not very bad? Maybe modern architecture can handle it? Maybe you have to be truly gigantic in scale before it becomes even worth considering? I'm curious as to what people on this site think about this issue.
In short, Rasmus or the interpretation is wrong. This shows a clear lack of understanding how computers work. The more something gets used, the more likely it's closer to the CPU, and therefore **faster**. Mind you, a single point of entry != single point of failure. But that's all beside the point, when people say single point of entry, we're talking about the app, it is a single point of entry for your logic. Not to mention it's architecturally brain-dead not to have a central point of entry, or reduce the number of entries points in general. As soon as you want to do one thing across your app at every entry point, guess how many places need to change? Having dealt with an app that each page stood on it's own, it sucked having to change, and I assure you, we needed it.
The important thing is that you use a web framework that supports scalability through methods like load-balancing and declarative code. No, a single-entry point does not in itself make a bottleneck. The front page of Google gets a lot of hits, but they have lots of servers. So the answer is: It doesn't matter.
Having a single entry point to a website. Bad? Good? Non-issue?
[ "", "php", "model-view-controller", "" ]
I wrote an application and its WiX installer and put it under version control using subversion. When the WiX installer builds I want its version number to be the current build version of the application. How do I accomplish this? I used c# to code the application. N.B. I am using ccnet to build this project
You could use `Product/@Version="!(bind.FileVersion.FileId)"` (replace `FileId` with the `Id` of the file from which you'd like to get the version number) and light.exe will populate the value with the version of the file referenced by the `FileId`. See the [WiX v3 documentation for all the available variables](https://wixtoolset.org/docs/v3/overview/light/#binder-variables).
In case someone is looking for an actual XML example, this works with .NET assemblies (and you don't have to do the Assembly or KeyPath attributes). I eliminated unrelated code with [...] place holders: ``` <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> <Product [...] Version="!(bind.fileVersion.MyDLL)"> [...] <Directory Id="TARGETDIR" Name="SourceDir"> <Directory Id="ProgramFilesFolder" Name="PFiles"> <Directory Id="INSTALLDIR" Name="MyDLLInstallLocation"> <Component Id="MainLib" Guid="[...]"> <File Id="MyDLL" Name="MyDll.dll" Source="MyDll.dll" /> [...] </Component> [...] </Directory> </Directory> </Directory> </Product> </Wix> ```
How can I set the WiX installer version to the current build version?
[ "", "c#", "svn", "wix", "" ]
Is it possible to have variable-height rows within a WinForms ListView in Details mode? There is no RowHeight or Rows[i].Height property on the control as far as I know. Some blogs suggests implementing OwnerDraw, which I did, but I still can't find anything resembling height property from within the event handlers. Ideally, the row height would auto-size to show multiline text when needed.
One option to think of: To override the item height of all rows, create a dummy ImageList and set it to the desired height and assign it to the listview depending on the view or grasp the concept of <http://www.codeproject.com/KB/list/changerowheight.aspx> If you use [ObjectListView](http://objectlistview.sourceforge.net/cs/features.html), you can change the item height of all rows pretty [easily](http://objectlistview.sourceforge.net/cs/features.html#row-height-can-be-changed). But still, there is no way to change the individual item height as long as you are using ListView.
If you are using details mode, I wonder if `DataGridView` wouldn't be more versatile. Each row has a Height, or you can use AutoSizeRowsMode to do it automatically. See [MSDN](http://msdn.microsoft.com/en-us/library/ms171604.aspx) "Resizing Columns and Rows in the Windows Forms DataGridView Control".
Variable height rows in WinForms ListView
[ "", "c#", ".net", "winforms", "listview", "" ]
I want to create a generic to which I can pass a function as a parameter, however this function may include parameters itself so... ``` int foo = GetCachedValue("LastFoo", methodToGetFoo) ``` Such that: ``` protected int methodToGetFoo(DateTime today) { return 2; // example only } ``` Essentially I want to have a method that will check the cache for a value, otherwise will generate the value based on the passed in method. Thoughts?
It sounds like you want a `Func<T>`: ``` T GetCachedValue<T>(string key, Func<T> method) { T value; if(!cache.TryGetValue(key, out value)) { value = method(); cache[key] = value; } return value; } ``` The caller can then wrap this in many ways; for simple functions: ``` int i = GetCachedValue("Foo", GetNextValue); ... int GetNextValue() {...} ``` or where arguments are involved, a closure: ``` var bar = ... int i = GetCachedValue("Foo", () => GetNextValue(bar)); ```
Use `System.Action` and a lambda expression (anonymous method). For example: ``` public void myMethod(int integer) { // Do something } public void passFunction(System.Action methodWithParameters) { // Invoke methodWithParameters(); } // ... // Pass anonymous method using lambda expression passFunction(() => myMethod(1234)); ```
Passing a Function (with parameters) as a parameter?
[ "", "c#", "parameters", "delegates", "" ]
I'm using quite much STL in performance critical C++ code under windows. One possible "cheap" way to get some extra performance would be to change to a faster STL library. According to this [post](http://garrys-brain.blogspot.com/2007/01/development-stlport-versus-microsoft.html) STLport is faster and uses less memory, however it's a few years old. Has anyone made this change recently and what were your results?
I haven't compared the performance of STLPort to MSCVC but I'd be surprised if there were a *significant* difference. (In release mode of course - debug builds are likely to be quite different.) Unfortunately the link you provided - and any other comparison I've seen - is too light on details to be useful. Before even considering changing standard library providers I recommend you heavily profile your code to determine where the bottlenecks are. This is standard advice; always profile before attempting any performance improvements! Even if profiling does reveal performance issues in standard library containers or algorithms I'd suggest you first analyse *how you're using them*. Algorithmic improvements and appropriate container selection, especially considering Big-O costs, are *far more* likely to bring greater returns in performance.
Before making the switch, be sure to test the MS (in fact, Dinkumware) library with [checked iterators](http://www.codeproject.com/KB/stl/checkediterators.aspx) turned off. For some weird reason, they are turned on by default even in release builds and that makes a big difference when it comes to performance.
Switch from Microsofts STL to STLport
[ "", "c++", "windows", "visual-studio", "performance", "stl", "" ]
I am wondering if there are any differences to derived classes when using abstract vs real classes for inheritance? It looks to me like the real class inheritance creates an hierarchy whereas abstract class inheritance is just copy-paste code for the compiler to derived classes? Does the abstract class creates a hierarchy? Can it be accessed using a special keyword? I know that you use the base keyword to access the base class, but abstract members look just like the original members in the derived classes? Lastly what's the performance difference between the 2?
Yes the abstract class does exist - the compiler does not do a copy-paste. You will not find any performance difference though as the CLR must still do virtual method calls. For example the following C#: ``` abstract class Foo { } class Bar : Foo { } ``` generates the following IL: ``` .class private abstract auto ansi beforefieldinit Foo extends [mscorlib]System.Object { } .class private auto ansi beforefieldinit Bar extends Foo { } ``` The concept of an abstract type is very much a part of the IL.
The only difference is that an abstract base class cannot be instantiated without being derived from, whereas a non-abstract one can. From the point of view of a derived class, everything is the same.
Abstract vs real class inheritance in C#
[ "", "c#", ".net", "inheritance", "class", "" ]
I want to build a small ORM ([Object Relational Mapping](http://en.wikipedia.org/wiki/Object-relational_mapping)) framework in PHP. I want to do a mixture of an MVC approach, with the same controller/method/variable approach used by CodeIgniter. There are a few frameworks out there already which do this, but things like * Form validation * Pagination * CRUD * And AJAX are very difficult to do in these frameworks. My main goal, other than to have the entire functioning of the system be done using objects, is to use the DRY principle as much as possible. This mainly means very little repetitive code for form validation and CRUD etc. I'm looking for ideas on how such a framework would be organized, what the architecture would be, and how a typical request such as a signup form and how to validate it, would be handled by this framework. Please share your thoughts/ideas. This will be released as an open source framework, free of charge, when its finished.
I would probably suggest that rather than building your validation rules around forms (ala Zend Framework), you should build the validation within your domain objects. Then submit your form data directly to the domain object for validation. I am using Zend Framework, but I use this basic structure for my validation needs: ``` /** * Contains the domain object properties. * @var array */ protected $_data = null; /** * @var array */ protected $_filters = null; /** * @var array */ protected $_validators = null; public function validate($data = null) { if(!$data) { $data = (array) $this->_data; } else { $data = array_merge((array) $this->_data, $data); } $this->_input = new Zend_Filter_Input($this->_filters, $this->_validators, $data, $options); $this->_input->addValidatorPrefixPath('LP_Validate_', 'LP/Validate/'); $this->_input->addFilterPrefixPath('LP_Filter_', 'LP/Filter/'); if($this->_input->isValid()) { $this->_data = (object) $this->_input->getEscaped(); return true; } else { $this->_data = (object) $data; return false; } } ``` Some of the limitations with my current approach with validation is that I can't call any necessary custom setters on the object properties and the fact that I need to figure out a way to keep the original data for the object available after running the validate function. But otherwise it has worked well so far. As far as CRUD is concerned, the answer depends in part on the complexity of the problems you want to address and in part on what patterns you are familiar with and do/don't like and do/don't want to try to implement. Obviously the most robust design to implement is to use Data Mapper with separate Domain Objects sitting on top. However, in most cases this is overkill and so you could just use the much (inappropriately) maligned Active Record pattern. This is basically what CodeIgniter and Zend Framework have done with what they have provided. I ended up having to construct a custom ORM layer that uses the Data Mapper pattern because I needed to handle cases of Inheritance Mapping in my design and its worked pretty slick but I do regret losing the metadata mapping functionality that came with the Table and Row Gateway implementations in Zend Framework. (If you could find a way to effectively create metadata mapping using data mappers I want you to show me how you did it. :P). Even though you are trying to build your own, you might consider looking at Zend Framework as it has some of the finest PHP code I've seen and follows standard design patterns very closely. One thing that would be nice to see in a Pagination class would be the ability to tie directly to a database object in such a way that the limit clause can be applied to the query based on what range of values the page should display. Otherwise, the key components with pagination are to keep track of current page, number of records to display per page, and some sort of collection object that contains the values to be iterated over. At the very least though, you want to make certain that you don't preload the entire collection and then only display a certain range of records as this will provide a huge performance hit. As far as Ajax requests are concerned, I would suggest building in some sort of context helper that can check for whether an HTTP Request is an XHR or not and then handling it specifically based on that context.
There are a lot of good open source frameworks out there that accomplish what you are looking to do much more easily and quickly than writing one from scratch! Having said that, I had an MVC framework that I developed that taught me a lot about framework development and object-oriented design. It is recommended if you have a lot of time and want to do it as a learning experiment (which may end with a pretty good framework). As far as your idea of an ORM framework ... I think there may be some confusion about what ORM is. ORM is a technique that maps your objects to your relational database, handling retrieval and storage of data. It is usually one component in a larger framework, and does not necessarily characterize the framework itself. Most people throw around MVC framework, for the basic Model-View-Controller architecture on which an application can be built. Some PHP frameworks provide more out-of-the box functionality, such as what you are interested in doing. So, there are other threads on this, but I would say, build your own framework if you have time and want to learn. Use one of the many existing frameworks if you want to do something as easily as possible and in the shortest amount of time.
How would an ORM framework in PHP be structured?
[ "", "php", "orm", "oop", "frameworks", "" ]
Some time ago I had to address a certain C# design problem when I was implementing a JavaScript code-generation framework. One of the solutions I came with was using the “using” keyword in a totally different (hackish, if you please) way. I used it as a syntax sugar (well, originally it is one anyway) for building hierarchical code structure. Something that looked like this: ``` CodeBuilder cb = new CodeBuilder(); using(cb.Function("foo")) { // Generate some function code cb.Add(someStatement); cb.Add(someOtherStatement); using(cb.While(someCondition)) { cb.Add(someLoopStatement); // Generate some more code } } ``` It is working because the Function and the While methods return IDisposable object, that, upon dispose, tells the builder to close the current scope. Such thing can be helpful for any tree-like structure that need to be hard-codded. Do you think such “hacks” are justified? Because you can say that in C++, for example, many of the features such as templates and operator overloading get over-abused and this behavior is encouraged by many (look at boost for example). On the other side, you can say that many modern languages discourage such abuse and give you specific, much more restricted features. My example is, of course, somewhat esoteric, but real. So what do you think about the specific hack and of the whole issue? Have you encountered similar dilemmas? How much abuse can you tolerate?
I think this is something that has blown over from languages like Ruby that have much more extensive mechanisms to let you create languages within your language (google for "dsl" or "domain specific languages" if you want to know more). C# is less flexible in this respect. I think creating DSL's in this way is a good thing. It makes for more readable code. Using blocks can be a useful part of a DSL in C#. In this case I think there are better alternatives. The use of using is this case strays a bit too far from its original purpose. This can confuse the reader. I like Anton Gogolev's solution better for example.
Offtopic, but just take a look at how pretty this becomes with lambdas: ``` var codeBuilder = new CodeBuilder(); codeBuilder.DefineFunction("Foo", x => { codeBuilder.While(condition, y => { } } ```
Ab-using languages
[ "", "c#", "using-statement", "" ]
I have something like this: ``` var itemsInCart = from o in db.OrderLineItems where o.OrderId == currentOrder.OrderId select new { o.OrderLineItemId, ..., ..., o.WishListItem.Price} ``` is there any way to do a ``` itemsCart.Sum() //not sure what to pass into the function ``` to get the sum of o.WishListItem.Price or do i have to get another iQueryable< T> from the database with group ... into?
What about: ``` itemsInCart.AsEnumerable().Sum(o=>o.Price); ``` [AsEnumerable](http://www.hookedonlinq.com/AsEnumerableOperator.ashx) makes the difference, this query will execute locally (Linq To Objects).
you can: itemsCart.Select(c=>c.Price).Sum(); To hit the db only once do: ``` var itemsInCart = (from o in db.OrderLineItems where o.OrderId == currentOrder.OrderId select new { o.OrderLineItemId, ..., ..., o.WishListItem.Price} ).ToList(); var sum = itemsCart.Select(c=>c.Price).Sum(); ``` The extra round-trip saved is worth it :)
Linq to SQL .Sum() without group ... into
[ "", "c#", "linq-to-sql", ".net-3.5", "" ]
I'm toying with Zend Framework and trying to use the "QuickStart" guide against a website I'm making just to see how the process would work. Forgive me if this answer is obvious, hopefully someone experienced can shed some light on this. I have three database tables: ``` CREATE TABLE `users` ( `id` int(11) NOT NULL auto_increment, `email` varchar(255) NOT NULL, `username` varchar(255) NOT NULL default '', `first` varchar(128) NOT NULL default '', `last` varchar(128) NOT NULL default '', `gender` enum('M','F') default NULL, `birthyear` year(4) default NULL, `postal` varchar(16) default NULL, `auth_method` enum('Default','OpenID','Facebook','Disabled') NOT NULL default 'Default', PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`), UNIQUE KEY `username` (`username`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 CREATE TABLE `user_password` ( `user_id` int(11) NOT NULL, `password` varchar(16) NOT NULL default '', PRIMARY KEY (`user_id`), UNIQUE KEY `user_id` (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 CREATE TABLE `user_metadata` ( `user_id` int(11) NOT NULL default '0', `signup_date` datetime default NULL, `signup_ip` varchar(15) default NULL, `last_login_date` datetime default NULL, `last_login_ip` varchar(15) default NULL, PRIMARY KEY (`user_id`), UNIQUE KEY `user_id` (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 ``` I want to create a User model that uses all three tables in certain situations. E.g., the metadata table is accessed if/when the meta data is needed. The user\_password table is accessed only if the 'Default' auth\_method is set. I'll likely be adding a profile table later on that I would like to be able to access from the user model. What is the best way to do this with ZF and why?
``` class Users extends Zend_Db_Table_Abstract { protected $_name = 'users'; protected $_rowClass = 'User'; protected $_dependentTables = array ('UserMetadata', 'UserPassword'); ... class UserMetadata extends Zend_Db_Table_Abstract { protected $_name = 'user_metadata'; protected $_referenceMap = array ( 'Users'=> array ( 'columns'=>'user_id', 'refTableClass'=>'Users', 'refColumns'=>'id' ) ); ... class UserPassword extends Zend_Db_Table_Abstract { protected $_name = 'user_password'; protected $_referenceMap = array ( 'Users'=> array ( 'columns'=>'user_id', 'refTableClass'=>'Users', 'refColumns'=>'id' ) ); ``` Fetching data: ``` $id = //get your user id from somewhere $users = new Users(); $user = $users->fetchRow('id=?', $id); if ($user->authMethod == 0) { $metadata = $user->findDependentRowset('UserMetadata')->current(); } ``` or ``` $user = $users->fetchRow($users->select() ->where('gender=?, 'M') ->order('email ASC'); ``` ... etc. Inserting data: ``` $newRow = $users->fetchNew(); $newRow->email = me@domain.com; $newRow->save(); ``` or ``` $users = new Users(); $data = array('email' => 'me@domain.com', 'firstname' => 'Me'); $users->insert($data); ``` Updating: ``` $user->email = 'me@domain.org'; $user->save(); ``` Deleting a row: ``` $user->delete(); ``` Using transaction: ``` $db->beginTransaction(); $db->commit(); $db->rollback(); ``` etc... it's all in the [ZF Manual](http://framework.zend.com/manual/en/)!
In a nutshell I would create a model for each table, not one model that accesses all three. I would then [define relationships](http://framework.zend.com/manual/en/zend.db.table.relationships.html) between the tables. To be honest it seems not very "DRY" to have to create a model for each table but that is what I see done repeatedly in the various examples online and it is what I have done in the handful of projects that I have created with the Zend Framework. If anyone has a better way of handling this I hope the will post it here.
Modeling objects with multiple table relationships in Zend Framework
[ "", "php", "zend-framework", "model", "" ]
How can I serialize an object to JSON in JavaScript?
You’re looking for [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). Examples: ``` const object = { hello: "world", "some array": [ 42, 69, 420, 1337, null, true ] }, primitive = false; console.log(JSON.stringify(object)); // "{\"hello\":\"world\",\"some array\":[42,69,420,1337,null,true]}" console.log(JSON.stringify(primitive)); // "false" ```
Download [`https://github.com/douglascrockford/JSON-js/blob/master/json2.js`](https://github.com/douglascrockford/JSON-js/blob/master/json2.js), include it and do ``` var json_data = JSON.stringify(obj); ```
Serializing an object to JSON
[ "", "javascript", "json", "" ]
I'm developing a puzzle game for windows mobile. The objetive is to split an image in nine parts and rearrage them to obtain the original image. These split images are put on pictureBoxes and these pictureBoxes are redistributed in a matrix of 3X3 cells. The user move this cells to arrange them in the correct position (it's a puzzle game!). I need something to access these pictureBoxes and to know where are they in the matrix. Suppose that I need to update the image on row 1, column 2 (it's only an example). In C++ I use pointers to reference object, but I don't know how to do it with C#. Any advice? Thanks!
Just create the matrix with objects that contain the reference to the PictureBox. ``` MyObject[,] layout = new MyObject[3,3]; public class MyObject { #region attributes private PictureBox pictureBox; #endregion public MyObject(PictureBox pictureBox) { this.pictureBox = pictureBox; } } ```
``` //This is a reference object MyCustomObject o1 = new MyCustomObject(imageUrl, row, col); ``` So from my example I am creating a custom object which holds the url of the image and also a row and column reference. I can then call: ``` int row = o1.Row; int col = o1.Col; string imageUrl = o1.ImageUrl; ``` You can then use how you wish. Hope this helps: Andrew
c# Matrix of pictureBox
[ "", "c#", "windows-mobile", "pointers", "" ]
I recently read the questions that recommend against using switch-case statements in languages that do support it. As far as Python goes, I've seen a number of switch case replacements, such as: 1. Using a dictionary (Many variants) 2. Using a Tuple 3. Using a function decorator (<http://code.activestate.com/recipes/440499/>) 4. Using Polymorphism (Recommended method instead of type checking objects) 5. Using an if-elif-else ladder 6. Someone even recommended the Visitor pattern (Possibly Extrinsic) Given the wide variety of options, I am having a bit of difficulty deciding what to do for a particular piece of code. I would like to learn the criteria for selecting one of these methods over the other in general. In addition, I would appreciate advice on what to do in the specific cases where I am having trouble deciding (with an explanation of the choice). Here is the specific problem: (1) ``` def _setCurrentCurve(self, curve): if curve == "sine": self.currentCurve = SineCurve(startAngle = 0, endAngle = 14, lineColor = (0.0, 0.0, 0.0), expansionFactor = 1, centerPos = (0.0, 0.0)) elif curve == "quadratic": self.currentCurve = QuadraticCurve(lineColor = (0.0, 0.0, 0.0)) ``` This method is called by a **qt-slot** in response to choosing to draw a curve from a menu. The above method will contain a total of 4-7 curves once the application is complete. Is it justified to use a throw away dictionary in this case? Since the most obvious way to do this is if-elif-else, should I stick with that? I have also consider using \*\*kargs here (with a friends help) since all the curve classes use \*\*kargs... (2) This second piece of code is a **qt-slot** that is called when the user changes a property of a curve. Basically the slot takes the data from the gui (spinBox) and puts it in an instance variable of the appropriate curve class. In this case, I again have the same question - should I use a dict? Here is the aforementioned slot- ``` def propertyChanged(self, name, value): """A Qt slot, to react to changes of SineCurve's properties.""" if name == "amplitude": self.amplitude = value elif name == "expansionFactor": self.expansionFactor = value elif name == "startAngle": self.startAngle = value elif name == "endAngle": self.endAngle = value ``` For reference, here is the code for connecting to the above slot - ``` def _connectToPage(self, page): for connectionData in page.getConnectibles(): self.connect(connectionData["object"], SIGNAL(connectionData["signal"]), lambda value, name = connectionData["property"]:\ self.currentCurve.propertyChanged(name, value)) self.connect(connectionData["object"], SIGNAL(connectionData["signal"]), self.hackedDisplayArea.update) ``` **Note** - The self.endAngle etc. are initialized in the constructor. As far as I know, the reasons for choosing a dict is for fast lookup. When is that warranted? when I have 100 cases or more? Is it a good idea to keep building and throwing away a dictionary each time the function is called? If I build a dict for this purpose outside a function, should I check If it is needed elswhere? What happens if it is not needed elsewhere? My question is what is the best-practice if there is one? What is the best/most elegant way to go about things? Put in yet another way, when to use **if-elif-else**, when to use each of the other options?
Sigh. Too much hand-wringing over the wrong part of the problem. The switch statement is not the issue. There are many ways of expressing "alternative" that don't add **meaning**. The issue is **meaning** -- not technical statement choices. There are three common patterns. * **Mapping a key to an object**. Use a dictionary if it is almost totally static and you have a mapping between a simple key and another more complex thing. Building a dictionary on the fly each time you need it is silly. You can use this if it's what you **mean**: your "conditions" are simple, static key values that map to objects. * **Variant behavior among subclasses**. Use Polymorphism instead of type checking objects. Correct. If you have similar objects in multiple classes with variant behavior, they should be polymorphic. Use this as often as possible. * **Other variant behavior**. Use an if-elif-else ladder. Use this when you don't have largely static key-to-value mapping. Use this when the conditions are complex, or you **mean** procedures, not objects. Everything else is just tricky code that can achieve similar results. Using a Tuple. This is just dictionary without the mapping. This requires search, and search should be avoided whenever possible. Don't do this, it's inefficient. Use a dictionary. Using a function decorator (<http://code.activestate.com/recipes/440499/>). Icky. This conceals the if-elif-elif nature of the problem you're solving. Don't do this, it isn't obvious that the choices are *exclusive*. Use anything else. Someone even recommended the **Visitor** pattern. Use this when you have an object which follows the **Composite** design pattern. This depends on polymorphism to work, so it's not really a different solution.
In the first example I would certainly stick with the if-else statement. In fact I don't see a reason not to use if-else unless 1. You find (using e.g. the profile module) that the if statement is a bottleneck (very unlikely IMO unless you have a huge number of cases that do very little) 2. The code using a dictionary is clearer / has less repetition. Your second example I would actually rewrite ``` setattr(self, name, value) ``` (probably adding an assert statement to catch invalid names).
Choosing between different switch-case replacements in Python - dictionary or if-elif-else?
[ "", "python", "switch-statement", "" ]
We've been discussing about a client-only solution in javascript that provides means for a site visitor to annotate a page for printing and it's exploitability in terms of XSS or similar attack vector. Rationale: There's a potentially long process choosing what data to display. In order to document the steps taken, a *textarea* (without enclosing *form*) is provided that the user can write arbitrary text that is not supposed to be transferred to the server. The initial text is static, e.g. a short set of instructions how to use this field, so that there is no (obvious) possibility for an attacker to construct an url containing malicious javascript for this textarea. Once the users change this text they print the page (and their notes). The notes are lost once the user leaves the page. In case of "too much prose error" here's some example code: ``` <span id="descriptionHeader">Description of the result</span> <div id="description"> <textarea id="descriptionEditor" rows="15" cols="80" type="text" ondblclick="replaceDescription()"> Edit this text to add a detailed description to this page. Double click to this editing area to finish editing. If you want to edit the text again, do a double click to the description header. You may use html (e.g. <br>) for formatting. </textarea> </div> <script type="text/javascript"> var header = getElem("descriptionHeader"); var editor = getElem("descriptionEditor"); var description = getElem("description"); function empty() { } function editDescription() { header.ondblclick = empty; editor.value = description.innerHTML; description.innerHTML = ""; description.appendChild(editor); } function replaceDescription() { header.ondblclick = editDescription; description.removeChild(editor); description.innerHTML = editor.value; } </script> ``` Again: * The text is never processed server-side, only the static description ("how to use") is ever sent from the server to the client, never from client to server. * The user may add javascript elements as they like and exploit the hell out of themselves. * I can't think of a scenario where this will pose a security risk, but a queasy feeling stays... Note: The question is not about the elegance of this solution or any library that does inline editing more comfortable, but purely about conceivable security risks - if any.
A social engineering attack is possible : Asking a user (by chat or something else) to copy-paste something supposed to be a beautiful template to add to the page. It may look less suspicious to the user than asking for password; but except as a targeted attack it won't work as it may be flagged pretty fast if posted on a public place like a forum. --- I don't see any automated attack as no data goes back and forth between the client and the server. All attacks are client-side, and other than social any client-side attack that could modify your DOM or call javascript on your page doesn't need this to do XSS. --- Note that if needed for the social engineering [clickjacking](http://www.sectheory.com/clickjacking.htm) could be used, by using multiple iframes over your site, with your site in an iframe underneath, an attacker could hide the fact that the form is the one on your site, but they still need to trick the user to copy-paste the javascript code into the input textbox. --- To secure the input without loosing the HTML functionallity you could filter the HTML by porting code like the [stackoverflow one](https://blog.stackoverflow.com/2008/06/safe-html-and-xss/) to javascript (Or ask nicely for a license to the javascript version that is used in the live preview).
> description.innerHTML = editor.value; Whilst it is indeed relatively unlikely that a user could be persuaded to compromise themselves by typing a suitable <script> tag, is it actually necessary to allow them to type HTML at all? How about simply escaping the value: ``` function escapeMultiline(s) { return s.split('&').join('&amp;').split('<').join('&lt;').split('\n').join('<br />'); }; description.innerHTML= escapeMultiline(editor.value); ``` Then the user could happily type < characters and linebreaks without them being misinterpreted as HTML. (With similar de-escaping on the way back, of course.)
XSS without a server being involved - is this dangerous?
[ "", "javascript", "security", "xss", "" ]
A while back I wrote an application which used [Spring AOP](http://static.springframework.org/spring/docs/2.5.x/reference/aop.html) for defining which methods were transactional. I am now having second thoughts as to how much of a great idea this was; I have been hit a few times after a minor refactor (changing method signatures etc), which of course doesn't become apparent until something actually goes wrong (and I have a logically inconsistent database). So I'm interested in a few things: 1. Have other people decided to revert to explicit transaction management (e.g. via `@Transactional` annotations)? 2. Are there useful tools I can use as part of a build process to help identify whether anything has been "broken"? 3. If people are using AOP to manage transactions, what steps are they taking to avoid the mistakes I've made? I'm using IntelliJ IDEA which allows you to browse decorated methods and will refactor Spring `XML` config together with method name changes, but this is not always sufficient (adding a parameter to a method in the wrong place can affect whether an aspect fires for example)
I am currently using declarative transaction management in the two Java projects I work on, specifying which methods need transactional scope with `@Transactional` annotation. In my opinion, it is a good mix of flexibility and robustness: you are able to see which methods have transactional behavior via a simple text search, can adjust isolation and propagation attributes by hand if needed, and the additional amount of typing is practically negligent. On one of those projects, I have security/logging implemented via aspects and have occasionally stumbled on same obstacles you when renaming a method or changing signatures. In the worst case, I lost some logging data of user accessing contracts, and in one release, some user roles were not able to access all application features. Nothing major, but, as far as database transactions go, though, I think it's simply not worth it, and I it is better to type `@Transactional` bit yourself. Spring does the hard part, anyway.
Regarding (1): I found @Transactonal a more practical solution in all projects worked on in the past few years. In some very specific cases, however, I had also to use Spring AOP to allow the use of more than one JDBC connection / TransactionManager because @Transaction is tied to a single transaction manager. Regarding (2): Having said that, in a mixed scenario, I do a lot of automated testing to find possibly broken code. I use Spring's AbstractTransactionalJUnit4SpringContextTests / AbstractTransactionalTestNGSpringContextTests to create my tests. It's been a very effective solution so far.
Would you use AOP for database transaction management?
[ "", "java", "database", "spring", "transactions", "aop", "" ]
When I select a `Node` in the `TreeView`, it highlights and I show data based on that `Node`. When I select another `Control` (the `TreeView` loses focus) it is no longer highlighted. How do I keep it highlighted after losing focus? While doing a search I cant tell which node is selected since I must keep the focus on the textbox (so the user can type more text).
You have to set the HideSelection property to false - so you'll see the selection, altough the TreeView control lost focus
I just run into this issue and this is how I addressed it: Changed the DrawMode property to `TreeViewDrawMode.OwnerDrawText` and registered to DrawNode event ``` private void MyTreeGridview_DrawNode(object sender, DrawTreeNodeEventArgs e) { if ((e.State == TreeNodeStates.Selected) && (!MyTreeGridview.Focused)) { Font font = e.Node.NodeFont ?? e.Node.TreeView.Font; Color fore = e.Node.ForeColor; if (fore == Color.Empty)fore = e.Node.TreeView.ForeColor; fore = SystemColors.HighlightText; Color highlightColor = SystemColors.Highlight; e.Graphics.FillRectangle(new SolidBrush(highlightColor), e.Bounds); ControlPaint.DrawFocusRectangle(e.Graphics, e.Bounds, fore, highlightColor); TextRenderer.DrawText(e.Graphics, e.Node.Text, font, e.Bounds, fore, highlightColor, TextFormatFlags.GlyphOverhangPadding); } else { e.DrawDefault = true; } } ```
TreeView control in C#, select() and focus
[ "", "c#", "treeview", "" ]
I have a need to search a pdf file to see if a certain string is present. The string in question is definitely encoded as text (ie. it is not an image or anything). I have tried just searching the file as though it was plain text, but this does not work. Is it possible to do this? Are there any librarys out there for .net2.0 that will extract/decode all the text out of pdf file for me?
There are a few libraries available out there. Check out <http://www.codeproject.com/KB/cs/PDFToText.aspx> and <http://itextsharp.sourceforge.net/> It takes a little bit of effort but it's possible.
You can use [Docotic.Pdf library](https://bitmiracle.com/pdf-library/) to search for text in PDF files. Here is a sample code: ``` static void searchForText(string path, string text) { using (PdfDocument pdf = new PdfDocument(path)) { for (int i = 0; i < pdf.Pages.Count; i++) { string pageText = pdf.Pages[i].GetText(); int index = pageText.IndexOf(text, 0, StringComparison.CurrentCultureIgnoreCase); if (index != -1) Console.WriteLine("'{0}' found on page {1}", text, i); } } } ``` The library can also [extract formatted and plain text](https://bitmiracle.com/pdf-library/pdf-text/extract) from the whole document or any document page. Disclaimer: I work for Bit Miracle, vendor of the library.
How to programmatically search a PDF document in c#
[ "", "c#", ".net", "search", "pdf", "" ]
I am trying to create a simple C# app which does port forwarding, and need to know how to use the IP\_HDRINCL socket option to try to fake out the receiving end to think the connection is really to the source. Any examples would be greatly appreciated.
``` sock = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP ); sock.Bind( new IPEndPoint( IPAddress.Parse( "10.25.2.148" ), 0 ) ); sock.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1 ); byte[] trueBytes = new byte[] { 1, 0, 0, 0 }; byte[] outBytes = new byte[] { 0, 0, 0, 0 }; sock.IOControl( IOControlCode.ReceiveAll, trueBytes, outBytes ); sock.BeginReceive( data, 0, data.Length, SocketFlags.None, new AsyncCallback( OnReceive ), null ); ``` The only problem is that I've been able to successfully receive data from a raw socket like this, (including the IP header) but not send it.
Newer versions of windows restrict the use of raw sockets due to malware heavily abusing them. Quoted from the [MSDN](http://msdn.microsoft.com/en-us/library/ms740548%28VS.85%29.aspx) > On Windows 7, > Windows Vista, and Windows XP with > Service Pack 2 (SP2), the ability to > send traffic over raw sockets has been > restricted in several ways: > > * TCP data cannot be sent over raw sockets. > * UDP datagrams with an invalid source address cannot be sent over raw sockets. The IP source address for any outgoing UDP datagram must exist on a network interface or the datagram is dropped. This change was made to limit the ability of malicious code to create distributed denial-of-service attacks and limits the ability to send spoofed packets (TCP/IP packets with a forged source IP address). > * A call to the bind function with a raw socket for the IPPROTO\_TCP protocol is not allowed. > **Note** The bind function with a raw socket is allowed for other protocols (IPPROTO\_IP, IPPROTO\_UDP, or IPPROTO\_SCTP, for example. > > These above restrictions do not apply to Windows Server 2008 R2, Windows Server 2008 , Windows Server 2003, or to versions of the operating system earlier than Windows XP with SP2.
C# Raw Sockets Port Forwarding
[ "", "c#", "networking", "sockets", "portforwarding", "" ]
I'm trying to create a generic function to help me select thousands of records using LINQ to SQL from a local list. SQL Server (2005 at least) limits queries to 2100 parameters and I'd like to select more records than that. Here would be a good example usage: ``` var some_product_numbers = new int[] { 1,2,3 ... 9999 }; Products.SelectByParameterList(some_product_numbers, p => p.ProductNumber); ``` Here is my (non-working) implementation: ``` public static IEnumerable<T> SelectByParameterList<T, PropertyType>(Table<T> items, IEnumerable<PropertyType> parameterList, Expression<Func<T, PropertyType>> property) where T : class { var groups = parameterList .Select((Parameter, index) => new { GroupID = index / 2000, //2000 parameters per request Parameter } ) .GroupBy(x => x.GroupID) .AsEnumerable(); var results = groups .Select(g => new { Group = g, Parameters = g.Select(x => x.Parameter) } ) .SelectMany(g => /* THIS PART FAILS MISERABLY */ items.Where(item => g.Parameters.Contains(property.Compile()(item))) ); return results; } ``` I have seen plenty of examples of building predicates using expressions. In this case I only want to execute the delegate to return the value of the current ProductNumber. Or rather, I want to translate this into the SQL query (it works fine in non-generic form). I know that compiling the Expression just takes me back to square one (passing in the delegate as Func) but I'm unsure of how to pass a parameter to an "uncompiled" expression. Thanks for your help! \*\*\*\* EDIT:\*\* Let me clarify further: Here is a working example of what I want to generalize: ``` var local_refill_ids = Refills.Select(r => r.Id).Take(20).ToArray(); var groups = local_refill_ids .Select((Parameter, index) => new { GroupID = index / 5, //5 parameters per request Parameter } ) .GroupBy(x => x.GroupID) .AsEnumerable(); var results = groups .Select(g => new { Group = g, Parameters = g.Select(x => x.Parameter) } ) .SelectMany(g => Refills.Where(r => g.Parameters.Contains(r.Id)) ) .ToArray() ; ``` Results in this SQL code: ``` SELECT [t0].[Id], ... [t0].[Version] FROM [Refill] AS [t0] WHERE [t0].[Id] IN (@p0, @p1, @p2, @p3, @p4) ... That query 4 more times (20 / 5 = 4) ```
Easiest way to do this: Use [LINQKit](http://www.albahari.com/nutshell/linqkit.aspx) (Free, non-restrictive license) Working version of code: ``` public static IEnumerable<T> SelectByParameterList<T, PropertyType>(this Table<T> items, IEnumerable<PropertyType> parameterList, Expression<Func<T, PropertyType>> propertySelector, int blockSize) where T : class { var groups = parameterList .Select((Parameter, index) => new { GroupID = index / blockSize, //# of parameters per request Parameter } ) .GroupBy(x => x.GroupID) .AsEnumerable(); var selector = LinqKit.Linq.Expr(propertySelector); var results = groups .Select(g => new { Group = g, Parameters = g.Select(x => x.Parameter) } ) .SelectMany(g => /* AsExpandable() extension method requires LinqKit DLL */ items.AsExpandable().Where(item => g.Parameters.Contains(selector.Invoke(item))) ); return results; } ``` Example usage: ``` Guid[] local_refill_ids = Refills.Select(r => r.Id).Take(20).ToArray(); IEnumerable<Refill> results = Refills.SelectByParameterList(local_refill_ids, r => r.Id, 10); //runs 2 SQL queries with 10 parameters each ``` Thanks again for all your help!
I've come up with a way to chunk the query into pieces - i.e. you give it 4000 values, so it might do 4 requests of 1000 each; with full Northwind example. Note that this might not work on Entity Framework, due to `Expression.Invoke` - but is fine on LINQ to SQL: ``` using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace ConsoleApplication5 { /// SAMPLE USAGE class Program { static void Main(string[] args) { // get some ids to play with... string[] ids; using(var ctx = new DataClasses1DataContext()) { ids = ctx.Customers.Select(x => x.CustomerID) .Take(100).ToArray(); } // now do our fun select - using a deliberately small // batch size to prove it... using (var ctx = new DataClasses1DataContext()) { ctx.Log = Console.Out; foreach(var cust in ctx.Customers .InRange(x => x.CustomerID, 5, ids)) { Console.WriteLine(cust.CompanyName); } } } } /// THIS IS THE INTERESTING BIT public static class QueryableChunked { public static IEnumerable<T> InRange<T, TValue>( this IQueryable<T> source, Expression<Func<T, TValue>> selector, int blockSize, IEnumerable<TValue> values) { MethodInfo method = null; foreach(MethodInfo tmp in typeof(Enumerable).GetMethods( BindingFlags.Public | BindingFlags.Static)) { if(tmp.Name == "Contains" && tmp.IsGenericMethodDefinition && tmp.GetParameters().Length == 2) { method = tmp.MakeGenericMethod(typeof (TValue)); break; } } if(method==null) throw new InvalidOperationException( "Unable to locate Contains"); foreach(TValue[] block in values.GetBlocks(blockSize)) { var row = Expression.Parameter(typeof (T), "row"); var member = Expression.Invoke(selector, row); var keys = Expression.Constant(block, typeof (TValue[])); var predicate = Expression.Call(method, keys, member); var lambda = Expression.Lambda<Func<T,bool>>( predicate, row); foreach(T record in source.Where(lambda)) { yield return record; } } } public static IEnumerable<T[]> GetBlocks<T>( this IEnumerable<T> source, int blockSize) { List<T> list = new List<T>(blockSize); foreach(T item in source) { list.Add(item); if(list.Count == blockSize) { yield return list.ToArray(); list.Clear(); } } if(list.Count > 0) { yield return list.ToArray(); } } } } ```
LINQ Expression to return Property value?
[ "", "c#", "linq", "linq-to-sql", "lambda", "expression", "" ]
I'm having a slight issue wrapping my head around on how to set up Subversion when working with php files. I store all my files at c:\www[nameOfProject]\htdocs and I setup virtual hosts for each project. (c:\www\project1\htdocs\index.php maps to <http://localhost/project1/index.php>). How do you guys handle using SVN? Lets say I have c:\svnrepos\ which is where I store each repo for each project. Now ideally I would want to check out from the repo at c:\svnrepos\project1 to c:\www\project1 correct? But the docs say to do it to an empty directory, but how can I preview my code then without moving it somewhere else first? Thanks for the help guys!
One way of doing this effectively is to do your development by checking out the trunk into, say, c:\www\preview\project1 and testing it with an appropriate virtual host or different url there. As you get it working, you will be checking in various versions of the trunk. When it's ripe to move over to your "real" host/url, then you 1. Create a branch or a tag to reflect this (like branches/rel.1), and 2. Check out (svn co) the branch into c:\www\project1\htdocs After that you can do urgent bug fixes under branches/rel.1, and merge them back into ongoing work under trunk. When another release is ready, you 1. Make another branch (say, branches/rel.2), and 2. Switch (svn switch) c:\www\project1\htdocs to the new branch This way, you can keep your development from interfering with the real service, and also switch back to an earlier release if you have problems. For a more complicated, but urgent, bugfix, you can 1. Check in your development as trunk 2. Switch c:\www\preview\project1 to the current release branch 3. Fix and test the bug in c:\www\preview\project1, committing as necessary 4. When satisfied, do the final checkin, then svn update on c:\www\project1\htdocs 5. Switch c:\www\preview\project1 back to trunk, and carry on developing
An empty directory does not imply c:. Therefore you can safely have a repository at c:\svnrepos\project1 and checkout to c:\www\project1 to work.
How to set up SVN with files that are in an /htdocs directory structure
[ "", "php", "svn", "apache", "version-control", "" ]
### Background In our last [adventure](https://stackoverflow.com/questions/583689/dictionaryt-of-listt-and-listviews-in-asp-net), I was attempting to properly show a `Dictionary<Foo, Bar<T>>`. Thanks to the helpful answers in that post, I realize I had been going about it in the wrong way. ### Problem In today's adventure, I've been trying to get two specific properties from the `List<T>` in the last question to display. Each List has specific properties, shown below: ``` --------------------- | Bar Class | --------------------- | Id int | | Foo.Id int | | Name string | | Type string | --------------------- ``` For display, I'd like to display the `Bar.Name + Bar.Type`, concatenated together. Obviously I have to retain the complete object, since the Id will be passed back to be sent to the database. At first, I tried `<%#Eval("Value.Type" + "Value.Name")%>`, clearly that did not work. My guess now is that I need to write a foreach loop to iterate through the Dictionary Object, and retrieve the `Dictionary.Value` Objects intact, and build a dropdown list out of that. But then, the problem becomes tying that back to the associated profile, and sending it back to the database wholesale. Here currently is how the page looks: ``` <tr><td align="center"> <%#Eval("Key.Name") %></td> <td align="center"><asp:DropDownList ID="ddlListOfBars" runat="server" DataSource='<%#Eval("Value")%>' DataValueField="Id" DataTextField="Type" /> </td> ``` I've been monkeying around with different ways of changing the `DataTextField` but haven't yet figured out a combination that works. ### Questions 1. Am I overthinking this? 2. What am I missing? 3. Is there a resource for how you would pull specific properties out of the `List<T>` to use those values as the display Values for the `DropDownList`, and if so, is there a good resource on that topic? 4. Is this post as clear as mud?
As it turns out, the problem is easily solvable if the two columns from the table are concatenated and into one column, like so: `SELECT Column1Name + ' - ' + Column2Name AS Column3Name FROM Table1 WHERE`... This turns this: ``` Column1Name Column2Name ----------- ----------- Stuff1 Stuff5 Stuff2 Stuff6 Stuff3 Stuff7 Stuff4 Stuff8 ``` Into this: ``` Column3Name --------------- Stuff1 - Stuff5 Stuff2 - Stuff6 Stuff3 - Stuff7 Stuff4 - Stuff8 ``` When all else fails, think a little lower level.
Maybe I'm missing something (didn't look at the earlier question), but why wouldn't you just do this? ``` <%# Eval("Name") + Eval("Type") %> ```
Concatenating Two Properties for Display in a DropDownList
[ "", "c#", "asp.net", "dictionary", "" ]
Is F# better than C# in scenarios where you need complete parallelism in parts of an application? My main language is C# and I am writing an app where the core functionality built on top of the app (C#) has to be and planned to be very parallel. Am I better of implementing these classes in F#?
I'd look at the Parallel Extensions that's being developed by [Microsoft](http://msdn.microsoft.com/en-us/concurrency/default.aspx).
If you just need to process sets of data in parallel, the ParallelFX are very handy. They'll take a lot of pain out of doing it manually in C#. But if the code has a lot of asynchronous code, F#'s async monad makes it vastly easier than can be done in C#. If you're looking at a lot of BeginXXX/EndXXX or the dreaded XXXAsync/XXXCompletedEvent code, then F# will be a major win. Otherwise, you'll just have the general gains of F# over C#.
Is F# better than C# in scenarios where you need complete parallelism in parts of an application?
[ "", "c#", ".net", "f#", "parallel-processing", "" ]
I have heard this a lot, the the Java API is poorly designed. Do you agree and if so, how? I know there are major issues with the Calendar/Date apis. The collections api takes a lot of boilerplate code to use. The File/IO API can be complicated for some things. But, does this apply across the aboard? And to which versions of Java?
In short, Java APIs are OK. Longer answer is that some APIs went through changes, sometimes significant, over Java releases and may contain odd pieces. Date, for instance, has quite a few deprecated methods. Nevertheless, what's important is that those API **do exist**. Java is strong with it's standard library where you can find API for almost anything (may be not always perfect API, but good enough). P.S. Next time someone produces such a statement, ask him how many languages he designed himself in his life.
Java was not a poorly designed API. Java was made at a time when current best practices weren't exactly known. A lot of implementations were done in a way that are now frowned upon. Since that time there has been a LOT of work done in order to incorporate better techniques and practices. That is why there is a lot of deprecated code. A bunch of this stuff is talked about in the AMAZING book [Effective Java](https://rads.stackoverflow.com/amzn/click/com/0321356683). Bloch talks about some of the "mistakes" that were made in the initial implementation and how they have worked at trying to fix them. If you are a serious Java developer and haven't checked out Effective Java I recommend it HIGHLY. (I actually recommend all of 3 of [Bloch's books.](http://en.wikipedia.org/wiki/Joshua_Bloch) He is an excellent writer with a thorough understanding of Java.)
Is the Java API poorly designed and why?
[ "", "java", "api", "" ]
I am providing search functionality in my website, when user searches a record then I want to display the time the query taken to get the results same as google does. When we search anything then google displays how much time it takes to get results? For this I have declared a @start variable in my SP and finding the difference in the end, as below; ``` DECLARE @start_time DATETIME SET @start_time = GETDATE() -- my query SELECT * FROM @search_temp_table SELECT RTRIM(CAST(DATEDIFF(MS, @start_time, GETDATE()) AS CHAR(10))) AS 'TimeTaken' ``` Is there any other easy and fast way, or a single line of query with which we can find out the time a query taken to execute? I'm using SQL Server 2005.
We monitor this from the application code, just to include the time required to establish/close the connection and transmit data across the network. It's pretty straight-forward... ``` Dim Duration as TimeSpan Dim StartTime as DateTime = DateTime.Now 'Call the database here and execute your SQL statement Duration = DateTime.Now.Subtract(StartTime) Console.WriteLine(String.Format("Query took {0} seconds", Duration.TotalSeconds.ToString())) Console.ReadLine() ```
Well, If you really want to do it in your DB there is a more accurate way as given in [MSDN](http://msdn.microsoft.com/en-us/library/ms190287.aspx): ``` SET STATISTICS TIME ON ``` You can read this information from your application as well.
Calculate execution time of a SQL query?
[ "", "sql", "sql-server-2005", "" ]
I have a situation where I am mapping classes that have an inheritance hierarchy. I have a list of items that each class knows that it needs. For example: ``` public class PersonMapper { private string[] attributes = new[] {"firstName", "lastName"}; } public class UserMapper : PersonMapper { private string[] attributes = new[] {"username"}; } public class EmployeeMapper : PersonMapper { private string[] attributes = new[] {"employeeId"}; } ``` I would like to make a method call that returns the aggregate of all of the super classes like this: ``` EmployeeMapper mapper = new EmployeeMapper(); string[] attributes = mapper.GetAttributes(); Assert.That(attributes, Has.Member("firstname")); ``` I can think of some solutions, but they seem overly complicated. I feel like there is an elegant solution to this that I am missing. Can anyone help? Thanks in advance!
You can have a virtual method/property on the superclass called GetAttributes that returns the private array. Then, in each subclass, override it like so. First call the base GetAttribute method to get the base classes array, and the combine that with the subclasses array, and return the new array. Code sample: ``` public class PersonMapper { private string[] attributes = new[] { "firstName", "lastName" }; public virtual string[] GetAttributes() { return attributes; } } public class EmployeeMapper : PersonMapper { private string[] attributes = new[] { "employeeId" }; public override string[] GetAttributes() { return base.GetAttributes().Union(this.attributes).ToArray(); } } ```
I'd be tempted to develop a custom attribute that gets applied to each of the properties that I care to track and then use reflection to enumerate the properties with that attribute applied. You could use lazy loading so that the attribute list only gets populated once. I'd also probably make GetAttributes() a static (class) method. ``` public class MappedAttribute : Attribute { } public class Person { [Mapped] public string FirstName { get; set; } [Mapped] public string LastName { get; set; } public string DisplayName { get { return FirstName + " " + LastName; } } } public static class Mapper { public static IList<string> Attributes( Type t ) { List<string> attributes = new List<string>(); foreach (PropertyInfo pInfo in t.GetProperties()) { MappedAttribute attr = pInfo.GetCustomAttributes(typeof(MappedAttribute),false) .Cast<MappedAttribute>() .FirstOrDefault(); if (attr != null) { attributes.Add(pInfo.Name); } } return attributes; } } ```
What is an elegant way to aggregate properties from subclasses in C#?
[ "", "c#", "" ]
I thought this would be as easy as: ``` if(typeof(Array.push) == 'undefined'){ //not defined, prototype a version of the push method // Firefox never gets here, but IE/Safari/Chrome/etc. do, even though // the Array object has a push method! } ``` And it does work fine in Firefox, ***but not in IE, Chrome, Safari, Opera***, they return all properties/methods of the native Array object as 'undefined' using this test. The .hasOwnProperty( prop ) method only works on instances... so it doesn't work, but by trial and error I noticed that this works. ``` //this works in Firefox/IE(6,7,8)/Chrome/Safari/Opera if(typeof(Array().push) == 'undefined'){ //not defined, prototype a version of the push method } ``` Is there anything wrong with using this syntax to determine if a property/method exists on a *Native Object / ~"JavaScript Class"~*, or is there a better way to do this?
First of all, typeof is an operator, not a function, so you don't need the parentheses. Secondly, access the object's prototype. ``` alert( typeof Array.prototype.push ); alert( typeof Array.prototype.foo ); ``` When you execute `typeof Array.push` you are testing if the Array object itself has a push method, not if instances of Array have a push method.
The proper way to check if a property exists: ``` if ('property' in objectVar) ```
How to determine if Native JavaScript Object has a Property/Method?
[ "", "javascript", "methods", "properties", "native", "typeof", "" ]
Can anyone tell me why this isn't working? ``` function changeBG(element_id){ document.getElementById(element_id).className= "arrowActive"; setTimeout("document.getElementById("+element_id+").className= 'arrow'", 300); } ``` In firebug I get an error saying that the element\_id passed to setTimeout() is not defined.
The variable `element_id` will be a string, so your timeout code will look like: ``` document.getElementById(myId).className = ... ``` Notice that myId should be in quotes, but it's not. A better way is to use a closure, like this: ``` function changeBG(element_id) { var elm = document.getElementById(element_id); elm.className = "arrowActive"; setTimeout(function() { elm.className= 'arrow'; }, 300); } ``` It should be noted that passing the code in a a string is [not recommended](https://developer.mozilla.org/En/DOM/window.setTimeout).
Try: ``` setTimeout("document.getElementById('" + element_id + "').className= 'arrow'", 300); ``` Notice that I added quotes to the string parameter you're passing to `getElementById`.
Function Variable passed to setTimeout not working?
[ "", "javascript", "iphone", "html", "" ]
In Eclipse source code, I've found some '$NON-NLS-1$' in comments used like that : ``` private String toolTip = ""; //$NON-NLS-1$ ``` What does that mean ?
They silence a warning that Eclipse emits when it encounters string literals (and has been configured to complain). The idea is that UI messages should not be embedded as string literals, but rather sourced from a resource file (so that they can be translated, proofed, etc). Consequently, Eclipse can be configured to detect string literals, so that you don't accidentally have leave unexternalized UI strings in the code; however, there are strings which should not be externalized (such as regexps) and so, //$NON-NLS-1$ gives you a way to communicate that fact to the compiler.
The string is not translatable. It tells the Eclipse editor to not flag the string as unresourced. This is important for multilingual applications.
What does $NON-NLS-1$ mean?
[ "", "java", "eclipse", "eclipse-rcp", "" ]
How do I make nested loops in Python (version 3.0)? I am trying to get the following loops to show me the products of two numbers: ``` def PrintProductsBelowNumber(number): number1 = 1 number2 = 1 while number1 <= number: while number2 <= number: print(number1, "*", number2, "=", number1 * number2) number2 += 1 number1 += 1 PrintProductsBelowNumber(2) ``` As a result I get: ``` 1 * 1 = 1 1 * 2 = 2 ``` So it seems the outer loop over number1 does not run. How do I get the loop over number1 to run, and thus obtain: ``` 1 * 1 = 1 1 * 2 = 2 2 * 1 = 2 2 * 2 = 4 ```
Because you aren't setting number2 back to 1 after the inner loop completes the first time. number1 then increments, but since number2 is still too high the inner loop doesn't run again. ``` def PrintProductsBelowNumber(number): number1 = 1 while number1 <= number: number2 = 1 while number2 <= number: print(number1, "*", number2, "=", number1 * number2) number2 += 1 number1 += 1 PrintProductsBelowNumber(2) ``` **EDIT**: Adam's solution is much better in general, but this is to show why your's wasn't working the way you thought it should in the first place.
`number2` only gets initialized once, you need to re-initialize it for each iteration of the inner loop. However, this code is very C-like and not very Pythonic. The better way to do it would be to use the `for number in range(n)` construct: ``` def PrintProductsBelowNumber(number): for number1 in range(1, number+1): for number2 in range(1, number+1): print(number1, "*", number2, "=", number1 * number2) ```
What is wrong with my nested loops in Python?
[ "", "python", "loops", "nested", "" ]
I would like to save my backups from my SQL 2008 server to another server location. We have 2 servers: * Deployment server * File Server The problem is that the deployment server doesn't have much space. And we keep 10 days backups of our databases. Therefore we need to store our backups on an external "file server". The problem is that SQL doesn't permit this. I've tried to run the SQL 2008 service with an account that has admin rights on both pc's (domain account), but this still doesn't work. Any thoughts on this one. Otherwise we'll have to put an external harddisk on a rack server and that's kinda silly no? **EDIT:** I've found a way to make it work. You have to share the folder on the server. Then grant the Development Server (the PC itself) write permissions. This will make external backups possible with SQL server. Don't know if it's safe though, I find it kinda strange to give a computer rights on a folder.
you might use a scheduler to move backups after a certain amount of time after the backup started with a batch file. If I remember correctly there's a hack to enable the sql server to back up on remote storage, but I don't think a hack is the way to go. Surely the best possibility may be to use an external backup tool which supports the use of agents. They control when the backup starts and take care of the files to move around. Sascha
You can use 3rd party tools like [SqlBackupAndFTP](http://SqlBackupAndFTP.com)
Microsoft SQL Server 2008 External Backup
[ "", "sql", "sql-server", "sql-server-2008", "backup", "" ]
I have a set of global counter variables in Javascript: ``` var counter_0 = 0; var counter_1 = 0; var counter_2 = 0; ``` etc I then have a Javascript function that accepts an 'index' number that maps to those global counters. Inside this function, I need to read and write to those global counters using the 'index' value passed to the function. Example of how I'd like it to work, but of course doesn't work at all: ``` function process(index) { // do some processing // if 'index' == 0, then this would be incrementing the counter_0 global variable ++counter_+index; if (counter_+index == 13) { // do other stuff } } ``` I hope what I'm trying to accomplish is clear. If not I'll try to clarify. Thanks. EDIT Clarification: I'm not trying to increment the name of the counter, but rather the value the counter contains.
Looks like an array to me, or am I missing something? ``` var counters = [0,0,0]; function process(index) { ++counters[index]; /* or ++counters[index]+index, not sure what you want to do */ if (counters[index] === 13) { /* do stuff */ } } ```
``` function process(index) { // do some processing var counter; eval('counter = ++counter_'+index); if (counter == 13) { // do other stuff } } ``` Make sure that index really is an integer, otherwise mayhem could ensue. **Edit**: Others have pointed out that you should use an array if you can. But if you are stuck with the named global variables then the above approach will work. **Edit**: bobince points out that you can use the window object to access globals by name, and so deserves any credit for the following: ``` function process(index) { // do some processing var counter = ++window['counter_' + index]; if (counter == 13) { // do other stuff } } ``` Other answers have said "don't use `eval()`", but not why. Here's an explanation from [MDC](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Functions/eval): > **Don't use eval!** > > eval() is a dangerous function, which > executes the code it's passed with the > privileges of the caller. If you run > eval() with a string that could be > affected by a malicious party, you may > end up running malicious code on the > user's machine with the permissions of > your webpage / extension. > > There are safe alternatives to eval() > for common use-cases.
Javascript "Variable Variables": how to assign variable based on another variable?
[ "", "javascript", "variables", "" ]
I have a generic method that copies values between value types. The following approaches give a design time error, even with the struct constraint. Any idea how I can copy or cast between the values? ``` private Ttgt MyMethod<Tsrc,Ttgt>(Tsrc SourceObject) where Tsrc : struct where Ttgt : struct { //Error:cannot implictly convert type 'Tsrc' to 'Ttgt' Ttgt returnObject = SourceObject; //Error:Cannot convert type 'Tsrc' to 'Ttgt' Ttgt returnObject = (Ttgt)SourceObject; return returnObject; } ```
Given that there is a registered type converter for the types that you're trying to convert between a little reflection magic could do the trick: ``` private Ttgt MyMethod<Tsrc,Ttgt>(Tsrc sourceObject) where Tsrc:struct where Ttgt:struct { Type targetType = typeof(Ttgt); TypeConverter tc = TypeDescriptor.GetConverter(targetType); Ttgt returnObject = (Ttgt)tc.ConvertTo(sourceObject, targetType); return returnObject; } ``` But out of the box it would be of very limited use since there is no converter between bool and int for example. What problem are you trying to solve? I also discovered another [question](https://stackoverflow.com/questions/452120/how-do-i-make-a-universal-type-conversion-method) with some crazy conversion code in it. Edit: Your comment makes it clear that you are trying to perform object to object mapping between domain objects and some kind of view/contract model. Have you looked at [AutoMapper](http://www.codeplex.com/AutoMapper)?
> //Error:Cannot convert type 'Tsrc' to 'Ttgt' You cannot convert between arbitrary types, unless there is an accessible conversion operator.
How to copy between generic declared types with value type constraints
[ "", "c#", ".net", "generics", "casting", "generic-constraints", "" ]
I have looked in *The C++ Programming Language* to try to find the answer to this. When I `#include "my_dir/my_header.hpp"` in a header, where does it look for this file? Is it relative to the header, relative to the source file that included it, or something else?
Implementation defined. See [what is the difference between #include <filename> and #include “filename”](https://stackoverflow.com/questions/21593/what-is-the-difference-between-include-filename-and-include-filename).
It is relative to both the current source file and to any search paths given (-I for gcc).
#include directive: relative to where?
[ "", "c++", "include", "c-preprocessor", "" ]
Consider the following code ``` template<unsigned int N> void foo(std::bitset<N> bs) { /* whatever */ } int main() { bitset<8> bar; foo(bar); return 0; } ``` g++ complains about this on 64 bit because the <8> gets interpreted as an unsigned long int, which doesn't exactly match the template. If I change the template to say unsigned long int, then 32-bit compiles complain. Obviously one way to fix this is to change bitset<8> to bitset<8ul>, but is there any way to re-write the *template* part so that it will work with whatever the default interpretation of a numeric literal is?
The problem isn't whether or not you write `8u` or `8`. The problem has to do with the type of the template parameter of your function template. Its type has to match the one used in the declaration of `std::bitset`. That's `size_t` according to the Standard (section `23.3.5`) ``` namespace std { template<size_t N> class bitset { public: // bit reference: ... ``` The exception are array dimensions, for which you can use any integer type (even `bool` - then the only size that can be accepted is `1` of course): ``` // better size_t (non-negative), but other types work too template<int N> void f(char(&)[N]); ``` But in other occasions, types have to match. Note that this is only true for autodeduced template arguments, but not for explicitly given ones. The reason is that for deduced ones, the compiler tries to figure out the best match between actual template arguments and what it deduced from the call to it. Many otherwise implicit conversions are disallowed then. You have the full range of conversions available if you put the argument explicit (ignoring the solution of using `size_t` now to make my point) ``` template<int N> void foo(std::bitset<N> bs) { /* whatever */ } int main() { bitset<8> bar; foo<8>(bar); // no deduction, but full range of conversions } ```
Use `size_t`. So sayeth the MSDN at least.
How to write a std::bitset template that works on 32 and 64-bit
[ "", "c++", "templates", "64-bit", "bitsets", "" ]
The application I'm working on has a single class that maintains a database connection. All members of this class are static to enforce a singleton-like pattern, so the actual connection logic is performed in a static initializer block: ``` public class HibernateUtil { private static final SessionFactory sessionFactory; static { sessionFactory = new Configuration().configure().buildSessionFactory(); } static void openSession() { //open session with sessionFactory } public static Session currentSession() { //return the currently open session } static void closeSession() { //close the currently open session } } ``` However, the application now needs to open a database connection to a second database. The way this class in structured now, the only way to maintain the second connection while keeping the above pattern would be to create a second class (something like SecondHibernateUtil) and change the one line of configuration in the initializer block. That feels like a truly wasteful amount of copy/paste. Can anyone suggest a way that I could rework this setup to maintain multiple connections simultaneously while not being overly destructive to the code already calling the existing methods?
Keep the static methods and let them delegate to corresponding instance methods of a default instance. For the secondary databases allow to create more instances by whatever means and access them via their instance methods. Then you can chip away at the callers of the static methods, and when they are all gone remove the static methods.
Maybe it shouldn't have been static in the first place.
What's the best way to duplicate/extend a static class's functionality?
[ "", "java", "class", "oop", "static", "" ]
I'm having a problem setting up an event on a form. Here's the setup: I was given a page with two controls, two different versions of a form for the end-user to fill out- standard and advanced. The two forms have different code and javascript, so the original dev put them in separate web user controls. Aside from the controls is a LinkButton that switches to Advanced mode. ``` <uc1:Standard runat="server" ID="StandardForm" /> <uc1:Advanced runat="server" ID="AdvancedForm" /> <asp:LinkButton runat="server" ID="lnkAdvanced" Text="Go To Advanced" OnClick="lnkAdvanced_Click" /> ``` lnkAdvanced\_Click just takes all the info currently entered to the advanced and flips the Visible. My problem is that one of the bosses wants the 'Go to Advanced' button inside the standard form, but the .Visible code is on the page. So I thought it could be done using an event, but it doesn't seem to be working. I tried to set up the event like this: ``` public event EventHandler AdvanceClick; protected void lnkAdvanced_Click(object sender, EventArgs e) { AdvanceClick(sender, e); } ``` And when that didn't work, I tried to set up a delegate: ``` public delegate void AdvancedEventHandler(object sender, EventArgs e); public event AdvancedEventHandler AdvanceClick; ``` When I moved the button to the standard form, I expected to be able to type something like: ``` StandardForm.AdvanceClick += new AdvancedEventHandler(GoToAdvanced); ``` But it doesn't seem to recognize any events within the control! I get an error: "Standard does not contain a definition for 'AdvanceClick' and no extension method 'AdvanceClick accepting a first argument of type 'Standard' could be found" It finds the other properties just fine, am I going about this the wrong way?
If the standard form has the "Switch to advanced" button. Then, clearly, it has to know about the Advanced form and thus they seem to be pretty tightly coupled. If this is the case, it seems to me that you might as well just have the advanced form as a child of the standard form then... or better yet, merge them into one control. If you don't like these options you might want to create a third controls which hosts the button and the two forms, along with the logic to move data between them and toggle their visibility. I personally recommend the single control option. Having tighly coupled controls usually just leads to confusion down the road. You could loosen up the dependency in various ways, but think hard about it before you do so. In the legacy project I currently work on we have a bunch of examples such as serach forms and search results being split up into multiple controls, but then in the end needing each others instances to function properly. As I said earlier, I wont reccomend this path.
``` // in your Standard user control public event EventHandler AdvancedClick; private void lbtnAdvanced_Click(object sender, EventArgs e) { OnAdvancedClick(e); } protected void OnAdvancedClick(EventArgs e) { if (AdvancedClick != null) AdvancedClick(this, e); } // on your page StandardForm.AdvancedClick += new EventHandler(StandardForm_AdvancedClick); private void StandardForm_AdvancedClick(object sender, EventArgs e) { // toggle logic here } ```
How do I register event handlers for a web user control in my code behind?
[ "", "c#", "event-handling", "web-user-controls", "" ]
I have been trying to convert a php page to mysqli, and have encoutnered some problems. Given the code below, and the way which I have ordered things to work, I would like to know what the better way is using mysqli methods. Is there an mysqli alternative to mysql\_num\_rows or is a different method of calculating the number of rows required? How would I do the following using mysqli?: ``` $data = mysql_query($countQuery) or die(mysql_error()); $rowcount = mysql_num_rows($data); ``` What is an alternative for mysql\_fetch\_assoc? I feel that I should not be using the current rows method I am using, even if there is a replacement function, so what would be the correct approach? I apologize for these questions, but I have not been able to determine the answers myself so far. ``` <?php $con = mysqli_connect("localhost", "user", "", "ebay"); if (!$con) { echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error(); exit; } $con->query("SET NAMES 'utf8'"); $cmd = "word"; //normally retrieved from GET if($cmd=="deleterec") { $deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?"; if ($delRecord = $con->prepare($deleteQuery)) { $delRecord->bind_param("s", $pk); $delRecord->execute(); } } $table = 'AUCTIONS'; $brand = "test"; $countQuery = "SELECT ARTICLE_NO FROM ? WHERE upper(ARTICLE_NAME) LIKE '% ? %'"; if ($numRecords = $con->prepare($countQuery)) { $numRecords->bind_param("ss", $table, $brand); $numRecords->execute(); $data = $con->query($countQuery) or die(print_r($con->error)); $rowcount = mysql_num_rows($data); $rows = getRowsByArticleSearch($query, $table, $max); $last = ceil($rowcount/$page_rows); } $self = htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'utf-8'); foreach ($rows as $row) // print table rows { echo '<tr>' . "\n"; echo '<td><a href="#" onclick="doThings(\'Layer2\', \'' . $pk . '\')">'.$row['USERNAME'].'</a></td>' . "\n"; // repeated for each column } function getRowsByArticleSearch($searchString, $table, $max) { global $con; $recordsQuery = "SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME, date_format(str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s'), '%d %m %Y' ) AS shortDate FROM ? WHERE upper(ARTICLE_NAME) LIKE '%?%' ORDER BY str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s')" . $max; if ($getRecords = $con->prepare($recordsQuery)) { $getRecords->bind_param("ss", $searchString, $table); $getRecords->execute(); $getRecords->bind_result($ARTICLE_NO, $USERNAME, $ACCESSSTARTS, $ARTICLE_NAME, $shortDate); while ($getRecords->fetch()) { $result = $con->query($recordsQuery); $rows = array(); while($row = mysql_fetch_assoc($result)) { $rows[] = $row; } return $rows; } } } ```
I've rewritten your code sample with the correct property / function calls to fix the two issues that you mention in the question: ``` <?php $con = mysqli::connect("localhost", "user", "", "ebay"); if (!$con) { echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error(); exit; } $con->query("SET NAMES 'utf8'"); $cmd = "word"; //normally retrieved from GET if($cmd=="deleterec") { $deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?"; if ($delRecord = $con->prepare($deleteQuery)) { $delRecord->bind_param("s", $pk); $delRecord->execute(); } } $table = 'AUCTIONS'; $brand = "test"; $countQuery = "SELECT ARTICLE_NO FROM ? WHERE upper(ARTICLE_NAME) LIKE '% ? %'"; if ($numRecords = $con->prepare($countQuery)) { $numRecords->bind_param("ss", $table, $brand); $numRecords->execute(); $data = $con->query($countQuery) or die(print_r($con->error)); // Here is the property that you can reference to determine the affected rows from the previous query. -- gabriel $rowcount = $data->num_rows; $rows = getRowsByArticleSearch($query, $table, $max); $last = ceil($rowcount/$page_rows); } $self = htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'utf-8'); foreach ($rows as $row) // print table rows { echo '<tr>' . "\n"; echo '<td><a href="#" onclick="doThings(\'Layer2\', \'' . $pk . '\')">'.$row['USERNAME'].'</a></td>' . "\n"; // repeated for each column } function getRowsByArticleSearch($searchString, $table, $max) { //global $con; Globals are BAD!! Please don't use. $con = mysqli::connet("localhost", "user", "", "ebay"); $recordsQuery = "SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME, date_format(str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s'), '%d %m %Y' ) AS shortDate FROM ? WHERE upper(ARTICLE_NAME) LIKE '%?%' ORDER BY str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s')" . $max; if ($getRecords = $con->prepare($recordsQuery)) { $getRecords->bind_param("ss", $searchString, $table); $getRecords->execute(); $getRecords->bind_result($ARTICLE_NO, $USERNAME, $ACCESSSTARTS, $ARTICLE_NAME, $shortDate); while ($getRecords->fetch()) { $result = $con->query($recordsQuery); $rows = array(); // Notice the adjusted function call to retrieve the associate array for each record within the result set. -- gabriel while($row = $result->fetch_assoc()) { $rows[] = $row; } return $rows; } } } ``` However, I would like to add that dusoft was correct in the assessment that MySQLi is buggy and is known to create issues. It is for this reason that we had to switch from MySQLi to PDO (which is native to PHP as of at least 5.1) and we haven't had any problems since. I would strongly recommend that you look at PDO or perhaps one of the Pear libraries to actually provide your database connection interface.
I usually use this directly after my execute: ``` $query->execute(); // store the result first $query->store_result(); $rows = $query->num_rows; ```
counting rows and passing information with mysqli
[ "", "php", "mysql", "mysqli", "" ]
I'm interested in wed development and web 2.0 but I'm a real beginner, so I'm reading a lot about the technologies involved. I'm beginning to move towards ASP.NET because of the great free resources for learning. However, as I begin to work in "Visual Web Developer Express" I notice that I need to understand ASP and C# or VB. Two technologies. Is this the same for Ruby or PHP. Do you need to learn two languages/technologies to make web applications (not including XHTML/CSS/XML), or do you just learn PHP/Ruby? Therefore is it quicker (not saying better!) for a beginner to start with PHP/RUBY rather than ASP.NET and C#/VB because you can spend your time learning one rather than two languages?
ASP.NET is **not** a programming language. It's a server-side technology that supports programming in any .NET language. So you are not forced to learn 2 different *languages*. This is just like PHP and Ruby. Both of them can be used to build non-Web based applications. When you are building Web applications with PHP, you are actually using both PHP scripting language and the functionality provided by some kind of framework that helps you specifically build Web applications. The two things are still the same. The difference is that they are not given separate names.
I wouldn't call ASP.NET two languages. You cna use C#, VB.Net or something else to write ASP.NET pages. PHP is a Webpage-centric scripting language. Some would call it a templating language because you can embed PHP in what are otherwise HTML documents. There are many ways to do PHP but you can if you want use just PHP. Others throw in things like particular frameworks (eg Zend), templating engines like Smarty and so on but these are all optional. Ruby on Rails on the other hand is a heavyweight development stack. It not encapsulates a persistence pattern (active record) but goes so far as to incorporate a Javascript library (Prototype) into the stack. It's really an end to end solution that doesn't have the interchangeability of some lighter weight stacks.
Do you need 2 languages with ASP.NET, but only one for PHP/Ruby?
[ "", "php", "asp.net", "programming-languages", "" ]
Is there any difference between the two statements: ``` IntPtr myPtr = new IntPtr(0); IntPtr myPtr2 = IntPtr.Zero; ``` I have seen many samples that use PInvoke that prefer the first syntax if the myPtr argument is sent by ref to the called function. If I'll replace all new IntPtr(0) with IntPtr.Zero in my application, will it cause any damage?
`IntPtr` is a value type, so unlike `String.Empty` there's relatively little benefit in having the static property `IntPtr.Zero` As soon as you pass `IntPtr.Zero` anywhere you'll get a copy, so for variable initialisation it makes no difference: ``` IntPtr myPtr = new IntPtr(0); IntPtr myPtr2 = IntPtr.Zero; //using myPtr or myPtr2 makes no difference //you can pass myPtr2 by ref, it's now a copy ``` There is one exception, and that's comparison: ``` if( myPtr != new IntPtr(0) ) { //new pointer initialised to check } if( myPtr != IntPtr.Zero ) { //no new pointer needed } ``` As a couple of posters have already said.
They are functionally equivalent, so it should cause no problems. `IntPtr.Zero` represents the default state of the structure (it is declared but no constructor is used), so the default value of the `intptr (void*)` would be `null`. However, as `(void*)null` and `(void*)0` are equivalent, `IntPtr.Zero == new IntPtr(0)` **Edit:** While they are equivalent, I do recommend using `IntPtr.Zero` for comparisons since it simply is easier to read.
new IntPtr(0) vs. IntPtr.Zero
[ "", "c#", ".net", "pinvoke", "" ]
I've got a table of 'folders'. I want to return all the records with the userId of 16. ``` SELECT * FROM `folders` WHERE userId = 16; ``` I've got a table of 'files'. For each 'folder' returned above, I want to return a count of 'files' within that 'folder'. ``` SELECT COUNT(*) as "Files" FROM files WHERE Folder = n; ``` How do I combine these? I'm lost. Thanks!
``` SELECT fol.* , ( SELECT COUNT(*) FROM files fil WHERE fil.Folder = fol.Folder ) AS "Files" FROM folders fol WHERE fol.userId = 16 ``` It's called a correlated subquery. <http://dev.mysql.com/doc/refman/5.1/en/correlated-subqueries.html>
you would probably need to use GROUP BY and group it by ID or such: ``` SELECT folders.*, COUNT(files.*) as filetotal FROM folders LEFT JOIN files ON folders.ID=files.folderID WHERE userId = 16 GROUP BY folders.ID ```
MySQL statement combining a join and a count?
[ "", "sql", "join", "count", "" ]
I have a problem with my ASP.NET application. It has been developed for about a year or so without disabling Debug mode. I wanted to test if it works without debug and it isn't but, when I set debug="true", it works fine. When I try to open application for the first time it gives me "Server not available" error. In the events log I have two errors: 1. .NET Runtime 2.0 error - Faulting application aspnet\_wp.exe, version 2.0.50727.3082, stamp 492b8702, faulting module kernel32.dll, version 5.1.2600.3119, stamp 46239c44, debug? 0, fault address 0x00012a5b. 2. ASP.NET 2.0.50727.0 - Unexpected end of process aspnet\_wp.exe (PID: 4932) (it may be written a little different, it's translated). My IIS version is 5.1 running on Windows XP. I'll be grateful for any suggestions. UPDATE: Change of debug mode is made in the web.config
The crash you're describing is happening in kernel32.dll - this might indicate that this is not a crash inside your managed code, but rather in the .NET engine itself (ugh) - in which case things like verifying precompiler paths etc. would not yield any positive results (IMHO). I would suggest you try resolving this issue via "binary search" (for the culprit) :-). As the first "iteration", I would create a trivial aspx page (/Test.aspx), keep the debug mode disabled and try to hit the page (no code-behind, just basic HTML with title and Hello, world body). This will verify ASP.NET is installed and working properly on your IIS server. If this simplest page fails again, I suggest exactly what @JSC mentioned in comments: re-register ASP.NET on IIS: ``` rem (reregister ASP.NET in IIS) rem (run as administrator!) %SystemRoot%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i ``` Once the simplest page is running, I would add simple code-behind, try that. Once code-behind is running, I would try updating the real starting page of your application by stripping ALL code-behind, leave only the markup and try hitting the page - yes, it will look horrible but at least it might display :-). Afterwards, I would try adding only the initialization logic, see how that goes... Essentially, you need to find whatever "thing" in your application is causing the crash. I presume the two extremes are: markup + no code behind = works, markup + all code behind = crashes; binary search "approach" would enable half of your code, see if it still displays (we are not worrying about functionality right now - it will not behave as expected, of course). If it does not display, disable the second half of the first half (i.e. only a quarter of your code will be active), try that. Keep going until you restrict your search to the problematic area... Another approach I would suggest is to install Server 2003 (IIS6) / Server 2008 (IIS7) on a virtual machine - VirtualPC, VMWare, VirtualBox (if you don't have access to MSDN downloads of server images, you can always download trials - Server 2008 trial is good for 60 days plus two "resets"). After installing clean OS in a virtual machine, try to deploy your application and see how it behaves in that environment.
I propose you check your code against asserts containing nondebug code. I did several times a common mistake writing code like following: Assert(doSomeCrucialOperation()); when compiling in release mode the whole Assert with the operation invocation is not compiled.
Application failure in Release mode
[ "", "c#", "asp.net", "crash", "release", "" ]
I've read ['what are bitwise operators?'](https://stackoverflow.com/questions/276706/what-are-bitwise-operators), so I know **what** [bitwise operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators) are but I'm still not clear on how one might use them. Can anyone offer any real-world examples of where a bitwise operator would be useful in JavaScript? Thanks. ## Edit: Just digging into the **[jQuery source](http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js)** I've found a couple of places where bitwise operators are used, for example: (only the & operator) ``` // Line 2756: event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); // Line 2101 var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; ```
Example: Parses hexadecimal value to get RGB color values. ``` var hex = 'ffaadd'; var rgb = parseInt(hex, 16); // rgb is 16755421 var red = (rgb >> 16) & 0xFF; // returns 255 var green = (rgb >> 8) & 0xFF; // 170 var blue = rgb & 0xFF; // 221 ```
I *heavily* use bitwise operators for numerical convertions in production scripts, because sometimes they're much faster than their `Math` or `parseInt` equivalents. The price I have to pay is **code readability**. So I usualy use `Math` in development and bitwise in production. [You can find some performance tricks on jsperf.com](http://jsperf.com/math-floor-vs-math-round-vs-parseint/18). As you can see, browsers don't optimize `Math.ceil` and `parseInt` for years, so I predict bitwise will be faster and shorter way to do things [in furure as well](https://stackoverflow.com/questions/2526682/why-is-javascripts-math-floor-the-slowest-way-to-calculate-floor-in-javascript). [Some further reading on SO...](https://stackoverflow.com/questions/4024429/what-does-a-single-vertical-bar-mean-in-javascript) --- Bonus: **cheat sheet** for `| 0` : an easy and fast way to convert anything to integer: ``` ( 3|0 ) === 3; // it does not change integers ( 3.3|0 ) === 3; // it casts off the fractional part in fractionalal numbers ( 3.8|0 ) === 3; // it does not round, but exactly casts off the fractional part ( -3.3|0 ) === -3; // including negative fractional numbers ( -3.8|0 ) === -3; // which have Math.floor(-3.3) == Math.floor(-3.8) == -4 ( "3"|0 ) === 3; // strings with numbers are typecast to integers ( "3.8"|0 ) === 3; // during this the fractional part is cast off too ( "-3.8"|0 ) === -3; // including negative fractional numbers ( NaN|0 ) === 0; // NaN is typecast to 0 ( Infinity|0 ) === 0; // the typecast to 0 occurs with the Infinity ( -Infinity|0 ) === 0; // and with -Infinity ( null|0 ) === 0; // and with null, ( (void 0)|0 ) === 0; // and with undefined ( []|0 ) === 0; // and with an empty array ( [3]|0 ) === 3; // but an array with one number is typecast to number ( [-3.8]|0 ) === -3; // including the cast off of the fractional part ( [" -3.8 "]|0 ) === -3; // including the typecast of strings to numbers ( [-3.8, 22]|0 ) === 0 // but an Array with several numbers is typecast to 0 ( {}|0 ) === 0; // an empty object is typecast to 0 ( {'2':'3'}|0 ) === 0; // or a not empty object ( (function(){})|0 ) === 0; // an empty function is typecast to 0 too ( (function(){ return 3;})|0 ) === 0; ``` and some magic for me: ``` 3 | '0px' === 3; ```
Where would I use a bitwise operator in JavaScript?
[ "", "javascript", "bitwise-operators", "" ]
I'm a game's developer and am currently in the processing of writing a cross-platform, multi-threaded engine for our company. Arguably, one of the most powerful tools in a game engine is its scripting system, hence I'm on the hunt for a new scripting language to integrate into our engine (currently using a relatively basic in-house engine). Key features for the desired scripting system (in order of importance) are: * Performance - MUST be fast to call & update scripts * Cross platform - Needs to be relatively easy to port to multiple platforms (don't mind a bit of work, but should only take a few days to port to each platform) * Offline compilation - Being able to pre-parse the script code offline is almost essential (helps with file sizes and load times) * Ability to integrate well with c++ - Should be able to support OO code within the language, and integrate this functionality with c++ * Multi-threaded - not required, but desired. Would be best to be able to run separate instances of it on multiple threads that don't interfere with each other (i.e. no globals within the underlying code that need to be altered while running). Critical Section and Mutex based solutions need not apply. I've so far had experience integrating/using Lua, Squirrel (OO language, based on Lua) and have written an ActionScript 2 virtual machine. So, what scripting system do you recommend that fits the above criteria? (And if possible, could you also post or link to any comparisons to other scripting languages that you may have) Thanks, Grant
We've had good luck with [Squirrel](http://squirrel-lang.org/) so far. Lua is so popular it's on its way to becoming a standard. I recommend you worry more about memory than speed. Most scripting languages are "fast enough" and if they get slow you can always push some of that functionality back down into C++. Many of them burn through lots of memory, though, and on a console memory is an even more scarce resource than CPU time. Unbounded memory consumption will crash you eventually, and if you have to allocate 4MB just for the interpreter, that's like having to throw 30 textures out the window to make room.
Lua has the advantage of being time-tested by a number of big-name video game developers and a good base of knowledgeable developers thanks to Blizzard-Activision's adoption of it as the primary platform for developing World of Warcraft add-ins.
What is a good scripting language to integrate into high-performance applications?
[ "", "c++", "performance", "scripting", "cross-platform", "" ]
1) How can a linux server be configured such that it can receive any emails sent to `account@domain.com`. 2) How can these emails be accessed and displayed by a PHP script? I'm building a simple web mail script, so i want to receive emails only for the registered email accounts and classify their emails and show them. Needs also to have the ability to show attachments.
The mail server itself can be setup to receive email with any number of MTA's (sendmail, postfix, exim, etc). You'll want SPAM protection and Virus scanning as well (again there are free packages in any distribution for this). Be warned, running your own mail server is NOT a job for the faint of heart these days. Once that's in place I would probably setup IMAP and use [PHP's IMAP functions](https://www.php.net/imap) to retrieve and parse the messages. Viewing attachments will be a lot harder if you want them readable in the browser, but easy to mark that they are there and make them downloadable. There is likely a class already written that does most of this for you (excepting the setup of course). Update: In fact there is an [old article at evolt](http://www.evolt.org/article/Incoming_Mail_and_PHP/18/27914/index.html) that appears to cover this.
Honestly, you're better off looking at one of the webmail systems already out there and modifying it to fit your needs rather than writing something from scratch. The email RFCs are a fun read (no, no they're not) and attachment handling has caused many developers to take up heavy drinking. Don't get me wrong, it can be done. Its just a lot of work and not something that you want to take on unless you have a bunch of time to dig deep into it. However, if you wanted to write something quick and simple, I suggest setting up a linux box with an Imap or pop server and then accessing that mailbox with the appropriate PHP / Pear libraries. That will be the quickest way to get going. But I would still recommend using one of the off the shelf solutions that are out there and hacking it up to fit your needs.
How to build a PHP webmail script?
[ "", "php", "email", "smtp", "" ]
In the following example code, I attach an `onclick` event handler to the span containing the text "foo". The handler is an anonymous function that pops up an `alert()`. However, if I assign to the parent node's `innerHTML`, this `onclick` event handler gets destroyed - clicking "foo" fails to pop up the alert box. Is this fixable? ``` <html> <head> <script type="text/javascript"> function start () { myspan = document.getElementById("myspan"); myspan.onclick = function() { alert ("hi"); }; mydiv = document.getElementById("mydiv"); mydiv.innerHTML += "bar"; } </script> </head> <body onload="start()"> <div id="mydiv" style="border: solid red 2px"> <span id="myspan">foo</span> </div> </body> </html> ```
Unfortunately, assignment to `innerHTML` causes the destruction of all child elements, even if you're trying to append. If you want to preserve child nodes (and their event handlers), you'll need to use [DOM functions](https://developer.mozilla.org/en/Gecko_DOM_Reference): ``` function start() { var myspan = document.getElementById("myspan"); myspan.onclick = function() { alert ("hi"); }; var mydiv = document.getElementById("mydiv"); mydiv.appendChild(document.createTextNode("bar")); } ``` **Edit:** Bob's solution, from the comments. Post your answer, Bob! Get credit for it. :-) ``` function start() { var myspan = document.getElementById("myspan"); myspan.onclick = function() { alert ("hi"); }; var mydiv = document.getElementById("mydiv"); var newcontent = document.createElement('div'); newcontent.innerHTML = "bar"; while (newcontent.firstChild) { mydiv.appendChild(newcontent.firstChild); } } ```
Using [`.insertAdjacentHTML()`](https://developer.mozilla.org/en/docs/Web/API/Element/insertAdjacentHTML) preserves event listeners, and [is supported by all major browsers](http://caniuse.com/#feat=insertadjacenthtml). It's a simple one-line replacement for `.innerHTML`. ``` var html_to_insert = "<p>New paragraph</p>"; // with .innerHTML, destroys event listeners document.getElementById('mydiv').innerHTML += html_to_insert; // with .insertAdjacentHTML, preserves event listeners document.getElementById('mydiv').insertAdjacentHTML('beforeend', html_to_insert); ``` The `'beforeend'` argument specifies where in the element to insert the HTML content. Options are `'beforebegin'`, `'afterbegin'`, `'beforeend'`, and `'afterend'`. Their corresponding locations are: ``` <!-- beforebegin --> <div id="mydiv"> <!-- afterbegin --> <p>Existing content in #mydiv</p> <!-- beforeend --> </div> <!-- afterend --> ```
Is it possible to append to innerHTML without destroying descendants' event listeners?
[ "", "javascript", "html", "innerhtml", "dom-events", "" ]
I've read that in PHP non-persistent open links are automatically closed at the end of the script's execution. So what's up with asp.net?
Yes you need to close open connections to database. ADO.NET has a connection pool, and open connections are reserved to you while it stays opened. When you close it, it will be available to other connection requests. But if you're using **DataAdapter**, and you don't open connection manually, you don't need to close it. *DataAdapter manages it and closes it's own connection* : ``` SqlConnection nwindConn = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind"); SqlCommand selectCMD = new SqlCommand("SELECT CustomerID, CompanyName FROM Customers", nwindConn); selectCMD.CommandTimeout = 30; SqlDataAdapter custDA = new SqlDataAdapter(); custDA.SelectCommand = selectCMD; DataSet custDS = new DataSet(); custDA.Fill(custDS, "Customers"); ```
Simple: PHP and ASP.NET aren't the same thing. They have different "rules". Don't try to write code in one environment as if it were the other. In .NET should almost always open a connection as late as you can and close it as early as you can, letting the built-in connection pool handle the "real" connection to the database. *Don't* leave it to the GC/finalizer to tidy up connections for you.
Do i need to close a MySqlConnection in asp.net?
[ "", "c#", "asp.net", "" ]
I would like to know how to put text into the clipboard like some popular websites are able to do. I have seen sites like www.photobucket.com and www.hulu.com somehow make copying to the clipboard automatic and cross browser. How can I do the same? I saw a cross browser way to do it using flash, but it won't work with the current version?
Take a look at this: <http://ajaxian.com/archives/seeding-the-clipboard-in-flash10-with-zero-clipboard>
One option is [Clippy](http://github.com/mojombo/clippy/tree/master), "a very simple Flash widget that makes it possible to place arbitrary text onto the client's clipboard.
Clipboard management with websites
[ "", "javascript", "html", "flash", "clipboard", "copy-paste", "" ]
Many a times we get an error, while trying to write file on Windows platform, "The process cannot access the file 'XXX' because it is being used by another process." How to check in C#, before writing to file that its not being used by another process?
You can't, basically - you have to attempt to open the file for writing, and if you get an exception you can't write to it :( Even if you could do a separate check first, the result would be out of date before you could start writing - you could still end up with the exception later. It would be nice if the framework provided a `TryOpen` method, admittedly...
The only option here is to catch the generated exception and handle it appropriately. See these other two SO threads for full discussions: * [How to check for file lock?](https://stackoverflow.com/questions/1304/how-to-check-for-file-lock-in-c) * [Detecting whether a file is locked by another process (or indeed the same process)](https://stackoverflow.com/questions/424830/detecting-whether-a-file-is-locked-by-another-process-or-indeed-the-same-process)
File used by another process
[ "", "c#", "file-io", "" ]
Is there a Lower Bound function on a `SortedList<K ,V>`? The function should return the first element equal to or greater than the specified key. Is there some other class that supports this? Guys - please read the question once again. **I do not need a function that returns the key if it is present. I'm interested in scenario when there is no exact key matching.** **I'm interested in O(log n) time**. It means that I do not have a problem with foreach loop, but rather would like to have an efficient way of doing this. I have done some tests on this. Linq statements are not optimized by neither the compiler nor runtime machine, so they walk through all collection elements and are slow O(n). Based on Mehrdad Afshari answer, here is a Binary Search that works in O(log n) on the Keys collection: ``` public static int FindFirstIndexGreaterThanOrEqualTo<T>( this IList<T> sortedCollection, T key ) where T : IComparable<T> { int begin = 0; int end = sortedCollection.Count; while (end > begin) { int index = (begin + end) / 2; T el = sortedCollection[index]; if (el.CompareTo(key) >= 0) end = index; else begin = index + 1; } return end; } ```
Binary search the `SortedList.Keys` collection. Here we go. This is O(log *n*): ``` private static int BinarySearch<T>(IList<T> list, T value) { if (list == null) throw new ArgumentNullException("list"); var comp = Comparer<T>.Default; int lo = 0, hi = list.Count - 1; while (lo < hi) { int m = (hi + lo) / 2; // this might overflow; be careful. if (comp.Compare(list[m], value) < 0) lo = m + 1; else hi = m - 1; } if (comp.Compare(list[lo], value) < 0) lo++; return lo; } public static int FindFirstIndexGreaterThanOrEqualTo<T,U> (this SortedList<T,U> sortedList, T key) { return BinarySearch(sortedList.Keys, key); } ```
I'd go with LINQ (presuming you're using C#3), but using the overload of FirstOrDefault that takes a predicate: ``` first = sortedList.FirstOrDefault(x => x >= theObjectForComparison); ``` (a lot of the other Enumerable methods can also take predicates which is a nice shortcut)
Is there a Lower Bound function on a SortedList<K ,V>?
[ "", "c#", ".net", "sortedlist", "" ]
There are times when I have a choice between using a CSS element:hover or JavaScript onmouseover to control the appearance of html elements on a page. Consider the following scenario where a div wraps an input ``` <div> <input id="input"> </div> ``` I want the input to change background color when the mouse cursor hovers over the div. The CSS approach is ``` <style> input {background-color:White;} div:hover input {background-color:Blue;} </style> <div><input></div> ``` The JavaScript approach is ``` <div onmouseover="document.getElementById('input').style.backgroundColor='Blue';"> <input id="input"> </div> ``` What are the advantages and disadvantages of each approach? Does the CSS approach work well with most web browsers? Is JavaScript slower than css?
The problem with :hover is that IE6 only supports it on links. I use jQuery for this kind of thing these days: ``` $("div input").hover(function() { $(this).addClass("blue"); }, function() { $(this).removeClass("blue"); }); ``` Makes things a lot easier. That'll work in IE6, FF, Chrome and Safari.
The CSS one is much more maintainable and readable.
CSS hover vs. JavaScript mouseover
[ "", "javascript", "css", "" ]
I have a large number objects which are tree like structures. I have a problem that the amount of memory the application uses starts to approach >1GB which means performance on the machine drops off and that there are out of memory instructions. I managed to solve this by using sqlite to put the objects to tables and thus effectively manage the data but this is no longer a possible solution (for reasons I wont go into here). What suggestions do you have for managing this sort of thing ? I have no (real) databases to use so I am thinking that a solution would be to somehow mimick the sqlite procedure and use some file back storage - is there anything that exists in pure dot net already or is it a complicated roll your own situation?
When you start storing a very large number of objects, object allocation overhead becomes a real issue. For example, with .NET running on a 32-bit system, allocating any object requires a minimum of 16 bytes. On a 64-bit system, you're talking 24 bytes minimum per object. If your individual objects are small, that allocation overhead is a huge price to pay. You said that you have a "tree like structure." Without more detail about your application, I can't say for certain that this applies, but most tree structures require pointers to child nodes and (sometimes) pointers back to the parent nodes. As useful as trees are, they sometimes incur very large overhead. It's not uncommon for the parent and child links to require 50% or more of the total memory used by your tree. In C#, you can alleviate the allocation overhead by using structs rather than objects, because structs have essentially no allocation overhead. The drawback, of course, is that you have to deal with the sometimes very inconvenient value type semantics. It's possible, too, to collapse many tree structures into arrays, eliminating child and parent links and thereby saving tremendous amounts of memory. This usually comes at the cost of more complicated code and some loss in runtime efficiency. In my work, I regularly have to keep very large collections (hundreds of millions of nodes) in memory. When you have 250 million records in memory, every four bytes in your node requires another gigabyte of RAM. Even on a 16-gigabyte machine, maintaining such data structures requires very careful thought about how memory is being used. If you must keep the entire thing in memory, then I would suggest that you make your tree nodes structs if at all possible. You should also consider alternate ways to store your tree--ways that eliminate explicit links to parents or children. Without more more information about your particular application, I can't make more specific recommendations.
Sounds like you need to investigate [Memory Mapped Files](http://en.wikipedia.org/wiki/Memory-mapped_file). I haven't used this [CodeProject article](http://www.codeproject.com/KB/recipes/MemoryMappedGenericArray.aspx) but it seems like a good starting point. Essentially you will be using [Win32 to implement a memory mapped file](http://msdn.microsoft.com/en-us/library/ms810613.aspx).
Managing large objects in C#
[ "", "c#", "memory-management", "" ]
Can anyone figure out a nice way to get the following code to work? (This is, once again, an incredibly simplified way of doing this) template <class f, class g> class Ptr; class RealBase { }; template <class a, class b, class c = Ptr<a,b> > class Base : public RealBase { public: Base(){}; }; template <class d, class e> class Derived : public Base <d,e> { public: Derived(){}; void DerivedMethod(){}; }; template <class f, class g> class Ptr { public: Ptr(){}; Ptr(Base<f,g,Ptr<f,g> >\* a){in = a;}; Base<f,g,Ptr<f,g> >\* operator->() { return in; }; private: Base<f,g,Ptr<f,g> >\* in; }; typedef Derived<double,double> DDerived; int main() { Base<int,int> b = Base<int,int>(); Derived<double,double> d = Derived<double,double>(); DDerived dd = DDerived(); Ptr<double,double> p(&dd); p->DerivedMethod(); return 1; } At the moment the compiler moans because a Base<> doesn't have a DerivedMethod(); EDIT I do understand the problem here, my bad for a lack of explanation in the first case (I was in a rush). [This is very cut down code by the way so, yes, for the sake of simplicity I don't have destructors or methods that actually DO anything. Just ignore that, it makes no difference to the problem.] What I need to happen is that an iterator (that isn't detailed here) that deals only with the derived class (D\_Derived) need to access a method that is contained within a derived class and not the base class. Simply plonking this method into the base class isn't really an option because this error is going to occur a LOT if I have to do that. (There are about 10 classes built on the real base class, and they all have derived methods of their own. Like 20 of them. Each.) Can anyone think of another way to achieve this functionality?
OK. After trying about 10 different methods (`static_cast`, `reinterpret_cast` etc.) you can just cast it. ``` int main() { Base&lt;int,int> b = Base&lt;int,int>(); Derived&lt;double,double> d = Derived&lt;double,double>(); DDerived dd = DDerived(); Ptr&lt;double,double> p(&dd); DDerived * fauxpointer; fauxpointer = (DDerived\*) &(*p); fauxpointer->DerivedMethod(); return 1; } ``` Nasty. But it works, and that's all that counts. Cheers to everyone who repeated the question back at me.
This code doesn't work because template class Ptr returns the object of Class of Base Template not Class of Derived Template. Derived Method is part of derived template so this throws compilation error. Whereas if DerivedMethod was part of Base Template this code will work
Inheritance issues with template classes
[ "", "c++", "inheritance", "" ]
i have the following template method, ``` template <class T> void Class::setData( vector<T> data ) { vector<T>::iterator it; } ``` and i'm getting the following compilation error ( XCode/gcc ) > error: expected `;' before 'it' i found someone else with a similar problem [here (read down to see it's the same even though it starts out with a different issue)](http://www.codeguru.com/forum/archive/index.php/t-221670.html) but they seem to have resolved by updating Visual Studio. This makes me guess that it is a compiler issue and that it should compile, is that correct? Iteration via indexing from 0 to size works, however it is not the way i would prefer to implement this function. Is there another way around this? Thanks
Classic case of when to use the `typename` keyword. Hoping that you have `#include`-ed `vector` and `iterator` and have a `using namespace std;` somewhere in scope. Use: ``` typename vector<T>::iterator it; ``` Look up dependent names. Start [here](http://pages.cs.wisc.edu/~driscoll/typename.html).
I think you are missing a `typename`: ``` #include <vector> using namespace std; class Class{ public: template <class T> void setData( vector<T> data ) { typename vector<T>::iterator it; } }; ```
STL iterator with custom template
[ "", "c++", "xcode", "gcc", "stl", "" ]
I'm a beginner C++ programmer and so I've learnt using arrays rather than vectors (this seems to be the general way to do things, then move on to vectors later on). I've noticed that a lot of answers on SO suggest using vectors over arrays, and strings over char arrays. It seems that this is the "proper" way to code in C++. That all being said, when is it still worth using a classic array/char\* (if ever)?
When writing code that should used in other projects, in particular if you target special platforms (embedded, game consoles, etc.) where STL might not be present. Old projects or projects with special requirements might not want to introduce dependencies on STL libraries. An interface depending on arrays, char\* or whatever will be compatible with anything since it's part of the language. STL however is not guaranteed to be present in all build environments.
***Never.*** If a raw array seems a better solution than a vector (for reasons other said here) then I use **std::tr1::array** or std::array in C++11 compilers (or [**boost::array**](http://www.boost.org/doc/libs/1_38_0/doc/html/array.html)). It simply does the checks I would do anyway to be sure and the size value usage makes DRY automatically implemented (for example I use the size in loops so that future changes of the array declaration will automatically work). It's the array implementation "is" a raw array with checks and provided size constant anyway, so it's easy to get the array code in embedded code too because [the code is not really "too smart"](http://www.boost.org/doc/libs/1_38_0/doc/html/boost/array.html) for any compiler. As far as the compiler support templates, I would copy the boost headers in my code to allow me to use this one instead of raw arrays. Because it's clearly too easy to make mistakes with raw arrays. [Raw arrays are *evil*.](http://www.parashift.com/c++-faq-lite/containers.html) They are error prone. And it work very well with STL algorithms (if available). Now, there is two cases where you **need** to use raw arrays (obligation) : when you're in C-only code (not communicating with C code, but writing in C-only part of code, like a C library). But then it's *another language*. The other reason is when the compiler don't support templates at all...
When would you use an array rather than a vector/string?
[ "", "c++", "arrays", "string", "vector", "" ]
I use JAXB to create XML messages. The XML I need to create is (for the sake of simplicity): ``` <request> <header/> </request> ``` My code looks like this: ``` import javax.xml.bind.annotation.*; @XmlRootElement(name = "request") public class Request { private String header; @XmlElement(required=true) public String getHeader() { return header; } public void setHeader(String header) { this.header=header; } } ``` The problem: the `header` element is not displayed (header is `null`). When header is set to an empty string, the following is displayed: ``` <request> <header></header> </request> ``` When I use as type `Object` instead of `String`, the result is even worse: ``` <request> <header xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></header> </request> ``` BTW: I'm using [this code](https://stackoverflow.com/questions/590405/generic-method-in-java-without-generic-argument/590418#590418) to create the XML string. Is it possible to get an empty tag?
In XML, `<header/>` and `<header></header>` are the same thing. If you really want the former, then use a prettifier. `javax.xml.transform.TransformerFactory.newTransformer()` will probably do that for you.
An empty tag for a String object is essentially the empty string. If you call the following, you will get what you are looking for: ``` request.setHeader("") ``` I should also note that in XML the following two declarations of a header are idential. Both of these have no child text nodes. These are essentially the same and will be treated the same by all XML parsers: ``` <header></header> <header/> ```
How to instantiate an empty element with JAXB
[ "", "java", "xml", "jaxb", "" ]
I am a newbie in programming and I want to write a program in Visual Studio with using C# language which uses a textbox and a button only. When the user writes string "A" in the textbox and presses the button, the program shows integer "5" in a messagebox. If the user writes string "B" in the textbox, the program shows integer "4" in a messagebox, and for string "C", it shows "3", and goes like that... The tricky (for me) part of this program is I am not able to use any decision structures like if,switch,etc. It is possible in some way that I don't know. Please help me to learn how to do it. Thanks for giving your time.
This works in Java, I think this will work in C# as well. If you subtract 'A' from the charachter the user enters you'll get an Int, 0 for A, 1 for B, etc. Basic maths can do the rest :) Don't forget to convert to a Char rather than subtracting strings.
You should not use a decision structure. The idea is to find the difference of the entered character from "A". Good luck!
How do I do my homework in C# without using certain decision structures?
[ "", "c#", "string", "char", "" ]
My application is written in python. What I am doing is I am running a script on each email received by postfix and do something with the email content. Procmail is responsible for running the script taking the email as input. The problem started when I was converting the input message(may be text) to email\_message object(because the latter comes in handy). I am using email.message\_from\_string (where email is the default email module, comes with python). `import email message = email.message_from_string(original_mail_content) message_body = message.get_payload()` This message\_body is sometimes returning a list[email.message.Message instance,email.message.Message instance] and sometime returning a string(actual body content of the incoming email). Why is it. And even I found one more observation. When I was browsing through the email.message.Message.get\_payload() docstring, I found this.. """ The payload will either be a list object or a string.If you mutate the list object, you modify the message's payload in place.....""" So how do I have generic method to get the body of email through python? Please help me out.
Well, the answers are correct, you should read the docs, but for an example of a generic way: ``` def get_first_text_part(msg): maintype = msg.get_content_maintype() if maintype == 'multipart': for part in msg.get_payload(): if part.get_content_maintype() == 'text': return part.get_payload() elif maintype == 'text': return msg.get_payload() ``` This is prone to some disaster, as it is conceivable the parts themselves might have multiparts, and it really only returns the first text part, so this might be wrong too, but you can play with it.
As crazy as it might seem, the reason for the sometimes string, sometimes list-semantics are [given in the documentation](http://docs.python.org/library/email.parser.html#email.message_from_string). Basically, multipart messages are returned as lists.
Email body is a string sometimes and a list sometimes. Why?
[ "", "python", "email", "message", "payload", "" ]
I am trying to wrap my head around the control infrastructure to understand which ones ASP.NET maintains view state for. There are these regular HTML controls ex: `<input type="radio" checked="checked"/>` -> I understand these do not have viewstate Then there are HTML controls with runat="server" `<input type="radio" checked="checked" runat="server"/>` -> Does the viewstate get maintained between postbacks? Then there are ASP.NET controls `<asp:TextBox id="txtMyText" runat="server"/>` -> I understand these do have viewstate We have a few custom controls that inherit HtmlTextBox `<myPrefix:myTextBox id="txtMyText" runat="server"/>` -> Is this the same as type 2 above? Is it safe to assume that any control with `runat="server"` tag will have viewstate maintained?
There are 3 types of controls, the standard HTML elements like , HTML server controls which have the runat=server tag added, and full web controls. Only the web controls have viewstate maintained.
When we were having problems with viewstate I started using the Viewstate helper software from Binary Fortress <http://www.binaryfortress.com/aspnet-viewstate-helper/> It gives you a real insight into what's going on - as well as helping with viewstate related performance issues you can decode the viewstate with one click and see what is actually in there - so you get to understand what controls are using viewstate and which aren't, and exactly what they are storing in there. Also, something nobody else has mentioned is ControlState. This came along with ASP.NET 2 and the *theory* is that the important stuff that is necesssary for a control to function goes in the control state, and the data etc in the viewstate, so you can switch off the viewstate and bind the data to your control on every postback and the control still basically works using controlstate. I say "theory" because in practice the implementation seems patchy. When you look into the dropdownlist code using reflector for example this isn't properly implemented. This may have changed with later releases of the framework, I'm not sure. Lots of info on controlstate out there if you search for it, I just thought I'd mention it.
Which controls have ViewState maintained?
[ "", "c#", ".net", "asp.net", "viewstate", "" ]
I am building a simple blog which is viewed single-page (do not worry, it is progressively built) and thus I am sending AJAX requests which return HTML to be inserted into the page. What is the most efficient way to store/cache information (HTML) to be added at a later time into the DOM? How much information (old entries which the user may return to) dare I save client side using JavaScript considering that they contain HTML for an entire article? Maybe I do not have to save them with JavaScript if I somehow make sure the clients browser cache the AJAX application's state (e.g. getHTML.php?article=4) so that it returns the HTML without really sending an AJAX request (after it has already been requested once)? Thanks in advance, Willem
I would recommend that you cache them somewhere inside the DOM itself, either at their natural place or in a "cache" `div`, just hide them or their container (`visibility: hidden`). Move them around the DOM (e.g. `final_container.appendChild(cache.removeChild(cached_item))`) and show them as required. This should give you the best bang for the buck in terms of memory efficiency, speed and simplicity when dealing with moderate amounts of cached information. With the proper cache directives inside your AJAX replies' headers, the browser might also perform caching for your AJAX replies just like for regular pages. Check out [this Browser-Side Cache article](http://ajaxpatterns.org/Browser-Side_Cache) for ideas, too.
Wouldn't it be better to let the browser cache these sort of requests? ``` getHTML.php?article=4 ``` It is silly to reinvent the wheel for such requests. **I think the only things you should cache is data that you *know* the user will toggle to view.** Take for example Digg -- they cache the comments on each submission in the format of an object in Javascript. When the user wants to view this comment, a function simply inserts it into the document in the correct format. However, not all comments are cached. Only the top ones, which are ones most likely to be viewed. Any information that you can "toggle" to show/hide, these can be cached, and even preloaded. You can also use the `visibility: hidden` and `display:none` technique as pointed out above. That way, you just transpose them to the DOM and simply show and hide that element when needed.
AJAX and Javascript cache efficiency question
[ "", "javascript", "ajax", "caching", "performance", "" ]
Using JavaScript, is there a way to update window.location.hash without scrolling the web page? I have clickable title elements that toggle the visibility of a div directly beneath them. I want the /foo#bar in the history when clicking titles but don't want the page scrolling about. So when navigating away from /foo#bar I'll be able to use the back button and have the div whose ID is in window.location.hash be visible upon return. Is this behavior possible?
This behavior is very much possible. You should look into some of the libraries that have been developed to give you this functionality. Really Simple History: <http://code.google.com/p/reallysimplehistory/> SWFAddress: <http://www.asual.com/swfaddress/>
To change the hash without having the page reload/scroll, you can now simply use html5 `history.pushState`. ``` history.pushState(null,null,'#hashexample'); ``` It's supported by all the major browsers: <http://caniuse.com/history> MDN: <https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_pushState().C2.A0method> Also note that the last url parameter we're using here can be any url, so it's not limited to hashes.
Can I update window.location.hash without having the web page scroll?
[ "", "javascript", "browser-history", "back-button", "deep-linking", "" ]
I am writing a very simple RMI server, and I am seeing intermittent `java.rmi.NoSuchObjectExceptions` in the unit tests. I have a string of remote method calls on the same object, and while the first few go through, the later ones will sometimes fail. I am not doing anything to unregister the server object in between. These error do not appear always, and if I put in breakpoints they tend to not appear. Are those Heisenbugs, whose race conditions dissolve when looking at them through the slowed down execution of the debugger? There is no multi-threading going on in my test or server code (though maybe inside of the RMI stack?). I am running this on Mac OS X 10.5 (Java 1.5) through Eclipse's JUnit plugin, and the RMI server and client are both in the same JVM. What can cause these exceptions?
**Keep a strong reference to the object that implements the `java.rmi.Remote` interface so that it remains [reachable](http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.6.1), i.e. ineligible for garbage collection.** Below is a short program that demonstrates a [`java.rmi.NoSuchObjectException`](http://java.sun.com/javase/6/docs/api/java/rmi/NoSuchObjectException.html). The script is self-contained, creating an RMI registry as well as a "client" and a "server" in a single JVM. Simply copy this code and save it in a file named `RMITest.java`. Compile and invoke with your choice of command line arguments: * **`-gc`** (default) Explicitly instruct the JVM to make "a best effort" to run the garbage collector after the server is started, but before the client connects to the server. This will likely cause the `Remote` object to be reclaimed by the garbage collector *if the strong reference to the `Remote` object is **released***. A `java.rmi.NoSuchObjectException` is observed when the client connects after the `Remote` object is reclaimed. * **`-nogc`** Do not explicitly request garbage collection. This will likely cause the `Remote` object to remain accessible by the client regardless of whether a strong reference is held or released *unless there is a sufficient **delay** between the server start and the client call such that the system "naturally" invokes the garbage collector and reclaims the `Remote` object*. * **`-hold`** Retain a strong reference to the `Remote` object. In this case, a class variable refers to the `Remote` object. * **`-release`** (default) A strong reference to the `Remote` object will be released. In this case, a method variable refers to the `Remote` object. After the method returns, the strong reference is lost. * **`-delay<S>`** The number of seconds to wait between server start and the client call. Inserting a delay provides time for the garbage collector to run "naturally." This simulates a process that "works" initially, but fails after some significant time has passed. Note there is no space before the number of seconds. Example: `-delay5` will make the client call 5 seconds after the server is started. Program behavior will likely vary from machine to machine and JVM to JVM because things like `System.gc()` are only hints and setting the `-delay<S>` option is a guessing game with respect to the behavior of the garbage collector. On my machine, after `javac RMITest.java` to compile, I see this behavior: ``` $ java RMITest -nogc -hold received: foo $ java RMITest -nogc -release received: foo $ java RMITest -gc -hold received: foo $ java RMITest -gc -release Exception in thread "main" java.rmi.NoSuchObjectException: no such object in table at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:255) at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:233) at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:142) at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:178) at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:132) at $Proxy0.remoteOperation(Unknown Source) at RMITest.client(RMITest.java:69) at RMITest.main(RMITest.java:46) ``` Here is the source code: ``` import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import static java.util.concurrent.TimeUnit.*; interface RemoteOperations extends Remote { String remoteOperation() throws RemoteException; } public final class RMITest implements RemoteOperations { private static final String REMOTE_NAME = RemoteOperations.class.getName(); private static final RemoteOperations classVariable = new RMITest(); private static boolean holdStrongReference = false; private static boolean invokeGarbageCollector = true; private static int delay = 0; public static void main(final String... args) throws Exception { for (final String arg : args) { if ("-gc".equals(arg)) { invokeGarbageCollector = true; } else if ("-nogc".equals(arg)) { invokeGarbageCollector = false; } else if ("-hold".equals(arg)) { holdStrongReference = true; } else if ("-release".equals(arg)) { holdStrongReference = false; } else if (arg.startsWith("-delay")) { delay = Integer.parseInt(arg.substring("-delay".length())); } else { System.err.println("usage: javac RMITest.java && java RMITest [-gc] [-nogc] [-hold] [-release] [-delay<seconds>]"); System.exit(1); } } server(); if (invokeGarbageCollector) { System.gc(); } if (delay > 0) { System.out.println("delaying " + delay + " seconds"); final long milliseconds = MILLISECONDS.convert(delay, SECONDS); Thread.sleep(milliseconds); } client(); System.exit(0); // stop RMI server thread } @Override public String remoteOperation() { return "foo"; } private static void server() throws Exception { // This reference is eligible for GC after this method returns final RemoteOperations methodVariable = new RMITest(); final RemoteOperations toBeStubbed = holdStrongReference ? classVariable : methodVariable; final Remote remote = UnicastRemoteObject.exportObject(toBeStubbed, 0); final Registry registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT); registry.bind(REMOTE_NAME, remote); } private static void client() throws Exception { final Registry registry = LocateRegistry.getRegistry(); final Remote remote = registry.lookup(REMOTE_NAME); final RemoteOperations stub = RemoteOperations.class.cast(remote); final String message = stub.remoteOperation(); System.out.println("received: " + message); } } ```
Some other questions to consider - First are you referencing an object instance or is the stub interface itself gone? If some object instance is gone, its for the usual reasons, it got dereferenced and GC'd, but if it's the interface then your RMI server end point loop quit for some reason. The best debugging tool I've found so far is to turn on the java.rmi.server.logCalls=true property (see <http://java.sun.com/j2se/1.5.0/docs/guide/rmi/javarmiproperties.html>) and watch all the wonderfull information stream down your log window. This tells me what's up every time. jos
java.rmi.NoSuchObjectException: no such object in table
[ "", "java", "exception", "rmi", "" ]
I extract some code from a web page (<http://www.opensolaris.org/os/community/on/flag-days/all/>) like follows, ``` <tr class="build"> <th colspan="0">Build 110</th> </tr> <tr class="arccase project flagday"> <td>Feb-25</td> <td></td> <td></td> <td></td> <td> <a href="../pages/2009022501/">Flag Day and Heads Up: Power Aware Dispatcher and Deep C-States</a><br /> cpupm keyword mode extensions - <a href="/os/community/arc/caselog/2008/777/">PSARC/2008/777</a><br /> CPU Deep Idle Keyword - <a href="/os/community/arc/caselog/2008/663/">PSARC/2008/663</a><br /> </td> </tr> ``` and there are some relative url path in it, now I want to search it with regular expression and replace them with absolute url path. Since I know urljoin can do the replace work like that, ``` >>> urljoin("http://www.opensolaris.org/os/community/on/flag-days/all/", ... "/os/community/arc/caselog/2008/777/") 'http://www.opensolaris.org/os/community/arc/caselog/2008/777/' ``` Now I want to know that how to search them using regular expressions, and finally tanslate the code to, ``` <tr class="build"> <th colspan="0">Build 110</th> </tr> <tr class="arccase project flagday"> <td>Feb-25</td> <td></td> <td></td> <td></td> <td> <a href="http://www.opensolaris.org/os/community/on/flag-days/all//pages/2009022501/">Flag Day and Heads Up: Power Aware Dispatcher and Deep C-States</a><br /> cpupm keyword mode extensions - <a href="http://www.opensolaris.org/os/community/arc/caselog/2008/777/">PSARC/2008/777</a><br /> CPU Deep Idle Keyword - <a href="http://www.opensolaris.org/os/community/arc/caselog/2008/663/">PSARC/2008/663</a><br /> </td> </tr> ``` My knowledge of regular expressions is so poor that I want to know how to do that. Thanks **I have finished the work using Beautiful Soup, haha~ Thx for everybody!**
First, I'd recommend using a HTML parser, such as [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/). HTML is not a regular language, and thus can't be parsed fully by regular expressions alone. Parts of HTML can be parsed though. If you don't want to use a full HTML parser, you could use something like this to approximate the work: ``` import re, urlparse find_re = re.compile(r'\bhref\s*=\s*("[^"]*"|\'[^\']*\'|[^"\'<>=\s]+)') def fix_urls(document, base_url): ret = [] last_end = 0 for match in find_re.finditer(document): url = match.group(1) if url[0] in "\"'": url = url.strip(url[0]) parsed = urlparse.urlparse(url) if parsed.scheme == parsed.netloc == '': #relative to domain url = urlparse.urljoin(base_url, url) ret.append(document[last_end:match.start(1)]) ret.append('"%s"' % (url,)) last_end = match.end(1) ret.append(document[last_end:]) return ''.join(ret) ``` Example: ``` >>> document = '''<tr class="build"><th colspan="0">Build 110</th></tr> <tr class="arccase project flagday"><td>Feb-25</td><td></td><td></td><td></td><td><a href="../pages/2009022501/">Flag Day and Heads Up: Power Aware Dispatcher and Deep C-States</a><br />cpupm keyword mode extensions - <a href="/os/community/arc/caselog/2008/777/">PSARC/2008/777</a><br /> CPU Deep Idle Keyword - <a href="/os/community/arc/caselog/2008/663/">PSARC/2008/663</a><br /></td></tr>''' >>> fix_urls(document,"http://www.opensolaris.org/os/community/on/flag-days/all/") '<tr class="build"><th colspan="0">Build 110</th></tr> <tr class="arccase project flagday"><td>Feb-25</td><td></td><td></td><td></td><td><a href="http://www.opensolaris.org/os/community/on/flag-days/pages/2009022501/">Flag Day and Heads Up: Power Aware Dispatcher and Deep C-States</a><br />cpupm keyword mode extensions - <a href="http://www.opensolaris.org/os/community/arc/caselog/2008/777/">PSARC/2008/777</a><br /> CPU Deep Idle Keyword - <a href="http://www.opensolaris.org/os/community/arc/caselog/2008/663/">PSARC/2008/663</a><br /></td></tr>' >>> ```
I'm not sure about what you're trying to achieve but using the [BASE tag in HTML](http://www.w3schools.com/TAGS/tag_base.asp) may do this trick for you without having to resort to regular expressions when doing the processing.
How to find a relative URL and translate it to an absolute URL in Python
[ "", "python", "regex", "" ]
I have some public user defined classes with relations between their members and also several methods with specific and generic signatures. I would like to be able to store and manipulate custom control flow over these classes (plus CLR classes) using basic control statements like if/then/else, foreach, do/while, variable assignments etc. The custom control flow should be created at runtime and then stored for later use and manipulation. The idea is to have a data representation of the control flow, possibly in the form of a abstract syntax tree, with **strongly typed syntax** in order to be able to apply genetic operations. The resulting custom code has to be executed as part of another program. 1) What is the preferred code representation for manipulating genetic operations and then execute the code including my classes, 2) Which c# technologies should I use for the above problem? I know there are related technologies like reflection, the new c# 3.0 features (lambda, expression trees), CodeDom, DLR library, etc but which approach or combination is the most efficient. 3) Are there such paradigms or implementations available? EDIT: The platform is supplied with data of defined c# custom types, both constant and time variable. Every moment rules are applied to the data (basic conditions or more complicated functions) and it is decided to take some actions. I would like to be able to: Represent the rules on a tree or a graph and execute tha flow. Create custom rule sets by the user via a UI toolkit Make rearrangement on the tree or graph and apply GP operations
Reflection is the technology to inspect already generated types, methods, fields, etc., hence it'll probably not help you much for now. Expression trees are rather interesting, but AFAIK they will not allow you to create complex program flow since a lambda expression cannot have a body, which would make it rather difficult to create anything moderately complex. DLR is somewhat in the making. You will get the bits and pieces, but only the next .NET version will have baked-in support for the DLR. That could be an interesting alternative, by creating programs on the fly and executing them. What you could do now is possibly emitting IL, either in a Dynamic Method or a dynamically generated assembly. All possible constructs should be available to you, but a subsequent manipulation is probably rather difficult. Even so, there is one project that does quite a bit of IL magic and it may even be something that could be useful to you: [LinFu](http://www.codeproject.com/KB/cs/LinFuPart1.aspx). According to the list you have an implementation of Dynamic Object and can do stuff like dynamicObject.CreateDuck<InterfaceType>() Another route which may be a bit heavy but also interesting is the WF (Workflow Foundation) Framework. Such workflows should be constructable by program and they may be interesting due to their continuation style working: You can persist a running workflow any time and pick it up just where you left it. All traditional program structures should be available to you within WF.
Breeding programs represented in languages such as C# is very tricky - they simply aren't designed to be malleable - you will find that the vast majority of changes you make simply cause the program to fail. I would recommend one of two alternative approaches: 1. Pseudo-machine language, using pattern-matching on two kinds of NOPs to allow branching or looping; 2. A LISP-link language, using recursion on named functions to allow iteration. (1) is representable using a linear sequence of instructions and some form of virtual register or stack machine. (2) is representable using a tree, and evaluated using some form of "reduce" algorithm. Whatever approach you use, you'll need to execute the programs in a sandbox - infinite loops will be common, so you'll need to be able to stop them after a set number of cycles.
C# Dynamic Trees for Genetic Programming
[ "", "c#", "expression-trees", "genetic-programming", "" ]
I'm just starting to use [Maven](http://en.wikipedia.org/wiki/Apache_Maven), (evaluating it, really) and I need to be able to quickly generate a [JAR](http://en.wikipedia.org/wiki/JAR_file) file for my application and a directory with all the dependencies (for example, lib) so that I can deploy those two to be run in a stand-alone manner. Generating the JAR file with the proper manifest is easy, but I do not know how to get Maven to copy the dependencies for the current project into a `lib` directory that I can deploy. Since this is for a stand-alone Java applications, I am *not* interested in deploying to a Maven repository, that is also fairly trivial, or at least easily googleable. I've found out how to do everything *except* copy the dependent JAR files into some specified directory. This is the workflow I'm looking for: ``` $ mvn clean $ mvn package $ cp -r target/{lib,myApp.jar} installLocation ``` Then, running `myApp.jar` from `installLocation` as a JAR file should "just work" regardless of my `$CLASSPATH`. To try and pre-empt some answers: * I do have a Main-class: set, and it works fine. * I've also set the classpath in the MANIFEST.MF, and that works fine too. * I've found out how to use `<classpathPrefix>` and `<classpathMavenRepositoryLayout>` to make this work -- but only on my machine. (via: `<classpathPrefix>${settings.localRepository}</classpathPrefix>`)
What you want to investigate is [Maven's dependency plugin](http://maven.apache.org/plugins/maven-dependency-plugin "Maven Dependency Plugin"). Add something similar to the following to pom.xml: ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <configuration> <outputDirectory> ${project.build.directory} </outputDirectory> </configuration> </plugin> ``` Then run `mvn clean dependency:copy-dependencies` to copy perform the copy. Combine this with the [assembly plugin](http://maven.apache.org/plugins/maven-assembly-plugin/ "Maven Assembly Plugin") and you can package everything into a self contained archive for distribution.
I did not care for the Shade plugin since it rolls all the packages from all the jars together. To include all of the external libs you can use the Dependency Plugin as mentioned above. This example will create a "lib" directory under "target/classes" before the "package" phase. ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.6</version> <executions> <execution> <id>copy-dependencies</id> <phase>prepare-package</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>target/classes/lib</outputDirectory> <overWriteIfNewer>true</overWriteIfNewer> <excludeGroupIds> junit,org.hamcrest,org.mockito,org.powermock,${project.groupId} </excludeGroupIds> </configuration> </execution> <execution> <phase>generate-sources</phase> <goals> <goal>sources</goal> </goals> </execution> </executions> <configuration> <verbose>true</verbose> <detail>true</detail> <outputDirectory>${project.build.directory}</outputDirectory> </configuration> </plugin> ```
Can Maven collect all the dependent JARs for a project to help with application deployment?
[ "", "java", "deployment", "maven-2", "desktop-application", "" ]
Similar to how database connections made within the scope of a TransactionScope will behave accordingly, I want to be able to test inside my class whether it is within an instance of another class? **My Scenario** I have a class (EntityBase) that all database objects are built upon, and has methods such as AddToDatabase, UpdateInDatabase, DeleteFromDatabase. I want to create a BulkLoader class, that will handle inserts in a bulk fashion. This will then have a complete method, like the TransactionScope class, which will be the point that the data is loaded to the database. This will require changing the EntityBase class so that it behaves differently if it is being instanitated within the scope of a BulkLoader class, and interacting with that class. Example code: ``` using (BulkLoader bulk = new BulkLoader(connection, transaction)) { foreach (IToDatabase assignment in assignmentsCollection) { assignment.WriteToDataBase(connection, transaction); } bulk.Complete(); } class ClientAssignment : IToDatabase { public int WriteToDataBase(IDbConnection connection, IDbTransaction transaction) { foreach (EntityBase account in accountsCollection) { account.AddToDataBase(connection, transaction); } foreach (EntityBase person in personsCollection) { person.AddToDataBase(connection, transaction); } } } class EntityBase { public virtual int AddToDatabase(IDbConnection connection, IDbTransaction transaction) { // question relates to this bit if (inBulkLoaderClass) { // interact with bulk loader } else { // do existing code } } } ```
You could use [ThreadStaticAttribute](http://msdn.microsoft.com/en-us/library/system.threadstaticattribute.aspx): ``` public class BulkLoader : IDisposable { [ThreadStatic] private static BulkLoader currentBulkLoader; public BulkLoader() { if (InBulkLoader) { throw new InvalidOperationException(); } currentBulkLoader = this; } public void Dispose() { currentBulkLoader = null; } public static bool InBulkLoader { get { return currentBulkLoader != null; } } public static BulkLoader CurrentBulkLoader { get { return currentBulkLoader; } } } ``` I'm not generally keen on thread statics, but I think it's probably okay in this case. The check in the constructor makes sure you'll never be in a "nested" bulk loader. If you *want* to be able to nest them, keep a counter instead (increment in the constructor, decrement in the Dispose call).
Well, there are some things you can do with ambient objects (in particular thread-static fields), but it isn't pretty. I'd argue that if the logic is different, it should be a separate method in the first place. Also, note that one point of view is that entity objects shoudn't be talking to the database anyway - their job is to represent the state of an object; it is the job of a repository class (or similar) to worry about persistance. Then you repository would have two strategies to cope with things. Perhaps there is an IBulkRepository interface that the repo could (optionally) implement, etc.
How can I check if the current operation is in the scope of an object?
[ "", "c#", ".net-2.0", "" ]
when I code: ``` var a = function() { alert("44") return function(){alert(33)} }()(); ``` is this expression evaluated in the following order? 1. define the function; 2. pass its reference pointer to a 3. a() is invoked 4. return in a a new function pointer 5. a() is invoked again and if so why do I have a syntax error if I do: ``` function() { alert("44") return function(){alert(33)} }(); ``` the interpreter wants a left operand first... but this syntax works: ``` ( function() { alert("44") return function(){alert(33)} }; )() ``` the outer parenthesis what does meaning??? Thanks
It's the syntax of the language. If you want to in-place execute an anonymous function, you must enclose it in parens. JS has these edge cases where the syntax is weirder than you expect. Take for example, evaling a string that has a JSON doesn't work unless it's wrapped with parens. ``` // Wrong eval("{ ... }"); // Right eval("({ ... })"); ``` It's the syntax of the language. That said, I think (and this is strictly IMHO), the steps you've outlined are not accurate. 1. Function is defined and invoked. alert("44"); happens as a result. 2. The function returns another function which is also invoked. alert("33"); happens. 3. The innermost function doesn't return anything, so a is effectively undefined. typeof a returns "undefined".
1. **`function() { alert("44") return function(){alert(33)} }`** *you define the function* 2. `function() { alert("44") return function(){alert(33)} }`**`()`** *you call that function returning anonymous function* `function(){alert(33)}` 3. `function() { alert("44") return function(){alert(33)} }()`**`()`** *you call returned function, so it's actually equivalent to* `function(){alert(33)}()` So the whole execution is equivalent to: ``` alert("44"); alert(33); ```
self-invoking functions
[ "", "javascript", "function", "" ]
I need to sort two arrays simultaneously, or rather I need to sort one of the arrays and bring the corresponding element of its associated array with it as I sort. That is if the array is [(5, 33), (4, 44), (3, 55)] and I sort by the first axis (labeled below dtype='alpha') then I want: [(3.0, 55.0) (4.0, 44.0) (5.0, 33.0)]. These are really big data sets and I need to sort first ( for nlog(n) speed ) before I do some other operations. I don't know how to merge my two separate arrays though in the proper manner to get the sort algorithm working. I think my problem is rather simple. I tried three different methods: ``` import numpy x=numpy.asarray([5,4,3]) y=numpy.asarray([33,44,55]) dtype=[('alpha',float), ('beta',float)] values=numpy.array([(x),(y)]) values=numpy.rollaxis(values,1) #values = numpy.array(values, dtype=dtype) #a=numpy.array(values,dtype=dtype) #q=numpy.sort(a,order='alpha') print "Try 1:\n", values values=numpy.empty((len(x),2)) for n in range (len(x)): values[n][0]=y[n] values[n][1]=x[n] print "Try 2:\n", values #values = numpy.array(values, dtype=dtype) #a=numpy.array(values,dtype=dtype) #q=numpy.sort(a,order='alpha') ### values = [(x[0], y[0]), (x[1],y[1]) , (x[2],y[2])] print "Try 3:\n", values values = numpy.array(values, dtype=dtype) a=numpy.array(values,dtype=dtype) q=numpy.sort(a,order='alpha') print "Result:\n",q ``` I commented out the first and second trys because they create errors, I knew the third one would work because that was mirroring what I saw when I was RTFM. Given the arrays x and y (which are very large, just examples shown) how do I construct the array (called values) that can be called by numpy.sort properly? \*\*\* Zip works great, thanks. Bonus question: How can I later unzip the sorted data into two arrays again?
I think what you want is the zip function. If you have ``` x = [1,2,3] y = [4,5,6] ``` then `zip(x,y) == [(1,4),(2,5),(3,6)]` So your array could be constructed using ``` a = numpy.array(zip(x,y), dtype=dtype) ```
for your bonus question -- zip actually unzips too: ``` In [1]: a = range(10) In [2]: b = range(10, 20) In [3]: c = zip(a, b) In [4]: c Out[4]: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)] In [5]: d, e = zip(*c) In [6]: d, e Out[6]: ((0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (10, 11, 12, 13, 14, 15, 16, 17, 18, 19)) ```
How do you construct an array suitable for numpy sorting?
[ "", "python", "algorithm", "arrays", "numpy", "" ]
What are the pros and cons of using **@Autowired** in a class that will be wired up by Spring? Just to clarify, I'm talking specifically about the **@Autowired** annotation, not auto-wiring in XML. I probably just don't understand it, but to me it almost seems like an anti-pattern - your classes start to become aware that they are tied to a DI framework, rather than just being POJOs. Maybe I'm a glutton for punishment, but I like having the external XML config for beans, and I like to have explicit wirings, so I know exactly what is wired where.
For a long time I believed that there was a value in having a "centralized, declarative, configuration" like the xml files we all used to use. Then I realized that most of the stuff in the files wasn't *configuration* - it was never changed anywhere after development, ever. Then I realized that "centralized" only has value in quite small systems - only in small systems will you ever be able to grok a configuration file *as a whole*. And what is really the value of understanding the wiring as a whole, when the same "wirings" are mostly duplicated by dependencies in the code? So the only thing I've kept is meta-data (annotations), which is still kind-of declarative. These *never* change at runtime and they're *never* "configuration" data that someone will change on the fly - so I think keeping it in the code is nice. I use full auto-wiring as much as I can. I love it. I won't go back to old-style spring unless threatened at gun-point. My reasons for preferring fully `@Autowired` have changed over time. Right now I think the most important reason for using autowiring is that there's one less abstraction in your system to keep track of. The "bean name" is effectively gone. It turns out the bean name only exists because of xml. So a full layer of abstract indirections (where you would wire bean-name "foo" into bean "bar") is gone. Now I wire the "Foo" interface into my bean directly, and implementation is chosen by run-time profile. This allows me to *work with code* when tracing dependencies and implementations. When I see an autowired dependency in my code I can just press the "go to implementation" key in my IDE and up comes the list of known implementations. In most cases there's just one implementation and I'm straight into the class. Can't be much simpler than that, and I always know *exactly* what implementation is being used (I claim that the opposite is closer to the truth with xml wiring - funny how your perspective changes!) Now you could say that it's just a very simple layer, but each layer of abstraction that we add to our systems *increase* complexity. I really don't think the xml ever added any real value to any system I've worked with. Most systems I've ever work with only have *one* configuration of the production runtime environment. There may be other configurations for test and so on. I'd say that full autowiring is the ruby-on-rails of spring: It embraces the notion that there's a normal and common usage pattern that most use cases follow. With XML configuration you *permit* a lot of consistent/inconsistent configuration usage that may/may not be intended. I've seen so much xml configuration go overboard with inconsistencies - does it get refactored together with the code ? Thought not. Are those variations there for a reason? Usually not. We hardly use qualifiers in our configuration, and found other ways to solve these situations. This is a clear "disadvantage" we encounter: We've slightly changed the way we code to make it interact smoother with autowiring: A customer repository no longer implements the generic `Repository<Customer>` interface but we make an interface `CustomerRepository` that extends `Repository<Customer>`. Sometimes there's also a trick or two when it comes to subclassing. But it usually just points us in the direction of stronger typing, which I find is almost always a better solution. But yes, you're tying to a particular style of DI that mostly spring does. We don't even make public setters for dependencies any more (So you could argue that we're +1 in the encapsulation/information hiding department) We still have some xml in our system, but the xml basically *only* contains the anomalies. Full autowiring integrates nicely with xml. The only thing we need now is for the `@Component`, `@Autowired` and the rest to be included in a JSR (like [JSR-250](https://www.jcp.org/en/jsr/detail?id=250)), so we don't have to tie in with spring. This is the way things have been happening in the past (the `java.util.concurrent` stuff springs to mind), so I wouldn't be entirely surprised if this happened again.
For me here is what I like/dislike about Spring and auto-wiring. Pros: * Auto-wiring gets rid of nasty XML configuration. * Much easier to use annotations which allows you to inject directly using fields, setter methods, or constructors. Also allows you to annotate and 'qualify' your injected beans. Cons: * Using auto-wiring and annotations makes you dependent on Spring libraries where as with XML configuration you could chose to run with or without Spring. Like you said, you become tied to a DI framework. * At the same time I like being able to 'qualify' beans, to me this makes the code really messy. If you need to inject the same bean in multiple places, I've seen the same string name repeated all over. To me this seems to have the potential for errors. I've started using auto-wiring almost exclusively at work because we depend so much on Spring integration anyway that the dependency issue is moot. I worked on a Spring MVC project that used auto-wiring extensively and was a little hard to wrap my head around. I think auto-wiring is an acquired taste, once you get used to it you realize how powerful, easy, and much less of a headache it is to work with than the XML configuration.
Spring @Autowired usage
[ "", "java", "spring", "autowired", "" ]
I need to throw together a quick CRUD asp.net site, but this may become a bigger application down the road. I have some experience with [SubSonic](http://subsonicproject.com/), but it has been so long since I did a project with it I have to relearn it. I am also considering using [Dynamic Data](http://www.asp.net/dynamicdata/). Does anyone have any experience with these tools that can tell me which way I should go?
I use subsonic for almost everything these days. The advantage of SubSonic is that you can build whatever abstraction layer you want on top of it, if you need to enhance/extend it later - it really only serves one main purpose - taking the crap out of creating crud code. I've not used dynamic data extensively, but from what I've read, it seems like it creates a lot of the scaffolding for you, and it might not mix well with a more extensive application. If you need future extensibility, I'd recommend subsonic, but dynamic data may be the way to go for short one-off applications strictly used to maintain a database via the web.
I have used SubSonic before and in my case it worked great. If all you need is an abstraction layer SubSonic does a great job while keeping setup and knowledge curve very simple. I am not sure about Dynamic Data but with Subsonic as your database grows the process to regenerate classes is very simple. Also, Subsonic works well with views and stored procedures everything can be accessed from the your classes. The tutorial are helpful for setting up data providers and references. Not sure if there is much help with Dynamic Data. So if you are looking for quick and easy I would say SubSonic is the way to go.
Should I use SubSonic or Dynamic Data for a new CRUD asp.net application?
[ "", "c#", "asp.net", "vb.net", "subsonic", "dynamic-data", "" ]
I have the following code ``` class Program { static void Main(string[] args) { List<A> aList = new List<A>(); var aObj = new A(); aObj.Go(aList.Cast<IB>()); } } class A : IB { public void Go(IEnumerable<IB> interfaceList) { foreach (IB ibby in interfaceList) { Console.WriteLine("Here"); } } } interface IB { void Go(IEnumerable<IB> interfaceList); } ``` } I originally tried passing a List but that [doesn't work](http://blogs.msdn.com/ericlippert/archive/2007/10/17/covariance-and-contravariance-in-c-part-two-array-covariance.aspx). After a lot of help from [SO](https://stackoverflow.com/questions/504729/how-do-i-cast-a-listt-effectively) I found that passing IEnumerable is the only way to get the objects across as .ofType(IB). Unfortunately for me, in my code the following line will be executed thousands of times: ``` aList.Cast<IB>(); ``` I was wondering if anyone knew how it was implemented algorithmically (in IL) and what its time order is. That is to say, is it faster than a foreach loop that just casts each item, or is that exactly what it does? **EDIT** The main class needs to maintain a list of the actual objects. But the reader is only allowed to touch them through the interface.
You should change `Go` to: ``` public void Go<T>(IEnumerable<T> interfaceList) where T : IB { foreach (IB ibby in interfaceList) { Console.WriteLine("Here"); } } ``` Then you'll be fine with no need to call `Cast`. I suspect the source code implementation of Cast is pretty simple, although I believe it changed between 3.5 and 3.5SP1. However, it probably needs to set up a new state machine etc in the normal iterator block fashion. Better to avoid it if possible. Even though the new method is generic, type inference should usually take care of it for you so you don't need to specify `T` explicitly.
Why not just declare the list like: ``` List<IB> aList = new List<IB>(); ``` Is there something in particular that requires you to have a list of the concrete classes? --- So in that case I'd make the list part of the domain. Have an interface like IIBCollection (for example), expose the methods on that you want the reader to be able to access. For example: ``` interface IIBCollection{ IEnumerable<IB> IBs { get; } } // and in your implementation you can do IEnumerable<IB> IBs { get { foreach(IB ib in innerList) yield return ib; }} ```
List<T> Casting algorithms and performance considerations
[ "", "c#", "performance", "casting", "generic-list", "" ]
I'm working on an MFC program that started way back in the VC6 days. Back then there was a class wizard that used a bunch of decorators and markup in comments to parse class files. For example, it would insert `afx_msg` in front of message handlers that it maintained. It would mark a block of code with `//{{AFX_MSG_MAP(TheApp)` and `}}AFX_MSG_MAP` comments to help it find the parts of the message map it wanted to handle. AFAIK, this isn't needed anymore. Besides that, there were so many shortcomings with the class wizard that we had to do a lot of manual editing of these managed blocks and we never used it very often anyways. Are there any other reasons to keep using `afx_msg` and its ilk?
`afx_msg` still exists but has always been purely informative. A decorator as you put it. It's always been `#defined` as an empty string. The `{{` and `}}` markers are no longer needed since VS2003: VS is now smart enough to put things in the right place without having to rely on these markers. You'll notice that VS2003+ no longer includes these lines in the projects it creates.
AFAIK, `afx_msg` is no longer used. The other marker were used to help CW figure out where to put things, and some of them may still be used (eg: message map location in the .cpp files). The ones in the header files are probably more safe to remove, but I wouldn't take them out arbitrarily. One thing you could do: start a new dummy MFC project in your current VS version, add a window class and a few handlers, and observe the notations currently created. Anything not put in is probably no longer used, and anything still inserted is probably still used in some form). PS: MS is well aware of the issues with the current CW editing, and I'm told they will be addressed to a large extent in VS2010... we shall see.
Are things like "afx_msg" decorators still used by VS/MFC?
[ "", "c++", "visual-studio", "mfc", "" ]
G'day all, I am coding a main menu for a project. The menu displays properly. I have also set up ActionListeners for the three buttons on the menu. What I wish to do is reuse the JPanel for a new set of radio buttons when the user chooses "Start a New Game". However, coding ActionPerformed to remove the existing components from the JPanel has me stumped. I know removeAll is somehow important, but unfortunately NetBeans informs me I cannot call it on my mainMenu JPanel object within ActionPerformed. So i have commented it out in my code below, but left it in so you can see what I am trying to do. Your thoughts or hints are appreciated. Here is my main code: ``` public class Main { public static void main(String[] args) { MainMenu menu = new MainMenu(); menu.pack(); menu.setVisible(true); } } ``` Here is my mainMenu code: ``` import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MainMenu extends JFrame implements ActionListener { JButton startNewGame = new JButton("Start a New Game"); JButton loadOldGame = new JButton("Load an Old Game"); JButton seeInstructions = new JButton("Instructions"); public MainMenu() { super("RPG Main Menu"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel mainMenu = new JPanel(); mainMenu.setLayout(new FlowLayout()); startNewGame.setMnemonic('n'); loadOldGame.setMnemonic('l'); seeInstructions.setMnemonic('i'); startNewGame.addActionListener(this); loadOldGame.addActionListener(this); seeInstructions.addActionListener(this); mainMenu.add(startNewGame); mainMenu.add(loadOldGame); mainMenu.add(seeInstructions); setContentPane(mainMenu); } public void actionPerformed(ActionEvent evt) { Object source = evt.getSource(); if (source == startNewGame) { // StartNewGame code goes here // mainMenu.removeAll(); } if (source == loadOldGame) { // LoadOldGame code goes here } if (source == seeInstructions) { // Quit code goes here } } } ```
You need mainMenu to be a member variable: ``` public class MainMenu extends JFrame implements ActionListener { JButton startNewGame = new JButton("Start a New Game"); JButton loadOldGame = new JButton("Load an Old Game"); JButton seeInstructions = new JButton("Instructions"); JPanel mainMenu = new JPanel(); ``` Why do you feel the need to re-use this object?
Consider using a [`CardLayout`](http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html) instead, which manages two or more components (usually `JPanel` instances) that share the same display space. That way you don't have to fiddle with adding and removing components at runtime.
Difficulty removing all components from a Jpanel
[ "", "java", "swing", "components", "jpanel", "" ]
I am new to PHP. In the path of learning PHP language, I notice that, some website would this kind of URL: www.website.com/profile.php?user=roa3&... My questions: 1. What is the "?" symbol used for? 2. If I were develop a php website, must I use it in my URL? For example, after a user(roa3) successful logged in, I will redirect to "www.website.com/profile.php?user=roa3" instead of "www.website.com/profile.php" 3. What are the advantages and disadvantages of using it?
Good questions, briefly, 1. "?" stands for the start of querying string which contains the data to be passed to the server. in this case you are passing user=roa3 to profile.php page. You can get the data by using $\_GET['user'] within profile.php. querystring is one of the methods to send data to the server from client agent. The other one places the data in HTTP body and POST to the server, you don't see the HTTP POST data directly from browser. 2. querystring can be edited by user and it is visible to the public. If www.website.com/profile.php?user=roa3 is intended to be public then it is fine, otherwise you may want to use session to get current user's context. 3. it is a flexible way to pass data to the server, but it is visible and editable to the users, for some sensitive data, at least produce some kind of hash before attaching it to the querystring, this prevents users to edit it or understanding the meaning of it. However this doesn't prevent a decent hacker to do something wrong about your website. Different browsers support different max length of URL, the lengthy URL is made up by those querystring parameters. If you want to send large amount of data, place the data in the HTTP body and POST to the server.
Most of the answers I've seen so far have been in terms of PHP, when in reality this isn't language specific. The answers given so far have been from the view of PHP and the methods you would use to access the information differ from one language to the next, but the format in which the data is in the URL (known as the Query String) will remain the same (Ex: page.ext?key1=value&key2=value&...). I don't know your technical background or knowledge, so please forgive me... There are two different methods for a web page to provide data back to the web server. These are known as the POST or GET methods. There also also a bunch of others, but none of those should be used in any sort of web design when dealing with a normal user. The POST method is sent invisibly to the server and is meant for 'uploading' data, while the GET method is visible to the user as the Query String in the URL and is only meant to literally 'get' information. Not all sites follow this rule of thumb, but there can be reasons as to why. For example, a site could use POST exclusively to get around caching by proxy servers or your browser, or because they use double byte languages and can cause issues when trying to perform a GET because of the encoding conversion. Some resources about the two methods and when to use them... <http://www.cs.tut.fi/~jkorpela/forms/methods.html> <http://weblogs.asp.net/mschwarz/archive/2006/12/04/post-vs-get.aspx> <http://en.wikipedia.org/wiki/Query_string> Now from a strictly PHP position, there are now 3 different arrays you can use to get the information a webpage has sent back to the server. You have to your disposal... * $\_POST['keyname'], to grab only the information from a POST method * $\_GET['keyname'], to grab only the information from a GET method * $\_REQUEST['keyname'], to allow you to grab the POST, GET, and any COOKIE information that might have been submitted. Sort of a catchall, especially in cases where you don't know which method a page might be using to submit data. Don't get sloppy by going directly with the $\_REQUEST method. Unless you have a case like I mentioned above for the $\_REQUEST variable, then don't use it. You want to try and use a 'deny all, and only allow x,y,z' approach when it comes to security. Only look for the data that you know your own site will be sending, only look for the combinations that you'll be expecting, and cleanse all of the information before you use it. For example.. * Never do an eval() on anything passed via the above methods. I've never seen this done, but it doesn't mean people haven't tried or do. * Never use the information directly with databases without cleaning them (research into SQL injection attacks if you're not familiar with them) This is by far not the end-all, be-all to PHP security, but we're not here for that. If you want to know more along line, well then thats another question for SO. Hope this helps and feel free to ask any questions.
What is the "?" symbol in URL used for in php?
[ "", "php", "url", "" ]
Consider the code, ``` Type t0 = Type.GetType("System.Drawing.dll"); Type t1 = Type.GetType("System.Drawing.Font"); ``` Here in order to find type of "System.Drawing.Font" the assembly "System.Drawing.dll" is needed. how to use it.? i.e wat if i do, so that value of **t0** wont be null.?? Consider i ave a dll, **proj.dll** and i need to find the type of the class **Class1** that is present in the dll.
Specify the assembly, including the version number for strongly named assemblies: ``` Type t = Type.GetType("System.Drawing.Font,System.Drawing,"+ " Version=2.0.0.0, Culture=neutral, "+ "PublicKeyToken=b03f5f7f11d50a3a"); ``` Of course, if it's *really* just `System.Drawing.Font` (or another type you know at compile-time), use `typeof`: ``` Type t = typeof(System.Drawing.Font); ``` If you know another type in the same assembly at compile-time, you can use [`Assembly.GetType`](http://msdn.microsoft.com/en-us/library/y0cd10tb.aspx): ``` Type sizeType = typeof(System.Drawing.Size); Assembly assembly = sizeType.Assembly; Type fontType = assembly.GetType("System.Drawing.Font"); ```
Pass the strong name of the assembly to load it, and then load the type from it, like ``` Assembly asm = Assembly.Load("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); Type font = asm.GetType("System.Drawing.Font"); ```
C# doubt in GetType, Managed CodeGen
[ "", "c#", "" ]
I am writing an application using CakePHP and I am unsure as to where I should be putting my `generateMapUrl` function. ``` function generateMapUrl($id = null) { if ( !$id ) { $this->Session->setFlash('Invalid Property Id'); } $this->read(null, $id); $url = "http://maps.google.com/maps?oi=map&amp;q="; $url .= $this->data['street_num'] . '+'; $url .= $this->data['street'] . '+'; $url .= $this->data['city'] . '+'; $url .= $this->data['province'] . '+'; $url .= $this->data['country'] . '+'; $url .= $this->data['postal_code']; return $url; } ``` I have the following structure: > Booking (Model & Controller) > Properties (Model & Controller) > Address (Model & Controller) A Booking `hasOne` Property and a Property `hasOne` Address. I would like to be able to call `generateMapUrl` for any Address. I am unsure as to where to put the method though... Address controller? Address Model? (Note: I am calling this method from the Bookings controller)
The generateMapUrl() method should be a method in your Address model as it is dealing with fetching and formatting Address data, but should return false and not contain the session calls: ``` function generateMapUrl($id = null) { $this->recursive = -1; if (!$this->read(null, $id)) { return false; } $url = "http://maps.google.com/maps?oi=map&amp;q="; $url .= $this->data['street_num'] . '+'; $url .= $this->data['street'] . '+'; $url .= $this->data['city'] . '+'; $url .= $this->data['province'] . '+'; $url .= $this->data['country'] . '+'; $url .= $this->data['postal_code']; return $url; } ``` You can then call this from any controller and use the session calls there: ``` function x() { if (!$mapUrl = ClassRegistry::init('Address')->generateMapUrl($addressId)) { $this->Session->setFlash('Invalid Property Id'); } } ```
In the Controller, it has session data. The Model should not be aware of any session states.
Where should I put this method in CakePHP-driven site?
[ "", "php", "cakephp", "" ]
``` if (x() > 10) { if (y > 5) action1(p1, p2, p3, p4); else action2(p1, p2); } else { if (z > 2) action1(p1, p2, p3, p4); else action2(p1, p2); } ``` I real project on mine, action1 and action2 are actually 2-3 lines of code and those functions that are invoked take 6-8 parameters in total, so writing them as a single function doesn't seem right. UPDATE: I forgot to mention this, and now I see many answers just don't work. x() is expensive operation and has side-effects, so it should not be called twice.
``` bool condition_satisfied = (x() > 10 ? y > 5 : z > 2); if (condition_satisfied) action1(p1, p2, p3, p4); else action2(p1, p2); ``` Or, alternatively, what Roger Lipscombe [answered](https://stackoverflow.com/questions/578304/how-would-you-shorten-this-so-that-action1-and-action2-only-show-up-once-in-code/578326#578326).
``` if (should_do_action1(x(), y, z)) action1(p1, p2, p3, p4); else action2(p1, p2); ```
How would you shorten this so that action1 and action2 only show up once in code?
[ "", "c++", "c", "" ]
I want to create a Java `File` object in memory (without creating a physical file) and populate its content with a byte array. Can this be done? The idea is to pass it to a Spring `InputStreamSource`. I'm trying the method below, but it returns saying "the byte array does not contain a file name.". ``` MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); helper.setFrom("no-reply@example.com", "xyz"); helper.setTo(email); helper.setText(body,true); helper.setSubject(subject); helper.addInline("cImage", new InputStreamResource(new ByteArrayInputStream(imageByteArr))); mailSender.send(message); ```
Can you paste the full stack trace? There is no such thing as an "in memory" file. Using a ByteArrayInputStream should be sufficient. --- You need to implement Resource#getFilename(). Try the following: ``` helper.addInline("cImage", new ByteArrayResource(imageByteArr){ @Override public String getFilename() { return fileName; } }); ```
Maybe you need to use the [other constructor of InputStreamResource](http://static.springframework.org/spring/docs/1.1.5/api/org/springframework/core/io/InputStreamResource.html#InputStreamResource(java.io.InputStream,%20java.lang.String))?
Create a Java File object (or equivalent) using a byte array in memory (without a physical file)
[ "", "java", "spring", "file", "memory", "io", "" ]
I am using DotNetZip and have noticed that i am getting permission issues on Mac's. This seems to only occur when i use content disposition. ie if i just save it to disk ``` using (ZipFile zip = new ZipFile(@"C:\zip\temp.zip")) { // this works fine } ``` but if i use content disposition like so, on mac the user permissions are denied ( everyone group is unchecked) ``` Response.ContentType = "application/zip"; Response.AddHeader("content-disposition", "filename=" + filename); using (ZipFile zip = new ZipFile(Response.OutputStream)) { // } ```
You could try changing the ApplicationType to "application/octet-stream". Believe it or not that has fixed problems for me before. It's worth a shot anyway. The biggest question is how is the file being requested from the Mac's side? If it's a Windows web server offering up the file, Windows can't set the permissions on the client side. If it's a web browser (Safari/Firefox) they're probably just running on the default settings. So knowing what is requesting the file from the Mac could help get the right answer.
I don't know if it has anything to do with DotNetZip, but there is a later version of the library out now - v1.7. It does AES encryption, ZIP64, a bunch of other stuff. And the v1.8 version has some new cool Seelctor features, as well as a replacement for GZipStream.
DotNetZip: creating zip with C# permissions issue
[ "", "c#", "macos", "permissions", "zip", "dotnetzip", "" ]
``` function all_images(&$post){ $content = $post->post_content; if(preg_match_all('/<img[^>]+src="(.*?)"[^>]*>/', $content, $results)){ $i = 0; $count = count($results); $count = $count - 1; while($i < $count) { foreach($results as $result){ echo $result[$i]; } $i++; } } } ``` The above loop manages to get all of the images out of the original text. However, it only returns one image. I have tried several different combinations of while() and foreach() but it only ever returns one image. Does anyone know what i am doing wrong? Thanks
$results[1] should be an array of all the matches on the first parenthesized subpattern, so something as simple as this should work: ``` if(preg_match_all('/<img[^>]+src="(.*?)"[^>]*>/i', $content, $results)){ foreach($results[1] as $src) { echo "src is $src<br>"; } } ``` Note I've used the /i modifier to make the match case insensitive, which might help you. You might also want to supply some sample content you are trying to match against.
Why are you doing $count = $count - 1? You should be able to just do this: ``` if(preg_match_all('/<img[^>]+src="(.*?)"[^>]*>/', $content, $results)){ foreach($results[1] as $result) { echo $result; } } } ```
Image loop only returns one image but should return them all
[ "", "php", "" ]