Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
How can I convert a number between 1 and 7 into a DateTime object in C# which represents the day of the week? The numbers are coming from a XML file which I am parsing. I am retrieving each instance of a field containing a number between 1 and 7 which represents a day of the week between Sunday and Saturday.
I would assume casting to a DayOfWeek object would give you a day of the week ``` DayOfWeek day = (DayOfWeek)myInt; ``` As far as a DateTime object goes, the object represents a specific day, not necessarily a random day of the week. You may try adding a # of days to a specific date if this is what you're trying to achieve. [http://msdn.microsoft.com/en-us/library/system.dayofweek.aspx](http://msdn.microsoft.com/en-us/library/system.dayofweek.aspx "DayOfWeek MSDN")
In order to get a `DateTime`, you'd need a specific range of dates that you want the weekday to fall under (since a `DateTime` is a specific date and time, and a weekday isn't). There is a `DayOfWeek` enumeration (whose values actually range from 0-6). If all you need is something to represent the day of the week, then you should be able to cast your int to a `DayOfWeek` like.. ``` DayOfWeek myDay = (DayOfWeek)yourInt; ``` If you need an actual `DateTime`, you'll need a start date. You could then do... ``` DateTime myDate = startDate.AddDays( (int)startDate.DayOfWeek >= yourInt ? (int)startDate.DayOfWeek - yourInt : (int)startDate.DayOfWeek - yourInt + 7); ``` This will give you a DateTime for the next occuring instance of the day of the week you're describing.
DateTime Object Representing Day of Week
[ "", "c#", "datetime", "dayofweek", "" ]
I have a FindControl in OnLoad event to find my button on page i.e.: ``` protected override void OnLoad(EventArgs e) { DataBind(); control button = Page.FindControl("myButton"); } ``` on my aspx page I have ``` <asp:Button runat="server" ID="myButton" /> ``` If I only have this, everything works, when I pass in the OnLoad, button is not null and I can execute what I want. The problem is when I add dynamic text in my aspx: ``` <asp:Button runat="server" ID="myButton" Text='<%# "Here is my dynamic text pulled from a XML" %>' /> ``` Then the FindControl finds nothing and the button is null. Adding a binding server tag on aspx isn't suppose to delay anything right? When I inspect the Page object I have some controls in Controls collection, but I'm unable to find myButton. Any idea on what I am doing wrong? **EDIT** People seem to think that my code example is my real code but it **isn't**, So I use FindControl because I need to since I have nested controls and I cannot access it directly and I use binding because the dynamic text I'm putting is inside a ContentTemplate which I can override in other page aspx. The question I asked was more specific to the fact that I have traced the problem where my FindControl returns null because a newly implement behaviour which is the binding. Improving the code example isn't a solution or an explanation to the fact that if I put a <%# %> tag in my aspx page, the FindControl in the OnLoad event return null. **EDIT 2** the bind tag alone seems to not be the culprit but the DataBind() to populate them. Whether or not I have bind tag, putting DataBind() before the FindControl makes the myButton to be null. Correction in code example was made.
[In here](http://msdn.microsoft.com/en-us/library/ms178472.aspx#databindingevents) MSDN says that : > **PreRender :** Each data bound control whose > DataSourceID property is set calls its > DataBind method. It looks like you're not using DataSourceID of your data bound control, but moving your FindControl code to PreRender event might help.
The Page.FindControl() method will only search the imediate collection of controls that are associated with Page. It will not recurse down the entire control tree, so if your button is contained within another control it will not be found. You would need to call the FindControl method on the containing control.
FindControl doesn't work with bind server tag, why?
[ "", "c#", "asp.net", "" ]
I'm writing an application for android and would like to have an `itunes` like coverflow preview. Is there anything in the api that I can use or do I have to build it from scratch?
There is no built-in coverflow widget, the closest thing is probably the [Gallery](http://developer.android.com/reference/android/widget/Gallery.html) widget. Still I'd be surprised if someone hadn't tried something of the sort yet, and you might find some code floating around the internet. Google has some mentions of coverflow on Android, though I haven't checked it out in any detail.
I've created a basic coverflow widget it can be found here: <http://www.inter-fuser.com/2010/01/android-coverflow-widget.html>
Android coverflow
[ "", "java", "android", "mobile", "coverflow", "" ]
Why can't I use lambda expressions while debugging in “Quick watch” window? UPD: see also [Link](https://web.archive.org/web/20160206201209/http://blogs.msdn.com:80/b/jaredpar/archive/2009/08/26/why-no-linq-in-debugger-windows.aspx) [Link](https://learn.microsoft.com/en-us/archive/blogs/jaredpar/why-is-linq-absent-from-debugger-windows-part-2)
Lambda expressions, like anonymous methods, are actually very complex beasts. Even if we rule out `Expression` (.NET 3.5), that still leaves a *lot* of complexity, not least being captured variables, which fundamentally re-structure the code that uses them (what you think of as variables become fields on compiler-generated classes), with a bit of smoke and mirrors. As such, I'm not in the least surprised that you can't use them idly - there is a *lot* of compiler work (and type generation behind the scenes) that supports this magic.
No you cannot use lambda expressions in the watch / locals / immediate window. As Marc has pointed out this is incredibly complex. I wanted to dive a bit further into the topic though. What most people don't consider with executing an anonymous function in the debugger is that it does not occur in a vaccuum. The very act of defining and running an anonymous function changes the underlying structure of the code base. Changing the code, in general, and in particular from the immediate window, is a very difficult task. Consider the following code. ``` void Example() { var v1 = 42; var v2 = 56; Func<int> func1 = () => v1; System.Diagnostics.Debugger.Break(); var v3 = v1 + v2; } ``` This particular code creates a single closure to capture the value v1. Closure capture is required whenever an anonymous function uses a variable declared outside it's scope. For all intents and purposes v1 no longer exists in this function. The last line actually looks more like the following ``` var v3 = closure1.v1 + v2; ``` If the function Example is run in the debugger it will stop at the Break line. Now imagine if the user typed the following into the watch window ``` (Func<int>)(() => v2); ``` In order to properly execute this the debugger (or more appropriate the EE) would need to create a closure for variable v2. This is difficult but not impossible to do. What really makes this a tough job for the EE though is that last line. How should that line now be executed? For all intents and purposes the anonymous function deleted the v2 variable and replaced it with closure2.v2. So the last line of code really now needs to read ``` var v3 = closure1.v1 + closure2.v2; ``` Yet to actually get this effect in code requires the EE to change the last line of code which is actually an ENC action. While this specific example is possible, a good portion of the scenarios are not. What's even worse is executing that lambda expression shouldn't be creating a new closure. It should actually be appending data to the original closure. At this point you run straight on into the limitations ENC. My small example unfortunately only scratches the surface of the problems we run into. I keep saying I'll write a full blog post on this subject and hopefully I'll have time this weekend.
Visual Studio debugging "quick watch" tool and lambda expressions
[ "", "c#", "visual-studio", "debugging", "lambda", "" ]
I've written this jQuery code that fades in a overlay with some links over an image. What i found out is that it is painfully slow when I add like 10 of these images. I would really appreciate some tips and tricks on how to make this code faster. If you have some tips for my HTML and CSS that would be great too ;) jQuery code ``` $(document).ready(function() { var div = $(".thumb").find("div"); div.fadeTo(0, 0); div.css("display","block"); $(".thumb").hover( function () { $(this).children(".download").fadeTo("fast", 1); $(this).children(".hud").fadeTo("fast", 0.7); }, function () { div.fadeTo("fast", 0); } ); }); ``` All the code ``` <style type="text/css"> a:active { outline:none; } :focus { -moz-outline-style:none; } img { border: none; } #backgrounds { font: 82.5% "Lucida Grande", Lucida, Verdana, sans-serif; margin: 50px 0 0 0; padding: 0; width: 585px; } .thumb { margin: 5px; position: relative; float: left; } .thumb img { background: #fff; border: solid 1px #ccc; padding: 4px; } .thumb div { display: none; } .thumb .download { color: #fff; position: absolute; top: 0; left: 0; z-index: 999; padding: 0 10px; } .thumb .download h3 { font-size: 14px; margin-bottom: 10px; margin-top: 13px; text-align: center; } .thumb .download a { font-size: 11px; color: #fff; text-decoration: none; font-weight: bold; line-height: 16px; } .thumb .download a:hover { text-decoration: underline; } .thumb .download .left, .thumb .download .right { width: 44%; margin: 0; padding: 4px; } .thumb .download .left { float: left; text-align: right; } .thumb .download .right { float: right; text-align: left; } .thumb img, .thumb .hud { -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } .thumb .hud { width: 100%; height: 110px; position: absolute; top: 0; left: 0; background: #000; } </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var div = $(".thumb").find("div"); div.fadeTo(0, 0); div.css("display","block"); $(".thumb").hover( function () { $(this).children(".download").fadeTo("fast", 1); $(this).children(".hud").fadeTo("fast", 0.7); }, function () { div.fadeTo("fast", 0); } ); }); </script> <div id="backgrounds"> <div class="thumb"> <div class="download"> <h3>Download wallpaper</h3> <p class="left"> <a href="1024x768.jpg">1024x768</a> <a href="1280x800.jpg">1280x800</a> <a href="1280x1024.jpg">1280x1024</a> </p> <p class="right"> <a href="1440x900.jpg">1440x900</a> <a href="1680x1050.jpg">1680x1050</a> <a href="1920x1200.jpg">1920x1200</a> </p> </div> <div class="hud"></div> <img alt="image" src="thumb.jpg"/> </div> </div> ```
I got it to respond a little better by simply changing the following within the hover(..): ``` function () { $(".download", this).fadeTo("fast", 1); $(".hud", this).fadeTo("fast", 0.7); }, function () { $(".download, .hud", this).fadeTo("fast", 0); } ``` The biggest difference comes from only applying the hoverout effect to the event target, no need to reapply to all your divs on the page.
**Pre-Select MORE** Good job preselecting the div. Try this way so that it pre-selects the fade in elements as well instead of doing it on hover: ``` $().ready(function() { var div = $(".thumb").find("div"); div.fadeTo(0, 0); div.css("display","block"); $(".thumb").each(function() { var download = $(this).children(".download"); var hud = $(this).children(".hud"); $(this).hover( function () { download.fadeTo("fast", 1); hud.fadeTo("fast", 0.7); }, function () { div.fadeTo("fast", 0); } ); }); }); ```
Optimize jQuery code
[ "", "javascript", "jquery", "html", "css", "optimization", "" ]
I have an idea why but I'd like to ask if someone has a good grasp on why the exception raised inside a thread is never caught by the code that started it. Here's some very simple code to demonstrate what I mean: ``` using System; using System.Collections.Generic; using System.Threading; namespace TestCrash { class Program { private static void Crash(object control) { AutoResetEvent are = (AutoResetEvent)(((object[])control)[0]); are.Set(); throw new Exception("Burn baby burn"); } static void Main(string[] args) { try { List<WaitHandle> waitHandles = new List<WaitHandle>(); for (int i = 0; i < 100; i++) { AutoResetEvent are = new AutoResetEvent(false); waitHandles.Add(are); object[] procControl = new object[] { are }; ThreadPool.QueueUserWorkItem(Crash, procControl); WaitHandle.WaitAll(waitHandles.ToArray()); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } ``` I naively thought that by having the try/catch I would be safe, but I found out the hard way that it is not the case (it is crashing one of my services).
Well in general, you've no idea where the originating thread will be by the time the exception is thrown in the new thread - why would it be waiting around for the thread to throw an exception? Think of the stacks involved - when an exception is thrown, it goes up the stack until it reaches an appropriate catch block. The new thread has a completely separate stack to the creating thread, so it'll never reach the catch block in the creating thread's stack. EDIT: Of course, you could design your system so that the creating thread *did* wait for other things to happen - a bit like the message loop in a Windows Forms application. The new thread could then catch the exception and send a message to the creating thread, which could then deal with the exception. That isn't the normal setup though - you have to do it all explicitly.
The running thread will not be caught in your try/catch statement because it is running in another thread. Try/Catch only works for the current thread. What you need to do is have try/catch in the function being run by the thread, and have some way of managing what happens when that crash occurs.
Try/Catch and threading
[ "", "c#", "multithreading", "try-catch", "" ]
I'm interested in data mining projects, and have always wanted to create a classification algorithm that would determine which specific check-ins need code-reviews, and which may not. I've developed many heuristics for my algorithm, although I've yet to figure out the killer... How can I programmatically check the computational complexity of a chunk of code? Furthermore, and even more interesting - how could I use not just the code but the diff that the source control repository provides to obtain better data there.. IE: If I add complexity to the code I'm checking in - but it reduces complexity in the code that is left - shouldn't that be considered 'good' code? Interested in your thoughts on this. **UPDATE** Apparently I wasn't clear. I want this double codeValue = CodeChecker.CheckCode(someCodeFile); I want a number to come out based on how good the code was. I'll start with numbers like VS2008 gives when you calculate complexity, but would like to move to further heuristics. Anyone have any ideas? It would be much appreciated!
Have you taken a look at [NDepend](http://www.ndepend.com/Features.aspx)? This tool can be used to calculated code complexity and supports a query language by which you can get an incredible amount of data on your application.
The [NDepend](http://www.ndepend.com/) web site contains a [list of definitions](http://www.ndepend.com/Metrics.aspx) of various metrics. Deciding which are most important in your environment is largely up to you. NDepend also has a [command line version](http://www.ndepend.com/NDependConsole.aspx) that can be [integrated into your build process](http://s3.amazonaws.com/NDependOnlineDemos/NDependBuildProcessIntegration_viewlet_swf.html).
Programmatically checking code complexity, possibly via c#?
[ "", "c#", "asp.net", "performance", "artificial-intelligence", "complexity-theory", "" ]
I would like to implement a heartbeat functionality in the server that would periodically alert **window clients** of its liveness. There are few ideas I am considering but would appreciate suggestions and examples/references * have a separate thread that would send a heartbeat to connected clients * have different types of heartbeat to indicating different states of the server (slow, fast, overwhelmed with clients, up and ready) * perhaps let clients subscribe to different levels, have up heartbeat sent by default I would really like to see how it is done in practice, examples are best. **EDIT 1** clients and server are not web-based! (server might migrate to the web, but I dont think it should change the protocol much)
What kind of client are we talking about? Windows client or asp.net? There are two very general patterns for this. You can either push or pull the data. Pushing doesn't work if your on the internet you'll run into firewalls and nats. So you end up with a third variation where the client initates the connection, and the server leaves the connection open to send information back and forth. You need to provide a lot more information, are we talking about internet or intranet? What .net framework are you targeting? How many clients are you talking? A solution that can handle a dozen clients (Especially in a push model or the third model) could look very different from a solution which can scale to thousands of clients. The easiest solution is to do polling from the client side, which unless you want the server to have instant communication to the client is the way to go. And a heart beat is not instant communication. # Edit Ok you indicated sockets, are you really sure you want to do lower level network type programing? Why not build upon existing network strategies such as HTTP. You can do a simple remoting service over HTTP which will let you bypass firewalls. Or even better if your server is a web server then just setup a plain old xml service. I don't have any examples I can share of this, but there should be plenty around.
Using the pull model mentioned by Josh is the simplest approach. First of all, you'll get past a lot of security issues with that. No need to worry about client-side firewalls. Plus, you don't need to worry about having to open the same port on each client, or opening dynamic ports and notifying the server about what port on what client is being used. In addition, you won't have to maintain a subscriber list on the server. Plus, you will not need to worry about cleaning up the subscriber list if a client disconnects in a not so clean manner (application crash, power failure, etc). Basically, a simple polling from the client to a service on the server is the simplest and cleanest approach, IMHO. I've used it several times. You can even have the polling interval be user-configurable if you choose. Edit: While I cannot provide a reference or example code, I'll describe what I've done in the past. Basically, I had a web service that, when queried, would return the state of the system. This web service obviously ran on the server. The clients, when started, would launch a separate thread that would query the web service every 30 seconds to get the state of the server system. Then, the UI would be updated to indicate that state. Once that task was complete the thread would go back to sleep for 30 seconds. The update time was configurable through a configuration file. Just make sure to trap errors so that if the request to the service fails for a reason other than the server being down, the entire application doesn't crash.
Pattern to implement heartbeat between server and the client
[ "", "c#", ".net", "design-patterns", "" ]
Windows Explorer in Windows 7, and maybe Vista too (can't rememmber), does not have a title in the window. but does have a title (some text) in the taskbar. Is this possible to reproduce in C# (wpf or winforms)? either through the framework or introp. I want to have a window that says "Options" in the taskbar but the window itself doesn't have a title.
look at <http://blogs.msdn.com/wpfsdk/archive/2008/09/08/custom-window-chrome-in-wpf.aspx> for the section titled "Vista Explorer – Removing redundant information from the title bar"
MSDN has a nice article called [Custom Window Frame Using DWM](http://msdn.microsoft.com/en-us/library/bb688195(loband).aspx) which discusses the things you can do with the window frame using the DWM of Vista and Windows 7. In particular, the *Removing the Standard Frame* section should be relevant for your case.
How to have no/one window title and have a different title for the task bar?
[ "", "c#", "wpf", "windows", "winforms", "" ]
I'm trying to finish this exception handler: ``` if (ConfigurationManager.ConnectionStrings["ConnectionString"]==null) { string pathOfActiveConfigFile = ...? throw new ConfigurationErrorsException( "You either forgot to set the connection string, or " + "you're using a unit test framework that looks for "+ "the config file in strange places, update this file : " + pathOfActiveConfigFile); } ``` This problem seems to only happen to me when I'm using nUnit.
For .Net Framework, try this ``` AppDomain.CurrentDomain.SetupInformation.ConfigurationFile ``` For .Net core or anything newer, see the other answers.
Strictly speaking, there is no single configuration file. Excluding ASP.NET1 there can be three configuration files using the inbuilt (`System.Configuration`) support. In addition to the machine config: `app.exe.config`, user roaming, and user local. To get the "global" configuration (*exe*.config): ``` ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) .FilePath ``` Use different [`ConfigurationUserLevel`](http://msdn.microsoft.com/library/System.Configuration.ConfigurationUserLevel) values for per-use roaming and non-roaming configuration files. --- 1 Which has a completely different model where the content of a child folders (IIS-virtual or file system) `web.config` can (depending on the setting) add to or override the parent's `web.config`.
How to find path of active app.config file?
[ "", "c#", ".net", "nunit", "app-config", "configurationmanager", "" ]
I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds. Is there an easy way to convert the seconds to this format in Python?
You can use [`datetime.timedelta`](https://docs.python.org/library/datetime.html#datetime.timedelta) function: ``` >>> import datetime >>> str(datetime.timedelta(seconds=666)) '0:11:06' ```
By using the [`divmod()`](http://docs.python.org/library/functions.html#divmod) function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations: ``` m, s = divmod(seconds, 60) h, m = divmod(m, 60) ``` And then use [string formatting](https://stackoverflow.com/a/134951/4936137) to convert the result into your desired output: ``` print('{:d}:{:02d}:{:02d}'.format(h, m, s)) # Python 3 print(f'{h:d}:{m:02d}:{s:02d}') # Python 3.6+ ```
How do I convert seconds to hours, minutes and seconds?
[ "", "python", "datetime", "" ]
I have the following inner class: ``` @Entity @Table(name = "SATTET0") public class SATTET0Key { @Column(name="IESTATUT") public String estatut; @Column(name="IINICIO") public Date dataInicio; } ``` In the same class i have the following code: ``` Query q = exp.createNativeQuery("SELECT IESTATUT, IINICIO FROM " + "\n SATTET0 WHERE IESTATUT=? AND DATAFIM IS NULL ", SATTET0Key.class); q.setParameter(1, estatuto); try { key = (SATTET0Key) q.getSingleResult(); return key; } catch (NoResultException e) { return null; } ``` When i run this code i get the following: ``` javax.ejb.EJBException: EJB Exception: ; nested exception is: <openjpa-1.1.0-r422266:657916 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: Índice de colunas inválido at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.unwrapRemoteException(RemoteBusinessIntfProxy.java:105) at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.invoke(RemoteBusinessIntfProxy.java:87) at $Proxy0.lookupSATTET0Key(Unknown Source) at com.siemens.eori.service.testEstatutoServiceBean.testLookups(testEstatutoServiceBean.java:58) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196) Caused by: <openjpa-1.1.0-r422266:657916 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: Índice de colunas inválido at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:813) at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:774) at kodo.kernel.KodoQuery.execute(KodoQuery.java:43) at org.apache.openjpa.kernel.DelegatingQuery.execute(DelegatingQuery.java:533) at org.apache.openjpa.persistence.QueryImpl.execute(QueryImpl.java:235) at org.apache.openjpa.persistence.QueryImpl.getSingleResult(QueryImpl.java:300) at com.siemens.eori.service.ejb3.session.EstatutoServiceBean.lookupSATTET0Key(EstatutoServiceBean.java:159) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.bea.core.repackaged.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:281) at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:187) at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:154) at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:126) at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:114) at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:176) at com.bea.core.repackaged.springframework.jee.spi.MethodInvocationVisitorImpl.visit(MethodInvocationVisitorImpl.java:15) at weblogic.ejb.container.injection.EnvironmentInterceptorCallbackImpl.callback(EnvironmentInterceptorCallbackImpl.java:54) at com.bea.core.repackaged.springframework.jee.spi.EnvironmentInterceptor.invoke(EnvironmentInterceptor.java:30) at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:176) at com.bea.core.repackaged.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:176) at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:126) at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:114) at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:176) at com.bea.core.repackaged.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:210) at $Proxy335.lookupSATTET0Key(Unknown Source) at com.siemens.eori.service.ejb3.session.EstatutoServiceBean_jfjn40_EstatutoServiceImpl.lookupSATTET0Key(EstatutoServiceBean_jfjn40_EstatutoServiceImpl.java:297) at com.siemens.eori.service.ejb3.session.EstatutoServiceBean_jfjn40_EstatutoServiceImpl_WLSkel.invoke(Unknown Source) at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:589) at weblogic.rmi.cluster.ClusterableServerRef.invoke(ClusterableServerRef.java:230) at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:477) at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363) at weblogic.security.service.SecurityManager.runAs(Unknown Source) at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:473) at weblogic.rmi.internal.wls.WLSExecuteRequest.run(WLSExecuteRequest.java:118) at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201) at weblogic.work.ExecuteThread.run(ExecuteThread.java:173) Caused by: java.lang.Exception: java.sql.SQLException: Índice de colunas inválido at org.apache.openjpa.util.Exceptions.replaceNestedThrowables(Exceptions.java:249) at org.apache.openjpa.persistence.ArgumentException.writeObject(ArgumentException.java:107) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at weblogic.utils.io.ObjectStreamClass.writeObject(ObjectStreamClass.java:282) at weblogic.corba.utils.ValueHandlerImpl.writeValueData(ValueHandlerImpl.java:231) at weblogic.corba.utils.ValueHandlerImpl.writeValue(ValueHandlerImpl.java:182) at weblogic.iiop.IIOPOutputStream.write_value(IIOPOutputStream.java:1963) at weblogic.iiop.IIOPOutputStream.write_value(IIOPOutputStream.java:2001) at weblogic.iiop.IIOPOutputStream.writeObject(IIOPOutputStream.java:2266) at weblogic.utils.io.ObjectStreamClass.writeFields(ObjectStreamClass.java:413) at weblogic.corba.utils.ValueHandlerImpl.writeValueData(ValueHandlerImpl.java:235) at weblogic.corba.utils.ValueHandlerImpl.writeValue(ValueHandlerImpl.java:182) at weblogic.iiop.IIOPOutputStream.write_value(IIOPOutputStream.java:1963) at weblogic.iiop.UnknownExceptionInfo.writeEncapsulation(UnknownExceptionInfo.java:40) at weblogic.iiop.ServiceContext.writeEncapsulatedContext(ServiceContext.java:130) at weblogic.iiop.UnknownExceptionInfo.write(UnknownExceptionInfo.java:35) at weblogic.iiop.ServiceContextList.write(ServiceContextList.java:41) at weblogic.iiop.Message.writeServiceContexts(Message.java:230) at weblogic.iiop.ReplyMessage.write(ReplyMessage.java:425) at weblogic.iiop.Message.flush(Message.java:193) at weblogic.iiop.OutboundResponseImpl.writeUncheckedException(OutboundResponseImpl.java:337) at weblogic.iiop.OutboundResponseImpl.sendThrowable(OutboundResponseImpl.java:180) at weblogic.rmi.internal.BasicServerRef.handleThrowable(BasicServerRef.java:694) at weblogic.rmi.internal.BasicServerRef.postInvoke(BasicServerRef.java:650) at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:492) ... 3 more ``` Where you see "Índice de colunas inválido" its the Portuguese translation of "Invalid Collumn Index" What am i missing here?
You should write your native query like this (use :1 instead of ?) WHERE IESTATUT=:1 ``` Query q = exp.createNativeQuery ( "SELECT IESTATUT, IINICIO FROM \n SATTET0 WHERE IESTATUT=:1 AND DATAFIM IS NULL", SATTET0Key.class ); q.setParameter(1, estatuto); ``` it works well.
There may be a problem with the parameter's index (1). May be it should start with 0. In any case I prefer the use of named parameters in queries (:param instead of ?).
EJB3 Native Query Problem
[ "", "java", "ejb-3.0", "" ]
**Update 2009.04.24** The main point of my question is not developer confusion and what to do about it. The point is to understand when delimited values are the right solution. I've seen delimited data used in commercial product databases (Ektron lol). SQL Server even has an XML datatype, so that could be used for the same purpose as delimited fields. **/end Update** The application I'm designing has some many-to-many relationships. In the past, I've often used associative tables to represent these in the database. This has caused some confusion to the developers. Here's an example DB structure: ``` Document --------------- ID (PK) Title CategoryIDs (varchar(4000)) Category ------------ ID (PK) Title ``` **There is a many-to-many relationship between Document and Category.** In this implementation, Document.CategoryIDs is a big pipe-delimited list of CategoryIDs. To me, this is bad because it requires use of substring matching in queries -- which cannot make use of indexes. I think this will be slow and will not scale. With that model, to get all Documents for a Category, you would need something like the following: ``` select * from documents where categoryids like '%|' + @targetCategoryId + '|%' ``` My solution is to create an associative table as follows: ``` Document_Category ------------------------------- DocumentID (PK) CategoryID (PK) ``` This is confusing to the developers. Is there some elegant alternate solution that I'm missing? I'm assuming there will be thousands of rows in Document. Category may be like 40 rows or so. The primary concern is query performance. Am I over-engineering this? Is there a case where it's preferred to store lists of IDs in database columns rather than pushing the data out to an associative table? Consider also that we may need to create many-to-many relationships among documents. This would suggest an associative table Document\_Document. Is that the preferred design or is it better to store the associated Document IDs in a single column? Thanks.
The Document\_Category table in your design is certainly the correct way to approach the problem. If it's possible, I would suggest that you educate the developers instead of coming up with a suboptimal solution (and taking a performance hit, and not having referential integrity). Your other options may depend on the database you're using. For example, in SQL Server you can have an XML column that would allow you to store your array in a pre-defined schema and then do joins based on the contents of that field. Other database systems may have something similar.
> This is confusing to the developers. Get better developers. That is the right approach.
Many-to-many relationship: use associative table or delimited values in a column?
[ "", "sql", "database", "database-design", "architecture", "many-to-many", "" ]
Basically I want to be able to wrap any command in a $.holdTillFinished() method that will not allow execution to continue until the specified method/jquery animation is finished executing. I suspect that this may be difficult or even impossible in javascript, but I'm hoping someone will know. I don't want to hear about how I can pass a callback into an animation to have it run oncomplete, or anything else like that. I really want to know if such a thing is possible and how to go about it. If that isn't going to happen if anyone knows of a nice queue plugin that is capable of queuing both user defined methods and animations, that would be cool too. What I really want is a way to delay execution though.(while still allowing animations to function)
> I suspect that this may be difficult or even impossible in javascript Your suspicion is correct. Methods like animations, user input loops and ‘async=true’ XMLHttpRequests *must* return control to the browser in order to proceed, and the browser can't get back control until every nesting level of function call has returned. That means all your code, including the function that called ‘holdTillFinished()’ would have to unwind: therefore ‘holdTillFinished()’ is impossible. Other languages have flow-control features that allow you to effectively execute an asynchronous process as one that appears to the caller to be synchronous, and similarly vice-versa. The best-known are [threads](http://en.wikipedia.org/wiki/Thread_(computer_science)) and [continuations](http://en.wikipedia.org/wiki/Continuation). JavaScript does not possess these facilities, so the best you can do is timeouts and callbacks. (Defining a callback as an inline function to gain access to the enclosing function's variables in a closure does at least take some of the pain out of it; some other languages have to start wrapping every bit of enclosing state in an object's properties to achieve this.)
You're probably looking for <http://docs.jquery.com/Effects/queue> But if you're looking for a more generalized way of delaying things, I've used this snippet before (I didn't write it, so all credit goes to the original author): ``` //Simple wrapper enabling setTimout within chained functions. $.fn.wait = function(time, type) { time = time || 1000; type = type || "fx"; return this.queue(type, function() { var self = this; setTimeout(function() { $(self).dequeue(); }, time); }); }; ```
Is it possible to stop execution in javascript/jquery?
[ "", "javascript", "jquery", "jquery-animate", "" ]
I hacked a following code: ``` unsigned long long get_cc_time () volatile { uint64 ret; __asm__ __volatile__("rdtsc" : "=A" (ret) : :); return ret; } ``` It works on g++ but not on Visual Studio. How can I port it ? What are the right macros to detect VS / g++ ?
``` #if defined(_MSC_VER) // visual c #elif defined(__GCCE__) // gcce #else // unknown #endif ``` My inline assembler skills are rusty, but it works like: ``` __asm { // some assembler code } ``` But to just use **rdtsc** you can just use intrinsics: ``` unsigned __int64 counter; counter = __rdtsc(); ``` <http://msdn.microsoft.com/en-us/library/twchhe95.aspx>
The specific problem OP had aside: I found a way to define a macro that works for both syntax versions: ``` #ifdef _MSC_VER # define ASM(asm_literal) \ __asm { \ asm_literal \ }; #elif __GNUC__ || __clang__ # define ASM(asm_literal) \ "__asm__(\"" \ #asm_literal \ "\" : : );" #endif ``` Unfortunately, because the preprocessor [strips newlines before macro expansion](https://stackoverflow.com/a/1510919/894166), you have to surround each assembly statement with this macro. ``` float abs(float x) { ASM( fld dword ptr[x] ); ASM( fabs ); ASM( fstp dword ptr[x] ); return x; } ``` But please be aware that GCC and clang [use AT&T/UNIX assembly synax](http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html#s3) but MSVC usees Intel assembly syntax (couldn't find any official source though). But fortunately GCC/clang can be [configured to use Intel syntax](http://wiki.osdev.org/Inline_Assembly#Intel_Syntax), too. Either use `__asm__(".intel_syntax noprefix");`/ `__asm__(".att_syntax prefix");` (be sure to reset the changes as it will affect *all* assembly generated from that point on, even the one generated by the compiler from the C source). This would leave us with a macro like this: ``` #ifdef _MSC_VER # define ASM(asm_literal) \ __asm { \ asm_literal \ }; #elif __GNUC__ || __clang__ # define ASM(asm_literal) \ "__asm__(\".intel_syntax noprefix\");" \ "__asm__(\"" \ #asm_literal \ "\" : : );" \ "__asm__(\".att_syntax prefix\");" #endif ``` Or you can also compile with GCC/clang using the `-masm=intel` flag, which switches the syntax globally.
How to make a cross-platform c++ inline assembly language?
[ "", "c++", "cross-platform", "assembly", "" ]
Currently, my level of understanding is below all the coding examples on the web about the Observer Pattern. I understand it simply as being almost a subscription that updates all other events when a change is made that the delegate registers. However, I'm very unstable in my true comprehension of the benefits and uses. I've done some googling, but most are above my level of understanding. I'm trying to implement this pattern with my current homework assignment, and to truly make sense on my project need a better understanding of the pattern itself and perhaps an example to see what its use. I don't want to force this pattern into something just to submit, I need to understand the purpose and develop my methods accordingly so that it actually serves a good purpose. My text doesn't really go into it, just mentions it in one sentence. MSDN was hard for me to understand, as I'm a beginner on this, and it seems more of an advanced topic. How would you describe this Observer pattern and its uses in C# to a *beginner?* For an example, please keep code very simple so I can understand the purpose more than complex code snippets. I'm trying to use it effectively with some simple textbox string manipulations and using delegates for my assignment, so a pointer would help!
The best example I can come up with is that of a mailing list (as an example). You, the observer, subscribe to a mailing list and you observe the list. When you are no longer interested in the list, you unsubscribe. This concept is the observer pattern. Two or more classes are involved. One or more class, subscribes to a publisher class (there are different names) and then the first class (and every subscribing class) will get notified when ever the publisher desires. This is how I explained it to my wife, who often listens to my rantings about programming and design theory. It made sense to her. I realize this might be too simple for you but is a good start... Regards, Frank
Check out ["Head First: Design Patterns"](https://rads.stackoverflow.com/amzn/click/com/0596007124) for some really, smack-your-forehead easy to follow descriptions of the major patterns. For Observer it is important to understand that it describes a one-to-many relationship and uses a subscription model for telling other classes when there has been a change. RSS, Atom, and Twitter work along these lines.
How you would you describe the Observer pattern in beginner language?
[ "", "c#", "design-patterns", "observer-pattern", "" ]
My question is simple (although the answer will most likely not be): I'm trying to decide how to implement a server side upload handler in C# / ASP.NET. I've used both HttpModules (IHttpModule interface) and HttpHandlers (IHttpHandler interface) and it occurs to me that I could implement this using either mechanism. It also occurs to me that I don't understand the differences between the two. So my question is this: **In what cases would I choose to use IHttpHandler instead of IHttpModule (and vice/versa)?** *Is one executed much higher in the pipeline? Is one much easier to configure in certain situations? Does one not work well with medium security?*
An ASP.NET **HTTP handler** is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser. Typical uses for custom HTTP handlers include the following: * RSS feeds To create an RSS feed for a Web site, you can create a handler that emits RSS-formatted XML. You can then bind a file name extension such as .rss to the custom handler. When users send a request to your site that ends in .rss, ASP.NET calls your handler to process the request. * Image server If you want a Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them to the user as the handler's response. An **HTTP module** is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request. Typical uses for HTTP modules include the following: * Security Because you can examine incoming requests, an HTTP module can perform custom authentication or other security checks before the requested page, XML Web service, or handler is called. In Internet Information Services (IIS) 7.0 running in Integrated mode, you can extend forms authentication to all content types in an application. * Statistics and logging Because HTTP modules are called on every request, you can gather request statistics and log information in a centralized module, instead of in individual pages. * Custom headers or footers Because you can modify the outgoing response, you can insert content such as custom header information into every page or XML Web service response. From: <http://msdn.microsoft.com/en-us/library/bb398986.aspx>
As stated [here](http://www.worldofasp.net/tut/HttpHandlers/Using_HttpHandlers_and_HttpModules_in_your_ASPNET_Websites_90.aspx), HttpModules are simple classes that can plug themselves into the request processing pipeline, whereas HttpHandlers differ from HttpModules not only because of their positions in the request processing pipeline, but also because they must be mapped to a specific file extensions.
IHttpHandler vs IHttpModule
[ "", "c#", "asp.net", "iis", "httphandler", "httpmodule", "" ]
I would like to be able to pull some code samples out of a database and/or have the text embedded into the website and then have the sample formatted in a code like fashion on the screen. While the text alone on the screen is great, the format will make it more user friendly. How is this done? **I want this:**  public string MyString = "The Sample Text"; --- **To look like:** ``` public string MyString = "The Sample Text"; ``` --- **EDIT WITH ANSWER** I took [Gortok's](https://stackoverflow.com/questions/749209/display-code-samples-on-web-like-stackoverflow/749229#749229) suggestion and looked into [Prettify.js](http://code.google.com/p/google-code-prettify/) and its doing just what I had hoped. Here is how this is implemented. ``` <head runat="server"> <script src="Scripts/prettify.js" type="text/javascript"></script> <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script> <link href="Scripts/prettify.css" rel="stylesheet" type="text/css"></link> </head> <body> <code class="prettyprint"> public String HelloString = "New String"; </code> <script language="javascript"> $().ready(function() { prettyPrint(); }); </script> </body> ```
Stack Overflow uses [prettify.js](http://code.google.com/p/google-code-prettify/) from Google.
I use SyntaxHighlighter by Alex Gorbatchev <http://alexgorbatchev.com/wiki/SyntaxHighlighter> It's used on Yahoo Developer Network <http://developer.yahoo.com/yui/animation/>
How do I Display Code Samples On Web Pages With Nice Syntax Styling Like Stack Overflow Does?
[ "", "asp.net", "javascript", "html", "css", "" ]
I am trying to get version information from a file. My code works perfectly for me, but fails on several others' machines. Because I can't reproduce the bug, I'm having quite a time finding the issue. Does anyone see anything majorly wrong with this? ``` LPBYTE versionInformationBlock; struct LANGANDCODEPAGE { WORD wLanguage; WORD wCodePage; } *langBlockPointer; UINT translationsCount; void fileData::enumVersionInformationBlock() { bits.set(VERSIONINFOCHECKED); disable64.disableFS(); //Shut down WOW64 DWORD zero = 0; DWORD lengthOfVersionData = GetFileVersionInfoSize(getFileName().c_str(),&zero); if (!lengthOfVersionData) { disable64.enableFS(); return; } versionInformationBlock = new BYTE[lengthOfVersionData]; GetFileVersionInfo(getFileName().c_str(),zero,lengthOfVersionData,versionInformationBlock); VerQueryValue(versionInformationBlock,L"\\VarFileInfo\\Translation",(LPVOID*)&langBlockPointer,&translationsCount); translationsCount /= sizeof(struct LANGANDCODEPAGE); disable64.enableFS(); } std::wstring fileData::getVersionInformationString(const std::wstring& str) { if (!bits[VERSIONINFOCHECKED]) enumVersionInformationBlock(); if (!versionInformationBlock) return L"!VERINFO: NOT PE FILE!"; LPCTSTR retString; UINT retStringLength; std::wstring result; static const wchar_t hexChars[] = L"0123456789ABCDEF"; wchar_t hexLanguage[26] = L"\\StringFileInfo\\ \\"; for( size_t idx = 0; idx < translationsCount; idx++ ) { hexLanguage[16] = *(hexChars + ((langBlockPointer[idx].wLanguage >> 12) & 0x0F)); hexLanguage[17] = *(hexChars + ((langBlockPointer[idx].wLanguage >> 8 ) & 0x0F)); hexLanguage[18] = *(hexChars + ((langBlockPointer[idx].wLanguage >> 4 ) & 0x0F)); hexLanguage[19] = *(hexChars + ( langBlockPointer[idx].wLanguage & 0x0F)); hexLanguage[20] = *(hexChars + ((langBlockPointer[idx].wCodePage >> 12) & 0x0F)); hexLanguage[21] = *(hexChars + ((langBlockPointer[idx].wCodePage >> 8 ) & 0x0F)); hexLanguage[22] = *(hexChars + ((langBlockPointer[idx].wCodePage >> 4 ) & 0x0F)); hexLanguage[23] = *(hexChars + ( langBlockPointer[idx].wCodePage & 0x0F)); std::wstring targetResource(hexLanguage,25); targetResource.append(str); if (!VerQueryValue(versionInformationBlock,targetResource.c_str(),(LPVOID *)&retString,&retStringLength)) { return std::wstring(L"!DOESN'T APPER TO EXIST IN FILE! ERROR: ").append(boost::lexical_cast<std::wstring>(GetLastError())); } retStringLength--; if (!result.empty()) result.append(L" / "); std::wstring toAppend; toAppend.assign(retString,retStringLength); boost::algorithm::trim(toAppend); result.append(toAppend); } return result; } std::wstring fileData::getVerCompany() { return getVersionInformationString(L"CompanyName"); } ~fileData() { if (versionInformationBlock) delete [] versionInformationBlock; }; ``` What's really bugging me is that it isn't throwing any of my error messages... it keeps returning garbage. Any ideas? Billy3
nvm. Seems Stackoverflow beats the heck out of me if it isn't answered..... Billy3
Try the following: * Retrieve the reason for `GetFileVersion`'s failure by using `GetLastError` * Tell us what OS it works on and what OS it doesn't * Check if `GetFileVersionInfo` succeeds or not (again `GetLastError`) * Read the **Remarks** section of the MSDN documentation of the abovementioned functions repeatedly and check if you are not missing something.
Getting File Version Information fails -- But not for me
[ "", "c++", "winapi", "version", "" ]
Consider this program: ``` #include <iostream> #include <string> #include <sstream> #include <cassert> int main() { std::istringstream stream( "-1" ); unsigned short n = 0; stream >> n; assert( stream.fail() && n == 0 ); std::cout << "can't convert -1 to unsigned short" << std::endl; return 0; } ``` I tried this on gcc (version 4.0.1 Apple Inc. build 5490) on OS X 10.5.6 and the assertion is true; it fails to convert -1 to an unsigned short. In Visual Studio 2005 (and 2008) however, the assertion fails and the resulting value of n is the same as what you would expect from an compiler generated implicit conversion - i.e "-1" is 65535, "-2" is 65534, etc. But then it gets weird at "-32769" which converts to 32767. Who's right and who's wrong here? (And what the hell's going on with -32769??)
The behaviour claimed by GCC in Max Lybbert's post is based on the tables om the C++ Standard that map iostream behaviour onto printf/scanf converters (or at least that;'s my reading). However, the scanf behaviour of g++ seems to be different from the istream behavior: ``` #include <iostream> #include <cstdio> using namespace std;; int main() { unsigned short n = 0; if ( ! sscanf( "-1", "%hu", &n ) ) { cout << "conversion failed\n"; } else { cout << n << endl; } } ``` actually prints 65535.
First, reading the string "-1" as a negative number is locale dependent (it would be possible for a locale to identify negative numbers by enclosing them in parenthesis). [Your default standard is the "classic" C locale](http://www.research.att.com/~bs/3rd_loc.pdf): > By far the dominant use of *locales* is implicitly, in stream I/O. Each *istream* and *ostream* has its own *locale*. The *locale* of a stream is by default the global *locale* at the time of the stream’s creation (page 6). ... > > Initially, the global locale is the standard C locale, *locale::classic()* (page 11). According to the GCC guys, [numeric overflow is allowed to fail the stream input operation](http://gcc.gnu.org/ml/gcc-prs/2002-01/msg00693.html) (talking about negative numbers that overflowed a signed int): > [T]he behaviour of libstdc++-v3 is strictly standard conforming. ... When the read is attempted it does *not* fit in a signed int i, and it fails. Thanks to another answer, [a bug was filed and this behavior changed](http://gcc.gnu.org/bugzilla/show_bug.cgi?id=39802): > Oops, apparently we never parsed correctly negative values for unsigned. The > fix is simple. ... > > Fixed in mainline, will be fixed in 4.4.1 too. Second, although integer overflow is generally predictable, I believe it's [officially undefined behavior](http://dobbscodetalk.com/index.php?option=com_myblog&show=A-parable-about-undefined-behavior.html&Itemid=29), so while I can't say why -32769" converts to 32767, I think it's allowed.
stringstream unsigned conversion broken?
[ "", "c++", "iostream", "stringstream", "" ]
I am trying out jqueryUI, but firebug catches the following error on this script: ``` $(function(){$("#date").datepicker()}); ``` The firebug error reads: ``` $("#date").datepicker is not a function ``` On my html, the "date" id looks like this: ``` <input type="text" name="date" id="date" > ``` NB: I have used the correct JqueryUI css/js scripts on the section Nothing is executing...
[jQuery documentation](http://docs.jquery.com/UI/Datepicker) says you can call the datepicker by this command: ``` $("#datepicker").datepicker(); ``` If you click the 'view source' button on the documentation page you can see that they've wrapped it into the *ready* function: ``` $(document).ready(function(){ $("#datepicker").datepicker(); }); ``` **EDIT:** It should work with INPUT (thanks for pointing this out Steerpike). This is the test I've written and it works, try it yourself: ``` <html> <head> <link type="text/css" href="http://jqueryui.com/latest/themes/base/ui.all.css" rel="stylesheet" /> <script type="text/javascript" src="http://jqueryui.com/latest/jquery-1.3.2.js"></script> <script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.core.js"></script> <script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.datepicker.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#datepicker").datepicker(); }); </script> </head> <body> <input type="text" id="datepicker" value="this is a test"> </body> </html> ```
You're almost certainly not loading the datepicker plugin properly. Please supply us the code you're using to include the javascript files. If you keep having problems, load the jquery and the UI from the google api. ``` <link type="text/css" href="http://jqueryui.com/latest/themes/base/ui.all.css" rel="stylesheet" /> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("jquery", "1.3.2"); google.load("jqueryui", "1.7.0"); </script> ```
Why is jqueryUI datepicker throwing an error?
[ "", "javascript", "jquery", "jquery-ui", "jquery-ui-datepicker", "" ]
I am making a rails app and having a ridiculously hard time trying to get the Redbox plugin to work. I'm pretty sure I installed everything correctly and am using it properly. When I use one of the helper methods, it seems to generate javascript properly. For example when I type: ``` <%= link_to_redbox 'hello', 'test' %> ``` it generates: ``` <a href="#" onclick="RedBox.showInline('test'); return false;">hello</a> ``` which seems correct if i want to show a non visible ( `display:none;` ) div called test. I'm so confused on this one. I'm pretty sure it is not finding the js or something but don't see why this would be. The redbox.js link is generated as: ``` <script src="/javascripts/redbox.js?1239506092" type="text/javascript"></script> ```
the css has to be inline!
Check that the javascript file actually exists - it should be at public/javascripts/redbox.js (at least, that appears to be where it expects it to be).
how to install and use a javascript based plugin on rails?
[ "", "javascript", "ruby-on-rails", "ruby", "ruby-on-rails-plugins", "" ]
I have an entity loaded by Hibernate (via `EntityManager`): ``` User u = em.load(User.class, id) ``` This class is audited by Hibernate Envers. How can I load the previous version of a User entity?
maybe this then (from [AuditReader](http://www.jboss.org/files/envers/api-beta/org/hibernate/envers/AuditReader.html) docs) ``` AuditReader reader = AuditReaderFactory.get(entityManager); User user_rev1 = reader.find(User.class, user.getId(), 1); List<Number> revNumbers = reader.getRevisions(User.class, user_rev1); User user_previous = reader.find(User.class, user_rev1.getId(), revNumbers.get(revNumbers.size()-1)); ``` (I'm very new to this, not sure if I have all the syntax right, maybe the size()-1 should be size()-2?)
Here's another version that finds the previous revision relative to a "current" revision number, so it can be used even if the entity you're looking at isn't the latest revision. It also handles the case where there *isn't* a prior revision. (`em` is assumed to be a previously-populated EntityManager) ``` public static User getPreviousVersion(User user, int current_rev) { AuditReader reader = AuditReaderFactory.get(em); Number prior_revision = (Number) reader.createQuery() .forRevisionsOfEntity(User.class, false, true) .addProjection(AuditEntity.revisionNumber().max()) .add(AuditEntity.id().eq(user.getId())) .add(AuditEntity.revisionNumber().lt(current_rev)) .getSingleResult(); if (prior_revision != null) return (User) reader.find(User.class, user.getId(), prior_revision); else return null } ``` This can be generalized to: ``` public static T getPreviousVersion(T entity, int current_rev) { AuditReader reader = AuditReaderFactory.get(JPA.em()); Number prior_revision = (Number) reader.createQuery() .forRevisionsOfEntity(entity.getClass(), false, true) .addProjection(AuditEntity.revisionNumber().max()) .add(AuditEntity.id().eq(((Model) entity).id)) .add(AuditEntity.revisionNumber().lt(current_rev)) .getSingleResult(); if (prior_revision != null) return (T) reader.find(entity.getClass(), ((Model) entity).id, prior_revision); else return null } ``` The only tricky bit with this generalization is getting the entity's id. Because I'm using the Play! framework, I can exploit the fact that all entities are Models and use `((Model) entity).id` to get the id, but you'll have to adjust this to suit your environment.
Get previous version of entity in Hibernate Envers
[ "", "java", "hibernate", "jboss", "hibernate-envers", "" ]
my problem is that the assignment of decodedProxyExcerpt2 below overwrites decodedProxyExcerpt1 and I do not know why. Any clues? Thanks in advance. ``` DecodedProxyExcerpt decodedProxyExcerpt1 = new DecodedProxyExcerpt(stepSize); if (audiofactory.MoveNext(stepSize)) { decodedProxyExcerpt1 = audiofactory.Current(stepSize); } // At this point decodedProxyExcerpt1.data contains the correct values. DecodedProxyExcerpt decodedProxyExcerpt2 = new DecodedProxyExcerpt(stepSize); if (audiofactory.MoveNext(stepSize)) { decodedProxyExcerpt2 = audiofactory.Current(stepSize); } // At this point decodedProxyExcerpt2.data contains the correct values. // However, decodedProxyExcerpt1.data is overwritten and now holds the values of decodedProxyExcerpt2.data. public class DecodedProxyExcerpt { public short[] data { get; set; } // PCM data public DecodedProxyExcerpt(int size) { this.data = new short[size]; } } ``` From AudioFactory: ``` public bool MoveNext(int stepSize) { if (index == -1) { index = 0; return (true); } else { index = index + stepSize; if (index >= buffer.Length - stepSize) return (false); else return (true); } } public DecodedProxyExcerpt Current(int stepSize) { Array.Copy(buffer, index, CurrentExcerpt.data, 0, stepSize); return(CurrentExcerpt); }} ```
Instances of classes are stored as references. decodedProxyExcerpt1 and decodedProxyExcerpt2 are both references to the same object -- audiofactory.CurrentExcerpt.
From the looks of it `audiofactory.MoveNext(stepSize)` is staying at the same reference. This is causing `audiofactory.Current(stepSize)` to stay at the same address. For this reason, but `decodedProxyExcerpt1` and `decodedProxyExcerpt2` point to the same reference and therefore changes to one propagate to the other. So, the problems lies in your `AudioFactory` class.
Data integrity problem C#
[ "", "c#", "variable-assignment", "overwrite", "" ]
Let's say I have a `Product`, `Category`, and `Product_To_Category` table. A Product can be in multiple categories. ``` Product Category Product_to_category ID | NAME ID | Name Prod_id | Cat_id ===================== ============ =================== 1| Rose 1| Flowers 1| 1 2| Chocolate Bar 2| Food 2| 2 3| Chocolate Flower 3| 1 3| 2 ``` I would like an SQL query which gives me a result such as ``` ProductName | Category_1 | Category_2 | Category_3 ======================================================= Rose | Flowers | | Chocolate Flower | Flowers | Food | ``` etc. The best way I've been able to get this is to union a bunch of queries together; one query for every expected number of categories for a given product. ``` select p.name, cat1.name, cat2.name from product p, (select * from category c, producttocategory pc where pc.category_id = c.id) cat1, (select * from category c, producttocategory pc where pc.category_id = c.id) cat2 where p.id = cat1.id and p.id = cat2.id and cat1.id != cat2.id union all select p.name, cat1.name, null from product p, (select * from category c, producttocategory pc where pc.category_id = c.id) cat1 where p.id = cat1.id and not exists (select 1 from producttocategory pc where pc.product_id = p.id and pc.category_id != cat1.id) ``` There are several problems with this. * First, I have to repeat this union for each expected category; if a product can be in 8 categories I'd need 8 queries. * Second, the categories are not uniformly put into the same columns. For example, sometimes a product might have 'Food, Flowers' and another time 'Flowers, Food'. Does anyone know of a better way to do this? Also, does this technique have a technical name?
I don't know what RDBMS you're using, but in MySQL you can use GROUP\_CONCAT: ``` SELECT p.name, GROUP_CONCAT(c.name SEPARATOR ', ') AS categories FROM product p JOIN product_to_category pc ON p.id = pc.product_id JOIN category c ON c.id = pc.category_id GROUP BY p.name ORDER BY p.name, c.name ```
You can't create these results with a strict SQL query. What you're trying to produce is called a **pivot table**. Many reporting tools support this sort of behavior, where you would select your product and category, then turn the category into the pivot column. I believe SQL Server Analysis Services supports functionality like this, too, but I don't have any experience with SSAS.
SQL to join one table to another table multiple times? (Mapping products to categories)
[ "", "sql", "join", "" ]
I'm trying to insert binary data (a whirlpool hash) into a PG table and am getting an error: ``` TypeError: not all arguments converted during string formatting ``` code: ``` cur.execute(""" INSERT INTO sessions (identity_hash, posted_on) VALUES (%s, NOW()) """, identity_hash) ``` I tried adding conn.Binary("identity\_hash") to the variable before insertion, but get the same error. The identity\_hash column is a bytea. Any ideas?
Have you taken a look at the "examples/binary.py" script in the psycopg2 source distribution? It works fine here. It looks a bit different than your excerpt: ``` data1 = {'id':1, 'name':'somehackers.jpg', 'img':psycopg2.Binary(open('somehackers.jpg').read())} curs.execute("""INSERT INTO test_binary VALUES (%(id)s, %(name)s, %(img)s)""", data1) ```
The problem you have is that you are passing the object as second parameter: the second parameters should be either a tuple or a dict. There is no shortcut as in the % string operator. You should do: ``` cur.execute(""" INSERT INTO sessions (identity_hash, posted_on) VALUES (%s, NOW()) """, (identity_hash,)) ```
psycopg2 "TypeError: not all arguments converted during string formatting"
[ "", "python", "postgresql", "psycopg2", "" ]
I just got a heaping pile of (mostly undocumented) C# code and I'd like to visualize it's structure before I dive in and start refactoring. I've done this in the past (in other languages) with tools that generate call graphs. Can you recommend a good tool for facilitating the discovery of structure in C#? **UPDATE** In addition to the tools mentioned here I've seen (through the tubes) people say that [.NET Reflector](http://www.red-gate.com/products/reflector/) and [CLR Profiler](http://www.microsoft.com/downloads/details.aspx?FamilyId=86CE6052-D7F4-4AEB-9B7A-94635BEEBDDA) have this functionality. Any experience with these?
[NDepend](http://www.ndepend.com/Features.aspx) is pretty good at this. Additionally Visual Studio 2008 Team System has a bunch of features that allow you to keep track of cyclomatic complexity but its much more basic than NDepend. (Run code analysis)
Concerning NDepend, it can produce some usable call graph like for example: [![NDepend Method Call Graph](https://i.stack.imgur.com/ALeTa.png)](https://i.stack.imgur.com/ALeTa.png) The call graph can be made clearer by grouping its method by parent classes, namespaces or projects: [![NDepend Method Call Graph grouped by parent class](https://i.stack.imgur.com/NBrNc.png)](https://i.stack.imgur.com/NBrNc.png) Find more explanations about NDepend call graph [here](http://www.ndepend.com/Doc_VS_Arch.aspx#Call).
C# Call Graph Generation Tool
[ "", "c#", ".net", "code-analysis", "call-graph", "" ]
I am not sure if I am getting in a little too deep but I have decided i'd like to learn how to develop applications built using the Oracle technology stack. I don't come from a programming background (I have always been on the business side) but I love that no matter what problem you encounter, you can almost always solve it with a program of some description (i know 'program' is probably the wrong word there but hopefully you know what I mean). So my questions: 1. Given I have no programming experience, should I be trying to start with something else? 2. If Oracle is an ok start, from what I can ascertain i'll need to get a fair grasp of Java as well. Where should I start? Im not necessarily looking for the quickest way, but I do want to make sure that whatever I do gives me a good understanding of what is going on.
If you don't have any object-oriented programming background, I suggest you should start out by getting familiar with basic OO concept. I recommend reading this book "Head First Java" [http://www.amazon.com/Head-First-Java-Kathy-Sierra/dp/0596009208](https://rads.stackoverflow.com/amzn/click/com/0596009208) and the official java tutorial - <http://java.sun.com/docs/books/tutorial/reallybigindex.html> After you get the idea and basic concept on object-oriented programming and java. You can move yourself to use any technology including Oracle technology stack and other OO language such as python and C#.
As natch3z has mentioned, if you don't have a programming background it might be worthwhile starting a little simpler than the oracle tech stack. By Oracle tech stack, I am assuming using things like oc4j, ADF, oracle DB etc all within Oracle's JDeveloper IDE. Even though technologies like this can be powerful and achieve what you want, it might be a little overwhelming for a beginner. It might be a little more advantageous to start off with something like the Eclipse IDE and work you way through some simple tutorials. There's nothing worse than starting with something difficult and getting discouraged due to being overwhelmed.
Getting started with Oracle application development
[ "", "java", "oracle", "" ]
I have a custom control which is part of a list. The text that it should display is set by assigning a value to its Text property. At runtime, this text is loaded from a database. I want to prepend this text with the string "Toelichting: " (Dutch for "Explanation"). I can accomplish this by setting the FormatString property of the control to the following: ``` "Toelichting: {0}" ``` Now, if the text that is loaded is an empty string, I want to display "Toelichting: –", so with an en-dash at the end. Otherwise, I want to display "Toelichting: MyText". Is it possible to add some condition-checking code to the FormatString, such that I can check if the parameter is not empty?
No, there's no way to do that.
Why not just this? ``` string.Format("Toelichting: {0}", string.IsNullOrEmpty(explanation) ? "–" : explanation); ``` I don't think there's a way to embed this within the format string.
Can you include condition-checking code in a format string?
[ "", "c#", ".net", "compact-framework", "" ]
> **Possible Duplicate:** > [Storing Images in DB - Yea or Nay?](https://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay) Hi At the moment each Company on my website have 1 picture they can add to their profile. I save that image into the database....its their Company Logo. Now i want to allow them to add more pictures. Now i don’t know if i must save it all in the database or save it in folders???? Reason why i think folders will be better is because there are so much nice articles with fancy silver light kinda features that i can use but all of them only cater for images saved in folders. And since i am not THAT good its hard for me to change the code to look at the database instead of the examples that uses folders for image retrieval. I would like to add something like this to my website (browsing through the images). Any code examples for me on how to do this when images are saved in the database? I am using ASP.NET with VB.net. [Click here to view what i am talking about](http://capetown.gumtree.co.za/c-Cars-for-Sale-cars-R35K-BMW-318i-E46-Motorsport-2004-W0QQAdIdZ118186301) Any ideas guys? Regards Etienne
I've done it both ways recently and personally; I do prefer using the directory method for storing the images while keeping their properties in a DB. Main reason: I had client to whom I made a website for. On the Webiste; there was a Photo Gallery section that allowed the user to upload new photos (which could be browsed from the public site). Since my client hasn´t thought on optimizing the images before uploading; the \*.jpg was over 1mb. I did implement the ability to update the image (once it was saved to the DB) but it had to be done one record at a time. If this happens while storing the images in a directory, then the files can be saved locally, optimized and put back onto the server. [Here is an example](http://www.aspnettutorials.com/tutorials/file/fileupload-vb.aspx)
I'd go for folders. More flexibility if you run out of sttorage space (just move them to another disk and re-point), more flexibility with other apps (eg. Silverlight). I'd only use DB for files that had to be secure.
Should I store my images in the database or folders?
[ "", "c#", "asp.net", "vb.net", "image", "file", "" ]
I have few questions about string literals in C++. ``` char *strPtr = "Hello" ; char strArray[] = "Hello"; ``` Now `strPtr` and `strArray` are considered to be string literals. As per my understanding, string literals are stored in read-only memory so we cannot modify their values. We cannot do: ``` strPtr[2] = 'a'; // or strArray[2] = 'a'; ``` Both the above statements should be illegal. The compiler should raise errors in both cases, because it keeps string literals in read-only memory, so if we try to modify them, the compiler throws errors. Also, `const` objects are considered read-only. Is it that both string literals and `const` objects are treated same way? Can I remove `const`ness using `const_cast` from string literals to change their value? Where exactly are string literals stored? (In the `.data` section of program, I assume.)
> Now strPtr and strArray are considered to be string literals. No, they aren't. String literals are the things you see in your code. For example, the `"Hello"`. `strPtr` is a *pointer* to the literal (which is now compiled in the executable). Note that it should be `const char *`; you cannot legally remove the `const` per the C standard and expect defined behavior when using it. `strArray` is an array containing a copy of the literal (compiled in the execuable). > Both the above statements should be illegal. compiler should throw errors in both cases. No, it shouldn't. The two statements are completely legal. Due to circumstance, the first one is undefined. It would be an error if they were pointers to `const char`s, though. As far as I know, string literals may be defined the same way as other literals and constants. However, there are differences: ``` // These copy from ROM to RAM at run-time: char myString[] = "hello"; const int myInt = 42; float myFloats[] = { 3.1, 4.1, 5.9 }; // These copy a pointer to some data in ROM at run-time: const char *myString2 = "hello"; const float *myFloats2 = { 3.1, 4.1, 5.9 }; char *myString3 = "hello"; // Legal, but... myString3[0] = 'j'; // Undefined behavior! (Most likely segfaults.) ``` My use of ROM and RAM here are general. If the platform is only RAM (e.g. most Nintendo DS programs) then const data *may* be in RAM. Writes are still undefined, though. The location of const data shouldn't matter for a normal C++ programmer.
``` char *strPtr ="Hello" ; ``` Defines `strPtr` a pointer to char pointing to a string literal `"Hello"` -- the effective type of this pointer is `const char *`. No modification allowed through `strPtr` to the pointee (invokes UB if you try to do so). This is a backward compatibility feature for older C code. This convention is deprecated in C++0x. See Annex C: > **Change: String literals made const** > The type of a string literal is changed from “array of char” to “array of const char.” [...] > > **Rationale:** This avoids calling an inappropriate overloaded function, which might expect to be able to modify its argument. > > **Effect on original feature:** Change to semantics of well-defined feature. Difficulty of converting: Simple syntactic transformation, because string literals can be converted to char\*; (4.2). The most common cases are handled by a new but deprecated standard conversion: > > `char* p = "abc"; // valid in C, deprecated in C++` > > `char* q = expr ? "abc" : "de"; // valid in C, invalid in C++` > > **How widely used:** Programs that have a legitimate reason to treat string literals as pointers to potentially modifiable memory are probably rare. ``` char strArray[] ="Hello"; ``` The declared type of `strPtr` is -- it is an array of characters of unspecified size containing the string `Hello` including the null terminator i.e. 6 characters. However, the initialization makes it a complete type and it's type is array of 6 characters. Modification via `strPtr` is okay. > Where exactly do string literals are stored ? Implementation defined.
Where are string literals stored, and can I modify them?
[ "", "c++", "arrays", "string", "string-literals", "" ]
I have the following code that throws an exception: ``` ThreadPool.QueueUserWorkItem(state => action()); ``` When the action throws an exception, my program crashes. What is the best practice for handling this situation? --- Related: [Exceptions on .Net ThreadPool Threads](https://stackoverflow.com/questions/668265)
If you have access to `action`'s source code, insert a try/catch block in that method; otherwise, create a new `tryAction` method which wraps the call to `action` in a try/catch block.
You can add try/catch like this: ``` ThreadPool.QueueUserWorkItem(state => { try { action(); } catch (Exception ex) { OnException(ex); } }); ```
How to catch exceptions from a ThreadPool.QueueUserWorkItem?
[ "", "c#", ".net", "multithreading", "threadpool", "" ]
1. Since all files in a web project are compiled into single assembly, then does this assembly maintain a directory structure? For example, if a file in a root directory references a file in a subdirectory, then how could this reference still be valid when the two files get compiled into same assembly? 2. Assume a web project has the directory structure shown below. Since all of web project’s ASPX files get compiled into a single assembly `WebProject1.dll`, how is this assembly able to record/memorize the directory structure? Thus, when you deploy `WebProject1.dll` to a web server and user makes a request for `http://WebProject1/some_SubDir/default.aspx`, how will `WebProject1.dll` be able to figure out which Page to render? WebProject1\SubDir (where WebProject1 is a root directory) WebProject1 -- contains several ASPX files WebProject1\SubDir -- contains a file **`default1.aspx`**. 3. When we deploy the Web project, must we create the same directory structure on a web server (`WebProject1\SubDir`), even though we won’t put any ASPX files into those directories? 4. I assume that on Web server `WebProject1.dll` should be placed into the `Bin` directory? thanx **EDIT:** > Only the sourcecode is compiled into the assembly, you still need to upload the aspx files into a matching directory on the server. My book says that when using Web project all web code is compiled into single assembly. I thought “all code” includes aspx files?! > Links are maintained between the page and it's code behind file through a class declaration which by default is in a namespace that matches the directory structure So if I add a new aspx page via *Project --> Add New Item*, and store this aspx page in a subdirectory named *Hey*, then this page will reside in namespace *WebProject1.Hey*?! But how do I do add new item into a subdirectory, since *Project --> Add New Item* doesn’t give me an option to browse and choose a directory I wish to save it in, but instead automatically creates aspx file in a root directory? > The relative path is kept when the compiler generate the dll. I’m not sure I know what relative path you’re referring to? thanx
Only the sourcecode is compiled into the assembly, you still need to upload the aspx files into a matching directory on the server. For example you project in Visual Studio may look like the following: ``` WebProject1 (The root project) | |- some_SubDir (A physical directory inside the project) | |-default1.aspx |-default1.aspx.cs (assuming a C# project) ``` Once you have compiled the web app you'll need to upload the following to the server: ``` WebProject1 (The root directory for your website) | |-bin (The binary directory created by the build) | |-WebProject1.dll (The compiled source code of the web app) |-some_SubDir | |-default1.aspx (The file that will map to the URL www.websitename.com/some_subdir/default1.aspx) ``` Compiled resources (non-sourcecode files that are compiled and stored inside the assembly) are different issue that are addressed in your [other question](https://stackoverflow.com/questions/786996/are-jpg-doc-pdf-etc-files-also-compiled-into-assembly) --- Edited to add direct answers to the questions: 1. Not all files are compiled into the assembly, only source code files are. Links are maintained between the page and it's code behind file through a class declaration which by default is in a namespace that matches the directory structure, but it doesn't have to be. 2. Your default1.aspx file will have in the header something like: The inherits line tells the webserver that when a user requests this page it should be processed in conjunction with the source code that defines that class, which it will find inside the compiled assembly. The combination of the physical aspx file and the compiled class will generate standard html which is then passed back to the client. 3. Yes, you need to create the same directory structure, but you *are* required to put the aspx files in there. 4. Yes (can someone please edit this if they know how to get the list items to number correctly, please?)
All those path information will be embedded as Meta Data/resource file, so, you can deploy it safely to the server. The relative path is kept when the compiler generate the dll. I suggest you use [Reflector](http://www.red-gate.com/products/reflector/) to open the dll, and you can get a much more deeper understanding what is inside dll.
Does an assembly maintain its directory structure?
[ "", "c#", "asp.net", "assemblies", "asp.net-2.0", "" ]
I am trying to write a program to check that some C source code conforms to a variable naming convention. In order to do this, I need to analyse the source code and identify the type of all the local and global variables. The end result will almost certainly be a python program, but the tool to analyse the code could either be a python module or an application that produces an easy-to-parse report. Alternatively (more on this below) it could be a way of extracting information from the compiler (by way of a report or similar). In case that's helpful, in all likelihood, it will be the [Keil](http://www.keil.com) ARM compiler. I've been experimenting with [ctags](http://ctags.sourceforge.net) and this is very useful for finding all of the typedefs and macro definitions etc, but it doesn't provide a direct way to find the type of variables, especially when the definition is spread over multiple lines (which I hope it won't be!). Examples might include: ``` static volatile u8 var1; // should be flagged as static and volatile and a u8 (typedef of unsigned 8-bit integer) volatile /* comments */ static /* inserted just to make life */ u8 /* difficult! */ var2 = (u8) 72 ; // likewise (nasty syntax, but technically valid C) const uint_16t *pointer1; // flagged as a pointer to a constant uint_16t int * const pointer2; // flagged as a constant pointer to an int const char * const pointer3; // flagged as a constant pointer to a constant char static MyTypedefTYPE var3; // flagged as a MyTypedefTYPE variable u8 var4, var5, var6 = 72; int *array1[SOME_LENGTH]; // flagged as an array of pointers to integers char array2[FIRST_DIM][72]; // flagged as an array of arrays of type char ``` etc etc etc It will also need to identify whether they're local or global/file-scope variables (which ctags can do) and if they're local, I'd ideally like the name of the function that they're declared within. Also, I'd like to do a similar thing with functions: identify the return type, whether they're static and the type and name of all of their arguments. Unfortunately, this is rather difficult with the C syntax since there is a certain amount of flexibility in parameter order and lots of flexibility in the amount of white space that is allowed between the parameters. I've toyed with using some fancy regular expressions to do the work, but it's far from ideal as there are so many different situations that can be applied, so the regular expressions quickly become unmanageable. I can't help but think that compilers must be able to do this (in order to work!), so I was wondering whether it was possible to extract this information. The Keil compiler seems to produce a ".crf" file for each source file that's compiled and this appears to contain all of the variables declared in that file, but it's a binary format and I can't find any information on how to parse this file. Alternatively a way of getting the information out of ctags would be perfect. Any help that anyone can offer with this would be gratefully appreciated. Thanks, Al
There are a number of Python parser packages that can be used to describe a syntax and then it will generate Python code to parse that syntax. Ned Batchelder wrote a **[very nice summary](http://nedbatchelder.com/text/python-parsers.html)** Of those, Ply was used in a project called **[pycparser](http://code.google.com/p/pycparser/)** that parses C source code. I would recommend starting with this. Some of those other parser projects might also have sample C parsers. **Edit**: just noticed that pycparser even has a sample Python script to just [parse C type declarations](http://code.google.com/p/pycparser/source/browse/examples/cdecl.py) like the old cdecl program.
How about approaching it from the other side completely. You already have a parser that fully understands all of the nuances of the C type system: the compiler itself. So, compile the project with full debug support, and go spelunking in the debug data. For a system based on formats supported by [binutils](http://www.gnu.org/software/binutils/), most of the detail you need can be learned with the [BFD](http://sourceware.org/binutils/docs/bfd/index.html) library. Microsoft's debug formats are (somewhat) supported by libraries and documents at MSDN, but my Google-fu is weak today and I'm not putting my hands on the articles I know exist to link here. The Keil 8051 compiler (I haven't used their ARM compiler here) uses Intel OMF or OMF2 format, and documents that the debug symbols are for their debugger or "any Intel-compatible emulators". Specs for [OMF](http://www.keil.com/support/docs/163.htm) as used by Keil C51 are available from [Keil](http://www.keil.com/), so I would imagine that similar specs are available for their other compilers too. A quick scan of Keil's web site seems to indicate that they abandoned their proprietary ARM compiler in favor of licensing ARM's RealView Compiler, which appears to use ELF objects with DWARF format debug info. Dwarf should be supported by BFD, and should give you everything you need to know to verify that the types and names match.
Identifying the types of all variables in a C project
[ "", "python", "c", "variables", "coding-style", "code-analysis", "" ]
Suppose I've got a method that accepts an array and processes each element in it using Java's built in [for-each loop](http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html), like this: ``` public static void myFun(SomeClass[] arr) { for (SomeClass sc : arr) { // Stuff is processed here } } ``` This works just fine, but now I want to be able to pass the same method a `List<SomeClass>` instead. Am I destined to use [Collection.toArray(T [])](http://java.sun.com/javase/6/docs/api/java/util/Collection.html#toArray(T[])), or is there a parameter I can use for `myFun()` that accepts any type that can be used in a for-each construct? To clarify: I want a method signature that will accept any iterable object, be it a primitive array or a Collection. I can very easily write two methods, with one wrapping the other, but I'm just curious if there's a better way.
I would suggest using `Iterable`, `Collection` or `List` as the parameter type. IMO, collections should be preferred to reference arrays. If you happen to have an array `Arrays.asList` does the conversion nicely. `Arrays.asList` allows gets and sets back through to the array, but obviously not "structural" modifications which would change the array length. ``` myFun(Arrays.asList(arr)); ``` You may have to use wildcards in extreme/general cases. ``` public static void myFun(Iterable<? extends SomeClass> somethings) { for (SomeClass something : somethings) { // something is processed here } } ``` It is noteworthy that `Collections.toArray` and `Arrays.asList` work slightly differently. `asList` keeps the original array to back the collection, so changes to the collection will be reflected in the array. `Collections.toArray` makes a (shallow) copy of the collection data. Making a copy is often what you would want anyway if you are returning an array. Asymmetrically, if you are passing as an argument you generally do not copy (unless storing as a field).
Use [`Iterable`](http://java.sun.com/javase/6/docs/api/java/lang/Iterable.html). That's what it's for. As you said, [`Iterable`](http://java.sun.com/javase/6/docs/api/java/lang/Iterable.html) won't handle arrays. You don't want to use multiple methods wrapping each other. That rules out `Arrays.asList` and `Collection.toArray`. So the answer to your question is no, there isn't a way. But if you *can* use `Lists`, why would you ever use arrays? I would still go with `Iterable` here. I like it better than `Collection` because in the past I've had classes that implemented `Iterable` but were not collections; this made it easy for them to lazily retrieve values as needed, and I could use the foreach loop on them.
Is there a parameter I can use in Java that works with all for-each loops?
[ "", "java", "iterator", "foreach", "" ]
I have the following implementation of HttpSessionlistener ``` public class SessionListener implements HttpSessionAttributeListener, HttpSessionListener { public void attributeAdded(HttpSessionBindingEvent event) { ... } public void attributeRemoved(HttpSessionBindingEvent event) { ... } public void attributeReplaced(HttpSessionBindingEvent event) { } //HttpSesion creation & destruction public void sessionCreated(HttpSessionEvent event) { HttpSession session = event.getSession(); //log created time } public void sessionDestroyed(HttpSessionEvent event) { HttpSession session = event.getSession(); long destroyedTime = System.currentTimeMillis(); //log destroyed time } ``` } Basically i log the session creation and destruction time. But if the session is long (default to 30 minutes), and user closes browser meanwhile, the ``` sessionDestroyed ``` is not called ? Why is that ? Is there a workaround to log exactly the when the session was destroyed (when user closes the browser)? Should'nt be this be the browser's problem, to kill the session when it is closed ? Is there any interface that i have to implement for this to work ? Thank you !
How would the server know when the browser is closed or the tab closed? At that point the browser doesn't send anything to the server. This is a fundamental part of HTTP - it's a request/response protocol, not a "permanently open conversation" where you can tell if one party leaves the conversation. Think of it as a series of telegrams rather than a phone call - and you can't tell when you've received the last telegram you're going to get. You'll need to design your way round this - to avoid *needing* to know when the browser has been closed. There are some ugly hacks to work around it - making AJAX poll the server with a heartbeat message, for example - but changing the design is a better solution.
*NOTE:* As [jwenting](https://stackoverflow.com/questions/706224/javawhy-http-session-is-not-destroyed-when-tab-or-browser-is-closed/1121034#comment-8129744) commented below, this it's not 100% safe at all. If the the onunload event does not get triggered by a closing event of the browser tab or window, then this would fail. I had the same problem, and solve it using an intrusive JavaScript event: ``` window.onunload ``` Let me briefly explain, lets say you have a JavaScript function that post, using jQuery, the current Session ID to that Servlet to invalidate it, like this: ``` function safeexit(){ $.post("/SessionKillServlet", { SID = <%=session.getId()%> }, function(data){}); } ``` To call that function, you just need to bind it like these: ``` window.onunload = safeexit; //without the () ``` Now, safeexit method will be called when the TAB or BROWSER WINDOW gets closed (or in a redirection).
Java:Why http session is not destroyed when tab or browser is closed?
[ "", "java", "session", "" ]
Is it possible to use C# for free? Which tools would you use? 1. For fun/studying: I'm pretty sure you can, but still, the tools question remains. 2. For programs you wish to sell? The tools I'm looking for: 1. IDE (as complete as possible: debugging, refactoring, libraries, IntelliSense etc.) - also, if it's not included in the IDE, compiler. 2. Unit Testing, 3. Documenting (extracting comments as with JavaDoc), 4. Deploying. Other suggestions for nice free tools are also welcome. Note that IMO, Visual Studio Express is NOT offering all these tools.
IDEs: * [Visual Studio 2017 Community](https://www.visualstudio.com/downloads/). It has a subset of Professional Edition's features, but all that you have mentioned. You may want to [Compare Visual Studio 2017 Editions](https://www.visualstudio.com/vs/compare/). High school and university students are eligible for free licence of VS Professional from [Dreamspark](http://www.dreamspark.com). * Sharp Develop * [Mono Develop](http://monodevelop.com/) standalone compiler: * csc.exe, vbc.exe and msbuild.exe are a part of .NET Framework. Windows SDK tools is also free. Or you can use compiler from [Mono project](http://mono-project.com/). --- Unit Testing: * NUnit, mbUnit, xUnit and many, many others. Documenting: (extracting comments JavaDoc-style) * [GhostDoc](http://www.roland-weigelt.de/ghostdoc/) - not for Express Edition Deploying: * [NAnt](http://nant.sourceforge.net/), [Cruse Control .NET](http://ccnet.thoughtworks.com/)
While OP says: > Visual Studio Express is NOT offering all this tools as claimed! > > > What doesn't C# Express provide that you want? > > serious deploying, unit testing, documenting Yet, IMO you *can* do that with Visual Studio Express. ### Deployment Visual Studio Deployment projects are certainly missing from Visual Studio Express, but frankly that's not much of an omission. The whole feature is half baked, good enough to tick off a feature list, good enough for toy deployments but, arguably, not really up to the rigors of the real world. [Windows Installer XML](http://wix.sourceforge.net/) (WiX) is an open source toolkit from Microsoft for creating installers. The installer for Microsoft Office 2007 was [reportedly](http://www.tramontana.co.hu/wix/) built with WiX, so it's reasonable to believe that it can handle any smaller case. Another installation tool is the [Nullsoft Scriptable Install System](http://nsis.sourceforge.net/Main_Page), perhaps easier to understand than WiX, but also not using with the MSI technology built into Windows and therefore harder to manage in the Enterprise case. ### Unit Testing The Microsoft testing framework is [MSTest](http://en.wikipedia.org/wiki/MSTest), and while it's up to the task, it's not the leader of the pack. In fact, if you google around for reactions to MSTest, you'll find many who think it a ripoff of [NUnit](http://www.nunit.org/). There was a time that you could integrate any of the test tools into Visual Studio Express, using [Test Driven.Net](http://www.testdriven.net/), though that no longer works. What *does* work is to use the external runner programs for your unit testing tool - all of the major unit testing frameworks come with them. When using VS Express myself, I tend to have the test runner hanging around in the background; rerunning tests then just involves a task switch. NUnit is the grandaddy of the .NET testing frameworks, and it works very well. There are others around though, such as [mbUnit](http://www.mbunit.com/) and [xUnit](http://www.codeplex.com/xunit). ### Documentation No version of Visual Studio has a good story for documentation. In fact, they all have the *same story* - a compiler switch to generate XML files based on the documentation comments. To convert those XML files into real documentation, you need other tools. [NDoc](http://ndoc.sourceforge.net/) used to be the standard, but that project is unfortunately now dead ([quite a sad tale](http://weblogs.asp.net/bhouse/archive/2006/07/26/NDoc-2.0-_2D00_-R.I.P.aspx)). [Sandcastle](http://blogs.msdn.com/sandcastle/) (another Microsoft Open Source project) is likely to become the new gold standard, but the tool isn't yet as mature and easy to use as we would like. [DocU](http://blog.jagregory.com/2009/03/19/introducing-docu-simple-doc-gen-for-net/) is a new release in this field, might be worth followup. ### Conclusions As you can see, there are good ways to achieve the goals you want, even using Visual Studio Express. In fact, there are only two things you'll gain from moving up to a paid version of Visual Studio. 1. You'll get MSTest, if you want it. 2. You'll be able install extensions/plugins like TestDriven.NET and Resharper. For someone getting started, I don't think the value proposition is there. Start with the free tools and spend money when you have enough experience to spend it well.
How to write, compile and run C# for free (in Windows)
[ "", "c#", "deployment", "ide", "" ]
Hey there I got a problem with my code, I compared three ways of implementing a query on a database 1. Standard SQL Query (From \* Select ...) 2. LinQ Query 3. Precompiled LinqQuery (CompiledQuery) Now the result I got is that the Precompiled LingQuery is 5 times faster than the LinQ Query but much more interesting ist that the Standard SQL Query is approximately ten times fast than the Precompiled LinqQuery. The table that my Queries run against is one simple table with no associations to other tables. The fact that makes the table interesting is that it consists of 5 columns which represent all together the primary key I mean. all columns together is unique so there is no row in the table that looks like the other. All columns are indexed. Does anyone have an idea about what goes wrong with LinQ? With kind regards Sebastian
Have you had a look at the actual query that linq generates? Comparing those with your SQL query might give you some answers. You can do this either using SQL Profiler or listening to the linq datacontext's Out property? You can do it like this in a console app: ``` DataContext ctx = new ...; ctx.Log = Console.Out; //Now execute the linq query, and the query will be output to the console. ```
Just make sure that your queries are not cached, that can skew the results.
Standard SQL Query much faster than Linq 2 SQL
[ "", ".net", "sql", "linq", "" ]
I'm looking for an example of how I would read a value from a database and use it in a jQuery script to set the background color of a control. I'm still learning jQuery, and it's not clear to me how to get a value from the database. I'm using ASP.NET MVC, and my form is already pulling the value - do I need to put it in a hidden field and use it that way, or is there a better/different way to communicate the color value to jQuery?
I can think of a few different ways to do this, some of which don't use jQuery depending on what you are trying to accomplish. **Theming** Develop custom CSS and have your view choose which CSS file to use based on the selection from the database. This would be view code that constructs a CSS link based on the value of the database field. Apply classes to your controls from the theme (each theme would have the same classes, just different settings for each one). ``` <link href='<%= Url.Content( "~/Content/styles/" + Model.Theme ) %>' type="text/css" rel="stylesheet" /> ``` **User Preferences** You want the user to be able to actually change a particular element's look and feel, not merely choose a theme. In this case there are a couple of different options -- one have a helper that generates custom CSS for the user based on the database values -- again using common classes so that you can style the controls with classes. Call this helper from your View and inject the correct CSS into the page either directly or as a link to an action that generates the CSS in response to a link. Or, and I don't like this option, set the style property on the control itself using the View layout and get the value of the background color property from ViewData. ``` <link href='<% Url.Action("css","generate", new { id = Model.UserID } ) %>' type="text/css" rel="stylesheet" /> <div style='background-color: <%= ViewData["controlBackgroundColor"] %>;'></div> ``` **Dynamic Changes** You want to have the color change dynamically based on a user action and have the new color(s) come from the database. In this case you can inject the color into the script tag where your jQuery lives directly. ``` <script type="text/javascript"> $(document).ready( function() { $('#someButton').click( function() { $('#someControl').css('background','<%= ViewData["controlBackground"] %>'); }); }); </script> ``` I don't see any need to use a hidden field.
A hidden value would work fine, you could retrieve it using: ``` $("#hiddenFieldId").val(); ``` Another thing you could do, is to set a global variable in javascript (i.e, at the top of your file, outside the definition of all functions. Then it will be available inside all functions.). You'll do something like this: ``` //On top of your-file.js: var color=''; $(document).ready(function() { $("body").css("background-color",color); //Not tested } ); ``` In the HTML file: ``` <script type='text/javascript' src='your-file.js'> </script> color="<?=$color;?>"; //Or do it how you'd do it in ASP ```
Use jQuery to set background color with value from database
[ "", "asp.net", "javascript", "jquery", "" ]
In the following example, I want to define a System.Action which executes a specific method that I define at runtime, but **how do I pass the method name (or the method itself)** so that the Action method can define the delegate to point to that particular method? I'm currently getting the following error: *'methodName' is a 'variable' but is used like a 'method'* ``` using System; using System.Collections.Generic; namespace TestDelegate { class Program { private delegate void WriteHandler(string message); static void Main(string[] args) { List<string> words = new List<string>() { "one", "two", "three", "four", "five" }; Action<string> theFunction = WriteMessage("WriteBasic"); foreach (string word in words) { theFunction(word); } Console.ReadLine(); } public static void WriteBasic(string message) { Console.WriteLine(message); } public static void WriteAdvanced(string message) { Console.WriteLine("*** {0} ***", message); } public static Action<string> WriteMessage(string methodName) { //gets error: 'methodName' is a 'variable' but is used like a 'method' WriteHandler writeIt = new WriteHandler(methodName); return new Action<string>(writeIt); } } } ```
You don't need the Delegate declaration or the WriteMessage method. Try the following: ``` using System; using System.Collections.Generic; namespace TestDelegate { class Program { static void Main(string[] args) { List<string> words = new List<string>() { "one", "two", "three", "four", "five" }; Action<string> theFunction = WriteBasic; foreach (string word in words) { theFunction(word); } Console.ReadLine(); } public static void WriteBasic(string message) { Console.WriteLine(message); } public static void WriteAdvanced(string message) { Console.WriteLine("*** {0} ***", message); } } } ``` Action is already a delegate so you don't need to make another one.
Pass it without quotes - ``` Action<string> theFunction = WriteMessage(WriteBasic); ``` Change the signature of "WriteMessage" to - ``` public static Action<string> WriteMessage(WriteHandler methodName) ``` Also change the "private" delegate to "public" - ``` public delegate void WriteHandler(string message); //Edit suggested by Mladen Mihajlovic ```
How to pass a method name in order to instantiate a delegate?
[ "", "c#", "delegates", "" ]
I've been really interested in adding support for video podcasts to Media Browser. I would like users to be able to navigate through the available video podcasts and stream them from the internets. That's really easy cause media player etc.. will happily play a file that lives in the cloud. The problem is that I want cache these files locally so subsequent viewings of the same episode will not involve streaming and instead will play the local file. So... I was thinking, why not host an `HttpListener` and as media player asks it for bits of the file, have the `HttpListener` download and store it locally. Next time a user plays the file we will already have portions of the file locally. Does anyone know of example code that uses `HttpListener` for proxying? **EDIT** The idea would be only to proxy simple streamable content like MP3 or Mov. The bounty will go to an actual implementation. Here is the API I would like: ``` // will proxy a uri on the local port, if cacheFile exists it will resume the // download from cacheFile. // while the file is downloading it will be name cacheFile.partial, after the // download is complete the file will be renamed to cacheFile. // Example usage: ProxyFile("http://media.railscasts.com/videos/176_searchlogic.mov", 8000, @"c:\downloads\railscasts\176_searchlogic.mov") // // Directly after this call http://localhost:8000 will be the proxy stream, it will be playable locally. void ProxyUri(Uri uri, int port, string cacheFile) ``` **Edit 2** `HttpListener` is looking pretty unpromising I will probably need to do the work at a TCP socket level as `HttpListener`s seem to require the program runs as admin which is going to be really tricky.
I hadn't done anything with `HttpListener` before, so I thought this would be a nice little exercise to bring myself up to speed with it - and so it proved. I implemented it as a single `ProxyListener` class whose constructor takes the parameters of the `ProxyUri` function you specified. Once you obtain an instance, you start it listening (and potentially downloading) by calling its `Start` method. When you're done with it, call `Cleanup`. There are one or two rough edges but basically it works as per your question. To test it, I built it up as a console application with a `Program` class which accepts input lines consisting of (uri, port, filename), space-separated, creates the `ProxyListener` instances and starts them. You can run this console application, type in a suitable line, and the downloader will start (printing out progress to console). Simultaneously you can e.g. fire up IE and fetch the file from the specified port, and you will be able to download it while the downloader is still working. The "uploader" progress will be printed to console, too. I'm having a bit of trouble pasting it in here, maybe due to size (it's not that big, but bigger than the snippets you normally see here - the `ProxyListener` class is a tad under 200 lines). Does it sound interesting? If so, I'll post it to a pastebin and update this answer with a link. **Update:** Posted as a [gist](https://gist.github.com/2f4df2dafc3ecfb0f450). Note that you will need Administrator privileges to run the program, since `HttpListener` requires this. **Update 2:** Under certain circumstances, it is not necessary to have admin privileges to run `HttpListener`. See [this link](http://msdn.microsoft.com/en-us/library/aa364673%28VS.85%29.aspx) and [this one](http://urlreservation.codeplex.com/). The idea is, if you can reserve an URL namespace during installation time, then the user does not have to have admin privileges if listening against that namespace.
Streaming was not designed to be saved, and also these protocols are very custom and very complex to implement, streaming sessions do lots of validation and synchronization which will be extremely difficult to imitate. Of course it is not an impossible task, but its fairly big task to do. Only other way is to read and save it as local media file, and use that as a reference. Because you can use windows media encoder to read stream and write stream data as local file, but it still may not allow you to do copy protected data.
Proxying Videos locally with a TCP Socket
[ "", "c#", ".net", "proxy", "" ]
consider the program below ``` char str[5]; strcpy(str,"Hello12345678"); printf("%s",str); ``` When run this program gives segmentation fault. But when strcpy is replaced with following, program runs fine. ``` strcpy(str,"Hello1234567"); ``` So question is it should crash when trying to copy to str any other string of more than 5 chars length. So why it is not crashing for "Hello1234567" and only crashing for "Hello12345678" ie of string with length 13 or more than 13. This program was run on 32 bit machine .
There are three types of standards behaviour you should be interested in. 1/ *Defined behaviour*. This will work on all complying implementations. Use this freely. 2/ *Implementation-defined behaviour*. As stated, it depends on the implementation but at least it's still defined. Implementations are required to document what they do in these cases. Use this if you don't care about portability. 3/ *Undefined behaviour*. Anything can happen. And we mean *anything*, up to and including your entire computer collapsing into a naked singularity and swallowing itself, you and a large proportion of your workmates. Never use this. Ever! Seriously! Don't make me come over there. Copying more that 4 characters and a zero-byte to a `char[5]` is undefined behaviour. Seriously, it doesn't matter why your program crashes with 14 characters but not 13, you're almost certainly overwriting some non-crashing information on the stack and your program will most likely produce incorrect results anyway. In fact, the crash is better since at least it stops you relying on the possibly bad effects. Increase the size of the array to something more suitable (`char[14]` in this case with the available information) or use some other data structure that can cope. --- *Update:* Since you seem so concerned with finding out why an extra 7 characters doesn't cause problems but 8 characters does, let's envisage the possible stack layout on entering `main()`. I say "possible" since the actual layout depends on the calling convention that your compiler uses. Since the C start-up code calls `main()` with `argc` and `argv`, the stack at the start of `main()`, after allocating space for a `char[5]`, could look like this: ``` +------------------------------------+ | C start-up code return address (4) | | argc (4) | | argv (4) | | x = char[5] (5) | +------------------------------------+ ``` When you write the bytes `Hello1234567\0` with: ``` strcpy (x, "Hello1234567"); ``` to `x`, it overwrites the `argc` and `argv` but, on return from `main()`, that's okay. Specifically `Hello` populates `x`, `1234` populates `argv` and `567\0` populates `argc`. Provided you don't actually try to *use* `argc` and/or `argv` after that, you'll be okay: ``` +------------------------------------+ Overwrites with: | C start-up code return address (4) | | argc (4) | '567<NUL>' | argv (4) | '1234' | x = char[5] (5) | 'Hello' +------------------------------------+ ``` However, if you write `Hello12345678\0` (note the extra "8") to `x`, it overwrites the `argc` and `argv` *and also* one byte of the return address so that, when `main()` attempts to return to the C start-up code, it goes off into fairy land instead: ``` +------------------------------------+ Overwrites with: | C start-up code return address (4) | '<NUL>' | argc (4) | '5678' | argv (4) | '1234' | x = char[5] (5) | 'Hello' +------------------------------------+ ``` Again, this depends entirely on the calling convention of your compiler. It's possible a different compiler would always pad out arrays to a multiple of 4 bytes and the code wouldn't fail there until you wrote another three characters. Even the same compiler may allocate variables on the stack frame differently to ensure alignment is satisfied. That's what they mean by undefined: you don't *know* what's going to happen.
You're copying to the stack, so it's dependent on what the compiler has placed on the stack, for how much extra data will be required to crash your program. Some compilers might produce code that will crash with only a single byte over the buffer size - it's undefined what the behaviour is. I guess size 13 is enough to overwrite the return address, or something similar, which crashes when your function returns. But another compiler or another platform could/will crash with a different length. Also your program might crash with a different length if it ran for a longer time, if something less important was being overwritten.
Segmentation fault in strcpy
[ "", "c++", "c", "undefined-behavior", "" ]
I need to resize an animated GIF file without destroying the animation. How can I do it using PHP?
if you have imagemagick access, you can do this: ``` system("convert big.gif -coalesce coalesce.gif"); system("convert -size 200x100 coalesce.gif -resize 200x10 small.gif"); ``` this is most likely possible with the imagemagick plugin if you don't have system() access NOTE: this may create a larger filesize though a smaller dimensions image due to coalescing essentially deoptimizing the image. **UPDATE:** If you don't have ImageMagick access, you should be able to use a combination of the following steps to resize an animated gif (assuming you have GD access): 1. Detect if the image is an animated gif: [Can I detect animated gifs using php and gd?](https://stackoverflow.com/questions/280658/can-i-detect-animated-gifs-using-php-and-gd) (top answer) 2. Split the animated gif into individual frames: <http://www.phpclasses.org/package/3234-PHP-Split-GIF-animations-into-multiple-images.html> 3. Resize the individual frames: <http://www.akemapa.com/2008/07/10/php-gd-resize-transparent-image-png-gif/> 4. Recomposite the frames into an animated gif again: <http://www.phpclasses.org/package/3163-PHP-Generate-GIF-animations-from-a-set-of-GIF-images.html> This is definitely much more intensive than the ImageMagick route, but it should be technically possible. If you get it working, please share with the world!
Try ~~GDEnhancer~~ (Use [ImageCraft](https://github.com/coldume/imagecraft)). It only need GD Library, and it keep gif animation
Resize animated GIF file without destroying animation
[ "", "php", "image", "imagemagick", "animated-gif", "" ]
I realize that there are a lot of questions regarding friend classes in C++. My question, though, is tied to a specific scenario. Given the below code, is it appropriate to use friend in such a manner? ``` class Software { friend class SoftwareProducer; SoftwareProducer* m_producer; int m_key; // Only producers can produce software Software(SoftwareProducer* producer) : m_producer(producer) { } public: void buy() { m_key = m_producer->next_key(); } }; class SoftwareProducer { friend class Software; public: Software* produce() { return new Software(this); } private: // Only software from this producer can get a valid key for registration int next_key() { return ...; } }; ``` Thanks, Best regards,
Sure, that's perfectly reasonable. Basically what you have done is very similar to a factory pattern. I see no issue with that since your code seems to imply that every Software object should have a pointer to its creator. Though, usually you can avoid to have "Manager" classes like SoftwareProducer, and just have static methods in Software. Since it seems likely that there will be only one SoftwareProducer. Something like this perhaps: ``` class Software { private: Software() : m_key(0) { /* whatever */ } public: void buy() { m_key = new_key(); } public: static Software *create() { return new Software; } private: static int new_key() { static int example_id = 1; return example_id++; } private: int m_key; }; ``` Then you can just do this: ``` Software *soft = Software::create(); soft->buy(); ``` Of course if you do plan on having more than one SoftwareProducer object, then what you have done seems appropriate.
This seems perfectly reasonable to me. Check out [Factories: encapsulating object creation](http://www.codeguru.com/cpp/tic/tic0289.shtml) from Bruce Eckel's [Thinking in C++](http://www.codeguru.com/cpp/tic/tic_c.shtml) for more on this particular use of friends. You might also have a look at the [C++ FAQ on friends](http://www.parashift.com/c++-faq-lite/friends.html) for some more rules of thumb.
C++ friend classes
[ "", "c++", "coding-style", "" ]
Is there any way of reading and writing the data from a Microsoft Project 2007 mpp file? I have an application that reads and writes data from a Project 2003 access database file. In order for this to work, I first save the Project 2003 mpp file as an Access database and my code can then read and write to the Access database. But Project 2007 does not allow you to save as an Access database file. I was wondering if there is any other method to get the data?
You can use the [.NET Office Interop](http://msdn.microsoft.com/en-us/office/aa905525.aspx) to work with Microsoft Project 2007.
You may find [MPXJ](http://mpxj.sf.net) useful. It will allow you to read from MPP files, and a variety of file formats from Project and other planning applications. It will allow you to save your data as MPX or MSPDI files if you want to read it into Project again. Jon p.s. Disclaimer: I maintain MPXJ.
Reading and Writing to a Microsoft Project 2007 from C#
[ "", "c#", "ms-project", "" ]
I have a text file input which contains data as below. How can I display data from the text file into specific format? ``` Monday Jessy Walking 20 minutes Matthew Run 20 minutes Karen Jogging 40 minutes Jessica Run 12 minutes Tuesday Messia Walking 10 minutes Matthew Run 20 minutes Pete Run 10 minutes Carol Walking 30 minutes ``` I want to display data from the text file into this format: ``` Day Name Type of exercise Time Monday Jessy Walking 20 minutes Matthew Run 20 minutes Karen Jogging 40 minutes Jessica Run 12 minutes Tuesday Messia Walking 10 minutes Matthew Run 20 minutes Pete Run 10 minutes Carol Walking 30 minutes ```
I just threw this together quickly, but what about something like: ``` static final String[] DAYS = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; public class ActivityEvent { public int day; public String name; public String typeOfExercise; public String time; } public List loadActivities(String filename) throws IOException { List activities = new ArrayList(); FileInputStream fis = new FileInputStream(filename); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); int lastDay = -1; String line; while ((line = br.readLine()) != null) { line = line.trim(); int day; for (day = DAYS.length - 1; day >= 0; day--) { if (line.equals(DAYS[day])) { break; } } String name; if (day < 0) { day = lastDay; if (lastDay < 0) { throw new IOException(filename + " must start with day of week"); } name = line; } else { name = br.readLine(); if (name == null) { throw new IOException(filename + " expected name, reached end of file"); } } String type = br.readLine(); if (type == null) { throw new IOException(filename + " expected type of exercise, reached end of file"); } String time = br.readLine(); if (time != null) { throw new IOException(filename + " expected time of exercise, reached end of file"); } ActivityEvent activity = new ActivityEvent(); activity.day = day; activity.name = name; activity.typeOfExercise = type; activity.time = time; activities.add(activity); } return activities; } public void printActivities(List activities) { StringBuilder str = new StringBuilder("Day\tName\tType of Exercise\tTime\n"); int numActivities = activities.size(); int lastDay = -1; for (int index = 0; index < numActivities; index++) { ActivityEvent activity = (ActivityEvent)activities.get(index); if (activity.day != lastDay) { str.append(DAYS[activity.day]); } str.append('\t'); str.append(activity.name); str.append('\t'); str.append(activity.typeOfExercise); str.append('\t'); str.append(activity.time); str.append('\n'); } System.out.print(str.toString()); } ``` And then invoke everything for example: ``` List activities = loadActivities("somefile.txt"); // Do optional sorting, etc. here. printActivities(activities); ```
I would have a look at Java's [sprintf](http://java.sun.com/j2se/1.5.0/docs/api/java/io/PrintStream.html#printf%28java.lang.String,%20java.lang.Object...%29)() function and it's ability to [left/right justify](http://www.java2s.com/Tutorial/Java/0120__Development/Rightjustifyingandleftjustifyingvalues.htm) data with specified widths.
How to display data from txt file in specific format
[ "", "java", "file", "text-files", "" ]
I'm writing a windowed program in C++, but I would like to have the option to pop up a console to output to from inside the program (such as various things that go on behind the scenes of my program, to see that everything is acting correctly). Is there an easy way to do this? EDIT: In this particular case I'm using [sfml](http://www.sfml-dev.org) on windows, but for the purposes of this question it can be any API or platform (and platform independent solutions are best)
If you are talking about MS Windows, which your question does not make clear, you can use the [AllocConsole](http://msdn.microsoft.com/en-us/library/ms681944%28VS.85%29.aspx) API to create a console. for your app. **Edit:** You say that it could be any platform, but this is not so as many platforms have no concept of a console. For this reason, a cross-platform solution is not possible.
There are Windows API functions to deal with console management. [This](http://msdn.microsoft.com/en-us/library/ms681944(VS.85).aspx) might be a good starting point.
Programatically opening and closing a console
[ "", "c++", "windows", "console", "" ]
### Rational I would like to have more detailed logging debugging/logging output on a few superclasses, so the subclass name will not actually be effecting real-time performance nor application logic. I'm also of the opinion that it is fairly bad design to do this normally, however I really do want this info to be logged during development runs. ### Question Suppose I have a simple class structure as below, how do I pull the name of the subclass into the superclass without having to explicitly pass a reference? ``` public abstract AbstractClass { private Logger logger = LoggerFactory.getLogger(getClass()); public AbstractClass() {} public void execute(ContextObject context) { if (logger.debuggingEnabled()) { String invokingClassName = ""; // <-- how do I get this? logger.debug("Executing {}", invokingClassName); } // shared application logic is here... } } public MyClass extends AbstractClass { public MyClass() {} @Override public void execute(ContextObject context) { super.execute(context); // application logic... } } ``` I have worked with parsing stack traces before and I suspect that is the route I will have to go if I want this information. Does anyone know of a library that will do this for me or a good code snippet?
Doesn't [`this.getClass().getName()`](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#getName()) do the trick? Namely: ``` public void execute(ContextObject context) { if (logger.debuggingEnabled()) { String invokingClassName = ""; // <-- how do I get this? logger.debug("Executing {}", this.getClass().getName()); } // shared application logic is here... } ```
You've already got that information when you execute this line: ``` private Logger logger = LoggerFactory.getLogger(getClass()); ``` That means you'll be logging with a category for the *actual* class. As that information is in the log already, I don't think it makes much sense to *also* include it in the `execute` method. Just make sure that your log output format includes the category name and it should be fine.
How do I retrieve the name of the lowest subclass from the context of the superclass in Java?
[ "", "java", "debugging", "stack-trace", "" ]
I have a considerable amount of experience with [ACE](http://www.cs.wustl.edu/~schmidt/ACE.html), [Boost](http://www.boost.org/) and [wxWidgets](http://www.wxwidgets.org/). I have recently found the [POCO](http://pocoproject.org/) libraries. Does anyone have any experience with them and how they compare to ACE, Boost and wxWidgets with regard to performance and reliability? I am particularly interested in replacing ACE with POCO. I have been unable to get ACE to compile with VS2008 with an x64 target. I mostly use ACE\_Task so I think I can replace those with Poco's threads and message queues. Some other portions of POCO that interest me are the HTTPServer, HTTPClient, and LayeredConfiguration. Those libraries are similiar to libraries in Boost and wxWidgets but I try to limit my use of wxWidgets to GUI components and the comparable Boost libraries are... difficult. I'm interested in any experience anyone can share about POCO, good or bad.
I have used parts of POCO now and again and found it to be a very nice lib. I largely abandoned ACE a number of years ago but POCO contains some of the same patterns - Task, Reactor, etc. I have never had any problems with it so I have to assume it is stable. Some aspects that I like: * it is a pretty well integrated OOP hierarchy so the components work well with each other. It has a much more cohesive feel than something like Boost which is rather piece-meal. * the source code is available and very clear. You don't need to devote large blocks of time to understand what it is doing (ACE, at least last I looked at the source) or be a template wizard (Boost). * Components stick close to standard C++. Exceptions are derived from std::exception; they didn't reinvent yet-another-string class, etc. * It is surprising comprehensive. There is a lot more there than appears at first glance. The downside: * A matter of personal preference but the authors stick pretty much to a one class per header file model so you end up including a lot of different files. * Limited documentation. Mostly doxygen type API pages and a couple of PDFs pointing to source examples. It's usable but considering the size of the lib it is initially difficult to figure if you are making the best use of the components. * If there is an active community built around it, I never found it. The package is maintained by some European based company and they had a wiki but I didn't find it that active or useful. All things considered, the downside is pretty minor. I think it is a very good library and would definitely recommend it.
I have never used ACE, but I used Boost and Poco. I really like the coding style of Poco. The packages are consistent and the source code is easy to read. They're not template crazy like boost. In my experience I spend hours reading how to use boost - serialization package, pointer map container etc- and little time reading how to use Poco stuff. I would say they have good design and make use of templates where needed. On the negative side they have API documentation but they don't have extensive documentation on how you would use a package. For that you usually look at example source code, or their unit tests source code. I have the HTTPServer working on Windows/Linux without any obvious errors. So chalk it up as 1 positive experience.
ACE vs Boost vs Poco vs wxWidgets
[ "", "c++", "boost", "ace", "poco-libraries", "" ]
I am trying to add an autocomplete feature to a textbox, the results are coming from a database. They come in the format of > [001] Last, First Middle Currently you must type [001]... to get the entries to show. **So the problem is that I want it to complete even if I type the firstname first**. So if an entry was > [001] Smith, John D if I started typing John then this entry should show up in the results for the auto complete. Currently the code looks something like ``` AutoCompleteStringCollection acsc = new AutoCompleteStringCollection(); txtBox1.AutoCompleteCustomSource = acsc; txtBox1.AutoCompleteMode = AutoCompleteMode.Suggest; txtBox1.AutoCompleteSource = AutoCompleteSource.CustomSource; .... if (results.Rows.Count > 0) for (int i = 0; i < results.Rows.Count && i < 10; i++) { row = results.Rows[i]; acsc.Add(row["Details"].ToString()); } } ``` *results is a dataset containing the query results* *The query is a simple search query using the like statement. The correct results are returned if we do not use the autocomplete and just toss the results into an array.* Any advice? **EDIT:** Here is the query that returns the results ``` SELECT Name from view_customers where Details LIKE '{0}' ``` *With {0} being the placeholder for the searched string.*
The existing AutoComplete functionality only supports searching by prefix. There doesn't seem to be any decent way to override the behavior. Some people have implemented their own autocomplete functions by overriding the `OnTextChanged` event. That's probably your best bet. For example, you can add a `ListBox` just below the `TextBox` and set its default visibility to false. Then you can use the `OnTextChanged` event of the `TextBox` and the `SelectedIndexChanged` event of the `ListBox` to display and select items. This seems to work pretty well as a rudimentary example: ``` public Form1() { InitializeComponent(); acsc = new AutoCompleteStringCollection(); textBox1.AutoCompleteCustomSource = acsc; textBox1.AutoCompleteMode = AutoCompleteMode.None; textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource; } private void button1_Click(object sender, EventArgs e) { acsc.Add("[001] some kind of item"); acsc.Add("[002] some other item"); acsc.Add("[003] an orange"); acsc.Add("[004] i like pickles"); } void textBox1_TextChanged(object sender, System.EventArgs e) { listBox1.Items.Clear(); if (textBox1.Text.Length == 0) { hideResults(); return; } foreach (String s in textBox1.AutoCompleteCustomSource) { if (s.Contains(textBox1.Text)) { Console.WriteLine("Found text in: " + s); listBox1.Items.Add(s); listBox1.Visible = true; } } } void listBox1_SelectedIndexChanged(object sender, System.EventArgs e) { textBox1.Text = listBox1.Items[listBox1.SelectedIndex].ToString(); hideResults(); } void listBox1_LostFocus(object sender, System.EventArgs e) { hideResults(); } void hideResults() { listBox1.Visible = false; } ``` There's a lot more you could do without too much effort: append text to the text box, capture additional keyboard commands, and so forth.
If you decide to use a query that is based on user input make sure you use SqlParameters to avoid SQL Injection attacks ``` SqlCommand sqlCommand = new SqlCommand(); sqlCommand.CommandText = "SELECT Name from view_customers where Details LIKE '%" + @SearchParam + "%'"; sqlCommand.Parameters.AddWithValue("@SearchParam", searchParam); ```
C# AutoComplete
[ "", "c#", "winforms", "autocomplete", "" ]
I try to construct a big Int64 with nibble information stored in bytes. The following lines of code work as expected: ``` Console.WriteLine("{0:X12}", (Int64)(0x0d * 0x100000000)); Console.WriteLine("{0:X12}", (Int64)(0x0d * 0x1000000)); Console.WriteLine("{0:X12}", (Int64)(0x0d * 0x100000)); ``` Why does the following line lead to a compile error CS0220 "The operation overflows at compile time in checked mode" and the others do not? ``` Console.WriteLine("{0:X12}", (Int64)(0x0d * 0x10000000)); ``` The result would be: ``` FFFFFFFFD0000000 ``` instead of: ``` 0000D0000000 ``` Can anyone explain this? I will now convert with shift operators, but still curious why this approach does not work! Update: The error also occurs when using (Int64)(0x0d << 28).
You need to mark the constant values specifically as longs (Int64s) or possibly ulongs (UInt64s), otherwise by default they will be interpreter as ints (i.e. Int32s), clearly causing overflows. Casting after the multiplication operation won't do you any good in this case. Haven't tested, but this code should work: ``` Console.WriteLine("{0:X12}", 0x0dL * 0x100000000L); Console.WriteLine("{0:X12}", 0x0dL * 0x1000000L); Console.WriteLine("{0:X12}", 0x0dL * 0x100000L); ```
Integer literals have type Int32 (even if in hex). Use the "L" suffix to make them longs (Int64). ``` Console.WriteLine("{0:X12}", 0x0dL * 0x100000000L); ```
Why this specific operation overflow (cf. CS0220) in C#?
[ "", "c#", "compiler-construction", "overflow", "" ]
I was wondering, after having read [this question](https://stackoverflow.com/questions/786890/generic-way-to-find-or-create-an-object-in-linq-to-sql/786932#786932)... he has this code: ``` public static T FindOrCreate<T>(this Table<T> table, Func<T, bool> find) where T : new() { T val = table.FirstOrDefault(find); if (val == null) { val = new T(); table.InsertOnSubmit(val); } return val; } ``` Would it be possible to also send in that new item as another Func? I mean, of course it would. But, would that have been created already? Or would it be created first when you actually run the Func? Lets say you have this: ``` public static T FindOrCreate<T>(this Table<T> table, Func<T, bool> find, Func<T> replacement) where T : new() { T val = table.FirstOrDefault(find); if (val == null) { val = replacement(); table.InsertOnSubmit(val); } return val; } ``` And then called that by doing this: ``` var invoiceDb = ctx.Invoices.FindOrCreate(a => a.InvoicerId == InvoicerId && a.Number == invoiceNumber, () => new Invoice()); invoiceDb.Number = invoiceNumber; ``` If that invoice was found, would that new Invoice have been created? Or is that code ran not until the function is actually called? or how does that work?
In this case you're passing a delegate so the ``` () => new Invoice() ``` code is not called until the ``` val = replacement(); ``` line
The code in `replacement` wouldn't be run until the function was actually called, and the value was found to be missing in the table. By the way, if you implement this as stated, which is perfectly reasonable -- you might want to remove the "`where T : new()`" constraint from the function, since it's no longer necessary; you give it all the information about how to construct one quite explicitly.
Using new in a Func<T>
[ "", "c#", "generics", "function", "delegates", "" ]
I am using Microsoft's Unity for dependency injection and I want to do something like this: ``` IDataContext context = _unityContainer.Resolve<IDataContext>(); var repositoryA = _unityContainer.Resolve<IRepositoryA>(context); //Same instance of context var repositoryB = _unityContainer.Resolve<IRepositoryB>(context); //Same instance of context IDataContext context2 = _unityContainer.Resolve<IDataContext>(); //New instance var repositoryA2 = _unityContainer.Resolve<IRepositoryA>(context2); ``` `RepositoryA` and `RepositoryB` both have a constructor that takes an `IDataContext` parameter, and I want Unity to initialize the repository with the context that I pass it. Also note that `IDataContext` is not registered with Unity (I don't want 3 instances of `IDataContext`).
As of today they have added this functionality: It’s in the latest drop here: <http://unity.codeplex.com/SourceControl/changeset/view/33899> Discussion on it here: <http://unity.codeplex.com/Thread/View.aspx?ThreadId=66434> Example: ``` container.Resolve<IFoo>(new ParameterOverrides<Foo> { { "name", "bar" }, { "address", 42 } });" ```
< 2 cents> What if you later on decide to use a different service that requires more or less than just the context? The problem with constructor parameters and IoC is that the parameters are ultimately tied to the concrete type being used, as opposed to being part of the contract that the service interface defines. My suggestion would be that you either resolve the context as well, and I believe Unity should have a way for you to avoid constructing 3 instances of it, or you should consider a factory service that has a way for you to construct the object. For instance, what if you later on decide to construct a repository that doesn't rely on a traditional database at all, but instead use an XML file to produce dummy-data for the test? How would you go about feeding the XML content to that constructor? IoC is based around decoupling code, by tying in the type and semantics of the arguments to the concrete types, you really haven't done the decoupling correctly, there's still a dependency. "This code can talk to any type of repository possibly, as long as it implements this interface.... Oh, and uses a data context". Now, I know that other IoC containers have support for this, and I had it in my first version of my own as well, but in my opinion, it doesn't belong with the resolution step. < /2 cents>
Can I pass constructor parameters to Unity's Resolve() method?
[ "", "c#", ".net", "dependency-injection", "unity-container", "constructor-injection", "" ]
How to convert to PDF from my JSP/HTML file?. I want to convert a particular part of my webpage to a PDF file. Is it possible?
Yes. Take a good look at booth [Apache FOP](http://xmlgraphics.apache.org/fop/) and [iText](http://www.lowagie.com/iText/). No matter what you use, you'll probably have to do a little fiddling.
I used [HTMLDoc](https://www.msweet.org/projects.php?Z1) a couple of years ago and had pretty good luck with it.
JSP/HTML Page to PDF conversion
[ "", "java", "html", "jsp", "pdf", "" ]
The INSERT syntax I've been using is this ``` INSERT INTO TableName VALUES (...) ``` The UPDATE syntax I've been using is ``` UPDATE TableName SET ColumnName=Value WHERE ... ``` So in all my code, I have to generate 2 strings, which would result in something like this ``` insertStr = "(27, 'John Brown', 102)"; updateStr = "ID=27, Name='John Brown', ItemID=102"; ``` and then use them separately ``` "UPDATE TableName SET " + updateStr + " WHERE ID=27 " + "IF @@ROWCOUNT=0 "+ "INSERT INTO TableName VALUES (" + insertStr + ")" ``` It starts bothering me when I am working with tables with like 30 columns. Can't we generate just one string to use on both INSERT and UPDATE? eg. using insertStr above on UPDATE statement or updateStr on INSERT statement, or a whole new way?
Some DBMS' have an extension to do this but why don't you just provide a function to do it for you? We've actually done this before. I'm not sure what language you're using but it's probably got associative arrays where you can wrote something like: ``` pk{"ID"} = "27" val{"Name"} = "'John Brown'" val{"ItemID"} = "102" upsert ("MyTable", pk, val) ``` and, if it doesn't have associative arrays, you can emulate them with multiple integer-based arrays of strings. In our `upsert()` function, we just constructed a string (`update`, then `insert` if the `update` failed) and passed it to our DBMS. We kept the primary keys separate from our other fields since that made construction of the update statement a lot easier (primary key columns went in the where clause, other columns were just set). The result of the calls above would result in the following SQL (we had a different check for failed `update` but I've put your `@@rowcount` in for this example): ``` update MyTable set Name = 'John Brown', ItemID = 102 where ID = 27 if @@rowcount=0 insert into MyTable (ID, Name, ItemID) values ( 27, 'John Brown', 102 ) ``` That's one solution which worked well for us. No doubt there are others.
I think you need a whole new approach. You are open to **[SQL Injection](http://en.wikipedia.org/wiki/SQL_injection)**. Provide us with some sample code as to how you are getting your data inputs and sending the statements to the database. [alt text http://goose.ycp.edu/~weddins/440/S09%20IFS440%20Bobby%20Drop%20Tables.PNG](http://goose.ycp.edu/~weddins/440/S09%20IFS440%20Bobby%20Drop%20Tables.PNG)
SQL: Use the same string for both INSERT and UPDATE?
[ "", "sql", "insert", "sql-update", "" ]
I currently use this handy conversion extension method to do conversions between types: ``` public static T To<T>(this IConvertible obj) { return (T)Convert.ChangeType(obj, typeof(T)); } ``` However, it doesn't like converting valid values to Nullable, for example, this fails: ``` "1".To<int?>(); ``` Obviously, 1 is easily converted to an (int?), but it gets the error: ``` Invalid cast from 'System.String' to 'System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. ``` This is an obviously simplified example, in reality I'm using it to do conversions from string types like so: ``` packageDb.Quantity = package.package.ElementDeep(Namespace + "PackageQuantity", Namespace + "ActualQuantity", Namespace + "Quantity").ValueOrNull().To<int?>(); ``` If Convert.ChangeType doesn't like Nullable, anyone have any great ideas?
``` public static T To<T>(this IConvertible obj) { Type t = typeof(T); Type u = Nullable.GetUnderlyingType(t); if (u != null) { return (obj == null) ? default(T) : (T)Convert.ChangeType(obj, u); } else { return (T)Convert.ChangeType(obj, t); } } ```
``` public static T To<T>(this IConvertible obj) { Type t = typeof(T); if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) t = t.GetGenericArguments()[0]; return (T)Convert.ChangeType(obj, t); } ``` But if the conversion fail, it will throw an exception, not returning a null as should be expected.
How can I fix this up to do generic conversion to Nullable<T>?
[ "", "c#", "nullable", "" ]
I try to store a draft e-mail via IMAP to a folder running on MS Exchange. Everything ok, except that Bcc recipients don't get shown in the draft message stored on the server. Bcc recipients also don't receive the email if I send it with MS Outlook. If I read the message back with Python after I have stored it on the server, I can see the Bcc in the draft. The following Python code reproduces this behavior: ``` import imaplib import time from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText message = MIMEMultipart() message['Subject'] = 'Test Draft' message['From'] = 'test@test.net' message['to'] = 'test@test.com' message['cc'] = 'testcc@test.com' message['bcc'] = 'testbcc@test.com' message.attach(MIMEText('This is a test.\n')) server= imaplib.IMAP4('the.ser.ver.ip') server.login('test', 'test') server.append("Drafts" ,'\Draft' ,imaplib.Time2Internaldate(time.time()) ,str(message)) server.logout() ``` If I run this code, a draft gets stored into the `Draft` folder on the Exchange Server. But if I look at the draft with MS Outlook, it does not include the `bcc` recipient (`message['bcc'] = 'testbcc@test.com'`). `Message`, `to`, `from`, `cc` ok, no error. If I download drafts that already include a bcc from an Exchange folder, I can also see the bcc. Only uploading doesn't work for me. Any help very much appreciated. Thanks. BTW, MAPI is not an option. **Update**: `X-Receiver` didn't work for me. As for playing around with an IMAP-Folder in Outlook, I got an interesting result. If I access the draft via the IMAP-Folder in Outlook, I see the bcc. But if I access it via the MAPI-Folder, I don't see it. Will play a little bit around with that. **Conclusion**: Actually, the code works just fine. See below for the answer that I found.
Actually, the code works just fine. It creates the proper mail with all the right headers including bcc. **How does the mail client display bcc?** The [mail client](http://en.wikipedia.org/wiki/E-mail_client) (e.g. Python or MS Outlook via IMAP or MAPI in my case) decides whether and how to display bcc-headers. Outlook for example doesn't display bcc headers from an IMAP folder. This is a feature to hide bcc recipients from each other where they have not been stripped away from the mail before (it is not clear from the standard whether one bcc recipient is allowed to see all other bcc recipients or not, see [Wikipedia](http://en.wikipedia.org/wiki/Blind_carbon_copy#Visibility)). **Who handles bcc upon sending an email?** Suppose now that we have drafted a message in a mail client and stored it in an IMAP or MAPI folder. The server providing the IMAP / MAPI folders leaves the draft message unchanged. What happens to the bcc-headers upon sending the mail is implementation dependent, and might depend both on the mail client and the [mail transfer agent](http://en.wikipedia.org/wiki/Mail_transfer_agent) (e.g. MS Exchange Server in my case). In a nutshell, people do not agree whether the mail client or the mail transfer agent is reponsible for removing bcc headers. It seems however to be the case that a majority of developers is of the opinion that it is the mail client's business with the mail transfer agent not touching the mail (e.g. MS Exchange, MS SMTP, Exim, OpenWave). In this case, the mail transfer agent sends the email to the recipient as defined in the `RCPT TO:` of the [SMTP](http://en.wikipedia.org/wiki/SMTP) communication, and leaves the email unchanged otherwise. Some other mail transfer agents strip bcc headers from emails however (e.g. sendmail, Lotus Notes). A very thorough discussion can be found on the Exim mailing list starting [here](http://lists.exim.org/lurker/message/20040722.043422.7a079b9f.hu.html#exim-dev). In the case of MS Outlook and MS Exchange, MS Outlook never sends bcc (but sends individual emails for each bcc recipient) and MS Exchange does not touch the email headers, but sends the full email (possibly including bcc recipients) to the recipients defined in `RCPT TO:`. **Conclusion** I did not understand that there is no guaranteed behavior for bcc, and that usually the client handles bcc. I will rewrite my Python code to loop over bcc recipients and generate one email for each bcc recipient.
It could be that way by design. After all, the whole point of bcc is that the recipients are hidden from each other. I understand that you are not sending the e-mail, just storing it. But my guess is that Exchange's internal rules kick in when the message is IMAP.appended to the folder, causing the bcc field to be stripped away. Obviously, when messages are saved to a folder using Outlook the bcc field is **not** stripped away. But I guess outlook communicates with Exchange using some internal mechanizm (MAPI?). All the above is just guesswork. Something fun you could try: * In an empty Outlook/MAPI profile, create a IMAP account. Set it up to store Drafts and Sent Items on the Exchange server. * See if outlook using IMAP can save bcc of Drafts correctly. I tried the above using the Evolution e-mail client connected to Exchange over IMAP. Using outlook (connected the normal way), I then had a look in Drafts and Sent Items. The bcc field was missing in both places. I belive this supports my theory.
Python: how to store a draft email with BCC recipients to Exchange Server via IMAP?
[ "", "python", "email", "exchange-server", "imap", "bcc", "" ]
I am attemptting to attach a small CMS to a website I am creating. However I have come across a small problem. The CMS uses PHP functions for inserting menus, these PHP functions create the HTML. The particular function I wish to use (treemenu) creates a nested ul li that can then be used for a drop down menu. However the nested ul li is structured like so: ``` <li>Projects (Menu Level 1)</li> <ul> <li>Project 1 (Menu Level 2)</li> <li>Project 2 (Menu Level 2)</li> <li>Project 3 (Menu Level 2)</li> </ul> <li>News (Menu Level 1)</li> <li>Contact (Menu Level 1)</li> ``` When creating a drop down menu in CSS I believe the Menu Level 1 li should wrap its children like so: ``` <li>Projects (Menu Level 1) <ul> <li>Project 1 (Menu Level 2)</li> <li>Project 2 (Menu Level 2)</li> <li>Project 3 (Menu Level 2)</li> </ul> </li> <li>News (Menu Level 1)</li> <li>Contact (Menu Level 1)</li> ``` I have never before worked with PHP and therefore would not know how to alter the function in order to accomplish the above. I would hope it would be a simple change. Below is the PHP function that outputs the first example structure: ``` function treemenu($generat=0) { global $pagenum, $menu, $selected, $extension, $set; $count=0; $out="\n"; $intend=0; while($menu[$count][0] != "") { if(strpos($menu[$count][3],"#") === false) { if($menu[$count][2]=="0" && $intend==2) { $intend--; $out.="</ul>\n"; } if($menu[$count][1]=="0" && $intend==1) { $intend--; $out.="</ul>\n"; } if($menu[$count][1]!="0" && $intend<1) { $intend=1; $out.="<ul>\n"; } if($menu[$count][2]!="0" && $intend<2) { $intend=2; $out.="<ul>\n"; } $out.="<li class=\"LNE_menu\"><a "; if($menu[$count][4]==$selected['name']) $out.= 'class="selected" '; if(strpos($menu[$count][3],"*")) $out.='href="'.str_replace("*", "",$menu[$count][3]).'">'; elseif($generat) $out.='href="'.$menu[$count][3].".".$set['extension'].'">'; else $out.='href="'.$set['indexfile'].'?page='.$menu[$count][3].'">'; $out.=$menu[$count][4]."</a></li>\n"; } $count++; } return $out; } ``` Could anyone possibly point me in the right direction as to how to make the closing li tag of a level 1 menu item wrap the ul immediately after, as in the second example?
This would be a excellent example of the use of recursion. An array (with sub-arrays within it) defines each level, and a function loops, calling itself whenever it finds a new array to process. As long as the function cleans up appropriately (closing the `</li> & </ol>`), it's largely automatic. ``` <?php // I know which function I'd rather write.... $tree = array('Projects (Menu Level 1)', array('Project 1 (Menu Level 2)', 'Project 2 (Menu Level 2)', 'Project 3 (Menu Level 2)'), 'News (Menu Level 1)', 'Contact (Menu Level 1)'); // now quake beneath the power of this fully operational recursive function! function olLiTree($tree) { echo '<ul>'; foreach($tree as $item) { if (is_array($item)) { olLiTree($item); } else { echo '<li>', $item, '</li>'; } } echo '</ul>'; } olLiTree($tree); // kick off from the top level ```
It appears Topbit already beat me to this, but mine is *slightly* differs in that it doesn't echo the value straight to the output stream, but saves it in a variable that you may `echo` at your convenience: ``` <?php function GenerateMenu($arr) { $output = "<ul>\n"; foreach($arr as $val) { if (is_array($val)) { $output .= "<li>\n" . GenerateMenu($val, $output) . "</li>\n"; } else { $output .= "<li>" . $val . "</li>\n"; } } $output .= "</ul>\n"; return $output; } $html = GenerateMenu($menu); ?> ``` **Edit:** Thanks Gumbo and Topbit, now that I'm on my machine with PHP installed, I have tested it and it works fine.
PHP function that creates a nested ul li?
[ "", "php", "css", "function", "" ]
Autoboxing seems to come down to the fact that I can write: ``` Integer i = 0; ``` instead of: ``` Integer i = new Integer(0); ``` So, the compiler can automatically convert a primitive to an Object. Is that the idea? Why is this important?
You kind of simplified it a little too much. **Autoboxing also comes into play when using collections. As explained in sun's java docs:** > Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class. **...** When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter. > > So when should you use autoboxing and unboxing? Use them only when there is an “impedance mismatch” between reference types and primitives, for example, when you have to put numerical values into a collection. It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it. [Great overview of Autoboxing](http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html)
BTW ``` Integer i = 0; ``` is equivalent to ``` Integer i = Integer.valueOf(0); ``` The distinction is that valueOf() does not create a new object for values between -128 and 127 (Apparently this will be tunable if Java 6u14)
Autoboxing: So I can write: Integer i = 0; instead of: Integer i = new Integer(0);
[ "", "java", "autoboxing", "" ]
I am writing a concurrent, persistent message queue in C++, which requires concurrent read access to a file without using memory mapped io. Short story is that several threads will need to read from different offsets of the file. Originally I had a file object that had typical read/write methods, and threads would acquire a mutex to call those methods. However, it so happened that I did not acquire the mutex properly somewhere, causing one thread to move the file offset during a read/write, and another thread would start reading/writing to an incorrect part of the file. So, the paranoid solution is to have one open file handle per thread. Now I've got a lot of file handles to the same file, which I'm assuming can't be great. I'd like to use something like [pread](http://linux.about.com/library/cmd/blcmdl2_pread.htm), which allows passing in of the current offset to read/write functions. However, the function is only available on linux, and I need equivalent implementations on windows, aix, solaris and hpux, any suggestions?
On Windows, the [ReadFile()](http://msdn.microsoft.com/en-us/library/aa365467(VS.85).aspx) function can do it, see the `lpOverlapped` parameter and [this info on async IO](http://msdn.microsoft.com/en-us/library/ms686358(VS.85).aspx).
With NIO, `java.nio.channels.FileChannel` has a `read(ByteBuffer dst, long position)` method, which internally uses `pread`. Oh wait, your question is about C++, not Java. Well, I just looked at the JDK source code to see how it does it for Windows, but unfortunately on Windows it isn't atomic: it simply seeks, then reads, then seeks back. For Unix platforms, the punchline is that `pread` is standard for any XSI-supporting (X/Open System Interface, apparently) operating system: <http://www.opengroup.org/onlinepubs/009695399/functions/pread.html>
Are there equivalents to pread on different platforms?
[ "", "c++", "file", "file-io", "cross-platform", "" ]
We are discussing whether it's a good idea to switch from plain portlet development on a liferay installation to spring webmvc portlet based development. We're starting the development of some portlets soon, so now is the time. But the problem I see is that we'd like to use some of the portlet 2.0 features, which won't work with versions older than spring 3.0. (Right?) Has anyone insight, if it's worth the waiting? (When is 3.0 scheduled anyway?) Is the current milestone stable enough? Our first real release will be in the last quarter of the year, so the springsource guys have some time left to get a final out of the door... ;-) Any ideas? **UPDATE** So, Spring 3 has been released and it supports all JSR286 features we need. (I think it's a pretty complete support for the JSR286 features) The only drawback I am seeing is the documentation which is not up to speed in regard to the annotations.
We use Spring Portlet MVC 2.5 on Liferay and we have excellent results. Most of JSR-286 functionality(like events) can be reached be extending DispatcherPortlet class. There is still a lot of bugs open for upcoming 3.0 release, so I would be rather conservative and stay with stable&mature version 2
Juergen Hoeller gave Jul 2008 as the estimated release date for Spring 3.0: <http://www.springify.com/archives/15> I think they're late. 8) Matt Raible lamented the fact in Oct 2008, almost six months ago: <http://raibledesigns.com/rd/entry/the_colorado_software_summit_and> I wonder if the new professional versus open source model has affected availability. They also have the Spring DM, Spring Blaze, and Spring Integration work going on now. Given their past history of quality releases, I'd bet that they're resisting the urge to release early in order to make certain the code is up to their standards.
portlet 2.0 (jsr286) development with spring
[ "", "java", "spring", "spring-mvc", "portlet", "jsr286", "" ]
I have several lines of a method that I would like to ensure that there is no context switch to another thread while executing these? Yes, re-architecting is an option but it would be far more expedient for now if I could do this. Is this possible? If not then does anyone know the reasoning behind the decision? **Edit:** The reason I am asking is that I have a class responsible for returning a value, the value is provided via an event so when GetValue() is called, the thread needs to block until the event is raised. So we have: ``` public class ValueResolver { IPersistentNotifier _notifier; IValueMonitor _monitor; Value _value; ManualResetEvent _resolvedEvent = new ManualResetEvent(false); public ValueResolver(IPersistentNotifier notifier, IValueMonitor monitor) { _notifier = notifier; _monitor = monitor; _monitor.ValueAcquired += ValueAcquired; } public Value GetValue() { _value = null; persistentNotifier.Show("Getting Value") _monitor.Start(); _resolvedEvent.WaitOne(60000, false); return _value } public void ValueAcquired(Value val) { _value = val; _monitor.Stop(); _notifier.Hide(); _resolvedEvent.Set(); } } ``` Only way I can think of writing a test for this is something like (in rhino mocks) ``` var monitor = MockRepository.GetMock<IValueMonitor>() monitor.Expect(x=>x.Start()).Do(new Action(() => { Thread.Sleep(100); monitor.Raise(y=>y.ValueAcquired, GetTestValue()); }); ``` but any suggestions are welcomed.
No, you can't. You can use a lock to make sure that no other threads will enter sensitive pieces of code to do with your operation, but that's all. As for the "why" - it's generally not needed, and would be slightly strange in a pre-emptive operating system on a relatively high-level platform. It may be possible in driver code, but it's not usually needed in user code. Note that "other threads running" doesn't necessarily mean a context switch anyway, given multi-core and multi-processor machines. EDIT: Despite your edit, I still don't see why it's a problem for there to be a context switch. If the thread has to block anyway, it's pretty much *bound* to context switch to a different thread. I agree it's a slightly annoyance that you have to wait for (say) 100ms or so to be confident that your test will have let everything happen on the other thread that you need, but you definitely *don't* need to ensure that it won't context-switch.
Context switch is the method by which OS tries to be "fair" to the all threads\processes executing in the system. Based on the OS, for instance Windows, implements the priority based preemptive scheduling. Preemptive scheduling means if the higher priority thread is ready for execution then current thread has to leave the CPU. Writing an atomic code means interrupting the OS scheduling, which OS doesn't allow. Also, Scheduling in Windows event driven. You cannot hold the CPU unless there are no waiting threads of same\higher priority.
Is there a way to enforce an atomic operation with no context switch in c#?
[ "", "c#", ".net", "multithreading", "" ]
This seems like something that should be easy, but I am having a tough time figuring out what needs to happen here. In the "KeyDown" eventhandler, if the "e.KeyValue" is a number, I want to treat it as a number and store it as an int. So, if I hit "8" on the number pad, I don't want "Numpad8" I want the int value 8 that I can add or subtract or whatever. So, how do I convert from the KeyValue to an int?
I'd go with this solution: ``` int value = -1; if (e.KeyValue >= ((int) Keys.NumPad0) && e.KeyValue <= ((int) Keys.NumPad9)) { // numpad value = e.KeyValue - ((int) Keys.NumPad0); } else if (e.KeyValue >= ((int) Keys.D0) && e.KeyValue <= ((int) Keys.D9)) { // regular numbers value = e.KeyValue - ((int) Keys.D0); } ``` ...if the point was to get the numeric value of the label of they key that was punched in.
Facts: Keyboard has keys. Some keys represent numbers and some do not. Problem (rephrased): Yield a numeric value represented by a key, if the key represents a number. To solve the problem it is necessary to know which keys (out of set of all keys) represent numbers as well as exact numeric value each (number) key represents. To my knowledge there is no an easy way to get such a mapping from the framework. Note: The fact D0-D9 and NumPad0-NamPad9 are sequential in the Keys enum is accidental and relying on these values being ordered sequentially is unfounded. So solution would be: 1. Determine if given key represents a number. 2. Return numeric value of the key if key represents a number. --- ``` private static readonly IDictionary<Keys, int> NumericKeys = new Dictionary<Keys, int> { { Keys.D0, 0 }, { Keys.D1, 1 }, { Keys.D2, 2 }, { Keys.D3, 3 }, { Keys.D4, 4 }, { Keys.D5, 5 }, { Keys.D6, 6 }, { Keys.D7, 7 }, { Keys.D8, 8 }, { Keys.D9, 9 }, { Keys.NumPad0, 0 }, { Keys.NumPad1, 1 }, { Keys.NumPad2, 2 }, { Keys.NumPad3, 3 }, { Keys.NumPad4, 4 }, { Keys.NumPad5, 5 }, { Keys.NumPad6, 6 }, { Keys.NumPad7, 7 }, { Keys.NumPad8, 8 }, { Keys.NumPad9, 9 } }; private int? GetKeyNumericValue(KeyEventArgs e) { if (NumericKeys.ContainsKey(e.KeyCode)) return NumericKeys[e.KeyCode]; else return null; } ``` Arguably, not the simplest solution, but the one that models the solution closely.
How do I convert a "Keys" enum value to an "int" character in C#?
[ "", "c#", "winforms", "keydown", "" ]
I'm trying to dynamically load modules I've created. Right now this works properly: ``` import structures.index ``` But if I try the same thing by importing it dynamically, it fails. ``` struct = __import__("structures.index") ``` Error supplied is: ``` Error ('No module named structures.index',) ``` Any ideas why? --- Edit: When using full scope (it sort of works?): ``` struct = __import__("neoform.structures.index") ``` This doesn't throw any errors, however, it isn't loading the index module, it's loading the "neoform" module instead. The result of "struct" is: ``` <module 'neoform' from '/neoform/__init__.py'> ``` Also, as a side question, how can I then instantiate a class within a dynamically loaded module? (assuming all the modules contain a common class name). Edit: Solution: (thanks coonj & Rick) This ended up being what worked. Not sure why (yet), but the `fromlist` had to be something "anything apparently, since it worked when I put the letter "a" as a value (strange, given that the file only had 1 class in it). ``` def get_struct_module(self, name): try: return = __import__("neoform.structures." + name, fromlist='*') except ImportError, e: self.out.add("Could not load struct: neoform.structure." + name + "\n\n" + "Error " + str(e.args)) ```
I'm not sure what "it fails" means, so I'll just mention that `__import__('structures.index')` should, in fact, work, but it doesn't assign the module name in the current scope. To do that (and then use a class in the dynamically imported module), you'll have to use: ``` structures = __import__('structures.index') structures.index.SomeClass(...) ``` The complete details on `__import__` are available [here](http://docs.python.org/library/functions.html#__import__). **Edit: (based on question edit)** To import `neoform.structures.index`, and return the `index` module, you would do the following: ``` structures = __import__('neoform.structures.index', fromlist=['does not in fact matter what goes here!']) ``` So if you have a list of package names `packages`, you can import their `index` modules and instantiate some `MyClass` class for each using the following code: ``` modules = [ __import__('neoform.%s.index' % pkg, fromlist=['a']) for pkg in packages ] objects = [ m.MyClass() for m in modules ] ```
To import sub-modules, you need to specify them in the `fromlist` arg of `__import__()` Fo example, the equivalent of: ``` import structures.index ``` is: ``` structures = __import__('structures', fromlist=['index']) ``` To do this in a map is a little more tricky... ``` import mod1.index import mod2.index import mod3.index ``` For those imports, you would want to define a new function to get the `index` sub-module from each module: ``` def getIndexMods(mod_names): mod_list = map(lambda x: __import__(x, fromlist='index')) index_mods = [mod.index for mod in mod_list] return index_mods ``` Now, you can do this to get references to all index modules: ``` index_mods = getIndexMods(['mod1', 'mod2', 'mod3']) ``` Also, if you want to grab sub-modules that are not named 'index' then you could do this: ``` mod1, mod2, mod3 = map(lambda x,y: __import__(x, fromlist=y), ['mod1', 'mod2', 'mod3'], ['index1', 'index2', 'index3']) ```
Dynamic Loading of Python Modules
[ "", "python", "dynamic", "module", "loading", "" ]
We would like to hook calls to LoadLibrary in order to download assemblies that are not found. We have a handler for ResolveAssembly that handles the managed assemblies, but we also need to handle unmanaged assemblies. We have attempted to hook LoadLibrary calls by re-writing the imports table via techniques specified in "Programming Applications for Microsoft Windows", but when we call WriteProcessMemory() we get a permission denied error (998). (Yes, we're running with elevated privs) Has anyone succeeded in re-writing the imports table while the CLR is loaded? Can anyone point me in the right direction? **Update:** We resolved the permission denied issue, but now when we iterate the Imports Table of a mixed assembly (managed + unmanaged), the only entry we find is mscoree.dll. Does anyone know how to find the native imports? (*we're working in C++/CLI*).
I have successfully hooked from Managed code. However, I did it by injecting an unmanaged DLL into the remote process and have it rewrite the import table in DllMain. You may want to consider this method. Here is my hooking function: ``` //structure of a function to hook struct HookedFunction { public: LPTSTR moduleName; LPTSTR functionName; LPVOID newfunc; LPVOID* oldfunc; }; BOOL Hook(HMODULE Module, struct HookedFunction Function) { //parse dos header IMAGE_DOS_HEADER* dos_header = (IMAGE_DOS_HEADER*)Module; if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) return 0; //not a dos program //parse nt header IMAGE_NT_HEADERS* nt_header = (IMAGE_NT_HEADERS*)(dos_header->e_lfanew + (SIZE_T)Module); if (nt_header->Signature != IMAGE_NT_SIGNATURE) return 0; //not a windows program //optional header (pretty much not optional) IMAGE_OPTIONAL_HEADER optional_header = nt_header->OptionalHeader; if (optional_header.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) return 0; //no optional header IMAGE_IMPORT_DESCRIPTOR* idt_address = (IMAGE_IMPORT_DESCRIPTOR*)(optional_header.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress + (SIZE_T)Module); if (!optional_header.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size) return 0; //no import table //enumerate the import dlls BOOL hooked = false; for(IMAGE_IMPORT_DESCRIPTOR* i = idt_address; i->Name != NULL; i++) //check the import filename if (!_stricmp(Function.moduleName, (char*)(i->Name + (SIZE_T)Module))) //enumerate imported functions for this dll for (int j = 0; *(j + (LPVOID*)(i->FirstThunk + (SIZE_T)Module)) != NULL; j++) //check if the function matches the function we are looking for if (!_stricmp(Function.functionName, (char*)(*(j + (SIZE_T*)(i->OriginalFirstThunk + (SIZE_T)Module)) + (SIZE_T)Module + 2) )) { //replace the function LPVOID* memloc = j + (LPVOID*)(i->FirstThunk + (SIZE_T)Module); if (*memloc != Function.newfunc) { //not already hooked DWORD oldrights; DWORD newrights = PAGE_READWRITE; VirtualProtect(memloc, sizeof(LPVOID), newrights, &oldrights); if (Function.oldfunc && !*Function.oldfunc) *Function.oldfunc = *memloc; *memloc = Function.newfunc; VirtualProtect(memloc, sizeof(LPVOID), oldrights, &newrights); } hooked = true; } return hooked; } ```
Should work, but try using [detours](http://research.microsoft.com/en-us/projects/detours/) (or the free [N-CodeHook](http://www.newgre.net/ncodehook)) instead. Detours is almost the de-facto way of instrumenting Win32 binaries.
Hook LoadLibrary call from managed code
[ "", ".net", "c++", "loadlibrary", "" ]
How can I merge two MySQL tables that have the same structure? The primary keys of the two tables will clash, so I have take that into account.
You can also try: ``` INSERT IGNORE INTO table_1 SELECT * FROM table_2 ; ``` which allows those rows in table\_1 to supersede those in table\_2 that have a matching primary key, while still inserting rows with new primary keys. Alternatively, ``` REPLACE INTO table_1 SELECT * FROM table_2 ; ``` will update those rows already in table\_1 with the corresponding row from table\_2, while inserting rows with new primary keys.
It depends on the semantic of the primary key. If it's just autoincrement, then use something like: ``` insert into table1 (all columns except pk) select all_columns_except_pk from table2; ``` If PK means something, you need to find a way to determine which record should have priority. You could create a select query to find duplicates first (see [answer by cpitis](https://stackoverflow.com/questions/725556/how-can-i-merge-two-mysql-tables/725571#725571)). Then eliminate the ones you don't want to keep and use the above insert to add records that remain.
How can I merge two MySQL tables?
[ "", "sql", "mysql", "merge", "" ]
I am creating a web application using Netbeans and servlets. I have used some css into my pages. Is there a way how I can put the banner and menu which every servlet will have in one place so I do not need to rewrite this in every servlet? Thank you
With facelets this would be cake. Since you are using servlets, try making a base Servlet class that just contains the header, menu, etc. code. Then, have each child override, say, getBody: Here is the parent (pseudocode): ``` class Template extends HttpServlet { doGet() { write getHeader(); write getMenu(); write getBody(); } } class SamplePage extends Template { getBody() { //put body HTML here } } ``` Then each child will be templated by Template.
Include a JSP file containing the common fragments, e.g. ``` <%@include page="..." /> ``` You could also set up a common header/footer arrangement and include the top and bottom bits at the start and end of each file.
Some sort of master page for java servlet using css
[ "", "java", "css", "web-applications", "master-pages", "" ]
I am working on a library where we want to determine how much of our library is being used. I.E. we want to know how many methods in our library are public, but never being called. Goal: Static Analysis Determine how many lines of code call each public method in package A in the current project. If the number of calls is zero, the method should be reported as such.
I belive you are looking for this eclipse plugin --> [UCDetector](http://www.ucdetector.org/) From the documentation (pay notice to second bullet point) * Unnecessary (dead) code * **Code where the visibility could be changed to protected, default or private** * Methods of fields, which can be final On Larger scale, if you want to do Object Level Static Analysis, look at this tool from IBM -->[Structural Analysis for Java](http://www.alphaworks.ibm.com/tech/sa4j). It is really helpful for object analysis of libraries, APIs, etc.
Not exactly what you are looking for, but: Something similar be done with code coverage tools (like [Cobertura](http://cobertura.sourceforge.net/)). They do not do static inspection of the source code, but instrument the bytecode to gather metrics at runtime. Of course, you need to drive the application in a way that exercises all usage pattern, and might miss the rarer code paths. On the static analysis front, maybe these tools can help you (the Apache project uses them to check for API compatibility for new releases, seems like that task is somewhat related to what you are trying to do): * [Clirr](http://clirr.sourceforge.net/) is a tool that checks Java libraries for binary and source compatibility with older releases. Basically you give it two sets of jar files and Clirr dumps out a list of changes in the public api. * [JDiff](http://jdiff.sourceforge.net/) is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.
Java Code Use Checker
[ "", "java", "code-coverage", "static-analysis", "" ]
I'm trying to use a dynamic order by in a stored procedure so I can pass the order I want the data returned into the stored procedure as a parameter. This works fine for VARCHAR fields however if I try to sort an int or datetime field it errors the code I have is as follows ``` DECLARE @ORDERBY INT SET @ORDERBY = 1 SELECT TOP 10 * FROM TBL_LMS_USERS_RECORDs_LAST_ATTEMPT ORDER BY CASE WHEN @OrderBy = 1 THEN s10_record_dow --WHEN @OrderBy = 2 THEN pk_big_record_id else s10_record_dow END ``` If I uncomment the second WHEN in the case statement it errors with > "Error converting data type varchar to bigint." I can order by this field fine if I dont use the case statement. Any ideas?
Change it to this: ``` SELECT TOP 10 * FROM TBL_LMS_USERS_RECORDs_LAST_ATTEMPT ORDER BY CASE WHEN @OrderBy = 1 THEN s10_record_dow ELSE NUll END, CASE WHEN @OrderBy = 2 THEN pk_big_record_id ELSE NULL END, CASE WHEN @OrderBy <> 1 AND @OrderBy <> 2 THEN s10_record_dow ELSE NULL END ```
Why not use ROW\_NUMBER()? ``` SELECT TOP 10 *, CASE @SortBy WHEN 'A' THEN ROW_NUMBER () OVER (ORDER BY s10_record_dow) WHEN 'B' THEN ROW_NUMBER () OVER (ORDER BY pk_id) END RowNumber FROM TBL_LMS_USERS_RECORDs_LAST_ATTEMPT ``` Then the columns you order by can be of any type.
SQL Server Dynamic Order By
[ "", "sql", "sql-server", "" ]
I'm using the official Sybase JDBC driver to connect to a database and call a stored procedure by creating a CallableStatement, binding the parameters to it and calling .execute() on it. However, I found that no exception is thrown, even if the stored procedure fails. I can verify that the failure is propagated back to me by sniffing the traffic to the database with Wireshark and observing the error messages coming back. Finally I found that using .executeUpdate() instead of .execute() *does* give me the exceptions, however I still have two questions left: 1. Why are .execute() and .executeUpdate() behaving differently? From the SUN documentation of the interface it seems that they should do (almost) the same thing... 2. Is it always appropriate to replace .execute() with .executeUpdate() when calling a stored procedure? Must the stored procedure conform to some particular requirements to be callable with .executeUpdate()? (for example, must it have an update/delete/insert statement as the last step?) *Update*: I've tried jTDS, and it behaves correctly (as in: it throws the SQLException in both cases - with .execute() and with .executeUpdate()). However, due to constraints beyond my control, switching out the driver is not really possible. Also: I'm no interested in the result returned by this stored procedure, it is an insert/update type procedure. I would only be inserted to see (and be able to catch / log) if it fails or not. An other thing I've tried is to get the warnings off the connection after .execute(), but it didn't contain anything either.
Because those Sybase people are crazy, that's why it eats Exceptions! There's no reason to avoid using executeUpdate() for prepared/callable statements. If that's what you've got to use to get it working then go ahead and do so. But you ought to file a bug report with Sybase - there's no reason the driver should be doing that.
not sure, whether the sybase people are "crazy". Maybe. On the other hand, not synchronuously retrieving results when you don't actively check for the return code of a callable statement may make sense performance-wise. I have not yet tested it completely, but there is a simple workaround to your problem (ASE 15.5, jconn 7): the exception will be triggered when you fetch an out param from the stored proc (at least when calling stored procedures): ``` // one may force the error check by retrieving the return code! cs = conn.prepareCall("{ ? = call sp_nested_error @nNestLevels = 1 }"); cs.registerOutParameter(1, Types.INTEGER); cs.execute(); try { cs.getInt(1); fail(); } catch(SQLException e) { assertTrue(e.getMessage().indexOf("some error") > -1); } ``` Another curiosity is that this behavior only shows up when errors are triggered in nested stored procedure calls and the workaround is not necessary when the top-most procedure raises the error.
Why is the Sybase JDBC driver "eating" the exceptions?
[ "", "java", "jdbc", "sybase", "sqlexception", "" ]
I have a GridView that gets populated with data from a SQL database, very easy. Now i want to replace values in my one column like so...... If c04\_oprogrs value is a 1 then display **Take** in the GridView. If c04\_oprogrs value is 2 then display **Available** in the GridView. What code changes must i make to change to my code to display the new values. My Grid ``` <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Height="281px" Width="940px" Font-Size="X-Small" AllowPaging="True" onpageindexchanging="GridView1_PageIndexChanging"> <Columns> <asp:BoundField DataField="c04_oprogrs" HeaderText="Order Progress" SortExpression="c04_oprogrs" /> <asp:BoundField DataField="c04_orderno" HeaderText="Order No." SortExpression="c04_orderno" /> <asp:BoundField DataField="c04_orddate" HeaderText="Date of Order" SortExpression="c04_orddate" DataFormatString="{0:d/MM/yyyy}" /> <asp:BoundField DataField="c04_ordval" HeaderText="Order Value" SortExpression="c04_ordval" DataFormatString="{0:R#,###,###.00}" /> <asp:BoundField DataField="c04_delval" HeaderText="Delivered Value" SortExpression="c04_delval" DataFormatString="{0:R#,###,###.00}" /> <asp:BoundField DataField="c04_invval" HeaderText="Invoice Value" SortExpression="c04_invval" DataFormatString="{0:R#,###,###.00}" /> <asp:BoundField DataField="c04_orddesc" HeaderText="Order Description" SortExpression="c04_orddesc" > <ControlStyle Width="300px" /> </asp:BoundField> </Columns> </asp:GridView> ``` My Page load ``` SqlConnection myConnection; DataSet dataSet = new DataSet(); SqlDataAdapter adapter; //making my connection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SAMRASConnectionString"].ConnectionString); adapter = new SqlDataAdapter("Select TOP 40 c04_credno, c04_orderno, c04_orddate, c04_ordval, c04_delval, c04_invval, c04_oprogrs, c04_orddesc FROM C04ORDS WHERE c04_credno = '" + Session["CreditorNumber"] + "'AND c04_oprogrs <> 9 ORDER BY c04_orddate DESC", myConnection); adapter.Fill(dataSet, "MyData"); GridView1.DataSource = dataSet; Session["DataSource"] = dataSet; GridView1.DataBind(); ``` Etienne **EDIT:** *MY FINAL SOLUTION* ``` protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { // Find the value in the c04_oprogrs column. You'll have to use string value = e.Row.Cells[0].Text; if (value == "1") { e.Row.Cells[0].Text = "Take"; } else if (value == "2") { e.Row.Cells[0].Text = "Available"; } } } ```
You can use the [`RowDataBound`](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx) event for this. Using this event you can alter the content of specific columns before the grid is rendered. To clarify a little. First you add a template column with a label to your grid view (see also the answer by ranomore): ``` <asp:TemplateField> <ItemTemplate> <asp:Label ID="myLabel" runat="server" /> </ItemTemplate> </asp:TemplateField> ``` Next you implement the `RowDataBound` event (I haven't checked the code below, so it may contain some syntax errors): ``` protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if(e.Row.RowType == DataControlRowType.DataRow) { // Find the value in the c04_oprogrs column. You'll have to use // some trial and error here to find the right control. The line // below may provide the desired value but I'm not entirely sure. string value = e.Row.Cells[0].Text; // Next find the label in the template field. Label myLabel = (Label) e.Row.FindControl("myLabel"); if (value == "1") { myLabel.Text = "Take"; } else if (value == "2") { myLabel.Text = "Available"; } } } ```
Without using a function. The ternary statement is in VB. If you have to nest another ternary statement to really test for 2 then it'd be easier to go with rwwilden's solution. ``` <asp:TemplateField HeaderText="Order Progress" SortExpression="c04_oprogrs" > <ItemTemplate> <asp:Label runat="server" ID="Label1" Text='<%# IIF(CInt(Eval("c04_oprogrs")) = 1, "Take", "Available") %>' /> </ItemTemplate> </asp:TemplateField> ```
Changing values inside my GridView on load with ASP.NET
[ "", "c#", "asp.net", "gridview", "" ]
Is it possible to overload a method on default parameters? For example, if I have a method split() to split a string, but the string has two delimiters, say '\_' and "delimit". Can I have two methods something like: ``` split(const char *str, char delim = ' ') ``` and ``` split(const char *str, const char* delim = "delimit"); ``` Or, is there a better way of achieving this? Somehow, my brain isn't working now and am unable to think of any other solution. Edit: The problem in detail: I have a string with two delimiters, say for example, nativeProbableCause\_Complete|Alarm|Text. I need to separate nativeProbableCause and Complete|Alarm|Text and then further, I need to separate Complete|Alarm|Text into individual words and join them back with space as a separator sometime later (for which I already have written a utility and isn't a big deal). It is only the separation of the delimited string that is troubling me.
How about implementing as 2 different methods like * `split_with_default_delimiter_space` * `split_with_default_delimiter_delimit` Personally I'd prefer using something like this (more readable.. intent conveying) over the type of overloading that you mentioned... even if it was somehow possible for the compiler to do that.
No, you cant - if you think about it, the notion of a default means 'use this unless I say otherwise'. If the compiler has 2 options for a default, which one will it choose?
Overloading a method on default arguments
[ "", "c++", "string", "delimiter", "" ]
To build a bind\_param dynamically, I have found this on other SO posts. ``` call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params); ``` Can someone break this down in plain english for me? I get especially lost that the first argument is an array.
``` array($stmt, 'bindparams') ``` is PHP's way of identifying method bind\_params on the object `$stmt`, since PHP 5 you don't need to use the `&` in front any longer (and mysqli is PHP 5 so this looks like a glitch in the older post). you can see a similar example [here](https://www.php.net/call_user_func_array) so ``` call_user_func_array(array($stmt, 'bindparams'), $array_of_params); ``` basically means ``` $stmt->bind_params($array_of_params[0], $array_of_params[1] ... $array_of_params[N]) ```
As far as I know, you cannot pass the result of e.g. `$userid == "ALL"` to a mysqli-statement-Object's bind\_param method, because this method wants the parameters to be passed by reference. Obviously this is not possible with the result of an expression evaluated "in place". As a workaround, I changed the program's second part to ``` $userIdEmpty = $userid == "ALL"; $locationEmpty = $location = "ALL"; $stmt->bind_param( "siiiii", "active", $userid, $userIdEmpty, $location, $locationEmpty, $limit); ``` Like that, the result of the boolean operation can be passed by reference.
What is a simple solution for dynamic mysqli bind_param arguments in PHP?
[ "", "php", "mysqli", "" ]
For diagnostic purposes I sometimes need to store the call stack that lead to a given state transition (such as granting a lock, committing a transaction, etc.) so that when something goes wrong later I can find out who originally triggered the state transition. Currently, the only way I am aware of to retrieve the call stack looks like the following code snippet, which I consider terribly ugly: ``` StackTraceElement[] cause; try { throw new Exception(); } catch (Exception e) { cause = e.getStackTrace(); } ``` Does somebody know of a better way to accomplish this?
I think you can get the same thing with: ``` StackTraceElement[] cause = Thread.currentThread().getStackTrace(); ```
Well, you can improve it slightly by not actually throwing the exception. ``` Exception ex = new Exception(); ex.fillInStackTrace(); StackTraceElement[] cause = ex.getStackTrace(); ``` Actually, I just checked: the constructor calls `fillInStackTrace()` already. So you can simplify it to: ``` StackTraceElement[] cause = new Exception().getStackTrace(); ``` This is actually what [`Thread.getStackTrace()`](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#getStackTrace()) does if it's called on the current thread, so you might prefer using it instead.
Determining Current Call Stack (For Diagnostic Purposes)
[ "", "java", "stack-trace", "" ]
If there is a difference, what is the difference between the two ways of doing the following cast? In this case `e` is a `GridViewRowEventArgs` object. ``` GridView gv = (GridView)e.Row.FindControl("gv"); //first way GridView gv2 = e.Row.FindControl("gv") as GridView; //second way ```
The differences are: * If a cast fails, it throws an [`InvalidCastException`](http://msdn.microsoft.com/en-us/library/system.invalidcastexception.aspx). * If the `as` operator fails, it just returns a null reference. * You can't use `as` with non-nullable value types (e.g. you can't do "`o as int`"). * The cast operator is also used for unboxing. (`as` can be used to unbox to a nullable value type.) * The cast operator can also perform user-defined conversions. EDIT: I've [written elsewhere](https://stackoverflow.com/questions/496096/casting-vs-using-the-as-keyword-in-the-clr/496167#496167) about when I feel it's appropriate to use which operator. That might be worth a read...
What isn't mentioned in the above answers is *intent* -- why are you performing the conversion, and (more importantly) what happens on the lines after the conversion? For example, I've seen code similar to the following a number of times: > `if ((foo as SomeType).SomeMethod()) { /* ... */ }` This could be compared to the cast-using version: > `if (((SomeType) foo).SomeMethod()) { /* ... */ }` So, which of these is better? The cast is. Using `as` will result in a `NullReferenceException` if the conversion fails. Using a cast will result in an `InvalidCastException` if the conversion fails. Now tell me, which is a more useful exception for debugging? A `NullReferenceException`, which could be produced by nearly anything, or an `InvalidCastException`, which lets you know what actually went wrong? Thus, *only* use `as` if the conversion is *actually* optional (meaning that there *must* be a `null` check before using the variable). Otherwise, use a cast, thus making your intentions more explicit.
What is the difference between casting and using "as" in C#?
[ "", "c#", "" ]
I recently sped up a complicated query by an order of magnitude by giving SQLite a good index to work with. Results like this make me wonder if I should index a lot of other fields that are commonly used for JOINs or ORDER BY clauses. But I don't want to get overzealous and have it backfire on me: I assume there must be some reasons *not* to create indices, or every field would be indexed by default. I'm using SQLite in this case, but of course DBMS-agnostic advice is welcome as well.
Indexes slow down inserts and updates (which can become a really serious issue with locking) and cost disk space. That's pretty much it.
In order to test your particular application you can put "EXPLAIN QUERY PLAN" in front of any query you run and check the results. It will show you where it is or is not using indexes. That way you can determine where you could use more indexes and where they would not make a difference. [Sqlite Explain](http://www.sqlite.org/lang_explain.html) I use [SqliteSpy](http://www.yunqa.de/delphi/doku.php/products/sqlitespy/index) to hand test query's that seem to be causing trouble.
What are the disadvantages of having many indices?
[ "", "sql", "database", "sqlite", "indexing", "rdbms-agnostic", "" ]
what is the diff, advantage and disadvantage between remoting and socket... which is best way for Server-Client functionality....
Sockets are raw binary streams between two endpoints. You would need to wrap your own RPC (etc) layer to process the messages, and deal with a lot of infrastructure code. However, since they are so close to the metal this can be very, very efficient. It is not tied to any specific architecture, as long as both ends talk the same message format. Tools like protobuf-net can help you construct binary messages for streams (rather than rolling your own serialization code). Remoting is a .NET specific tool, and is very brittle re versioning. I wouldn't recommend remoting for client/server - use things like WCF instead. WCF is a more flexible comms stack - a lot of power and complexity, but arguably a bit of bloat too (xml, complex security etc). It is data-contract based, so *roughly* open (client/server can be different), but still a bit .NET focused. --- **edit** For info, [protobuf-net](http://code.google.com/p/protobuf-net/) provides an RPC stack too; at the moment there is only an HTTP implementation provided, but at some point I'll add raw TCP/IP.
Direct socket manipulation can give you more power, flexibility, performance, and unfortunately complexity when compared to Remoting or WCF. However, if you need the benefits of low-level TCP/IP, such as non-blocking IO and custom protocols, tools such as [Ragel](http://www.complang.org/ragel/) and frameworks like [Mina](http://mina.apache.org/) can ease the complexity burden. I recommend trying the higher-level APIs like WCF first and only use direct sockets if these don't meet your needs.
remoting vs socket
[ "", "c#", "" ]
I have query build from Visual Studio 2005. I am inserting records from SQL database to Access. My query is ``` insert into i_mails (id,from_mails,to_mails,cc_mails,subject,body, anchor_level_id,attachment,forward_status ,reply_status,delete_status, read_status, received_date,response_date, batch,forward_score,delete_score,priority, is_auto_reply,parent_mail_id,case_id,time_bound) values (1,'a@a.com', 'a@a.com','a@a.com', 'Hi','--long html field--', 7 , 'True' ,False,False,False,False, #12/12/2000 00:00:00# ,#12/12/2000 00:00:00#, 0, '0','0', 1 , 'False',0,2,0) ``` I get Data Type Mismatch in criteria expression Error.. Not knowing where this error is firing in Query ... Please Help !! Access Database Structure: Id - Number, from\_mails - Memo, to\_mails - Memo, cc\_mails - Memo, subject - Memo, body - Memo, anchor\_level\_id - Number, attachment -Yes\No, forward\_status - Yes\No, reply\_status - Yes\No, delete\_status - Yes\No, read\_status - Yes\No, received\_date - DateTime, response\_date - DateTime, batch - Number, forward\_score - Number, delete\_score - Number, priority - Number, is\_auto\_reply - Yes\No, parent\_mail\_id - Number, case\_id - Number, time\_bound - Number,
For is\_auto\_reply, use 'false' without quotes. This seems to be the problem
Replace each value with a null (or other 'zero' value). Start with the first, then the second (leaving the first as null) and on until you have replaced all the values with nulls. test the query after each change. When the query starts working, the last value you changed is the one that is causing the problem. P.S. It may not be the only value that is incorrect, but using this method you will find all the badly typed values. Hope this helps
Insert query in Access
[ "", "sql", "ms-access", "" ]
I'm looking for a Java web framework that requires the most minimal amount of configuration for a very small app. Spring & Struts are definitely overkill here. This is an app that could be written without any framework at all but I would prefer to use a minimal MVC framework if I can find one.
[Stripes](http://www.stripesframework.org/) and [ZTemplates](http://en.wikipedia.org/wiki/Ztemplates) are supposed to be pretty light.
Checkout [spark](http://www.sparkjava.com/). Its as mimimalistic as it can get.
What's the most minimal Java web MVC framework?
[ "", "java", "model-view-controller", "web-frameworks", "" ]
I've spent the past few days working on updating my personal website. The URL of my personal website is (my first name).(my last name).com, as my last name is rather unusual, and I was lucky enough to pick up the domain name. My e-mail address is (my first name)@(my last name).com. So really, when it comes down to guessing it, it's not very hard. Anyways, I want to integrate a mailto: link into my website, so people can contact me. And, despite my e-mail address not being very hard to guess, I'd rather not have it harvested by spam bots that just crawl websites for e-mail address patterns and add them to their database. What is the best way for me to obfuscate my e-mail address, preferably in link form? The methods I know of are: ``` <a href="mailto:x@y.com">e-mail me</a> ``` It works, but it also means that as soon as my website hits Google, I'll be wading through spam as spam bots easily pick out my e-mail address. ``` <img src="images/e-mail.png" /> ``` This is less desirable, because not only will visitors be unable to click on it to send me an e-mail, but smarter spam bots will probably be able to detect the characters that the image contains. I know that there is probably no perfect solution, but I was just wondering what everyone thought was best. I'm definitely willing to use JavaScript if necessary, as my website already makes use of tons of it.
I encode the characters as HTML entities ([something like this](http://www.wbwip.com/wbw/emailencoder.html)). It doesn't require JS to be enabled and seems to have stopped most of the spam. I suppose a smart bot might still harvest it, but I haven't had any problems.
Personally, I've given up on hiding my email address. I find it easier to look into better spam-filtering solutions than worry about obfuscating. You could spend days trying to find the best way to obfuscate your address, and then all it takes is one person to sell your address to a spammer and all that work was useless.
Best way to obfuscate an e-mail address on a website?
[ "", "javascript", "html", "email", "obfuscation", "" ]
Why does `str(A())` seemingly call `A.__repr__()` and not `dict.__str__()` in the example below? ``` class A(dict): def __repr__(self): return 'repr(A)' def __str__(self): return dict.__str__(self) class B(dict): def __str__(self): return dict.__str__(self) print 'call: repr(A) expect: repr(A) get:', repr(A()) # works print 'call: str(A) expect: {} get:', str(A()) # does not work print 'call: str(B) expect: {} get:', str(B()) # works ``` Output: ``` call: repr(A) expect: repr(A) get: repr(A) call: str(A) expect: {} get: repr(A) call: str(B) expect: {} get: {} ```
`str(A())` does call `__str__`, in turn calling `dict.__str__()`. It is `dict.__str__()` that returns the value repr(A).
I have modified the code to clear things out: ``` class A(dict): def __repr__(self): print "repr of A called", return 'repr(A)' def __str__(self): print "str of A called", return dict.__str__(self) class B(dict): def __str__(self): print "str of B called", return dict.__str__(self) ``` And the output is: ``` >>> print 'call: repr(A) expect: repr(A) get:', repr(A()) call: repr(A) expect: repr(A) get: repr of A called repr(A) >>> print 'call: str(A) expect: {} get:', str(A()) call: str(A) expect: {} get: str of A called repr of A called repr(A) >>> print 'call: str(B) expect: {} get:', str(B()) call: str(B) expect: {} get: str of B called {} ``` Meaning that str function calls the repr function automatically. And since it was redefined with class A, it returns the 'unexpected' value.
Python base class method call: unexpected behavior
[ "", "python", "inheritance", "dictionary", "" ]
I'm having problems with our MSSQL database set to any of the Turkish Collations. Becuase of the "Turkish I" problem, none of our queries containing an 'i' in them are working correctly. For example, if we have a table called "Unit" with a column "UnitID" defined in that case, the query "select unitid from unit" no longer works because the lower case "i" in "id" differs from the defined capital I in "UnitID". The error message would read "Invalid column name 'unitid'." I know that this is occurring because in Turkish, the letter i and I are seen as different letters. However, I am not sure as to how to fix this problem? It is not an option to go through all 1900 SPs in the DB and correct the casing of the "i"s. Any help would be appreciated, even suggestions of other collations that could be used instead of Turkish but would support their character set.
Turns out that the best solution was to in fact refactor all SQL and the code. In the last few days I've written a refactoring app to fix up all Stored procs, functions, views, tablenames to be consistent and use the correct casing eg: ``` select unitid from dbo.unit ``` would be changed to ``` select UnitId from dbo.Unit ``` The app also then goes through the code and replaces any occurrences of the stored proc and its parameters and corrects them to match the case defined in the DB. All datatables in the app are set to invariant locale (thanks to FXCop for pointing out all the datatables..), this prevents the calls from within code having to be case sensitive. If anyone would like the app or any advice on the process you can contact me on dotnetvixen@gmail.com.
I developed so many systems with Turkish support and this is well known problem as you said. Best practice to do change your database settings to UTF-8, and that's it. It should solve the all problem. You might run into problems if you want to support case-sensitivity in (ı-I,i-İ) that can be a problematic to support in SQL Server. If the whole entrance is from Web ensure that is UTF-8 as well. If you keep your Web UTF-8 input and SQL Server settings as UTF-8 everything should goes smoothly.
Problems with Turkish SQL Collation (Turkish "I")
[ "", "sql", "sql-server", "collation", "turkish", "" ]
i'm working on a network programming assignment about writing a simple IM system (pretty much like the simplest version of windows messenger). the spec specifies that i must send over 4 fields of data in a single datagram packet, those are: ``` To From Type Message where type refers to message type, implemented as a user defined enum class. ``` I would like to be taught how to pack all these datas into a single packet. UPDATE: thx for the help so far, but say i have String sentence and String From the normal way to patch the packet individually would be ``` byte[] sendData = new byte [256] sendData = sentence.getBytes(); ``` but how exactly can i append the "from" string to sendData along with the sentence string?
Briefly, what you need to do is: 1. create an object (class) which contains your 4 fields (from/to/enum/message) 2. serialise this. It has to implement [Serializable](https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html). See other solutions here for how to serialise 3. convert to a byte array and send down the socket (see elsewhere for details) At the other end you'll read this bytestream, deserialise and cast it to an instance of your class defined in 1. above. By creating the one object containing the 4 fields and serialising this object, this allows you to send all four fields together (I get the impression that this is the stumbling block?). Note that datagrams will have size limits imposed by the network transport layers, but for this application I suspect that's not a problem.
You can send any Serializable object using something like this. ``` ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(objectYouWantToSend); out.close(); buffer.close(); DatagramPacket packet = new DatagramPacket(buffer.toByteArray(), buffer.size(), InetAddress.getByName(...), portNumber); socket.send(packet); ```
Send multiple data in 1 single UDP datagram
[ "", "java", "udp", "packets", "" ]
Forgive me if this has been asked before; I did a search but couldn't find anything that specifically answered this question, but I'd be happy to be referred. I'm taking a peek at both the Entity Framework and LINQ to SQL, and while I like the systems (and of course the LINQ integration) I'm a little skeptical on the data-binding aspect. I've taken query results and inspected them, and they don't appear to implement the standard .NET list-binding interfaces (`IBindingList`, and more importantly `ITypedList`), leading me to believe that binding them to a grid (or anything else) is going to use reflection to get/set my entity properties. This seems like a comparatively expensive operation, especially when all of the code is generated anyway and could implement the interfaces. Does anyone have any insight into this? Is reflection used to get/set the value of the properties? If yes, does this have a performance impact that's noticeable, and does anyone have any idea why they went this route? **Edit** I'm actually concentrating on whether or not `ITypedList` is implemented somewhere along the way, as that's what has the capability to provide an explicit mechanism for defining and interacting with properties without resorting to reflection. While I didn't have a LINQ to SQL project up, I did inspect a simple Entity Framework entity query result, and it did not appear to implement `ITypedList`. Does anyone know if I'm just looking at something incorrectly, or if not why this is the case? **Edit 2** After accepting Marc's answer, I thought it might be helpful for others if I posted some simple code I used to seamlessly implement his solution. I put the following in the static constructor for my class: ``` public static ContextName() { foreach(Type type in System.Reflection.Assembly.GetExecutingAssembly() .GetTypes()) { if (type.GetCustomAttributes(typeof(System.Data.Linq.Mapping .TableAttribute), true) != null) { System.ComponentModel.TypeDescriptor.AddProvider( new Hyper.ComponentModel.HyperTypeDescriptionProvider( System.ComponentModel.TypeDescriptor.GetProvider( type)), type); } } } ``` While this is for LINQ to SQL, I'm sure an equivalent version could be written for the Entity Framework. This will scan the assembly for any types with the `Table` attribute and add a custom provider for each of them.
The Expression API that underpins LINQ etc is founded on reflection (`MemberInfo`), not the component-model (`PropertyDescriptor` etc) - so there is not a huge requirement for `ITypedList`. Instead, the contents are inferred from the `T` in `IQueryable<T>`, `IEnumerable<T>` and `IList<T>` etc. The closest you might get is `IListSource`, but that will still just be a shallow wrapper around a proper typed list. If performance of runtime binding (to `PropertyDescriptor`) is key, you might want to look at [HyperDescriptor](http://www.codeproject.com/KB/cs/HyperPropertyDescriptor.aspx) - which uses `Reflection.Emit` and `TypeDescriptionProvider` to wrap the component-model. Re the "why" etc; note that in almost all cases with LINQ-to-SQL and EF the `Expression` (or the "create and set members" part) is going to be compiled to a delegate before it is invoked - so at runtime there is no huge reflection cost. And likewise, with LINQ-to-Objects everything is *already* compiled (by the C# compiler).
In my experience with LINQ to SQL, I have concluded for a few reasons that LINQ is using reflection to set and get field values in entity class instances. I don't know if I can remember all the reasons, but here's what I can tell you. 1. If I recall correctly, LINQ does not call any property procedures, but directly sets and reads all the private field values directly, which can only be done via reflection, as far as I know. 2. The names provided by the MetaData (in the attributes on the entity class properties) provide field name information in string form (if the database column and property name are different, for example). You can conclude from this that LINQ must be using reflection to look up the member to access it. I think it does this to enforce simplicity -- you can rely on the values in the fields in the entity class directly mirroring the database column values, and there's not much overhead in retrieving the object from the database (populating a newly created entity to correspond to values retrieved from the database should not be routed through property procedures). One thing I have done to represent enumerated values retrieved from the database, for example, is to make some of the LINQ-generated properties private and wrap them in a manually coded property in a partial class that reads and writes the LINQ property.
Does Entity Framework/LINQ to SQL Data Binding use reflection?
[ "", "c#", "vb.net", "linq-to-sql", "entity-framework", "reflection", "" ]
I'm just writing some data access code. I've decided to pass in the name of connection string from the config via constructor injection which the repository then reads and uses to construct a SqlConnectionStringBuilder. Thinking about it I probably don't need the SqlConnectionStringBuilder but that's a different matter. Should I be reading the configuration here or should that be confined to client code? Opinions? ``` public class SqlRepository : IRepository { private SqlConnectionStringBuilder _connString; public SqlRepository(string connectionStringName) { var connStringSetting = ConfigurationManager.ConnectionStrings[connectionStringName]; if (connStringSetting == null) throw new ArgumentException("Could not find connection string in configuration."); _connString = new SqlConnectionStringBuilder(connStringSetting.ConnectionString); } } ```
I'd perfer to pass an actual connection string (or even Dependency Inject it). Doing so helps maintaining [SoC](http://en.wikipedia.org/wiki/Separation_of_concerns) and [SRP](http://en.wikipedia.org/wiki/Single_responsibility_principle).
IF you pass the connection string into the DAL, you are making something out side of the data layer aware of the data base, which is a layer violation. Nothing outside of the DAL should have any knowledge of anything DB related, if you want to have the client set what connection string to use, then have them set the configuration, nothing more. If you want to decouple the connection string use the factory pattern, and let it worry about what connection string to use, single responsibility principal. You can use dependency injection, config file, etc.
Configuration reading, should it be confined to client code?
[ "", "c#", ".net", "configuration", "" ]
Another recent C# interview question I had was if I knew what Boxing and Unboxing is. I explained that value types are on Stack and reference types on Heap. When a value is cast to a reference type, we call it boxing and vice versa. Then he asked me to calculate this: ``` int i = 20; object j = i; j = 50; ``` What is `i`? I messed it up and said 50, where its actually 20. Now I think understand it why, however when I was playing with different combinations I was surprised to see this: ``` Object a = 1; // Boxing Object b = a; // referencing the pointer on stack to both objects on heap a = 2; // Boxing ``` I was expecting to see `b == 2` as well, but it isn't, why? Is it because the second boxing destroys and replaces the whole `a` object on the heap? Because if I do this, it's fine: ``` public class TT { public int x; } TT t = new TT(); t.x = 1; TT t2 = new TT(); t2.x = 2; t = t2; t.x = 3; ``` What is `t2.x`? It should be 3, and it is. But this is not an example of boxing / unboxing at all, is this correct? So how would you summarize this? **Could the values ever become the same in a boxing/unboxing conversion as above?**
1. You're right the second assignment replaces the first. It doesn't change the boxed value. 2. Your example doesn't make use of boxing. The value (int) is stored as an int and not boxed. 3. No, boxing still keeps the immutability guarantee.
Very short: boxing means **creating a new instance of a reference type**. If you know this, you understand that one instance does not change by creating another. What you are doing with `a = 2` is not changing the value in the 'box', you are creating a new instance of a reference type. So why should anything else change?
Boxing vs Unboxing
[ "", "c#", "boxing", "unboxing", "" ]
What is the difference between function and procedure in PL/SQL ?
A procedure does not have a return value, whereas a function has. Example: ``` CREATE OR REPLACE PROCEDURE my_proc (p_name IN VARCHAR2 := 'John') as begin ... end CREATE OR REPLACE FUNCTION my_func (p_name IN VARCHAR2 := 'John') return varchar2 as begin ... end ``` Notice how the function has a return clause between the parameter list and the "as" keyword. This means that it is expected to have the last statement inside the body of the function read something like: ``` return(my_varchar2_local_variable); ``` Where my\_varchar2\_local\_variable is some varchar2 that should be returned by that function.
A function can be in-lined into a SQL statement, e.g. ``` select foo ,fn_bar (foo) from foobar ``` Which cannot be done with a stored procedure. The architecture of the query optimiser limits what can be done with functions in this context, requiring that they are pure (i.e. the same inputs always produce the same output). This restricts what can be done in the function, but allows it to be used in-line in the query if it is defined to be "pure". Otherwise, a function (not necessarily deterministic) can return a variable or a result set. In the case of a function returning a result set, you can join it against some other selection in a query. However, you cannot use a non-deterministic function like this in a correlated subquery as the optimiser cannot predict what sort of result set will be returned (this is computationally intractable, like the halting problem).
What is the difference between function and procedure in PL/SQL?
[ "", "sql", "stored-procedures", "function", "plsql", "" ]
C# 2008 I have using the WebClient DownloadFile method. I can download the files I want. However, the client has insisted on creating different folders which will contain the version number. So the name of the folders would be something like this: 1.0.1, 1.0.2, 1.0.3, etc. So the files will be contained in the latest version in this case folder 1.0.3. However, how can my web client detect which is the latest one? The client will check this when it starts up. Unless I actually download all the folders and then compare. I am not sure how else I can do this. Many thanks for any advice,
Create a page which gives you the current version number. ``` string versionNumber = WebClient.DownloadString(); ```
[Allow directory browsing in IIS](http://blog.crowe.co.nz/archive/2006/03/18/603.aspx) and download the root folder. Then you could find the latest version number and construct the actual url to download. Here's a sample (assuming your directories will be of the form Major.Minor.Revision): ``` using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { using (var client = new WebClient()) { var directories = client.DownloadString("http://example.com/root"); var latestVersion = GetVersions(directories).Max(); if (latestVersion != null) { // construct url here for latest version client.DownloadFile(...); } } } static IEnumerable<Version> GetVersions(string directories) { var regex = new Regex(@"<a href=""[^""]*/([0-9]+\.[0-9]+\.[0-9])+/"">", RegexOptions.IgnoreCase); foreach (Match match in regex.Matches(directories)) { var href = match.Groups[1].Value; yield return new Version(href); } yield break; } } ```
c# check files on server using web client
[ "", "c#", "client", "" ]
I'm creating a program where the user has the option of creating their own custom properties that will ultimately be displayed in a `PropertyGrid`. Right now I don't want to mess with custom editors, so I'm only allowing primitive type properties (`string`, `int`, `double`, `DateTime`, `bool` etc.) that the `PropertyGrid` already has built in editors for. However, I also want to give the user the option to create multiple choice properties where they can defined a list of possible values which in turn will show up as a drop down list in the `PropertyGrid`. When I hard code an `Enum` in my code the property grid automatically shows properties of that `enum` as a drop down list. But can I create and or modify an enumeration at runtime so the user could add another property option, and go back to the `PropertyGrid` and see their new option in a drop down? **Update** Considering Patricks comment, I'm thinking that `Enum`s are not the right way to go in this case. So instead how can I use a list of strings to populate a drop down in a `PropertyGrid` item? Would that require a custom editor?
The answer is in a simple class: **TypeConverter**. (and yes, enums are not suitable here). Since I have not a lot of details, I will assume that you have a PropertyGrid "linked" to a target instance by the SelectedObject property and that your target instance implements ICustomTypeDescriptor so that you can add properties (i.e. PropertyDescriptors) at runtime. I don't know your design but if you are not doing like this, I advise you to have a look at it. Now let's say that you add a string property and that you want to let your user specify a set of constraints for this property. Your UI let's the user enter a set of strings and you get a list of strings as a result. Maybe you keep a dictionary of properties in your target instance so let's assume this new list is stored there too. Now, just write a new converter derived from TypeConverter (or StringConverter maybe in this example). You will have to override GetStandardValuesSupported to return true and **GetStandardValues** to return the list of strings (use the context parameter to access the Instance property and its list of strings). This converter will be published by your PropertyDescriptor with the PropertyDescriptor.Converter property. I hope this is not too nebulous. If you have a specific question on this process, just let me know.
The typical engineering solution to your problem is to use to maintain the list as reference data in your database. In general enums are intended to be constants defined at compile time, and their modification in later released of code is discouraged (let alone runtime), as it can cause side effects in switch statements.
Creating / Modifying Enums at Runtime
[ "", "c#", "enums", "propertygrid", "" ]
Using the following logic, what would the correct syntax be for a single LINQ query? > `If Branch is Service, I want its parent, otherwise I want Branch.` Can you critique my attempt and let me know how I can improve it? ``` int branchId = 21; var t = ctx.BranchInfos.Single(p => p.BranchID == branchId ); if (t.Type == BranchType.Service.ToString()) { t = ctx.BranchInfos.Single(p => p.BranchID == t.Parent); } ```
I suggest that if this is only needed in one place then what you have now is reasonably clear and should be kept. If you are doing this a lot then do something like: ``` public static BranchInfo BranchOrServiceParent( this IEnumerable<BranchInfo> input) { var t = BranchInfos.Single(p => p.BranchID == branchId); if (t.Type == BranchType.Service.ToString()) t = input.BranchInfos.Single(p => p.BranchID == t.Parent); return t; } ``` Then using it is as simple as: ``` int branchId = 21; var t = ctx.BranchInfos.BranchOrServiceParent(); ``` If you subsequently need to parameterize/change thing things you can in a clear fashion. If you subsequently find that the two *possible* trips to the database are a performance issue then you can either try a complex Linq query or accept that this probably needs to actually be done by a stored procedure.
This will probably get you what you need unless I messed up the logic. Edit: Different approach ``` var t = ctx.BranchInfos.Where(p.BranchID == branchId).First(p => p.Type == BranchType.Service.ToString() ? p.Parent : p); ```
How would I write this as a single LINQ query?
[ "", "c#", ".net", "linq", ".net-3.5", "" ]
Can you guys help me determine the performance difference of each of these statements? Which one would you use? 1. Making a new Array using ``` - var new_list = new Array(); //or - var new_list = []; ``` 2. Appending element using ``` - push('a') - new_list[i]; (if i know the length) ``` 3. Ternary operator or `if() {} else (){}` 4. Trying to make isodd function, which is faster ``` (! (is_even)) or (x%2!=0) ``` 5. `forEach()` or normal iteration one more 6. `a= b = 3;` or `b=3; a=b;` [edit: I'm making a Math Library. So any performance hacks discussions are also welcome :) ] Thanks for your help.
Performance characteristics for all browser (especially at the level of individual library functions) can vary dramatically, so it's difficult to give meaningful really meaningful answers to these questions. Anyhoo, just looking at the *fast* js engines (so Nitro, TraceMonkey, and V8) 1. `[ ]` will be faster than `new Array` -- `new Array` turns into the following logic 1. `cons` = lookup property "Array", if it can't be found, throw an exception 2. Check to see if `cons` can be used as a constructor, if not: throw an exception 3. `thisVal` = runtime creates a new object directly 4. `res` = result of calling `cons` passing `thisVal` as the value for `this` -- which requires logic to distinguish JS functions from standard runtime functions (assuming standard runtime functions aren't implemented in JS, which is the normal case). In this case `Array` is a native constructor which will create and return a new runtime array object. 5. if `res` is undefined or null then the final result is `thisVal` otherwise the final result is `res`. In the case of calling `Array` a new array object will be returned and `thisVal` will be thrown away `[ ]` just tells the JS engine to directly create a new runtime array object immediately with no additional logic. This means `new Array` has a large amount of additional (not very cheap) logic, and performs and extra unnecessary object allocation. 2. `newlist[newlist.length] = ...` is faster (esp. if newlist is not a sparse array), but push is sufficiently common for me to expect engine developers to put quite a bit of effort into improving performance so this *could* change in time. 3. If you have a tight enough loop there may be a very slight win to the ternary operator, but arguably that's an engine flaw in the trival case of `a = b ? c : d` vs `if (b) a = c; else a = d` 4. Just the function call overhead alone will dwarf the cost of more or less any JS operator, at least in the sane cases (eg. you're performing arithmetic on numbers rather than objects) 5. The `foreach` syntax isn't yet standardised but its final performane will depend on a large number of details; Often JS semantics result in efficient looking statements being less efficient -- eg. `for (var i in array) ...` is vastly slower than `for (var i = 0; i < array.length; i++) ...` as the JS semantics require `in` enumeration to build up a list of all properties on the object (including the prototype chain), and *then* checking to make sure that each property is still on the object before sending it through the loop. Oh, and the properties need to be converted from integers (in the array case anyway) into strings, which costs time and memory.
I've always assumed that since (x&1) is a bitwise operation, it would be the fastest way to check for even/odd numbers, rather than checking for the remainder of the number.
JavaScript's Statement Performance Questions
[ "", "javascript", "performance", "" ]
Problem: I need to output the TOP X Contributors determined by the amount of messages posted. Data: I have a collection of the messages posted. This is not a Database/SQL question by the sample query below just give an overview of the code. ``` tweetsSQL = db.GqlQuery("SELECT * FROM TweetModel ORDER BY date_created DESC") ``` My Model: ``` class TweetModel(db.Model): # Model Definition # Tweet Message ID is the Key Name to_user_id = db.IntegerProperty() to_user = db.StringProperty(multiline=False) message = db.StringProperty(multiline=False) date_created = db.DateTimeProperty(auto_now_add=False) user = db.ReferenceProperty(UserModel, collection_name = 'tweets') ``` From examples on SO, I was able to find the TOP X Contributors by doing this: ``` visits = defaultdict(int) for t in tweetsSQL: visits[t.user.from_user] += 1 ``` Now I can then sort it using: ``` c = sorted(visits.iteritems(), key=operator.itemgetter(1), reverse=True) ``` But the only way now to retrieve the original Objects is to loop through object c, find the KeyName and then look in TweetsSQL for it to obtain the TweetModel Object. Is there a better way? \*\*\* Sorry I should have added that Count(\*) is not available due to using google app engine [EDIT 2] In Summary, given a List of Messages, how do I order them by User's message Count. IN SQL, it would be: SELECT \* FROM TweetModel GROUP BY Users ORDER BY Count(\*) But I cannot do it in SQL and need to duplicate this functionality in code. My starting point is "SELECT \* FROM TweetModel"
Use heapq.nlargest() instead of sorted(), for efficiency; it's what it's for. I don't know the answer about the DB part of your question.
I think your job would be a lot easier if you change the SQL query to something like: ``` SELECT top 100 userId FROM TweetModel GROUP BY userId ORDER BY count(*) ``` I wouldn't bother with the TweetModel class if you only need the data to solve the stated problem.
Python Collections.DefaultDict Sort + Output Top X Custom Class Object
[ "", "python", "" ]
Say I have an old class, dated from c# 1.1 and I would like to add more methods, fields to it. Now I am using 2005, and thus the most logical solution is to use partial classes. However, it seems that I have to pretend word partial to every class in a file where I define it. The problem: What if I cannot change the class declaration in an old file (add word partial to it), but still want to add methods to it, what should I do?
Well, firstly, yes you do need to use the partial keyword to all of the involved classes, under the same namespace. This will tell the compiler that those are the parts of the same class that will be put together. Now, if you really cannot change the old classes, one thing you can do is to inherit your old class: ``` public class NewClass : OldClass ``` ...and as such you can extend the functionality of the OldClass. You may also choose to just consume the old class some sort of wrapper, as an attribute/property: ``` public class NewClass { public OldClass MyClass { get; set; } //.NET 3.5 / VS2008 private OldClass _oldClass; //.NET 2.0 / VS2005 public OldClass MyClass { get { return _oldClass; } set { _oldClass = value; } } } ``` ...or even a generic: ``` public class NewClass<T> where T: OldClass //applicable in both versions ``` The suggestion for extension methods will also work: ``` public void NewMethod1(this OldClass, string someParameter){} //available only in .NET 3.5/VS2008 ```
You should derive from it.
Do we need a keyword partial for all instantiation of partial classes?
[ "", "c#", ".net", "" ]
I have this Java `JFrame` class, in which I want to use a boxlayout, but I get an error saying `java.awt.AWTError: BoxLayout can't be shared`. I've seen others with this problem, but they solved it by creating the boxlayout on the contentpane, but that is what I'm doing here. Here's my code: ``` class EditDialog extends JFrame { JTextField title = new JTextField(); public editDialog() { setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setTitle("New entity"); getContentPane().setLayout( new BoxLayout(this, BoxLayout.PAGE_AXIS)); add(title); pack(); setVisible(true); } } ```
Your problem is that you're creating a `BoxLayout` for a `JFrame` (`this`), but setting it as the layout for a `JPanel` (`getContentPane()`). Try: ``` getContentPane().setLayout( new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS) ); ```
I've also found this error making this: ``` JPanel panel = new JPanel(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); ``` The JPanel isn't initialized yet when passing it to the BoxLayout. So split this line like this: ``` JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); ``` This will work.
error upon assigning Layout: BoxLayout can't be shared
[ "", "java", "swing", "layout", "boxlayout", "" ]
I wish to do this but for a dictionary: ``` "My string".lower() ``` Is there a built in function or should I use a loop?
You will need to use either a loop or a list/generator comprehension. If you want to lowercase all the keys and values, you can do this:: ``` dict((k.lower(), v.lower()) for k,v in {'My Key':'My Value'}.iteritems()) ``` If you want to lowercase just the keys, you can do this:: ``` dict((k.lower(), v) for k,v in {'My Key':'My Value'}.iteritems()) ``` [Generator expressions](http://www.python.org/dev/peps/pep-0289/) (used above) are often useful in building dictionaries; I use them all the time. All the expressivity of a loop comprehension with none of the memory overhead.
If you want keys and values of multi-nested dictionary (json format) lowercase, this might help. Need to have support for dict comprehensions what should be in **Python 2.7** ``` dic = {'A':['XX', 'YY', 'ZZ'], 'B':(u'X', u'Y', u'Z'), 'C':{'D':10, 'E':('X', 'Y', 'Z'), 'F':{'X', 'Y', 'Z'} }, 'G':{'X', 'Y', 'Z'} } ``` ***PYTHON2.7*** -- also supports OrderedDict ``` def _lowercase(obj): """ Make dictionary lowercase """ if isinstance(obj, dict): t = type(obj)() for k, v in obj.items(): t[k.lower()] = _lowercase(v) return t elif isinstance(obj, (list, set, tuple)): t = type(obj) return t(_lowercase(o) for o in obj) elif isinstance(obj, basestring): return obj.lower() else: return obj ``` ***PYTHON 3.6*** ``` def _lowercase(obj): """ Make dictionary lowercase """ if isinstance(obj, dict): return {k.lower():_lowercase(v) for k, v in obj.items()} elif isinstance(obj, (list, set, tuple)): t = type(obj) return t(_lowercase(o) for o in obj) elif isinstance(obj, str): return obj.lower() else: return obj ```
Dictionary to lowercase in Python
[ "", "python", "dictionary", "lowercase", "" ]
I've a request to make some changes to a little applet that currently use a JFileChooser. One of the main complaints is that the file chooser is a pain in the ass to use because it behaves differently than the native widget, especially for navigating up to the root level. So, knowing that and all the other issue JFileChooser suffer (like the zip file caching on windows...), I was wondering that a viable alternative exists in the java world. Of course, there is SWT that use the native widget, but increasing the applet size by 25 is not really an option. So, is there a better pure java implementation of a file chooser?
You can also try [XFileDialog](http://code.google.com/p/xfiledialog/ "xfiledialog"). Haven't tried it much yet but looks worth evaluating.
The AWT [`FileDialog`](http://java.sun.com/javase/6/docs/api/java/awt/FileDialog.html "FileDialog") actually does use the native component, but as with most AWT vs. Swing issues, it's much less flexible and customizable than Swing's `JFileChooser`. So there's a tradeoff: `JFileChooser` may have a clunky user interface, but it's usually better for most purposes. If you really want your file choosing dialogs to look and feel like the native ones, though, then you can go with `FileDialog`.
Alternative to JFileChooser
[ "", "java", "user-interface", "jfilechooser", "" ]
My task is simple: make a post request to translate.google.com and get the translation. In the following example I'm using the word "hello" to translate into russian. ``` header('Content-Type: text/plain; charset=utf-8'); // optional error_reporting(E_ALL | E_STRICT); $context = stream_context_create(array( 'http' => array( 'method' => 'POST', 'header' => implode("\r\n", array( 'Content-type: application/x-www-form-urlencoded', 'Accept-Language: en-us,en;q=0.5', // optional 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7' // optional )), 'content' => http_build_query(array( 'prev' => '_t', 'hl' => 'en', 'ie' => 'UTF-8', 'text' => 'hello', 'sl' => 'en', 'tl' => 'ru' )) ) )); $page = file_get_contents('http://translate.google.com/translate_t', false, $context); require '../simplehtmldom/simple_html_dom.php'; $dom = str_get_html($page); $translation = $dom->find('#result_box', 0)->plaintext; echo $translation; ``` Lines marked as optional are those without which the output is the same. But I'm getting weird characters... ``` ������ ``` I tried ``` echo mb_convert_encoding($translation, 'UTF-8'); ``` But I get ``` ÐÒÉ×ÅÔ ``` Does anybody know how to solve this problem? UPDATE: 1. Forgot to mention that all my php files are encoded in UTF-8 without BOM 2. When i change the "to" language to "en", that is translate from english to english, it works ok. 3. I do not think the library I'm using is messing it up, because I tried to output the whole $page without passing it to the library functions. 4. I'm using PHP 5
First off, is your browser set to UTF-8? In Firefox you can set your text encoding in View->Character Encoding. Make sure you have "Unicode (UTF-8)" selected. I would also set View->Character Encoding->Auto-Detect to "Universal." Secondly, you could try passing the FILE\_TEXT flag, like so: ``` $page = file_get_contents('http://translate.google.com/translate_t', FILE_TEXT, $context); ```
Try to see this post if it can help [CURL import character encoding problem](https://stackoverflow.com/questions/649480/curl-import-character-encoding-problem/649856#649856) Also you can try this snippet (taken from php.net) ``` <?php function file_get_contents_utf8($fn) { $content = file_get_contents($fn); return mb_convert_encoding($content, 'UTF-8', mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true)); } ?> ```
php: file_get_contents encoding problem
[ "", "php", "encoding", "file-get-contents", "" ]
Look at the following code snippet: ``` <?php class A { function fn() { print 'Context: Class:' . get_class($this) . ' Parent:' . get_parent_class($this) . "\n"; if(get_parent_class($this)) { parent::fn(); } } } class B extends A { } class C extends B { } $a = new A(); $c = new C(); $a->fn(); print "\n"; $c->fn(); ?> ``` By running it you will get the following output: ``` Context: Class:A Parent: Context: Class:C Parent:B Fatal error: Cannot access parent:: when current class scope has no parent in /home/andrei/test/test.php on line 10 ``` I believe it should be something like this: ``` Context: Class:A Parent: Context: Class:C Parent:B Context: Class:B Parent:A Context: Class:A Parent: ``` What do you think? If `get_parent_class($this)` returns a not false value should we safely assume parent:: is defined? In what class context is `fn()` called?
Calls using parent:: or self:: are considered to be static. These are supposed to be evaluated in the context of the defining class, not in the scope of the calling object. PHP 5.3 adds a new meaning to the word **static** which would be available for static calls *like* parent and self, but will be evaluated in the context of the **calling class**. This is called **Late Static Binding**. More info on this page: <http://www.php.net/lsb> **Edit:** After some thought I believe this behavior is perfectly acceptable. First, let's see why would A want that its foo() method to call the foo() method of its parent, given that A has no parent. Because, it wants the method to always be executed regardless of the implementation of the children. If so, there are other solutions, not that nice though: ``` class A { final public function __construct() { echo __METHOD__; $this->foo(); $init = array($this, 'init'); $args = func_get_args(); call_user_func_array($init, $args); } // init would be used as a pseudo-constructor in children public function init() {} final private function foo() { echo __METHOD__; } } class B extends A {} class C extends B {} $c = new C; ``` If what you tried to do was to execute every foo() method in the chain, then it was expected behavior. If there was a B::foo() function then that would have been executed and if it had contain a call to parent::foo() then A::foo() would have been executed too. So, probably parent::foo() is somehow confusing. It should be read like (sorry, but I couldn't find a better example): the\_first\_parent\_in\_the\_inheritance\_chain\_which\_has\_a\_foo\_method::foo() That's what you are actually interested in. Why would you want to call foo() in the context of B? The only reason I can think of is for accessing private member from B. But then, how would A know what private members B has? It can't. You cannot use in A::foo() members that A hadn't declared. Unless A is abstract and defines some abstract methods. Of course, A may declare that property as private (B cannot give an overridden member a lower visibility than that in the parent and our aim is that B should have a private one). Then B overrides that property, making it private as we want. Now, if your code would have worked, A or C would have had access to B's private member although it shouldn't. That breaks a rule. Is there any situation in which you want the behavior you've asked about?
I am no php wizard but I would guess that the problem is with parent being static
PHP: call method in the context of each object of the inheritance chain
[ "", "php", "" ]
I'm afraid of varargs. I don't know what to use them for. Plus, it feels dangerous to let people pass as many arguments as they want. What's an example of a context that would be a good place to use them?
*Varargs* are *useful* for any method that needs to deal with an *indeterminate number of objects*. One good example is [`String.format`](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#format%28java.lang.String,%20java.lang.Object...%29). The format string can accept any number of parameters, so you need a mechanism to pass in any number of objects. ``` String.format("This is an integer: %d", myInt); String.format("This is an integer: %d and a string: %s", myInt, myString); ```
A good rule of thumb would be: **"Use varargs for any method (or constructor) that needs an array of T (whatever type T may be) as input".** That will make calls to these methods easier (no need to do `new T[]{...}`). You could extend this rule to include methods with a `List<T>` argument, provided that this argument is for input only (ie, the list is not modified by the method). Additionally, I would refrain from using `f(Object... args)` because its slips towards a programming way with unclear APIs. In terms of examples, I have used it in [DesignGridLayout](https://designgridlayout.java.net/), where I can add several `JComponent`s in one call: ``` layout.row().grid(new JLabel("Label")).add(field1, field2, field3); ``` In the code above the add() method is defined as `add(JComponent... components)`. Finally, the implementation of such methods must take care of the fact that it may be called with an empty vararg! If you want to impose at least one argument, then you have to use an ugly trick such as: ``` void f(T arg1, T... args) {...} ``` I consider this trick ugly because the implementation of the method will be less straightforward than having just `T... args` in its arguments list. Hopes this helps clarifying the point about varargs.
When do you use varargs in Java?
[ "", "java", "variadic-functions", "" ]
I have this code to send mail: ``` public bool SendMail(MailMessage message) { message.From = new MailAddress(AppProperties.FromMailAddress, AppProperties.FromDisplayName); SmtpClient smtp = new SmtpClient { EnableSsl = AppProperties.EnableSsl }; try { smtp.Send(message); return true; } catch (Exception) { return false; } } ``` and have configured web.config to send mail using IIS 5.1 in localhost with this (as suggested by the answers): ``` <system.net> <mailSettings> <smtp deliveryMethod="Network"> <network host="localhost" userName="" password="" defaultCredentials="false" port="25" /> </smtp> </mailSettings> </system.net> ``` What do I have to do to send mail with my IIS 5.1 in Windows XP? Is possible to do it? I guess yes, as you say, since I don't get any exception, but I don't receive it on destination. If I should put an user and a password, wich must be?
You should first install SMTP server (Windows Components > IIS > SMTP Service) and then configure it to enable relaying. > IIS > Default SMTP Server > Properties > Access > Authentication > > Access Control > Anonymous Access - Checked > > Relay Restrictions > Relay > Select - Only the list below > Add > 127.0.0.1
Sure it's possible, you will no longer need to use SSL however. In the config file, your port will probably be 25, you may or may not need username/password, and of course your hostname will change. Also make sure you install the SMTP components along with IIS.
How to send mail using IIS 5.1 in WinXP?
[ "", "c#", "asp.net", "asp.net-mvc", "iis", "email", "" ]