Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a thick GUI application (possibly running as a service, but also just as a normal application) on a desktop. I would like to expose a web interface to the application for some remote monitoring and control of the application. I currently am hosting a WCF service that just returns HTML in the application, which works fine, but optimally I would like to use an ASP.Net application, or a silverlight application. Is there any way to host the aspx or silverlight app from within my app? As part of this, I would like to be able to share data between the two applications.
Yes. You don't even need Cassini, as it wraps ASPX hosting bits already present in the framework it's all inside [System.Web.Hosting](http://msdn.microsoft.com/en-us/library/system.web.hosting.aspx) MSDN has a [good article](http://msdn.microsoft.com/en-gb/magazine/cc163879.aspx) on it all
The tiny webserver that is built into VS is called Cassini and you can download the source somewhere. Not sue about versions and licenses. Cassini provides (demonstrates) the ASP Hosting stuff.
Is it possible to host an ASPX web page, in a stand alone application, outside of IIS
[ "", "c#", "asp.net", "silverlight", "hosting", "" ]
Python's inner/nested classes confuse me. Is there something that can't be accomplished without them? If so, what is that thing?
Quoted from <http://www.geekinterview.com/question_details/64739>: > ### Advantages of inner class: > > * **Logical grouping of classes**: If a class is useful to only one other class then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined. > * **Increased encapsulation**: Consider two top-level classes A and B where B needs access to members of A that would otherwise be declared private. By hiding class B within class A A's members can be declared private and B can access them. In addition B itself can be hidden from the outside world. > * **More readable, maintainable code**: Nesting small classes within top-level classes places the code closer to where it is used. The main advantage is organization. Anything that can be accomplished with inner classes **can** be accomplished without them.
> Is there something that can't be accomplished without them? No. They are absolutely equivalent to defining the class normally at top level, and then copying a reference to it into the outer class. I don't think there's any special reason nested classes are ‘allowed’, other than it makes no particular sense to explicitly ‘disallow’ them either. If you're looking for a class that exists within the lifecycle of the outer/owner object, and always has a reference to an instance of the outer class — inner classes as Java does it – then Python's nested classes are not that thing. But you can hack up something *like* that thing: ``` import weakref, new class innerclass(object): """Descriptor for making inner classes. Adds a property 'owner' to the inner class, pointing to the outer owner instance. """ # Use a weakref dict to memoise previous results so that # instance.Inner() always returns the same inner classobj. # def __init__(self, inner): self.inner= inner self.instances= weakref.WeakKeyDictionary() # Not thread-safe - consider adding a lock. # def __get__(self, instance, _): if instance is None: return self.inner if instance not in self.instances: self.instances[instance]= new.classobj( self.inner.__name__, (self.inner,), {'owner': instance} ) return self.instances[instance] # Using an inner class # class Outer(object): @innerclass class Inner(object): def __repr__(self): return '<%s.%s inner object of %r>' % ( self.owner.__class__.__name__, self.__class__.__name__, self.owner ) >>> o1= Outer() >>> o2= Outer() >>> i1= o1.Inner() >>> i1 <Outer.Inner inner object of <__main__.Outer object at 0x7fb2cd62de90>> >>> isinstance(i1, Outer.Inner) True >>> isinstance(i1, o1.Inner) True >>> isinstance(i1, o2.Inner) False ``` (This uses class decorators, which are new in Python 2.6 and 3.0. Otherwise you'd have to say “Inner= innerclass(Inner)” after the class definition.)
What is the purpose of python's inner classes?
[ "", "python", "class", "oop", "language-features", "" ]
I have complex GUI application written in Python and wxPython. I want it to be certified for Windows Vista, so it has to crash in a way that causes Windows Error Reporting dialog (The one that asks "*Do you want to send report to Microsoft?*") to appear. This is relevant to test case no 32 from "*Certified for Windows Vista Test Cases*" document. Unfortunately when I crash my app with `ThreadHijacker` tool wxPython shows message like: ``` Unhandled exception --------------------------- An unhandled exception occurred. Press "Abort" to terminate the program, "Retry" to exit the program normally and "Ignore" to try to continue. --------------------------- Abort Retry Ignore ``` How can I prevent wxPython from showing this message? I have custom `sys.excepthook`, but it seems that this dialog is shown before my except hook can interfere. **EDIT:** wxWidgets [docs](http://docs.wxwidgets.org/trunk/classwx_app_console.html#ca806b41cf74fd6166e4fb2e2708e9bf) says that *wxAppConsole::OnExceptionInMainLoop* is called and under MSW it displays some fancy dialog that allows user to choose between the different options. It seems however, that wxPython doesn't allow overloading that function... Does anyone know how to change default behaviour of *wxAppConsole::OnExceptionInMainLoop* in wxPython? I prefer solutions that are on Python level over those that go into C/C++ **EDIT2:** All in all, I asked at wxPython mailing list, and Robin Dunn answered that he'll look into making *wxAppConsole::OnExceptionInMainLoop* overridable in next releases of wxPython. Since I couldn't wait, I had to compile my own version of wxPython which does not include that function. It turned out that the presence of *wxAppConsole::OnExceptionInMainLoop* function can be enabled/disabled by proper setting of compilation flags.
It all ended up with compiling my own wxWidgets and wxPython, with just one compilation flag changed: **wxUSE\_EXCEPTIONS** should be set to 0. Robin Dunn wrote that he will try to patch wxPython, so this behaviour could be modified without recompiling of the whole library.
Is it possible for you to just handle everything? You would have to, I guess, put a try:except: block around every method bound to a widget. You could write a decorator: ``` def catch_exception(f): def safe(*args, **kw): try: f(*args, **kw) except Exception, e: handle_exception(e) return safe def handle_exception(e): # do Vista stuff sys.exit() ``` Then decorate any function that could be called by the mainloop (since I presume that's where wxPython does its own catching).
Prevent wxPython from showing 'Unhandled exception' dialog
[ "", "python", "windows", "wxpython", "error-reporting", "" ]
I think instance variables are simple data types like int or double. Everything that is created automatically when the object is created. If an object creates additional objects - like everything that is it done with the NEW keyword - these are not instance variables. Am I right or wrong? What is the exact definition?
Wrong. Anything that is bound within the instance (i.e. an instantiated object) is instance variable. As opposite of static (class) variables, which are bound to the class. It doesn't matter if they are simple types or pointers to objects.
Instance variable are the ones which can be associated with an instance of a class. For example if you have ``` class A { private: int m_a; double m_b; int* m_c; }; ``` and if you create an object (i.e. an instance) of A, one instance of m\_a, m\_b, m\_c is created and associated with it. So these become instance variables. At the same time if you have a static variable inside the class, the static variable instance is not associated with each object of the class hence it is not an instance variable. NEW or creating a stack object are just ways of creating the objects and as such have nothing to do with instance variables.
What is the exact definition of instance variable?
[ "", "c++", "class", "instance-variables", "" ]
I was just trying the SetTimer method in Win32 with some low values such as 10ms as the timeout period. I calculated the time it took to get 500 timer events and expected it to be around 5 seconds. Surprisingly I found that it is taking about 7.5 seconds to get these many events which means that it is timing out at about 16ms. Is there any limitation on the value we can set for the timeout period ( I couldn't find anything on the MSDN ) ? Also, does the other processes running in my system affect these timer messages?
Windows is not a real-time OS and can't handle that kind of precision (10 ms intervals). Having said that, [there are multiple kinds of timers](http://www.codeproject.com/KB/system/timers_intro.aspx) and some have better precision than others.
OnTimer is based on `WM_TIMER` message, which is a low message priority, meaning it will be send only when there's no other message waiting. Also MSDN explain that you can not set an interval less than `USER_TIMER_MINIMUM`, which is 10. Regardless of that the scheduler will honor the time quantum.
Timer message in MFC/Win32
[ "", "c++", "winapi", "mfc", "" ]
I need to call a web and retrieve the resulting data from the model in my asp.net mvc application. When accessed on the web, the form looks like this: ``` <form id="textEntryForm" name="textEntryForm" method="post" action="/project/evaluate_to_pdf"> <textarea id="p" rows="20" name="p" cols="132"/><br/> <input type="button" value="parse" name="do_parse" onclick="new Ajax.Updater('parsedProject','/project/parse',{asynchronous:true,evalScripts:true,on404:function(e){alert('not found!')},parameters:Form.serialize(this.form)});return false"/> <input type="button" value="evaluate_to_html" name="do_evaluate_to_html" onclick="new Ajax.Updater('parsedProject','/project/evaluate_to_html',{asynchronous:true,evalScripts:true,on404:function(e){alert('not found!')},parameters:Form.serialize(this.form)});return false"/> <input type="button" value="evaluate" name="do_evaluate" onclick="new Ajax.Updater('parsedProject','/project/evaluate',{asynchronous:true,evalScripts:true,on404:function(e){alert('not found!')},parameters:Form.serialize(this.form)});return false"/> <input type="button" value="evaluate to pdf source" name="do_evaluate_to_pdf_source" onclick="new Ajax.Updater('parsedProject','/project/evaluate_to_pdf_source',{asynchronous:true,evalScripts:true,on404:function(e){alert('not found!')},parameters:Form.serialize(this.form)});return false"/> <input type="submit" id="do_evaluate_to_pdf" value="evaluate_to_pdf" name="do_evaluate_to_pdf"/> </form> ``` I need to pass the data that would be entered into textarea id="p". How do add that in, using a WebClient to connect? Thanks! **Edit** This isn't for testing purposes, I need to retrieve the data for use in my application.
I just used this: <http://www.eggheadcafe.com/community/aspnet/2/69261/you-can-use-the-webclient.aspx>
Another option is the [Lightweight Test Automation Framework by Microsoft](https://web.archive.org/web/20120501082849/http://blog.codeville.net/2009/03/27/first-steps-with-lightweight-test-automation-framework/) <- Here Steve Sanderson applies it to MVC. [![alt text](https://i.stack.imgur.com/7DbUn.png)](https://i.stack.imgur.com/7DbUn.png) (source: [codeville.net](http://blog.codeville.net/wp-content/uploads/2009/03/image-thumb.png)) [![alt text](https://i.stack.imgur.com/sK0Xn.png)](https://i.stack.imgur.com/sK0Xn.png) (source: [codeville.net](http://blog.codeville.net/wp-content/uploads/2009/03/image-thumb1.png))
Fake a form submission with C# WebClient
[ "", "c#", "asp.net-mvc", "" ]
I'm working on some classes that get part of their configuration from global variables, e.g. ``` class MyClass { public void MyClass(Hashtable<String, String> params) { this.foo = GlobalClass.GLOBALVAR.get("foo"); this.bar = GlobalClass.GLOBALVAR.get("bar"); this.params = params; } } ``` This is bad for a couple of reasons, GLOBALVAR talks to a database to get some of the variables and this makes it really hard to make unit tests. The other problem is that I have many (dozens) of classes that inherit from MyClass, so I can't easily change the constructor signature. My current solution is to create an additional default constructor and setter methods for `params`, `foo` and `bar`. ``` class MyClass { // Other code still here for backwards compatibility. public void MyClass() { // Do nothing much. } public void setParams(Hashtable<String, String> params) { this.params = params; } public void setFoo(Foo foo) { this.foo = foo; } public void setBar(Bar bar) { this.bar = bar; } } ``` Any ideas on a good way to refactor this, besides the way I did it? My other thought would be to use a factory method, but I'm afraid I'll run into polymorphic substitution problems.
I think I would start by doing the following. It let's your existing code work without modification, and allows you to add new constructors to the subclasses as you can. Once all of the subclasses have the new constructor, and all of the calls to the old constructors are gone, you can get rid of the GlobalClass and the constructors that use it. You can also then, hopefully, work on cleaning up the GLOBALVAR (the Car class in my code). ``` import java.util.Hashtable; class MyClass { private final Foo foo; private final Bar bar; private final Hashtable<String, String> params; public MyClass(final Hashtable<String, String> params) { this(params, GlobalClass.GLOBALVAR); } // added constructor public MyClass(final Hashtable<String, String> params, final FooBar fooBar) { this.foo = fooBar.getFoo(); this.bar = fooBar.getBar(); this.params = params; } } class MySubClass extends MyClass { public MySubClass(final Hashtable<String, String> params) { super(params); } // added constructor public MySubClass(final Hashtable<String, String> params, final FooBar fooBar) { super(params, fooBar); } } // unchanged class GlobalClass { public static Car GLOBALVAR; } // added interface interface FooBar { Foo getFoo(); Bar getBar(); } class Car // added implements implements FooBar { private Foo foo = new Foo(); private Bar bar = new Bar(); public Object get(final String name) { if(name.equals("foo")) { return (foo); } if(name.equals("bar")) { return (bar); } throw new Error(); } // added method public Foo getFoo() { return ((Foo)get("foo")); } // added method public Bar getBar() { return ((Bar)get("bar")); } } // unchanged class Foo { } // unchanged class Bar { } ```
I think you should introduce an interface to put a layer of abstraction between the global variable collection and its consumers. ``` interface GlobalVars { String get(String key); } ``` You should introduce a constructor with limited scope, probably `package-private` ``` MyClass(GlobalVars globals, Map<String, String> params) { // create the object } ``` And then provide `public static` factory methods to use this constructor. ``` public static MyClass newMyClass(Map<String, String> params) { return new MyClass(GlobalClass.GLOBAL_VAR, params); } ``` With this design you can pass in a mock implementation of `GlobalVars` in a unit test from within the same package by explicitly invoking the constructor. *Addendum*: Since `params` seems to be a required field, I would definitely make it `final` and avoid the approach where you add mutators to overwrite them. ``` private final Map<String, String> params; ``` Also, make a defensive copy to prevent l33t h4x. ``` this.params = Collections.unmodifiableMap(params); ```
Refactoring classes that use global variables
[ "", "java", "refactoring", "global-variables", "" ]
This time I have problem with virtual fields. I have core class for my game objects. This class contains a field with Model class object. Model's object contains values such as position etc. Now - while drawing I need to read position of each object from it's model. The problem starts when instead of default model class I'm using derived. Example: ``` abstract class GenericGameObject { public DefaultGameObjectModel Model = new DefaultGameObjectModel(); } class Missile : GenericGameObject { public new MissileModel Model = new MissileModel(); } class DefaultGameObjectModel { public Vector2 Position = new Vector2(){X=0}; } class MissileModel : DefaultGameObjectModel { } Missile m = new Missile(); m.Model.Position.X = 10; // NOT OK! ((GenericGameObject)m).Model.Position.X == 0 ``` I tried to make Model defined as virtual property instead of field, but this fails because derived properties have to be of same type as their base. Casting is futile because there will be many other model types. What can I do if I want to read a value from derived class, not from base? I asked this question already but the answer didn't brought any solution. Explaination: * **to use interface IGameObjectModel** Concept is good, but I have to enforce fields. Interfaces can't define fields so I have to define property. But then I can't do IGameObjectModel.Position.X=10 because Position is not a field. * **to make GenericGameObject a generic type such as GenericGameObject and Missile a type derived from GenericGameObject** I couldn't then cast a missile to GenericGameObject and generally store those object on same list. Of course I could make main base type which those two could inherit from, but then I wouldn't have access to Model field. * **to make model a property instead of field.** It is impossible to change property type in derived class. Whad can I do?
In this case your best approach would be to assign the value of your parent field to be an instance of your derived class, then either cast it back to your derived class or hold on to a reference of your derived class (probably better). Or you could go down this road, which I like the best... ``` abstract class GenericGameObject { public DefaultGameObjectModel Model { get { return ModelInternal; } } protected abstract DefaultGameObjectModel ModelInternal { get; } } class Missile : GenericGameObject { private MissileModel model = new MissileModel(); public override DefaultGameObjectModel ModelInternal { get { return model; } } public new MissileModel Model { get { return model; } set { model = value; } } } class DefaultGameObjectModel { public Vector2 Position = new Vector2(){X=0}; } class MissileModel : DefaultGameObjectModel { } Missile m = new Missile(); m.Model.Position.X = 10; ``` This solution gives you access to your base model instance from the context of the base class, while giving you access to your concrete model instance from the inherited class.
There's no such thing as 'virtual fields'. Only [properties](http://msdn.microsoft.com/en-us/library/aa664453(VS.71).aspx) and [methods](http://msdn.microsoft.com/en-us/library/aa645767(VS.71).aspx) can be virtual. In your Missle class, you appear to be using the [new keyword as a modifier](http://msdn.microsoft.com/en-us/library/51y09td4(VS.71).aspx#vclrfnew_newmodifier) to hide the inherited member named Model. When you hide an inherited member this way, you don't get polymorphic behavior. This is bad because the code in your base class (if it references the Model field) may not work as you expect. Best bet: Use a property. Cast or generalize (move members to base class) as necessary.
C# polymorphism question once again - overriding fields?
[ "", "c#", "xna", "polymorphism", "" ]
I have a select box that calls `window.open(url)` when an item is selected. Firefox will open the page in a new tab by default. However, I would like the page to open in a new window, not a new tab. How can I accomplish this?
Specify window "features" to the `open` call: ``` window.open(url, windowName, "height=200,width=200"); ``` When you specify a width/height, it will open it in a new window instead of a tab. See <https://developer.mozilla.org/en-US/docs/Web/API/Window.open#Position_and_size_features> for all the possible features.
You don't need to use height, just make sure you use `_blank`, Without it, it opens in a new tab. For a empty window: ``` window.open('', '_blank', 'toolbar=0,location=0,menubar=0'); ``` For a specific URL: ``` window.open('http://www.google.com', '_blank', 'toolbar=0,location=0,menubar=0'); ```
JavaScript open in a new window, not tab
[ "", "javascript", "firefox", "" ]
In Visual Studio, there's the compile flags /MD and /MT which let you choose which kind of C runtime library you want. I understand the difference in implementation, but I'm still not sure which one to use. What are the pros/cons? One advantage to /MD that I've heard, is that this allows someone to update the runtime, (like maybe patch a security problem) and my app will benefit from this update. Although to me, this almost seems like a non-feature: I don't want people changing my runtime without allowing me to test against the new version! Some things I am curious about: * How would this affect build times? (presumably /MT is a little slower?) * What are the other implications? * Which one do most people use?
By dynamically linking with /MD, * you are exposed to system updates (for good or ill), * your executable can be smaller (since it doesn't have the library embedded in it), and * I believe that at very least the code segment of a DLL is shared amongst all processes that are actively using it (reducing the total amount of RAM consumed). I've also found that in practice, when working with statically-linked 3rd-party binary-only libraries that have been built with different runtime options, /MT in the main application tends to cause conflicts much more often than /MD (because you'll run into trouble if the C runtime is statically-linked multiple times, especially if they are different versions).
If you are using DLLs then you should go for the dynamically linked CRT (/MD). If you use the dynamic CRT for your .exe and all .dlls then they will all share a single implementation of the CRT - which means they will all share a single CRT heap and memory allocated in one .exe/.dll can be freed in another. If you use the static CRT for your .exe and all .dlls then they'll all get a seperate copy of the CRT - which means they'll all use their own CRT heap so memory must be freed in the same module in which it was allocated. You'll also suffer from code bloat (multiple copies of the CRT) and excess runtime overhead (each heap allocates memory from the OS to keep track of its state, and the overhead can be noticeable).
Should I compile with /MD or /MT?
[ "", "c++", "visual-studio", "msbuild", "msvcrt", "crt", "" ]
In a [recent question](https://stackoverflow.com/questions/700684/content-ideas-for-a-short-javascript-lesson), I received suggestions to talk on, amongst other things, the aspect of JavaScript where functions are 'first class' objects. What does the 'first class' mean in this context, as opposed to other objects? EDIT (Jörg W Mittag): Exact Duplicate: ["What is a first class programming construct?"](http://StackOverflow.Com/questions/646794/)
To quote [Wikipedia](http://en.wikipedia.org/wiki/First-class_function): > In computer science, a programming > language is said to support > first-class functions (or function > literal) if it treats functions as > first-class objects. Specifically, > this means that the language supports > constructing new functions during the > execution of a program, storing them > in data structures, passing them as > arguments to other functions, and > returning them as the values of other > functions. This page also [illustrates](http://helephant.com/2008/08/functions-are-first-class-objects-in-javascript/) it beautifully: > Really, just like any other variable * A function is an instance of the Object type * A function can have properties and has a link back to its constructor method * You can store the function in a variable * You can pass the function as a parameter to another function * You can return the function from a function *also read TrayMan's comment, interesting...*
The notion of ["first-class functions"](http://C2.Com/cgi/wiki/?FirstClass) in a programming language was introduced by British computer scientist [Christopher Strachey](http://Wikipedia.Org/wiki/Christopher_Strachey) in the 1960s. The most famous formulation of this principle is probably in [Structure and Interpretation of Computer Programs](http://MITPress.MIT.Edu/sicp/full-text/book/book-Z-H-12.html#call_footnote_Temp_121) by Gerald Jay Sussman and Harry Abelson: * They may be named by variables. * They may be passed as arguments to procedures. * They may be returned as the results of procedures. * They may be included in data structures. Basically, it means that you can do with functions everything that you can do with all other elements in the programming language. So, in the case of JavaScript, it means that everything you can do with an Integer, a String, an Array or any other kind of Object, you can *also* do with functions.
What is meant by 'first class object'?
[ "", "javascript", "" ]
I'm attempting to add SSL to my server for sending customer details to a client. It appears to be working on the Server side with the digital certificate (.pfx) being loaded succesfully. The problem comes when I try to connect with the client. An AuthenticationException is thrown stating that the remote certificate is invalid. The certificate is a self-signed test certificate - could this be the problem? If not, I'm out of ideas! **EDIT:** The certificate is in the trusted root certificate folder in the MMC on both sides (server and client are being run on the same machine for devel purposes).
I've had to override the validation method: ``` public static bool RemoteCertificateValidationCallback(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; } ``` Obviously this will accept **every** certificate that is passed to it so I'll need to check using the hash of the certificate or something similar. However, right now it's holiday time!
That could most definitely be the problem. Have you tried adding that web server to your trusted Root Certificates on the client? If the client does not trust the certificate provider (your web server, since self-signed), it will throw exception when attempting to authenticate the certificate.
Invalid Digital Certificate
[ "", "c#", ".net", "ssl", "digital-certificate", "" ]
I would like to do a SUM on rows in a database and group by date. I am trying to run this SQL query using Django aggregates and annotations: ``` select strftime('%m/%d/%Y', time_stamp) as the_date, sum(numbers_data) from my_model group by the_date; ``` I tried the following: ``` data = My_Model.objects.values("strftime('%m/%d/%Y', time_stamp)").annotate(Sum("numbers_data")).order_by() ``` but it seems like you can only use column names in the values() function; it doesn't like the use of strftime(). How should I go about this?
This works for me: ``` select_data = {"d": """strftime('%%m/%%d/%%Y', time_stamp)"""} data = My_Model.objects.extra(select=select_data).values('d').annotate(Sum("numbers_data")).order_by() ``` Took a bit to figure out I had to escape the % signs.
As of v1.8, you can use [Func() expressions](https://docs.djangoproject.com/en/1.8/ref/models/expressions/#func-expressions). For example, if you happen to be targeting AWS Redshift's date and time functions: ``` from django.db.models import F, Func, Value def TimezoneConvertedDateF(field_name, tz_name): tz_fn = Func(Value(tz_name), F(field_name), function='CONVERT_TIMEZONE') dt_fn = Func(tz_fn, function='TRUNC') return dt_fn ``` Then you can use it like this: ``` SomeDbModel.objects \ .annotate(the_date=TimezoneConvertedDateF('some_timestamp_col_name', 'America/New_York')) \ .filter(the_date=...) ``` or like this: ``` SomeDbModel.objects \ .annotate(the_date=TimezoneConvertedDateF('some_timestamp_col_name', 'America/New_York')) \ .values('the_date') \ .annotate(...) ```
Django GROUP BY strftime date format
[ "", "python", "django", "orm", "django-models", "django-aggregation", "" ]
I've imported a bunch of posts into a Wordpress site that all have the exact same date. I'd like to edit the post dates so they are offset by one second. My concern is that there may be a performance issue when all of the dates are the same. Anyone know quick way to get this done using phpMyAdmin to edit the MySQL database or some other method?
You could set them all to be 'now' + id. It might look like; ``` UPDATE wp_posts SET createdDate = DATE_ADD(now(), INTERVAL wp_posts.wp_id SECOND); ```
Before you mess with this, I suggest that you make sure that in fact have a problem with simultaneous times. I quite often find that messing with the data like this has unintended consequences. And I'd be moderately surprised if the problem really is significant. It appears to me that I'm seeing proposals that will set all the rows to the same offset value. Assuming you have an integer surrogate key, and the rows are adjacent, you could use > UPDATE table > SET mydate = DATE\_ADD(my\_date, INTERVAL id - SECOND) > WHERE id BETWEEN AND ;
How to offset dates in a MySQL database by 1 second?
[ "", "php", "mysql", "wordpress", "date", "phpmyadmin", "" ]
I have tried a bunch of different things but always get syntax errors. I have two tables - tableA and tableB. They both have a con\_number field as a unique ID. I want to select all of the rows in tableB that do not exist in tableA. Can anyone please give me this query as it would be in MS Access? I know that using NOT IN is quite inefficient in this case so if there is a better way then that would be great. Thanks.
``` SELECT TableB.con_number FROM TableB WHERE NOT EXISTS (SELECT 1 FROM TableA WHERE TableA.con_number = TableB.con_number); ```
There is a Find Unmatched wizard that will set this up. The SQL is: ``` SELECT TableB.con_number FROM TableB LEFT JOIN TableA ON TableB.con_number = TableA.con_number WHERE TableA.con_number Is Null ```
How do I get all the rows in one table that are not in another in MS Access?
[ "", "sql", "ms-access", "" ]
Is there any difference in performance when running two executables with mono in linux, if: 1) the one executable has been compiled from c# source code previously in windows (e.g.VS). 2) the other executable has been compiled from the same source with gmcs in linux.
It shouldn't matter from mono runtime's perspective since they are both valid IL codes (assuming compilers are bug-free). There might be a performance difference which can be attributed to the level of optimization done by the *C# compiler*.
Which compiler on Windows? I believe gmcs on Windows or Linux will give you the same output. If you are using a different compiler (e.g. VS / csc) you will probably have subtle differences
Mono in linux & windows
[ "", "c#", "linux", "mono", "" ]
Using Visual C++ 2008. First time, I'm experimenting in crossing over from C# and wanted to try my hand at it. I have not changed base settings much, other than a few things like smart block and maybe a few colors. Because I'm at level ZERO on c++ knowledge all the Googling I've done is over my head. **Part 1 of the problem** My issue is that I just created my first windows form project. now that I double click and go into something like this, intellisense doesn't list any members? ``` private: System::Void executeDocumentationCmd_Click(System::Object^ sender, System::EventArgs^ e) { this. NOTHING POPS UP? } ``` If I type in `MessageBox::`, then it will popup intellisense for `Show`. Is this normal? I find it helpful as I'm learning basics to have it list available txt boxes and members, but it won't do that like it does in C# intellisense. I have `stdafx.h` included. I deleted the ncb file per online help and restarted, nothing. Additional headers? **Part 2 of the problem**: No underlined errors in realtime coding as in C# editing. Is this a feature that C++ express has (error checking before the compile)? I'm not seeing any warnings or errors listed as I type in wrong information.
`this` in C++ is a pointer that is dereferenced by `->` not `.` Also, intellisense for C++ in VS2008 is not as helpful as in C#, this includes not having error checking. VS2010 will be introducing inline error checking for C++. There are some very big differences between C# and C++ that you will need to be aware of. It's a big topic so I don't think a post here can summarise them but two important points are the lack of garbage collection (lookup the `delete` keyword) and pointers. Pointers exist in C# but they are only available in `unsafe` code blocks whereas in C++, pointers are almost king. You may want to invest in a book to help you with your learning.
FYI, according to your code snippet, you are not really using C++ but C++/CLI which is a different language.
Issue with C++ Intellisense and Error Checking
[ "", "c++", "visual-c++", "intellisense", "" ]
I have this code snippet where we get a collection from COM Dll ``` public BOCollection SelectedObjects{ get { IMSICDPInterfacesLib.IJMonikerElements oIJMonikerElements; oIJMonikerElements = m_oIJSelectSet.Elements as IMSICDPInterfacesLib.IJMonikerElements; BOCollection oBusinessObjects = new BOCollection(oIJMonikerElements); return oBusinessObjects; } ``` } Now BOCollection does implement IEnumerable. So would it be better to change it to ``` public IEnumerable<BusinessObject> SelectedObjects ``` So as to get the iterator goodness ? Or is there another way ? thanks Sunit
Are you wanting to return IEnumerable so you get deferred execution? First off, you wouldn't want to do this in a property, as I'm sure FxCop will yell at you for that. Here's how I suggest you change things so you can benefit from both deferred execution and LINQ. Change the m\_oIJSelectSet.Elements property to a method that returns IEnumerable like so: ``` public IEnumerable<IJMonikeElements> GetElements() { // Do some magic here to determine which elements are selected return (from e in this.allElements where e.IsSelected select e).AsEnumerable(); // This could also be a complicated loop // while (someCondition()) { // bool isSelected = false; // var item = this.allItems[i++]; // Complicated logic determine if item is selected // if (isSelected) { // yield return item; // } } } public IEnumerable<BusinessObject> GetSelectedObjects() { return m_oIJSelectSet.GetElements().Cast<BusinessObject>(); } ``` Now, you'll have complete deferred execution and LINQ support.
If BOCollection implements IEnumerable, then you've already got the iterator goodness. Just throw it in a for or foreach loop.
How to make this linq efficient
[ "", "c#", "linq", "" ]
I ran into a compiler error that didn't make much sense to me: ``` #include <memory> using namespace std; auto_ptr<Table> table = db->query("select * from t"); ``` error: conversion from 'Table\*' to non-scalar type 'std::auto\_ptr< Table>' requested However, the following line does work: ``` auto_ptr<Table> table(db->query("select * from t")); ``` What is it about this definiton of the constructor that prevents it from working as I expect? I thought that initialized declarations used the constructors. Here's my `auto_ptr`'s constructor (from the SGI STL): ``` explicit auto_ptr(element_type* __p = 0) throw() : _M_ptr(__p) { } ```
It's the "explicit" keyword. ``` template <typename T> struct foo { explicit foo(T const *) { } }; template <typename T> struct bar { bar(T const *) { } }; int main(int argc, char **argv) { int a; foo<int> f = &a; // doesn't work bar<int> b = &a; // works } ``` The "explicit" keyword prevents the constructor from being used for implicit type conversions. Consider the following two function prototypes: ``` void baz(foo<int> const &); void quux(bar<int> const &); ``` With those definitions, try calling both functions with an int pointer: ``` baz(&a); // fails quux(&a); // succeeds ``` In the case of quux, your int pointer was implicitly converted to a bar. **EDIT:** To expand on what other people commented, consider the following (rather silly) code: ``` void bar(std::auto_ptr<int>); int main(int argc, char **argv) { bar(new int()); // probably what you want. int a; bar(&a); // ouch. auto_ptr would try to delete a at the end of the // parameter's scope int * b = new int(); bar(b); *b = 42; // more subtle version of the above. } ```
You need to use ``` auto_ptr<Table> table = auto_ptr<Table>(db->query("select * from t")); ``` auto\_ptr does not define an assignment operator for it's template type. The only allowed assignment is from another auto\_ptr (and it's constructor from the pointer is explicit). This is done to protect accidental misuse of auto\_ptr, as auto\_ptr assumes ownership of the memory. My guess is that you need the assignment form to use multiple queries after another like: ``` // initialize using constructor auto_ptr<Table> table(db->query("select * from t1")); ... // new query using assignment table = auto_ptr<Table>(db->query("select * from t2")); ... // another query using assignment table = auto_ptr<Table>(db->query("select * from t3")); ```
Why doesn't auto_ptr construction work using = syntax
[ "", "c++", "gcc", "stl", "auto-ptr", "" ]
I have a couple email addresses, `'support@company.com'` and `'1234567@tickets.company.com'`. In perl, I could take the `To:` line of a raw email and find either of the above addresses with ``` /\w+@(tickets\.)?company\.com/i ``` In python, I simply wrote the above regex as`'\w+@(tickets\.)?company\.com'` expecting the same result. However, `support@company.com` isn't found at all and a findall on the second returns a list containing only `'tickets.'`. So clearly the `'(tickets\.)?'` is the problem area, but what exactly is the difference in regular expression rules between Perl and Python that I'm missing?
The documentation for `re.findall`: > ``` > findall(pattern, string, flags=0) > Return a list of all non-overlapping matches in the string. > > If one or more groups are present in the pattern, return a > list of groups; this will be a list of tuples if the pattern > has more than one group. > > Empty matches are included in the result. > ``` Since `(tickets\.)` is a group, `findall` returns that instead of the whole match. If you want the whole match, put a group around the whole pattern and/or use non-grouping matches, i.e. ``` r'(\w+@(tickets\.)?company\.com)' r'\w+@(?:tickets\.)?company\.com' ``` Note that you'll have to pick out the first element of each tuple returned by `findall` in the first case.
I think the problem is in your expectations of extracted values. Try using this in your current Python code: ``` '(\w+@(?:tickets\.)?company\.com)' ```
Difference in regex behavior between Perl and Python?
[ "", "python", "regex", "perl", "" ]
What is the best SQL data type for currency values? I'm using MySQL but would prefer a database independent type.
Something like `Decimal(19,4)` usually works pretty well in most cases. You can adjust the scale and precision to fit the needs of the numbers you need to store. Even in SQL Server, I tend not to use "`money`" as it's non-standard.
The only thing you have to watch out for is if you migrate from one database to another you may find that DECIMAL(19,4) and DECIMAL(19,4) mean different things ( [http://dev.mysql.com/doc/refman/5.1/en/precision-math-decimal-changes.html](https://web.archive.org/web/20090313093848/http://dev.mysql.com/doc/refman/5.1/en/precision-math-decimal-changes.html) ) ``` DBASE: 10,5 (10 integer, 5 decimal) MYSQL: 15,5 (15 digits, 10 integer (15-5), 5 decimal) ```
Best data type for storing currency values in a MySQL database
[ "", "mysql", "sql", "sqldatatypes", "" ]
What is the most efficient way to select the first and last element only, from a column in SQLite?
The first and last element from a *row*? ``` SELECT column1, columnN FROM mytable; ``` I think you must mean the first and last element from a *column*: ``` SELECT MIN(column1) AS First, MAX(column1) AS Last FROM mytable; ``` --- See <http://www.sqlite.org/lang_aggfunc.html> for `MIN()` and `MAX()`. I'm using `First` and `Last` as column aliases.
if it's just one column: ``` SELECT min(column) as first, max(column) as last FROM table ``` if you want to select whole row: ``` SELECT 'first',* FROM table ORDER BY column DESC LIMIT 1 UNION SELECT 'last',* FROM table ORDER BY column ASC LIMIT 1 ```
Most efficient way to select 1st and last element, SQLite?
[ "", "sql", "sqlite", "select", "" ]
I'm working on legacy code and need to make a patch. The problem: an ancient application sends bad HTTP POST requests. One of the parameters is not URL encoded. I know that this parameter always comes last and I know it's name. I'm now trying to fix it on the server side which is running inside tomcat. This parameter is not accessible via standard getParameter method of HttpServletRequest, since it's malformed. Method simply returns null. But when I manually read the whole body of request through ServletInputStream all the other parameters disappear. Looks like underlying classes can't parse contents of ServletInputStream since it's drained out. So far I've managed to make a wrapper that reads all parameters from body and overrides all parameter access methods. But if any filter in the chain before mine will try to access any parameter, everything will break since ServletInputStream will be empty. Can I somehow evade this problem? May be there's different approach? To summarize, If I'll read raw request body in the filter, parameters will disappear from the request. If I read single parameter, ServletInputStream will become empty and manual processing will be impossible. Moreover, it's impossible to read malformed parameter via getParameter method.
**Solution I've found:** It's not enough to just redefine parameter accessing methods. Several things must be done. 1. A filter is needed where request will be wrapped. 2. A custom **HttpRequestWrapper** is needed with all parameter access methods overridden. Request body should be parsed in constructor and stored as a field. 3. **getInputStream** and **getReader** methods should be redefined as well. They return values depend on the stored request body. 4. Custom class extending **ServletInputStream** is required since this one is abstract. This 4 combined will allow you to use **getParameter** without interference with **getInputStream** and **getReader** methods. Mind that manual request parameter parsing may get complicated with multipart requests. But that's another topic. To clarify, I redefined parameter accessing methods because my request was damaged as stated in the question. You may not need that.
Rather than overriding methods, why don't you install a servlet filter which rewrites the request? Jason Hunter has a pretty good [article on filters](http://www.servlets.com/soapbox/filters.html).
Modify HttpServletRequest body
[ "", "java", "http", "request", "" ]
How would you tackle the following storage and retrieval problem? Roughly 2.000.000 rows will be added each day (365 days/year) with the following information per row: * id (unique row identifier) * entity\_id (takes on values between 1 and 2.000.000 inclusive) * date\_id (incremented with one each day - will take on values between 1 and 3.650 (ten years: 1\*365\*10)) * value\_1 (takes on values between 1 and 1.000.000 inclusive) * value\_2 (takes on values between 1 and 1.000.000 inclusive) entity\_id combined with date\_id is unique. Hence, at most one row per entity and date can be added to the table. The database must be able to hold 10 years worth of daily data (7.300.000.000 rows (3.650\*2.000.000)). What is described above is the write patterns. The read pattern is simple: all queries will be made on a specific entity\_id. I.e. retrieve all rows describing entity\_id = 12345. Transactional support is not needed, but the storage solution must be open-sourced. Ideally I'd like to use MySQL, but I'm open for suggestions. Now - how would you tackle the described problem? **Update:** I was asked to elaborate regarding the read and write patterns. Writes to the table will be done in one batch per day where the new 2M entries will be added in one go. Reads will be done continuously with one read every second.
Use [partitioning](http://dev.mysql.com/doc/refman/5.1/en/partitioning.html). With your read pattern you'd want to partition by `entity_id` hash.
**"Now - how would you tackle the described problem?"** With simple flat files. Here's why > "all queries will be made on a > specific entity\_id. I.e. retrieve all > rows describing entity\_id = 12345." You have 2.000.000 entities. Partition based on entity number: ``` level1= entity/10000 level2= (entity/100)%100 level3= entity%100 ``` The each file of data is `level1/level2/level3/batch_of_data` You can then read all of the files in a given part of the directory to return samples for processing. If someone wants a relational database, then load files for a given entity\_id into a database for their use. --- **Edit** On day numbers. 1. The `date_id`/`entity_id` uniqueness rule is *not* something that has to be handled. It's (a) trivially imposed on the file names and (b) irrelevant for querying. 2. The `date_id` "rollover" doesn't mean anything -- there's no query, so there's no need to rename anything. The `date_id` should simply grow without bound from the epoch date. If you want to purge old data, then delete the old files. Since no query relies on `date_id`, nothing ever needs to be done with it. It can be the file name for all that it matters. To include the `date_id` in the result set, write it in the file with the other four attributes that are in each row of the file. --- **Edit** on open/close For writing, you have to leave the file(s) open. You do periodic flushes (or close/reopen) to assure that stuff really is going to disk. You have two choices for the architecture of your writer. 1. Have a single "writer" process that consolidates the data from the various source(s). This is helpful if queries are relatively frequent. You pay for merging the data at write time. 2. Have several files open concurrently for writing. When querying, merge these files into a single result. This is helpful is queries are relatively rare. You pay for merging the data at query time.
Efficiently storing 7.300.000.000 rows
[ "", "sql", "mysql", "database", "data-warehouse", "large-data-volumes", "" ]
I have a program which looks in source code, locates methods, and performs some calculations on the code inside of each method. I am trying to use regular expressions to do this, but this is my first time using them in C# and I am having difficulty testing the results. If I use this regular expression to find the method signature: ``` ((private)|(public)|(sealed)|(protected)|(virtual)|(internal))+([a-z]|[A-Z]|[0-9]|[\s])*([\()([a-z]|[A-Z]|[0-9]|[\s])*([\)|\{]+) ``` and then split the source code by this method, storing the results in an array of strings: ``` string[] MethodSignatureCollection = regularExpression.Split(SourceAsString); ``` would this get me what I want, ie a list of methods including the code inside of them?
I would strongly suggest using [Reflection](http://msdn.microsoft.com/en-us/library/ms173183(VS.80).aspx) (if it is appropriate) or [`CSharpCodeProvider.Parse(...)`](http://msdn.microsoft.com/en-us/library/system.codedom.compiler.codedomprovider.parse.aspx) (as recommended by rstevens) It can be very difficult to write a regular expression that works in all cases. Here are some cases you'd have to handle: ``` public /* comment */ void Foo(...) // Comments can be everywhere string foo = "public void Foo(...){}"; // Don't match signatures in strings private __fooClass _Foo() // Underscores are ugly, but legal private void @while() // Identifier escaping public override void Foo(...) // Have to recognize overrides void Foo(); // Defaults to private void IDisposable.Dispose() // Explicit implementation public // More comments // Signatures can span lines void Foo(...) private void // Attributes Foo([Description("Foo")] string foo) #if(DEBUG) // Don't forget the pre-processor private #else public #endif int Foo() { } ``` **Notes:** * The `Split` approach will throw away everything that it matches, so you will in fact lose all the "signatures" that you are splitting on. * Don't forget that signatures can have commas in them * `{...}` can be nested, your current regexp could consume more `{` than it should * There is a lot of other stuff (preprocessor commands, `using` statements, properties, comments, `enum` definitions, attributes) that can show up in code, so just because something is between two method signatures does not make it part of a method body.
Maybe it is a better approach to use the CSharpCodeProvider.Parse() which can "compile" C# source code into a CompileUnit. You can then walk through the namespaces, types, classes and methods of in that Compile Unit.
Finding methods in source code using regular expressions
[ "", "c#", "regex", "" ]
Database: MS SQL 2005 Table: > EmployeeNumber | EntryDate | Status Sample Data: 200 | 3/1/2009 | P 200 | 3/2/2009 | A 200 | 3/3/2009 | A 201 | 3/1/2009 | A 201 | 3/2/2009 | P Where P is present, A is absent. I have tried row\_number over partion. But it does not generate the sequence which I expect. For the above data the sequence I expect is 1 1 2 1 1 ``` SELECT EmployeeNumber, EntryDate,Status ROW_NUMBER() OVER ( PARTITION BY EmployeeNumber, Status ORDER BY EmployeeNumber,EntryDate ) AS 'RowNumber' FROM [Attendance] ```
You should be able to do this with a CTE in SQL 2005. Stealing Lievens data: ``` DECLARE @Attendance TABLE (EmployeeNumber INTEGER, EntryDate DATETIME, Status VARCHAR(1)) INSERT INTO @Attendance VALUES (200, '03/01/2009', 'P') INSERT INTO @Attendance VALUES (200, '03/02/2009', 'A') INSERT INTO @Attendance VALUES (200, '03/03/2009', 'A') INSERT INTO @Attendance VALUES (200, '03/04/2009', 'A') INSERT INTO @Attendance VALUES (200, '04/04/2009', 'A') INSERT INTO @Attendance VALUES (200, '04/05/2009', 'A') INSERT INTO @Attendance VALUES (201, '03/01/2009', 'A') INSERT INTO @Attendance VALUES (201, '03/02/2009', 'A') INSERT INTO @Attendance VALUES (201, '03/03/2009', 'P'); ``` Then use this CTE to extract the sequence: ``` WITH Dates ( EntryDate, EmployeeNumber, Status, Days ) AS ( SELECT a.EntryDate, a.EmployeeNumber, a.Status, 1 FROM @Attendance a WHERE a.EntryDate = (SELECT MIN(EntryDate) FROM @Attendance) -- RECURSIVE UNION ALL SELECT a.EntryDate, a.EmployeeNumber, a.Status, CASE WHEN (a.Status = Parent.Status) THEN Parent.Days + 1 ELSE 1 END FROM @Attendance a INNER JOIN Dates parent ON datediff(day, a.EntryDate, DateAdd(day, 1, parent.EntryDate)) = 0 AND a.EmployeeNumber = parent.EmployeeNumber ) SELECT * FROM Dates order by EmployeeNumber, EntryDate ``` Although as a final note the sequence does seem strange to me, depending on your requirements there may be a better way of aggregating the data? Never the less, this will produce the sequence you require
i'm not sure I follow what you're wanting with the 1 1 2 1 1 sequence, but simply adding an order by to your original query produces that sequence... ``` SELECT EmployeeNumber, EntryDate, Status, ROW_NUMBER() OVER (PARTITION BY EmployeeNumber, Status ORDER BY EmployeeNumber, EntryDate) AS 'RowNumber' FROM Attendance ORDER BY EmployeeNumber, EntryDate /* EmployeeNumber EntryDate Status RowNumber -------------- ----------------------- ------ -------------------- 200 2009-03-01 00:00:00 P 1 200 2009-03-02 00:00:00 A 1 200 2009-03-03 00:00:00 A 2 201 2009-03-01 00:00:00 A 1 201 2009-03-02 00:00:00 P 1 (5 row(s) affected) */ ```
How to find persons who are absent continuously for n number of days?
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I have an object that I want to use to look up other objects. I will be using a `Dictionary<TKey, TValue>()`. The key object has two strings that uniquely identify it, say `KeyObj.Str1` and `KeyObj.Str2`. What do you recommend that I use as the key for the dictionary? 1: The concatenation of the strings. ``` Dictionary<String, TValue>(); Key = KeyObj.Str1:KeyObj.Str2; ("somestring:anotherstring") ``` 2: A unique integer for each object to identify it? ``` Dictionary<int, TValue>(); KeyObj.ID = _nextID++; Key = KeyObj.ID; ``` 3: A reference to the object. ``` Dictionary<KeyObj, TValue>(); Key = KeyObj; ``` Option 3 would be the easiest, but it seems like it would be inefficient to index a dictionary based on reference values. If the key object contained a single unique string, the obvious choice would be use that, but having two strings that are only unique in combination makes it more difficult.
Concatenated strings should work best. IF you know that their combination is unique, then that is what you should choose -- remember that Hash code is **usually** unique, but not always.
You could use option 3 if you can override GetHashCode() and Equals() appropriately, i.e. something like this: ``` public override int GetHashCode() { return str1.GetHashCode() ^ str2.GetHashCode(); } public override bool Equals(object obj) { if (!obj is KeyObj) { return false; } KeyObj key = (KeyObj)obj; return this.str1.Equals(key.str1) && this.str2.Equals(key.str2); } ```
Selecting a good dictionary key
[ "", "c#", ".net", "dictionary", "indexing", "key", "" ]
I want to be able to grab content from web pages, especially the tags and the content within them. I have tried XQuery and XPath but they don't seem to work for malformed XHTML and REGEX is just a pain. Is there a better solution. Ideally I would like to be able to ask for all the links and get back an array of URLs, or ask for the text of the links and get back an array of Strings with the text of the links, or ask for all the bold text etc.
Run the XHTML through something like [JTidy](http://jtidy.sourceforge.net/), which should give you back valid XML.
You may want to look at [Watij](http://watij.com/). I have only used its Ruby cousin, Watir, but with it I was able to load a webpage and request all URLs of the page in exactly the manner you describe. It was very easy to work with - it literally fires up a webbrowser and gives you back information in nice forms. IE support seemed best, but at least with Watir Firefox was also supported.
What is the best way to screen scrape poorly formed XHTML pages for a java app
[ "", "java", "regex", "xpath", "screen-scraping", "xquery", "" ]
what's the best RSS reader for .net out there? most efficient and easy to use the ones i found are really complicated
<http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.aspx> <http://msdn.microsoft.com/en-us/magazine/cc135976.aspx> .net has a class to parse ATOM and RSS feeds. Check out the links. What are you trying to do? Can you give more information? Alternatively You can just remove the "Feed version" from the XML file and parse it as a normal XML file using xmlDocument class.
Have you looked at the [System.ServiceModel.Syndication](http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.aspx) namespace in .NET 3.5? There are other answers on Stack Overflow that may help - for example: [C# RSS Reader](https://stackoverflow.com/questions/576267/c-rss-reader).
rss parser in .net
[ "", "c#", ".net", "rss", "" ]
I am trying to detect whether the 'a' was entered as the first string argument.
``` public class YourClass { public static void main(String[] args) { if (args.length > 0 && args[0].equals("a")){ //... } } } ```
Use the [apache commons cli](http://commons.apache.org/cli/) if you plan on extending that past a single arg. "The Apache Commons CLI library provides an API for parsing command line options passed to programs. It's also able to print help messages detailing the options available for a command line tool." Commons CLI supports different types of options: * POSIX like options (ie. tar -zxvf foo.tar.gz) * GNU like long options (ie. du --human-readable --max-depth=1) * Java like properties (ie. java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo) * Short options with value attached (ie. gcc -O2 foo.c) * long options with single hyphen (ie. ant -projecthelp)
Java Command line arguments
[ "", "java", "command-line", "arguments", "" ]
I have a class in an external library subclassing UserControl and set to public. Now I want to use this usercontrol in my main WinForms app. I have added this external library to the references of the main app, but the user control haven't appeard in the Toolbox - I have been told it should appear. I am doing this for the first time. So, sorry if my question is too trivial.
1. Right click on the title panel, in the Toolbox, where you want the control. 2. Select Choose Items... 3. Click the Browse... button on the .NET Framework Components tab in the dialog that pops up (might take a few seconds for it to show) 4. Navigate to the external library, select the file and click Open. All public controls from that library are now available for selection.
You can right click on your toolbox and add it from the context menu...
WinForms: How can I include a usercontrol form an external library?
[ "", "c#", "winforms", "" ]
I want to have one file where I can check which version is installed. Its a PHP program so you can look into the files. I was thinking if there is a standardized place to put it since in the Zend Framework or the HTMLpurifier I can't find the version number at all. I would also want to add it to the Zend Framework and HTMLPurifier if there is no standard location so I always know what version is installed. Having to update a txt file would be another alternative.. EDIT: We are thinking of using PHPundercontrol in the very near future but why should it update the Zend Frameworks number? How should it know that I uploaded a new version of it?
I found it.. in the Zend Framework they have a file called Zend/Version.php -> Zend\_Version this file also has the Version number inside of it: ``` const VERSION = '1.7.5'; ``` In the HTMLPurifier it's located in HTMLPurifier/HTMLPurifier.php ``` /** Version of HTML Purifier */ public $version = '3.3.0'; /** Constant with version of HTML Purifier */ const VERSION = '3.3.0'; ``` I guess for mine I will add the version into a config file then.
I would go with the text file option rather than in the code. If you do this, as your project progresses, you can update other tools that you may or may not start to use on your project (eg: phpunderconstrol or a deployment system) to be able to set/update this number without having to risk those files touching real code and potentially causing bugs. Of course, this all depends on how you see your project progressing and whether you think you will ever use any other tools!
Is there a standard place to put the version number in the source code?
[ "", "php", "zend-framework", "version", "" ]
To add a blank line above every line that matches your regexp, you can use: ``` sed '/regexp/{x;p;x;}' ``` But I want to add a blank line, not *one* line above, but *two* lines above the line which matches my regexp. The pattern I'll be matching is a postal code in the address line. Here is a snippet of the text's formatting: > random info (belongs to previous business) > business name > business address For example: > Languages Spoken: English > Arnold's Cove, Nfld (sub To Clarenville) > Nile Road, Arnolds Cove, NL, A0B1N0 I'd like to add a new line above the business name: > Languages Spoken: English > > Arnold's Cove, Nfld (sub To Clarenville) > Nile Road, Arnolds Cove, NL, A0B1N0
Something a bit like your original approach in sed: ``` sed '/regexp/i\ $H x' ``` The basic idea is to print everything delayed by one line (**x**change the hold and pattern spaces - printing is implicit). That needs to be done because until we check whether the next line matches the regexp we don't know whether to **i**nsert a newline or not. (The $H there is just a trick to make the last line print. It appends the last line into the hold buffer so that the final implicit print command outputs it too.)
More readable Perl, and handles multiple files sanely. ``` #!/usr/bin/env perl use constant LINES => 2; my @buffer = (); while (<>) { /pattern/ and unshift @buffer, "\n"; push @buffer, $_; print splice @buffer, 0, -LINES; } continue { if (eof(ARGV)) { print @buffer; @buffer = (); } } ```
Shell: insert a blank/new line two lines above pattern
[ "", "python", "perl", "text", "sed", "awk", "" ]
I"m working on a C++ Win32 application for which I'm trying to essentially "auto detect" if a device has been plugged into one of the RS232 ports and then if it has been disconnected. The checking for a connected device is easy enough because my use case allows me to assume that this particular thread will be the first to try to initiate communication with the port. I'm able to scan the available ports every minute or so and once I've found a port with the device on it I flag that port has having a device, close the port, then set an event so that the process that actually will use the device knows it can now connect on that port. The disconnect detect is where I run into trouble. When I'm scanning for connected devices I can actually send data to the port to be sure that, if there is a device, it's the specific device I'm looking for. But once it's connected, that port will already be open by the other process and I can no longer open that port from the detect thread. So I am looking for a way to either open the port in a "listen mode" or something like that so I can just see if the device is still there. I briefly came across something about watching the DSR or DTR line or something...but couldn't find any more or how to actually do it. Any suggestions? **Edit:** Looks like I need to clarify a little more... For detecting the disconnect, I *cannot* send data to the RS232 port *in any way.* Also, I cannot assume that another application actually has the port open. The device may be physically connected, but without and open connection...but I still can't risk sending data to it. I was hoping there was a way to just check that there was still power on that port or something like that.
It depends on the connected hardware whether there will be a change in the modem state registers when you disconnect the hardware, but if there is then you could check the state of for example the CTS or DSR line using the [*GetCommModemStatus()*](http://msdn.microsoft.com/en-us/library/aa363258(VS.85).aspx) function. There is however the problem that you need a file handle to the COM port to call any API function, and this is exclusive as the documentation of [*CreateFile()*](http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx) states: > The CreateFile function can create a handle to a communications resource, such as the serial port COM1. For communications resources, the dwCreationDisposition parameter must be OPEN\_EXISTING, the dwShareMode parameter must be zero (exclusive access) So you can not open the COM port to watch the line state while another process has the port opened for communication. There are ways to do this, but they involve a driver. SysInternals has the [Portmon tool](http://technet.microsoft.com/en-us/sysinternals/bb896644.aspx), and a Google search will turn up some companies selling software for sharing COM port access between applications, but AFAIK simultaneous access is impossible using the standard API.
Sounds like it might be a good idea to have that process that will give notification of connected and disconnected events also relay the data to the other process. Have your app work in layers such that there is a process that takes control of the RS232 connection and sends your upper layer app events: connected, disconnected, data available, etc.
Determine if device is connected/disconnected to RS232 port without opening the port
[ "", "c++", "winapi", "serial-port", "" ]
We have a Legacy system that contains a number of stored procedures that we'd like to expose to other applications as web services. We are building the web services with JBoss. The stored procedures can run from Oracle, DB2 or MS SQL Server databases. JDeveloper has a wizard to generate the stubs and deploy to an ear file that would run on Oracle App Server (OC4J). We are in the process of migrating to JBoss and use Eclipse as our IDE of choice. I'd rather use a framework then rebuild and maintain the infrastructure myself. Ideally I'd like to use an open-source library or a JBoss tool/IDE to generate the web service based on the connection pool definition and stored procedure name. What are my options?
Not sure you will find exactly what you are looking for, so, if writing something yourself is out of the question, here are two alternatives: 1. Use a generic web service that will receive SP name, params and invoke the procedure. This is not very friendly to the caller and not type-safe, but it will get the job done. 2. Use a two-step approach. First step - wrap your stored procedure in a Java class (either POJO or EJB). Second step - expose the class as a web service using Apache Axis2, which is very popular, tried and tested. A quick search came us with [this framework](http://www.ohloh.net/p/ejb3spwrapper) for wrapping SPs in EJBs, but I haven't tested it myself. Besides, I think some vendors have proprietary tools for that purpose. It is a much simpler question, for sure.
If the stored procedures were not written with the intention of being directly exposed as web service operations, then it may be a very bad idea to expose them. They may be making assumptions that will not be true if they are being directly called. An alternative is to design an external API, based on requirements. If it turns out that the best way to implement one particular operation is to call a stored procedure, then do that. If it turns out that the best way to implement all of the operations is to call the existing stored procedures, then you were right, and I've just wasted your time. But I think it's likely that there will be some operations that are not best implemented by directly calling the existing stored procedures.
What is the easiest way to wrap a Stored Procedure in a Web Service?
[ "", "java", "eclipse", "web-services", "stored-procedures", "jboss", "" ]
My goal is to get a query written. I have three tables, A, B and C. The tables are written such that A.bID = B.bID, and B.cID = C.cID. This basically allows me to write a query where I link a record from a to b, and link the b record to a record from c. So far so good, simple query. What my problem is... one of the columns included in the query (let's call it C.col3) has to have unique values; the values in this column can only show up once in the query result, but other columns from the other tables do not have this requirement. Can anybody help me write this query? Thanks... **Update 1:** Here is the table layout (sorry, I have to use generic names) **Table A** aID, bID, aCol1, aCol2, aCol3 ... aCol10 **Table B** bID, cID, bCol1, bCol2, bCol3 ... bCol10 **Table C** cID, cCol1, cCol2, ***col3***, cCol4 ... cCol10 Without the unique value constraint in col3, I would write the query like this: ``` SELECT A.aID, A.bID, A.aCol1 ... A.aCol10, B.bID, B.cID, B.bCol1 ... B.bCol10, C.cID, C.cCol1, C.cCol2, C.col3 ... C.cCol10 FROM A, B, C WHERE A.bID = B.bID AND B.cID = C.cID ``` ... but of course that doesn't make sure the that values in C.col3 are unique. **Update 2:** More info... Table A and Table B have a one to many relationship; A is the "header", B is the "item". Table B and Table C have a one to one relationship. These tables are part of a caching mechanism, so lots of data that looks similar, but is still different in some cols. Since A is the header, most of the duplicate values will be found in A. I first need to order the rows by A.aID, but then after that I only need the first rows returned, where the value for C.col3 does not appear in a previous row for that col. Does that make things a little clearer, or am I still not making any sense? :) **Final Update:** I chose Bartosz Klimek's answer as it was the closest to what I needed; I just had to modify the nested join clause in the middle. Thank you all for your help!
``` SELECT A.*, B.*, C.* FROM C JOIN B ON B.cID = C.cID JOIN A ON A.bID = B.bID JOIN ( SELECT id = min(aID) FROM C JOIN B ON B.cID = C.cID JOIN A ON A.bID = B.bID GROUP BY col3 ) D ON D.id = A.aID ``` Note that the subquery at the end assures that for each col3 value you will have at most one record in the final resultset. The record selected is the one with the minimal aID. Obviously I assume that aID, bID and cID are primary keys of A, B and C, respectively.
I'm going to quickly make a little example of what you're trying to do and hopefully this will help clarify why what you are asking (currently) is impossible. If you had a Customer Table [CustomerID, CustomerName] and an Orders Table [OrderID, CustomerID, DollarAmount] If you wanted all orders for customers: ``` SELECT CustomerName, OrderID, DollarAmount FROM Customer, Orders WHERE Customer.CustomerID = Orders.CustomerID ``` it would return ``` "Acme Corp.", 1, $2300 "Acme Corp.", 2, $3022 "A company", 3, $1234 ``` Everything is good. But the equivalent of your question is asking for this query, but with unique CustomerNames. What would you display for OrderID and DollarAmount beside "Acme Corp"? You could use aggregates to display something, ``` SELECT CustomerName, MAX(OrderID), SUM(DollarAmount) FROM Customer, Orders WHERE Customer.CustomerID = Orders.CustomerID GROUP BY Orders.CustomerID ``` But I believe that you mentioned that you do not want to use aggregates. Does this explain the issue clearly?
Sql Query with unique column value
[ "", "sql", "unique", "" ]
I'm creating a regular gallery in ASP.NET but I have little experiences with creation of thumbnails. I know the algorithms and the GetThumbnailImage method, but my problem is somewhere else - I'm currently displaying the images (just resized) using the ImageButton control. And that's the point - I have no idea how to hook up the "thumbnailed" image to the ImageUrl property. Is it even possible and if yes, how? Or should I use some other control instead? Thanks for any suggestions!
You can create a HttpHandler which handles image requests and returns thumbnails (or does whatever you need on the images). Whenever you do graphics stuff in ASP.NET, keep in mind that almost *all* of System.Drawing is a wrapper for GDI+ and thetrefore holds references to unmanaged memory which needs to be disposed properly (use the `using` statement). This holds true even for simple classes like StringFormat etc.
It sounds like you need to set up an HttpHandler, which would create the resized image and probably cache it to disk as well, to save having to recreate the thumbnail on each request. So, for example: ``` <asp:ImageButton ID="ImageButton1" ImageUrl="~/ImageHandler.ashx?ImageId=123" runat="server /> ``` You would then have a handler: ``` namespace MyProject { public class ImageHandler : IHttpHandler { public virtual void ProcessRequest(HttpContext context) { // 1. Get querystring parameter // 2. Check if resized image is in cache // 3. If not, create it and cache to disk // 5. Send the image // Example Below // ------------- // Get ID from querystring string id = context.Request.QueryString.Get("ImageId"); // Construct path to cached thumbnail file string path = context.Server.MapPath("~/ImageCache/" + id + ".jpg"); // Create the file if it doesn't exist already if (!File.Exists(path)) CreateThumbnailImage(id); // Set content-type, content-length, etc headers // Send the file Response.TransmitFile(path); } public virtual bool IsReusable { get { return true; } } } } ``` You'd also need to set this up in web.config ``` <system.web> <httpHandlers> <add verb="*" path="ImageHandler.ashx" type="MyProject.ImageHandler, MyProject"/> </httpHandlers> </system.web> ``` This should be enough to get you started. You'll need to modify the ProcessRequest method to create the thumbnail, but you mentioned having taken care of this already. You'll also need to make sure that you set the headers correctly when transmitting the file to the browser.
What's the best way of displaying thumbnails in ASP.NET?
[ "", "c#", "asp.net", "image", "thumbnails", "imagebutton", "" ]
What's the easiest way to convert a `BindingList<T>` to a `T[]` ? EDIT: I'm on 3.0 for this project, so no LINQ.
Well, if you have LINQ (C# 3.0 + either .NET 3.5 or [LINQBridge](http://www.albahari.com/nutshell/linqbridge.aspx)) you can use `.ToArray()` - otherwise, just create an array and copy the data. ``` T[] arr = new T[list.Count]; list.CopyTo(arr, 0); ```
In .Net 2 you have to use `.CopyTo()` method on your `BindingList<T>`
Convert a BindingList<T> to an array of T
[ "", "c#", ".net", "generics", ".net-3.0", "" ]
I have got experience working in Spring framework, but i find it very difficult to understand the basics of Spring AOP or AOP in general. Could you guys suggest me some good online tutorials/books you have come across to learn it.
I learned by reading [AspectJ Documentation](http://www.eclipse.org/aspectj/docs.php). * [Getting Started](http://www.eclipse.org/aspectj/doc/released/progguide/starting.html) * [AspectJ Programming Guide](http://www.eclipse.org/aspectj/doc/released/progguide/index.html) I've found that these docs prepared me well enough to dive into Spring AOP without too much of a fuss.
[Ramnivas Laddad's book](https://rads.stackoverflow.com/amzn/click/com/1930110936) is very good indeed.
What is best way to learn Spring AOP or AOP in general?
[ "", "java", "spring", "aop", "" ]
I am writing a mad libs program for fun and to just program something. The program itself is pretty straight forward, but I find myself resorting to several concatenations due to the nature of the game where you place user given words into a sentence. Is there an elegant work around to resort to less concatenations or even eliminate them for something more efficient? I know in the end it will make no difference if I use concatenations or not, but I am curious if there is a more elegant way to write this program. Update: I am using java, but if there is a general solution to escaping concatenation that would be appreciated too.
One solution might be to write out your whole mad libs file and put in special tokens that need to be replaced by the words that are chosen. > You just bought a brand new ${NOUN1}, > and it is going to ${VERB1} you. Then you can use for example: `String.replace("${NOUN1}", noun1)` for all the words.
Which language are you using? Most high level langauges will have something similar to: ``` String.Format("{0} {1} {2} {3}", word1, word2, word3, word4); ```
Is there an elegant work around to concatenation?
[ "", "java", "string", "concatenation", "" ]
We are removing our XSL-> HTML solution annd replacing it with a Flex UI for our userbase. One of the concerns is that the BlazeDS (amf endpoint, so streaming or polling) won't be able to handle the load as well as the EJB -> XML -> XSLT -> HTML stack. My theory is that it should perform better, but I need a way to statistically prove this. Are there any suggestions for a product and/or method for stress-testing BlazeDS? Adobe has a stress test framework for LCDS, but it says it is not compatible with BlazeDS. I think that it might be simple to test given that I am not planning on using it as a messeging solution right now, and simple want it as an endpoint for RemoteObject connections.
I would look at using JMeter to run some automated tests against the backend: <http://jmeter.apache.org/> You should be able to write a test against the backend which takes some Java objects and uses the API available in Blaze to encode them in AMF and set the result as the body of the HTTP request.
Rob de Boer has a good article on implementing such an approach here <http://blog.jteam.nl/2009/07/14/performance-testing-a-flex-blazeds-application/>
Suggestions for Stress Testing BlazeDS
[ "", "java", "apache-flex", "actionscript", "blazeds", "stress-testing", "" ]
I've been trying to extend the ArrayList class without much success. I want to extend it, and be able to parameterize it. So normally you have something like ``` ArrayList<SomeObject> list = new ArrayList<SomeObject>(); ``` I want ``` MyList<SomeObject> list = new MyList<SomeObject>(); ``` Simply extending ArrayList doesn't work. ``` public class MyList extends ArrayList ... ``` The when I try to use it I get the error > The type MyList is not generic; it > cannot be parameterized with arguments > <SomeObject> I've tried variations of ``` public class MyList extends ArrayList<Object> public class MyList<SubObject> extends ArrayList<Object> ``` with no success, If I use the subobject behind the class name it appears to work, but hides methods in the subobject class for some reason. Any thoughts or suggestions on how to get this working right are appreciated.
You need to specify a type for the `ArrayList`'s type parameter. For generic type parameters, `T` is fairly common. Since the compiler doesn't know what a `T` is, you need to add a type parameter to `MyList` that can have the type passed in. Thus, you get: ``` public class MyList<T> extends ArrayList<T> ``` Additionally, you may want to consider implementing `List` and delegating to an `ArrayList`, rather than inheriting from `ArrayList`. "Favor object composition over class inheritance. [*Design Patterns* pg. 20]"
``` public class MyList<T> extends ArrayList<T> { } MyList<SomeObject> list = new MyList<SomeObject>(); ``` or ``` public class MyList extends ArrayList<SomeObject> { } MyList list = new MyList(); ```
How do I parameterize an extended Collection
[ "", "java", "collections", "parameterized", "extends", "" ]
I don't know if the title makes sense, but I am wondering how a hashtable enlarges when you add items to it? Is it like the `List<T>` where it doubles in size when the limit is reached? If so, then does this doubling recreates the collection from scratch (this can be answered for `List<T>` too, since I am not sure if that's what it does)? Lastly if it indeed recreates it from scratch, then this particular Add operation would be very expensive to the user who wouldn't know that the limit is reached, right?
I believe both `Hashtable` and `Dictionary<TKey, TValue>` expand to the next prime number after doubling the current count, e.g. 31 to 67. As I understand it, a resize doesn't involve *recomputing* the hashes (as they're stored with the entries) but involves putting each entry into its new bucket, where the bucket number is based on both the hash code and the bucket count. You asked about `List<T>` - there it's really simple. The list is backed by an array, and you just need to create a new array with the right size, and copy the contents of the current array. Something like: ``` private void Resize(int newCapacity) { T[] tmp = new T[newCapacity]; Array.Copy(backingArray, tmp, backingArray.Length); backingArray = tmp; } ```
The hashtable works by using buckets, which can hold several items each (at least in most implementations, there are some that reuse other buckets in case of already used buckets). The number of buckets is usually a prime number, so that dividing the hashcode by the number of buckets returns an acceptable distribution for "good" hashes. Usually, there is a certain fill factor which triggers the addition of more buckets and therefore the rebuild of the hashtable. Since the hashes are divided by the bucket count, the instances need to be redistributed according to their new bucket index, which is basically a recreate from scratch. For the .NET hashtable, you can specify the "load factor" in [some constructors](http://msdn.microsoft.com/en-us/library/7z8x5804.aspx). From MSDN: > The load factor is the maximum ratio > of elements to buckets. A smaller load > factor means faster lookup at the cost > of increased memory consumption. A > load factor of 1.0 is the best balance > between speed and size.
Hashtable doubling?
[ "", "c#", ".net", "list", "hashtable", "" ]
Is their anyway to test the correctness of a powershell script without executing it. I know you could do something similar in unix, but can't find the equiv for powershell. Essentially what I have is a script repository, where each script is tied to rule. If a rule fires, the script executes, but I need to be sure the script is valid, before its put in the repository. Thanks. Hi, Well, Unfortunately the -whatif command is not sufficient. Its the syntax of scripts I want to check from a C# runtime engine, which fires a script if a engine rule fires. Before the script fires, I write into it, IList values from the rule, and then I fire it. But I need to ensure it is syntactically correct, otherwise I'm going to have to rely on the rule writer to ensure they are correct, which I can't do, as many people will wrote rules, only one duff script will bring the engine down. I can't do that as the engine is an enterpise class product designed for six sigma uptime. I think the way to do it is to use this, which is a v2 lib. <http://msdn.microsoft.com/en-us/library/system.management.automation.parseexception(VS.85).aspx> I think there is way of creating a ScriptBlock and putting a try catch around it to catch the ParseException. Can somebody tell me how to do it. This is becoming a real challenge. Thanks. Hey, Well I spoke to a guy in MS (he's sharepoint pm) and he spoke to one of the powershell guys, and he informed me that there is no real way in powershell v1 to check the syntax of the script without executing. So I guess the -whatif flag is the closest, but it not a static checker unfortumately. Good news is, in v2 there is a way to tokenize the input stream, via the Automation.PsParser class, Tokenize member. This will tokenize a script in accordance with the PS grammes, so if it craps out, its a crap script. Question is v2 doesn't have an release date as yet. Thanks for help. Bob.
The thing you want is prolly [whatif / confirm](http://www.computerperformance.co.uk/powershell/powershell_whatif_confirm.htm). Its direct port from Unix world.
So, are you asking for functional correctness or syntactic correctness? Functionally you'd need to create a test case and environment to test in. Syntactically you're looking for a static code checker for powershell.
Testing Powershell scripts for correctness
[ "", "c#", "powershell", "scripting", "syntax-checking", "" ]
Need prettier solution of below example but with std::accumulate. ``` #include <algorithm> #include <vector> #include <iostream> class Object { public: Object( double a, double b ): a_( a ), b_( b ) {} double GetA() const { return a_; } double GetB() const { return b_; } // other methods private: double a_; double b_; }; class Calculator { public: Calculator( double& result ): result_( result ) {} void operator() ( const Object& object ) { // some formula result_ += object.GetA() * object.GetB(); } private: double& result_; }; int main() { std::vector< Object > collection; collection.push_back( Object( 1, 2 ) ); collection.push_back( Object( 3, 4 ) ); double result = 0.0; std::for_each( collection.begin(), collection.end(), Calculator( result ) ); std::cout << "result = " << result << std::endl; return 0; } ```
do changes in Calculator and main function. ``` struct Calculator { double operator() ( double result, const Object& obj ) { return result + ( obj.GetA() * obj.GetB()); } }; int main() { std::vector< Object > collection; collection.push_back( Object( 1, 2 ) ); collection.push_back( Object( 3, 4 ) ); double result = std::accumulate( collection.begin(), collection.end(), 0, Calculator() ); std::cout << "result = " << result << std::endl; return 0; } ``` also it could be better: ``` double sumABProduct( double result, const Object& obj ) { return result + ( obj.GetA() * obj.GetB()); } double result = std::accumulate( collection.begin(), collection.end(), 0, sumABProduct ); ```
**Update 2:** Boost.Lambda makes this a piece of cake: ``` // headers #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> using namespace boost::lambda; // ... cout << accumulate(dv.begin(), dv.end(), 0, _1 += bind(&strange::value, _2)) //strange defined below << endl; ``` **Update:** This has been bugging me for a while. I can't just get any of the STL algorithms to work in a decent manner. So, I rolled my own: ``` // include whatever ... using namespace std; // custom accumulator that computes a result of the // form: result += object.method(); // all other members same as that of std::accumulate template <class I, class V, class Fn1, class Fn2> V accumulate2(I first, I last, V val, Fn1 op, Fn2 memfn) { for (; first != last; ++first) val = op(val, memfn(*first)); return val; } struct strange { strange(int a, int b) : _a(a), _b(b) {} int value() { return _a + 10 * _b; } int _a, _b; }; int main() { std::vector<strange> dv; dv.push_back(strange(1, 3)); dv.push_back(strange(4, 6)); dv.push_back(strange(20, -11)); cout << accumulate2(dv.begin(), dv.end(), 0, std::plus<int>(), mem_fun_ref(&strange::value)) << endl; } ``` Of course, the original solution still holds: The easiest is to implement an `operator+`. In this case: ``` double operator+(double v, Object const& x) { return v + x.a_; } ``` and make it a friend of `Object` or member (look up why you may prefer one over the other): ``` class Object { //... friend double operator+(double v, Object const& x); ``` and you're done with: ``` result = accumulate(collection.begin(), collection.end(), 0.0); ``` My earlier approach doesn't work because we need a `binary_function`. [std::accumulate](http://www.sgi.com/tech/stl/accumulate.html) manual.
using of std::accumulate
[ "", "c++", "stl", "" ]
i'm having a memory issue while testing a find/replace function. Say the search subject is: ``` $subject = " I wrote an article in the A+ magazine. It'\s very long and full of words. I want to replace every A+ instance in this text by a link to a page dedicated to A+. "; ``` the string to be found : ``` $find='A+'; $find = preg_quote($find,'/'); ``` the replace function callback: ``` function replaceCallback($match) { if (is_array($match)) { return '<a class="tag" rel="tag-definition" title="Click to know more about ' .stripslashes($match[0]) . '" href="?tag=' . $match[0]. '">' . stripslashes($match[0]) . '</a>'; } } ``` and the call: ``` $result = preg_replace_callback($find, 'replaceCallback', $subject); ``` now, the complete searched pattern is drawn from the database. As of now, it is: ``` $find = '/(?![^<]+>)\b(voice recognition|test project reference|test|synesthesia|Superflux 2007|Suhjung Hur|scripts|Salvino a. Salvaggio|Professional Lighting Design Magazine|PLDChina|Nicolas Schöffer|Naziha Mestaoui|Nabi Art Center|Markos Novak|Mapping|Manuel Abendroth|liquid architecture|LAb[au] laboratory for Architecture and Urbanism|l'Arca Edizioni|l' ARCA n° 176 _ December 2002|Jérôme Decock|imagineering|hypertext|hypermedia|Game of Life|galerie Roger Tator|eversion|El Lissitzky|Bernhard Tschumi|Alexandre Plennevaux|A+)\b/s'; ``` This $find pattern is then looked for (and replaced if found) in 23 columns across 7 mysql tables. Using the suggested preg\_replace() instead of preg\_replace\_callback() seems to have solved the memory issue, but i'm having new issues down the path: the subject returned by preg\_replace() is missing a lot of content... UPDATE: the content loss is due to using preg\_quote($find,'/'); It now works, except for... 'A+' which becomes 'A ' after the process.
Alright - I can see, now, why you're using the callback First of all, I'd change your callback to this ``` function replaceCallback( $match ) { if ( is_array( $match ) ) { $htmlVersion = htmlspecialchars( $match[1], ENT_COMPAT, 'UTF-8' ); $urlVersion = urlencode( $match[1] ); return '<a class="tag" rel="tag-definition" title="Click to know more about ' . $htmlVersion . '" href="?tag=' . $urlVersion. '">' . $htmlVersion . '</a>'; } return $match; } ``` The stripslashes commands aren't going to do you any good. As far as addressing the memory issue, you may want to break down your pattern into multiple patterns and execute them in a loop. I think your match is just too big/complex for PHP to handle it in a single call cycle.
I'm trying to reproduce your error but there's a parse error that needs to be fixed first. Either this isn't enough code to be a good sample or there's genuinely a bug. First of all, the value you store in $find is not a pull pattern - so I had to add pattern delimiters. Secondly, your replace string doesn't include the closing element for the anchor tags. ``` $subject = " I wrote an article in the A+ magazine. It'\s very long and full of words. I want to replace every A+ instance in this text by a link to a page dedicated to A+. "; $find='A+'; $find = preg_quote($find,'/'); function replaceCallback($match) { if (is_array($match)) { return '<a class="tag" rel="tag-definition" title="Click to know more about ' .stripslashes($match[0]) . '" href="?tag=' . $match[0]. '">' . stripslashes($match[0]) . '</a>'; } } $result = preg_replace_callback( "/$find/", 'replaceCallback', $subject); echo $result; ``` This code works, but I'm not sure it's what you want. Also, I have have strong suspicion that you don't need preg\_replace\_callback() at all.
preg_replace_callback() memory issue
[ "", "php", "regex", "preg-replace", "preg-replace-callback", "" ]
I am building an application plugin in Python which allows users to arbitrarily extend the application with simple scripts (working under Mac OS X). Executing Python scripts is easy, but some users are more comfortable with languages like Ruby. From what I've read, I can easily execute Ruby scripts (or other arbitrary shell scripts) using `subprocess` and capture their output with a pipe; that's not a problem, and there's lots of examples online. However, I need to provide the script with multiple variables (say a chunk of text along with some simple boolean information about the text the script is modifying) and I'm having trouble figuring out the best way to do this. Does anyone have a suggestion for the best way to accomplish this? My goal is to provide scripts with the information they need with the least required code needed for accessing that information within the script. Thanks in advance!
See <http://docs.python.org/library/subprocess.html#using-the-subprocess-module> > args should be a string, or a sequence > of program arguments. The program to > execute is normally the first item in > the args sequence or the string if a > string is given, but can be explicitly > set by using the executable argument. So, your call can look like this ``` p = subprocess.Popen( args=["script.sh", "-p", p_opt, "-v", v_opt, arg1, arg2] ) ``` You've put arbitrary Python values into the args of `subprocess.Popen`.
If you are going to be launching multiple scripts and need to pass the same information to each of them, you might consider using the environment (warning, I don't know Python, so the following code most likely sucks): ``` #!/usr/bin/python import os try: #if environment is set if os.environ["child"] == "1": print os.environ["string"] except: #set environment os.environ["child"] = "1" os.environ["string"] = "hello world" #run this program 5 times as a child process for n in range(1, 5): os.system(__file__) ```
How to execute an arbitrary shell script and pass multiple variables via Python?
[ "", "python", "ruby", "macos", "shell", "environment-variables", "" ]
How do I obtain the version number of the calling web application in a referenced assembly? I've tried using System.Reflection.Assembly.GetCallingAssembly().GetName() but it just gives me the dynamically compiled assembly (returning a version number of 0.0.0.0). **UPDATE: In my case I needed a solution that did not require a reference back to a class within the web application assembly. Jason's answer below (marked as accepted) fulfils this requirement - a lot of others submitted here don't.**
Here is some code I use that supports getting the application's "main" assembly from either Web or non-web apps, you can then use GetName().Version to get the version. It first tries GetEntryAssembly() for non-web apps. This returns null under ASP.NET. It then looks at HttpContext.Current to determine if this is a web application. It then uses the Type of the current HttpHandler - but this type's assembly might be a generated ASP.NET assembly if the call is made from with an ASPX page, so it traverses the HttpHandler's BaseType chain until it finds a type that isn't in the namespace that ASP.NET uses for its generated types ("ASP"). This will usually be a type in your main assembly (eg. The Page in your code-behind file). We can then use the Assembly of that Type. If all else fails then fall back to GetExecutingAssembly(). There are still potential problems with this approach but it works in our applications. ``` private const string AspNetNamespace = "ASP"; private static Assembly getApplicationAssembly() { // Try the EntryAssembly, this doesn't work for ASP.NET classic pipeline (untested on integrated) Assembly ass = Assembly.GetEntryAssembly(); // Look for web application assembly HttpContext ctx = HttpContext.Current; if (ctx != null) ass = getWebApplicationAssembly(ctx); // Fallback to executing assembly return ass ?? (Assembly.GetExecutingAssembly()); } private static Assembly getWebApplicationAssembly(HttpContext context) { Guard.AgainstNullArgument(context); object app = context.ApplicationInstance; if (app == null) return null; Type type = app.GetType(); while (type != null && type != typeof(object) && type.Namespace == AspNetNamespace) type = type.BaseType; return type.Assembly; } ``` UPDATE: I've rolled this code up into a small project on [GitHub](https://github.com/laazyj/ApplicationAssemblyUtility) and [NuGet](https://nuget.org/packages/ApplicationAssemblyUtility).
I find that the simplest one-liner way to get the version of your "main" assembly (instead of the dynamic one) is: ``` typeof(MyMainClass).Assembly.GetName().Version ``` Use your top-level class, which isn't likely to ever "change its meaning" or to be replaced as part of a refactoring effort, as `MyMainClass`. You know in which assembly this very class is defined and there can no longer be confusion as to where the version number comes from.
Using the Web Application version number from an assembly (ASP.NET/C#)
[ "", "c#", ".net", "asp.net", "reflection", "assemblies", "" ]
This might be hard to explain, but I need a way to loop through a bunch of elements I've already selected and for each one find classes that start with the word "icon". So for example I might have the following elements ``` <div class="button iconStar"></div> <div class="button iconPlus"></div> <div class="button iconLeft"></div> <div class="button iconRight"></div> <div class="button iconUp"></div> <div class="button iconDown"></div> ``` So, I begin by selecting the elements and looping through them.... ``` $(".button").each(function(){ // Some code here }); ``` Now, I could put the following code in the loop... ``` if ($(this).hasClass("iconStar")){ $(this).append("<IMG SRC='Images/star.gif'>"); } ``` I would then have to repeat that for each possible icon, which seems very inefficient. What I'd like to do in the "each" loop is just cycle through all the classes that $(this) has and pick out the one that begins with ICON and then use that to append the image. Can anyone help?
For each element, get the value of the class attribute, split it by ' ', take the second part and call the image. From the top of my head ``` $(".button[class^='button icon']").each(function (el) { classStr = el.className; classes = classStr.split(' '); image = 'images/' + classes[1] + '.jpg'; }); ``` Not entirely sure of the syntax, bit rusty!
I recommend against using classes if you're not going to associate the class with the image. (*which would be the most correct way*) What I would do instead is put a link to the image in the rel tag. This does what you want, and will still validate as valid css. ``` <div class="button" rel="images/star.jpg">iconStar</div> <div class="button" rel="images/plus.jpg">iconPlus</div> <div class="button" rel="images/left.jpg">iconLeft</div> <div class="button" rel="images/right.jpg">iconRight</div> <div class="button" rel="images/up.jpg">iconUp</div> <div class="button" rel="images/down.jpg">iconDown</div> <script> $('.button').each(function() { $(this).append("<img src='"+$(this).attr('rel')+"'>"); }); </script> ``` See the example here: <http://jsbin.com/acasu> Note, if you're using a lot of tiny images, you're going to want to use [CSS Sprites](http://www.alistapart.com/articles/sprites). As it will greatly improve the performance of your page. If you absolute had to do it the way you are suggesting, you could do the following: ``` $(".button[class^='button icon']").each(function() { var iconSrc = $(this).attr('class').substr("button icon".length) $(this).append("<img src='/images/"+iconSrc+".jpg'>"); }); ```
How to pick out classes that start with a particular string
[ "", "javascript", "jquery", "" ]
I found the following example on <http://www.erictobia.com/2009/02/21/LoadADataTableWithLINQ.aspx> Unfortunately, I need it in VB and it's using some constructs that neither I nor the automated code converters reciognize. Anyone out there know how this should be written in VB.Net? (the problem spot is the "select new {...") ``` PeopleDataSet ds = new PeopleDataSet(); using (PeopleDataContext context = new PeopleDataContext()) { (from p in context.Persons select new { Row = ds.Person.AddPersonRow(p.Id, p.FirstName, p.LastName) }).ToList(); } ```
Looks to me to be case of using LINQ for the sake of using LINQ. Just for each context.Persons ``` For Each p As Person In context.Persons ds.Person.AddPersonRow(p.Id, p.FirstName, p.LastName) Next ```
Anthony has given the correct answer. However, for the record: the `new { … }` construct can be expressed in VB as follows: ``` Dim result = From p As Person in context.Persons _ Select New With { _ .Row = ds.Person.AddPersonRow(p.Id, p.FirstName, p.LastName) _ } ```
Load DataTable Using Linq - Convert C# to VB.Net
[ "", "c#", ".net", "vb.net", "linq", "datatable", "" ]
A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation. Is there an example of how this is done and the logic behind solving such a problem? I've seen a few code snippets but they weren't well commented/explained and thus hard to follow.
First of all: it smells like *recursion* of course! Since you also wanted to know the principle, I did my best to explain it human language. I think recursion is very easy most of the times. You only have to grasp two steps: 1. The first step 2. All the other steps (all with the same logic) In **human language**: > In short: > > 1. The permutation of 1 element is one element. > 2. The permutation of a set of elements is a list each of the elements, concatenated with every permutation of the other elements. > > ***Example:*** > > If the set just has one element --> > return it. > **perm(a) -> a** > > If the set has two characters: for > each element in it: return the > element, with the permutation of the > rest of the elements added, like so: > > *perm(ab) ->* > > a + perm(b) -> **ab** > > b + perm(a) -> **ba** > > Further: for each character in the set: return a character, concatenated with a permutation of > the rest of the set > > perm(abc) -> > > a + perm(bc) --> **abc**, **acb** > > b + perm(ac) --> **bac**, **bca** > > c + perm(ab) --> **cab**, **cba** > > perm(abc...z) --> > > a + perm(...), b + perm(....) > .... I found the **pseudocode** on <http://www.programmersheaven.com/mb/Algorithms/369713/369713/permutation-algorithm-help/>: ``` makePermutations(permutation) { if (length permutation < required length) { for (i = min digit to max digit) { if (i not in permutation) { makePermutations(permutation+i) } } } else { add permutation to list } } ``` **C#** OK, and something more elaborate (and since it is tagged c #), from <http://radio.weblogs.com/0111551/stories/2002/10/14/permutations.html> : Rather lengthy, but I decided to copy it anyway, so the post is not dependent on the original. > The function takes a string of characters, and writes down every possible permutation of that exact string, so for example, if "ABC" has been supplied, should spill out: ABC, ACB, BAC, BCA, CAB, CBA. Code: ``` class Program { private static void Swap(ref char a, ref char b) { if (a == b) return; var temp = a; a = b; b = temp; } public static void GetPer(char[] list) { int x = list.Length - 1; GetPer(list, 0, x); } private static void GetPer(char[] list, int k, int m) { if (k == m) { Console.Write(list); } else for (int i = k; i <= m; i++) { Swap(ref list[k], ref list[i]); GetPer(list, k + 1, m); Swap(ref list[k], ref list[i]); } } static void Main() { string str = "sagiv"; char[] arr = str.ToCharArray(); GetPer(arr); } } ```
It's just two lines of code if LINQ is allowed to use. Please see my answer [here](https://stackoverflow.com/a/10629938/1251423). **EDIT** Here is my generic function which can return all the permutations (not combinations) from a list of T: ``` static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> list, int length) { if (length == 1) return list.Select(t => new T[] { t }); return GetPermutations(list, length - 1) .SelectMany(t => list.Where(e => !t.Contains(e)), (t1, t2) => t1.Concat(new T[] { t2 })); } ``` Example: ``` IEnumerable<IEnumerable<int>> result = GetPermutations(Enumerable.Range(1, 3), 3); ``` Output - a list of integer-lists: ``` {1,2,3} {1,3,2} {2,1,3} {2,3,1} {3,1,2} {3,2,1} ``` As this function uses LINQ so it requires .net 3.5 or higher.
Listing all permutations of a string/integer
[ "", "c#", "algorithm", "permutation", "" ]
I want to find low-level C/C++ APIs, equivalent with "write" in linux systems, that don't have a buffer. Is there one? The buffered I/O such as fread, fwrite are not what I wanted.
Look at [CreateFile](http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx) with the FILE\_FLAG\_NO\_BUFFERING option
<http://www.codeproject.com/Articles/51678/Improve-responsiveness-in-Windows-with-the-FILE_FL> The only method to prevent swapping out cache is to open files with the `FILE_FLAG_NO_BUFFERING` flag. This, however, requires disk I/O requests to have sizes divisible by sector size (512 to 4096 bytes), which would require large rewrites of most applications that rely on being able to request different sizes. This project contains a drop-in wrapper that offers the `CreateFile_NB()`, `ReadFile_NB()`, `WriteFile_NB()`, and `CloseHandle_NB()` functions that take care of queuing and adjusting the file size when closing a file opened for writing. <http://msdn.microsoft.com/en-us/library/cc644950(v=vs.85).aspx> When opening or creating a file with the CreateFile function, the `FILE_FLAG_NO_BUFFERING` flag can be specified to disable system caching of data being read from or written to the file. Although this gives complete and direct control over data I/O buffering, in the case of files and similar devices there are data alignment requirements that must be considered.
Is there an un-buffered I/O in Windows system?
[ "", "c++", "c", "winapi", "file-io", "low-level", "" ]
I'm using SQL Server 2008. Say I create a temporary table like this one: ``` create table #MyTempTable (col1 int,col2 varchar(10)) ``` How can I retrieve the list of fields dynamically? I would like to see something like this: ``` Fields: col1 col2 ``` I was thinking of querying sys.columns but it doesn't seem to store any info about temporary tables. Any ideas?
``` select * from tempdb.sys.columns where object_id = object_id('tempdb..#mytemptable'); ```
``` SELECT * FROM tempdb.INFORMATION_SCHEMA.COLUMNS WHERE table_name LIKE '#MyTempTable%' ```
How to retrieve field names from temporary table (SQL Server 2008)
[ "", "sql", "sql-server", "sql-server-2008", "temp-tables", "" ]
I would like to convert a date object its integer representation for the day of week in C#. Right now, I am parsing a XML file in order to retrieve the date and storing that info in a string. It is in the following format: "2008-12-31T00:00:00.0000000+01:00" How can I take this and convert it into a number between 1 and 7 for the day of the week that it represents?
``` (Int32)Convert.ToDateTime("2008-12-31T00:00:00.0000000+01:00").DayOfWeek + 1 ```
If you load that into a DateTime varible, DateTime exposes an enum for the day of the week that you could cast to int.
Integer representation for day of the week
[ "", "c#", "datetime", "parsing", "" ]
I have an enum in a low level namespace. I'd like to provide a class or enum in a mid level namespace that "inherits" the low level enum. ``` namespace low { public enum base { x, y, z } } namespace mid { public enum consume : low.base { } } ``` I'm hoping that this is possible, or perhaps some kind of class that can take the place of the enum consume which will provide a layer of abstraction for the enum, but still let an instance of that class access the enum. Thoughts? EDIT: One of the reasons I haven't just switched this to consts in classes is that the low level enum is needed by a service that I must consume. I have been given the WSDLs and the XSDs, which define the structure as an enum. The service cannot be changed.
This is not possible. Enums cannot inherit from other enums. In fact all enums must actually inherit from `System.Enum`. C# allows syntax to change the underlying representation of the enum values which looks like inheritance, but in actuality they still inherit from System.enum. See section 8.5.2 of the [CLI spec](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-335.pdf) for the full details. Relevant information from the spec * All enums must derive from `System.Enum` * Because of the above, all enums are value types and hence sealed
You can achieve what you want with classes: ``` public class Base { public const int A = 1; public const int B = 2; public const int C = 3; } public class Consume : Base { public const int D = 4; public const int E = 5; } ``` Now you can use these classes similar as when they were enums: ``` int i = Consume.B; ``` **Update** (after your update of the question): If you assign the same int values to the constants as defined in the existing enum, then you can cast between the enum and the constants, e.g: ``` public enum SomeEnum // this is the existing enum (from WSDL) { A = 1, B = 2, ... } public class Base { public const int A = (int)SomeEnum.A; //... } public class Consume : Base { public const int D = 4; public const int E = 5; } // where you have to use the enum, use a cast: SomeEnum e = (SomeEnum)Consume.B; ```
Enum "Inheritance"
[ "", "c#", ".net", "enums", "" ]
For my web application (PHP/MYSQL), I show a list of items and a link on each row to delete the item. Right now, the link is ``` <a href='item.php?id=3&action=delete'>Delete Item</a> ``` If I wanted to use POST instead... how would I do it (this is a dynamically generated list)? Can I send POST data without the use of a form? Or, for every item, would I have to do: ``` <form action='item.php?id={$item_id}' method='POST'> <input type='hidden' name='action' value='delete'> <input type='submit' value='delete item'> </form> ``` and style the submit button to look like the original link? I am not familiar with php CURL or REST, would they help address this issue?
In general it's not a good idea to have a GET request that modifies the system state somehow, like deleting an item. You could have your form look like this: ``` <form action='item.php' method='POST' id='form'> <input type='hidden' name='action' value='delete' /> <input type='hidden' name='id' value='{item_id}' /> <a href="" onclick="document.getElementById('form').submit(); return false;">Delete item</a> </form> ```
Please use POST for anything that modifies persistent state in the database. You don't want crawlers visiting your delete links! Have a read at [Architecture of the World Wide Web, Volume One](http://www.w3.org/TR/webarch/) and [URIs, Addressability, and the use of HTTP GET and POST](http://www.w3.org/2001/tag/doc/whenToUseGet.html) by W3C. **Edit**: Sometimes though you need to use GET. For example membership activation URLs which are sent in emails are GET and need to somehow modify the database.
GET vs. POST Best Practices
[ "", "php", "html", "http", "forms", "rest", "" ]
A `JTextArea`'s tab size can easily be set using `setTabSize(int)`. Is there a similar way to do it with a `JEditorPane`? Right now, text with tabs in my pane looks like: ``` if (stuff){ more stuff; } ``` And, I'd prefer a much smaller tab stop: ``` if (stuff){ more stuff; } ```
As JEditorPane is designed to support different kinds of content types, it does not provide a way to specify a "tab size" directly, because the meaning of that should be defined by the content model. However when you use a model that's a PlainDocument or one of its descendants, there is a "tabSizeAttribute" that provides what you are looking for. Example: ``` JEditorPane pane = new JEditorPane(...); ... Document doc = pane.getDocument(); if (doc instanceof PlainDocument) { doc.putProperty(PlainDocument.tabSizeAttribute, 8); } ... ``` From the Javadoc: ``` /** * Name of the attribute that specifies the tab * size for tabs contained in the content. The * type for the value is Integer. */ public static final String tabSizeAttribute = "tabSize"; ```
In case anyone's using a StyledDocument (The link on the other answer died) You create a TabSet which is an array of TabStops. In my case I only cared about the 1st tab, and I wanted it 20px from the left, so this code worked for me: ``` StyleContext sc = StyleContext.getDefaultStyleContext(); TabSet tabs = new TabSet(new TabStop[] { new TabStop(20) }); AttributeSet paraSet = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.TabSet, tabs); pane.setParagraphAttributes(paraSet, false); ```
How do you set the tab size in a JEditorPane?
[ "", "java", "swing", "jeditorpane", "" ]
I'm trying to find a LINQ oneliner that takes a Dictionary<String,Int> and returns a Dictionary<String,SomeEnum>....it might not be possible, but would be nice. Any suggestions? EDIT: ToDictionary() is the obvious choice, but have any of you actually tried it? On a Dictionary it doesn't work the same as on a Enumerable... You can't pass it the key and value. EDIT #2: Doh, I had a typo above this line screwing up the compiler. All is well.
It works straight forward with a simple cast. ``` Dictionary<String, Int32> input = new Dictionary<String, Int32>(); // Transform input Dictionary to output Dictionary Dictionary<String, SomeEnum> output = input.ToDictionary(item => item.Key, item => (SomeEnum)item.Value); ``` --- I used this test and it does not fail. ``` using System; using System.Collections.Generic; using System.Linq; using System.Diagnostics; namespace DictionaryEnumConverter { enum SomeEnum { x, y, z = 4 }; class Program { static void Main(string[] args) { Dictionary<String, Int32> input = new Dictionary<String, Int32>(); input.Add("a", 0); input.Add("b", 1); input.Add("c", 4); Dictionary<String, SomeEnum> output = input.ToDictionary( pair => pair.Key, pair => (SomeEnum)pair.Value); Debug.Assert(output["a"] == SomeEnum.x); Debug.Assert(output["b"] == SomeEnum.y); Debug.Assert(output["c"] == SomeEnum.z); } } } ```
``` var result = dict.ToDictionary(kvp => kvp.Key, kvp => (SomeEnum)Enum.ToObject(typeof(SomeEnum), kvp.Value)); ```
Convert Dictionary<String,Int> to Dictionary<String,SomeEnum> using LINQ?
[ "", "c#", ".net", "linq", "dictionary", "" ]
I'm recording some statistics in my application. One of the statistics is the size of BigDataStructure. I have two options: 1. Create a counter and increment / decrement the counter each time there is an add/remove from the BigDataStructure. 2. Each time there is an add/remove from the BigDataStructure, set the counter to BigDataStructure.size(). Is there a good argument for doing it one way or another? Incrementing / decrementing the counter myself avoids a call to BigDataStructure.size(). It also doesn't directly involve the assignment operator (although maybe it does under the hood?) Given these two options, which one is preferable?
.size() would probably be the less error prone of the 2 options because it is [idempotent](http://en.wikipedia.org/wiki/Idempotent). If you want to get into threading/synchronization issues, .size() is safer here. Also, today you have only 1 place that adds entries, and 1 place that removes entries. But maybe in the future that won't be the case.
It depends... If BigDataStructure.size() requires work to compute the size, I would use a counter. This would be more efficient in that case. If BigDataStructure.size() is something that can be automatically determined by BigDataStructure, so very little computation is required, I'd prefer this approach. It has the advantage of keeping the logic contained in a single place, so it seems much cleaner/more OO in that respect.
Increment/decrement versus assignment?
[ "", "c++", "statistics", "" ]
I was reading this question [Deleting a const pointer](https://stackoverflow.com/questions/755196/deleting-a-const-pointer) and wanted to know more about `delete` behavior. Now, as per my understanding: `delete expression` works in two steps: 1. invoke destructor 2. then releases the memory (often with a call to `free()`) by calling operator delete. `operator delete` accepts a `void*`. As part of a test program I overloaded `operator delete` and found that `operator delete` doesn't accept `const` pointer. Since operator delete does not accept const pointer and delete internally calls operator delete, how does [Deleting a const pointer](https://stackoverflow.com/questions/755196/deleting-a-const-pointer) work ? Does `delete` uses const\_cast internally?
const\_cast doesn't really do anything – it's a way to suppress compiler moaning about const-ness of the object. *delete* keyword is a compiler construct, the compiler knows what to do in this case and doesn't care about const-ness of the pointer.
As [this answer](https://stackoverflow.com/questions/755196/deleting-a-const-pointer/755224#755224) says, `delete` is not a method like any other, but a part of the langage to destruct objects. `const`-ness has no bearing on destructability.
How does delete deal with pointer constness?
[ "", "c++", "delete-operator", "" ]
After years of using the big ugly MFC ASSERT macro, I have finally decided to ditch it and create the ultimate ASSERT macro. I am fine with getting the file and line number, and even the expression that failed. I can display a messagebox with these in, and Abort/Retry/Cancel buttons. And when I press Retry the VS debugger jumps to the line containing the ASSERT call (as opposed to the disassembly somewhere like some other ASSERT functions). So it's all pretty much working. But what would be really cool would be to *display the name of the function that failed*. Then I can decide whether to debug it without trying to guess what function it's in from the filename. e.g. if I have the following function: ``` int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { ASSERT(lpCreateStruct->cx > 0); ... } ``` Then when the ASSERT fires, the messagebox would show something like: ``` Function = CMainFrame::OnCreate ``` **So, what's the simplest way of finding out the current function name, at runtime?** *It should not use MFC or the .NET framework, even though I do use both of these. It should be as portable as possible.*
Your macro can contain the `__FUNCTION__` macro. Make no mistake, the function name **will be** inserted into the expanded code at **compile time**, but it will be the correct function name for each call to your macro. So it "seems like" it happens in run-time ;) e.g. ``` #define THROW_IF(val) if (val) throw "error in " __FUNCTION__ int foo() { int a = 0; THROW_IF(a > 0); // will throw "error in foo()" } ```
The C++ preprocessor macro `__FUNCTION__` gives the name of the function. Note that if you use this, it's not *really* getting the filename, line number, or function name at runtime. Macros are expanded by the preprocessor, and compiled in. Example program: ``` #include <iostream> void function1() { std::cout << "my function name is: " << __FUNCTION__ << "\n"; } int main() { std::cout << "my function name is: " << __FUNCTION__ << "\n"; function1(); return 0; } ``` output: ``` my function name is: main my function name is: function1 ```
How to find the name of the current function at runtime?
[ "", "c++", "function", "assert", "" ]
Here's a very specific coding question: I've recently been asked to maintain some old-ish Java Swing GUI code at work and ran into this problem: I've attached my own subclass of InputVerifier called MyFilenameVerifier to a JTextField (but it may as well be any JComponent for these purposes). I've overridden the verify() method such that it calls **`super.verify(input)`** (where input is the JComponent parameter to verify()). If **`super.verify(input)`** comes back false, I do: ``` input.setBorder(BorderFactory.createLineBorder(Color.RED)); ``` This is a convention used throughout the UI of this application that started long before me, so I don't have a lot of choice as far as using other ways to get the users attention (wish I did). This is just the way it works. Problem is, once the user goes back and types something valid into the text field, I need a way to set it back to default border (instead of just saying set it to Color.GRAY or whatever, which is a different color from its original border). I need a way to say, "remove the extra decoration and go back to normal" or just set the border to its default, in other words.
Couldn't you just call [`input.getBorder()`](http://java.sun.com/javase/6/docs/api/javax/swing/JComponent.html#getBorder()) and cache it somewhere before setting the border to red?
Or without caching anything, you could tell the JComponent to update its UI back to the look and feel's defaults via component.updateUI. That should make the component reset its colors, borders, fonts, etc to match the original settings.
Reset/remove a border in Swing
[ "", "java", "user-interface", "validation", "swing", "" ]
I want to get the various user account passwords which are stored in my computer programatically using Visual C++. Are there any APIs to help me do this?
There is no way to retrieve windows passwords nor passwords to most other programs via Win32 APIs. For Windows passwords you typically have to ask the user to enter their username/password and verify it, all by using LogonUser. For other programs they are usually stored on disk encrypted by the host application.
This is most definitely not allowed on Windows. Consider the consequences of letting any given program obtain passwords. That would mean that programs like Solitaire would be able to get your password and use it in any number of nefarious ways. Worse, the program could use the password to access other machines in resources. In short, it would throw security out the window
Password Information
[ "", "c++", "windows", "winapi", "passwords", "user-accounts", "" ]
I'd like to generate random unique strings like the ones being generated by MSDN library.([Error Object](http://msdn.microsoft.com/en-us/library/t9zk6eay.aspx)), for example. A string like 't9zk6eay' should be generated.
Using Guid would be a pretty good way, but to get something looking like your example, you probably want to convert it to a Base64 string: ``` Guid g = Guid.NewGuid(); string GuidString = Convert.ToBase64String(g.ToByteArray()); GuidString = GuidString.Replace("=",""); GuidString = GuidString.Replace("+",""); ``` I get rid of "=" and "+" to get a little closer to your example, otherwise you get "==" at the end of your string and a "+" in the middle. Here's an example output string: "OZVV5TpP4U6wJthaCORZEQ"
**Update 2016/1/23** If you find this answer useful, you may be interested in [a simple (~500 SLOC) password generation library I published](https://github.com/mkropat/MlkPwgen): ``` Install-Package MlkPwgen ``` Then you can generate random strings just like in the answer below: ``` var str = PasswordGenerator.Generate(length: 10, allowed: Sets.Alphanumerics); ``` One advantage of the library is that the code is better factored out so you can use secure randomness [for more than generating strings](http://www.codetinkerer.com/MlkPwgen/.net/html/e684d93b-fe9b-ca4a-f0a7-c23af59ab5e9.htm). Check out [the project site](https://github.com/mkropat/MlkPwgen) for more details. ### Original Answer Since no one has provided secure code yet, I post the following in case anyone finds it useful. ``` string RandomString(int length, string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") { if (length < 0) throw new ArgumentOutOfRangeException("length", "length cannot be less than zero."); if (string.IsNullOrEmpty(allowedChars)) throw new ArgumentException("allowedChars may not be empty."); const int byteSize = 0x100; var allowedCharSet = new HashSet<char>(allowedChars).ToArray(); if (byteSize < allowedCharSet.Length) throw new ArgumentException(String.Format("allowedChars may contain no more than {0} characters.", byteSize)); // Guid.NewGuid and System.Random are not particularly random. By using a // cryptographically-secure random number generator, the caller is always // protected, regardless of use. using (var rng = System.Security.Cryptography.RandomNumberGenerator.Create()) { var result = new StringBuilder(); var buf = new byte[128]; while (result.Length < length) { rng.GetBytes(buf); for (var i = 0; i < buf.Length && result.Length < length; ++i) { // Divide the byte into allowedCharSet-sized groups. If the // random value falls into the last group and the last group is // too small to choose from the entire allowedCharSet, ignore // the value in order to avoid biasing the result. var outOfRangeStart = byteSize - (byteSize % allowedCharSet.Length); if (outOfRangeStart <= buf[i]) continue; result.Append(allowedCharSet[buf[i] % allowedCharSet.Length]); } } return result.ToString(); } } ``` Thanks to Ahmad for pointing out how to get the code working on .NET Core.
Unique random string generation
[ "", "c#", "random", "" ]
I am reading the NOTIFYICONDATA documentation in MSDN. It says the NOTIFYICONDATA structure has a cbSize member should be set to the size of the structure, but NOTIFYICONDATA structure's size has different size in every Shell32.dll, so you should get the Shell32.dll version before setting cbSize. The following quotes from MSDN: --- If it is version 5.0 or later, initialize the cbSize member as follows. nid.cbSize = sizeof(NOTIFYICONDATA); Setting cbSize to this value enables all the version 5.0 and 6.0 enhancements. For earlier versions, the size of the pre-6.0 structure is given by the NOTIFYICONDATA\_V2\_SIZE constant and the pre-5.0 structure is given by the NOTIFYICONDATA\_V1\_SIZE constant. Initialize the cbSize member as follows. nid.cbSize = NOTIFYICONDATA\_V2\_SIZE; Using this value for cbSize will allow your application to use NOTIFYICONDATA with earlier Shell32.dll versions, although without the version 6.0 enhancements. --- I found it a bit of vague, because 'sizeof(NOTIFYICONDATA)' has different value in Win98 (using Shell32.dll version 4.x), Win2K (version 5.0) and WinXP (version 6.0). How could it 'enable all version 5.0 and 6.0 enhancements'? So I looked for the definition of NOTIFYICONDATA\_V1\_SIZE (source code as below), I see: NOTIFYICONDATA\_V1\_SIZE is for Win 2K (doesn't include 2K) NOTIFYICONDATA\_V2\_SIZE is for Win XP NOTIFYICONDATA\_V3\_SIZE is for Vista (not sure if I am right) It's completely different from what MSDN says? and none for Win2K? So, I am totally confused right now. How should I set the cbSize member according to Shell32.dll version? ``` //= = = = = = = = ShellAPI.h = = = = = = = = typedef struct _NOTIFYICONDATAA { DWORD cbSize; HWND hWnd; UINT uID; UINT uFlags; UINT uCallbackMessage; HICON hIcon; #if (NTDDI_VERSION < NTDDI_WIN2K) CHAR szTip[64]; #endif #if (NTDDI_VERSION >= NTDDI_WIN2K) CHAR szTip[128]; DWORD dwState; DWORD dwStateMask; CHAR szInfo[256]; union { UINT uTimeout; UINT uVersion; // used with NIM_SETVERSION, values 0, 3 and 4 } DUMMYUNIONNAME; CHAR szInfoTitle[64]; DWORD dwInfoFlags; #endif #if (NTDDI_VERSION >= NTDDI_WINXP) GUID guidItem; #endif #if (NTDDI_VERSION >= NTDDI_VISTA) HICON hBalloonIcon; #endif } NOTIFYICONDATAA, *PNOTIFYICONDATAA; typedef struct _NOTIFYICONDATAW { DWORD cbSize; HWND hWnd; UINT uID; UINT uFlags; UINT uCallbackMessage; HICON hIcon; #if (NTDDI_VERSION < NTDDI_WIN2K) WCHAR szTip[64]; #endif #if (NTDDI_VERSION >= NTDDI_WIN2K) WCHAR szTip[128]; DWORD dwState; DWORD dwStateMask; WCHAR szInfo[256]; union { UINT uTimeout; UINT uVersion; // used with NIM_SETVERSION, values 0, 3 and 4 } DUMMYUNIONNAME; WCHAR szInfoTitle[64]; DWORD dwInfoFlags; #endif #if (NTDDI_VERSION >= NTDDI_WINXP) GUID guidItem; #endif #if (NTDDI_VERSION >= NTDDI_VISTA) HICON hBalloonIcon; #endif } NOTIFYICONDATAW, *PNOTIFYICONDATAW; #define NOTIFYICONDATAA_V1_SIZE FIELD_OFFSET(NOTIFYICONDATAA, szTip[64]) #define NOTIFYICONDATAW_V1_SIZE FIELD_OFFSET(NOTIFYICONDATAW, szTip[64]) #ifdef UNICODE #define NOTIFYICONDATA_V1_SIZE NOTIFYICONDATAW_V1_SIZE #else #define NOTIFYICONDATA_V1_SIZE NOTIFYICONDATAA_V1_SIZE #endif #define NOTIFYICONDATAA_V2_SIZE FIELD_OFFSET(NOTIFYICONDATAA, guidItem) #define NOTIFYICONDATAW_V2_SIZE FIELD_OFFSET(NOTIFYICONDATAW, guidItem) #ifdef UNICODE #define NOTIFYICONDATA_V2_SIZE NOTIFYICONDATAW_V2_SIZE #else #define NOTIFYICONDATA_V2_SIZE NOTIFYICONDATAA_V2_SIZE #endif #define NOTIFYICONDATAA_V3_SIZE FIELD_OFFSET(NOTIFYICONDATAA, hBalloonIcon) #define NOTIFYICONDATAW_V3_SIZE FIELD_OFFSET(NOTIFYICONDATAW, hBalloonIcon) #ifdef UNICODE #define NOTIFYICONDATA_V3_SIZE NOTIFYICONDATAW_V3_SIZE #else #define NOTIFYICONDATA_V3_SIZE NOTIFYICONDATAA_V3_SIZE #endif ``` (Seems like the code doesn't look good on the web site, but it from ShellAPI.h, all the same)
Which features are available through platform sdk headers are controlled by `_WIN32_WINNT`, which should be defined to the lower version of the operating system you are targeting. From <http://msdn.microsoft.com/en-us/library/6sehtctf.aspx> the correct values are: > 0x0500 for Windows 2000 > operating system, 0x0501 for Windows XP, 0x0502 > for Windows Server 2003, and 0x0600 > for Windows Vista. So `NOTIFYICONDATA_V1_SIZE` refer to any version lower than 2K, `NOTIFYICONDATA_V2_SIZE` to 2K, `NOTIFYICONDATA_V3_SIZE` to XP and none to Vista (in this case you can use sizeof(NOTIFYICONDATA)). If you compile your project with `_WIN32_WINNT` set to the latest version, and detect which version of shell.dll you are running on runtime you can set .cbSize to the correct size, the rest of the fields will be ignored. Something like this should work: ``` NOTIFYICONDATA notify; ZeroMemory(&notify, sizeof(notify)); if(version >= VISTA) { notify.cbSize = sizeof(NOTIFYICONDATA); } else if(version >= XP) { notify.cbSize = NOTIFYICONDATA_V3_SIZE; } else if(version >= 2K) { notify.cbSize = NOTIFYICONDATA_V2_SIZE; } else { notify.cbSize = NOTIFYICONDATA_V1_SIZE; } ```
It depends on the lowest Windows version you compile for. You don't set the size dynamically. You set the size according to the lowest version of Windows you support.
About the MSDN Documentation on NOTIFYICONDATA's cbSize member
[ "", "c++", "winapi", "notifyicon", "" ]
I am working on a program which produces assembler code from expressions. One of the functions required is tan(x) which currently works using the following sequence of code (the addresses are filled in at run time): ``` fld [0x00C01288]; fld st(0); fsin; fld st(1); fcos; fdivp; fst [0x0030FA8C]; ``` However, I would like to use the [FPTAN](http://www.sesp.cse.clrc.ac.uk/html/SoftwareTools/vtune/users_guide/mergedProjects/analyzer_ec/mergedProjects/reference_olh/mergedProjects/instructions/instruct32_hh/vc110.htm) opcode instead, so I tried using the following code: ``` fld [0x00C01288]; fptan; fincstp; fst [0x0030FA8C]; ``` The test program uses printf to show the result stored at 0x30FA8C, but for the second sequence the result is displayed as -1.#IND (the first using cos and sin works fine). If I try examining the value at the memory address, or on top of the floating point stack, in the debugger, it appears as the correct number. So, my question is: Why is printf showing -1.#IND and how can I fix it? The value at 0x00C01288 is double precision 0.5 The result in both cases is ~0.5463024898 My first thought was that the value being stored was a different representation of the same number, but inspecting the value stored at 0x0030FA8C shows it to be 0x3FE17B4F5BF3474A in both cases. I do not understand why identical inputs to the printf function could produce different output... Any help or suggestions would be greatly appreciated. Edit: Source where printf is called: ``` #include "FridgeScript.h" #include <stdio.h> #include <math.h> char test[] = "a=tan(0.5);"; int main(int c, char** s) { unsigned int SC = FSCreateContext(); double a = 0.0; FSRegisterVariable(SC, "a", &a); unsigned int CH = FSCompile(SC, test); if(CH) FSExecute(SC, CH); printf("a: %.10g\r\n", a); printf("hex a: %I64X", a); FSDestroyContext(SC); return 0; } ```
Let me just throw something out there: how about using ``` fstp st(0); ``` instead of ``` fincstp; ``` The docs on fincstp say it's not equivalent to popping the item from the stack because it leaves that spot tagged as filled - perhaps this is messing up the float handling inside of printf? (You may be able to guess I don't know what I'm talking about. But maybe this will give you an idea?)
``` fld [0x00C01288]; fptan; fincstp; fst [0x0030FA8C]; ``` To me it looks like after this code executes, the tangent is still at `st0`. Shouldn't you use `fstp` instead of `fst`?
Why is printf showing -1.#IND for FPTAN results?
[ "", "c++", "assembly", "floating-point", "x86", "" ]
What is the best method for communication between Flex and PHP? In the past, we used AMFPHP with AS2, and it worked great for the most part (advantage of AMFPHP is that it also has a JSON mode that can let you seamlessly use the same remote PHP with either Javascript or Actionscript frontends). However, it seems like AMFPHP isn't realy maintained anymore. So what do people recommend to replace it? So far, what I've found is: 1. **[Zend\_AMF](http://framework.zend.com/wiki/display/ZFPROP/Zend_Amf+-+Wade+Arnold)** (looks too complex for us, we're not using the Zend framework otherwise) 2. **[AMFPHP](http://www.amfphp.org/)** (there were some updated made to support Flex, and it seems fairly stable, but not sure on long-term support) 3. **XML** (AS3 has nice XML handling routines, but it's more of a pain on the PHP side) 4. **[WebORB](http://www.themidnightcoders.com/products/weborb-for-php)** (I have no experience with this) 5. **Roll-our-own** using JSON or some other data-to-text serialization system (php's serialize(), XML, etc etc) Mostly I'm leaning towards AMFPHP, even because of the downsides, since that's what I'm used to. Any reason I should consider switching to something else?
If you want to have fast and efficient communication, I highly recommend sticking with an [AMF protocol](http://en.wikipedia.org/wiki/Action_Message_Format) instead of a REST or JSON custom format. **ZendAMF is actually not very confusing.** Watch the introduction tutorial on [GotoAndLearn](http://gotoandlearn.com/play?id=90), it's quite simple. And just so you know, [some of the developers](http://framework.zend.com/wiki/display/ZFPROP/Zend_Amf+-+Wade+Arnold) from AMFPHP moved to work on ZendAMF. So in a sense, ZendAMF is the continuation of AMFPHP.
ZendAMF Good short read - <http://theflashblog.com/?p=441> For me this is no brainer. The Zend framework is one of the best php frameworks out there, and now you can talk to Flash clients. Top it off with Adobe support, that's a done deal in my book. Alternatives : WebORB for php <http://www.themidnightcoders.com/products/weborb-for-php> AMFPHP <http://www.amfphp.com> If you read the url above, you'll probably know why this is no longer on my radar.
Best method for Flex to PHP communication?
[ "", "php", "xml", "apache-flex", "amfphp", "weborb", "" ]
I have OnMouseEnter and OnMouseLeave event handlers setup for my form. When the mouse moves over the form I want to set the opacity to 100% and when it moves away I want to set it to 25%. It works well, except when the mouse moves over one of the buttons on the form. The OnMouseLeave event fires and hides the form again. Is there a good way to handle this, without having to wire up OnMouseEnter for every control on the form?
EDIT: I'm going to leave this answer here, even though it can't be made to work reliably. The reason: to prevent somebody else from trying the same thing. See end of message for the reason it won't work. You can do this fairly easily for the client rectangle by getting the cursor position and checking to see if it's within the Form's client area: ``` private void Form1_MouseLeave(object sender, EventArgs e) { Point clientPos = PointToClient(Cursor.Position); if (!ClientRectangle.Contains(clientPos)) { this.Opacity = 0.25; } } ``` This assumes that none of your child controls will be changing the opacity. However, you'll find that it's a less than perfect solution, because when the mouse goes to the title bar, the Form goes to 0.25%. You could fix that by checking to see if the mouse position is within the window rect (using the Bounds property), but then your window will remain opaque if the mouse moves off the title bar and out of the window. You have a similar problem when entering the title bar from outside. I think you'll have to handle the `WM_NCMOUSEENTER` and `WM_NCMOUSELEAVE` messages in order to make this work reliably. Why it can't work: Even handling the non-client area notifications can fail. It's possible for the mouse to enter on a child control, which would prevent the Form from being notified.
I think it is impossible to do, without handling the MouseEnter and MouseLeave events of all the children, but you do not have to wire them manually. Here is some code I copied & pasted from a project of mine. It does almost what you described here. I actually copied the idea and the framework from [this site](http://seewinapp.blogspot.com/2005/08/mouseenter-and-mouseleave-events-on.html). In the constructor I call the AttachMouseOnChildren() to attach the events. The OnContainerEnter and OnContainerLeave are used to handle the mouse entering/leaving the form itself. ``` #region MouseEnter & Leave private bool _childControlsAttached = false; /// <summary> /// Attach enter & leave events to child controls (recursive), this is needed for the ContainerEnter & /// ContainerLeave methods. /// </summary> private void AttachMouseOnChildren() { if (_childControlsAttached) { return; } this.AttachMouseOnChildren(this.Controls); _childControlsAttached = true; } /// <summary> /// Attach the enter & leave events on a specific controls collection. The attachment /// is recursive. /// </summary> /// <param name="controls">The collection of child controls</param> private void AttachMouseOnChildren(System.Collections.IEnumerable controls) { foreach (Control item in controls) { item.MouseLeave += new EventHandler(item_MouseLeave); item.MouseEnter += new EventHandler(item_MouseEnter); this.AttachMouseOnChildren(item.Controls); } } /// <summary> /// Will be called by a MouseEnter event, with any of the controls within this /// </summary> void item_MouseEnter(object sender, EventArgs e) { this.OnMouseEnter(e); } /// <summary> /// Will be called by a MouseLeave event, with any of the controls within this /// </summary> void item_MouseLeave(object sender, EventArgs e) { this.OnMouseLeave(e); } /// <summary> /// Flag if the mouse is "entered" in this control, or any of its children /// </summary> private bool _containsMouse = false; /// <summary> /// Is called when the mouse entered the Form, or any of its children without entering /// the form itself first. /// </summary> protected void OnContainerEnter(EventArgs e) { // No longer transparent this.Opacity = 1; } /// <summary> /// Is called when the mouse leaves the form. When the mouse leaves the form via one of /// its children, this will also call OnContainerLeave /// </summary> /// <param name="e"></param> protected void OnContainerLeave(EventArgs e) { this.Opacity = DEFAULT_OPACITY; } /// <summary> /// <para>Is called when a MouseLeave occurs on this form, or any of its children</para> /// <para>Calculates if OnContainerLeave should be called</para> /// </summary> protected override void OnMouseLeave(EventArgs e) { Point clientMouse = PointToClient(Control.MousePosition); if (!ClientRectangle.Contains(clientMouse)) { this._containsMouse = false; OnContainerLeave(e); } } /// <summary> /// <para>Is called when a MouseEnter occurs on this form, or any of its children</para> /// <para>Calculates if OnContainerEnter should be called</para> /// </summary> protected override void OnMouseEnter(EventArgs e) { if (!this._containsMouse) { _containsMouse = true; OnContainerEnter(e); } } #endregion ```
OnMouseEnter for all controls on a form
[ "", "c#", "winforms", "" ]
I have a collection of elements on my page, and I want to see if they are visible or not currently. So: ``` $(".someClass") ``` How can I loop through and figure this out? because if it is visible, i have to fire another function.
``` $(".someClass").each(function(){ if($(this).is(":visible")){ //item is visible: do something } }); ``` how about that?
``` $(".someClass:visible") ``` will return the visible ones.
Determine if collection of elements are visible using JQuery like $(".someClass")
[ "", "javascript", "jquery", "" ]
I have a GlobalAssemblyInfo.cs file in the root of my solution, and I have something like the following entry in it to enable strong naming of my output assemblies. ``` #pragma warning disable 1699 [assembly : AssemblyKeyFile("..\\keyfile.snk")] #pragma warning restore 1699 ``` This approach has two drawbacks. Firstly, AssemblyKeyFileAttribute is deprecated, and so to avoid compilation warnings I need the pragma lines you see above. Secondly, I either need to keep all my projects at the same depth relative to the root to use the relative path, or use an absolute path, which dictates a checkout location on other users' machines (and on continuous integration servers/build agents). Does anyone have a better solution than this, other than going through each project setting strong naming in the project file?
Those attributes for key signing were deprecated for good reason (information leakage), which is another reason to go the project route. If you have a lot of projects it might be possible to set them via a recorded macro, or even directly manipulating the .csproj files (ensure they are unloaded from VS first).
Well, to avoid the path problem you can use `[assembly:AssemblyKeyName(...)]` instead (although IIRC this is also deprecated); use `sn -i` to install a named key. Each machine (that does builds) would need this key adding. Other than that; yes, you'd probably need to edit the project files.
GlobalAssemblyInfo.cs and strong naming
[ "", "c#", ".net", "configuration-management", "" ]
Is it possible to create a MySQL database from Java? I have only seen connection URLs examples like this where the database name is specified in the URL: ``` String url="jdbc:mysql://localhost:3306/test"; Connection con = DriverManager.getConnection( url, "cb0", "xxx" ); ``` How can I create a MySQL database when I only have a login name and password?
The database isn't required in the jdbc connection, so you can do something like recommended at <http://forums.mysql.com/read.php?39,99321,102211#msg-102211> and <http://marc.info/?l=mysql-java&m=104508605511590&w=2>: ``` Conn = DriverManager.getConnection ("jdbc:mysql://localhost/?user=root&password=rootpassword"); s=Conn.createStatement(); int Result=s.executeUpdate("CREATE DATABASE databasename"); ```
To create database through Java code, you must use `executeUpdate(sql)` instead of `executeQuery(sql);` and connect to the `mysql` database as root: ``` connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull", "root", "root" ); Statement st = connection.createStatement(); st.executeUpdate(sql); st.close(); ```
Create MySQL database from Java
[ "", "java", "mysql", "database", "" ]
For following data: > date|value|check > 2009 | 5 | 1 > 2008 | 5 | 1 > 2007 | 5 | 1 > 2006 | 5 | 0 > 2005 | 5 | 0 > 2004 | 5 | 1 > 2003 | 5 | 1 > 2002 | 5 | 1 I need to select all rows from 2009 back until first occurrence of 0 in check column: > date|value|check > 2009 | 5 | 1 > 2008 | 5 | 1 > 2007 | 5 | 1 I tried with the lag function, but I was only able to check a month back. I am working on Oracle 10g. UPDATE: All seems to work well, my test data set is too small to say anything about the performance differences.
``` SELECT * FROM mytable where date > ( SELECT max(date) FROM mytable where check = 0 ) ```
``` SELECT * FROM ( SELECT m.*, MIN(CASE WHEN check = 0 THEN 0 ELSE 1 END) OVER (ORDER BY date DESC)) AS mn FROM mytable ) WHERE mn = 1 ``` or even better: ``` SELECT * FROM ( SELECT m.*, ROW_NUMBER() OVER (ORDER BY mydate DESC) AS rn FROM mytable m ORDER BY mydate DESC ) WHERE rownum = DECODE(check, 0, NULL, rn) ORDER BY mydate DESC ``` The latter query will actually stop scanning as soon as it encounters the first zero in check.
Selecting all rows until first occurrence of given value
[ "", "sql", "oracle", "" ]
Here's the problem. I have an image: ``` <img alt="alttext" src="filename.jpg"/> ``` Note no height or width specified. On certain pages I want to only show a thumbnail. I can't alter the html, so I use the following CSS: ``` .blog_list div.postbody img { width:75px; } ``` Which (in most browsers) makes a page of uniformly wide thumbnails, all with preserved aspect ratios. In IE6 though, the image is only scaled in the dimension specified in the CSS. It retains the 'natural' height. Here's an example of a pair of pages that illustrate the problem: * [The list, which should show thumbnails](http://www.escapelondon.co.uk/profiles/blog/list) * [A single blog post, which shows the full-size image.](http://www.escapelondon.co.uk/profiles/blogs/epernay-champagne) I'd be very grateful for all suggestions, but would like to point out that (due to the limitations of the clients chosen platform) I'm looking for something that doesn't involve modifying the html. CSS would also be preferable to javascript. EDIT: Should mention that the images are of different sizes and aspect ratios.
Adam Luter gave me the idea for this, but it actually turned out to be really simple: ``` img { width: 75px; height: auto; } ``` IE6 now scales the image fine and this seems to be what all the other browsers use by default. Thanks for both the answers though!
I'm glad that worked out, so I guess you had to explicitly set 'auto' on IE6 in order for it to mimic other browsers! I actually recently found another technique for scaling images, again designed for backgrounds. This technique has some interesting features: 1. The image aspect ratio is preserved 2. The image's original size is maintained (that is, it can never shrink only grow) The markup relies on a wrapper element: ``` <div id="wrap"><img src="test.png" /></div> ``` Given the above markup you then use these rules: ``` #wrap { height: 100px; width: 100px; } #wrap img { min-height: 100%; min-width: 100%; } ``` If you then control the size of wrapper you get the interesting scale effects that I list above. To be explicit, consider the following base state: A container that is 100x100 and an image that is 10x10. The result is a scaled image of 100x100. 1. Starting at the base state, the container resized to 20x100, the image stays resized at 100x100. 2. Starting at the base state, the image is changed to 10x20, the image resizes to 100x200. So, in other words, the image is always *at least* as big as the container, but will scale *beyond* it to maintain it's aspect ratio. This probably isn't useful for your site, and it doesn't work in IE6. But, it *is* useful to get a scaled background for your view port or container.
How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?
[ "", "javascript", "css", "internet-explorer", "image", "internet-explorer-6", "" ]
Is there a mechanism to comment out large blocks of Python code? Right now, the only ways I can see of commenting out code are to either start every line with a `#`, or to enclose the code in triple quotes: `"""`. The problem with these is that inserting `#` before every line is cumbersome and `"""` makes the string I want to use as a comment show up in generated documentation. After reading all comments, the answer seems to be "No".
Python does not have such a mechanism. Prepend a `#` to each line to block comment. For more information see [PEP 8](http://www.python.org/dev/peps/pep-0008/). Most Python IDEs support a mechanism to do the block-commenting-with-hash-signs automatically for you. For example, in IDLE on my machine, it's `Alt`+`3` and `Alt`+`4`. **Don't use triple-quotes;** as you discovered, this is for documentation strings not block comments, although it has a similar effect. If you're just commenting things out temporarily, this is fine as a temporary measure.
Hide the triple quotes in a context that won't be mistaken for a docstring, eg: ``` ''' ...statements... ''' and None ``` or: ``` if False: ''' ...statements... ''' ```
How to comment out a block of code in Python
[ "", "python", "docstring", "" ]
Given a section of HTML, can I selectively pick some types of elements (e.g., input) and add a custom attribute using JavaScript? I would also need to remove this attribute if it exists. I have done this before using jQuery, but I'm unable to use it for this particular task.
[Accessing HTML attributes using the DOM](http://www.javascriptkit.com/dhtmltutors/domattribute.shtml) ``` element.hasAttribute('foo'); element.getAttribute('foo'); element.setAttribute('foo', value); element.removeAttribute('foo'); ```
``` <div class="first-div"> <p class="first-p">Hello! </p> </div> ``` Adding attribute via javascript: ``` var myDiv= document.getElementsByClassName("first-div")[0]; var myp= myDiv.children[0]; nyp.setAttribute('myAttribute','valueForAttribute'); ``` getting the attribute via javascript: ``` console.log(myp.getAttribute('myAttribute')); ```
Javascript for adding a custom attribute to some elements
[ "", "javascript", "" ]
I am using a ASP.NET MVC framework, jQuery library (1.3.2), linq to sql, sql server 2005. I have a problem with jQuery MaskMoney plugin, to save data in sql server table. I created a table, where this table have a field "valueProducts" type Decimal(18,2). In my page, I have a html field with jQuery maskmoney. Example: 10.000,00 (Ten thousand (R$)). When I save this data, occurs this error: "The model of type 'MercanteWeb.Dados.MateriasPrimasEntradas' was not successfully updated." (I use UpdateModel to save data). I found out that this problem occurs because of thousand separator (.) and if I remove this mask plugin, it is work. Someone can help me? Thanks.
I did it. The problem of answer above is in the Linq to SQL data mapping. Fields type money or smallmoney are mapping using decimal type. The solution that I found was... I don't save money fields of the View using UpdateModel. before: ``` Check c = new Check(); this.UpdateModel(c, new[] { "number", "name", "value1", "value2" }); ``` after: ``` Check c = new Check(); this.UpdateModel(c, new[] { "number", "name" }); c.value1 = Convert.ToDecimal(f["value1"]); c.value2 = Convert.ToDecimal(f["value2"]); ``` With this, the value is successfully convert for decimal data type. In the view, I used the objects of Globalization namespace. ``` //ViewPage <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <%@ Import Namespace="System.Globalization" %> <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server"> <% NumberFormatInfo LocalFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone(); LocalFormat.CurrencySymbol = ""; Check c = (Check)ViewData.Model; %> //In the field, I use de string format type currency and I passed the object of //CurrentSymbol ... Value1:<br> <%= Html.TextBox("value1", Convert.ToDouble(c.value1).ToString("C", LocalFormat))%> .... </asp:Content> ``` Thank you for helping me.
You can either remove the separators: ``` $("#real").maskMoney({symbol:"R$",decimal:"",thousands:""}); ``` Or parse through the number in asp.net removing them and it will work. I'm not familiar with asp.net so I couldn't give you the syntax. I would do some data parsing/checking on the server side anyway just for security reasons.
Trouble with jQuery MaskMoney plugin and Field type Decimal (SQL SERVER table)
[ "", "javascript", "jquery", "sql-server", "asp.net-mvc", "linq-to-sql", "" ]
I have a Javascript function that returns the innerHTML of a div. I am attempting to call this function from Actionscript and store the return value. I know that the Javascript function is being called because there is an alert that displays the return data, The data that is returned to Actionscript, however, is null. I am not sure what is causing this. Here is a code example of what I am attempting to do: ``` Javascript: function JSFunc () { var x = document.getElementById("myDiv"); alert(x.innerHTML); return x.innerHTML; } Actionscript: import flash.external.*; if (ExternalInterface.available) { var retData:Object = ExternalInterface.call("JSFunc"); if(retData != null) { textField.text = retData.toString(); } else { textField.text = "Returned Null"; } } else { textField.text = "External Interface not available"; } ``` Like I said earlier, the alert shows up with the contents of the div but the text in the textfield is always "Returned Null", meaning that the ExternalInterface is available. I should add that I can only test this in IE7 and IE8. Any advice on what to do would be much appreciated.
The source of the problem that I have been having has to do the object tag that I was using to embed the flash movie. I was using a tag that followed this example <http://www.w3schools.com/flash/flash_inhtml.asp>, I changed it to match this example: <http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_4150> and then I made sure that I added id to the object and everything worked.
[This is a working sample](http://osmanu.com/flex/EITest/EITest.html) based on the code you provided. You can right click it to view the source. I suspect the problem lies in the HTML for 'myDiv' or when you are making the actionscript call.
ExternalInterface.call() not getting return value
[ "", "javascript", "apache-flex", "flash", "actionscript-3", "" ]
Without thinking to much, it seems to me that a large set of Prolog's functionality could be implemented as relational calculus (a.k.a. SQL). Has anyone heard of any tools to automatically convert Prolog to SQL?
Recommending: <https://www.cs.cmu.edu/afs/cs/project/ai-repository/ai/lang/prolog/code/io/pl2sql/0.html> my advice- use Eclipse prolog (http://www.eclipseclp.org/) (not (here) to be confused with prolog in the eclipse IDE). I spent hours trying to get the code to compile in 4 other prologs(!) and 4 minutes to compile in eclipse. When it works, it's a thing of beauty. Credit to Herr Draxler of course
Yes, of course. A premise for skeptics: any semi-decent book on database theory mentions [Datalog](http://en.wikipedia.org/wiki/Datalog) (which is Prolog-like) and theorems which demonstrate that is possible to translate it to/from Relational Algebra (RA) (under specific restrictions). SQL is not faithful to RA or relational calculi, but is enough to support Prolog: * [Christoph Draxler](http://www.phonetik.uni-muenchen.de/institut/mitarbeiter/draxler/draxler.html) has developed a Prolog to SQL compiler (PL2SQL) for his thesis, [available for download](http://www.phonetik.uni-muenchen.de/institut/mitarbeiter/draxler/prolog_sql.tgz) (.tgz) - also here at [CMU Artificial Intelligence Repository](https://www.cs.cmu.edu/afs/cs/project/ai-repository/ai/lang/prolog/code/io/pl2sql/0.html) (it was adapted and included in at least: [Ciao Prolog](http://clip.dia.fi.upm.es/Software/Ciao/ciao_html/ciao_152.html) and [SWI-Prolog](http://www.berkeleybop.org/blipdoc/doc/users/cjm/cvs/blipkit/packages/blip/sql/sql_compiler.pro) via [Blipkit - Biomedical LogIc Programming Knowledge Integration Kit](http://www.blipkit.org/)); * Igor Wojnicki has developed for his PhD ([A Rule-based Inference Engine Extending Knowledge Processing Capabilities of Relational Database Management Systems](http://home.agh.edu.pl/~wojnicki/phd/)) a prototype system implementing his [Jelly View technology](http://portal.acm.org/citation.cfm?id=1066822) called **ReDaReS**, but it seems not available for download; * [Relational Abstract Machine (RAM)](http://babel.ls.fi.upm.es/research/ram/) translates Prolog to Relational Algebra, but it doesn't seems to have a SQL backend; * Walter D. Potter has [a couple of papers](http://pages.citebite.com/j1m9o0t1t3vqu) on Prolog/RDBMS integration; * Kevin Boone's paper on [Using SQL with Prolog to improve performance with large databases](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.31.6333) is also interesting; * [and so on](http://www.google.com/search?q=Prolog+to+SQL+compiler)...
prolog to SQL converter
[ "", "sql", "prolog", "transpiler", "" ]
I have a server and has 2 clients connecting to it through TCP. These clients continuously send information to the server. This is a proxy server and relays the messages it receives from the client. But it has to do relay the messages alternately. i.e. message from client A, then message from client B and again A then B and so on. This I can achieve by checking where the message is coming from and then relay messages alternately and ignoring consecutive messages from the same client. However I also do not want the server to get bogged down if any of the clients disconnects or is not sending messages. If this happens the proxy will continue to wait forever for the some message from the client which is now disconnected (or for some reason not sending message). In this case I would want the server to relay the message from from sole connected client. Instead I am thinking if something like this is possible. If I get 2 consecutive messages from the same client I would like to check if the other client is read to send me a message. My question is whether it is possible to check from the other client's socket if there is a message buffered and ready to be sent. In this this case can ignore the consecutive message from the same the client and instead first send the message from the other client. (that I have checked.) Is this possible? Hope I have asked the question clearly. Thanks
I am reading the problem as thus: You have: 1 server 2 clients Your server gets messages from client 1 and 2 and forwards them. The clients are different producers, meaning the messages they are sending could potentially be different. What you want is the messages from the clients to be sent alteratively out from your server, but not to "wait" if a client has dropped. In this scenario, I suggest that you have two queues (client1queue and client2queue) in your server. You will have to read from the sockets in two seperate threads, and when a message comes in add it to its corresponding queue. client1Socket -> client1queue client2Socket -> client2queue Then, in a third thread, have the server forward the messages, alternating pulling these messages from client1queue and client2queue. To solve your problem of "not waiting" if the queue is empty simply skip that queues' "turn." This insures sending all messages at the fastest possible rate while still getting all the messages across. The downside is that it only alternates if a message is ready to be sent. You could, of course, have it wait for X amount to see if a message comes for the other queue, but I don't see why you would want to if the system is supposed to work regardless of the client state.
You could set the read timeout on the sockets to be something short (like a second maybe or whatever time you want to wait for each client) with the setSoTimeout() method; that way, when you get the second message from client A, you can just read() from client B's socket and if you get a SocketTimeoutException then you can process A's message. But you will have to modify your current code to catch any SocketTimeoutExceptions you may get whenever you're reading from the sockets.
Java Network Programming. Question about sockets
[ "", "java", "networking", "sockets", "" ]
**Note**: Part of a series: [C#: Accessing form members from another class](https://stackoverflow.com/questions/717264/c-accessing-form-members-from-another-class) and [How to access form objects from another cs file in C#](https://stackoverflow.com/questions/717074/how-to-access-form-objects-from-another-cs-file-in-c). --- Hello, The Idea is to notify the user using the memo when a packet is received/sent in a TCP Client. After couple of fixes,the most suitable solution seemed to be this one ``` public string TextValue { set { this.Memo.Text += value + "\n"; } } ``` That's how it's being called ``` var form = Form.ActiveForm as Form1; if(form != null) form.TextValue = "Test asdasd"; ``` However,calling the code throws an exception ,because of Unsafe thread call.I found a solution at [msdn](http://msdn.microsoft.com/en-us/library/ms171728.aspx),but I can't seem to acquire the method they've used there. This is my remake,which doesn't work. ``` private void SetTextMemo(string txt) { if(this.Memo.InvokeRequired) { this.Invoke(SetTextMemo,txt); //error here } else { this.Memo.Text += txt + "\n"; } } ``` errors: Argument '1': cannot convert from 'method group' to 'System.Delegate' Argument '2': cannot convert from 'string' to 'object[]' Basically,I'm trying to access the Memo(or more likely said,add text to the memo) from another thread using Invoke.I never used it before,maybe that's why I misunderstand my mistake.
The easy way is: ``` this.Invoke((MethodInvoker)delegate { this.Memo.Text += txt + "\n"; }); ``` Which uses an anonymous method to do the job inline. Since you *expect* to be on another thread, you may as well just call Invoke - it is safe even from the UI thread.
If you're using C# 3.0 and the 3.5 framework try the following ``` if ( this.Memo.InvokeRequired ) { this.Invoke((Action)(() => SetTextMemo(txt))); } ```
Accessing Class members with Invoke from a different thread in C#
[ "", "c#", "winforms", "multithreading", "invoke", "" ]
I'm new to hibernate, as you'll soon see. I apologize if this question has an easy answer, but I'm just not familiar enough with all of the terminology to find it easily. Let's say I have a base class "A" and one subclass "B" that I'm mapping with Hibernate, perhaps using the table per subclass strategy. The base class is not abstract. All Bs are As, but not all As are Bs. This is reflected in the database, where table B references table A. Ok, now suppose I have a program of some sort that displays a list of A objects. The user can select any A object and be taken to a screen to modify it...BUT, if the A object is also a B, the screen will allow the user to modify B instead of just A. How in the world do I approach this? **Note: I'm not asking about how to determine what class an object is. What I'm asking is how do I get hibernate to return a list of objects that are of the proper class.**
I apologize again for this question. I'm very surprised at how hibernate works, it's really cool. I didn't think it would do all of this automagically, and I really wasn't even sure what I was trying to ask. As I responded to comments I started to refine the question in my head and was able to then find the answer I was looking for. Thanks to everyone who helped. The answer is: hibernate does this automatically. Suppose you have in your database table A with a primary key "id", and a table B that has a primary key called "a\_id" that references table A. So you create the following classes (abbreviated): ``` public class A { private String aProperty; // ... getter and setter, etc { public class B extends A { private String bProperty; // ... getter and setter, etc } ``` Then map them like so: ``` <hibernate-mapping> <class name="A" table="a" catalog="testokdelete"> <id name="id" type="java.lang.Integer"> <column name="id" /> <generator class="identity" /> </id> <property name="aProperty" column="a_property"/> <joined-subclass name="B" table="b"> <key column="a_id"/> <property name="bProperty" column="b_property"/> </joined-subclass> </class> </hibernate-mapping> ``` And you can return A and B objects using a simple "from A" query, as in the following code: ``` Query query = session.createQuery("from A"); List<Object> objects = query.list(); for (Object object: objects) { System.out.print("A property: "); System.out.print(((A)object).getAProperty()); System.out.print(", B property: "); System.out.println( (object.getClass() == B.class) ? ((B)object).getBProperty() : "not a B"); } ``` All it does is return a list of objects using the query "from A", and then walks through them printing out aProperty from our A class and, if the class is of type B, the bProperty from our B class. The hibernate query in this case is automatically polymorphic and will give you a B object when appropriate.
You could use RTTI, with instanceof, but that's not object-oriented. Instead, give the base class, `A` a method that pertains to what extra a `B` does, e.g, if `A` is `Customer` and `B` is `PreferredCustomer`, the method might be `isPreferredCustomer()`. In `A`, the method return false, in `B` it returns true. It's important to note that we're not asking if an object is of a certain class; we're asking a business question, asking an object if it can do something. It's a subtle but important distinction. In particular, it means that your code below won't have to change when and if you add more `Customer` subclasses, so long as each subclass truthfully answers the question, `isPreferredCustomer()`. In your code: ``` if( a.isPreferredCustomer() ) { showPreferredCustomerPage( a) ; else { show CustomerPage(a); } ``` You might think it even better to give `Customer` a `showPage()` method, but that too tightly binds your models to your views. Instead, you put the above code in some `ViewDispatcher` class, which can vary orthogonally with Customer and its subclasses. For example, you might have several `ViewDispatcher` subclasses, some of which care about `PreferredCustomer`s and some which don't.
Hibernate polymorphism: instantiating the right class
[ "", "java", "hibernate", "orm", "" ]
I'm using CURL to import some code. However, in french, all the characters come out funny. For example: Bonjour ... I don't have access to change anything on the imported code. Is there anything I can do my side to fix this? Thanks
Like Jon Skeet pointed it's difficult to understand your situation, however if you have access only to final text, you can try to use **iconv** for changing text encoding. I.e. ``` $text = iconv("Windows-1252","UTF-8",$text); ``` I've had similar issue time ago (with Italian language and special chars) and I've solved it in this way. Try different combination (UTF-8, ISO-8859-1, Windows-1252).
I had a similar problem. I tried to loop through all combinations of input and output charsets. Nothing helped! :( However I was able to access the code that actually fetched the data and this is where the culprit lied. Data was fetched via cURL. Adding ``` curl_setopt($ch,CURLOPT_BINARYTRANSFER,true); ``` fixed it. A handy set of code to try out all possible combinations of a list of charsets: ``` $charsets = array( "UTF-8", "ASCII", "Windows-1252", "ISO-8859-15", "ISO-8859-1", "ISO-8859-6", "CP1256" ); foreach ($charsets as $ch1) { foreach ($charsets as $ch2){ echo "<h1>Combination $ch1 to $ch2 produces: </h1>".iconv($ch1, $ch2, $text_2_convert); } } ```
CURL import character encoding problem
[ "", "php", "encoding", "curl", "" ]
For a block like this: ``` try: #some stuff except Exception: pass ``` pylint raises warning W0703 'Catch "Exception"'. Why?
It's considered good practice to not normally catch the root Exception object, instead of catching more specific ones - for example IOException. Consider if an out of memory exception occurred - simply using "pass" isn't going to leave your programme in a good state. Pretty much the only time you should catch Exception is at the top level of your programme, where you can (try to) log it, display an error, and exit as gracefully as you can.
It's good practice to catch only a very narrow range of types. 'Exception' is too general - you will end up catching not just the errors you planned for, but other errors too, which may mask bugs in your code that would be quicker to diagnose if they weren't caught at all, or possibly would be better dealt with by a single very high level exception handler. Having said that, since Python2.6, catching Exception has become a lot more reasonable, because all the exceptions that you wouldn't want to catch (SystemExit, KeyboardInterrupt) no longer inherit from Exception. They instead inherit from a common BaseException instead. This has been done deliberately in order to make catching Exception relatively harmless, since it is such a common idiom. See [PEP 3110](http://www.python.org/dev/peps/pep-3110/) for details & future plans.
pylint warning on 'except Exception:'
[ "", "python", "pylint", "" ]
I need to save an image from a PHP URL to my PC. Let's say I have a page, `http://example.com/image.php`, holding a single "flower" image, nothing else. How can I save this image from the URL with a new name (using PHP)?
If you have `allow_url_fopen` set to `true`: ``` $url = 'http://example.com/image.php'; $img = '/my/folder/flower.gif'; file_put_contents($img, file_get_contents($url)); ``` Else use [cURL](http://www.php.net/manual/en/book.curl.php): ``` $ch = curl_init('http://example.com/image.php'); $fp = fopen('/my/folder/flower.gif', 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); fclose($fp); ```
Use PHP's function [copy()](https://www.php.net/manual/en/function.copy.php): ``` copy('http://example.com/image.php', 'local/folder/flower.jpg'); ``` Note: this requires [allow\_url\_fopen](https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen)
Saving image from PHP URL
[ "", "php", "image", "" ]
I am using [GDIView](http://www.nirsoft.net/utils/gdi_handles.html) to try to track down the source of a few lingering GDI handles, and the source seems to be Fonts used in a menu on the form. The only way I've found to make sure the font handles are GCed is to explicitly set them to null like this: ``` tsmiTextLocation.Font = null; tsmiLocationSelection.Font = null; ``` This doesn't seem quite right to me, but I'm not sure how else to address the issue. Has anyone else run into this problem before?
Even though it is best practice to call `IDisposable.Dispose()` yourself either by calling it directly or leveraging the using keyword. Some GDI+ objects are exception to this rule. GDI+ contains predefined brushes and pens in Brushes and Pens classes. You should not call `Dispose()` on objects returned by members of these classes (or other GDI pre-cached objects which you haven't created by new on your own). And a note from MSDN - [`Font.Dispose`](http://msdn.microsoft.com/en-us/library/system.drawing.font.dispose.aspx): > Always call Dispose before you release your last reference to the Font. > Otherwise, the resources it is using will not be freed until the garbage > collector calls the Font object's Finalize method.
Setting to null will make them be garbage collected eventually, and the finalizer will be called. This could take some time, if there is no memory pressure the objects may live for a while. System.Drawing.Font implements IDisposable, so you should call Font.Dispose to free up any unmanaged resources (the GDI handles) deterministically. I believe you have to call Dispose explicitly, since the font may be shared and therefore the form can't dispose of the font in its Dispose method.
Why are Font Handles not being disposed?
[ "", "c#", ".net", "winforms", "" ]
What's the best way to pass a method and a method parameter to another method? Is there a better way to do the following? ``` def method1(name) return 'Hello ' + name def method2(methodToCall, methodToCallParams, question): greetings = methodToCall(methodToCallParams) return greetings + ', ' + question method2(method1, 'Sam', 'How are you?') ```
You could do it this way: ``` def method1(name): def wrapper(): return 'Hello ' + name return wrapper def method2(method, question): output = method() return output + ', ' + question method2(method1(name = 'Sam'), 'How are you?') ``` You can of course pass some variables in the method() call too: ``` def method1(name): def wrapper(greeting): return greeting + name return wrapper def method2(method, question): output = method(greeting = 'Hello ') return output + ', ' + question method2(method1(name = 'Sam'), 'How are you?') ```
If you want to package the invocation up in one hit, you can use the functools module: ``` from functools import partial def some_function(param_one, param_two): print "Param One: %s" % param_one print "Param Two: %s" % param_two def calling_function(target): target() calling_function(partial(some_function, "foo", "bar")) ``` You can do tweakier things with functools.partial too, such as binding only some parameters, leaving you with a function with a new signature. It's overkill in a lot of cases to use it but it certainly has it's place.
What is the best way to pass a method (with parameters) to another method in python
[ "", "python", "" ]
If I have objects on one layer with the same name as objects on another layer, is it best to change the object names with some prefix or have new namespace and refer to them with fully qualified names? For example: ``` namespace Project1.Data Object Person; namespace Project1.Model Object Person; ``` --- ``` Data.Person.Name=Person.Name; OR dbPerson.Name= Person.Name; ```
I'd use namespaces and namespace aliases, e.g: Define your classes in appropriate namespaces: ``` namespace Project1.Data { public class Person {...} } namespace Project1.Model { public class Person {...} } ``` And where you use the classes, either use fully qualified names or define an alias for the namespaces (especially usefule if the full namespace is long): ``` using data = Project1.Data; using model = Project1.Model; data.Person p1 = new data.Person(); model.Person p2 = new model.Person(); //... p1.Name = p2.Name; ```
It depends on how often you're referring to the overloaded name. If you use it several times in one file, then use the first way. If you use it only once or twice, then write out the fully qualified name, so that other people won't have to go hunting around at the top of your file to figure out what object you're referring to.
Naming Conventions and Namespaces
[ "", "c#", "naming-conventions", "" ]
I wanted to get ideas from the SO community about this issue. Here is the problem: We have a user on the other side of the world launching our app through WebStart. The user, however, is complaining that her whole application freezes up and becomes unresponsive. Usually, the client is doing a lot of database queries to a distributed database. Questions: 1. If we ask her to do a **CTRL-Break** on her application, where would the JVM write the stack trace to? 2. Would it be enough just to use **JConsole**? 3. Would implementing **JMX beans** on the client be overkill? Would it actually help in troubleshooting issues in production? Right now the users are running on JRE 1.5.0-b08, but we do plan on migrating to JRE 6 in a couple of months. What do you think?
José, you can get a lot of information from the JVM in a number of ways. The best might be to enable debugging in the remote JVM. You can set them using the `j2se` element in the descriptor XML, as shown [here](http://java.sun.com/j2se/1.5.0/docs/guide/javaws/developersguide/syntax.html#resources). Since you can set `-Xdebug` you have a good start; I've never tried to do remote debugging on a web start app, so it may be a little bit of an issue setting up the remote part. You could also set some things up yourself by adding a separate thread to talk to you remotely and send debugging messages. You could use a [native java](http://java.sun.com/j2se/1.4.2/docs/guide/util/logging/overview.html#1.18) or [log4j remote logger](http://logging.apache.org/log4j/1.2/apidocs/index.html). If it's hanging the way you describe, though, the odds are very high that what's happening is a network hangup of some sort. Can you put some tracing/debugging onto *your* end of the conversation?
Instead of these debugging suggestions, why don't you install an exception handler for your threads? See java.lang.Thread. ``` void setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) ``` Here's the relevant javadoc: <http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)> If you install that in your code, and once inside Swing's EDT, then just write some java code to e-mail it to yourself, save it on a server, show it to the user, etc.
How to obtain a Java stack trace from a client running under web start?
[ "", "java", "stack-trace", "java-web-start", "" ]
I have the following javascript snippet, which fails to load due to a missing ; before statement before thr declarion of url withing searchUserInfo.. I have double and triple checked this code ``` function submitUserInfo(username) { url = "edit_user.php?cmd=submitinfo&username="+username+"&firstname="+document.userForm.firstname.value+"&lastname="+document.userForm.lastname.value+"&flaggedauctions="+document.userForm.flaggedauctions.value+"&lastauction="+document.userForm.lastauction.value+"&street1="+document.userForm.street1.value+"&city1="+document.userForm.city1.value+"&postcode1="+document.userForm.postcode1.value+"&street2="+document.userForm.street2.value+"&city2="+document.userForm.city2.value+"&postcode2="+document.userForm.postcode2.value+"&phone="+document.userForm.phone.value+"&mobilephone="+document.userForm.mobilephone.value+"&fax="+document.userForm.fax.value+"&email="+document.userForm.email.value+"&website="+document.userForm.website.value+"&bank="+document.userForm.bank.value+"&banknumber="+document.userForm.banknumber.value+"&accountnumber="+document.userForm.accountnumber.value+"&comments="+document.userForm.comments.value; var xmlHttp=GetXmlHttpObject(); //you have this defined elsewhere //if(xmlHttp.responseText == 'true') { xmlHttp.open("GET",url,true); xmlHttp.send(null); updateByUser(username); //} } function searchUserInfo() { url = "get_results.php?cmd=SearchUserData&searchstring="+document.searchForm.search.value"&subcat="+subcat; var xmlHttp=GetXmlHttpObject(); //you have this defined elsewhere //if(xmlHttp.responseText == 'true') { xmlHttp.open("GET",url,true); xmlHttp.send(null); update('Layer3', url); //} } ``` I have used jslint, and can not see what, if anything has changed. There are no errors. I am using firebug, but it does not aid me.
You forgot a `+` operator. This: ``` url = "get_results.php?cmd=SearchUserData&searchstring="+document.searchForm.search.value"&subcat="+subcat; ``` Should be: ``` url = "get_results.php?cmd=SearchUserData&searchstring="+document.searchForm.search.value+"&subcat="+subcat; ```
You are missing a + here ``` value"&subcat="+subcat ```
Javascript syntax problems -- finding it
[ "", "javascript", "html", "" ]
I have a base class that contains the following events: ``` public event EventHandler Loading; public event EventHandler Finished; ``` In a class that inherits from this base class I try to raise the event: ``` this.Loading(this, new EventHandler()); // All we care about is which object is loading. ``` I receive the following error: *The event 'BaseClass.Loading' can only appear on the left hand side of += or -= (BaseClass')* I am assuming I cannot access these events the same as other inherited members?
What you have to do , is this: In your base class (where you have declared the events), create protected methods which can be used to raise the events: ``` public class MyClass { public event EventHandler Loading; public event EventHandler Finished; protected virtual void OnLoading(EventArgs e) { EventHandler handler = Loading; if( handler != null ) { handler(this, e); } } protected virtual void OnFinished(EventArgs e) { EventHandler handler = Finished; if( handler != null ) { handler(this, e); } } } ``` (Note that you should probably change those methods, in order to check whether you have to Invoke the eventhandler or not). Then, in classes that inherit from this base class, you can just call the OnFinished or OnLoading methods to raise the events: ``` public AnotherClass : MyClass { public void DoSomeStuff() { ... OnLoading(EventArgs.Empty); ... OnFinished(EventArgs.Empty); } } ```
You can only access an event in the declaring class, as .NET creates private instance variables behind the scenes that actually hold the delegate. Doing this.. ``` public event EventHandler MyPropertyChanged; ``` is actually doing this; ``` private EventHandler myPropertyChangedDelegate; public event EventHandler MyPropertyChanged { add { myPropertyChangedDelegate += value; } remove { myPropertyChangedDelegate -= value; } } ``` and doing this... ``` MyPropertyChanged(this, EventArgs.Empty); ``` is actually this... ``` myPropertyChangedDelegate(this, EventArgs.Empty); ``` So you can (obviously) only access the private delegate instance variable from within the declaring class. The convention is to provide something like this in the declaring class.. ``` protected virtual void OnMyPropertyChanged(EventArgs e) { EventHandler invoker = MyPropertyChanged; if(invoker != null) invoker(this, e); } ``` You can then call `OnMyPropertyChanged(EventArgs.Empty)` from anywhere in that class or below the inheritance heirarchy to invoke the event.
C#: Raising an inherited event
[ "", "c#", "events", "inheritance", "" ]
I try to reuse some columns that I calculate dynamically in Oracle SQL, something like ``` SELECT A*2 AS P, P+5 AS Q FROM tablename ``` Where 'tablename' has a column called 'A', but no other colums. This gives me an ``` ORA-00904: "P": invalid identifier ``` I know how to work around this by using a subquery like ``` SELECT P, P+5 AS Q FROM ( SELECT A*2 AS P FROM tablename ) ``` but I think this is kinda ugly. Furthermore I want to make the query somewhat more complex, e.g. reusing 'Q' as well, and I do not want to create yet another subquery. Update: The reason I want to store the calculation of 'P' is that I want to make it more complex, and reuse 'P' multiple times. So I do not want to explicitly say 'A\*2+5 AS Q', because that would quickly become to cumbersome as 'P' gets more complex. There must be a good way to do this, any ideas? Update: I should note that I'm not a DB-admin :(. --- Update: A real world example, with a more concrete query. What I would like to do is: ``` SELECT SL/SQRT(AB) AS ALPHA, 5*LOG(10,ALPHA) AS B, 2.5*LOG(10,1-EXP(-5/ALPHA)*(5/ALPHA+1)) AS D BS -2.74 + B + D AS BSA FROM tablename ``` for now, I've written it out, which works, but is ugly: ``` SELECT SL/SQRT(AB) AS ALPHA, 5*LOG(10,SL/SQRT(AB)) AS B, 2.5*LOG(10,1-EXP(-5/(SL/SQRT(AB)))*(5/(SL/SQRT(AB))+1)) AS D BS -2.74 + 5*LOG(10,SL/SQRT(AB)) + 2.5*LOG(10,1-EXP(-5/(SL/SQRT(AB)))*((5/(SL/SQRT(AB)))+1)) AS BSA FROM tablename ``` I could do all of this after receiving the data, but I thought, let's see how much I can let the database do. Also, I would like to select on 'BSA' as well (which I can do now with this query as a subquery/with-clause). --- Update: OK, I think for now I finished with Cade Roux' and Dave Costa's solution. Albeit Pax' and Jens Schauder's solution would look better, but I can't use them since I'm not a DBA. Now I don't know who to mark as the best answer :). ``` WITH A1 AS ( SELECT A0.*, SL/SQRT(AB) AS ALPHA FROM tablename A0 ), A2 AS ( SELECT A1.*, 5*LOG(10,ALPHA) AS B, 2.5*LOG(10,1-EXP(-5/ALPHA)*((5/ALPHA)+1)) AS D FROM A1 ) SELECT ALPHA, B, D, BS, BS -2.74 + B + D AS BSA FROM A2 ``` --- BTW, in case anyone is interested, SB is the 'surface brightness' of galaxies, for which B and D are correction terms.
We have this same problem in SQL Server (it's an ANSI problem). I believe it is intended to avoid confusing aliasing effects: ``` SELECT A * 2 AS A ,A * 3 AS B -- This is the original A, not the new A FROM whatever ``` We work around it by stacking up common table expressions: ``` WITH A1 AS ( SELECT A * 2 AS A FROM whatever ) ,A2 AS ( SELECT A1.* ,A * 3 AS B FROM A1 ) ,A3 AS ( SELECT A2.* ,A + B AS X FROM A2 ) SELECT * FROM A3 ``` This is the most readable and maintable and followable version. For UPDATEs, there is a deprecated SQL Server workaround using the column\_name = notation, where you can reference a column which has been updated previously in the list. But this cannot be used in SELECTs. I would hope that some ability to stack expressions (without using a scalar UDF) is added to ANSI SQL at some point in the future.
I'm not sure you can do this (I've never seen it done) but you could work around it with: ``` SELECT A*2 AS P, A*2+5 AS Q FROM tablename ``` That's certainly better than introducing a subquery. The only other way I'd suggest is to create a view giving you the P/Q-type columns (using the formulae above) which would at least simplify the text of the query. Then you could just: ``` SELECT P, Q FROM viewintotablename ```
How to reuse dynamic columns in an Oracle SQL statement?
[ "", "sql", "oracle", "ora-00904", "" ]
I'm trying to establish whether we are better off rendering charts serverside and pushing them to the browser as images or using a javascript charting library to draw the charts clientside. I'm looking at the JFreeChart and Dojo Charting libraries, my target is an existing JSP site that runs in JBoss. Does anyone have any experience with this who might be able to point out the merits/flaws of each. At the moment I'm seeing Client side rendering as being a hell of a lot more efficient unless the dataset is Huge.
I would like to recommend a library I wrote: [charts4j](http://charts4j.googlecode.com) which is a server-side charting solution. Here are some features: * Supports nearly all features of the [Google Chart API](http://code.google.com/apis/chart/) * Hides the ugly details of creating the URL parameters that are necessary for communicating with the Google Chart API * Can be incorporated into any Internet enabled Swing or web application environment (JSP/Servlet, GWT, Spring MVC, etc.) * 100% pure core Java solution. No need for special graphics libraries, etc. * Super-scalable & Lightweight. Only one 160Kb jar and an Internet connection required * Well documented * Best of all, it is FREE! Here are some [testimonials](http://code.google.com/p/charts4j/wiki/Testimonials). Also check out the [FAQ](http://code.google.com/p/charts4j/wiki/FAQ). I have an example of incorporating this technology into a Spring MVC (using JSPs) app on [my blog](http://radioeiffel.blogspot.com/2008/12/incorporating-google-charts-into-spring.html).
I would recommend determining your performance/provisioning needs and making the decision from there. If you are expecting a large number of clients, each requiring a large number of charts which may need to update periodically, offloading the processing onto the clients will likely be the better solution. As jesper mentioned, you would also be able to do more interaction directly with the charts on the client, rather than requiring callbacks to the server for more complex functionality. If the general use-model for your charts is simple (e.g. static charts being generated on the fly by the server, w/out needs for updating), and the number of clients is low, you might be fine using hardware to better improve performance. Server-side would probably be sufficient in this case. Scalability and performance can be hard to implement later down the road. If you have the potential to mitigate this from the beginning, you should do so, since current use models so often change as future users decide they need faster/better functionality.
Web Charting, serverside or client side?
[ "", "java", "jsp", "charts", "" ]
Previously, I ran into a problem trying to share a type definition between my ASMX webservice and my .aspx page (webclient) [Confused on C# Array of objects and implicit type conversion](https://stackoverflow.com/questions/667619/confused-on-c-array-of-objects-and-implicit-type-conversion) As I understand the advice, the "problem" this creates can be solved by copying the array of objects created in the client to a new array of objects as defined by the ASMX proxy class. Being a rookie in C# I am still struggling with this simple task. Here are more parts of my code (the other fragments in the previous post remain unchanged): ... here is where I populate the "test data" I want to pass to the web service: ``` // create an array of MetaData objects MetaData[] nvPairs = new MetaData[20]; // arbitrary length of 20 pairs // create arbitrary MetaData objects in the array nvPairs[0] = new MetaData("Grant Number", "2577-9912"); nvPairs[1] = new MetaData("OPEAnalyst", "Simpson"); ``` ... here I attempt a function to "copy" from "real" type defined in my TRIMBrokerUtil namespace (which I can't use completely because of the proxy) to the proxy version of that type: ``` protected TRIMBrokerASMXProxy.ASMXProxy.MetaData[] CopyMetaData( MetaData utilArray) { TRIMBrokerASMXProxy.ASMXProxy.MetaData[] outArray = new TRIMBrokerASMXProxy.ASMXProxy.MetaData[utilArray.Name.Length]; int i; for (i = 0; i < utilArray.Name.Length; i++) { outArray[i].Name = utilArray.Name; outArray[i].Value = utilArray.Value; } return outArray; } ``` ... and then here is where I try to call that function (compiler flags 2 errors on this line: ``` TRIMBrokerASMXProxy.ASMXProxy.MetaData[] kvData = CopyMetaData(metaDataArray); ``` Both of the compile errors below point to the same line: Error 1 The best overloaded method match for '\_Default.CopyMetaData(TRIMBrokerUtil.MetaData)' has some invalid arguments Error 2 Argument '1': cannot convert from 'TRIMBrokerUtil.MetaData[]' to 'TRIMBrokerUtil.MetaData' Am I close ?
You've declared your parameter to be `MetaData` rather than `MetaData[]` - in other words it's not an array. You're then using `utilArray.Name` rather a lot, but it's not clear why. I suspect you actually want: ``` protected TRIMBrokerASMXProxy.ASMXProxy.MetaData[] CopyMetaData(MetaData[] utilArray) { TRIMBrokerASMXProxy.ASMXProxy.MetaData[] outArray = new TRIMBrokerASMXProxy.ASMXProxy.MetaData[utilArray.Length]; for (int i = 0; i < utilArray.Length; i++) { outArray[i] = new TRIMBrokerASMXProxy.ASMXProxy.MetaData(); outArray[i].Name = utilArray[i].Name; outArray[i].Value = utilArray[i].Value; } return outArray; } ``` By the way, you might want to consider a `using` directive to make this easier to read: ``` using ProxyMetaData = TRIMBrokerASMXProxy.ASMXProxy.MetaData; ... protected ProxyMetaData[] CopyMetaData(MetaData[] utilArray) { ProxyMetaData[] outArray = new ProxyMetaData[utilArray.Length]; for (int i = 0; i < utilArray.Length; i++) { outArray[i] = new ProxyMetaData(); outArray[i].Name = utilArray[i].Name; outArray[i].Value = utilArray[i].Value; } return outArray; } ``` Another alternative is `Array.ConvertAll`: ``` ProxyMetaData[] output = Array.ConvertAll(input, metaData => new ProxyMetaData(metaData.Name, metaData.Value)); ``` If you're not using C# 3 you can use an anonymous method for that. If `ProxyMetaData` doesn't have an appropriate constructor and you *are* using C# 3, you can use an object initializer: ``` ProxyMetaData[] output = Array.ConvertAll(input, metaData => new ProxyMetaData { metaData.Name, metaData.Value }); ``` If you're stuck with C# 2 and no appropriate constructor, then: ``` ProxyMetaData[] output = Array.ConvertAll(input, delegate(MetaData metaData) { ProxyMetaData proxy = new ProxyMetaData(); proxy.Name = metaData.Name; proxy.Value = metaData.Value; }); ``` I *think* that's covered all the bases :)
I would just use LINQ to do this: ``` TRIMBrokerASMXProxy.ASMXProxy.MetaData[] kvData = metaDataArray.Select(d => new TRIMBrokerASMXProxy.ASMXProxy.MetaData( d.Name, d.Value)).ToArray(); ``` Additionally, if you are using .NET 3.5, it means you can use WCF as well, which is what you should be using to generate the proxy. You would be able to attribute your TRIMBrokerASMXProxy.ASMXProxy.MetaData type with the DataContract attribute and the members being serialized with the DataMember attribute. Then, you would be able to define your contract with the actual type, and not have to perform conversion at all.
Copy array of objects to array of different type
[ "", "c#", "arrays", "object", "copying", "" ]
I need to copy the indexes from one table to another. There are a LOT of indexes and I don't want to recreate them from scratch. Seems error prone anyways. I have copied the structure using ``` SELECT * INTO [BackupTable] FROM [OriginalTable] ``` But that doesn't copy indexes, constraints, triggers etc Does anyone know how to do this?
Do you want to copy the Index definition? Then you can reverse engineer the index, triggers etc using the "Script" option in the Microsoft SQL Management tool Simply right click on a table name in the SQL Management Studio table list and select "Script Table as" and then "Create to" You can't copy the Index data as it relates to the physical storage of the Index First **check that you have "Tools/Options/SQL Server Object Explorer/Scripting/Script Indexes" set to "True".** This is set to false in some version of the SQL Management tool (thanks Mark) ![enter image description here](https://i.stack.imgur.com/KEMcp.png)
By default the right-click table "CREATE" does not include the indexes or triggers, just the table definition and constraints. You can right click the *database* and click "Tasks" -> "Generate Scripts" which will allow you to do this Edit: this is the default but as TFD mentions it can be changed, thankfully.
How to copy indexes from one table to another in SQL Server
[ "", "sql", "sql-server", "database", "indexing", "" ]
I am doing a tutorial and am getting this error: > Fatal error: Class 'MySQLi' not found (LONG URL) on line 8 The code on line 8 is: ``` $mysqli = new MySQLi($db_server, $db_user, $db_pass, $db_name); ``` I saw online someone said to see if it was turned on in my phpinfo(), but there wasn't anything listed in there under for "mysqli". Also, I am running PHP version 5.2.5
Sounds like you just need to [install MySQLi](https://php.net/manual/en/mysqli.installation.php).
You can check if the mysqli libraries are present by executing this code: ``` if (!function_exists('mysqli_init') && !extension_loaded('mysqli')) { echo 'We don\'t have mysqli!!!'; } else { echo 'Phew we have it!'; } ```
How to solve "Fatal error: Class 'MySQLi' not found"?
[ "", "php", "mysqli", "" ]
I have an array: ``` $myArray = array('key1'=>'value1', 'key2'=>'value2'); ``` I save it as a variable: ``` $fileContents = var_dump($myArray); ``` How can convert the variable back to use as a regular array? ``` echo $fileContents[0]; //output: value1 echo $fileContents[1]; //output: value2 ```
I think you might want to look into [`serialize`](http://us.php.net/serialize) and [`unserialize`](http://us.php.net/manual/en/function.unserialize.php). ``` $myArray = array('key1'=>'value1', 'key2'=>'value2'); $serialized = serialize($myArray); $myNewArray = unserialize($serialized); print_r($myNewArray); // Array ( [key1] => value1 [key2] => value2 ) ```
serialize might be the right answer - but I prefer using JSON - human editing of the data will be possible that way... ``` $myArray = array('key1'=>'value1', 'key2'=>'value2'); $serialized = json_encode($myArray); $myNewArray = json_decode($serialized, true); print_r($myNewArray); // Array ( [key1] => value1 [key2] => value2 ) ```
Convert PHP array string into an array
[ "", "php", "arrays", "serialization", "" ]
I am wondering, Is it possible to Shut down a remote PC programatically through .net application? If yes, how it can be?
See [this KB article](http://support.microsoft.com/kb/317371) For example: ``` System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.EnableRaisingEvents=false; proc.StartInfo.FileName = "shutdown.exe"; proc.StartInfo.Arguments = @"\\computername /t:120 ""The computer is shutting down"" /y /c"; proc.Start(); ``` The example above uses the following switches (excerpted from the linked article) * \\computername: Use this switch to specify the remote computer to shut down. If you omit this parameter, the local computer name is used. * /t:xx: Use this switch to specify the time (in seconds) after which the computer is shut down. The default is 20 seconds. * "The computer is shutting down": Use this switch to specify a message during the shutdown process. The maximum number of characters that the message can contain is 127. * /y: Use this switch to force a "yes" answer to all queries from the computer. * /c: Use this switch quit all running programs. If you use this switch, Windows forces all programs that are running to quit. The option to save any data that may have changed is ignored. This can result in data loss in any programs for which data is not previously saved.
WMI will work for this task. The Win32\_OperatingSystem class has a method called Win32Shutdown. This can be used to shutdown a remote computer. Win32Shutdown: <http://msdn.microsoft.com/en-us/library/aa394058(VS.85).aspx> The following blog entry has a full program in C# that demonstrates how to shutdown a computer using WMI. Search for Win32Shutdown on the page (about the 2nd article down) <http://urkec.mojblog.rs/>
Is it possible to Shut down a 'remote PC' programatically through .net application?
[ "", "c#", "remoting", "" ]
I'm trying to use a typedef from a subclass in my project, I've isolated my problem in the example below. Does anyone know where I'm going wrong? ``` template<typename Subclass> class A { public: //Why doesn't it like this? void action(typename Subclass::mytype var) { (static_cast<Subclass*>(this))->do_action(var); } }; class B : public A<B> { public: typedef int mytype; B() {} void do_action(mytype var) { // Do stuff } }; int main(int argc, char** argv) { B myInstance; return 0; } ``` This is the output I get: ``` sean@SEAN-PC:~/Documents/LucadeStudios/experiments$ g++ -o test test.cpp test.cpp: In instantiation of ‘A<B>’: test.cpp:10: instantiated from here test.cpp:5: error: invalid use of incomplete type ‘class B’ test.cpp:10: error: forward declaration of ‘class B’ ```
The reason is that when instantiating a class template, all its declarations (not the definitions) of its member functions are instantiated too. The class template is instantiated precisely when the full definition of a specialization is required. That is the case when it is used as a base class for example, as in your case. So what happens is that `A<B>` is instantiated at ``` class B : public A<B> ``` at which point `B` is not a complete type yet (it is after the closing brace of the class definition). However, `A<B>::action`'s declaration requires `B` to be complete, because it is crawling in the scope of it: ``` Subclass::mytype ``` What you need to do is delaying the instantiation to some point at which `B` is complete. One way of doing this is to modify the declaration of `action` to make it a member template. ``` template<typename T> void action(T var) { (static_cast<Subclass*>(this))->do_action(var); } ``` It is still type-safe because if `var` is not of the right type, passing `var` to `do_action` will fail.
You can get around this by using a traits class: It requires you set up a specialsed traits class for each actuall class you use. ``` template<typename SubClass> class SubClass_traits {}; template<typename Subclass> class A { public: void action(typename SubClass_traits<Subclass>::mytype var) { (static_cast<Subclass*>(this))->do_action(var); } }; // Definitions for B class B; // Forward declare template<> // Define traits for B. So other classes can use it. class SubClass_traits<B> { public: typedef int mytype; }; // Define B class B : public A<B> { // Define mytype in terms of the traits type. typedef SubClass_traits<B>::mytype mytype; public: B() {} void do_action(mytype var) { // Do stuff } }; int main(int argc, char** argv) { B myInstance; return 0; } ```
invalid use of incomplete type
[ "", "c++", "templates", "typedef", "crtp", "" ]
Can a class extend both an interface and another class in PHP? Basically I want to do this: ``` interface databaseInterface{ public function query($q); public function escape($s); //more methods } class database{ //extends both mysqli and implements databaseInterface //etc. } ``` How would one do this, simply doing: ``` class database implements databaseInterface extends mysqli{ ``` results in a fatal error: ``` Parse error: syntax error, unexpected T_EXTENDS, expecting '{' in *file* on line *line* ```
Try it the other way around: ``` class database extends mysqli implements databaseInterface { ...} ``` This should work.
Yes it can. You just need to retain the correct order. ``` class database extends mysqli implements databaseInterface { ... } ``` Moreover, a class can implement more than one interface. Just separate 'em with commas. However, I feel obliged to warn you that **extending mysqli class is incredibly bad idea**. Inheritance per se is probably the most overrated and misused concept in object oriented programming. Instead I'd advise doing db-related stuff the mysqli way (or PDO way). Plus, a minor thing, but naming conventions do matter. Your class `database` seems more general then `mysqli`, therefore it suggests that the latter inherits from `database` and not the way around.
Can a class extend both a class and implement an Interface
[ "", "php", "php-parse-error", "" ]
Does anyone know how to convert a string from ISO-8859-1 to UTF-8 and back in Java? I'm getting a string from the web and saving it in the RMS (J2ME), but I want to preserve the special chars and get the string from the RMS but with the ISO-8859-1 encoding. How do I do this?
In general, you can't do this. UTF-8 is capable of encoding any Unicode code point. ISO-8859-1 can handle only a tiny fraction of them. So, transcoding from ISO-8859-1 to UTF-8 is no problem. Going backwards from UTF-8 to ISO-8859-1 will cause "replacement characters" (�) to appear in your text when unsupported characters are found. To transcode text: ``` byte[] latin1 = ... byte[] utf8 = new String(latin1, "ISO-8859-1").getBytes("UTF-8"); ``` or ``` byte[] utf8 = ... byte[] latin1 = new String(utf8, "UTF-8").getBytes("ISO-8859-1"); ``` You can exercise more control by using the lower-level [`Charset`](http://java.sun.com/javase/6/docs/api/java/nio/charset/package-summary.html) APIs. For example, you can raise an exception when an un-encodable character is found, or use a different character for replacement text.
***Which worked for me:*** *("üzüm bağları" is the correct written in Turkish)* Convert ISO-8859-1 to UTF-8: ``` String encodedWithISO88591 = "üzüm baÄları"; String decodedToUTF8 = new String(encodedWithISO88591.getBytes("ISO-8859-1"), "UTF-8"); //Result, decodedToUTF8 --> "üzüm bağları" ``` Convert UTF-8 to ISO-8859-1 ``` String encodedWithUTF8 = "üzüm bağları"; String decodedToISO88591 = new String(encodedWithUTF8.getBytes("UTF-8"), "ISO-8859-1"); //Result, decodedToISO88591 --> "üzüm baÄları" ```
How do I convert between ISO-8859-1 and UTF-8 in Java?
[ "", "java", "java-me", "utf-8", "character-encoding", "iso-8859-1", "" ]