Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
We are developing a web application that will be sold to many clients. There is already one client (a bank) which has decided that it will buy the product once it is ready. Unfortunately due to some miscommunication it came out rather late that the only browser they use is IE6. The application was already started with the thought in mind that it does not need to support anything else below IE7. The results are pretty good too - it's fully useable on IE7/FF/Opera/Safari. Haven't tested on Chrome, but expect little problems there. Unfortunately there is now the IE6 requirement after all... The application isn't too far developed yet, and the design is pretty much OK, so the change isn't that horrible. Still, it'll take some work. A nice thing about IE6 is that it supports two nonstandard and very helpful features. First is conditional comments, which lets me include some CSS/JS files only for IE6. Second is CSS expressions. That is, things like this: ``` input { background-color: expression(this.type='text'?'silver':''); } ``` In essence it binds CSS values to JavaScript expressions. This allows to easily emulate many CSS features that IE6 does not support natively, and could lighten my burden considerably. Unfortunately IE is infamous for its JavaScript performance. I'm worried that using too many of these expressions might slow it down to a crawl. I also have no idea what computers the bank is using. Since it's a pretty big one, I'd expect a wide variety in all their branch offices. I don't expect to use anything much there - some simple math, ternary operators and looking at this element's/parent element's properties. Still there would be a couple dozen of these in the IE6\_override.CSS file. Can this be a problem? **Added:** Blah, this was what I was afraid of. OK, will see how much I can use other hacks to get around the shortcomings. Thanx, people!
<https://developer.yahoo.com/blogs/ydn/high-performance-sites-rule-7-avoid-css-expressions-7202.html> Turns out you might want to avoid using these, they are dangerous.
Expressions are re-evaluated on many page events, which has the potential to slow down entire page performance when used too liberally. (And yet still, they can't respond to all events that might cause them to need re-evaluating.) MS have admitted expression() was a mistake, and are [removing it from future browsers](http://blogs.msdn.com/ie/archive/2008/10/16/ending-expressions.aspx). There are generally better individual JavaScript workarounds for IE6's various CSS shortcomings. It is rather sad that so many companies are still sticking with the dire IE6. Maybe if you deliver the project late they'll have upgraded by then!
IE6 performance with CSS expressions
[ "", "javascript", "css", "performance", "internet-explorer-6", "css-expressions", "" ]
I want to load and draw pdf files graphically using C#. I don't need to edit them or anything, just render them at a given zoom level. The pdf libraries I have found seem to be focussed on generation. How do I do this? Thanks.
There are a few other choices in case the Adobe ActiveX isn't what you're looking for (since Acrobat must be present on the user machine and you can't ship it yourself). For creating the PDF preview, first have a look at some other discussions on the subject on StackOverflow: * [How can I take preview of documents?](https://stackoverflow.com/questions/175528/how-can-i-take-preview-of-documents) * [Get a preview jpeg of a pdf on windows?](https://stackoverflow.com/questions/502/get-a-preview-jpeg-of-a-pdf-on-windows) * [.NET open PDF in winform without external dependencies](https://stackoverflow.com/questions/549504/-net-open-pdf-in-winform-without-external-dependencies/) * [PDF Previewing and viewing](https://stackoverflow.com/questions/541891/pdf-previewing-and-viewing/) In the last two I talk about a few things you can try: * You can get a commercial renderer ([PDFViewForNet](http://www.o2sol.com/pdfview4net/overview.htm), [PDFRasterizer.NET](http://tallcomponents.com/default.aspx?id=pdfrasterizer2), [ABCPDF](http://www.websupergoo.com/abcpdf-1.htm), [ActivePDF](http://www.activepdf.com/), [XpdfRasterizer](http://www.glyphandcog.com/XpdfRasterizer.html) and others in the other answers...). Most are fairly expensive though, especially if all you care about is making a simple preview/thumbnails. * In addition to Omar Shahine's code snippet, there is a [CodeProject article](http://www.codeproject.com/KB/GDI-plus/pdfthumbnail.aspx) that shows how to use the Adobe ActiveX, but it may be out of date, easily broken by new releases and its legality is murky (basically it's ok for internal use but you can't ship it and you can't use it on a server to produce images of PDF). * You could have a look at the source code for [SumatraPDF](http://blog.kowalczyk.info/software/sumatrapdf/free-pdf-reader.html), an OpenSource PDF viewer for windows. * There is also [Poppler](http://poppler.freedesktop.org/), a rendering engine that uses [Xpdf](http://www.foolabs.com/xpdf/) as a rendering engine. All of these are great but they will require a fair amount of commitment to make make them work and interface with .Net and they tend to be be distributed under the GPL. * You may want to consider using [GhostScript](http://pages.cs.wisc.edu/~ghost/) as an interpreter because rendering pages is a fairly simple process. The drawback is that you will need to either re-package it to install it with your app, or make it a pre-requisite (or at least a part of your install process). It's not a big challenge, and it's certainly easier than having to massage the other rendering engines into cooperating with .Net. I did a small project that you will find on the [Developer Express forums](http://community.devexpress.com/forums/p/55582/188207.aspx#188207) as an attachment. Be careful of the license requirements for GhostScript through. If you can't leave with that then commercial software is probably your only choice.
Google has open sourced its excellent PDF rendering engine - [PDFium](https://code.google.com/p/pdfium/) - that it wrote with Foxit Software. There is a C# nuget package called [PdfiumViewer](https://github.com/Bluegrams/PdfiumViewer) which gives a C# wrapper around PDFium and allows PDFs to be displayed and printed. I have used it and was very impressed with the quality of the rendering. --- PDFium works directly with streams so it doesn't require any data to be written to disk. This is my example from a WinForms app ``` public void LoadPdf(byte[] pdfBytes) { var stream = new MemoryStream(pdfBytes); LoadPdf(stream); } public void LoadPdf(Stream stream) { // Create PDF Document var pdfDocument = PdfDocument.Load(stream); // Load PDF Document into WinForms Control pdfRenderer.Load(pdfDocument); } ``` --- Edit: To get the *pdfRenderer* control in WinForm: Add the `PdfiumViewer` NuGet package to the project; open the projects packages folder in Windows Explorer and drag the `PdfiumViewer.dll` file onto the `Toolbox` window; A control called `PdfRenderer` will be available to add: [![Adding PdfRenderer control to WinForms](https://i.stack.imgur.com/oMDhc.png)](https://i.stack.imgur.com/oMDhc.png)
How to render pdfs using C#
[ "", "c#", "pdf", "drawing", "rendering", "" ]
I'm looping through a list of items, and I'd like to get a request parameter based on the item's index. I could easily do it with a scriptlet as done below, but I'd like to use expression language. ``` <c:forEach var="item" items="${list}" varStatus="count"> <!-- This would work --> <%=request.getParameter("item_" + count.index)%> <!-- I'd like to make this work --> ${param.?????} </c:forEach> ```
``` <c:set var="index" value="item_${count.index}" /> ${param[index]} ``` Unfortunately, + doesn't work for strings like in plain Java, so ``` ${param["index_" + count.index]} ``` doesn't work ;-(
There is a list of implicit objects in the [Expression Language documentation](http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPIntro7.html#wp71043) section of the J2EE 1.4 documentation. You're looking for *param*.
How do I dynamically access request parameters with JSP EL?
[ "", "java", "jsp", "jstl", "el", "" ]
Problem statement: Implement a plug-in system that allows the associated assemblies to be overwritten (avoid file locking). In .Net, specific assemblies may not be unloaded, only entire AppDomains may be unloaded. I'm posting this because when I was trying to solve the problem, every solution made reference to using multiple AppDomains. Multiple AppDomains are very hard to implement correctly, even when architected at the start of a project. Also, AppDomains didn't work for me because I needed to transfer Type across domains as a setting for Speech Server worfklow's InvokeWorkflow activity. Unfortunately, sending a type across domains causes the assembly to be injected into the local AppDomain. Also, this is relevant to IIS. IIS has a Shadow Copy setting that allows an executing assembly to be overwritten while its loaded into memory. The problem is that (at least under XP, didnt test on production 2003 servers) when you programmatically load an assembly, the shadow copy doesnt work (because you are loading the DLL, not IIS).
1. Check if the assembly is already loaded (to avoid memory leaks caused by loading the same assembly over and over again). 2. If its not loaded, read the assembly into a byte array. This will prevent locking the file. 3. Supply the byte array as an arguement to Assembly.Load The following code assumes you know the FullName of an assembly. ``` Assembly assembly = null; foreach(Assembly loadedAssembly in AppDomain.CurrentDomain.GetAssemblies()) if (loadedAssembly.FullName == "foobar, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null") assembly = loadedAssembly; if(assembly == null) { byte[] studybin = System.IO.File.ReadAllBytes(@"C:\pathToAssembly\foobar.dll"); assembly = Assembly.Load(studybin); } ``` Note that if you are trying to find a specific assembly in a directory, you can run 'System.Reflection.AssemblyName.GetAssemblyName(path);' to see if the FullName matches what you are looking for. 'GetAssemblyName(path)' does NOT inject the assembly into your current AppDomain. Also note that this solution is not appropriate for applications that must only rarely restart AND the assemblies change with high frequency. Every time an assembly is loaded, the memory footprint of you application will grow. There is no method to unload an assembly, thus the only option to shrink memory usage is to restart the application. However, this limitation is often preferable to the large performance, memory, and code complexity overhead of using multiple app domains. This limitation is also unavoidable if you wish to work with `Type`s.
If you want to isolate your addins, you must... 1. Create a type that extends MarshallByRefObject which will interact with your addins (lets call it FOOMASTER) 2. Create a new appdomain (lets call it addinLand) 3. Call addinLand.CreateInstanceAndUnwrap to create an instance of FOOMASTER in addinLand and get a proxy in the current app domain 4. Tell FOOMASTER to load your addins Now your addins are loaded in addinLand and you can interact with them from your primary appdomain via your FOOMASTER proxy. When your addins crash, they don't take down your application. Its an interesting and slightly confusing process. I originally thought the idea was to load your addins and then bring them over into the current app domain as transparent proxies, but the best design is to leave the addins as simple objects that interact with more complex types you create (FOOMASTER), that extend MarshallByRefObject, that are loaded in the addinLand app domain, and whose transparent proxies you interact with. Chapters 21 and 22 of CLR Via C# are very helpful in understanding the process.
How do I implement .net plugins without using AppDomains?
[ "", "c#", ".net", "iis", "assemblies", "appdomain", "" ]
I have a long snippet of HTML I want some javascript variable to equal and for maintainability I want to store it with actual newlines instead of adding \n (or as it is HTML just omitting newline characters). In Python I would do something like: ``` largeString = """Hello This is long!""" ``` And that would work perfectly. However, I haven't seen a way to do this in JavaScript. Some additional information: the javascript is in an external .js file and the snippet really is quite huge (~6kb).
Put a \ at the end of each line. Alternatively store it in a div with display:none and then use .html() to retrieve it
JavaScript doesn't support multi-line strings in the same manner. You can use `\` to escape a newline for your script, but this is only for developer reading as it won't stay with the string (and most validators will throw errors for it). To keep a newline with the string, you'll still be required to use `\n`. If you want the readability, you can combine them: ``` var largeString = '"Hello\n\ This is long!"'; ```
Multiline JavaScript Text
[ "", "javascript", "html", "newline", "" ]
A coworker of mine thought of a great way to visualize a lot of the data we work with in our user-end applications, but we're not aware of many available sdk's or apis that hook in. We're trying to recreate in essence, the "Magic-Wall" of CNN. We would like to be able to show trends across the country in a 'heat-map' kind of way, and be able to drill down into a state to show those same trends across counties. We don't need the move-states-all-over-the-place functionality that the commentators loved to use. We're aware of Mappoint, but more research needs to be done if its capable of what we require. Would it make more sense to just try and roll our own? Has anyone else tried something along these lines? The only problem I can see is defining the boundaries for each state, or by county on the state-level. Thoughts? Ideas?
We ended up going with [SharpMap](http://www.codeplex.com/SharpMap).
Hi you can take a look at Telogis GeoBase C# SDK, support WPF, WinForms and there is an XML/SOAP server for webservice implementations. <http://dev.telogis.com/> (I work for Telogis)
Powerful .NET Map APIs?
[ "", "c#", ".net", "mapping", "gis", "" ]
I've got a web application that controls which web applications get served traffic from our load balancer. The web application runs on each individual server. It keeps track of the "in or out" state for each application in an object in the ASP.NET application state, and the object is serialized to a file on the disk whenever the state is changed. The state is deserialized from the file when the web application starts. While the site itself only gets a couple requests a second tops, and the file it rarely accessed, I've found that it was extremely easy for some reason to get collisions while attempting to read from or write to the file. This mechanism needs to be extremely reliable, because we have an automated system that regularly does rolling deployments to the server. Before anyone makes any comments questioning the prudence of any of the above, allow me to simply say that explaining the reasoning behind it would make this post much longer than it already is, so I'd like to avoid moving mountains. That said, the code that I use to control access to the file looks like this: ``` internal static Mutex _lock = null; /// <summary>Executes the specified <see cref="Func{FileStream, Object}" /> delegate on /// the filesystem copy of the <see cref="ServerState" />. /// The work done on the file is wrapped in a lock statement to ensure there are no /// locking collisions caused by attempting to save and load the file simultaneously /// from separate requests. /// </summary> /// <param name="action">The logic to be executed on the /// <see cref="ServerState" /> file.</param> /// <returns>An object containing any result data returned by <param name="func" />. ///</returns> private static Boolean InvokeOnFile(Func<FileStream, Object> func, out Object result) { var l = new Logger(); if (ServerState._lock.WaitOne(1500, false)) { l.LogInformation( "Got lock to read/write file-based server state." , (Int32)VipEvent.GotStateLock); var fileStream = File.Open( ServerState.PATH, FileMode.OpenOrCreate , FileAccess.ReadWrite, FileShare.None); result = func.Invoke(fileStream); fileStream.Close(); fileStream.Dispose(); fileStream = null; ServerState._lock.ReleaseMutex(); l.LogInformation( "Released state file lock." , (Int32)VipEvent.ReleasedStateLock); return true; } else { l.LogWarning( "Could not get a lock to access the file-based server state." , (Int32)VipEvent.CouldNotGetStateLock); result = null; return false; } } ``` This *usually* works, but occasionally I cannot get access to the mutex (I see the "Could not get a lock" event in the log). I cannot reproduce this locally - it only happens on my production servers (Win Server 2k3/IIS 6). If I remove the timeout, the application hangs indefinitely (race condition??), including on subsequent requests. When I do get the errors, looking at the event log tells me that the mutex lock was achieved and released by the previous request *before* the error was logged. The mutex is instantiated in the Application\_Start event. I get the same results when it is instantiated statically in the declaration. Excuses, excuses: threading/locking is not my forté, as I generally don't have to worry about it. Any suggestions as to why it randomly would fail to get a signal? --- **Update:** I've added proper error handling (how embarrassing!), but I am still getting the same errors - and for the record, unhandled exceptions were never the problem. Only one process would ever be accessing the file - I don't use a web garden for this application's web pool, and no other applications use the file. The only exception I can think of would be when the app pool recycles, and the old WP is still open when the new one is created - but I can tell from watching the task manager that the issue occurs while there is only one worker process. @mmr: How is using Monitor any different from using a Mutex? Based on the MSDN documentation, it looks like it is effectively doing the same thing - if and I can't get the lock with my Mutex, it *does* fail gracefully by just returning false. Another thing to note: The issues I'm having seem to be completely random - if it fails on one request, it might work fine on the next. There doesn't seem to be a pattern, either (certainly no every other, at least). --- **Update 2:** This lock is not used for any other call. The only time \_lock is referenced outside the InvokeOnFile method is when it is instantiated. The Func that is invoked is either reading from the file and deserializing into an object, or serializing an object and writing it to the file. Neither operation is done on a separate thread. ServerState.PATH is a static readonly field, which I don't expect would cause any concurrency problems. I'd also like to re-iterate my earlier point that I cannot reproduce this locally (in Cassini). --- **Lessons learned:** * Use proper error handling (duh!) * Use the right tool for the job (and have a basic understanding of what/how that tool does). As sambo points out, using a Mutex apparently has a lot of overhead, which was causing issues in my application, whereas Monitor is designed specifically for .NET.
You should only be using Mutexes if you need **cross-process synchronization**. > Although a mutex can be used for > intra-process thread synchronization, > using Monitor is generally preferred, > because monitors were designed > specifically for the .NET Framework > and therefore make better use of > resources. In contrast, the Mutex > class is a wrapper to a Win32 > construct. While it is more powerful > than a monitor, a mutex requires > interop transitions that are more > computationally expensive than those > required by the Monitor class. If you need to support inter-process locking you need a [Global mutex](https://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c). The pattern being used is incredibly fragile, there is no exception handling and you are not ensuring that your Mutex is released. That is really risky code and most likely the reason you see these hangs when there is no timeout. Also, if your file operation ever takes longer than 1.5 seconds then there is a chance concurrent Mutexes will not be able to grab it. I would recommend getting the locking right and avoiding the timeout. I think its best to re-write this to use a lock. Also, it looks like you are calling out to another method, if this take forever, the lock will be held forever. That's pretty risky. This is both shorter and much safer: ``` // if you want timeout support use // try{var success=Monitor.TryEnter(m_syncObj, 2000);} // finally{Monitor.Exit(m_syncObj)} lock(m_syncObj) { l.LogInformation( "Got lock to read/write file-based server state." , (Int32)VipEvent.GotStateLock); using (var fileStream = File.Open( ServerState.PATH, FileMode.OpenOrCreate , FileAccess.ReadWrite, FileShare.None)) { // the line below is risky, what will happen if the call to invoke // never returns? result = func.Invoke(fileStream); } } l.LogInformation("Released state file lock.", (Int32)VipEvent.ReleasedStateLock); return true; // note exceptions may leak out of this method. either handle them here. // or in the calling method. // For example the file access may fail of func.Invoke may fail ```
If some of the file operations fail, the lock will not be released. Most probably that is the case. Put the file operations in try/catch block, and release the lock in the finally block. Anyway, if you read the file in your Global.asax Application\_Start method, this will ensure that noone else is working on it (you said that the file is read on application start, right?). To avoid collisions on application pool restaring, etc., you just can try to read the file (assuming that the write operation takes an exclusive lock), and then wait 1 second and retry if exception is thrown. Now, you have the problem of synchronizing the writes. Whatever method decides to change the file should take care to not invoke a write operation if another one is in progress with simple lock statement.
C# - Locking issues with Mutex
[ "", "c#", "asp.net", "locking", "mutex", "" ]
Why does the compiler say "a constant value is required" for the first case...the second case works fine... ``` switch (definingGroup) { case Properties.Settings.Default.OU_HomeOffice: //do something break; case "OU=Home Office": //do something break; default: break; } ``` also tried... ``` switch (definingGroup) { case Properties.Settings.Default.OU_HomeOffice.ToString(): //do something break; case "OU=Home Office": //do something break; default: break; } ``` ...same error Here's the Properties.Setting code ``` [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("OU=Home Office")] public string OU_HomeOffice { get { return ((string)(this["OU_HomeOffice"])); } } ```
`Properties.Settings.Default.OU_HomeOffice` isn't a constant string - something known at compile time. The C# switch statement requires that every case is a compile-time constant. (Apart from anything else, that's the only way it can know that there won't be any duplicates.) See section 8.7.2 of the C# 3.0 spec for more details.
This is because the value cannot be determined at compile time (as it is coming out of a configuration setting). You need to supply values that are known at the time the code is compiled (constants).
switch statement in C# and "a constant value is expected"
[ "", "c#", "visual-studio", "" ]
Sorry in advance, I'm struggling a bit with how to explain this... :) Essentially, I've got a typical windows coordinate system (the Top, Left is 0,0). If anybody's familiar with the haversine query, [like in SQL](http://forums.mysql.com/read.php?10,238858,238858), it can get all points in a radius based on latitude and longitude coordinates. I need something much simpler, but my math skills ain't all up to par! Basically, I've got random points scattered throughout about a 600x400 space. I have a need to, for any X,Y point on the map, run a query to determine how many other points are within a given radius of that one. If that's not descriptive enough, just let me know!
Use Pythagoras: ``` distance = sqrt(xDifference^2 + yDifference^2) ``` Note that '^' in this example means "to the power of" and not C's bitwise XOR operator. In other words the idea is to square both differences.
Straightforward approach: You can calculate the distance between to points using the [Pythagorean theorem](http://en.wikipedia.org/wiki/Pythagorean_theorem#Distance_in_Cartesian_coordinates): ``` deltaX = x1 - x2 deltaY = y1 - y2 distance = square root of (deltaX * deltaX + deltaY * deltaY) ``` Given point `x1,y1`, do this for every other point (`x2,y2`) to see if the calculated distance is within (less than or equal to) your radius. If you want to make it speedier, calculate and store the square of the radius and just compare against `(deltaX * deltaX + deltaY * deltaY)`, avoiding the square root.
(C++) Need to figure out all points within a radius using reg. 2D windows coord. system
[ "", "c++", "algorithm", "visual-c++", "" ]
Ok, so I wanted to get opinions on this topic. I have a dumb data object - CustomerOrder. CustomerOrder has a price and a quantity but also has a TotalCash property (price \* quantity). so I have a totalCash property but I dont want to put the calculation into the object directly because that would be breaking the dumb data object rule. I do need to get the cashflow over and over again throughout the app so I need to centralize the calculation. I could create a cashFlowCalculator class and pass in a customerOrder but I dont want another class for every simple calculation. Any ideas or best practices?
In the same situation I would break the "dumb data object rule" since I don't expect that particular calculation to change often. I'd probably implement it as a getter. For more complex scenarios, it makes sense to create an OrderCalculator class that takes in order-related classes and can perform all sorts of calculations such as included tax, measuring margins, etc. In this way you are delegating the responsibilities of performing a calculation outside of the CustomerOrder. That way the CustomerOrder does not need to know about the state tax in Texas to determine if sale tax is needed, for example.
I understand the rationale of keeping your data objects separate from your business logic. Using LINQ with designer generated classes, I feel comfortable extending the generated class with a partial class implementation that contains the business logic. I feel that this is enough separation for my needs. If this doesn't work for you then I would have both data objects and business objects -- perhaps with a 1-1 correspondence, perhaps not. A factory class or method can be used to translate between your business and data objects. Then simply implement your business logic in your business objects without need for auxiliary objects for your calculations.
Data modeling question - separation of data and calculation and accessor logic
[ "", "c#", "model-view-controller", "" ]
I need a library that can detect objects in an image (uses edge detection). This is NOT related to captchas. I am working on an MTGO bot that uses OCR and that works in any screen resolution. In order for it to port to any screen resolution my idea is to scan down narrow range on a results page (the cards that a player has can be listed in rows of text) and to find each object in that range. Then to take the lowest and highest pixel coordinates of each object to find where the row starts and ends (on the y axis) so that I can use OCR to read each line.
If you don't know of the [OpenCV](http://sourceforge.net/projects/opencvlibrary) collection of examples, then they could help you in the right direction... there's also [Camellia](http://camellia.sourceforge.net/index.html) which doesn't use "edge detection" per-se but could get the results you need with a bit of work.
Its not cheap, but I've used the Intel Processing Primitives, and was very impressed with their performance. They work on Intel and AMD processors, as well as Windows and Linux
Image Processing Library for C++
[ "", "c++", "image-processing", "ocr", "" ]
[Wikipedia](http://en.wikipedia.org/wiki/Join_(SQL)#) states: "In practice, explicit right outer joins are rarely used, since they can always be replaced with left outer joins and provide no additional functionality." Can anyone provide a situation where they have preferred to use the RIGHT notation, and why? I can't think of a reason to ever use it. To me, it wouldn't ever make things more clear. Edit: I'm an Oracle veteran making the New Year's Resolution to wean myself from the (+) syntax. I want to do it right
The only reason I can think of to use RIGHT OUTER JOIN is to try to make your SQL more self-documenting. You might possibly want to use left joins for queries that have null rows in the dependent (many) side of one-to-many relationships and right joins on those queries that generate null rows in the independent side. This can also occur in generated code or if a shop's coding requirements specify the order of declaration of tables in the FROM clause.
I've never used `right join` before and never thought I could actually need it, and it seems a bit unnatural. But after I thought about it, it could be really useful in the situation, when you need to outer join one table with intersection of many tables, so you have tables like this: ![enter image description here](https://i.stack.imgur.com/jhkPn.png) And want to get result like this: ![enter image description here](https://i.stack.imgur.com/lxLHS.png) Or, in SQL (MS SQL Server): ``` declare @temp_a table (id int) declare @temp_b table (id int) declare @temp_c table (id int) declare @temp_d table (id int) insert into @temp_a select 1 union all select 2 union all select 3 union all select 4 insert into @temp_b select 2 union all select 3 union all select 5 insert into @temp_c select 1 union all select 2 union all select 4 insert into @temp_d select id from @temp_a union select id from @temp_b union select id from @temp_c select * from @temp_a as a inner join @temp_b as b on b.id = a.id inner join @temp_c as c on c.id = a.id right outer join @temp_d as d on d.id = a.id id id id id ----------- ----------- ----------- ----------- NULL NULL NULL 1 2 2 2 2 NULL NULL NULL 3 NULL NULL NULL 4 NULL NULL NULL 5 ``` So if you switch to the `left join`, results will not be the same. ``` select * from @temp_d as d left outer join @temp_a as a on a.id = d.id left outer join @temp_b as b on b.id = d.id left outer join @temp_c as c on c.id = d.id id id id id ----------- ----------- ----------- ----------- 1 1 NULL 1 2 2 2 2 3 3 3 NULL 4 4 NULL 4 5 NULL 5 NULL ``` The only way to do this without the right join is to use common table expression or subquery ``` select * from @temp_d as d left outer join ( select * from @temp_a as a inner join @temp_b as b on b.id = a.id inner join @temp_c as c on c.id = a.id ) as q on ... ```
When or why would you use a right outer join instead of left?
[ "", "sql", "database", "right-join", "" ]
firebug is quite useful tool that I can't think myself living without it. I also downloaded the js file that helps you get similar functionality when using IE6 hoping it would help me resolve some issues, however, the messages I receive are not quite friendly such as: "Expected ':' (default2.aspx,16)" - on line 16 there is nothing that can possibly expect a ":" or "Object doesn't support this property or method (default2.aspx,198)" on line 198 nothing interesting that can require any support for anything. my site looks like a different web site in IE6.. most of the css doesnt work, some of the jquery functions doesnt work and I need to get this site work in IE6. Any help would be appreciated in terms of; * how to know what the messages (like the ones above) mean in IE6 and how to effectively debug js in IE6? * where to start for css compatibility.. e.g. shall I create different css files for different browsers and load them by detecting the browser? or are there any common issues and hacks? I am lost so please give me any direction to start..
You debug javascript in IE6 with:- [Microsoft Script Debugger](http://www.microsoft.com/downloads/details.aspx?familyid=2F465BE0-94FD-4569-B3C4-DFFDF19CCD99&displaylang=en) The [QuirksMode](http://www.quirksmode.org/) website is useful site to determine which bits of CSS is implemented in what way by which browser. Note IE6 "standards" mode rendering is notoriously buggy.
You can try [Companion JS](http://www.my-debugbar.com/wiki/CompanionJS/HomePage). It is pretty good with respect to debugging. It requires Microsoft Script Debugger as well. Companion JS thankfully supports "console.log" (via firebug). It is free tool. [Debug-bar](http://www.debugbar.com/) is a good CSS-DOM-Javascript debugger, but it is not free for commercial purposes.
debugging javascript for IE6
[ "", "javascript", "css", "debugging", "internet-explorer-6", "cross-browser", "" ]
Imagine that you have several links on a page. When you clicked, a div gets updated via AJAX. The updated div includes data from the database. According to this scenario, every time a link is clicked, the date is grabbed from the database and injected into the div. Would you... 1. support this scenario or... 2. would load each link's content in several hidden divs and display relevant div on each link click. This way the ajax call is only called once..
depends... is the content going to change? If so... Ajax every time. If not? Ajax once(or zero times if posible)
If the data you are retrieving is changed regularly and needs to be up to date, I would choose option 1, If not, I would choose option 2 and that way opt to reduce network traffic and increase performance. You could even make option 3 and render the data (in hidden divs) when the page loads, that way you wouldnt need ajax at all.
ajax in each time or load everything at once
[ "", "javascript", "jquery", "css", "ajax", "dom", "" ]
Our web page is only available internally in our company and we am very intrested in being able to offer interactive .net usercontrols on our departments website in the **.Net 2.0** enviorment. I have been successful with embeding the object as so: ``` <object id="Object1" classid="http:EmbedTest1.dll#EmbedTest1.UserControl1" width="400" height="400"> <param name="TestStr" value="Test Param String" /> </object> ``` The control worked just fine and the value was passed to the control without issue. But I had a problem with passing subsequent values back to the embedded control **attempt to Recieve event from control:** **attempt to update control:** ``` <script type="text/javascript"> function UpdateStr() { Object1.Text = "update string"; } </script> ``` Reference: <http://www.15seconds.com/issue/030610.htm> <http://windowsclient.net/articles/iesourcing.aspx> **Questions:** 1. Is this technology outdated? - if so is there a replacement 2. Should I just work with action script instead of trying this? 3. I have got this to partially work and I was attempting to connect to a webservice that I have running and I got many security exceptions...I didn't get the same exceptions when I used action scipt2 in the same manner? (side note : - how do i paste html script examples?) Thanks. Brad
1. Not out-dated so much as rarely used, and IE-only. If you want web-like deployment for desktop apps, use ClickOnce. If you want C# code that runs in the browser without security issues, use Silverlight. You could also look at XBAPs, which are sandboxed WPF apps that run in the browser, works on IE and Firefox, but requires the full .NET to be installed client-side, whereas Silverlight does not have this problem. **Bottom line:** look at Silverlight. 2. That's certainly an option. If you're more familiar with the Microsoft stack, you should try Silverlight, where you can code C# against a subset of the .NET framework right inside the browser. 3. We've used .NET controls in web pages internally and had a wide variety of strange issues, mostly related to scripting or security. Hard to determine the problem without more information. p.s. write all code examples using the <pre> tags. There's a "code sample" button on the toolbar.
If the things that you are doing with the Windows Controls could be done with ASP.NET web controls instead, I recommend that you consider switching. You'll have much better control over the exchange of info from the client to the server.
c# hosting a usercontrol in IE
[ "", "c#", "internet-explorer", ".net-2.0", "user-controls", "" ]
Is it possible to make a public method private in a subclass? I don't want other classes extending this one to be able to call some of the methods. Here is an example: ``` class A: def __init__(self): #do something here def method(self): #some code here class B(A): def __init__(self): A.__init__(self) #additional initialization goes here def method(self): #this overrides the method ( and possibly make it private here ) ``` from this point forward, I don't want any class that extends from B to be able to call `method`. Is this possible? EDIT: a "logical" reason for this is that I don't want users to call methods in the wrong order.
Python is distributed as source. The very idea of a private method makes very little sense. The programmer who wants to extend `B`, frustrated by a privacy issue, looks at the source for `B`, copies and pastes the source code for `method` into the subclass `C`. What have you gained through "privacy"? The best you can hope for is to frustrate your potential customers into copying and pasting. At worst, they discard your package because they can't extend it. And yes, all open source is extended in one way or another. You can't foresee everything and every use to which you code will be put. Preventing some future use is hard to do when the code is distributed as source. See [How do I protect Python code?](https://stackoverflow.com/questions/261638/how-do-i-protect-python-code) --- **Edit** On "idiot-proof" code. First, python is distributed as source 90% of the time. So, any idiot who downloads, installs, and then refuses to read the API guide and calls the methods out of order still has the source to figure out what went wrong. We have three classes of idiots. * People who refuse to read the API guide (or skim it and ignore the relevant parts) and call the methods out of order in spite of the documentation. You can try to make something private, but it won't help because they'll do something else wrong -- and complain about it. [I won't name names, but I've worked with folks who seem to spend a lot of time calling the API's improperly. Also, you'll see questions like this on SO.] You can only help them with a working code sample they can cut and paste. * People who are confused by API's and call the methods every different way you can imagine (and some you can't.) You can try to make something private, but they'll never get the API. You can only help them by providing the working code sample; even then, they'll cut and paste it incorrectly. * People who reject your API and want to rewrite it to make it "idiot proof". You can provide them a working code sample, but they don't like your API and will insist on rewriting it. They'll tell you that your API is crazy and they've improved on it. You can engage these folks in an escalating arms race of "idiot-proofing". Everything you put together they take apart. At this point, what has privacy done for you? Some people will refuse to understand it; some people are confused by it; and some people want to work around it. How about public, and let the folks you're calling "idiots" learn from your code?
Contrary to popular fashion on this subject, there **are** legitimate reasons to have a distinction between public, private, and protected members, whether you work in Python or a more traditional OOP environment. Many times, it comes to be that you develop auxiliary methods for a particularly long-winded task at some level of object specialization. Needless to say, you really don't want these methods inherited by any subclass because they make no sense in the specialized context and shouldn't even be visible; and yet they are visible, and they diminish the utility of things like tab completion, object navigators, and other system software, because everything at all different levels of abstraction get flattened and thrown together. These programming aids are not trivial, mind you. They are only trivial if you're a student and enjoy doing the same thing a million times just because you're learning how. Python historically developed in such a way that to implement the public/private distinction became increasingly difficult due to ideological inertia and compatibility concerns. That's the plain truth. It would be a real headache for everyone to change what they've been doing. Consequently, we now have a million Python fans out there, all of whom have read the same one or two original articles deciding unequivocally that the public/private distinction is "unpythonic". These people, for lack of critical thought or fairness to wide-spread, common practices, instantly use this occasion to accrete a predictable slew of appologetics -- *De Defensione Serpentis* -- which I suspect arises not from a rational selection of the *via pythonis* (the pythonic way) but from neglect of other languages, which they either choose not to use, are not skilled at using, or are not able to use because of work. As someone already said, the best you can do in Python to produce an effect similar to private methods is to prepend the method name with `__` (two underscores). On the other hand, the only thing this accomplishes, practically speaking, is the insertion of a transmogrified attribute name in the object's `__dict__`. For instance, say you have the following class definition: ``` class Dog(object): def __bark(self): print 'woof' ``` If you run `dir(Dog())`, you'll see a strange member, called `_Dog__bark`. Indeed, the only reason this trick exists is to circumvent the problem I described before: namely, preventing inheritance, overloading, and replacement of super methods. Hopefully there will be some standardized implementation of private methods in the future, when people realize that tissue need not have access to the methods by which the individual cell replicates DNA, and the conscious mind need constantly figure out how to repair its tissues and internal organs.
Making a method private in a python subclass
[ "", "python", "oop", "inheritance", "" ]
I have a very very simple SQL string that MS Access doesn't seem to like. > Select Top 5 \* From news\_table Order By news\_date This is returning ALL rows from the news\_table not just the Top 5. I thought this was a simple SQL statement, apparently it is not. Any fixes or idea as to why this is not working? Thanks!
Does this do the trick? ``` select top 5 * from (select * from news_table order by news_date) ``` I don't know why the original doesn't work. Maybe it's a quirk with Access. Edit: Business rules weren't specified. I didn't fully understand that the goal was to rank the table first and get the top 5 dates. It could have been to get the first 5 records and then rank them. I can't reproduce your problem in my version of Access. Weird.
Select Top n selects all records where records are equal, that is, if you select Top 2 and you have 20 date1 and 20 date2, 40 records will be selected. If there is a keyfield, ``` Select Top 5 * Order By KeyField ``` Should return 5 records, because keyfield is unique.
Why doesn't Select Top 5 From news_table order by news_date work?
[ "", "sql", "ms-access", "" ]
I want to cleanup some javascript files and reformat them with nice indents, etc, Are there recommendations for utilities to do this under Windows?
[Beautify Javascript](http://elfz.laacz.lv/beautify/) is a good, simple option. (Oops. Thought I grabbed the link for the app, not the home page.) ;)
Try the online [JavaScript Tidy](http://www.howtocreate.co.uk/tutorials/jsexamples/JSTidy.html) > Several attempts have been made to > produce programs to reformat code, but > these often fail to cope with > situations such as '{', '}' or ';' > characters inside strings, regular > expressions, or comments, so **virtually > all of them end up with broken code**. > However, browsers already have their > own parsers built in that deal with > all of these situations. **This script > hooks into the browser's own parser, > by wrapping the code in a function > then using the native toString method > to obtain the tidied code.** As a > result, it relies on the browser > producing a tidied output, which there > is no requirement for them to do. In > fact, it relies on the browser > decompiling to tidied code instead of > just retaining the original, which is > an expensive process in terms of > performance, and leads to extra > complexity when trying to make sure > the decompiled code still works, so > not all browsers choose to do it this > way. > > For best results, use Opera 9.2x- (not > 9.5+), Safari or Konqueror on this page. It partially works in Firefox > (nested functions are not tidied, > meaning that most scripts you want to > tidy still end up unreadable), and > fails to reformat code in IE and iCab > 3-. Since you can always keep a copy > of Opera 9.2 on your computer (as well > as whatever the current version is), I > recommend you use Opera, and keep a > copy of it around for use with JSTidy.
Is there a windows utility similar to HTML Tidy for Javascript?
[ "", "javascript", "editor", "code-formatting", "" ]
What does it mean to call a class like this: ``` class Example { public: Example(void); ~Example(void); } int main(void) { Example ex(); // <<<<<< what is it called to call it like this? return(0); } ``` Like it appears that it isn't calling the default constructor in that case. Can someone give a reason why that would be bad? Thanks for all answers.
Currently you are trying to call the default constructor like so. ``` Example ex(); ``` This is not actually calling the default constructor. Instead you are defining a function prototype with return type Example and taking no parameters. In order to call the default constructor, omit the ()'s ``` Example ex; ```
This declares a function prototype for a function named `ex`, returning an `Example`! You are *not* declaring and initializing a variable here.
C++ Question about default constructor
[ "", "c++", "class", "" ]
I added an XML file as an embedded resource in my class library by using the accessing the project properties in Visual Studio and then Resources | Add Resource | Add Existing File... I've tried to access the file using the following code, but I keep getting a null reference returned. Anyone have any ideas? ``` var path = Server.MapPath("~/bin/MyAssembly.dll"); var assembly = Assembly.LoadFile(path); var stream = assembly.GetManifestResourceStream("MyNamespace.filename.xml"); ```
The [MSDN page for GetManifestResourceStream](http://msdn.microsoft.com/en-us/library/xc4235zt.aspx) makes this note: > This method returns a null reference > (Nothing in Visual Basic) if a private > resource in another assembly is > accessed and the caller does not have > ReflectionPermission with the > ReflectionPermissionFlag.MemberAccess > flag. Have you marked the resource as "public" in your assembly?
I find it much easier to use the "Resources" tab of the project's properties dialog in Visual Studio. Then you have a generated strongly typed reference to your resource through: ``` Properties.Resources.Filename ```
How can I retrieve an embedded xml resource?
[ "", "c#", "asp.net", "resources", "assemblies", "" ]
Is it possible to create a cursor from an image and have it be semi-transparent? I'm currently taking a custom image and overylaying the mouse cursor image. It would be great if I could make this semi-transparent, but not necessary. The sales guys love shiny. Currently doing something like this: ``` Image cursorImage = customImage.GetThumbnailImage(300, 100, null, IntPtr.Zero); cursorImage.SetResolution(96.0F, 96.0F); int midPointX = cursorImage.Width / 2; int midPointY = cursorImage.Height / 2; Bitmap cursorMouse = GetCursorImage(cursorOverlay); Graphics cursorGfx = Graphics.FromImage(cursorImageCopy); cursorGfx.DrawImageUnscaled(cursorMouse, midPointX, midPointY); Cursor tmp = new Cursor(cursorImage.GetHicon()); ``` [alt text http://members.cox.net/dustinbrooks/drag.jpg](http://members.cox.net/dustinbrooks/drag.jpg)
I've tried following example, and it was working fine... ``` public struct IconInfo { public bool fIcon; public int xHotspot; public int yHotspot; public IntPtr hbmMask; public IntPtr hbmColor; } [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo); [DllImport("user32.dll")] public static extern IntPtr CreateIconIndirect(ref IconInfo icon); public static Cursor CreateCursor(Bitmap bmp, int xHotSpot, int yHotSpot) { IntPtr ptr = bmp.GetHicon(); IconInfo tmp = new IconInfo(); GetIconInfo(ptr, ref tmp); tmp.xHotspot = xHotSpot; tmp.yHotspot = yHotSpot; tmp.fIcon = false; ptr = CreateIconIndirect(ref tmp); return new Cursor(ptr); } ``` And i've put this on button click event (you can call from where you like): ``` Bitmap b = new Bitmap("D:/Up.png"); this.Cursor = CreateCursor(b, 5, 5); ``` And the Up.png image is saved with 75% opacity in AdobePhotoshop.
On the top of my head (I would try that first): 1. create new bitmap with same size as original, but with ARGB structure 2. drawimage: existing bitmap to the new bitmap 3. access raw bitmap data, and replace A bytes with 128 You should have nice semitransparent bitmap there. If performance allows, you can scan for fully transparent pixels and set A to zero for them!
Create a semi-transparent cursor from an image
[ "", "c#", "winforms", "transparency", "mouse-cursor", "" ]
Very similar to [this question](https://stackoverflow.com/questions/157646/best-way-to-encode-text-data-for-xml), except for Java. What is the recommended way of encoding strings for an XML output in Java. The strings might contain characters like "&", "<", etc.
Very simply: use an XML library. That way it will actually be *right* instead of requiring detailed knowledge of bits of the XML spec.
As others have mentioned, using an XML library is the easiest way. If you do want to escape yourself, you could look into [`StringEscapeUtils`](https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringEscapeUtils.html) from the [Apache Commons Lang](http://commons.apache.org/lang/) library.
Best way to encode text data for XML in Java?
[ "", "java", "xml", "encoding", "" ]
``` #include "iostream" class A { private: int a; public : A(): a(-1) {} int getA() { return a; } }; class A; class B : public A { private: int b; public: B() : b(-1) {} int getB() { return b; } }; int main() { std::auto_ptr<A> a = new A(); std::auto_ptr<B> b = dynamic_cast<std::auto_ptr<B> > (a); return 0; } ``` ERROR: cannot dynamic\_cast `(&a)->std::auto\_ptr<\_Tp>::get() const
Well, `std::auto_ptr<B>` is not derived from `std::auto_ptr<A>`. But `B` is derived from `A`. The auto\_ptr does not know about that (it's not that clever). Looks like you want to use a shared ownership pointer. `boost::shared_ptr` is ideal, it also provides a dynamic\_pointer\_cast: ``` boost::shared_ptr<A> a = new A(); boost::shared_ptr<B> b = dynamic_pointer_cast<B> (a); ``` For auto\_ptr, such a thing can't really work. Because ownership will move to `b`. But if the cast fails, b can't get ownership. It's not clear what to do then to me. You would probably have to say if the cast fails, a will keep having the ownership - which sounds like it will cause serious trouble. Best start using shared\_ptr. Both `a` and `b` then would point to the same object - but `B` as a `shared_ptr<B>` and `a` as a `shared_ptr<A>`
dynamic cast doesn't work that way. `A : public B` does not imply `auto_ptr<A> : public auto_ptr<B>`. This is why boost's `shared_ptr` provides `shared_dynamic_cast`. You could write an `auto_ptr` dynamic cast though: ``` template<typename R, typename T> std::auto_ptr<R> auto_ptr_dynamic_cast(std::auto_ptr<T>& in) { auto_ptr<R> rv; R* p; if( p = dynamic_cast<R*>( in.get() ) ) { in.release(); rv = p; } return rv; ``` } Just be aware of what happens here. Since `auto_ptr`s have ownership semantics, a successful downcast means the original more generally typed, auto\_ptr no longer has ownership.
Why does this dynamic_cast of auto_ptr fail?
[ "", "c++", "casting", "" ]
Python for Windows by default comes with IDLE, which is the barest-bones IDE I've ever encountered. For editing files, I'll stick to emacs, thank you very much. However, I want to run programs in some other shell than the crappy windows command prompt, which can't be widened to more than 80 characters. IDLE lets me run programs in it *if* I open the file, then hit F5 (to go Run-> Run Module). I would rather like to just "run" the command, rather than going through the rigmarole of closing the emacs file, loading the IDLE file, etc. A scan of google and the IDLE docs doesn't seem to give much help about using IDLE's shell but not it's IDE. Any advice from the stack overflow guys? Ideally I'd either like * advice on running programs using IDLE's shell * advice on other ways to run python programs in windows outside of IDLE or "cmd". Thanks, /YGA
For an interactive interpreter, nothing beats [IPython](http://ipython.scipy.org/). It's superb. It's also free and open source. On Windows, you'll want to install the readline library. Instructions for that are on the IPython installation documentation. [Winpdb](http://winpdb.org/) is my Python debugger of choice. It's free, open source, and cross platform (using wxWidgets for the GUI). I wrote a [tutorial on how to use Winpdb](http://code.google.com/p/winpdb/wiki/DebuggingTutorial) to help get people started on using graphical debuggers.
You can easily widen the Windows console by doing the following: * click the icon for the console window in the upper right * select **Properties** from the menu * click the **Layout** tab * change the **Window Size** > Width to 140 This can also be saved universally by changing the **Defaults** on the menu.
Cleanest way to run/debug python programs in windows
[ "", "python", "windows", "python-idle", "" ]
I am having problems with my JScript code. I am trying to loop through all of the rows in a table and add an `onclick` event. I can get the `onclick` event to add but have a couple of problems. The first problem is that all rows end up getting set up with the wrong parameter for the `onclick` event. The second problem is that it only works in IE. Here is the code excerpt: ``` shanesObj.addTableEvents = function(){ table = document.getElementById("trackerTable"); for(i=1; i<table.getElementsByTagName("tr").length; i++){ row = table.getElementsByTagName("tr")[i]; orderID = row.getAttributeNode("id").value; alert("before onclick: " + orderID); row.onclick=function(){shanesObj.tableRowEvent(orderID);}; }} shanesObj.tableRowEvent = function(orderID){ alert(orderID);} ``` The table is located at the following location... <http://www.blackcanyonsoftware.com/OrderTracker/testAJAX.html> The id's of each row in sequence are... 95, 96, 94... For some reason, when `shanesObj.tableRowEvent` is called, the `onclick` is set up for all rows with the last value id that went through iteration on the loop (94). I added some alerts to the page to illustrate the problem.
When a function is called in javascript, the first thing that happens is that the interpreter sets the scope chain to the state it was in when the function was defined. In your case the scope chain looks like: ``` GLOBAL | CAll addTableEvents | CALL onclick ``` So when the variable *orderID* is stumbled upon by the javascript interpreter it searches the scope chain for that variable. There is no *orderID* defined inside your *onclick* function, so the next spot to look is inside *addTableEvents*. You would think *orderID* is defined here, but since you did not declare *orderID* with the var keyword, *orderID* became a global variable, so *orderID* is not found inside *addTableEvents*. The last spot to look is inside GLOBAL, and sure enough it is there, and its value is the last one which it was assigned, and in this case its the last value of *orderID = row.getAttributeNode("id").value;* in the for loop. To see this more clearly look at the following ``` shanesObj.addTableEvents = function(){ table = document.getElementById("trackerTable"); for(i=1; i<table.getElementsByTagName("tr").length; i++){ row = table.getElementsByTagName("tr")[i]; orderID = row.getAttributeNode("id").value; alert("before onclick: " + orderID); row.onclick=function(){var orderID = orderID; shanesObj.tableRowEvent(orderID);}; } orderID = -1; } shanesObj.tableRowEvent = function(orderID){ alert(orderID); } ``` The result of a click here will always be -1. So, to get around this problem, I suggest you drop all the extra and unneeded code and use something like the following, ``` for(i=1; i<table.getElementsByTagName("tr").length; i++){ row = table.getElementsByTagName("tr")[i]; row.onclick=function(){shanesObj.tableRowEvent(this.id);}; } ``` Just access the id attribute directly from the called object. P.S. I have no idea why your code doesn't work in IE (it worked in my IE7).
Why not attach the event handler to the table and grab the rowindex of the cell that fired the click event inside the click handler.
Javascript Onclick with Table Rows
[ "", "javascript", "onclick", "dom-events", "" ]
Why is it impossible to have a reference to void? The only thing I found in the C++ Standard is this line, at **8.3.2.1** > A declarator that specifies the type "reference to *cv* void" is ill-formed. Why is it that way? Why can't I write a "generic" function that accept a `void&`? Just to be clear, I have no useful application in mind where using a reference-to-void could be better than using templates, but I'm just curious about the rationale for forbidding this construct. --- To clarify a little, I understand that using a reference-to-void "as is" would be as meaningless as dereferencing a pointer-to-void. However, I could cast it to a reference-to-*sometype* in order to use it, couldn't I? In fact, I don't see why the following snippet can work... ``` void foo(void *data) { int *i = reinterpret_cast<int*>(data); // do something with i } ``` ...while this one cannot: ``` void foo(void &data) { int &i = reinterpret_cast<int&>(data); // do something with i } ```
If you did have a reference to void, what would you do with it? It wouldn't be a number, or a character, or a pointer, or anything like that. Your hypothetical generic function couldn't perform any operation on it, except taking its address (and not its size). "void" has two uses: to disclaim any knowledge of type (as in void \*), and to specify nothing as opposed to something (void function return). In neither case is it possible to say anything about a void something except that it may have an address. If you can't think of a way something can be useful, and I can't, that is at least evidence that something is useless, and that may well be at least part of the rationale here.
OK, one thing is bugging me about this. The idea of a `void*`, as mentioned above, is that you still have a valid variable containing an address, but the type is being ignored. This seems allowable since we can still work with the address data - the type is somewhat superfluous (or less important) in this context. Dereferencing it is bad, because to try and *access a member* doesn't make sense e.g. `p.mem`. We don't know what class to refer to, and thus the memory to jump to, the vtable pointers to follow. However, it'd then seem to make sense that `p` on its own would be OK since it'd only refer to the object, but none of its data. No class information is needed to do so, just the address. I understand there's absolutely no use for this, but it's important in defining when things break down. Allowing this notion, a C++ reference (constantly dereferenced but not accessing anything) e.g. `void& ref = static_cast< &void >(obj)` also makes sense, and thus would allow void references. I'm not saying anyone should take it up with those in charge, but from a "making sense" point of view, it'd seem correct, no? As Luc Touraille pointed out above (at least, this is my interpretation), it could be implemented, but the issue is a semantic one. The reasonable explanation I could come to was that since an object variable is a "tag" for a sequence of memory, the type is of important semantic value. Thus, the pointer, being thought of as a variable with an address value, treats the type as somewhat superfluous - not key to defining it. Would anyone agree with that?
Why is it impossible to have a reference-to-void?
[ "", "c++", "reference", "void-pointers", "" ]
What's the purpose of implementing the IDisposable interface? I've seen some classes implementing it and I don't understand why.
If your class creates unmanaged resources, then you can implement IDisposable so that these resources will be cleaned up properly when the object is disposed of. You override Dispose and release them there.
When your classes makes use of some system resource, it's the class' responsibility to make sure the resource is freed too. By .Net design you're supposed to do that in the Dispose method of the class. The IDisposable interface marks that your class needs to free resource when it's no longer in use, and the Dispose method is made available so that users of your class can call it to free the consumed resources. The IDisposable method is also essential if you want auto clean-up to work properly and want to use the using() statement.
What's the purpose of implementing the IDisposable interface?
[ "", "c#", "idisposable", "" ]
I'm working on a customer's website, and they've asked for a shopping cart. They need to use securetrading.net for the payment, so I don't need to ask for any credit card details. All I need to do is keep track of the items in their cart. I've read about using PHP sessions, but I'm concerned about security there. Is this not a problem if the only information I'm storing is product codes and quantities? Otherwise, is it worth using a MySQL database? I'm sorry if this seems like an obvious thing to know, but this is my first time implementing this kind of thing!
There is tutorial for simple/small php/MySQL cart that keeps cart status in sessions, there is even downloadable demo code and online demo. <http://v3.thewatchmakerproject.com/journal/276/building-a-simple-php-shopping-cart> I used it when full blown online shoping programs were just that "over blown". Same as you there was no need to take cc data, user registration, etc... just siple place to send selected items to payment gateway's purchase proces and after that to forget about it. That is what client wanted, and that is what he got on the end (my first choice was magento but it was too complicated for clients 3 products). Of course you need to extend it to fit your need but it's good starting point for something simple.
I'd use a prefab open-source solution. You really don't want to let in silly security issues when you're dealing with other people's money. [Magento](http://www.magentocommerce.com) comes to mind. It's certainly the slickest I've seen in a while... And there appears to be securetrading support if [you hack it in yourself](http://www.magentocommerce.com/boards/viewthread/4617/).
Best way to implement shopping cart using PHP/MySQL
[ "", "php", "shopping-cart", "" ]
I have a stored proc that processes a large amount of data (about 5m rows in this example). The performance varies wildly. I've had the process running in as little as 15 minutes and seen it run for as long as 4 hours. For maintenance, and in order to verify that the logic and processing is correct, we have the SP broken up into sections: 1. `TRUNCATE` and populate a work table (indexed) we can verify later with automated testing tools. 2. Join several tables together (including some of these work tables) to product another work table Repeat 1 and/or 2 until a final output is produced. My concern is that this is a single SP and so gets an execution plan when it is first run (even `WITH RECOMPILE`). But at that time, the work tables (permanent tables in a Work schema) are empty. I am concerned that, regardless of the indexing scheme, the execution plan will be poor. I am considering breaking up the SP and calling separate SPs from within it so that they could take advantage of a re-evaluated execution plan after the data in the work tables is built. I have also seen reference to using EXEC to run dynamic SQL which, obviously might get a `RECOMPILE` also. I'm still trying to get `SHOWPLAN` permissions, so I'm flying quite blind.
Are you able to determine whether there are any locking problems? Are you running the SP in sufficiently small transactions? Breaking it up into subprocedures should have no benefit. Somebody should be concerned about your productivity, working without basic optimization resources. That suggests there may be other possible unseen issues as well.
Grab the free copy of "Dissecting Execution Plan" in the link below and maybe you can pick up a tip or two from it that will give you some idea of what's really going on under the hood of your SP. <http://dbalink.wordpress.com/2008/08/08/dissecting-sql-server-execution-plans-free-ebook/>
Stored Procedure Execution Plan - Data Manipulation
[ "", "sql", "sql-server", "stored-procedures", "sql-execution-plan", "" ]
Here's a simplified version of my class: ``` public abstract class Task { private static object LockObject = new object(); protected virtual void UpdateSharedData() { } protected virtual void UpdateNonSharedData() { } public void Method() { lock(LockObject) { UpdateSharedData(); } UpdateNonSharedData(); } } ``` I'm trying to hide the locking code from derived classes. But I only want to obtain the lock if the derived class overrides UpdateSharedData; if it doesn't, I don't want the method to block and wait on all of the other running instances that do update shared data before it updates the non-shared data. So the (seemingly) obvious thing for Method to do is to check and see if the current instance's implementation of UpdateSharedData has overriden the base class's implementation. I'm pretty sure this isn't possible without using reflection, and it's probably not desirable to do that. I've thought of some workarounds to this, but they're all pretty awkward: * Add a protected bool property that the derived class's constructor sets, and check that property to see if a lock is needed. That's doing a pretty terrible job of hiding the locking code from the derived classes. * Make the UpdateSharedData method a delegate property, have any derived class set the property to a private method in its constructor, and only obtain the lock if the delegate isn't null. That's better, but it still kind of sucks.
What if you defined an abstract Task and a IHasSharedData interface, then in Method you check if the derived Task implements IHasSharedData before doing the lock. Only classes that implement the interface need wait. I realize that this avoids answering the actual question, but I think it would be a cleaner solution than using reflection. Hopefully, you'd find a better name for the interface that more closely matches what the classes actually do. ``` public interface IHasSharedData { void UpdateSharedData(); } public abstract class Task { private static object LockObject = new object(); protected virtual void UpdateNonSharedData() { } public void Method() { if (this is IHasSharedData) { lock(LockObject) { UpdateSharedData(); } } UpdateNonSharedData(); } } public class SharedDataTask : Task, IHasSharedData { public void UpdateSharedData() { ... } } ```
You can do this check with a smidge of reflection: ``` bool IsUpdateSharedDataOverridden() { Type t = this.GetType(); MethodInfo m = subType.GetMethod("UpdateSharedData"); return m.DeclaringType == t && m.GetBaseDefinition().DeclaringType == typeof(Task); } ```
Can a base class determine if a derived class has overridden a virtual member?
[ "", "c#", "reflection", "inheritance", "overriding", "" ]
I have a twenty byte hex hash that I would like to store in a django model. If I use a text field, it's interpreted as unicode and it comes back garbled. Currently I'm encoding it and decoding it, which really clutters up the code, because I have to be able to filter by it. ``` def get_changeset(self): return bin(self._changeset) def set_changeset(self, value): self._changeset = hex(value) changeset = property(get_changeset, set_changeset) ``` Here's an example for filtering ``` Change.objects.get(_changeset=hex(ctx.node())) ``` This is the approach that was recommended by a django developer, but I'm really struggling to come to terms with the fact that it's this ugly to just store twenty bytes. Maybe I'm too much of a purist, but ideally I would be able to write ``` Change.objects.get(changeset=ctx.node()) ``` The properties allow me to write: ``` change.changeset = ctx.node() ``` So that's as good as I can ask.
I'm assuming if you were writing raw SQL you'd be using a Postgres bytea or a MySQL VARBINARY. There's a [ticket with a patch](http://code.djangoproject.com/ticket/2417) (marked "needs testing") that purportedly makes a field like this (Ticket 2417: Support for binary type fields (aka: bytea in postgres and VARBINARY in mysql)). Otherwise, you could probably try your hand at writing a [custom field type](http://docs.djangoproject.com/en/dev/howto/custom-model-fields/).
Starting with 1.6, Django has [`BinaryField`](https://docs.djangoproject.com/en/1.11/ref/models/fields/#binaryfield) allowing to store raw binary data. However, for hashes and other values up to 128 bits it's more efficient (at least with the PostgreSQL backend) to use [`UUIDField`](https://docs.djangoproject.com/en/1.11/ref/models/fields/#uuidfield) available in Django 1.8+.
Storing a binary hash value in a Django model field
[ "", "python", "django", "encoding", "django-models", "binary-data", "" ]
Usually when defining a DAO, you would have a setter for the datasource on the DAO object. My problem is that our datasource varies dynamically based on the request to the server. i.e. every request can access different database instance. The request holds logical properties, that later can be used to retrieve the connection to the DB of the request. So when dependency injecting the DAO to the business logic object, I need a way to set the properties on the DAO at runtime (not configuration time). One solution is to store the datasource on the thread local, but I don't really like messing with thread local variables. Another option is to have an initialize method on the business logic object that calls initialize on the DAO with the request properties. I guess it's a common problem, can you suggest a common solution?
It sounds like your problem is that you are creating a single DAO instance for your application. You either need to create a separate instance for each datasource (maybe making some kind of dao controller to manage it all for you) or possibly allow your methods in your dao to be static and pass all information about how to connect to the datasource along with the data you are persisting into every method.
Your problem is a little confusing. Having one DAO access multiple different datasources would seem to be a maintenance nightmare. As a result, you should define one DAO interface containing all the methods you would want to call. For each database you are connecting to I would construct a new class that implements your DAO interface. This allows you to have multiple implementations. I would then store these implementations (each that has its own datasource) in a Map (java.util.Map), using your "logical properties" as the key to the map. Since all your DAO Implementations implement your interface you will be able to cast them to the interface and use them interchangeably. On your business object, you would inject the Map of DAO implementations. I hope this helps your design.
How to design DAOs when the datasource varies dynamically
[ "", "java", "spring", "dao", "" ]
In javascript, what is the best way to parse an INT from a string which starts with a letter (such as "test[123]")? I need something that will work for the example below. My JS: ``` $(document).ready(function() { $(':input').change( function() { id = parseInt($(this).attr("id")); //fails for the data below alert(id); }); } ``` My generated HTML: ``` <select id="attribute[123]"> <!-- various options --> </select> <select id="attribute[456]"> <!-- various options --> </select> ``` Thank you!
You could use a regular expression to match the number: ``` $(this).attr("id").match(/\d+/) ```
``` parseInt(input.replace(/[^0-9-]/,""),10) ```
Parsing an Int from a string in javascript
[ "", "javascript", "jquery", "" ]
We have a crystal report that we need to send out as an e-mail, but the HTML generated from the crystal report is pretty much just plain ugly and causes issues with some e-mail clients. I wanted to export it as rich text and convert that to HTML if it's possible. Any suggestions?
I would check out this tool on CodeProject RTFConverter. This guy gives a great breakdown of how the program works along with details of the conversion. [Writing Your Own RTF Converter](http://www.codeproject.com/KB/recipes/RtfConverter.aspx "Writing Your Own RTF Converter")
There is also a sample on the MSDN Code Samples gallery called [Converting between RTF and HTML](http://matthewmanela.com/blog/converting-rtf-to-html/) which allows you to convert between HTML, RTF and XAML.
Convert Rtf to HTML
[ "", "c#", "html", "rtf", "" ]
I wondering what the "best practice" way (in C#) is to implement this xpath query with LINQ: ``` /topNode/middleNode[@filteringAttribute='filterValue']/penultimateNode[@anotherFilterAttribute='somethingElse']/nodesIWantReturned ``` I would like an IEnumerable list of the 'nodesIWantReturned', but only from a certain section of the XML tree, dependent on the value of ancestor attributes.
A more *verbal* solution: ``` var nodesIWantReturned = from m in doc.Elements("topNode").Elements("middleNode") from p in m.Elements("penultimateNode") from n in p.Elements("nodesIWantReturned") where m.Attribute("filteringAttribute").Value == "filterValue" where p.Attribute("anotherFilterAttribute").Value == "somethingElse" select n; ```
In addition to the Linq methods shown, you can also import the `System.Xml.XPath` namespace and then use the [`XPathSelectElements`](http://msdn.microsoft.com/en-us/library/bb342176.aspx) extension method to use your XPath query directly. It is noted in the class that these methods are slower than 'proper' Linq-to-XML, however a lot of the time this isn't too important, and sometimes it's easier just to use XPath (it's certainly a lot terser!). ``` var result = doc.XPathSelectElements("your xpath here"); ```
What is the LINQ to XML equivalent for this XPath
[ "", "c#", "xml", "linq", "xpath", "" ]
I was just wondering whether there is some way to do this: I have a form in a web page, after the user submits the form, the page is redirected to another static HTML page. Is there any way to manipulate the data in the second HTML page without the help of any server code? I mean can I display the form data that the user submitted in the second page? Of course there should be a navigation, not some Ajax code to load the second page (using which it would be easy to manipulate the data).
You can use a `<form>` with GET method to go to another static HTML page with some query parameters and then grab those parameters with JavaScript: First page: ``` <form method="GET" action="page2.html"> <input type="text" name="value1"/> <input type="text" name="value2"/> <input type="submit"/> </form> ``` Second page: ``` <script type="text/javascript"> function getParams() { function decode(s) { return decodeURIComponent(s).split(/\+/).join(" "); } var params = {}; document.location.search.replace( /\??(?:([^=]+)=([^&]*)&?)/g, function () { params[decode(arguments[1])] = decode(arguments[2]); }); return params; } var params = getParams(); alert("value1=" + params.value1); alert("value2=" + params.value2); // or massage the DOM with these values </script> ```
You can access the pages GET parameters from JavaScript (*window.location.search*, which you still need to parse), and use this to pass some veriables to the static page. (I suppose there is no way to get to POST content.) You can also read and set the values of cookies from JavaScript. If you are within a frameset where a "parent" page always sticks around you could potentially also store information in there (also cross-frame-scripting is tricky and I would try to avoid that).
Data processing in HTML without server code (using just Javascript)
[ "", "javascript", "html", "web-applications", "client-side", "" ]
I can do something like this: ``` validator.showErrors({ "nameOfField" : "ErrorMessage" }); ``` And that works fine, however if I try and do something like this: ``` var propertyName = "nameOfField"; var errorMessage = "ErrorMessage"; validator.showErrors({ propertyName : errorMessage }); ``` It throws an 'element is undefined' error.
What about: ``` var propertyName = "nameOfField"; var errorMessage = "ErrorMessage"; var obj = new Object(); obj[propertyName] = errorMessage; validator.showErrors(obj); ``` --- Is worth to notice that the following three syntaxes are equivalent: ``` var a = {'a':0, 'b':1, 'c':2}; var b = new Object(); b['a'] = 0; b['b'] = 1; b['c'] = 2; var c = new Object(); c.a = 0; c.b = 1; c.c = 2; ```
The reason you're getting an 'element is undefined' error there by the way, is because: ``` var propertyName = "test"; var a = {propertyName: "test"}; ``` is equivalent to.. ``` var a = {"propertyName": "test"}; ``` i.e., you're not assigning the value of propertyName as the key, you're assigning propertyName as a string to it.
jQuery Validator, programmatically show errors
[ "", "javascript", "jquery", "" ]
I want to do something like `String.Format("[{0}, {1}, {2}]", 1, 2, 3)` which returns: ``` [1, 2, 3] ``` How do I do this in Python?
The previous answers have used % formatting, which is being phased out in Python 3.0+. Assuming you're using Python 2.6+, a more future-proof formatting system is described here: <http://docs.python.org/library/string.html#formatstrings> Although there are more advanced features as well, the simplest form ends up looking very close to what you wrote: ``` >>> "[{0}, {1}, {2}]".format(1, 2, 3) [1, 2, 3] ```
You can do it three ways: --- Use Python's automatic pretty printing: ``` print([1, 2, 3]) # Prints [1, 2, 3] ``` Showing the same thing with a variable: ``` numberList = [1, 2] numberList.append(3) print(numberList) # Prints [1, 2, 3] ``` --- Use 'classic' string substitutions (ala C's printf). Note the different meanings here of % as the string-format specifier, and the % to apply the list (actually a tuple) to the formatting string. (And note the % is used as the modulo(remainder) operator for arithmetic expressions.) ``` print("[%i, %i, %i]" % (1, 2, 3)) ``` Note if we use our pre-defined variable, we'll need to turn it into a tuple to do this: ``` print("[%i, %i, %i]" % tuple(numberList)) ``` --- Use Python 3 string formatting. This is still available in earlier versions (from 2.6), but is the 'new' way of doing it in Py 3. Note you can either use positional (ordinal) arguments, or named arguments (for the heck of it I've put them in reverse order. ``` print("[{0}, {1}, {2}]".format(1, 2, 3)) ``` Note the names 'one' ,'two' and 'three' can be whatever makes sense.) ``` print("[{one}, {two}, {three}]".format(three=3, two=2, one=1)) ```
String formatting in Python
[ "", "python", "string", "formatting", "" ]
So I have ASP.NET running on the server in IIS7. I think I'm going to use MVC for some static pages and basic dynamic forms - but the majority of the client side is written in Flash/ActionScript. What's the simplest, most succint, most DRY way of building/generating proxies between client and server? Which format should I use? * JSON * SOAP * Binary And which comms protocol should I use? * WCF * HTTP via MVC Controller actions I'm probably missing some format or protocol, but basically it should be relatively efficient, not require alot of plumbing code and preferably auto-generates client-side proxies.
WSDL web services are very easy to consume in Flash and simple to create in .NET. I'd also suggest you at least look into AMF, which is Adobe's proprietary binary format for exchanging data between client and server. There are a couple of implementations for .NET, including amf.net and weborb. I've never used it, but I've heard really great things about weborb: <http://www.themidnightcoders.com/products/weborb-for-net/overview.html>
i've consumed JSON in swfs .. pretty simple using a3corelib stuff
How should client Flash(SWF) communicate with server-side .NET?
[ "", "c#", ".net", "flash", "actionscript-3", "" ]
I'm using Java SE 1.6 on Mac OS X 10.5.6. The code for my applet is as follows: ``` import java.awt.Graphics; import javax.swing.JApplet; public class HelloWorld extends JApplet { public void paint( Graphics g ) { super.paint( g ); g.drawString( "Hello World!", 25, 25 ); } } ``` I compiled this to a *.class* file. The code for my HTML file is as follows: ``` <html> <head> <title>Hello World</title> </head> <body> <applet code="HelloWorld.class" height="300" width="300"> Your browser is ignoring the applet tag. </applet> </body> </html> ``` If I run the applet with *appletviewer*, it works fine. However, if I open the HTML file in a browser, a square appears for the applet space, but the applet doesn't load. (The "Your browser is ignoring the applet tag." doesn't appear either.) The browser status bar shows two messages: **Applet HelloWorld notloaded** and **Loading Java Applet Failed...** I tried the applet with Firefox 3.0.6, Safari 3.2.1, and Opera 9.6.3. None of them could load the applet. If I try opening the HTML for one of the Java demo applets in */Developer/Examples/Java/Applets*, it loads fine in all three browsers. Is there something I'm missing here, in trying to get this simple applet to load in a browser?
Thank you for all your answers. Some of them pointed me in the right direction to figure out the source of the problem. I turned on the Java Console in Java Preferences. When I ran the applet again, the following output is what I received: Java Plug-in 1.5.0 Using JRE version 1.5.0\_16 Java HotSpot(TM) Client VM MRJ Plugin for Mac OS X v1.0.1 [starting up Java Applet Security @ Fri Feb 06 23:47:20 CST 2009] java.lang.UnsupportedClassVersionError: Bad version number in .class file at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:675) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124) at sun.applet.AppletClassLoader.findClass(AppletClassLoader.java:177) at java.lang.ClassLoader.loadClass(ClassLoader.java:316) at sun.applet.AppletClassLoader.loadClass(AppletClassLoader.java:119) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at sun.applet.AppletClassLoader.loadCode(AppletClassLoader.java:605) at sun.applet.AppletPanel.createApplet(AppletPanel.java:723) at sun.plugin.AppletViewer.createApplet(AppletViewer.java:1864) at jep.AppletFramePanel.createApplet(AppletFramePanel.java:189) at sun.applet.AppletPanel.runLoader(AppletPanel.java:652) at sun.applet.AppletPanel.run(AppletPanel.java:326) at jep.AppletFramePanel.run(AppletFramePanel.java:176) at java.lang.Thread.run(Thread.java:613) I installed Java SE 1.6 on my Mac, but I guess it didn't install a 1.6 plug-in. Also, it looks as if *.class* files get stamped with a version number when they are created. I compiled that applet with version 1.6, but tried to run it with a 1.5 plug-in, thus resulting in the *UnsupportedClassVersionError*. I re-compiled the applet with version 1.5 and tried running it in all three browsers again. Worked like a charm. Does anyone know if a 1.6 plug-in is in the works?
You do not specify a codebase property in the applet tag, so I'd guess your class can not be found. Try to enable the java console output window. You can do this in "Java Settings" (use spotlight) under the extended options tab (the one with the tree and many checkboxes). Maybe you can see some more information (like ClassNotFoundException) there. Set the setting to "Enable/Show console". Then it should show up when you start the applet.
How do I get a simple, Hello World Java applet to work in a browser in Mac OS X?
[ "", "java", "html", "macos", "applet", "" ]
I have a `System.Windows.Forms.TreeView` docked inside a panel. I am setting a node selected programmatically. What method or property would I use to have the treeview scroll the selected into view?
``` node.EnsureVisible(); ``` for example: ``` if(treeView.SelectedNode != null) treeView.SelectedNode.EnsureVisible(); ``` (see [MSDN](http://msdn.microsoft.com/en-us/library/system.windows.forms.treenode.ensurevisible.aspx))
To ensure the visibility of selected item: ``` private void EnsureItemVisible() { if(treeView1.SelectedNode == null) { return; } for (int i = treeView1.SelectedNode.Index + treeView1.VisibleCount / 2; i >= 0; i--) { if (treeView1.Nodes.Count > i && treeView1.Nodes[i] != null) { treeView1.Nodes[i].EnsureVisible(); break; } } for (int i = treeView1.SelectedNode.Index - treeView1.VisibleCount / 2; i < treeView1.Nodes.Count; i++) { if (i >= 0 && treeView1.Nodes[i] != null) { treeView1.Nodes[i].EnsureVisible(); break; } } } ``` Handle the TreeView selection has been changed: ``` private void TreeView_AfterSelect(object sender, TreeViewEventArgs e) { EnsureItemVisible(); } ```
Scroll selected TreeView node into view
[ "", "c#", "winforms", "treeview", "" ]
I can think of a few messy ways to solve this, but it strikes me that there should be a far more elegant solution than those which I've already come up with. What's the most appropriate way for an object to cleanse itself of all of its event handlers prior to being disposed. It's a shame the event handler can't be enumerated upon. In theory, is it considered more correct for the code adding the handler to an object to remember to remove it than assuming the object will clean itself up before it goes out of scope?
> In theory, is it considered more > correct for the code adding the > handler to an object to remember to > remove it than assuming the object > will clean itself up before it goes > out of scope? To the above question, I'll have to say yes. The basic theory about events is that the event firer shouldn't be responsible for managing its own handlers; whoever added the event should do cleanup.
There is a way to avoid this common problem with events - [WeakEvent pattern](https://msdn.microsoft.com/en-us/library/aa970850(v=vs.100).aspx).
Remove handlers on disposing object
[ "", "c#", ".net", "" ]
I find long sequences of standard includes annoying: ``` #include <vector> #include <string> #include <sstream> #include <iostream> ``` Considering these header files change only very rarely, is there a reason why I should not make a "std.h" file #including all std headers and just use that everywhere?
Including unnecessary header files will increase compile times.
You might like to add these to your project's standard, precompiled header file: if your project has a standard, precompiled header file, and if your files aren't supposed to be reusuable in other projects which might have a different standard header file.
Disadvantages of a <std.h> file that brings in all std headers?
[ "", "c++", "include", "" ]
I wrote a couple of Java classes—`SingleThreadedCompute` and `MultithreadedCompute`—to demonstrate the fact (or what I always thought was a fact!) that if you parallelize a compute-centric (no I/O) task on a single core machine, you don't get a speedup. Indeed my understanding is that parallelizing such tasks actually slows things down because now you have to deal with context-switching overhead. Well, I ran the classes and the parallel version unexpectedly runs faster: the single-threaded version is consistently running at just over 7 seconds on my machine, and the multithreaded version is consistently running at just over 6 seconds on my machine. Can anybody explain how this is possible? Here are the classes if anybody wants to look or try it for themselves. ``` public final class SingleThreadedCompute { private static final long _1B = 1000000000L; // one billion public static void main(String[] args) { long startMs = System.currentTimeMillis(); long total = 0; for (long i = 0; i < _1B; i++) { total += i; } System.out.println("total=" + total); long elapsedMs = System.currentTimeMillis() - startMs; System.out.println("Elapsed time: " + elapsedMs + " ms"); } } ``` Here's the multithreaded version: ``` public final class MultithreadedCompute { private static final long _1B = 1000000000L; // one billion private static final long _100M = _1B / 10L; public static void main(String[] args) { long startMs = System.currentTimeMillis(); System.out.println("Creating workers"); Worker[] workers = new Worker[10]; for (int i = 0; i < 10; i++) { workers[i] = new Worker(i * _100M, (i+1) * _100M); } System.out.println("Starting workers"); for (int i = 0; i < 10; i++) { workers[i].start(); } for (int i = 0; i < 10; i++) { try { workers[i].join(); System.out.println("Joined with thread " + i); } catch (InterruptedException e) { /* can't happen */ } } System.out.println("Summing worker totals"); long total = 0; for (int i = 0; i < 10; i++) { total += workers[i].getTotal(); } System.out.println("total=" + total); long elapsedMs = System.currentTimeMillis() - startMs; System.out.println("Elapsed time: " + elapsedMs + " ms"); } private static class Worker extends Thread { private long start, end; private long total; public Worker(long start, long end) { this.start = start; this.end = end; } public void run() { System.out.println("Computing sum " + start + " + ... + (" + end + " - 1)"); for (long i = start; i < end; i++) { total += i; } } public long getTotal() { return total; } } } ``` Here's the output from running the single-threaded version: ``` total=499999999500000000 Elapsed time: 7031 ms ``` And here's the output from running the multithreaded version: ``` Creating workers Starting workers Computing sum 0 + ... + (100000000 - 1) Computing sum 100000000 + ... + (200000000 - 1) Computing sum 200000000 + ... + (300000000 - 1) Computing sum 300000000 + ... + (400000000 - 1) Computing sum 400000000 + ... + (500000000 - 1) Computing sum 500000000 + ... + (600000000 - 1) Computing sum 600000000 + ... + (700000000 - 1) Computing sum 700000000 + ... + (800000000 - 1) Computing sum 800000000 + ... + (900000000 - 1) Computing sum 900000000 + ... + (1000000000 - 1) Joined with thread 0 Joined with thread 1 Joined with thread 2 Joined with thread 3 Joined with thread 4 Joined with thread 5 Joined with thread 6 Joined with thread 7 Joined with thread 8 Joined with thread 9 Summing worker totals total=499999999500000000 Elapsed time: 6172 ms ``` --- **EDIT: Information on the environment:** * Microsoft Windows XP Professional Version 2002, SP3 * Dell Precision 670 * Intel Xeon CPU 2.80GHz, 1 MB L2 cache Not sure how to prove it's a single core machine other than by stating the spec above and by noting that back when I bought the machine (Aug 2005), single cores were the standard and I didn't upgrade to multicore (if that was even an option... I don't remember). If there's somewhere in Windows I can check other than System Properties (which shows the info above) let me know and I'll check. --- Here are five consecutive ST and MT runs: FIVE SINGLETHREADED RUNS: total=499999999500000000 Elapsed time: 7000 ms total=499999999500000000 Elapsed time: 7031 ms total=499999999500000000 Elapsed time: 6922 ms total=499999999500000000 Elapsed time: 6968 ms total=499999999500000000 Elapsed time: 6938 ms --- FIVE MULTITHREADED RUNS: total=499999999500000000 Elapsed time: 6047 ms total=499999999500000000 Elapsed time: 6141 ms total=499999999500000000 Elapsed time: 6063 ms total=499999999500000000 Elapsed time: 6282 ms total=499999999500000000 Elapsed time: 6125 ms
I tried turning off the JIT as Pax suggested in the comment above. Pax, if you want to post a quick "Turn off the JIT" answer I'll credit your solution. Anyway turning off the JIT worked (meaning that it brought the actual results in line with the expected results). I had to back away from one billion as it was taking forever, so I went with 100 million instead. The results are much more in line with what I would expect. Here they are: **FIVE NO-JIT SINGLE-THREADED RUNS** total=4999999950000000 Elapsed time: 17094 ms total=4999999950000000 Elapsed time: 17109 ms total=4999999950000000 Elapsed time: 17219 ms total=4999999950000000 Elapsed time: 17375 ms total=4999999950000000 Elapsed time: 17125 ms --- **FIVE NO-JIT MULTITHREADED RUNS** total=4999999950000000 Elapsed time: 18719 ms total=4999999950000000 Elapsed time: 18750 ms total=4999999950000000 Elapsed time: 18610 ms total=4999999950000000 Elapsed time: 18890 ms total=4999999950000000 Elapsed time: 18719 ms --- Thanks guys for the ideas and help.
It's possible that this is due to hyper-threading and/or pipelining. From wikipedia [on hyper-threading](http://en.wikipedia.org/wiki/Hyper-threading): > Hyper-threading is an advancement over super-threading. Hyper-threading (officially termed Hyper-Threading Technology or HTT) is an Intel-proprietary technology used to improve parallelization of computations (doing multiple tasks at once) performed on PC microprocessors. A processor with hyper-threading enabled is treated by the operating system as two processors instead of one. This means that only one processor is physically present but the operating system sees two virtual processors, and shares the workload between them. From wikipedia [on piplining](http://en.wikipedia.org/wiki/Pipeline_(computing)): > In computing, a pipeline is a set of data processing elements connected in series, so that the output of one element is the input of the next one. The elements of a pipeline are often executed in parallel or in time-sliced fashion
Unexpected multithreaded result
[ "", "java", "multithreading", "concurrency", "" ]
Based on information in Chapter 7 of [3D Programming For Windows (Charles Petzold)](http://www.charlespetzold.com/3D/), I've attempted to write as helper function that projects a Point3D to a standard 2D Point that contains the corresponding screen coordinates (x,y): ``` public Point Point3DToScreen2D(Point3D point3D,Viewport3D viewPort ) { double screenX = 0d, screenY = 0d; // Camera is defined in XAML as: // <Viewport3D.Camera> // <PerspectiveCamera Position="0,0,800" LookDirection="0,0,-1" /> // </Viewport3D.Camera> PerspectiveCamera cam = viewPort.Camera as PerspectiveCamera; // Translate input point using camera position double inputX = point3D.X - cam.Position.X; double inputY = point3D.Y - cam.Position.Y; double inputZ = point3D.Z - cam.Position.Z; double aspectRatio = viewPort.ActualWidth / viewPort.ActualHeight; // Apply projection to X and Y screenX = inputX / (-inputZ * Math.Tan(cam.FieldOfView / 2)); screenY = (inputY * aspectRatio) / (-inputZ * Math.Tan(cam.FieldOfView / 2)); // Convert to screen coordinates screenX = screenX * viewPort.ActualWidth; screenY = screenY * viewPort.ActualHeight; // Additional, currently unused, projection scaling factors /* double xScale = 1 / Math.Tan(Math.PI * cam.FieldOfView / 360); double yScale = aspectRatio * xScale; double zFar = cam.FarPlaneDistance; double zNear = cam.NearPlaneDistance; double zScale = zFar == Double.PositiveInfinity ? -1 : zFar / (zNear - zFar); double zOffset = zNear * zScale; */ return new Point(screenX, screenY); } ``` On testing however this function returns incorrect screen coordinates (checked by comparing 2D mouse coordinates against a simple 3D shape). Due to my lack of 3D programming experience I am confused as to why. The block commented section contains scaling calculations that may be essential, however I am not sure how, and the book continues with the MatrixCamera using XAML. Initially I just want to get a basic calculation working regardless of how inefficient it may be compared to Matrices. Can anyone advise what needs to be added or changed?
Since Windows coordinates are z into the screen (x cross y), I would use something like ``` screenY = viewPort.ActualHeight * (1 - screenY); ``` instead of ``` screenY = screenY * viewPort.ActualHeight; ``` to correct screenY to accomodate Windows. Alternately, you could use OpenGL. When you set the viewport x/y/z range, you could leave it in "native" units, and let OpenGL convert to screen coordinates. Edit: Since your origin is the center. I would try ``` screenX = viewPort.ActualWidth * (screenX + 1.0) / 2.0 screenY = viewPort.ActualHeight * (1.0 - ((screenY + 1.0) / 2.0)) ``` The screen + 1.0 converts from [-1.0, 1.0] to [0.0, 2.0]. At which point, you divide by 2.0 to get [0.0, 1.0] for the multiply. To account for Windows y being flipped from Cartesian y, you convert from [1.0, 0.0] (upper left to lower left), to [0.0, 1.0] (upper to lower) by subtracting the previous screen from 1.0. Then, you can scale to the ActualHeight.
I've created and succesfully tested a working method by using the [3DUtils](http://www.codeplex.com/Wiki/View.aspx?ProjectName=3DTools) Codeplex source library. The real work is performed in the TryWorldToViewportTransform() method from 3DUtils. This method will not work without it (see the above link). Very useful information was also found in the article by Eric Sink: [Auto-Zoom](http://www.ericsink.com/wpf3d/A_AutoZoom.html). NB. There may be more reliable/efficient approaches, if so please add them as an answer. In the meantime this is good enough for my needs. ``` /// <summary> /// Takes a 3D point and returns the corresponding 2D point (X,Y) within the viewport. /// Requires the 3DUtils project available at http://www.codeplex.com/Wiki/View.aspx?ProjectName=3DTools /// </summary> /// <param name="point3D">A point in 3D space</param> /// <param name="viewPort">An instance of Viewport3D</param> /// <returns>The corresponding 2D point or null if it could not be calculated</returns> public Point? Point3DToScreen2D(Point3D point3D, Viewport3D viewPort) { bool bOK = false; // We need a Viewport3DVisual but we only have a Viewport3D. Viewport3DVisual vpv =VisualTreeHelper.GetParent(viewPort.Children[0]) as Viewport3DVisual; // Get the world to viewport transform matrix Matrix3D m = MathUtils.TryWorldToViewportTransform(vpv, out bOK); if (bOK) { // Transform the 3D point to 2D Point3D transformedPoint = m.Transform(point3D); Point screen2DPoint = new Point(transformedPoint.X, transformedPoint.Y); return new Nullable<Point>(screen2DPoint); } else { return null; } } ```
Projecting a 3D point to a 2D screen coordinate
[ "", "c#", "wpf", "math", "3d", "" ]
I'm working on a SQL Reporting Services report (in VS.Net 2005) which displays a count of different data in a matrix. The columns have a count on the amount of customers in a certain set. So I have several columns like these: "1 employer", "2-9 employers", "10-19 employers" and so on. The problem I have is that SQL Reporting Services sorts the columns in the matrix alphabetically. So I end up having the "10-19" column after the "1 employer" column but before the "2-9". Is there any way to fix this? Or maybe a trick to change the labels of the columns to that they sort right? Thanks.
We do a lot of SSRS Reports and this was always an issue with mdx. Here is one way we do it: Set *Sorting* in the *Grouping and Sorting Properties* to sort by this expression: ``` =iif(Fields!DataSetField.Value = "ColumnName", "zzz", Fields!DataSetField.Value) ``` Where "zzz" could be a number or whatever you need it to be to help the sort and then select *Direction* as either Ascending or Descending base on this expression.
This can also be done by adding a new column to the query for the sort order. Then right click the column group from the matrix and select group properties. On the left hand side select sorting. From here you can specify another column to sort by instead of the column header. No custom formula needed.
How to specify an order for the columns in a matrix?
[ "", "sql", "visual-studio", "reporting-services", "matrix", "" ]
Is there a product (ideally open source, but not necessary), that would enable a zero dependency deployment? every service bus or queue library I've been able to find has a dependency on one of the queue apps (like msmq), or a database. I would like a very lightweight solution that I can just add a reference to my application, build it, and deploy it with as little configuration as possible. In an ideal world, the queue/service bus would run on IIS, and allow web and rich clients to talk to it. Such a tool would be ideal for fast prototyping of large distributed systems on a local development machine.
Rhino Queues from Ayende is exactly what you are looking for, this is the blog post introducing it: <http://ayende.com/Blog/archive/2008/08/01/Rhino-Queues.aspx> I think that all of the limitations mentioned in this post have been fixed since then. From the blog post, what rhino queues is: * XCopyable, Zero Administration, Embedded, Async queuing service * Robust in the face of networking outages * System.Transactions support * Fast * Works over HTTP
In a similar vein to ShuggyCoUk's [suggestion](https://stackoverflow.com/a/546328/3195477), you could rig up a queue (or queues) using the Windows built-in ESENT database (comes already installed with Windows). There is a managed code access library (open source): <http://www.codeplex.com/ManagedEsent>. If you stick with writing / reading CLOBs or BLOBs, it should work just fine. If you want to be really clever, you can use [NServiceBus](http://www.nservicebus.com) and write (contribute?) ESENT-flavored subscription storage and transports. There are some forays into using ESENT on [Ayende's blog](http://www.ayende.com) as well (you'll have to poke around his SVN repository for the juicy bits).
C# Queue or ServiceBus with no dependencies?
[ "", "c#", ".net", "iis", "queue", "servicebus", "" ]
Does anyone know a good safe way to redirect the output of a printf-style function to a string? The obvious ways result in buffer overflows. Something like: ``` string s; output.beginRedirect( s ); // redirect output to s ... output.print( "%s%d", foo, bar ); output.endRedirect(); ``` I think the problem is the same as asking, "how many characters will print produce?" Ideas?
[This StackOverflow question](https://stackoverflow.com/questions/69738/c-how-to-get-fprintf-results-as-a-stdstring-w-o-sprintf#69911) has a similar discussion. Also in that question I present my favorite solution, a "format" function that takes identical arguments to printf and returns a std::string.
You can use: [`std::snprintf`](http://en.cppreference.com/w/cpp/io/c/fprintf) if you are working with a char\* [`std::stringstream`](http://en.cppreference.com/w/cpp/io/basic_stringstream) if you want to use strings (not same as printf but will allow you to easily manipulate the string using the normal stream functions). [`boost::format`](http://www.boost.org/doc/libs/1_37_0/libs/format/doc/format.html) if you want a function similar to printf that will work with streams. (as per jalf in comments) [`fmt::format`](https://github.com/fmtlib/fmt) which is has been standardized since c++20 [`std::format`](https://en.cppreference.com/w/cpp/utility/format/format)
Best way to safely printf to a string?
[ "", "c++", "stl", "" ]
I want to compile a project differently, according to a constant defined by #define, like this: ``` #define USE_COMPONENT_X #if USE_COMPONENT_X ... #endif ``` and I can do that in C#. But when I go to another file in the same project, this constant is not defined. Can I in some way define a constant to all the project, like DEBUG is defined so?
You can add the /define compiler switch. 1. Open the project's Property Pages dialog box. 2. Click the Configuration Properties folder. 3. Click the Build property page. 4. Modify the Conditional Compilation Constants property.
You may want to go a step further and create different project configurations as variants of the standard Debug and Release project configuration. The Configuration Manager under the build menu will let you accomplish this. Then while you are in the project properties' Build tab you can select the various configurations and set the conditional compilation constants that are appropriate for each configuration. This will save you lots of time when you want to swap back and forth between various permutations of your conditionally compiled code.
How to define a constant globally in C# (like DEBUG)
[ "", "c#", ".net", "" ]
I have a simplified ajay script, from which I have removed all nonrelevant code. The problem I am having is first with my columns array and the subsequent foreach loop. I want to go through each element and change the corresponding element to YES if true and NO if false, I don't see why it isn't working. If there are any problems such as syntax errors or braces or such, they are a problem from simplifying my code, and are not present in the version on my machine. ``` <?php $con = mysqli_connect("localhost", "", "", ""); if (!$con) { echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error(); exit; } $con->set_charset("utf8"); $query1 = 'SELECT EGGS, SALAD, TREES, REVISED FROM AUCTIONS WHERE ARTICLE_NO = ?'; if ($getRecords = $con->prepare($query1)) { $getRecords->bind_param("s", $pk); $getRecords->execute(); $getRecords->bind_result($EGGS, $SALAD, $TREES, $REVISED); while ($getRecords->fetch()) { $columns = array('EGGS', 'SALAD', 'TREES', 'REVISED'); foreach($columns as $column) { $$column = $columns[$column] ? 'YES' : 'NO'; } imageSize = imageResize($PIC_URL, 250, 300); echo "<h1>".$EGGS."</h1>"; } } function imageResize($imageURL, $maxWidth, $maxHeight) { $imageSize["width"] = 0; $imageSize["height"] = 0; $size = getimagesize($imageURL); if ($size) { $imageWidth = $size[0]; $imageHeight = $size[1]; $wRatio = $imageWidth / $maxWidth; $hRatio = $imageHeight / $maxHeight; $maxRatio = max($wRatio, $hRatio); if ($maxRatio > 1) { $imageSize["width"] = $imageWidth / $maxRatio; $imageSize["height"] = $imageHeight / $maxRatio; return $imageSize; } else { $imageSize["width"] = $imageWidth; $imageSize["height"] = $imageHeight; return $imageSize; } } else { die(print_r(error_get_last())); } } ```
Your loop is wrong - $columns['EGGS'] doesn't exist: ``` $columns = array('EGGS', 'SALAD', 'TREES', 'REVISED'); foreach($columns as $column) { $$column = $columns[$column] ? 'YES' : 'NO'; } ``` it should be: ``` $columns = array('EGGS', 'SALAD', 'TREES', 'REVISED'); foreach($columns as $column) { $$column = $$column ? 'YES' : 'NO'; } ``` or better still: ``` $tmp = array(); $columns = array('EGGS', 'SALAD', 'TREES', 'REVISED'); foreach($columns as $column) { $tmp[$column] = $$column ? 'YES' : 'NO'; } ``` so that you're not over-writing your bound variables. also note that you should move that constant array declaration outside of your `while()` loop for performance reasons.
But I just want to add that while using variables like $$COLUMN seems to be a nice feature, it later can get really messy and produces a lot of extra variables. Why don't you just create a temporary array, holding all YES/NO pairs? In addition, PHP does not allow variables to contain numbers. I don't know what will happen when you create a variable like this: ``` $name = "123variable"; $$name = "foo"; ``` I will have to check that out. Edit: I just saw that you bind the query results to some variables only. Still I think this is not a good coding style.
looping array problem
[ "", "php", "" ]
Does Java have buffer overflows? If yes can you give me scenarios?
Since Java Strings are based on char arrays and Java automatically checks array bounds, buffer overflows are only possible in unusual scenarios: 1. If you call native code via JNI 2. In the JVM itself (usually written in C++) 3. The interpreter or JIT compiler does not work correctly (Java bytecode mandated bounds checks)
Managed languages such as Java and C# do not have these problems, but the specific virtual machines (JVM/CLR/etc) which actually run the code may.
Does Java have buffer overflows?
[ "", "java", "buffer-overflow", "buffer-overrun", "" ]
I'm looking for a way to reinterpret an array of type byte[] as a different type, say short[]. In C++ this would be achieved by a simple cast but in C# I haven't found a way to achieve this without resorting to duplicating the entire buffer. Any ideas?
You can achieve this but this is a relatively bad idea. Raw memory access like this is not type-safe and can only be done under a full trust security environment. You should never do this in a properly designed managed application. If your data is masquerading under two different forms, perhaps you actually have two separate data sets? In any case, here is a quick and simple code snippet to accomplish what you asked: ``` byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int byteCount = bytes.Length; unsafe { // By using the fixed keyword, we fix the array in a static memory location. // Otherwise, the garbage collector might move it while we are still using it! fixed (byte* bytePointer = bytes) { short* shortPointer = (short*)bytePointer; for (int index = 0; index < byteCount / 2; index++) { Console.WriteLine("Short {0}: {1}", index, shortPointer[index]); } } } ```
There are four good answers to this question. Each has different downsides. Of course, beware of endianness and realize that all of these answers are holes in the type system, just not particularly treacherous holes. In short, don't do this a lot, and only when you really need to. 1. [Sander](https://stackoverflow.com/a/479767/4093018)'s answer. Use unsafe code to reinterpret pointers. This is the fastest solution, but it uses unsafe code. Not always an option. 2. [Leonidas](https://stackoverflow.com/a/480962/4093018)' answer. Use [`StructLayout`](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.aspx) and [`FieldOffset(0)`](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.fieldoffsetattribute.aspx) to turn a struct into a union. The downsides to this are that some (rare) environments don't support StructLayout (eg Flash builds in Unity3D) and that StructLayout cannot be used with generics. 3. [ljs](https://stackoverflow.com/a/479736/4093018)' answer. Use [`BitConverter`](http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx) methods. This has the disadvantage that most of the methods allocate memory, which isn't great in low-level code. Also, there isn't a full suite of these methods, so you can't really use it generically. 4. [`Buffer.BlockCopy`](http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx) two arrays of different types. The only downside is that you need two buffers, which is perfect when converting arrays, but a pain when casting a single value. Just beware that length is specified in bytes, not elements. [`Buffer.ByteLength`](http://msdn.microsoft.com/en-us/library/system.buffer.bytelength.aspx) helps. Also, it only works on primitives, like ints, floats and bools, not structs or enums. But you can do some neat stuff with it. ``` public static class Cast { private static class ThreadLocalType<T> { [ThreadStatic] private static T[] buffer; public static T[] Buffer { get { if (buffer == null) { buffer = new T[1]; } return buffer; } } } public static TTarget Reinterpret<TTarget, TSource>(TSource source) { TSource[] sourceBuffer = ThreadLocalType<TSource>.Buffer; TTarget[] targetBuffer = ThreadLocalType<TTarget>.Buffer; int sourceSize = Buffer.ByteLength(sourceBuffer); int destSize = Buffer.ByteLength(targetBuffer); if (sourceSize != destSize) { throw new ArgumentException("Cannot convert " + typeof(TSource).FullName + " to " + typeof(TTarget).FullName + ". Data types are of different sizes."); } sourceBuffer[0] = source; Buffer.BlockCopy(sourceBuffer, 0, targetBuffer, 0, sourceSize); return targetBuffer[0]; } } class Program { static void Main(string[] args) { Console.WriteLine("Float: " + Cast.Reinterpret<int, float>(100)); Console.ReadKey(); } } ```
reinterpret_cast in C#
[ "", "c#", "arrays", "casting", "" ]
What is the best way to return the whole number part of a decimal (in c#)? (This has to work for very large numbers that may not fit into an int). ``` GetIntPart(343564564.4342) >> 343564564 GetIntPart(-323489.32) >> -323489 GetIntPart(324) >> 324 ``` The purpose of this is: I am inserting into a decimal (30,4) field in the db, and want to ensure that I do not try to insert a number than is too long for the field. Determining the length of the whole number part of the decimal is part of this operation.
By the way guys, (int)Decimal.MaxValue will overflow. You can't get the "int" part of a decimal because the decimal is too friggen big to put in the int box. Just checked... its even too big for a long (Int64). If you want the bit of a Decimal value to the LEFT of the dot, you need to do this: ``` Math.Truncate(number) ``` and return the value as... A DECIMAL or a DOUBLE. *edit: Truncate is definitely the correct function!*
I think [System.Math.Truncate](http://msdn.microsoft.com/en-us/library/c2eabd70.aspx) is what you're looking for.
Best way to get whole number part of a Decimal number
[ "", "c#", ".net", "decimal", "int", "" ]
I'm a hobbyist (and fairly new) programmer who has written several useful (to me) scripts in python to handle various system automation tasks that involve copying, renaming, and downloading files amongst other sundry activities. I'd like to create a web page served from one of my systems that would merely present a few buttons which would allow me to initiate these scripts remotely. The problem is that I don't know where to start investigating how to do this. Let's say I have a script called: *file\_arranger.py* What do I need to do to have a webpage execute that script? This isn't meant for public consumption, so anything lightweight would be great. For bonus points, what do I need to look into to provide the web user with the output from such scripts? edit: The first answer made me realize I forgot to include that this is a Win2k3 system.
[This page](http://docs.python.org/library/cgi.html) on the python site has a good description and example of what you need to do to run a python CGI script. Start out with the simplest case first. Just make a short script that prints html. ``` #!/usr/bin/python #on windows change to your path to the python exe print "Content-Type: text/html" # HTML is following print # blank line, end of headers print "<TITLE>CGI script output</TITLE>" print "<H1>This is my first CGI script</H1>" print "Hello, world!" ``` When you try this the first time, the hardest part is usually figuring out where to put the script and how to make the web server recognize and run it. If you are using an apache web sever, take a look at [these configuration steps](http://httpd.apache.org/docs/2.2/howto/cgi.html). Once you have this simple script working, you will just need to add an html form and button tag and use the action property to point it to scripts you want to run.
This simple approach requires nothing except Python standard library. Create this directory structure: ``` . |-- cgi-bin | `-- script.py |-- index.html `-- server.py ``` You put your scripts in "cgi-bin" directory, "index.html" contains links to scripts in "cgi-bin" directory (so you don't have to type them manually, although you could), and "server.py" contains this: ``` import CGIHTTPServer CGIHTTPServer.test() ``` To run your server, just run "server.py". That's it, no Apache, no other dependencies. HTH...
How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage?
[ "", "python", "windows", "web-services", "cgi", "" ]
I have a few places where I use the line below to clear out a status, for example. I have a few of these that hang out for 10 seconds or more and if the user gets clicking around the action can occur at incorrect time intervals. ``` window.setTimeout(function() { removeStatusIndicator(); }, statusTimeout); ``` Is it possible to cancel or kill this with some jQuery or JavaScript code, so I don't have this process hanging around?
``` var timer1 = setTimeout(function() { removeStatusIndicator(); }, statusTimeout); clearTimeout(timer1); ```
## The Trick `setTimeout` returns a number: [![enter image description here](https://i.stack.imgur.com/CEooI.png)](https://i.stack.imgur.com/CEooI.png) ## Solution Take this number. Pass it to the function `clearTimeout` and you're safe: [![enter image description here](https://i.stack.imgur.com/m4xGX.png)](https://i.stack.imgur.com/m4xGX.png) # Code: Whenever you may need to stop a `setTimeout`, store its value in a variable: ``` const timeoutID = setTimeout(f, 1000); // Some code clearTimeout(timeoutID); ``` (Think of this number as the ID of a `setTimeout`. Even if you have called many `setTimeout`, you can still stop anyone of them by using the proper ID.)
Cancel/kill window.setTimeout() before it happens
[ "", "javascript", "jquery", "" ]
I am stuck! this seems really daft but I can not see where I am going wrong. I am creating a 2.0 C# ASP.NET website. I am trying to use a custom section in the web.config file with: ``` DatabaseFactorySectionHandler sectionHandler = ConfigurationManager.GetSection("DatabaseFactoryConfiguration") as DatabaseFactorySectionHandler; ``` I have a separate DLL for the Objects which are in Bailey.DataLayer namespace. But when I run the test.aspx page I get the following error: ``` System.Configuration.ConfigurationErrorsException was unhandled by user code Message="An error occurred creating the configuration section handler for DatabaseFactoryConfiguration: Could not load file or assembly 'Bailey.DataLayer' or one of its dependencies. The system cannot find the file specified. (C:\\Documents and Settings\\Administrator.PIP\\My Documents\\Visual Studio 2005\\WebSites\\bailey\\web.config line 13)" Source="System.Configuration" ``` The class that I am trying to get is as follows: ``` namespace Bailey.DataLayer { public sealed class DatabaseFactorySectionHandler : ConfigurationSection { [ConfigurationProperty("Name")] public string Name { get { return (string)base["Name"]; } } [ConfigurationProperty("ConnectionStringName")] public string ConnectionStringName { get { return (string)base["ConnectionStringName"]; } } public string ConnectionString { get { try { return ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString; } catch (Exception excep) { throw new Exception("Connection string " + ConnectionStringName + " was not found in web.config. " + excep.Message); } } } } } ``` The web config file has this section: ``` <configSections> <section name="DatabaseFactoryConfiguration" type="Bailey.DataLayer.DatabaseFactorySectionHandler, Bailey.DataLayer" /> </configSections> ``` I have done this in a console app without a problem but can not see any differences apart from it being in a web page. **EDIT** It all compiles and throws the error at runtime so I can only assume it find the assembly because it is referenced in the test.aspx.cs page. I have the following using statement at the top of the test.aspx.cs page: ``` using Bailey.DataLayer; ``` Here is the whole web.config file so there is no confusion: ``` <configuration> <configSections> <section name="DatabaseFactoryConfiguration" type="Bailey.DataLayer.DatabaseFactorySectionHandler, Bailey.DataLayer" /> </configSections> <appSettings/> <connectionStrings> <add name="BaileyMDFConString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\bailey.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" /> </connectionStrings> <DatabaseFactoryConfiguration Name="System.Data.SqlClient" ConnectionStringName="BaileyMDFConString" /> <system.web> <compilation debug="true"/> <authentication mode="Windows"/> </system.web> </configuration> ```
Either you're using the wrong name (i.e. it's not called Bailey.DataLayer.dll), or it's not being copied to the bin directory on build. This last one doesn't seem likely however. (See my comments on the question for clarification).
Ok ... I had the same issue. None of the above solutions helped. In my case my config file was in the same dll as that of web.config. I simply removed the namespace from the config section and that fixed my issue. **Not working** ``` <configSections> <section name="authorizedServerSection" type="ProjectName.ClientApi.Filters.AuthorizedServerSection, ProjectName.ClientApi.Filters" requirePermission="false"/> ``` **Working** ``` <configSections> <section name="authorizedServerSection" type="ProjectName.ClientApi.Filters.AuthorizedServerSection" requirePermission="false"/> ``` As soon as I removed the namespace `, ProjectName.ClientApi.Filters` it started working.
C# ConfigurationManager.GetSection could not load file or assembly
[ "", "c#", "configurationmanager", "configsection", "" ]
I am creating a MFC application for Windows Mobile and don't know how to enable multiple selection for List Control (CListCtrl). In properties panel Single Selection is set to False but still can't select multiple items. Any idea?
I have never targeted Windows Mobile but you might try the following: > list.ModifyStyle(LVS\_SINGLESEL, 0);
ModifyStyle method of CWnd base will work (see post from Diego) if you desire to do this programmatically OR you can define the attribute within the Resource Editor IF your placing the control on a dialog.
CListCtrl - how to enable multiple selection
[ "", "c++", "mfc", "windows-mobile", "clistctrl", "" ]
I've got a function inside of a class that returns a string. Inside this function, I can only get it to work when I add `cout<<endl` to the function before the return statement. Any idea why this is, or how I can fix it? I'm running this in Eclipse on a Mac In "main.cpp": ``` #include <iostream> #include <fstream> #include <string> #include <vector> #include <cstdlib> #include "Braid.h" using namespace std; static int size=3; int main(){ Braid * b1 = new Braid(size); b1->setCanon();//creates canonical braid. cout<<"a "; cout<<b1->getName()<<endl; cout<<" b "; } ``` In "Braid.h" : ``` public: Braid(int); void setCanon(); string getName(); }; ``` And in "Braid.cpp": ``` string Braid::getName(){ string sName=""; /* body commented out for(int i=0; i<height; i++) { for(int j=2; j<(width-2); j++) { sName += boxes[i][j]; sName += "|"; } } */ //cout<<endl; return sName; } ``` When I run my main code, without the body of that function commented, the output I get is **"a 0|0|12|12|0|0|2|1|1|1|1|2|"** The "name" it returns is correct, but it's not making it past the function call. If I uncomment the `//cout<<endl` line, the function works and my output is **"a 0|0|12|12|0|0|2|1|1|1|1|2| b "** After commenting out the body of the function, so that it only creates an empty string, and returns it, my output is only "a" then if I add the endl back, I get the "a b" that is expected. What am I doing wrong? Is there something that comes with endl that I'm missing?
actually *getName()* function is probably working correctly. However, the cout 'caches' the output (i.e. it prints the output on screen when it's internal text buffer is full). 'endl' flushes the buffer and forces cout to dump the text (in cache) to screen. Try cout.flush() in main.cpp
Maybe your terminal is lazy. Try omitting the `endl` and insert `cout.flush(`) as the next line.
C++ function that returns string doesn't work unless there's an endl involved...?
[ "", "c++", "string", "stl", "" ]
I am making use of AJAX on my site and I would like to show users progress of a file that is being downloaded by my server. The download is done by script that **outputs a percentage to the shell**. I would like to pass this info back to the user using AJAX. How can I do this? Thank you for any help and direction. I hope your solutions do not involve writing to a text file and retrieving that percentage from the text file!! Too much over head I think. ## EDIT - More Info It is a Linux Shell command - Fedora Core 10. Currently this is how the shell output looks like: ``` [download] 9.9% of 10.09M at 10.62M/s ETA 00:00 ``` The percentage changes and I wish to capture that and send it back to the user as it changes. To execute this, I make use of PHPs exec() function.
Instead of exec, you could use [popen](https://www.php.net/popen). This will give you a handle you use with fread to grab the output your command generates as it happens. You'll need to parse out the updates it makes to the percentage indicator. Once you have that data, there are a few ways you could get it to a client, e.g. with a "[comet](http://en.wikipedia.org/wiki/Comet_(programming))" style push, or have an Ajax request poll for updates.
I haven't tried this, but I think this approach would work. You need three pieces: 1. Have shell script output its stream to netcat connected to a port 2. Have a php script listening to stream coming from said port for incoming data, updating a record in memcache or some database w/ the percentage finished. 3. Have your web script periodically make ajax calls, to the server which checks this value in your backend store.
AJAX - Progress bar for a shell command that is executed
[ "", "php", "ajax", "linux", "shell", "progress-bar", "" ]
Basically, I want to do "zipzam&&&?&&&?&&&" -> "zipzam%26%26%26?&&&?&&&". I can do that without regex many different ways, but it'd cleanup things a tad bit if I could do it with regex. Thanks Edit: "zip=zam&&&=?&&&?&&&" -> "zip=zam%26%26%26=?&&&?&&&" should make things a little clearer. Edit: "zip=zam=&=&=&=?&&&?&&&" -> "zip=zam=%26=%26=%26=?&&&?&&&" should make things clearer. However, theses are just examples. I still want to replace *all* '&' before the first '?' no matter where the '&' are before the first '?' and no matter if the '&' are consecutive or not.
This should do it: ``` "zip=zam=&=&=&=?&&&?&&&".replace(/^[^?]+/, function(match) { return match.replace(/&/g, "%26"); }); ```
you need negative lookbehinds which are tricky to replicate in JS, but fortunately there are ways and means: ``` var x = "zipzam&&&?&&&?&&&"; x.replace(/(&+)(?=.*?\?)/,function ($1) {for(var i=$1.length, s='';i;i--){s+='%26';} return s;}) ``` commentary: this works because it's *not* global. The first match is therefore a given, and the trick of replacing all of the matching "&" chars 1:1 with "%26" is achieved with the function loop --- edit: a solution for unknown groupings of "&" can be achieved simply (if perhaps a little clunkily) with a little modification. The basic pattern for replacer methods is infinitely flexible. ``` var x = "zipzam&foo&bar&baz?&&&?&&&"; var f = function ($1,$2) { return $2 + ($2=='' || $2.indexOf('?')>-1 ? '&' : '%26') } x.replace(/(.*?)&(?=.*?\?)/g,f) ```
Regex to match all '&' before first '?'
[ "", "javascript", "regex", "" ]
is it possible, in C++, to get the current RAM and CPU usage? Is there a platform-indepentent function call?
There is an open source library that gives these (and more system info stuff) across many platforms: [SIGAR API](https://github.com/hyperic/sigar) I've used it in fairly large projects and it works fine (except for certain corner cases on OS X etc.)
Sadly these things rely heavily on the underlying OS, so there are no platform-independent calls. (Maybe there are some wrapper frameworks, but I don't know of any.) On Linux you could have a look at the [getrusage()](http://linux.die.net/man/2/getrusage) function call, on Windows you can use [GetProcessMemoryInfo()](http://msdn.microsoft.com/en-us/library/ms683219.aspx) for RAM Usage. Have also a look at the other functions in the [Process Status API](http://msdn.microsoft.com/en-us/library/ms684884(VS.85).aspx) of Windows.
How to get current CPU and RAM usage in C++?
[ "", "c++", "cpu-usage", "ram", "" ]
How do I print the indicated div (without manually disabling all other content on the page)? I want to avoid a new preview dialog, so creating a new window with this content is not useful. The page contains a couple of tables, one of them contains the div I want to print - the table is styled with visual styles for the web, that should not show in print.
Here is a general solution, using **CSS only**, which I have verified to work. ``` @media print { body { visibility: hidden; } #section-to-print { visibility: visible; position: absolute; left: 0; top: 0; } } ``` *There's a [Code Sandbox](https://codesandbox.io/s/print-area-vo35v5) if you want to see this in action. Click the Open In New Window button above the preview; then you can use the browser's Print command to see a preview of the printout.* Alternative approaches aren't so good. Using `display` is tricky because if any element has `display:none` then none of its descendants will display either. To use it, you have to change the structure of your page. Using `visibility` works better since you can turn on visibility for descendants. The invisible elements still affect the layout though, so I move `section-to-print` to the top left so it prints properly.
I have a better solution with minimal code. Place your printable part inside a div with an id like this: ``` <div id="printableArea"> <h1>Print me</h1> </div> <input type="button" onclick="printDiv('printableArea')" value="print a div!" /> ``` Then add an event like an onclick (as shown above), and pass the id of the div like I did above. Now let's create a really simple javascript: ``` function printDiv(divId) { var printContents = document.getElementById(divId).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; } ``` Notice how simple this is? No popups, no new windows, no crazy styling, no JS libraries like jquery. The problem with really complicated solutions (the answer isn't complicated and not what I'm referring to) is the fact that it will NEVER translate across all browsers, ever! If you want to make the styles different, do as shown in the checked answer by adding the media attribute to a stylesheet link (media="print"). No fluff, lightweight, it just works.
Print <div id="printarea"></div> only?
[ "", "javascript", "css", "printing", "dhtml", "" ]
Is there a way to include a javascript-loaded advertisement last on the page, but have it positioned in the content? The primary purpose is to keep the javascript ad from slowing down the page load, so if there are other methods to achieve this please do share.
There is the **[`defer` attribute](http://www.websiteoptimization.com/speed/tweak/defer/)** you could put on script blocks to defer its execution until the page completes loading. ``` <script src="myscript.js" type="text/javascript" defer> // blah blah </script> ``` I am not sure about the general recommendation about using this attribute though. **EDIT:** As @David pointed out, use `defer="defer"` for XHTML And you can always put the code inside the **`window.onload`** event so that it executes *after* the pages load: ``` window.onload = function () { // ad codes here }; ``` But the later approach may pose some problems, you might want to test it out first. More information on [this blog post](http://dean.edwards.name/weblog/2005/09/busted/) by Dean Edwards, the guy who wrote the famous [javascript packer](http://dean.edwards.name/packer/). --- **EDIT:** If the size of ad code itself is the problem, you can always defer the loading by combining the above methods with script injection via `document.write`: ``` function loadScript(src) { document.write('<script src="' + src + '" type="text/javascript"></script>'); } ``` So the resulting code might look something like this: ``` <script type="text/javascript" defer> function loadScript(src) { document.write('<script src="' + src + '" type="text/javascript"></script>'); } loadScript('http://ads.example.com/advertisements.js'); </script> ``` But as I've said, it depends on the specific ad code you get too. Because of the position `document.write` will write stuffs to might not be the location you want. Some modifications might be neccessary.
``` function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); func(); } } } ``` The above code is a nice way to add a new onload event that doesn't interfere with your existing javascript. Then you can add a new load event to load the advertisements using the code below. ``` addLoadEvent(function() { // call to loadScript() here }); ```
Is it possible to load a javascript ad last on the page to prevent slow load times?
[ "", "javascript", "" ]
I cannot figure out how to make a C# Windows Form application write to a textbox from a thread. For example in the Program.cs we have the standard main() that draws the form: ``` static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } ``` Then we have in the Form1.cs: ``` public Form1() { InitializeComponent(); new Thread(SampleFunction).Start(); } public static void SampleFunction() { while(true) WindowsFormsApplication1.Form1.ActiveForm.Text += "hi. "; } ``` Am I going about this completely wrong? **UPDATE** Here is the working code sample provided from bendewey: ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); new Thread(SampleFunction).Start(); } public void AppendTextBox(string value) { if (InvokeRequired) { this.Invoke(new Action<string>(AppendTextBox), new object[] {value}); return; } textBox1.Text += value; } void SampleFunction() { // Gets executed on a seperate thread and // doesn't block the UI while sleeping for(int i = 0; i<5; i++) { AppendTextBox("hi. "); Thread.Sleep(1000); } } } ```
On your MainForm make a function to set the textbox the checks the InvokeRequired ``` public void AppendTextBox(string value) { if (InvokeRequired) { this.Invoke(new Action<string>(AppendTextBox), new object[] {value}); return; } ActiveForm.Text += value; } ``` although in your static method you can't just call. ``` WindowsFormsApplication1.Form1.AppendTextBox("hi. "); ``` you have to have a static reference to the Form1 somewhere, but this isn't really recommended or necessary, can you just make your SampleFunction not static if so then you can just call ``` AppendTextBox("hi. "); ``` It will append on a differnt thread and get marshalled to the UI using the Invoke call if required. ***Full Sample*** ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); new Thread(SampleFunction).Start(); } public void AppendTextBox(string value) { if (InvokeRequired) { this.Invoke(new Action<string>(AppendTextBox), new object[] {value}); return; } textBox1.Text += value; } void SampleFunction() { // Gets executed on a seperate thread and // doesn't block the UI while sleeping for(int i = 0; i<5; i++) { AppendTextBox("hi. "); Thread.Sleep(1000); } } } ```
I would use `BeginInvoke` instead of `Invoke` as often as possible, unless you are really required to wait until your control has been updated (which in your example is not the case). `BeginInvoke` posts the delegate on the WinForms message queue and lets the calling code proceed immediately (in your case the for-loop in the `SampleFunction`). `Invoke` not only posts the delegate, but also waits until it has been completed. So in the method `AppendTextBox` from your example you would replace `Invoke` with `BeginInvoke` like that: ``` public void AppendTextBox(string value) { if (InvokeRequired) { this.BeginInvoke(new Action<string>(AppendTextBox), new object[] {value}); return; } textBox1.Text += value; } ``` Well and if you want to get even more fancy, there is also the `SynchronizationContext` class, which lets you basically do the same as `Control.Invoke/Control.BeginInvoke`, but with the advantage of not needing a WinForms control reference to be known. [Here](http://www.codeproject.com/KB/cpp/SyncContextTutorial.aspx) is a small tutorial on `SynchronizationContext`.
Writing to a TextBox from another thread?
[ "", "c#", "winforms", "multithreading", "" ]
When accessing values from an **SqlDataReader** is there a performance difference between these two: ``` string key = reader.GetString("Key"); ``` or ``` string key = reader["Key"].ToString(); ``` In this code sample: ``` string key; using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { key = reader.GetString("Key"); // or key = reader["Key"].ToString(); } } ```
I’ve just peeked into the .NET source code, and the two access methods are essentially the same. The only difference is that the second does an additional boxing. So the first one corresponds to something like (in case of elementary types): ``` int key = GetInternalSQLDataAsInt32("Key"); ``` while the second one would be: ``` int key = (int)(object)GetInternalSQLDataAsInt32("Key"); ``` The GetInternalSQLDataAsInt32(...) function represents the SQL data library machinery of marshalling data from SQL to .NET. But as pointed above, a more significant difference can be expected between string-based keys and ordinal-based keys.
A Microsoft MVP wrote a blog entry about this: <http://jeffbarnes.net/portal/blogs/jeff_barnes/archive/2006/08/09/Maximize-Performance-with-SqlDataReader.aspx> Here are his conclusions: ``` .NET 1.1 .NET 2.0 Ordinal Position: 8.47 9.33 Get Methods: 11.36 8.07 Case Sensitive: 14.51 12.53 Case Insensitive (All Upper): 13.93 12.23 Case Insensitive (All Lower): 14.47 12.48 Case Insensitive (Mixed): 14.48 12.57 ``` But really, unless you are dealing with a significant number of rows, it isn't worth worrying about.
SqlDataReader performance differences in accessing values?
[ "", "c#", "asp.net", "sqldatareader", "" ]
**EDIT:** I suppose I should clarify, in case it matters. I am on a AIX Unix box, so I am using VAC compilers - no gnu compilers. **End edit** --- I am pretty rusty in C/C++, so forgive me if this is a simple question. I would like to take common functions out of a few of my C programs and put them in shared libraries or shared objects. If I was doing this in perl I would put my subs in a perl module and use that module when needed. For the sake of an example, let's say I have this function: ``` int giveInteger() { return 1034; } ``` Obviously this is not a real world example, but if I wanted to share that function, how would I proceed? I'm pretty sure I have 2 options: 1. Put my shared function in a file, and have it compile with my main program at compile time. If I ever make changes to my shared function, I would have to recompile my main program. 2. Put my shared function in a file, and compile it as a shared library (if I have my terms correct), and have my main program link to that shared library. Any changes I make to my shared library (after compiling it) would be integrated into my main program at runtime without re-compiling my main program. Am I correct on that thinking? If so, how can I complish either/both of those methods? I've searched a lot and I seem to find information how how I could have my own program link to someone else's shared library, but not how to create my own shared functions and compile them in a way I can use them in my own program. Thanks so much! Brian --- **EDIT:** ## Conclusion Thanks everyone for your help! I thought I would add to this post what is working for me (for dynamic shared libraries on AIX) so that others can benefit: I compile my shared functions: ``` xlc -c sharedFunctions.c -o sharedFunctions.o ``` Then make it a shared object: ``` xlc -qmkshrobj -qexpfile=exportlist sharedFunctions.o xlc -G -o libsharedFunctions.so sharedFunctions.o -bE:exportlist ``` Then link it another program: ``` xlc -brtl -o mainProgram mainProgram.c -L. -lsharedFunctions ``` And another comment helped me find this link, which also helped: <http://publib.boulder.ibm.com/infocenter/comphelp/v7v91/topic/com.ibm.vacpp7a.doc/proguide/ref/compile_library.htm> Thanks again to all who helped me out!
Yeah you are correct. The first is called a *static library*, while the second is called a *shared library*, because the code is not bound to the executable at compile time, but everytime again when your program is loaded. ## Static library Compile your library's code as follows: ``` gcc -c *.c ``` The `-c` tells the program not to link the object file, but just leaves you with object files for each `.c` file that was compiled. Now, archive them into one static library: ``` ar rcs libmystuff.a *.o ``` `man ar` will tell you what the rcs options mean. Now, libmystuff.a is a **a**rchive file (you can open it with some zip-file viewers) which contain those object files, together with an index of symbols for each object file. You can link it to your program: ``` gcc *.c libmystuff.a -o myprogram ``` Now, your program is ready. Note that the order of where the static libraries appear in the command matter. See my [Link order](https://stackoverflow.com/questions/45135/linker-order-gcc#409470) answer. ## Shared library For a shared library, you will create your library with ``` gcc -shared -o libmystuff.so *.c ``` That's all it takes, libmystuff.so is now a **s**hared **o**bject file. If you want to link a program to it, you have to put it into a directory that is listed in the `/etc/ld.so.conf` file, or that is given by the `-L` switch to GCC, or listed in the LD\_LIBRARY\_PATH variable. When linking, you cut the `lib` prefix and `.so` suffix from the library name you tell gcc. ``` gcc -L. -lmystuff *.c -o myprogram ``` Internally, gcc will just pass your arguments to the GNU linker. You can see what arguments it pass using the `-###` option: Gcc will print the exact arguments given to each sub process. For details about the linking process (how some stuff is done internally), view my [Linux GCC linker](https://stackoverflow.com/questions/332554/linux-gcc-linker#332572) answer.
You've got a third option. In general, your C++ compiler should be able to link C routines. The necessary options may vary from compiler to compiler, so R your fine M, but basically, you should be able to compile with g++ as here: ``` $ g++ -o myapp myapp.cpp myfunc.c giveint.c ``` ... or compile separately ``` $ gcc -c myfunc.c $ gcc -c giveint.c $ g++ -c myapp.cpp $ g++ -o myapp myapp.o myfunc.o ``` You also need to include your declaration of the functions; you do that in C++ as ``` extern "C" { int myfunc(int,int); int giveInterger(void); } ```
How do I source/link external functions in C or C++?
[ "", "c++", "c", "shared-libraries", "" ]
I know that accessing and manipulating the DOM can be very costly, so I want to do this as efficiently as possible. My situation is that a certain div will always contain a list of items, however sometimes I want to refresh that list with a completely different set of items. In this case, I can build the new list and append it to that div, but I also need to clear out the out list. What's the best way? Set the innerHTML to the empty string? Iterate over the child nodes and call "removeChild"? Something else?
Have a look on [QuirksMode](http://quirksmode.org/). It may take some digging, but there are times for just this operation in various browsers. Although the tests were done more than a year ago, setting `innerHTML` to `""` was the fastest in most browsers. P.S. [here](http://quirksmode.org/dom/innerhtml.html) is the page.
set innerHTML to an empty string.
What is the more efficient way to delete all of the children of an HTML element?
[ "", "javascript", "html", "" ]
First of all, am I the only person using JSONML? And second of all, would you recommend using JSONML for inserting dynamic HTML or is InnerHTML more efficient?
Bare in mind that (in IE) not every innerHTML is writable (innerHTML isn't standar compilant anyway). So closer you come to appending nodes rather then inserting html, better you are. As far as I can see, jsonml thingie creates DOM elements whch is nice. I can only sugest you to make some huge dataset, insert it in two different ways and mesure performance yourself.
While superficially used to perform similar tasks, JsonML and innerHTML are quite different beasts. innerHTML requires you to have all the markup exactly as you want it ready to go, meaning that either the server is rendering the markup, or you are performing expensive string concatenations in JavaScript. JsonML opens the door to client-side templating through JBST which means that your template is converted from HTML markup into a JavaScript template at build time. At runtime, you simply supply the data and you end up with DOM elements to be inserted or to replace an existing element (something innerHTML cannot easily do without extra DOM creation). Rebinding only requires requesting additional data, not the entire re-rendered markup. This is where large performance gains can be made as the markup can be requested/cached separately from the data. For simplicity, innerHTML has been the preferred method for the HTML-Message pattern style of Ajax. But tool-sets like JsonFx can make using JsonML and JBST just as easy while delivering a full browser-side templating Ajax pattern.
JSONML vs. InnerHTML vs.?
[ "", "javascript", "dom", "" ]
Hi have some forms that I want to use some basic php validation (regular expressions) on, how do you go about doing it? I have just general text input, usernames, passwords and date to validate. I would also like to know how to check for empty input boxes. I have looked on the interenet for this stuff but I haven't found any good tutorials. Thanks
1. Read in the PHP.net documentation on Text processing. 2. Use the string methods and regular expressions to make a function for email type, date type etc., returning true if valid, false otherwise. 3. Test with the functions when submitting the form, and display the appropriate error messages to the user.
Another function you should use is trim() to clean the input from all whitespaces for validation - some users might just enter a single whitespace as data.
Simple PHP form Validation and the validation symbols
[ "", "php", "regex", "validation", "" ]
I need an example algorithm that will draw pixels one at a time on a grid based (x,y) system, and also color them based on an rbg value based on binary data that is provided in some form. I am looking for anything written in php or a php like language such as C, but that does not use any sort of library or graphics card api, as i am coding in php. Here is something that i wrote in php, that uses random color values but it takes 15 seconds to render in an html canvas: ``` <?php $r_max = 240; $c_max = 320; $row = -1;//-1 to offset while while ($row<$r_max){ ++$row; for($column=0; $column<=$c_max; ++$column) { echo 'ctx.fillStyle = "rgb(', rand()%255, ',', rand()%255, ',', rand()%255, ')";'; echo 'ctx.fillRect(', $column, ',', $row, ',1,1);'; } } ?> ```
It seem you are trying to output JavaScript commands for drawing on a `<canvas>` tag. A faster way to draw the pixels might be to use `moveTo` and `lineTo`. Btw, why isn't you outer loop a for loop as well? Doesn't ``` for($row=0; $row<=$r_max; ++$row) { for($column=0; $column<=$c_max; ++$column) { # draw pixel } } ``` seem more natural?
Not really sure i quite understand your question but .. PHP has GD functions that include image allocate and setpixel calls, line drawing etc .. check [here](https://www.php.net/gd) oh and yes [imagemagick](https://www.php.net/manual/en/book.imagick.php) also for more exotic uses
Pixel Drawing Algorithm
[ "", "php", "algorithm", "render", "pixel", "" ]
I have a year 2009, a month 11 and a day 12. All of these are being passed to me as integers. What I want to do is create a date from these. I want to use these as part of my where statement. What is the best way to do it from either a clean code and most importantly a speed point of view? I personally am using MS SQL, which I'm sure will make a difference. Thanks in advance, Alex.
Assuming that your `INT`s are called `@d`, `@m` and `@y`: ``` DATEADD(month, ((@y - 1900) * 12) + @m - 1, @d - 1) ``` **EDIT** Please note that this technique isn't "canonical" in any way, it relies on manipulating SQL Server's implementation of `DATETIME`. If you pass invalid values for `@d`, `@m` or `@y` then you'll get an invalid `DATETIME` in return: * { @y=2009, @m=11, @d=12 } returns 2009-11-12 (correct) * { @y=2009, @m=11, @d=50 } returns 2009-12-19 (wrong) * { @y=2009, @m=13, @d=12 } returns 2010-01-12 (wrong)
The most unambiguous formats, using only integers, are `YYYYMMDD`, `YYYY-MM-DD`, and `YYYY/MM/DD`. I can't speak to MSSQL specifically, but in my experience, `YYYY-MM-DD` is the most universally supported (due in no small part to it being part of the [ISO 8601 standard](http://en.wikipedia.org/wiki/ISO_8601)).
What's the canonical way to create a date from three numbers representing days, months and years?
[ "", "sql", "sql-server", "date", "" ]
So I have [taken over a Java Web project](https://stackoverflow.com/questions/436212/taking-over-a-project-what-should-i-ask-the-previous-programmer). The application was written by another developer who now works for another company. Generally speaking, the application is straightforward, well designed and the code is documented enough. The only issue is that the previous developer decided to built his own database access library instead of using a popular framework. Over the years of his programming career he has build an impressive framework to access any database (something similar to a lightweight Hiberbate). Now, I have no reason to throw away his code and replace the data layer with a more conventional JPA layer since the current code work just fine (although it is tempting!). But I was wondering if I should use a more conventional framework with new features. The application stack is straightforward and I could easily plug Hibernate or JPA. So old pages (with new bugfixes) would use the old framework, and the new page would use the new framework. One of the drawback of this approach however is that it can get confusing to new developer. However, I can also continue to use the old framework, expanding/fixing it as necessary. Like I said, it works!
Eldimo, You should balance the decision to incorporate a new framework based on the return of investment of such change. The longevity of the current project is one way to look at it. If the project is stable and on maintenance phase then you shouldn't make drastic changes. But if the project will continue to incorporate new features and continue to grow, then you should consider adopting a supported framework if it increases the return of investment.If you foresee changes in the current home grow framework in order to support new requirements and if those requirements are supported by other existing frameworks, then you have a strong reason to adopt them. However, the adoption of a new persistence framework will destabilize the current project for a short period of time, increasing the volume of bugs due to the lack of team experience with the framework and can also affect the velocity of the development team.
You certainly don't want to add frameworks at a whim, but the opposite is also bad, writing your own psuedo-framework when an acceptable alternative exists. In my job, we had to a do a conversion from JPA to a more JDBC style using Spring. During the conversion, I didn't delete or modify any of the JPA code, I simply re-wrote it in JDBC. Once I was comfortable that particular method worked, I would swap out the implementation. This allowed me to piece-meal the conversion over, without pulling the rug out from under the service layer, so to speak. So to fully answer your question, it is okay to have 2 frameworks as long as the plan is to migrate to one or the other.
Is it OK to have two frameworks in the same project?
[ "", "java", "jsp", "frameworks", "" ]
I am getting the error OperationalError: FATAL: sorry, too many clients already when using psycopg2. I am calling the close method on my connection instance after I am done with it. I am not sure what could be causing this, it is my first experience with python and postgresql, but I have a few years experience with php, asp.net, mysql, and sql server. EDIT: I am running this locally, if the connections are closing like they should be then I only have 1 connection open at a time. I did have a GUI open to the database but even closed I am getting this error. It is happening very shortly after I run my program. I have a function I call that returns a connection that is opened like: psycopg2.connect(connectionString) Thanks Final Edit: It was my mistake, I was recursively calling the same method on mistake that was opening the same method over and over. It has been a long day..
This error means what it says, there are too many clients connected to postgreSQL. Questions you should ask yourself: * Are you the only one connected to this database? * Are you running a graphical IDE? * What method are you using to connect? * Are you testing queries at the same time that you running the code? Any of these things could be the problem. If you are the admin, you can up the number of clients, but if a program is hanging it open, then that won't help for long. There are many reasons why you could be having too many clients running at the same time.
Make sure your db connection command isn't in any kind of loop. I was getting the same error from my script until I moved my db.database() out of my programs repeating execution loop.
Getting OperationalError: FATAL: sorry, too many clients already using psycopg2
[ "", "python", "postgresql", "psycopg2", "" ]
I have a map defined like this ``` std::map<some_key_type, std::string::iterator> mIteratorMap; ``` And a huge string named "mHugeString". Then I walk trough the string collecting iterators like this: ``` std::string::iterator It=mHugeString.begin(); std::string::iterator EndIt=mHugeString.end(); for(;It!=EndIt;++It){ ...defining a key element... if(need_to_store_an_iterator)mIteratorMap[key_of_a_right_type]=It; } ``` In the end I should recieve a map, where an iterator is associated with a some sort of key. But the iterator somehow looses itself when being paired with a key by "make\_pair", unless it points to a place somewhere in the end of a string. It's hard to tell, but maybe last 256 bytes are fine. So the question is not how to avoid loosing iterators, it was a stupid idea to store them anyways, but why trying to store an iterator in the begining of the string fails, and why the same with the iterators on the end works fine? What is the difference between them?
I haven't tried it but I would have expected that, of course you **can** store iterator values as values in a map. Do you know that if you change the contents of `mHugeString` then any iterators into it which you have previously stored are now invalid? You might choose to store the index into the string, instead of the iterator.
It's fine, you *can* store iterators in the map. If you get some error, that is caused by something else. Note that if you modify your string, iterators pointing into your string will become invalid. Please show us a complete, compilable code snippet that is rendered unusable, so we can analyze it.
Why can't I put an iterator in map?
[ "", "c++", "string", "stl", "dictionary", "iterator", "" ]
What am I missing here? I want to do a simple call to Select() like this: ``` List<int> list = new List<int>(); //fill the list List<int> selections = (List<int>)list.Select(i => i*i); //for example ``` And I keep having trouble casting it. What am I missing?
Select() will return you an IEnumerable<int> type, you have to use the [ToList() operator](http://www.hookedonlinq.com/ToListOperator.ashx): ``` List<int> selections = list.Select(i => i*i).ToList(); ```
Select() doesn't return a List so of course you can't cast it to a list. You can use the ToList method instead: ``` list.Select(i => i*i).ToList(); ```
Trouble casting results of Select() to a List<T>
[ "", "c#", ".net", "linq", "" ]
A friend of mine is talking about these design techniques regarding state transitions of an object (he's a Java guru, btw), performed without having a `boolean myState` member, but rather declaring the `myState` member as an object that implements the same interface of the "owner" one. Ok, I've been too much cryptic, so you can find the discussion [here](http://andreagazzarini.blogspot.com/), with code samples. Personally, I'm excited with the approach, as my friend explained me the philosophy behind it; I also think it is pretty coherent, from a design perspective. My concerns, by the way, are mainly about performance and memory usage, as maybe compile-time and run-time optimizations enter the game. Since I don't know JIT compiler and JVM internals, I'm curious to have a wider opinion. What do you think about?
It sounds like you're asking whether there's a "concretely useful" benefit to using the state design pattern, to which I'd say definitely yes, particularly if your app actually relies heavily on the "state" of its objects. A popular canonical example is that of the video player, which is always in one state, and can only transition into different states depending on the state it's currently in (e.g., it can't stop if it's already stopped, but it can play, and it can rewind, and so on). While that particular example can be managed relatively easily with a handful of if/else/switch-type conditions (if (isStopped()), play(), etc.) because there aren't that many states to deal with, when states or their transition rules start to become more numerous or complicated, the state pattern absolutely becomes quite valuable, as without it, your code tends to accumulate elseifs like crazy, and things become less and less readable and manageable over time. So yes, in general, if you find your objects' behaviors varying according to their states (if isStopped() play() / elseif isPlaying() stop() / elseif (isBroken() fix()), etc.), then yes, do consider using the State pattern. It's a bit more work up front, but generally well worth the effort, and done right I doubt you'd notice any significant overhead simply for the using of it. [Head First Design Patterns](https://rads.stackoverflow.com/amzn/click/com/0596007124) offers a great description of its hows and whys, too -- I highly recommend picking up that book to pretty much anyone writing object-oriented code.
I have to disagree - useful design patterns aside, *this particular example* is ridiculous overkill: * a 15-line class with an easily-understandable process * became a 50-line class with an obfuscated purpose I fail to see how this is an improvement - it violates YAGNI1 and ASAP2, bloats the code, and reduces efficiency (multiple objects instantiated to do the job when not required). As an intellectual exercise, mildly interesting. As a programming habit, *terrifying*! ;-) --- 1 YANGI = You Ain't Gonna Need It 2 ASAP = As Simple As Possible
If-less code: is it just an intellectual challenge or is it concretely useful?
[ "", "java", "design-patterns", "oop", "" ]
I would like to call a windows program within my code with parameters determined within the code itself. I'm not looking to call an outside function or method, but an actual .exe or batch/script file within the WinXP environment. C or C++ would be the preferred language but if this is more easily done in any other language let me know (ASM, C#, Python, etc).
When you call CreateProcess(), System(), etc., make sure you double quote your file name strings (including the command program filename) in case your file name(s) and/or the fully qualified path have spaces otherwise the parts of the file name path will be parsed by the command interpreter as separate arguments. ``` system("\"d:some path\\program.exe\" \"d:\\other path\\file name.ext\""); ``` For Windows it is recommended to use CreateProcess(). It has messier setup but you have more control on how the processes is launched (as described by Greg Hewgill). For quick and dirty you can also use WinExec(). (system() is portable to UNIX). When launching batch files you may need to launch with cmd.exe (or command.com). ``` WinExec("cmd \"d:some path\\program.bat\" \"d:\\other path\\file name.ext\"",SW_SHOW_MINIMIZED); ``` (or `SW_SHOW_NORMAL` if you want the command window displayed ). Windows should find command.com or cmd.exe in the system PATH so in shouldn't need to be fully qualified, but if you want to be certain you can compose the fully qualified filename using [`CSIDL_SYSTEM`](http://msdn.microsoft.com/en-us/library/bb762494.aspx) (don't simply use C:\Windows\system32\cmd.exe).
C++ example: ``` char temp[512]; sprintf(temp, "command -%s -%s", parameter1, parameter2); system((char *)temp); ``` C# example: ``` private static void RunCommandExample() { // Don't forget using System.Diagnostics Process myProcess = new Process(); try { myProcess.StartInfo.FileName = "executabletorun.exe"; //Do not receive an event when the process exits. myProcess.EnableRaisingEvents = false; // Parameters myProcess.StartInfo.Arguments = "/user testuser /otherparam ok"; // Modify the following to hide / show the window myProcess.StartInfo.CreateNoWindow = false; myProcess.StartInfo.UseShellExecute = true; myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized; myProcess.Start(); } catch (Exception e) { // Handle error here } } ```
How to call an external program with parameters?
[ "", "c++", "c", "winapi", "external-application", "" ]
I am interested in creating a couple of add-ins for Office 2003 & 2007 for work and home. I see the project templates in VS2008 for creating the addins but I am un-clear as to what to do next. I also have had great difficulty finding direction online so far. I am not looking for cut and paste code but rather a finger pointing in the direction of a *Hello World*, of sorts, for creating addins using VS8's templates. Thank you in advance!
Thanks for the time and replies! Between *gkrodgers* and *Perpetualcoder's* responses I was lead to my ultimate destination --> [Walkthrough: Creating Your First Application-Level Add-in for Excel](http://msdn.microsoft.com/en-us/library/cc668205.aspx) Why I had such a time finding this in the first place is beyond me. Thanks you two for giving me the finger! ;)
This is the article that got me started when I needed to write a Word add-in: <http://support.microsoft.com/kb/302896> and this is my *actual* "Hello World" code! :-) ``` public void OnStartupComplete(ref System.Array custom) { System.Windows.Forms.MessageBox.Show("Hello World!"); } ```
.Net Excel Add In Help
[ "", "c#", ".net", "excel", "add-in", "" ]
I am looking for a Java Rules / Workflow engine. Something similar to Microsoft Workflow Engine. Can someone recommend a product?
[Here](http://java-source.net/open-source/rule-engines) is a rundown of many open-source Java rules engines including the usual suspects like [Drools](http://drools.org/), etc.
* [jBPM](http://www.jboss.com/products/jbpm): aimed at business processes mostly; * [OSWorkflow](http://www.opensymphony.com/osworkflow/documentation.action): pretty low-level; and * [Spring Webflow](http://www.springsource.org/webflow): not a generic workflow engine but a notworthy product if you ever need to implemented a flow-based Web application. Nothing quite up there with WWF.
Free / OpenSource Java Rules / Workflow engine
[ "", "java", "workflow", "rules", "" ]
I have the DGV bound to data and all the other controls properly. What I am trying to do now is update a PictureBox based on the contents of the data row. The picture is not a part of the bound data, its always available on the web. I have a function that will build the url string to a webserver with the images I need. The problem is that I can figure out the proper event. Mouse Click works perfectly but doesnt allow for keyboard selection (ie bound fields update but pictureBox does not). RowEnter/RowLeave both leave me with the picture from the row that was previously selected, never the current row. Any insight would be appreciated.
Another wild guess: SelectionChanged
EDIT: Realized you wanted it to happen when you selected a row.. ``` MyGrid.RowEnter += new DataGridViewCellEventHandler(MyGrid_RowEnter ); void MyGrid_RowEnter(object sender, DataGridViewCellEventHandlere) { if (0 > e.RowIndex) return; //TODO: Do whatever with your image here.. } ```
DataGridView: Which Event do I need?
[ "", "c#", "winforms", "datagridview", "" ]
i'm pretty sure it's not possible, but i'll throw this out there anyways. I have about 10 asp:checkbox controls on the page, and I need to go and update the database every time any of them gets checked/unchecked. Right now i have all of them tied to one event handler that fires on CheckedChanged, then i cast the sender to Checkbox and get the ID, and assign a value based on that ID to a parameter that gets passes to the stored procedure. Is it possible to assign a custom parameter to each checkbox, so i don't have to tie their IDs to sproc parameter values. Thank you. **p.s. static Dictionary<> seems to be the way to go, however i can't get examples from [this post](https://stackoverflow.com/questions/313324/declare-a-dictionary-inside-a-static-class) to work in .net 2.0**
Why not make your own custom server checkbox control. ``` namespace CustomControls { public class CustomCheckBox : CheckBox { string _myValue; public string MyValue { get { return _myValue; } set { _myValue = value; } } public CustomCheckBox() { } } } <%@ Register TagPrefix="MyControls" Namespace="CustomControls"%> <MyControls:CustomCheckBox id="chkBox" runat="server" MyValue="value"></MyControls:CustomTextBox> ```
It might be an idea to try using regular HTML checkboxes and submitting them as an array / comma-separated list: ``` <input type="checkbox" id="item-1" name="items[]" value="1" /> <label for="item1">Item 1</label> .... <input type="checkbox" id="item-n" name="items[]" value="n" /> <label for="item1">Item n</label> ``` Then on the server side you could do something like: ``` string tmp = Request.Form["items[]"]; if (!string.IsNullOrEmpty(tmp)) { string [] items = tmp.Split(new char[]{','}); // rest of processing, etc. } ``` Hopefully this will reduce the amount of work you have to do server side.
Assigning a value (or any other parameter) to asp:checkbox
[ "", "c#", ".net", "asp.net", ".net-2.0", "checkbox", "" ]
I have a service written in C# (.NET 1.1) and want it to perform some cleanup actions at midnight every night. I have to keep all code contained within the service, so what's the easiest way to accomplish this? Use of `Thread.Sleep()` and checking for the time rolling over?
I wouldn't use Thread.Sleep(). Either use a scheduled task (as others have mentioned), or set up a timer inside your service, which fires periodically (every 10 minutes for example) and check if the date changed since the last run: ``` private Timer _timer; private DateTime _lastRun = DateTime.Now.AddDays(-1); protected override void OnStart(string[] args) { _timer = new Timer(10 * 60 * 1000); // every 10 minutes _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); _timer.Start(); //... } private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { // ignore the time, just compare the date if (_lastRun.Date < DateTime.Now.Date) { // stop the timer while we are running the cleanup task _timer.Stop(); // // do cleanup stuff // _lastRun = DateTime.Now; _timer.Start(); } } ```
Check out [Quartz.NET](http://quartznet.sourceforge.net/). You can use it within a Windows service. It allows you to run a job based on a configured schedule, and it even supports a simple "cron job" syntax. I've had a lot of success with it. Here's a quick example of its usage: ``` // Instantiate the Quartz.NET scheduler var schedulerFactory = new StdSchedulerFactory(); var scheduler = schedulerFactory.GetScheduler(); // Instantiate the JobDetail object passing in the type of your // custom job class. Your class merely needs to implement a simple // interface with a single method called "Execute". var job = new JobDetail("job1", "group1", typeof(MyJobClass)); // Instantiate a trigger using the basic cron syntax. // This tells it to run at 1AM every Monday - Friday. var trigger = new CronTrigger( "trigger1", "group1", "job1", "group1", "0 0 1 ? * MON-FRI"); // Add the job to the scheduler scheduler.AddJob(job, true); scheduler.ScheduleJob(trigger); ```
How might I schedule a C# Windows Service to perform a task daily?
[ "", "c#", "windows-services", "scheduling", "scheduled-tasks", "" ]
I try to dynamically add nodes to a Java Swing [`JTree`](http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JTree.html), and the user should be able to browse and to collapse hierarchy while nodes are constantly added. When I add a `Thread.sleep(10)` in my loop, it works fine; but this is a dirty hack... Here is the stripped down code that triggers this problem. Whenever I run this and doubleclick on the root node to expand/collapse it (while nodes are added), I get an `ArrayIndexOutOfBoundsException`. When I add a `Thread.sleep(10)` this does not happen. I guess this is a threading issue, but I have no idea how to synchronize this? Any hints would be greatly appreciated! ``` public static void main(String[] args) throws InterruptedException { final JFrame frame = new JFrame(); frame.setSize(600, 800); frame.setVisible(true); MutableTreeNode root = new DefaultMutableTreeNode("root"); final DefaultTreeModel model = new DefaultTreeModel(root); final JTree tree = new JTree(model); frame.add(new JScrollPane(tree)); while (true) { MutableTreeNode child = new DefaultMutableTreeNode("test"); model.insertNodeInto(child, root, root.getChildCount()); tree.expandRow(tree.getRowCount() - 1); // uncommenting this to make it work // Thread.sleep(10); } } ``` I want to use this for a search-on-typing application, so giving (almost) instant results is essential for me. **EDIT:** Thanks for the quick answers! `SwingUtilities.invokeLater()` solves the problem. I now do this: 1. Add 100 items within `SwingUtilities.invokeLater();` 2. After 100 items, I run this so that the GUI can get updated: ``` // just wait so that all events in the queue can be processed SwingUtilities.invokeAndWait(new Runnable() { public void run() { }; }); ``` This way I have a very responsive GUI and it works perfectly. Thanks!
tree.expandRow needs to be done in the event thread, so change the loop as follows: ``` while (true) { MutableTreeNode child = new DefaultMutableTreeNode("test"); model.insertNodeInto(child, root, root.getChildCount()); final int rowToExpand = tree.getRowCount() - 1; // ? does this work ? SwingUtilities.invokeLater(new Runnable() { public void run() { tree.expandRow(rowToExpand); } }); } ``` While you're at it, you probably need to make sure whatever list your tree model is using is synchronized, so you don't insert into the collection while the tree is being traversed by the paint thread.
Swing is thread-hostile, so do your Swing manipulation in the AWT Event Diaptch Thread (EDT). The infinite loop is nonsense, so difficult to come up with a suggestion. The best equivalent I can think of is iterating posting an even to run the code again. Because there are certain priorities in the event queue, I'm not sure even that works. ``` public static void main(String[] args) throws InterruptedException { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { runEDT(); }}); } private static void runEDT() { assert java.awt.EventQueue.isDispatchThread(); final JFrame frame = new JFrame(); frame.setSize(600, 800); frame.setVisible(true); final MutableTreeNode root = new DefaultMutableTreeNode("root"); final DefaultTreeModel model = new DefaultTreeModel(root); final JTree tree = new JTree(model); frame.add(new JScrollPane(tree)); frame.validate(); new Runnable() { public void run() { final MutableTreeNode child = new DefaultMutableTreeNode("test"); model.insertNodeInto(child, root, root.getChildCount()); tree.expandRow(tree.getRowCount() - 1); final Runnable addNode = this; // Inner class confusion... java.awt.EventQueue.invokeLater(addNode); }}.run(); } ``` (Disclaimer: Not compiled or tested.)
JTree gives ArrayIndexOutOfBoundsException?
[ "", "java", "multithreading", "swing", "synchronization", "jtree", "" ]
Is there any way or a library to get a system-wide (global) keyboard shortcut to perform an action in a Java application?
There is not, but in windows you can use this: [jintellitype](https://github.com/melloware/jintellitype) Unfortunately there is nothing I'm aware of for Linux and OSX, probably that's why it doesn't come with java out of the box. If you find for the other platforms post it here please :) Just for couriosity, what are you doing with that?
I am the author of JIntellitype and I can tell you for a fact this must be done natively in DLL and called from Java JNI just like JIntellitype does it. This is an OS level hook that is not implemented in the JDK so libraries like JIntellitype and jxGrabKey must be used. As far as I know no one has written one for OSX yet. JIntellitype is open source on Github, so if you want an idea of how it works just check out the [source](https://github.com/melloware/jintellitype) code
Java System-Wide Keyboard Shortcut
[ "", "java", "keyboard", "system", "shortcut", "" ]
I'm using callables quite often , and I've stubled upon a question that irritates me: Lets say that to run function foo() , one needs to do a couple of checks first. Should you 1. Insert the checks as part of the Callable : ``` class A implements Callable<Long> { ... public Long call() { check1(); check2(); return (run()); } ``` 2. OR , insert all this logic into another class (ALogic) and use the Callable a mere shell for the executor? `class A implements Callable { ... public Long call() { ALogic aLogic = new ALogic(); return (aLogic.run()); }` What do you think are the pro's and con's? What do you usually prefer?
My general advice when implementing callback [Java keyword] interfaces is concentrate on making the [non-Java keyword] interface appropriate for the called type. There generally shouldn't be that much in the anonymous inner class (or whatever), but more than just forwarding call. Also, it's generally not good to have an object that is constructed and then only has a single method called on it. Make it a static method (which may, perhaps, in turn create an object through a private constructor and run that).
Which do you feel is simpler or clearer? I suggest you do that.
How much logic is it "right" to put in a Callable?
[ "", "java", "callable", "" ]
Ok so I have a number of methods that look like this:- which sorts a list by artist, album, year etc. ``` public void SortByAlbum(SortOrder sortOrder) { if (sortOrder == SortOrder.Ascending) _list = _list.OrderBy(x => x.Album).ToList(); else if (sortOrder == SortOrder.Descending) _list = _list.OrderByDescending(x => x.Album).ToList(); } ``` and this: ``` public void SortByArtist(SortOrder sortOrder) { if (sortOrder == SortOrder.Ascending) _list = _list.OrderBy(x => x.Artist).ToList(); else if (sortOrder == SortOrder.Descending) _list = _list.OrderByDescending(x => x.Artist).ToList(); } ``` Now obviously this isn't good code so it needs refactoring into one Sort() method but I just cant figure out how to do it in the simplest possible way. I don't care if it uses IComparer or LINQ. I want it to look something like this: ``` public void Sort(SortOrder sortOrder, SortType sortType) { //implementation here } public enum SortType { Artist, Album, Year } ``` So whats the cleanest way to do this with no code repetition? Thanks, Lee
You should be able to mimick the signature of the OrderBy extension method: **Update 1** you have to be explicit in the first generic parameter to your keySelector Func. I'm going to take a guess at your type and call it "Song". ``` public void Sort<TKey>(SortOrder sortOrder, Func<Song, TKey> keySelector) { if (sortOrder == SortOrder.Descending) { _list = _list.OrderByDescending(keySelector).ToList(); } else { _list = _list.OrderBy(keySelector).ToList(); } } ``` Now you can call "Sort" like this: ``` Sort(SortOrder.Descending, x => x.Album); ``` **Update 2** Following up on Tom Lokhorst's comment: If you want to predefine some shorthand sort criteria, you could do so by defining a class like this: ``` public static class SortColumn { public static readonly Func<Song, string> Artist = x => x.Artist; public static readonly Func<Song, string> Album = x => x.Album; } ``` Now you can simply call: ``` Sort(SortOrder.Descending, SortColumn.Artist); ```
You might try using a [generic comparer](http://www.c-sharpcorner.com/UploadFile/dipenlama22/SortingUsingGeneric07052006081035AM/SortingUsingGeneric.aspx?ArticleID=dafdb8cc-fd02-4a4d-bd17-0c5785b1b91d).
Avoiding code repetition when using LINQ
[ "", "c#", ".net", "linq", "refactoring", "" ]
Ok, I have a set of checkboxes for selecting criteria. For argument's sake, we'll say the data looks like this: ``` [] Vehicles [] Unpowered [] Bicycle [] Skateboard [] Powered [] Two-wheeled [] Motorcycle [] Scooter [] Four-wheeled etc ``` The []s represent checkboxes. Ignoring the obviously contrived nature of this example, the idea is this: * To start with, only the Vehicle checkbox is visible; * If the user clicks on the Vehicle checkbox is opsn up the next level (Powered, Unpowered); * If the user selects Powered it opens up the next level (Two-wheeled, Four-wheeled); * If the user then unchecks Powered, that level disappears. Now this is relatively easy to set up with onclick's toggling the display CSS attribute between block and none. This is currently structured on the page as: ``` <table> <tr> <td><input type="checkbox" onclick="toggle('__Vehicles');"></td> <td>Vehicles <table id="__Vehicles"> <tr> <td><input type="checkbox"></td> <td>Unpowered etc ``` I should point out before someone asks: the reason the checkbox was put in table cell was to control formatting. It made it easy to effectively indent since everything in the next table cell would line up. It all works fine but the table nesting gets pretty deep. I keep thinking there has to be a better way than this. It has to be able to be easily built dynamically and have good cross-browser support for formatting of the "tree". I should also mention that jQuery is available. I'm using it for other things. Suggestions? **Edit:** Yes the checkbox styling is important as a couple of comments have noted. Also, I have posted a solution to this, based on the responses I've gotten, as an answer below (too big to add here), just for those curious to see an example.
``` <ul> <li><input type="checkbox" />Vehicles <ul> <li><input type="checkbox" />Unpowered</li> <li><input type="checkbox" />Bicycle</li> <li><input type="checkbox" />Skateboard</li> </ul></li> <li><input type="checkbox" />Powered <ul> <li><input type="checkbox" />Two-wheeled <ul> <li><input type="checkbox" />Motorcycle</li> <li><input type="checkbox" />Scooter</li> </ul></li> <li><input type="checkbox" />Four-wheeled</li> </ul></li> </ul> ``` Edit: a little css & js to show & hide nested elements (no checkboxes) ``` li.opened ul { display: block; } li.closed ul { display: none; } ``` and js... ``` $(document).ready(function() { $('li input:checkbox').click(function () { $(this).parent().toggleClass('opened'); $(this).parent().toggleClass('closed'); }); $('li').addClass('closed'); }); ``` edit, again, because Sparr wants some better styles (assuming that the checkboxes have a style of "checkbox" ``` li input.checkbox { /* input:checkbox is not 100% compatible */ width: 6px; margin: 0 2px; /* This makes 10px be the total "width" ofh the checkbox */ } ul { margin: 0 0 0 10px; /* Or whatever your total checkbox width is */ padding: 0; } li { padding: 0; } ```
You could do this: ``` <ul> <li> <input type="checkbox" /> Option 1 <ul> <li><input type="checkbox" /> Option 1 Sub Option A</li> </ul> </li> </ul> ``` You'd then set the padding/margin of the UL's to 0 and 0. Then set the padding-left of the LI's to 10px. ``` ul { margin:0; padding:0; } li { margin:0; padding:0 0 0 20px; /* Each nested li will be padded incrementally */ } ``` For the javascript, attach an event to each checkbox that determines whether the sibling UL (if any exists) should be visible. If the box is checked, show it, else, hide it.
HTML/CSS: what's a better option for layout of a tree of nested elements than nested tables?
[ "", "javascript", "jquery", "html", "css", "cross-browser", "" ]
What would be the most efficient way to do a paging query in SQLServer 2000? Where a "paging query" would be the equivalent of using the LIMIT statement in MySQL. EDIT: Could a stored procedure be more efficient than any set based query in that case?
[Paging of Large Resultsets](http://www.codeproject.com/KB/aspnet/PagingLarge.aspx) and the winner is using RowCount. Also there's a generalized version for more complex queries. But give credit to **Jasmin Muharemovic** :) ``` DECLARE @Sort /* the type of the sorting column */ SET ROWCOUNT @StartRow SELECT @Sort = SortColumn FROM Table ORDER BY SortColumn SET ROWCOUNT @PageSize SELECT ... FROM Table WHERE SortColumn >= @Sort ORDER BY SortColumn ``` The article contains the entire source code. Please read the "Update 2004-05-05" information. !
I think a nested `SELECT TOP n` query is probably the most efficient way to accomplish it. ``` SELECT TOP ThisPageRecordCount * FROM Table WHERE ID NOT IN (SELECT TOP BeforeThisPageRecordCount ID FROM Table ORDER BY OrderingColumn) ORDER BY OrderingColumn ``` Replace `ThisPageRecordCount` with items per page and `BeforeThisPageRecordCount` with `(PageNumber - 1) * items-per-page`. Of course the better way in SQL Server 2005 is to use the `ROW_NUMBER()` function in a CTE.
Efficient Paging (Limit) Query in SQLServer 2000?
[ "", "sql", "sql-server-2000", "paging", "limit", "" ]
I am binding an Image.Source property to the result of the property shown below. ``` public BitmapSource MyImageSource { get { BitmapSource source = null; PngBitmapDecoder decoder; using (var stream = new FileStream(@"C:\Temp\logo.png", FileMode.Open, FileAccess.Read, FileShare.Read)) { decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); if (decoder.Frames != null && decoder.Frames.Count > 0) source = decoder.Frames[0]; } return source; } } ``` For some reason this is failing during the rendering of the image (Deep in the PresentationCore assembly). I am certain the image is not corrupt as I can successfully show the same image w/o the binding ``` <Image Name="FooImage" Source="/logo.png" /> ``` I have to bind the image source in code because I will eventually be creating the image stream from a base64 string. Anyone know if this is a bug w/ WPF? or am I doing something incorrectly?
The problem was the BitmapCacheOption option, changing to BitmapCacheOption.OnLoad works. With BitmapCacheOption.None the BitmapSource isn’t decoded until the image is rendered, but the stream with the png in it is already disposed at that point. If you cache OnLoad, it’ll decode right away and cache the results, rather than trying to decode later when the stream no longer exists.
Also, have you tried just using a BitmapImage to load the image? It works fine with PNG, BMP, and JPEG. It's also a specialized type of BitmapSource, so you could just replace your code in your property with this: ``` BitmapImage img = new BitmapImage(new Uri(@"C:\Temp\logo.png")); return img; ```
WPF BitmapSource ImageSource
[ "", "c#", "wpf", "xaml", "binding", "" ]
I'm trying to find out the best practice when removing characters from the start of a string. In some languages, you can use MID without a length parameter however, in TSQL the length is required. Considering the following code, what is the best practise? (The hex string is variable length) ``` DECLARE @sHex VARCHAR(66) SET @sHex = '0x7E260F3DA734AD4BD816B88F485CE501D843DF067C8EDCB8AC7DAD331852E04D' PRINT RIGHT(@sHex,LEN(@sHex) -2) PRINT SUBSTRING(@sHex,3,LEN(@sHex) -2) PRINT SUBSTRING(@sHex,3,65535) ```
Well, the first is more expressive of your intent. The last is clearly messy (hard-coded length etc). I doubt you'd find much performance difference between the first & second, so I'd use the simplest - `RIGHT`. Of course, if you are doing this lots, you could write a udf that encapsulates this - then if you change your mind you only have one place to change...
+1 on the right function, it is much clearer what you want to do
SQL SUBSTRING vs RIGHT - Best Practice
[ "", "sql", "t-sql", "string", "" ]
Is it possible via script/tool to generate a delete statement based on the tables fk relations. i.e. I have the table: DelMe(ID) and there are 30 tables with fk references to its ID that I need to delete first, is there some tool/script that I can run that will generate the 30 delete statements based on the FK relations for me ? (btw I know about cascade delete on the relations, I can't use it in this existing db) I'm using Microsoft SQL Server 2008
DELETE statements generated for use in SP with parameter, and as ON DELETE triggers: (this variant supports single column FKs only) ``` SELECT 'DELETE '+detail.name+' WHERE '+dcolumn.name+' = @'+mcolumn.name AS stmt, 'DELETE ' + detail.name + ' FROM ' + detail.name + ' INNER JOIN deleted ON ' + detail.name + '.' + dcolumn.name + ' = deleted.' + mcolumn.name AS trg FROM sys.columns AS mcolumn INNER JOIN sys.foreign_key_columns ON mcolumn.object_id = sys.foreign_key_columns.referenced_object_id AND mcolumn.column_id = sys.foreign_key_columns.referenced_column_id INNER JOIN sys.tables AS master ON mcolumn.object_id = master.object_id INNER JOIN sys.columns AS dcolumn ON sys.foreign_key_columns.parent_object_id = dcolumn.object_id AND sys.foreign_key_columns.parent_column_id = dcolumn.column_id INNER JOIN sys.tables AS detail ON dcolumn.object_id = detail.object_id WHERE (master.name = N'MyTableName') ```
Here is a script for cascading delete by [Aasim Abdullah](http://connectsql.blogspot.co.il/2011/03/sql-server-cascade-delete.html), works for me on MS SQL Server 2008: ``` IF OBJECT_ID('dbo.udfGetFullQualName') IS NOT NULL DROP FUNCTION dbo.udfGetFullQualName; GO CREATE FUNCTION dbo.udfGetFullQualName (@ObjectId INT) RETURNS VARCHAR (300) AS BEGIN DECLARE @schema_id AS BIGINT; SELECT @schema_id = schema_id FROM sys.tables WHERE object_id = @ObjectId; RETURN '[' + SCHEMA_NAME(@schema_id) + '].[' + OBJECT_NAME(@ObjectId) + ']'; END GO --============ Supporting Function dbo.udfGetOnJoinClause IF OBJECT_ID('dbo.udfGetOnJoinClause') IS NOT NULL DROP FUNCTION dbo.udfGetOnJoinClause; GO CREATE FUNCTION dbo.udfGetOnJoinClause (@fkNameId INT) RETURNS VARCHAR (1000) AS BEGIN DECLARE @OnClauseTemplate AS VARCHAR (1000); SET @OnClauseTemplate = '[<@pTable>].[<@pCol>] = [<@cTable>].[<@cCol>] AND '; DECLARE @str AS VARCHAR (1000); SET @str = ''; SELECT @str = @str + REPLACE(REPLACE(REPLACE(REPLACE(@OnClauseTemplate, '<@pTable>', OBJECT_NAME(rkeyid)), '<@pCol>', COL_NAME(rkeyid, rkey)), '<@cTable>', OBJECT_NAME(fkeyid)), '<@cCol>', COL_NAME(fkeyid, fkey)) FROM dbo.sysforeignkeys AS fk WHERE fk.constid = @fkNameId; --OBJECT_ID('FK_ProductArrearsMe_ProductArrears') RETURN LEFT(@str, LEN(@str) - LEN(' AND ')); END GO --=========== CASECADE DELETE STORED PROCEDURE dbo.uspCascadeDelete IF OBJECT_ID('dbo.uspCascadeDelete') IS NOT NULL DROP PROCEDURE dbo.uspCascadeDelete; GO CREATE PROCEDURE dbo.uspCascadeDelete @ParentTableId VARCHAR (300), @WhereClause VARCHAR (2000), @ExecuteDelete CHAR (1)='N', --'N' IF YOU NEED DELETE SCRIPT @FromClause VARCHAR (8000)='', @Level INT=0 -- TABLE NAME OR OBJECT (TABLE) ID (Production.Location) WHERE CLAUSE (Location.LocationID = 7) 'Y' IF WANT TO DELETE DIRECTLY FROM SP, IF LEVEL 0, THEN KEEP DEFAULT AS -- writen by Daniel Crowther 16 Dec 2004 - handles composite primary keys SET NOCOUNT ON; /* Set up debug */ DECLARE @DebugMsg AS VARCHAR (4000), @DebugIndent AS VARCHAR (50); SET @DebugIndent = REPLICATE('---', @@NESTLEVEL) + '> '; IF ISNUMERIC(@ParentTableId) = 0 BEGIN -- assume owner is dbo and calculate id IF CHARINDEX('.', @ParentTableId) = 0 SET @ParentTableId = OBJECT_ID('[dbo].[' + @ParentTableId + ']'); ELSE SET @ParentTableId = OBJECT_ID(@ParentTableId); END IF @Level = 0 BEGIN PRINT @DebugIndent + ' **************************************************************************'; PRINT @DebugIndent + ' *** Cascade delete ALL data from ' + dbo.udfGetFullQualName(@ParentTableId); IF @ExecuteDelete = 'Y' PRINT @DebugIndent + ' *** @ExecuteDelete = Y *** deleting data...'; ELSE PRINT @DebugIndent + ' *** Cut and paste output into another window and execute ***'; END DECLARE @CRLF AS CHAR (2); SET @CRLF = CHAR(13) + CHAR(10); DECLARE @strSQL AS VARCHAR (4000); IF @Level = 0 SET @strSQL = 'SET NOCOUNT ON' + @CRLF; ELSE SET @strSQL = ''; SET @strSQL = @strSQL + 'PRINT ''' + @DebugIndent + dbo.udfGetFullQualName(@ParentTableId) + ' Level=' + CAST (@@NESTLEVEL AS VARCHAR) + ''''; IF @ExecuteDelete = 'Y' EXECUTE (@strSQL); ELSE PRINT @strSQL; DECLARE curs_children CURSOR LOCAL FORWARD_ONLY FOR SELECT DISTINCT constid AS fkNameId, -- constraint name fkeyid AS cTableId FROM dbo.sysforeignkeys AS fk WHERE fk.rkeyid <> fk.fkeyid -- WE DO NOT HANDLE self referencing tables!!! AND fk.rkeyid = @ParentTableId; OPEN curs_children; DECLARE @fkNameId AS INT, @cTableId AS INT, @cColId AS INT, @pTableId AS INT, @pColId AS INT; FETCH NEXT FROM curs_children INTO @fkNameId, @cTableId; --, @cColId, @pTableId, @pColId DECLARE @strFromClause AS VARCHAR (1000); DECLARE @nLevel AS INT; IF @Level = 0 BEGIN SET @FromClause = 'FROM ' + dbo.udfGetFullQualName(@ParentTableId); END WHILE @@FETCH_STATUS = 0 BEGIN SELECT @strFromClause = @FromClause + @CRLF + ' INNER JOIN ' + dbo.udfGetFullQualName(@cTableId) + @CRLF + ' ON ' + dbo.udfGetOnJoinClause(@fkNameId); SET @nLevel = @Level + 1; EXECUTE dbo.uspCascadeDelete @ParentTableId = @cTableId, @WhereClause = @WhereClause, @ExecuteDelete = @ExecuteDelete, @FromClause = @strFromClause, @Level = @nLevel; SET @strSQL = 'DELETE FROM ' + dbo.udfGetFullQualName(@cTableId) + @CRLF + @strFromClause + @CRLF + 'WHERE ' + @WhereClause + @CRLF; SET @strSQL = @strSQL + 'PRINT ''---' + @DebugIndent + 'DELETE FROM ' + dbo.udfGetFullQualName(@cTableId) + ' Rows Deleted: '' + CAST(@@ROWCOUNT AS VARCHAR)' + @CRLF + @CRLF; IF @ExecuteDelete = 'Y' EXECUTE (@strSQL); ELSE PRINT @strSQL; FETCH NEXT FROM curs_children INTO @fkNameId, @cTableId; --, @cColId, @pTableId, @pColId END IF @Level = 0 BEGIN SET @strSQL = @CRLF + 'PRINT ''' + @DebugIndent + dbo.udfGetFullQualName(@ParentTableId) + ' Level=' + CAST (@@NESTLEVEL AS VARCHAR) + ' TOP LEVEL PARENT TABLE''' + @CRLF; SET @strSQL = @strSQL + 'DELETE FROM ' + dbo.udfGetFullQualName(@ParentTableId) + ' WHERE ' + @WhereClause + @CRLF; SET @strSQL = @strSQL + 'PRINT ''' + @DebugIndent + 'DELETE FROM ' + dbo.udfGetFullQualName(@ParentTableId) + ' Rows Deleted: '' + CAST(@@ROWCOUNT AS VARCHAR)' + @CRLF; IF @ExecuteDelete = 'Y' EXECUTE (@strSQL); ELSE PRINT @strSQL; END CLOSE curs_children; DEALLOCATE curs_children; ``` **Usage example 1** Note the use of the fully qualified column name in the example. It's subtle but you must specify the table name for the generated SQL to execute properly. ``` EXEC uspCascadeDelete @ParentTableId = 'Production.Location', @WhereClause = 'Location.LocationID = 2' ``` **Usage example 2** ``` EXEC uspCascadeDelete @ParentTableId = 'dbo.brand', @WhereClause = 'brand.brand_name <> ''Apple''' ``` **Usage example 3** ``` exec uspCascadeDelete @ParentTableId = 'dbo.product_type', @WhereClause = 'product_type.product_type_id NOT IN (SELECT bpt.product_type_id FROM dbo.brand_product_type bpt)' ```
Generate Delete Statement From Foreign Key Relationships in SQL 2008?
[ "", "sql", "code-generation", "foreign-keys", "dynamic-sql", "" ]
When using Python's `super()` to do method chaining, you have to explicitly specify your own class, for example: ``` class MyDecorator(Decorator): def decorate(self): super(MyDecorator, self).decorate() ``` I have to specify the name of my class `MyDecorator` as an argument to `super()`. This is not DRY. When I rename my class now I will have to rename it twice. Why is this implemented this way? And is there a way to weasel out of having to write the name of the class twice(or more)?
The BDFL agrees. See [PEP 3135 - New Super](http://www.python.org/dev/peps/pep-3135/) for Python 3.0 (and [Pep 367 - New Super](http://www.python.org/dev/peps/pep-0367/) for Python 2.6).
In Python 3.0, you can use `super()` which is equivalent to `super(ThisClass, self)`. Documentation [here](http://docs.python.org/3.0/library/functions.html#super). Code sample from the documentation: ``` class C(B): def method(self, arg): super().method(arg) # This does the same thing as: super(C, self).method(arg) ```
Why do I have to specify my own class when using super(), and is there a way to get around it?
[ "", "python", "multiple-inheritance", "" ]
I thought that to clone a List you would just call: ``` List<int> cloneList = new List<int>(originalList); ``` But I tried that in my code and I seem to be getting effects that imply the above is simply doing: cloneList = originalList... because changes to cloneList seem to be affecting originalList. So what is the way to clone a List? EDIT: I am thinking of doing something like this: ``` public static List<T> Clone<T>(this List<T> originalList) where T : ICloneable { return originalList.ConvertAll(x => (T) x.Clone()); } ``` EDIT2: I took the deep copy code suggested by Binoj Antony and created this extension method: ``` public static T DeepCopy<T>(this T original) where T : class { using (MemoryStream memoryStream = new MemoryStream()) { BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(memoryStream, original); memoryStream.Seek(0, SeekOrigin.Begin); return (T)binaryFormatter.Deserialize(memoryStream); } } ``` EDIT3: Now, say the items in the List are structs. What then would result if I called?: ``` List<StructType> cloneList = new List<StructType>(originalList); ``` I am pretty sure than I would get a List filled with new unique items, correct?
You can use the below code to make a deep copy of the list or any other object supporting serialization: Also you can use this for any version of .NET framework from v 2.0 and above, and the similar technique can be applied (removing the usage of generics) and used in 1.1 as well ``` public static class GenericCopier<T> { public static T DeepCopy(object objectToCopy) { using (MemoryStream memoryStream = new MemoryStream()) { BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(memoryStream, objectToCopy); memoryStream.Seek(0, SeekOrigin.Begin); return (T) binaryFormatter.Deserialize(memoryStream); } } } ``` You can call it by using ``` List<int> deepCopiedList = GenericCopier<List<int>>.DeepCopy(originalList); ``` Full code to test if this works: ``` static void Main(string[] args) { List<int> originalList = new List<int>(5); Random random = new Random(); for(int i = 0; i < 5; i++) { originalList.Add(random.Next(1, 100)); Console.WriteLine("List[{0}] = {1}", i, originalList[i]); } List<int> deepCopiedList = GenericCopier<List<int>>.DeepCopy(originalList); for (int i = 0; i < 5; i++) Console.WriteLine("deepCopiedList[{0}] value is {1}", i, deepCopiedList[i]); } ```
This would work... ``` List<Foo> cloneList = new List<Foo>(originalList); ``` When you say "because changes to cloneList seem to be affecting originalList." - do you mean changes to the **list**, or changes to the **items**... Adding / removing / swapping items is changing the **list** - so if we do: ``` cloneList.Add(anotherItem); ``` you should find that `cloneList` is longer than `originalList`. However, if the contents are reference-types (classes), then both lists are still pointing at the same underlying objects - so if we do: ``` cloneList[0].SomeObjectProperty = 12345; ``` then this will also show against `originalList[0].SomeObjectProperty` - there is only a single object (shared between both lists). If this is the problem, you will have to clone the **objects** in the list - and then you get into the whole deep vs shallow issue... is this the problem? For a shallow copy, you might be able to use something very much like the answer [here](https://stackoverflow.com/questions/516463/copying-a-listbaseclass-to-listderivedclass/516553#516553) - simply with `TTo = TFrom` (perhaps simplify to a single `T`).
Cloning List<T>
[ "", "c#", ".net", "" ]
Is there a standard way to bind arrays (of scalars) in a SQL query? I want to bind into an `IN` clause, like so: ``` SELECT * FROM junk WHERE junk.id IN (?); ``` I happen to be using `Perl::DBI` which coerces parameters to scalars, so I end up with useless queries like: ``` SELECT * FROM junk WHERE junk.id IN ('ARRAY(0xdeadbeef)'); ``` **Clarification:** I put the query in its own `.sql` file, so the string is already formed. Where the answers mention creating the query string dynamically I'd probably do a search and replace instead. **Edit:** This question is kind of a duplicate of [Parameterizing a SQL IN clause?](https://stackoverflow.com/questions/337704/parameterizing-a-sql-in-clause). I originally thought that it should be closed as such, but it seems like it's accumulating some good Perl-specific info.
You specify "this is the SQL for a query with one parameter" -- that won't work when you want many parameters. It's a pain to deal with, of course. Two other variations to what was suggested already: 1) Use DBI->quote instead of place holders. ``` my $sql = "select foo from bar where baz in (" . join(",", map { $dbh->quote($_) } @bazs) . ")"; my $data = $dbh->selectall_arrayref($sql); ``` 2) Use an ORM to do this sort of low level stuff for you. DBIx::Class or Rose::DB::Object, for example.
If you don't like the map there, you can use the 'x' operator: ``` my $params = join ', ' => ('?') x @foo; my $sql = "SELECT * FROM table WHERE id IN ($params)"; my $sth = $dbh->prepare( $sql ); $sth->execute( @foo ); ``` The parentheses are needed around the '?' because that forces 'x' to be in list context. Read "perldoc perlop" and search for 'Binary "x"' for more information (it's in the "Multiplicative Operators" section).
Is there SQL parameter binding for arrays?
[ "", "sql", "perl", "arrays", "binding", "parameters", "" ]
When trying to display a byte stream from HLDS (Half-Life Dedicated Server) in a textbox, it displays strange blocky question mark characters that look something like this: ``` [?] ``` Here's a sample line from the byte stream (with [?] in place of the strange character): ``` CPU In Out Uptime Users FPS Players[?] 0.00 0.97 0.91 2806 182 297.25 1[?] ``` Here is how I display the byte stream as a string: ``` byte[] bytes = listener.Receive(ref sender); // get bytes from stream TextBox1.Text = Encoding.ASCII.GetString(bytes, 0, bytes.Length); // write to textbox ``` The characters are appearing where `[CR][LF]` should normally appear. Why is it showing strange characters, and what can I do to remove the weird characters or correct the encoding? ``` ***** UPDATE ***** ``` Jon Skeet provided the right answer. The logs are returning \n for newline (not \r\n) and \0 at the end of each log line streamed. Replaced \n with Environment.NewLine and \0 with string.Empty and the strange characters are gone. Thank you Jon.
Firstly, I believe that if textboxes ever receive a character 0, they will assume that's the end of data - you may want to guard against that specifically. Where does your byte stream come from? What encoding is it *meant* to be? What are the bytes at that point in the data?
1. Are you sure that the data is in pure ASCII? Is it perhaps in one of the many, many code-pages? 2. Is it perhaps because of [CR] vs [LF] vs [CR][LF]? 3. Can you tell use the bytes that are around "Players..."? And what you expect to see? We *might* be able to recognize the code-page Presumably the byte is either in the codepage zone (128-255), or control characters (0-31).
Strange characters returned from byte stream?
[ "", "c#", "character-encoding", "arrays", "" ]
I want to provide dynamic download of files. These files can be generated on-the-fly on serverside so they are represented as byte[] and do not exist on disk. I want the user to fill in an ASP.NET form, hit the download button and return the file he/she wanted. Here is how my code behind the ASP.NET form looks like: ``` public partial class DownloadService : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void submitButtonClick(object sender, EventArgs e) { if (EverythingIsOK()) { byte[] binary = GenerateZipFile(); Response.Clear(); Response.ContentType = "application/zip"; Response.ContentEncoding = System.Text.Encoding.UTF8; Response.BinaryWrite(binary); Response.End(); } } ... } ``` I expected this piece of code just work. I clear the Respone, put in my generated zip file and bingo. However, this is not the case. I get the following message in the browser: *The XML page cannot be displayed Cannot view XML input using style sheet. Please correct the error and then click the Refresh button, or try again later. An invalid character was found in text content. Error processing resource '<http://localhost:15900/mywebsite/DownloadS>...* **What am I doing wrong?**
Here's a minor modification you need to make: ``` Response.Clear(); Response.ContentType = "application/x-zip-compressed"; Response.BinaryWrite(binary); Response.End(); ```
This is my (working) implementation: ``` Response.Clear(); Response.ContentType = mimeType; Response.AddHeader("Content-Disposition", String.Format("attachment; filename=\"{0} {1} Report for Week {2}.pdf\"", ddlClient.SelectedItem.Text, ddlCollectionsDirects.SelectedItem.Text, ddlWeek.SelectedValue)); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); ``` mimeType is like your application/zip (except PDF). The main differences are the extra header information passed, and the Flush call on the Response object.
providing dynamic file download in ASP.NET2.0
[ "", "c#", "asp.net", "dynamic", "download", "" ]
I'm consuming a webservice from my application in C# .net (2.0) that return values (as string) like this: ``` %23k.%0d%16%c4%8a%18%efG%28%b9c%12%b7%f1%e2%e7j%93 ``` I know that the real value for that is: ``` 236B2E0D16C48A18EF4728B96312B7F1E2E76A93 ``` But I don't know how to convert from the returned value to the real value. Any thoughts? Anyway, thanks for your time. Cheers.
Going down the line: If you encounter '%' copy the next two characters Otherwise take the ascii code of the character found and output as hex ``` %23 => 23 k => 6B . => 2E %0d => 0D ``` [ASCII Table](http://www.asciitable.com/) But in code I'm pretty sure this will work: ``` char c = 'k'; int ascii = (int)c; string hex = ascii.ToString("X2"); ```
Thanks for the info Rob. If anyone wants the full method here it is: ``` static private string convertInfoHash(string encodedHash) { string convertedHash = string.Empty; for (int i = 0; i < encodedHash.Length; i++) { if (encodedHash[i] == '%') { convertedHash += String.Format("{0}{1}",encodedHash[i + 1],encodedHash[i + 2]); i += 2; } else { int ascii = (int)encodedHash[i]; convertedHash += ascii.ToString("X2"); } } return convertedHash; } ```
How to convert this sequence to this hash?
[ "", "c#", ".net", "hash", "" ]
I'm working on a web app which is heavy on the client side, which is a first for me. I'm also using jQuery for the first time. I need to have my client-side code keep track of model data which it fetches via Ajax calls. What's a good way to store this data? Does jQuery provide a good solution, or is there a good generic Javascript solution? I basically want to write model classes in Javascript, (but I don't necessarily need inheritance). Right now my jQuery code is a controller layer, and the DOM and CSS form my view layer. How do other people accomplish a model layer?
jQuery developer [Adam Wulf released a series of tutorials](http://welcome.totheinter.net/2008/08/05/mvc-pattern-for-the-web/) covering his development of MVC patterns on the client with jQuery some time back. You may find them to be very helpful in your current project. Also, JollyToad did some work in this area as well. [You can view their results online too](http://jollytoad.googlepages.com/mvcusingjquery).
There is also, I've discovered, a technique known as Concrete Javascript, where the DOM objects are used as model objects. Effen sounds like a nice way to implement that: <http://github.com/nkallen/effen/tree/master>.
What's a good way to store model data in a jQuery app?
[ "", "javascript", "jquery", "model", "" ]
I've been using the `==` operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into `.equals()` instead, and it fixed the bug. Is `==` bad? When should it and should it not be used? What's the difference?
`==` tests for reference equality (whether they are the same object). `.equals()` tests for value equality (whether they contain the same data). [Objects.equals()](http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#equals(java.lang.Object,%20java.lang.Object)) checks for `null` before calling `.equals()` so you don't have to (available as of JDK7, also available in [Guava](https://github.com/google/guava/wiki/CommonObjectUtilitiesExplained#equals)). Consequently, if you want to test whether two strings have the same value you will probably want to use `Objects.equals()`. ``` // These two have the same value new String("test").equals("test") // --> true // ... but they are not the same object new String("test") == "test" // --> false // ... neither are these new String("test") == new String("test") // --> false // ... but these are because literals are interned by // the compiler and thus refer to the same object "test" == "test" // --> true // ... string literals are concatenated by the compiler // and the results are interned. "test" == "te" + "st" // --> true // ... but you should really just call Objects.equals() Objects.equals("test", new String("test")) // --> true Objects.equals(null, "test") // --> false Objects.equals(null, null) // --> true ``` From the Java Language Specification [JLS 15.21.3. Reference Equality Operators `==` and `!=`](https://docs.oracle.com/javase/specs/jls/se21/html/jls-15.html#jls-15.21.3): > While `==` may be used to compare references of type `String`, such an equality test determines whether or not the two operands refer to the same `String` object. The result is `false` if the operands are distinct `String` objects, even if they contain the same sequence of characters ([§3.10.5](https://docs.oracle.com/javase/specs/jls/se21/html/jls-3.html#jls-3.10.5), [§3.10.6](https://docs.oracle.com/javase/specs/jls/se21/html/jls-3.html#jls-3.10.6)). The contents of two strings `s` and `t` can be tested for equality by the method invocation `s.equals(t)`. You almost **always** want to use `Objects.equals()`. In the **rare** situation where you **know** you're dealing with [interned](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#intern--) strings, you *can* use `==`. From [JLS 3.10.5. *String Literals*](https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.5): > Moreover, a string literal always refers to the *same* instance of class `String`. This is because string literals - or, more generally, strings that are the values of constant expressions ([§15.28](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.28)) - are "interned" so as to share unique instances, using the method `String.intern`. Similar examples can also be found in [JLS 3.10.5-1](https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#d5e1634). ### Other Methods To Consider [String.equalsIgnoreCase()](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#equalsIgnoreCase-java.lang.String-) value equality that ignores case. Beware, however, that this method can have unexpected results in various locale-related cases, see [this question](https://stackoverflow.com/questions/44238749/equalsignorecase-not-working-as-intended). [String.contentEquals()](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#contentEquals-java.lang.CharSequence-) compares the content of the `String` with the content of any `CharSequence` (available since Java 1.5). Saves you from having to turn your StringBuffer, etc into a String before doing the equality comparison, but leaves the null checking to you.
`==` tests object references, `.equals()` tests the string values. Sometimes it looks as if `==` compares values, because Java does some behind-the-scenes stuff to make sure identical in-line strings are actually the same object. For example: ``` String fooString1 = new String("foo"); String fooString2 = new String("foo"); // Evaluates to false fooString1 == fooString2; // Evaluates to true fooString1.equals(fooString2); // Evaluates to true, because Java uses the same object "bar" == "bar"; ``` **But beware of nulls!** `==` handles `null` strings fine, but calling `.equals()` from a null string will cause an exception: ``` String nullString1 = null; String nullString2 = null; // Evaluates to true System.out.print(nullString1 == nullString2); // Throws a NullPointerException System.out.print(nullString1.equals(nullString2)); ``` So if you know that `fooString1` may be null, tell the reader that by writing ``` System.out.print(fooString1 != null && fooString1.equals("bar")); ``` The following are shorter, but it’s less obvious that it checks for null: ``` System.out.print("bar".equals(fooString1)); // "bar" is never null System.out.print(Objects.equals(fooString1, "bar")); // Java 7 required ```
How do I compare strings in Java?
[ "", "java", "string", "equality", "" ]
Simple question, but I haven't found a good explanation on google. When using Set Statistics IO ON, the logical reads and scan count is provided in the message window of management studio. If I have: tblExample, scan count 5, logical reads 20 What does scan count signify?
From Books On Line **Scan count:** Number of index or table scans performed. **logical reads:** Number of pages read from the data cache. **physical reads:** Number of pages read from disk. **read-ahead reads:** Number of pages placed into the cache for the query. See also here: <http://technet.microsoft.com/en-us/library/ms184361.aspx>
As far as what a "table scan" *means*, the best I could find is this: > **Scan count simply means how many times the table or index was accessed during the query.** It may be a full scan, partial scan, or simply a seek. In other words, scan count alone by itself is *not enough information* to proceed. You need to know what those scans were, exactly -- so you'll have to look at the actual execution plan for more detail. Bottom line it's not a very useful metric by itself! Additionally: <http://www.eggheadcafe.com/software/aspnet/32171165/set-statistics-io-scan-count-explanation.aspx> > Unfortunately, **Scan Count these days is not very informative**. Hm, well, > if you see a number like 19223, the table has probably be accessed > through a nested loop join many times. > > There was a time when "scan count" simply meant "times table accessed", > but that was long ago, maybe in SQL 6.5. The only time you could get > a scan count with that definition of 0 is with a query like ... > > ``` > select * > from TestA1 > where CompanyID = 1 > and CompanyID = 2 > ``` > > ... where SQL Server could be able to conclude that the query will not return > any rows, without accessing the table.
sql statistics io scan count explanation
[ "", "sql", "performance", "count", "statistics", "database-scan", "" ]