text
stringlengths
8
267k
meta
dict
Q: Benefits and portability of Boost Library Since I have started using this site, I keep hearing about the Boost library. I am wondering what are some of the major benefits of the Boost library (hence why should I use it) and how portable is the Boost library? A: Boost is a collection of high quality peer reviewed C++ libraries that place emphasis on portability and correctness. It acts as the defacto proving grounds for new additions to the language and the standard library. Check out their website for more details. A: Boost is organized by several members of the standard committee. So it is a breeding ground for libraries that will be in the next standard. * *It is an extension to the STL (it fills in the bits left out) *It is well documented. *It is well peer-reviewed. *It has high activity so bugs are found and fixed quickly. *It is platform neutral and works everywhere. *It is free to use. With tr1 coming up soon it is nice to know that boost already has a lot of the ground covered. A lot of the libraries in tr1 are basically adapted directly from boost originals and thus have been tried and tested. The difference is that they have been moved into the std::tr1 namespace (rather than boost). All that you need to do is add the following to your compilers default include search path: <boost-install-path>/boost/tr1/tr1 Then when you include the standard headers boost will automatically import all the required stuff into the namespace std::tr1 For Example: To use std::tr1::share_ptr you just need to include <memory>. This will give you all the smart pointers with one file. A: Boost's advantages: It's widely available, will port to any modern C++ compiler or about any platform. The functions are platform independant, you don't have to learn a new thread design for each new framework. It encapsulates a lot of platfom specific functions, like filesystems in a standard way. It's what C++ should have shipped with! A lot of Java's popularity was that is shipped with a standard library to do prety much everything you wanted. C++ unfortunately only inherited the limited C/Unix standard functions. A: shared_ptr and weak_ptr, especially in multithreaded code, are alone worth installing boost. BOOST_STATIC_ASSERT is also pretty cool for doing compile-time logic checking. The fact that a lot of the classes and utilities in boost are in headers, meaning you can get a lot of functionality without having to compile anything at all, is also a plus. Portability usually isn't a problem, unless you use an extremely old compiler. I once tried to get MPL to work with VC6 and it printed out 40,000 warnings/internal errors before exploding completely. But in general most of the library should work regardless of your platform or compiler vendor. Take into consideration the fact that quite a few things from Boost are already in TR1, and will most likely be in the next revision of the C++ standard library. That's a pretty big endorsement. A: Boost is a very extensive library of (usually) generic constructs that can help in almost any application. This can be shown by the fact that a lot of boost components have been included in the C++ 0x specifications. It is also portable across at least the major platforms, and should be portable to almost anything with a mostly standards compliant C++ compiler. The only warning is that there can be a lot of mingled dependencies between boost libraries, making it harder to pick out just a specific component to distribute (other than the entire boost library). A: All of the above, plus it encourages a lot of modern, best-practice C++ techniques. It tends to improve the quality of your code. A: You can simply read the Boost Background Information page to get a quick overview of why you should use Boost and what you can use it for. Worth the few minutes it takes. A: 99% portable. I would say that it has quite a few libraries that are really useful once you discover a need that is solved by boost. Either you code it yourself or you use a very solid library. Having off the shelve source for stuff like Multi-Index, Lambda, Program Options, RegEx, SmartPtr and Tuple is amazing... The best thing is to spend some time going through the documentation for the different libraries and evaluating whether it could be of any use to you. Worthy!! A: Boost is great, but just playing Devil's Advocate here are some reasons why you may not want to use Boost: * *Does sometimes fails to compile/work properly on old compilers. *It often increases compile times more than less template-heavy approaches. *Some Boost code may not do what you think that it does. Read the documentation! *Template abuse can lead to unreadable error messages. *Template abuse can lead to code hard to step through in the debugger. *It is bleeding edge C++. The next version of Boost may no longer compile on your current (older) compiler. All of this does not mean that you should not have a look at the Boost code and get some ideas yourself even if you do not use Boost as it is. A: You get a lot of the things that are coming in C++0x. But aside from that generality, some of the better specifics are a simple regex library, a casting library for casting from strings to ints (Lexical cast): int iResult = 0; try { iResult = lexical_cast<int>("4"); } catch(bad_lexical_cast &) { cout << "Unable to cast string to int"; } A date/time library, among others... using namespace boost::gregorian; date weekstart(2002,Feb,1); date thursday_next = next_weekday(weekstart, Thursday); // following Thursday There's also a Python interface (Boost Python), a lexer/parser DSL (Boost Spirit): // A grammar in C++ for equations group = '(' >> expression >> ')'; factor = integer | group; term = factor >> *(('*' >> factor) | ('/' >> factor)); expression = term >> *(('+' >> term) | ('-' >> term)); and that's just scratching the surface... A: Boost is a collection of C++ libraries. 10 of which are being included in tr1 of C++0x. You can get started with boost here. A: Also note most of boost is templates so does not require building (just include the correct header files). The few parts that do require building are optional: These can each be built independently thus preventing unnecessary bloat for unneeded code.
{ "language": "en", "url": "https://stackoverflow.com/questions/149268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "53" }
Q: How do eliminate the flicker effect on ajax call I am encountering a problem: On an html page, when i click a certain control (a tab panel title) i make an ajax call. From Wicket (java code) i call a javascript function that "redraws" all the componenets on my page (this is like a reload of the page). Everytime i do this i get a flickering effect on the html (which, as i said, after the ajax call will trigger a redrawing of all the components on the page). I am triggering the javascript function (that redraws) because i need to "redraw" using the new information supplied by the ajax response (the response gives me a new table for instance and i have to redraw, repaint the page using this new info as a sort of parameter, according to it). A: Sorry, but to be clear here: when you say "redraw" do you really mean redraw the currently existing content (as in "do dynamic changes to the table but don't delete it") or do you mean replacing the existing content with some new content, as is the normal Ajax technique? If you are replacing existing components with new components you should be OK as long as you provide some kind of fading/animation effect that draws the user's attention from the fact the control is being replaced. Sometimes doing some kind of "screen buffering" (loading all the new components in a hidden div, then replacing an existing div with the new one) will help if you are updating a lot of the interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/149272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: HTTP vs HTTPS performance Are there any major differences in performance between http and https? I seem to recall reading that HTTPS can be a fifth as fast as HTTP. Is this valid with the current generation webservers/browsers? If so, are there any whitepapers to support it? A: The overhead is NOT due to the encryption. On a modern CPU, the encryption required by SSL is trivial. The overhead is due to the SSL handshakes, which are lengthy and drastically increase the number of round-trips required for a HTTPS session over a HTTP one. Measure (using a tool such as Firebug) the page load times while the server is on the end of a simulated high-latency link. Tools exist to simulate a high latency link - for Linux there is "netem". Compare HTTP with HTTPS on the same setup. The latency can be mitigated to some extent by: * *Ensuring that your server is using HTTP keepalives - this allows the client to reuse SSL sessions, which avoids the need for another handshake *Reducing the number of requests to as few as possible - by combining resources where possible (e.g. .js include files, CSS) and encouraging client-side caching *Reduce the number of page loads, e.g. by loading data not required into the page (perhaps in a hidden HTML element) and then showing it using client-script. A: There isn't a single answer for this. Encryption will always consume more CPU. This can be offloaded to dedicated hardware in many cases, and the cost will vary by algorithm selected. 3des is more expensive than AES, for example. Some algorithms are more expensive for the encrypter than the decryptor. Some have the opposite cost. More expensive than the bulk crypto is handshake cost. New connections will consume much more CPU. This can be reduced with session resumption, at the cost of keeping old session secrets around until they expire. This means that small requests from a client that doesn't come back for more are the most expensive. For cross internet traffic you may not notice this cost in your data rate, because the bandwidth available is too low. But you will certainly notice it in CPU usage on a busy server. A: I can tell you (as a dialup user) that the same page over SSL is several times slower than via regular HTTP... A: In a number of cases the performance impact of SSL handshakes will be mitigated by the fact that the SSL session can be cached on both ends (desktop and server). On Windows machines for example the SSL session can be cached for up to 10 hours. See http://support.microsoft.com/kb/247658/EN-US . Some SSL accelerators will also have parameters allowing you to tune the time the session is cached. Another impact to consider is that static content served over HTTPS will not be cached by proxies, and this may reduce performance across multiple users accessing the site over the same proxy. This can be mitigated by the fact that static content will be cached at desktops as well, Internet Explorer versions 6 and 7 cache cacheable HTTPS static content unless instructed to do otherwise (Tools Menu/Internet Options/Advanced/Security/Do not save encrypted pages to disk). A: Here's a great article (a little bit old, but still great) on SSL handshake latency. Helped me identifying SSL as the main cause of slowness for clients who were using my app through slow Internet connections: http://www.semicomplete.com/blog/geekery/ssl-latency.html A: I made a small experiment and got 16% time difference for the same image from flickr (233 kb): http://farm8.staticflickr.com/7405/13368635263_d792fc1189_b.jpg https://farm8.staticflickr.com/7405/13368635263_d792fc1189_b.jpg Of course these numbers depends on many factors, such as computer performance, connection speed, server load, QoS on path (the particular network path taken from browser to the server) but it shows the general idea: HTTPS is slowser then HTTP, since it requesres more operations to complete (SSL handshaking and encoding/decoding data). A: December 2014 Update You can easily test the difference between HTTP and HTTPS performance in your own browser using the HTTP vs HTTPS Test website by AnthumChris: “This page measures its load time over unsecure HTTP and encrypted HTTPS connections. Both pages load 360 unique, non-cached images (2.04 MB total).” The results may surprise you. It's important to have an up to date knowledge about the HTTPS performance because the Let’s Encrypt Certificate Authority will start issuing free, automated, and open SSL certificates in Summer 2015, thanks to Mozilla, Akamai, Cisco, Electronic Frontier Foundation and IdenTrust. June 2015 Update Updates on Let’s Encrypt - Arriving September 2015: * *Let's Encrypt Launch Schedule (Jun 16, 2015) *Let's Encrypt Root and Intermediate Certificates (Jun 4, 2015) *Draft Let's Encrypt Subscriber Agreement (May 21, 2015) More info on Twitter: @letsencrypt For more info on HTTPS and SSL/TLS performance see: * *Is TLS Fast Yet? *High Performance Browser Networking, Chapter 4: Transport Layer Security *Overclocking SSL *Anatomy and Performance of SSL Processing For more info on the importance of using HTTPS see: * *Why HTTPS for Everything? (The HTTPS-Only Standard) *Let’s Encrypt (Internet Security Research Group) *HTTPS Everywhere (Electronic Frontier Foundation) To sum it up, let me quote Ilya Grigorik: "TLS has exactly one performance problem: it is not used widely enough. Everything else can be optimized." Thanks to Chris - author of the HTTP vs HTTPS Test benchmark - for his comments below. A: The current top answer is not fully correct. As others have pointed out here, https requires handshaking and therefore does more TCP/IP roundtrips. In a WAN environment typically then the latency becomes the limiting factor and not the increased CPU usage on the server. Just keep in mind that the latency from Europe to the US can be around 200 ms (torundtrip time). You can easily measure this (for the single user case) with HTTPWatch. A: There's a very simple answer to this: Profile the performance of your web server to see what the performance penalty is for your particular situation. There are several tools out there to compare the performance of an HTTP vs HTTPS server (JMeter and Visual Studio come to mind) and they are quite easy to use. No one can give you a meaningful answer without some information about the nature of your web site, hardware, software, and network configuration. As others have said, there will be some level of overhead due to encryption, but it is highly dependent on: * *Hardware *Server software *Ratio of dynamic vs static content *Client distance to server *Typical session length *Etc (my personal favorite) *Caching behavior of clients In my experience, servers that are heavy on dynamic content tend to be impacted less by HTTPS because the time spent encrypting (SSL-overhead) is insignificant compared to content generation time. Servers that are heavy on serving a fairly small set of static pages that can easily be cached in memory suffer from a much higher overhead (in one case, throughput was havled on an "intranet"). Edit: One point that has been brought up by several others is that SSL handshaking is the major cost of HTTPS. That is correct, which is why "typical session length" and "caching behavior of clients" are important. Many, very short sessions means that handshaking time will overwhelm any other performance factors. Longer sessions will mean the handshaking cost will be incurred at the start of the session, but subsequent requests will have relatively low overhead. Client caching can be done at several steps, anywhere from a large-scale proxy server down to the individual browser cache. Generally HTTPS content will not be cached in a shared cache (though a few proxy servers can exploit a man-in-the-middle type behavior to achieve this). Many browsers cache HTTPS content for the current session and often times across sessions. The impact the not-caching or less caching means clients will retrieve the same content more frequently. This results in more requests and bandwidth to service the same number of users. A: HTTPS requires an initial handshake which can be very slow. The actual amount of data transferred as part of the handshake isn't huge (under 5 kB typically), but for very small requests, this can be quite a bit of overhead. However, once the handshake is done, a very fast form of symmetric encryption is used, so the overhead there is minimal. Bottom line: making lots of short requests over HTTPS will be quite a bit slower than HTTP, but if you transfer a lot of data in a single request, the difference will be insignificant. However, keepalive is the default behaviour in HTTP/1.1, so you will do a single handshake and then lots of requests over the same connection. This makes a significant difference for HTTPS. You should probably profile your site (as others have suggested) to make sure, but I suspect that the performance difference will not be noticeable. A: Since I am investigating same problem for my project, I found these slides. Older but interesting: http://www.cs.nyu.edu/artg/research/comparison/comparison_slides/sld001.htm A: Is TLS fast yet? Yes. * *Watch: https://www.youtube.com/watch?v=0EB7zh_7UE4 *Read: https://istlsfastyet.com/ There are many projects out there that aim to blur the lines and to make HTTPS just as fast. Like SPDY and mod-spdy. A: There seems to be a nasty edge case here: Ajax over congested wifi. Ajax usually means that the KeepAlive has timed out after say 20 seconds. However, the wifi means that the (ideally fast) ajax connection has to make multiple round trips. Worse, the wifi often loses packets, and there are TCP retransmits. In this case, HTTPS performs really really badly! A: HTTP VS HTTPS PERFORMANCE COMPARISON I have always associated HTTPS with slower page load times when compared to plain old HTTP. As a web developer, web page performance is important to me and anything that will slow down the performance of my web pages is a no-no. In order to understand the performance implications involved, the diagram below gives you a basic idea of what happens under the hood when you make a request for a resource using HTTPS. As you can see from the diagram above, there are a few extra steps that need to take place when using HTTPS compared to using plain HTTP. When you make a request using HTTPS, a handshake needs to occur in order to verify the authenticity of the request. This handshake is an extra step when compared to an HTTP request and does unfortunately incur some overhead. In order to understand the performance implications and see for myself whether or not the performance impact would be significant, I used this site as a testing platform. I headed over to webpagetest.org and used the visual comparison tool to compare this site loading using HTTPS vs HTTP. As you can see from Here is Test video Result using HTTPS did have an impact on my page load times, however the difference is negligible and I only noticed a 300 millisecond difference. It's important to note that these times depend on many factors, such as computer performance, connection speed, server load, and distance from server. Your site may be different, and it is important to test your site thoroughly and check the performance impact involved in switching to HTTPS. A: In addition to everything mentioned so far, please keep in mind that some (all?) web browsers do not store cached content obtained over HTTPS on the local hard-drive for security reasons. This means that from the user's perspective pages with plenty of static content will appear to load slower after the browser is restarted, and from your server's perspective the volume of requests for static content over HTTPS will be higher than would have been over HTTP. A: To really understand how HTTPS will increase your latency, you have to understand how HTTPS connections are established. Here is a nice diagram. The key is that instead of the client getting the data after 2 "legs" (one round trip, you send a request, the server sends a response), the client won't get data until at least 4 legs (2 round trips). So, if it takes 100 ms for a packet to move between the client and the server, your first HTTPS request will take at least 500 ms. Of course, this can be mitigated by re-using the HTTPS connection (which browsers should do), but it does explain part of that initial stall when loading up an HTTPS web site. A: This is almost certainly going to be true given that SSL requires an extra step of encryption that simply isn't required by non-SLL HTTP. A: HTTPS has encryption/decryption overhead so it will always be slightly slower. SSL termination is very CPU intensive. If you have devices to offload SSL, the difference in latencies might be barely noticeable depending on the load your servers are under. A: There is a way to measure this. The tool from apache called jmeter will measure throughput. If you set up a large sampling of your service with jmeter, in a controlled environment, with and without SSL, you should get an accurate comparison of the relative cost. I would be interested in your results. A: The HTTPS indeed affects page speed... The quotes above reveal the foolishness of many people about site security and speed. HTTPS / SSL server handshaking creates an initial stall in making Internet connections. There’s a slow delay before anything starts to render on your visitor’s browser screen. This delay is measured in Time-to-First-Byte information. HTTPS handshake overhead appears in Time-to-First-Byte information (TTFB). Common TTFB ranges from under 100 milliseconds (best-case) to over 1.5 seconds (worst case). But, of course, with HTTPS it’s 500 milliseconds worse. Roundtrip, wireless 3G connections can be 500 milliseconds or more. The extra trips double delays to 1 second or more. This is a big, negative impact on mobile performance. Very bad news. My advice, if you're not exchanging sensitive data then you don't need SSL at all, but if you do like an ecommerce website then you can just enable HTTPS on certain pages where sensitive data is exchanged like Login and checkout. Source: Pagepipe A: A more important performance difference is that an HTTPS session is ketp open while the user is connected. An HTTP 'session' lasts only for a single item request. It you are running a site with a large number of concurrent users, expect to buy a lot of memory. A: Browsers can accept HTTP/1.1 protocol with either HTTP or HTTPS, yet browsers can only handle HTTP/2.0 protocol with HTTPS. The protocol differences from HTTP/1.1 to HTTP/2.0 make HTTP/2.0, on average, 4-5 times faster than HTTP/1.1. Also, of sites that implement HTTPS, most do so over the HTTP/2.0 protocol. Therefore, HTTPS is almost always going to be faster than HTTP simply due to the different protocol it generally uses. However, if HTTP over HTTP/1.1 is compared with HTTPS over HTTP/1.1, then HTTP is slightly faster, on average, than HTTPS. Here are some comparisons I ran using Chrome (Ver. 64): HTTPS over HTTP/1.1: * *0.47 seconds average page load time *0.05 seconds slower than HTTP over HTTP/1.1 *0.37 seconds slower than HTTPS over HTTP/2.0 HTTP over HTTP/1.1 * *0.42 seconds average page load time *0.05 seconds faster than HTTPS over HTTP/1.1 *0.32 seconds slower than HTTPS over HTTP/2.0 HTTPS over HTTP/2.0 * *0.10 seconds average load time *0.32 seconds faster than HTTP over HTTP/1.1 *0.37 seconds faster than HTTPS over HTTPS/1.1
{ "language": "en", "url": "https://stackoverflow.com/questions/149274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "386" }
Q: Restrict dependencies between Java packages What are the possibilities to enforce restrictions on the package dependencies in a Java build system? For example, the myapp.server.bl.Customer class should not be allowed to refer to the myapp.client.ui.customlayout package. I'm interested in either Ant-based or IDE-specific solutions. I'd like to get an error message in the build indicating that a (custom) package dependency rule has been violated and the build aborted. I also would like to maintain the dependencies in a list, preferably in a text file, outside of the Ant scripts or IDE project files. (I don't know Maven but I've read it here it has better support for module dependency management) A: I believe Checkstyle has a check for that. It's called Import Control A: You can configure Eclipse projects to specify Access Rules. Access rules can specify "Forbidden", "Discouraged", and "Accessible" levels all with wildcard rules. You can then configure violations of either Discouraged or Forbidden to be flagged as either warnings or errors during builds. Kind of an old article on the idea (details may be out of date): http://www.eclipsezone.com/eclipse/forums/t53736.html If you're using Eclipse (or OSGi) plugins, then the "public" parts of the plugin/module are explicitly defined and this is part of the model. A: ivy seems like a good solution for your problem (if you are using ant). Ivy is the offical dependency management component of Ant and thus integrates nicely with ant. It is capable of resolving dependencies, handle conflicts, create exclusions and so on. It uses a simple xml structure to describe the dependencies and is easier to use than Maven, because it only tries to address dependency resolution problems. From the Ivy homepage: Ivy is a tool for managing (recording, tracking, resolving and reporting) project dependencies. It is characterized by the following: * *flexibility and configurability - Ivy is essentially process agnostic and is not tied to any methodology or structure. Instead it provides the necessary flexibility and configurability to be adapted to a broad range of dependency management and build processes. *tight integration with Apache Ant - while available as a standalone tool, Ivy works particularly well with Apache Ant providing a number of powerful Ant tasks ranging from dependency resolution to dependency reporting and publication. A: For the IDE specific solutions, IntelliJ IDEA has a dependency analysis tool that allows one to define invalid dependencies as well. http://www.jetbrains.com/idea/webhelp2/dependency-validation-dialog.html The dependency violation will be shown both when compiling and live, while editing the dependent class (as error/warning stripes in the right side error bar). Even more automation can be obtained with JetBrains' TeamCity build server, that can run inspection builds and report the above configured checks. For another IDE independent solution, AspectJ can be used to declare invalid dependencies (and integrate the step in the build process, in order to obtain warning/error info for the issues). A: Eclipse has support for this via Build Path properties / jar properties. I think it may only work across jar / project boundaries. A: You can use multiple modules in IDEA or Maven or multiple projects in Eclipse and Gradle. The concept is the same in all cases. A trivial interpretation would be a module for myapp.server.bl and another for myapp.client.ui.customlayout with no compile time dependencies between either of them. Now any attempt to compile code or code-complete against the opposite module/project will fail as desired. To audit how extensive the problem already is, a useful starting point for IntelliJ IDEA is Analyzing Dependencies: http://www.jetbrains.com/idea/webhelp/analyzing-dependencies.html From that article you can see how to run and act on dependency analysis for your project. A: Maybe Classsycle can be used: http://classycle.sourceforge.net/ddf.html
{ "language": "en", "url": "https://stackoverflow.com/questions/149294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Prevent Text Wrap in DataGrid I have a problem with a data-bound DataGrid control, in that despite each column having its Wrap property set to false, the text still wraps. It seems to only do this on IE, and not FF. A: It appears that Microsoft is aware of this issue and they have provided a workaround... I don't know if this was addressed in IE8 B2... you might try it and see. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/149300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Background tasks on App Engine How can I run background tasks on App Engine? A: GAE is very useful tool to build scalable web applications. Few of the limitations pointed out by many are no support for background tasks, lack of periodic tasks and strict limit on how much time each HTTP request takes, if a request exceeds that time limit the operation is terminated, which makes running time consuming tasks impossible. How to run background task ? In GAE the code is executed only when there is a HTTP request. There is a strict time limit (i think 10secs) on how long the code can take. So if there are no requests then code is not executed. One of the suggested work around was use an external box to send requests continuously, so kind of creating a background task. But for this we need an external box and now we dependent on one more element. The other alternative was sending 302 redirect response so that client re-sends the request, this also makes us dependent on external element which is client. What if that external box is GAE itself ? Everyone who has used functional language which does not support looping construct in the language is aware of the alternative ie recursion is the replacement to loop. So what if we complete part of the computation and do a HTTP GET on the same url with very short time out say 1 second ? This creates a loop(recursion) on php code running on apache. <?php $i = 0; if(isset($_REQUEST["i"])){ $i= $_REQUEST["i"]; sleep(1); } $ch = curl_init("http://localhost".$_SERVER["PHP_SELF"]."?i=".($i+1)); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_TIMEOUT, 1); curl_exec($ch); print "hello world\n"; ?> Some how this does not work on GAE. So what if we do HTTP GET on some other url say url2 which does HTTP GET on the first url ? This seem to work in GAE. Code for this looks like this. class FirstUrl(webapp.RequestHandler): def get(self): self.response.out.write("ok") time.sleep(2) urlfetch.fetch("http://"+self.request.headers["HOST"]+'/url2') class SecondUrl(webapp.RequestHandler): def get(self): self.response.out.write("ok") time.sleep(2) urlfetch.fetch("http://"+self.request.headers["HOST"]+'/url1') application = webapp.WSGIApplication([('/url1', FirstUrl), ('/url2', SecondUrl)]) def main(): run_wsgi_app(application) if __name__ == "__main__": main() Since we found out a way to run background task, lets build abstractions for periodic task (timer) and a looping construct which spans across many HTTP requests (foreach). Timer Now building timer is straight forward. Basic idea is to have list of timers and the interval at which each should be called. Once we reach that interval call the callback function. We will use memcache to maintain the timer list. To find out when to call callback, we will store a key in memcache with interval as expiration time. We periodically (say 5secs) check if that key is present, if not present then call the callback and again set that key with interval. def timer(func, interval): timerlist = memcache.get('timer') if(None == timerlist): timerlist = [] timerlist.append({'func':func, 'interval':interval}) memcache.set('timer-'+func, '1', interval) memcache.set('timer', timerlist) def checktimers(): timerlist = memcache.get('timer') if(None == timerlist): return False for current in timerlist: if(None == memcache.get('timer-'+current['func'])): #reset interval memcache.set('timer-'+current['func'], '1', current['interval']) #invoke callback function try: eval(current['func']+'()') except: pass return True return False Foreach This is needed when we want to do long taking computation say doing some operation on 1000 database rows or fetch 1000 urls etc. Basic idea is to maintain list of callbacks and arguments in memcache and each time invoke callback with the argument. def foreach(func, args): looplist = memcache.get('foreach') if(None == looplist): looplist = [] looplist.append({'func':func, 'args':args}) memcache.set('foreach', looplist) def checkloops(): looplist = memcache.get('foreach') if(None == looplist): return False if((len(looplist) > 0) and (len(looplist[0]['args']) > 0)): arg = looplist[0]['args'].pop(0) func = looplist[0]['func'] if(len(looplist[0]['args']) == 0): looplist.pop(0) if((len(looplist) > 0) and (len(looplist[0]['args']) > 0)): memcache.set('foreach', looplist) else: memcache.delete('foreach') try: eval(func+'('+repr(arg)+')') except: pass return True else: return False # instead of # foreach index in range(0, 1000): # someoperaton(index) # we will say # foreach('someoperaton', range(0, 1000)) Now building a program which fetches list of urls every one hour is straight forward. Here is the code. def getone(url): try: result = urlfetch.fetch(url) if(result.status_code == 200): memcache.set(url, '1', 60*60) #process result.content except : pass def getallurl(): #list of urls to be fetched urllist = ['http://www.google.com/', 'http://www.cnn.com/', 'http://www.yahoo.com', 'http://news.google.com'] fetchlist = [] for url in urllist: if (memcache.get(url) is None): fetchlist.append(url) #this is equivalent to #for url in fetchlist: getone(url) if(len(fetchlist) > 0): foreach('getone', fetchlist) #register the timer callback timer('getallurl', 3*60) complete code is here http://groups.google.com/group/httpmr-discuss/t/1648611a54c01aa I have been running this code on appengine for few days without much problem. Warning: We make heavy use of urlfetch. The limit on no of urlfetch per day is 160000. So be careful not to reach that limit. A: You can find more about cron jobs in Python App Engine here. A: Up and coming version of runtime will have some kind of periodic execution engine a'la cron. See this message on AppEngine group. So, all the SDK pieces appear to work, but my testing indicates this isn't running on the production servers yet-- I set up an "every 1 minutes" cron that logs when it runs, and it hasn't been called yet Hard to say when this will be available, though... A: You may use the Task Queue Python API. A: Using the Deferred Python Library is the easiest way of doing background task on Appengine using Python which is built on top of TaskQueue API. from google.appengine.ext import deferred def do_something_expensive(a, b, c=None): logging.info("Doing something expensive!") # Do your work here # Somewhere else deferred.defer(do_something_expensive, "Hello, world!", 42, c=True) A: If you want to run background periodic tasks, see this question (AppEngine cron) If your tasks are not periodic, see Task Queue Python API or Task Queue Java API A: There is a cron facility built into app engine. Please refer to: https://developers.google.com/appengine/docs/python/config/cron?hl=en A: Use the Task Queue - http://code.google.com/appengine/docs/java/taskqueue/overview.html
{ "language": "en", "url": "https://stackoverflow.com/questions/149307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: ASP.NET GridView postback not setting posted controls' values When adding an EditItemTemplate of some complexity (mulitple fields in one template), and then parsing the controls from the RowUpdating event, the controls that were manually entered by the user have no values. My guess is there is something going on with when the data is bound, but I've had instances where simply adding and attribute to a control in codebehind started the behavior and removing that code made the code work. As a work-around, I can Request(controlname.UniqueId) to get it's value, but that is rather a hack. Edit When I access the value like so TextBox txtValue = gvwSettings.SelectedRow.FindControl("txtValue") as TextBox; the text box is found, but the .Text is not the user input. A: Did you turn off ViewState? Did you add control programmatically in the template? If so, did you create them at the correct stage? A: You should be able to use the GridViewUpdateEventArgs to retrieve the inputted value, for example: TextBox txtValue = gvwSettings.SelectedRow.FindControl("txtValue") as TextBox; I have used that syntax before and it works like a charm. A: Moved post-back data-bind to Page_Init
{ "language": "en", "url": "https://stackoverflow.com/questions/149311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Virtualized SQL Server: Why not? The IT department where I work is trying to move to 100% virtualized servers, with all the data stored on a SAN. They haven't done it yet, but the plan eventually calls for moving the existing physical SQL Server machines to virtual servers as well. A few months ago I attended the Heroes Happen Here launch event, and in one of the SQL Server sessions the speaker mentioned in passing that this is not a good idea for production systems. So I'm looking for a few things: * *What are the specific reasons why this is or is not a good idea? I need references, or don't bother responding. I could come up with a vague "I/O bound" response on my own via google. *The HHH speaker recollection alone probably won't convince our IT department to change their minds. Can anyone point me directly to something more authoritative? And by "directly", I mean something more specific than just a vague Books OnLine comment. Please narrow it down a little. A: SAN - of course, and clustering, but regarding Virtualization - you will take a Performance Hit (may or may not be worth it to you): http://blogs.technet.com/andrew/archive/2008/05/07/virtualized-sql-server.aspx http://sswug.org has had some notes about it in their daily newsletter lately A: I wanted to add this series of articles by Brent Ozar: * *Why Your Sysadmin Wants to Virtualize Your Servers *Why Would You Virtualize SQL Server? *Reasons Why You Shouldn't Virtualize SQL Server It's not exactly authoritative in the sense I was hoping for (coming from the team that builds the server, or an official manual of some kind), but Brent Ozar is pretty well respected and I think he does a great job covering all the issues here. A: I can say this from personal experience because I am dealing with this very problem as we speak. The place I am currently working as a contractor has this type of environment for their SQL Server development systems. I am trying to develop a fairly modest B.I. system on this environment and really struggling with the performance issues. TLB misses and emulated I/O are very slow on a naive virtual machine. If your O/S has paravirtualisation support (which is still not a mature technology on Windows) you use paravirtualised I/O (essentially a device driver that hooks into an API in the VM). Recent versions of the Opteron have support for nested page tables, which removes the need to emulate the MMU in software (which is really slow). Thus, applications that run over large data sets and do lots of I/O like (say) ETL processes trip over the achilles heel of virtualisation. If you have anything like a data warehouse system that might be hard on memory or Disk I/O you should consider something else. For a simple transactional application they are probably O.K. Put in perspective the systems I am using are running on blades (an IBM server) on a SAN with 4x 2gbit F/C links. This is a mid-range SAN. The VM has 4GB of RAM IIRC and now two virtual CPUs. At its best (when the SAN is quiet) this is still only half of the speed of my XW9300, which has 5 SCSI disks (system, tempdb, logs, data, data) on 1 U320 bus and 4GB of RAM. Your mileage may vary, but I'd recommend going with workstation systems like the one I described for developing anything I/O heavy in preference to virtual servers on a SAN. Unless your resource usage requirements are beyond this sort of kit (in which case they are well beyond a virtual server anyway) this is a much better solution. The hardware is not that expensive - certainly much cheaper than a SAN, blade chassis and VMWare licencing. SQL Server developer edition comes with V.S. Pro and above. This also has the benefit that your development team is forced to deal with deployment right from the word go - you have to come up with an architecture that's easy to 'one-click' deploy. This is not as hard as it sounds. Redgate SQL Compare Pro is your friend here. Your developers also get a basic working knowledge of database administration. A quick trip onto HP's website got me a list price of around $4,600 for an XW8600 (their current xeon-based model) with a quad-core xeon chip, 4GB of RAM and 1x146 and 4x73GB 15k SAS hard disks. Street price will probably be somewhat less. Compare this to the price for a SAN, blade chassis and VMware licensing and the cost of backup for that setup. For backup you can provide a network share with backup where people can drop compressed DB backup files as necessary. EDIT: This whitepaper on AMD's web-site discusses some benchmarks on a VM. From the benchmarks in the back, heavy I/O and MMU workload really clobber VM performance. Their benchmark (to be taken with a grain of salt as it is a vendor supplied statistic) suggests a 3.5x speed penalty on an OLTP benchmark. While this is vendor supplied one should bear in mind: * *It benchmarks naive virtualisation and compares it to a para-virtualised solution, not bare-metal performance. *An OLTP benchmark will have a more random-access I/O workload, and will spend more time waiting for disk seeks. A more sequential disk access pattern (characteristic of data warehouse queries) will have a higher penalty, and a memory-heavy operation (SSAS, for example, is a biblical memory hog) that has a large number of TLB misses will also incur additional penalties. This means that the slow-downs on this type of processing would probably be more pronounced than the OLTP benchmark penalty cited in the whitepaper. What we have seen here is that TLB misses and I/O are very expensive on a VM. A good architecture with paravirtualised drivers and hardware support in the MMU will mitigate some or all of this. However, I believe that Windows Server 2003 does not support paravirtualisation at all, and I'm not sure what level of support is delivered in Windows 2008 server. It has certainly been my experience that a VM will radically slow down a server when working on an ETL process and SSAS cube builds compared to relatively modest spec bare-metal hardware. A: We are running a payroll system for 900+ people on VMWare with no problems. This has been in production for 10 months. It's a medium sized load as far as DB goes, and we pre-allocated drive space in VM to prevent IO issues. You have to defrag both the VM Host and the VM slice on a regular basis in order to maintain acceptable performance. A: Here's some VMWARE testing on it.. http://www.vmware.com/files/pdf/SQLServerWorkloads.pdf Granted, they do not compare it to physical machines. But, you could probably do similar testing with the tools they used for your environment. We currently run SQL Server 2005 in a VMWARE environment. BUT, it is a very lightly loaded database and it is great. Runs with no problems. As most have pointed out, it will depend on your database load. Maybe you can convince the IT Department to do some good testing before blindly implementing. A: No, I can't point to any specific tests or anything like that, but I can say from experience that putting your production database server on a virtual machine is a bad idea, especially if it has a large load. It's fine for development. Possibly even testing (on the theory that if it runs fine under load on virtual box, it's going to run fine on prodcution) but not in production. It's common sense really. Do you want your hardware running two operating systems and your sql server or one operating system and sql server? Edit: My experience biased my response. I have worked with large databases under heavy constant load. If you have a smaller database under light load, virtualization may work fine for you. A: There is some information concerning this in Conor Cunningham's blog article Database Virtualization - The Dirty Little Secret Nobody is Talking About.... To quote: Within the server itself, there is suprisingly little knowledge of a lot of things in this area that are important to performance. SQL Server's core engine assumes things like: * *all CPUs are equally powerful *all CPUs process instructions at about the same rate. *a flush to disk should probably happen in a bounded amount of time. And the post goes on elaborating these issues somewhat further also. I think a good read considering the scarcity of available information considering this issue in general. A: Note there are some specialty virtualization products out there that are made for databases that might be worth looking into instead of a general product like VMWare. Our company (over 200 SQL servers) is currently in the process of deploying HP Polyserve on some of our servers: HP PolyServe Software for Microsoft SQL Server enables multiple Microsoft SQL Server instances to be consolidated onto substantially fewer servers and centralized SAN storage. HP PolyServe's unique "shared data" architecture delivers enterprise class availability and virtualization-like flexibility in a utility platform. Our primary reason for deploying it is to make hardware replacement easier: add the new box to the "matrix", shuffle around where each SQL instance resides (seamlessly), then remove the old box. Transparent to the application teams, because the SQL instance names don't change. A: Old Question with Old Answers The answers in this thread are years old. Most of the negative points in this entire thread are technically still correct but much less relevant. The overhead cost of virtualization and SAN’s is much less a factor now than it used to be. A correctly configured Virtualization host, guest, network, and SAN can provide good performance with the benefits of virtualization and operational flexibility including good recovery scenarios that are only provided by being virtual. However, in the real world it only takes one minor configuration detail to bring the whole thing to its knees. In practice your biggest challenge with virtual SQL servers is convincing and working with the people responsible for the virtualization to get it set up just right. Irony, in 100 percent of the cases where we took production off of the virtualization and moved it back to dedicated hardware performance went through the roof on the dedicated hardware. In all of these cases it was not the virtualization but the way it was setup. By going back to dedicated hardware we actually proved that the virtualization would have been a much better use of resources by factors of 5 or more. Modern software is usually designed to scale out across nodes so virtualization works to your advantage on that front as well. A: The biggest concern to me when virtualising software is normally licensing. Here's an article on it for MS SQL. Not sure about your situation so can't pick out any salient points. http://www.microsoft.com/sql/howtobuy/virtualization.mspx A: SQL Server is supported in a virtual environment. In fact I would recommend it seeing that one of the licensing options is per socket. This means you can put as many SQL Server instances in a virtualized (e.g. Windows 2008 Server Datacenter) system as you like and pay only per processor socket the machine has. It's better than that because DataCenter is licensed per socket with unlimited Virtual machine licenses as well. I'd recommend clustering your Hyper-V on two machines however so that if one fails the other can pick up the slack. A: I would think that the possibility of something bad happening to the data would be too great. As a dead simple example, let's say you ran a SQL Server box in Virtual Server 2005 R2 and undo disks were turned on (so, the main "disk" file stays the same and all changes are made to a separate file which can be purged or merged later). Then something happens (usually, you run into the 128GB limit or whatever the size is) and some middle of the night clueless admin has to reboot and figures out he can't do so until he removes the undo disks. You're screwed - even if he keeps the undo disk files for later analysis the possibilities of merging the data together is pretty slim. So echoing the other posts in this thread - for development it's great but for production it's not a good idea. Your code can be rebuilt and redeployed (that's another thing, VM's for source control aren't a good idea either) but your live production data is way more important. A: Security issues that can be introduced when dealing with Vitalization should also be considered. Virtualization Security is a good article by PandaLabs that covers some of the concerns. A: You are looking at this from the wrong angle. First, you are not going to find White Papers from Vendors why you should "not" virtualize or why you should Virtualize. Every environment is different and you need to do what works in your Environment. With that said, there are some servers that are perfect for virtualization and there are some that should not be virtualized. For example, if your SQL Server/s are doing millions and millions of transactions per second, like if your server was located at the NYSE or the NASDAQ and millions and millions of dollars depend on it, you probably should not virtualize it. Make sure you understand the ramifications of virtualizing an SQL server. I've seen where people virtualize SQL over and over just because Virtualization is cool. Then complain later on when the VM server does not perform as expected. What you need to do is set a benchmark, fully test the solution you want to deploy and show what it can and can't do so you don't run into any surprises. Virtualization is great, it is good for the envronment and saves through consolidation, but you need to show why your supervisors why you should not virtualize your SQL Servers and only you can do this.
{ "language": "en", "url": "https://stackoverflow.com/questions/149318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: Setting per-file flags with automake Is there a way set flags on a per-file basis with automake? In particular, if I have a c++ project and want to compile with -WAll all the files except one for which I want to disable a particular warning, what could I do? I tried something like: CXXFLAGS = -WAll ... bin_PROGRAMS = test test_SOURCES = main.cpp utility.cpp utility_o_CXXFLAGS = $(CXXFLAGS) -Wno-unused-value but it didn't work. EDITED: removed reference to automake manual, which was actually misleading (thanks to Douglas Leeder). A: Automake only supports per-target flags, while you want per-object flags. One way around is to create a small library that contains your object: CXXFLAGS = -Wall ... bin_PROGRAMS = test test_SOURCES = main.cpp test_LDADD = libutility.a noinst_LIBRARIES = libutility.a libutility_a_SOURCES = utility.cpp libutility_a_CXXFLAGS = $(CXXFLAGS) -Wno-unused-value A: You've got confused - that section is referring to options to automake itself. It's a way of setting the automake command-line options: -W CATEGORY --warnings=category Output warnings falling in category. category can be one of: gnu warnings related to the GNU Coding Standards (see Top). obsolete obsolete features or constructions override user redefinitions of Automake rules or variables portability portability issues (e.g., use of make features that are known to be not portable) syntax weird syntax, unused variables, typos unsupported unsupported or incomplete features all all the warnings none turn off all the warnings error treat warnings as errors A category can be turned off by prefixing its name with ‘no-’. For instance, -Wno-syntax will hide the warnings about unused variables. The categories output by default are ‘syntax’ and ‘unsupported’. Additionally, ‘gnu’ and ‘portability’ are enabled in --gnu and --gnits strictness. The environment variable WARNINGS can contain a comma separated list of categories to enable. It will be taken into account before the command-line switches, this way -Wnone will also ignore any warning category enabled by WARNINGS. This variable is also used by other tools like autoconf; unknown categories are ignored for this reason. The per-file listed in section 17 refers to per-Makefile not source file. I'm not aware of any per-source file flag setting, but you can set the option for each result binary with: binaryname_CXXFLAGS A: You can't do this with automake... but can do with make =) Add following line to your Makefile.am: utility.$(OBJEXT) : CXXFLAGS += -Wno-unused-value See GNU Make documentation : Target-specific Variable Values for details.
{ "language": "en", "url": "https://stackoverflow.com/questions/149324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Practical Uses for the "Curiously Recurring Template Pattern" What are some practical uses for the "Curiously Recurring Template Pattern"? The "counted class" example commonly shown just isn't a convincing example to me. A: The CRTP gets a lot less curious if you consider that the subclass type that is passed to the superclass is only needed at time of method expansion. So then all types are defined. You just need the pattern to import the symbolic subclass type into the superclass, but it is just a forward declaration - as all formal template param types are by definition - as far as the superclass is concerned. We use in a somewhat modified form, passing the subclass in a traits type structure to the superclass to make it possible for the superclass to return objects of the derived type. The application is a library for geometric calculus ( points, vectors, lines, boxes ) where all the generic functionality is implemented in the superclass, and the subclass just defines a specific type : CFltPoint inherits from TGenPoint. Also CFltPoint existed before TGenPoint, so subclassing was a natural way of refactoring this. A: Simulated dynamic binding. Avoiding the cost of virtual function calls while retaining some of the hierarchical benefits is an enormous win for the subsystems where it can be done in the project I am currently working on. A: It's also especially useful for mixins (by which I mean classes you inherit from to provide functionality) which themselves need to know what type they are operating on (and hence need to be templates). In Effective C++, Scott Meyers provides as an example a class template NewHandlerSupport<T>. This contains a static method to override the new handler for a particular class (in the same way that std::set_new_handler does for the default operator new), and an operator new which uses the handler. In order to provide a per-type handler, the parent class needs to know what type it is acting on, so it needs to be a class template. The template parameter is the child class. You couldn't really do this without CRTP, since you need the NewHandlerSupport template to be instantiated separately, with a separate static data member to store the current new_handler, per class that uses it. Obviously the whole example is extremely non-thread-safe, but it illustrates the point. Meyers suggests that CRTP might be thought of as "Do It For Me". I'd say this is generally the case for any mixin, and CRTP applies in the case where you need a mixin template rather than just a mixin class. A: Generally it is used for polymorphic-like patterns where you do not need to be able to choose the derived class at runtime, only at compile time. This can save the overhead of the virtual function call at runtime. A: For a real-world library use of CRTP, look at ATL and WTL (wtl.sf.net). It is used extensively there for compile-time polymorphism.
{ "language": "en", "url": "https://stackoverflow.com/questions/149336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "47" }
Q: HTTP Authentication in .NET Is it possible to create a .NET equivalent to the following code? <?php if (!isset($_SERVER['PHP_AUTH_USER'])) { header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized'); echo 'Text to send if user hits Cancel button'; exit; } else { echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>"; echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>"; } ?> I would like to be able to define a static user/password in the web.config as well. This is very easy to do in PHP, haven't seen anything explaining how to do this in MSDN. All I want is this: A: The easiest way to achieve the same as with the PHP code would be to directly send the same headers via Reponse.AppendHeader(). Still I would suggest you to read an ASP.NET Forms Authentication Tutorial. A: You need to implement basic authentication in ASP.NET not forms authentication as the above responders said. A good example can be found here . A: Yes, you can add to web.config and use forms authentication. I dont know php, so i cant help witjh the rest of your question http://msdn.microsoft.com/en-us/library/aa720092(VS.71).aspx\ A: Yes, you can specify credentials in the web.config. ASP.NET also has a built-in membership system and has controls like Login to work with it - although this is different from setting static credentials in the web.config. I think the easiest way to do what you're talking about is to protect the directory in IIS. A: I typically do my own authentication is asp.net against my own username and passwords in a database. For the way I do it, I create a username and password dialog on a page, and have a login button. During postback i do something like: if(SecurityHelper.LoginUser(txtUsername.Text, txtPassword.Text)) { FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true); } Do with that in mind all you need to do is the same, check the username and password against whatveer you want, you can even hardcode if you want buy i wouldnt recommend it. \if its valid use the formsauthentication class's static methods. A: I am afraid I cant help you. I dont know how to get a dialog like that besides using a different security setup in IIS, such as integrated security (windows security). If that is all you want then you need to go into IIS and disable anonymous access, enable another auth type, such as integrated, basic,, and in your code you can verify they are logged in by checking: System.Security.Principal.WindowsIdentity.GetCurrent().IsAuthenticated Although IIS takes care of verification in this case. Other than that i cant help you out. In case you need it, a link to windows auth in asp.net: http://msdn.microsoft.com/en-us/library/ms998358.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/149337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: SQL Server 2000 and System.Transactions.TransactionScope() Is it possible to create LIGHTWEIGHT transactions using TransactionScope() with SQL2000? Or if not, is there a workaround using CommitableTransaction and/or something similar? So the answer is, basically, "If you want local-to-1-server-transactions on SQL2000, don't use TransactionScope()". A: Lightweight transactions require support for "promotable" transactions. SQL Server 2000 simply does not have support for this. Promotable transactions were added in SQL Server 2005. Florin Lazar posted an adapter that can be used in specific scenarios. You'll have to judge for yourself if this adapter is appropriate for your environment.
{ "language": "en", "url": "https://stackoverflow.com/questions/149339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: New Date/Time data types in SQL 2008 I am trying to use the new DATETIMEOFFSET data type in SQL 2008 but I can't figure out how to get the DATETIMEOFFSET '2008-09-27 21:28:17.2930000 -07:00' to show as '2008-09-27 14:28:17.2930000' (basically applying the offset to show the local time). Does anyone know how to do this? A: The following MSDN articles appear to cover this: * *http://msdn.microsoft.com/en-us/library/bb384267.aspx *http://msdn.microsoft.com/en-us/library/bb630289.aspx *http://msdn.microsoft.com/en-us/library/ms187928.aspx It appears that you need to cast the datetimeoffset into another format, such as datetime, but the sample code on the 'CAST and CONVERT' page is not clear on that.
{ "language": "en", "url": "https://stackoverflow.com/questions/149346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Compact Framework DirectShow Based Camera with Preview I've an example (wimobot.org) of a working directshow camera (not based on CameraDialog), but this example doesn't includes preview. I don't know how to implement the direct show filter for the preview, any sample code in C# or Visual Basic .Net? Thanks in advance A: Sorry for the reply to an old question, but I've been looking for this for a while myself and have just come accross a DirectShow .Net CF Wrapper here: http://alexmogurenko.com/blog/directshownetcf/
{ "language": "en", "url": "https://stackoverflow.com/questions/149363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you add a superscript character into a Powerbuilder textbox? Is there any way to do this in the Powerbuilder properties window for a datawindow's textbox? A: That kind of depends on how you define "textbox", but in general the only way to mix normal and superscript text is with a richtext control. In PB 11.5, you can even use richtext as a column style. Good luck, Terry. A: Yes. For the text control, you must select a font that has superscript characters (Arial does). * *Go into the Windows Character Map (usually in the start menu under Accessories->System Tools) and select your font. *Then go to the superscript character that you want to place in your text control. Click it and then click the Select button to place it down in the character map text box. *Then click the Copy button. *Now you can return to PowerBuilder and paste this value into the properties window text area. As long as the same font is selected for the DataWindow control as was selected in the character map it should show as your superscript character. This same techinque can be done to include any of the Wingding type characters as well. A: We ended up using two separate text fields. It's a butt-ugly solution, but it works. The superscript field has a smaller font and is nudged a little higher up. I think newer PB versions support superscripts. Thanks for the help. Glenn A: If you go to the character map - when you select your character it will show the keys to enter this character on the bottom right of the window. Example : in Arial font - the ® (registered) mark is Alt + 0174 To enter these, turn your numlock on, hold the alt key down, and type 0 1 7 & 4 then let up on the alt key. You have to use the number keys on the number pad to do this the ones on the top of the keyboard dont work. You can then enter your characters directly or do something like this : ls_key = '®' A: Actually I stumbled across a simpler solution. I copied and pasted a portion of the text from a pdf into the text property of a datawindow text contol. The superscript character simply pasted in. So I'm guessing that Dougman's solution would work too. Example: "™Trademark used under..." Note: I'm using PB 9.0.1 Thanks for all the help, Glenn
{ "language": "en", "url": "https://stackoverflow.com/questions/149375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to generate Code39 barcodes in vb.net I want to create Code39 encoded barcodes from my application. I know I can use a font for this, but I'd prefer not to as I'd have to register the font on the server and I've had some pretty bad experiences with that. An example of what I've produced after asking this question is in the answers A: If you choose Code39, you could probably code up from this code I wrote http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/03/24/code-39-barcode-generation.aspx I wrote it to use our toolkit for image generation, but you could rewrite it to use .NET Image/Graphics pretty easily. A: I don't know about libraries -- all of the barcode work I've done has been with barcode fonts. Check out free 3-of-9 if you're using the "3 of 9" format. Caveats of 3-of-9: make sure all text is in upper case start and end each barcode with an asterisk A: Here's an open source barcode rendering library for .NET languages: http://www.codeplex.com/BarcodeRender It can render some usual encodings. The license looks benign, and it seems to be usable in both open source and commercial apps (however, IANAL, you might want to check its license yourself.) Here's another one, also open source, using the Apache 2.0 license: http://sourceforge.net/projects/onecode/ Generally, when you know from the start you're looking for open source components, it's better to bypass Google and directly start searching on SourceForge (it's got a wonderful filtering system for search results, you can filter by language, which is probably of interest to you) or on Microsoft's CodePlex (where choice is usually more limited, but there you go.) A: This is my current codebehind, with lots of comments: Option Explicit On Option Strict On Imports System.Drawing Imports System.Drawing.Imaging Imports System.Drawing.Bitmap Imports System.Drawing.Graphics Imports System.IO Partial Public Class Barcode Inherits System.Web.UI.Page 'Sebastiaan Janssen - 20081001 - TINT-30584 'Most of the code is based on this example: 'http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/04/25/writing-code-39-barcodes-with-javascript.aspx-generation.aspx 'With a bit of this thrown in: 'http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/03/24/code-39-barcode Private _encoding As Hashtable = New Hashtable Private Const _wideBarWidth As Short = 8 Private Const _narrowBarWidth As Short = 2 Private Const _barHeight As Short = 100 Sub BarcodeCode39() _encoding.Add("*", "bWbwBwBwb") _encoding.Add("-", "bWbwbwBwB") _encoding.Add("$", "bWbWbWbwb") _encoding.Add("%", "bwbWbWbWb") _encoding.Add(" ", "bWBwbwBwb") _encoding.Add(".", "BWbwbwBwb") _encoding.Add("/", "bWbWbwbWb") _encoding.Add("+", "bWbwbWbWb") _encoding.Add("0", "bwbWBwBwb") _encoding.Add("1", "BwbWbwbwB") _encoding.Add("2", "bwBWbwbwB") _encoding.Add("3", "BwBWbwbwb") _encoding.Add("4", "bwbWBwbwB") _encoding.Add("5", "BwbWBwbwb") _encoding.Add("6", "bwBWBwbwb") _encoding.Add("7", "bwbWbwBwB") _encoding.Add("8", "BwbWbwBwb") _encoding.Add("9", "bwBWbwBwb") _encoding.Add("A", "BwbwbWbwB") _encoding.Add("B", "bwBwbWbwB") _encoding.Add("C", "BwBwbWbwb") _encoding.Add("D", "bwbwBWbwB") _encoding.Add("E", "BwbwBWbwb") _encoding.Add("F", "bwBwBWbwb") _encoding.Add("G", "bwbwbWBwB") _encoding.Add("H", "BwbwbWBwb") _encoding.Add("I", "bwBwbWBwb") _encoding.Add("J", "bwbwBWBwb") _encoding.Add("K", "BwbwbwbWB") _encoding.Add("L", "bwBwbwbWB") _encoding.Add("M", "BwBwbwbWb") _encoding.Add("N", "bwbwBwbWB") _encoding.Add("O", "BwbwBwbWb") _encoding.Add("P", "bwBwBwbWb") _encoding.Add("Q", "bwbwbwBWB") _encoding.Add("R", "BwbwbwBWb") _encoding.Add("S", "bwBwbwBWb") _encoding.Add("T", "bwbwBwBWb") _encoding.Add("U", "BWbwbwbwB") _encoding.Add("V", "bWBwbwbwB") _encoding.Add("W", "BWBwbwbwb") _encoding.Add("X", "bWbwBwbwB") _encoding.Add("Y", "BWbwBwbwb") _encoding.Add("Z", "bWBwBwbwb") End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load BarcodeCode39() Dim barcode As String = String.Empty If Not IsNothing(Request("barcode")) AndAlso Not (Request("barcode").Length = 0) Then barcode = Request("barcode") Response.ContentType = "image/png" Response.AddHeader("Content-Disposition", String.Format("attachment; filename=barcode_{0}.png", barcode)) 'TODO: Depending on the length of the string, determine how wide the image will be GenerateBarcodeImage(250, 140, barcode).WriteTo(Response.OutputStream) End If End Sub Protected Function getBCSymbolColor(ByVal symbol As String) As System.Drawing.Brush getBCSymbolColor = Brushes.Black If symbol = "W" Or symbol = "w" Then getBCSymbolColor = Brushes.White End If End Function Protected Function getBCSymbolWidth(ByVal symbol As String) As Short getBCSymbolWidth = _narrowBarWidth If symbol = "B" Or symbol = "W" Then getBCSymbolWidth = _wideBarWidth End If End Function Protected Overridable Function GenerateBarcodeImage(ByVal imageWidth As Short, ByVal imageHeight As Short, ByVal Code As String) As MemoryStream 'create a new bitmap Dim b As New Bitmap(imageWidth, imageHeight, Imaging.PixelFormat.Format32bppArgb) 'create a canvas to paint on Dim canvas As New Rectangle(0, 0, imageWidth, imageHeight) 'draw a white background Dim g As Graphics = Graphics.FromImage(b) g.FillRectangle(Brushes.White, 0, 0, imageWidth, imageHeight) 'write the unaltered code at the bottom 'TODO: truely center this text Dim textBrush As New SolidBrush(Color.Black) g.DrawString(Code, New Font("Courier New", 12), textBrush, 100, 110) 'Code has to be surrounded by asterisks to make it a valid Code39 barcode Dim UseCode As String = String.Format("{0}{1}{0}", "*", Code) 'Start drawing at 10, 10 Dim XPosition As Short = 10 Dim YPosition As Short = 10 Dim invalidCharacter As Boolean = False Dim CurrentSymbol As String = String.Empty For j As Short = 0 To CShort(UseCode.Length - 1) CurrentSymbol = UseCode.Substring(j, 1) 'check if symbol can be used If Not IsNothing(_encoding(CurrentSymbol)) Then Dim EncodedSymbol As String = _encoding(CurrentSymbol).ToString For i As Short = 0 To CShort(EncodedSymbol.Length - 1) Dim CurrentCode As String = EncodedSymbol.Substring(i, 1) g.FillRectangle(getBCSymbolColor(CurrentCode), XPosition, YPosition, getBCSymbolWidth(CurrentCode), _barHeight) XPosition = XPosition + getBCSymbolWidth(CurrentCode) Next 'After each written full symbol we need a whitespace (narrow width) g.FillRectangle(getBCSymbolColor("w"), XPosition, YPosition, getBCSymbolWidth("w"), _barHeight) XPosition = XPosition + getBCSymbolWidth("w") Else invalidCharacter = True End If Next 'errorhandling when an invalidcharacter is found If invalidCharacter Then g.FillRectangle(Brushes.White, 0, 0, imageWidth, imageHeight) g.DrawString("Invalid characters found,", New Font("Courier New", 8), textBrush, 0, 0) g.DrawString("no barcode generated", New Font("Courier New", 8), textBrush, 0, 10) g.DrawString("Input was: ", New Font("Courier New", 8), textBrush, 0, 30) g.DrawString(Code, New Font("Courier New", 8), textBrush, 0, 40) End If 'write the image into a memorystream Dim ms As New MemoryStream Dim encodingParams As New EncoderParameters encodingParams.Param(0) = New EncoderParameter(Encoder.Quality, 100) Dim encodingInfo As ImageCodecInfo = FindCodecInfo("PNG") b.Save(ms, encodingInfo, encodingParams) 'dispose of the object we won't need any more g.Dispose() b.Dispose() Return ms End Function Protected Overridable Function FindCodecInfo(ByVal codec As String) As ImageCodecInfo Dim encoders As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders For Each e As ImageCodecInfo In encoders If e.FormatDescription.Equals(codec) Then Return e Next Return Nothing End Function End Class A: are you printing to a standard printer or an actual barcode printer (zebra or datamax)? both zebra and datamax have their own scripting languages - actually more like markup languages. ZPL and DPL respectively. I like zebra's more and their documentation is much cleaner. If you don't have a legitimate barcode printer, I suggest purchasing one and do the following.... (it'll be much cleaner than trying to work out building little image blocks and painting them to simulate a barcode font) both allow you great flexibility and you can let the printer handle creating the actual barcode image. have your program send a customized ZPL/DPL script that includes the values that you want to have printed as barcodes to the printer via ftp. basically, you just "put" a text file that contains the script to the IP of the printer and the printer takes care of the font. A: The iTextSharp library, while ostensibly for creating creating PDFs, also has a barcode generation library that includes Code39. Once you add a reference to the DLL, it's as simple as: Barcode39 code39 = new Barcode39(); code39.Code = "Whatever You're Encoding"; Oops, that's C#, but you get the idea. Once created, you can render an image in just about any image format and use it as you wish. A: If you render client side then the font can reside on a workstation. This way you can use 3-of-9. I've used 3-of-9 in several projects and the simplest solution for you. A: Here is an example of how to generate Code39 barcodes in vb.net. I tested It now and it works. Public Class code39 Private bitsCode As ArrayList Public Sub New() bitsCode = New ArrayList bitsCode.Add(New String(3) {"0001101", "0100111", "1110010", "000000"}) bitsCode.Add(New String(3) {"0011001", "0110011", "1100110", "001011"}) bitsCode.Add(New String(3) {"0010011", "0011011", "1101100", "001101"}) bitsCode.Add(New String(3) {"0111101", "0100001", "1000010", "001110"}) bitsCode.Add(New String(3) {"0100011", "0011101", "1011100", "010011"}) bitsCode.Add(New String(3) {"0110001", "0111001", "1001110", "011001"}) bitsCode.Add(New String(3) {"0101111", "0000101", "1010000", "011100"}) bitsCode.Add(New String(3) {"0111011", "0010001", "1000100", "010101"}) bitsCode.Add(New String(3) {"0110111", "0001001", "1001000", "010110"}) bitsCode.Add(New String(3) {"0001011", "0010111", "1110100", "011010"}) End Sub Public Function Generate(ByVal Code As String) As Image Dim a As Integer = 0 Dim b As Integer = 0 Dim imgCode As Image Dim g As Graphics Dim i As Integer Dim bCode As Byte() Dim bitCode As Byte() Dim tmpFont As Font If Code.Length <> 12 Or Not IsNumeric(Code.Replace(".", "_").Replace(",", "_")) Then Throw New Exception("Le code doit être composé de 12 chiffres") ReDim bCode(12) For i = 0 To 11 bCode(i) = CInt(Code.Substring(i, 1)) If (i Mod 2) = 1 Then b += bCode(i) Else a += bCode(i) End If Next i = (a + (b * 3)) Mod 10 If i = 0 Then bCode(12) = 0 Else bCode(12) = 10 - i End If bitCode = getBits(bCode) tmpFont = New Font("times new roman", 14, FontStyle.Regular, GraphicsUnit.Pixel) imgCode = New Bitmap(110, 50) g = Graphics.FromImage(imgCode) g.Clear(Color.White) g.DrawString(Code.Substring(0, 1), tmpFont, Brushes.Black, 2, 30) a = g.MeasureString(Code.Substring(0, 1), tmpFont).Width For i = 0 To bitCode.Length - 1 If i = 2 Then g.DrawString(Code.Substring(1, 6), tmpFont, Brushes.Black, a, 30) ElseIf i = 48 Then g.DrawString(Code.Substring(7, 5) & bCode(12).ToString, tmpFont, Brushes.Black, a, 30) End If If i = 0 Or i = 2 Or i = 46 Or i = 48 Or i = 92 Or i = 94 Then If bitCode(i) = 1 Then 'noir g.DrawLine(Pens.Black, a, 0, a, 40) a += 1 End If Else If bitCode(i) = 1 Then 'noir g.DrawLine(Pens.Black, a, 0, a, 30) a += 1 Else 'blanc a += 1 End If End If Next g.Flush() Return imgCode End Function Private Function getBits(ByVal bCode As Byte()) As Byte() Dim i As Integer Dim res As Byte() Dim bits As String = "101" Dim cle As String = bitsCode(bCode(0))(3) For i = 1 To 6 bits &= bitsCode(bCode(i))(CInt(cle.Substring(i - 1, 1))) Next bits &= "01010" For i = 7 To 12 bits &= bitsCode(bCode(i))(2) Next bits += "101" ReDim res(bits.Length - 1) For i = 0 To bits.Length - 1 res(i) = Asc(bits.Chars(i)) - 48 Next Return res End Function End Class A: Instead of using barcode font, i would prefer a .net barcode generator component. Below is a vb.net sample for creating Code 39 barcode. Imports System.IO Imports PQScan.BarcodeCreator Namespace BarcodeGeneratorVB Class Program Private Shared Sub Main(args As String()) Dim barcode As New Barcode() barcode.Data = "www.pqscan.com" barcode.BarType = BarCodeType.Code39 barcode.Width = 300 barcode.Height = 100 barcode.CreateBarcode("code39-vb.jpeg") End Sub End Class End Namespace A: At my last job I worked with a couple different libraries in vb.net for this. We had one, and moved to a different one. I can't remember their names (I'd recognize them again if I saw them), but I do know that both were for-pay, we evaluated several different components at the time of the switch, and I think that included a free one. We were a very small shop and very cost sensitive, so if the free component were any good at all you can bet we would have used it (I think we needed 128b support, and it only handled code39). I also remember that reason we switched was that it was at the same time we moved from .Net 1.1 to .Net 2.0, and the first component was too slow making the transition. So, in summary, there is something out there, but it wasn't any good 3 years ago. Hopefully someone else can come along and fill in some actual names.
{ "language": "en", "url": "https://stackoverflow.com/questions/149379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Dynamic Sorting within SQL Stored Procedures This is an issue that I've spent hours researching in the past. It seems to me to be something that should have been addressed by modern RDBMS solutions but as yet I have not found anything that really addresses what I see to be an incredibly common need in any Web or Windows application with a database back-end. I speak of dynamic sorting. In my fantasy world, it should be as simple as something like: ORDER BY @sortCol1, @sortCol2 This is the canonical example given by newbie SQL and Stored Procedure developers all over forums across the Internet. "Why isn't this possible?" they ask. Invariably, somebody eventually comes along to lecture them about the compiled nature of stored procedures, of execution plans in general, and all sorts of other reasons why it isn't possible to put a parameter directly into an ORDER BY clause. I know what some of you are already thinking: "Let the client do the sorting, then." Naturally, this offloads the work from your database. In our case though, our database servers aren't even breaking a sweat 99% of the time and they aren't even multi-core yet or any of the other myriad improvements to system architecture that happen every 6 months. For this reason alone, having our databases handle sorting wouldn't be a problem. Additionally, databases are very good at sorting. They are optimized for it and have had years to get it right, the language for doing it is incredibly flexible, intuitive, and simple and above all any beginner SQL writer knows how to do it and even more importantly they know how to edit it, make changes, do maintenance, etc. When your databases are far from being taxed and you just want to simplify (and shorten!) development time this seems like an obvious choice. Then there's the web issue. I've played around with JavaScript that will do client-side sorting of HTML tables, but they inevitably aren't flexible enough for my needs and, again, since my databases aren't overly taxed and can do sorting really really easily, I have a hard time justifying the time it would take to re-write or roll-my-own JavaScript sorter. The same generally goes for server-side sorting, though it is already probably much preferred over JavaScript. I'm not one that particularly likes the overhead of DataSets, so sue me. But this brings back the point that it isn't possible — or rather, not easily. I've done, with prior systems, an incredibly hack way of getting dynamic sorting. It wasn't pretty, nor intuitive, simple, or flexible and a beginner SQL writer would be lost within seconds. Already this is looking to be not so much a "solution" but a "complication." The following examples are not meant to expose any sort of best practices or good coding style or anything, nor are they indicative of my abilities as a T-SQL programmer. They are what they are and I fully admit they are confusing, bad form, and just plain hack. We pass an integer value as a parameter to a stored procedure (let's call the parameter just "sort") and from that we determine a bunch of other variables. For example... let's say sort is 1 (or the default): DECLARE @sortCol1 AS varchar(20) DECLARE @sortCol2 AS varchar(20) DECLARE @dir1 AS varchar(20) DECLARE @dir2 AS varchar(20) DECLARE @col1 AS varchar(20) DECLARE @col2 AS varchar(20) SET @col1 = 'storagedatetime'; SET @col2 = 'vehicleid'; IF @sort = 1 -- Default sort. BEGIN SET @sortCol1 = @col1; SET @dir1 = 'asc'; SET @sortCol2 = @col2; SET @dir2 = 'asc'; END ELSE IF @sort = 2 -- Reversed order default sort. BEGIN SET @sortCol1 = @col1; SET @dir1 = 'desc'; SET @sortCol2 = @col2; SET @dir2 = 'desc'; END You can already see how if I declared more @colX variables to define other columns I could really get creative with the columns to sort on based on the value of "sort"... to use it, it usually ends up looking like the following incredibly messy clause: ORDER BY CASE @dir1 WHEN 'desc' THEN CASE @sortCol1 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END DESC, CASE @dir1 WHEN 'asc' THEN CASE @sortCol1 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END, CASE @dir2 WHEN 'desc' THEN CASE @sortCol2 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END DESC, CASE @dir2 WHEN 'asc' THEN CASE @sortCol2 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END Obviously this is a very stripped down example. The real stuff, since we usually have four or five columns to support sorting on, each with possible secondary or even a third column to sort on in addition to that (for example date descending then sorted secondarily by name ascending) and each supporting bi-directional sorting which effectively doubles the number of cases. Yeah... it gets hairy really quick. The idea is that one could "easily" change the sort cases such that vehicleid gets sorted before the storagedatetime... but the pseudo-flexibility, at least in this simple example, really ends there. Essentially, each case that fails a test (because our sort method doesn't apply to it this time around) renders a NULL value. And thus you end up with a clause that functions like the following: ORDER BY NULL DESC, NULL, [storagedatetime] DESC, blah blah You get the idea. It works because SQL Server effectively ignores null values in order by clauses. This is incredibly hard to maintain, as anyone with any basic working knowledge of SQL can probably see. If I've lost any of you, don't feel bad. It took us a long time to get it working and we still get confused trying to edit it or create new ones like it. Thankfully it doesn't need changing often, otherwise it would quickly become "not worth the trouble." Yet it did work. My question is then: is there a better way? I'm okay with solutions other than Stored Procedure ones, as I realize it may just not be the way to go. Preferably, I'd like to know if anyone can do it better within the Stored Procedure, but if not, how do you all handle letting the user dynamically sort tables of data (bi-directionally, too) with ASP.NET? And thank you for reading (or at least skimming) such a long question! PS: Be glad I didn't show my example of a stored procedure that supports dynamic sorting, dynamic filtering/text-searching of columns, pagination via ROWNUMBER() OVER, AND try...catch with transaction rollbacking on errors... "behemoth-sized" doesn't even begin to describe them. Update: * *I would like to avoid dynamic SQL. Parsing a string together and running an EXEC on it defeats a lot of the purpose of having a stored procedure in the first place. Sometimes I wonder though if the cons of doing such a thing wouldn't be worth it, at least in these special dynamic sorting cases. Still, I always feel dirty whenever I do dynamic SQL strings like that — like I'm still living in the Classic ASP world. *A lot of the reason we want stored procedures in the first place is for security. I don't get to make the call on security concerns, only suggest solutions. With SQL Server 2005 we can set permissions (on a per-user basis if need be) at the schema level on individual stored procedures and then deny any queries against the tables directly. Critiquing the pros and cons of this approach is perhaps for another question, but again it's not my decision. I'm just the lead code monkey. :) A: Dynamic SQL is still an option. You just have to decide whether that option is more palatable than what you currently have. Here is an article that shows that: https://web.archive.org/web/20211029044050/https://www.4guysfromrolla.com/webtech/010704-1.shtml. A: My applications do this a lot but they are all dynamically building the SQL. However, when I deal with stored procedures I do this: * *Make the stored procedure a function that returns a table of your values - no sort. *Then in your application code do a select * from dbo.fn_myData() where ... order by ... so you can dynamically specify the sort order there. Then at least the dynamic part is in your application, but the database is still doing the heavy lifting. A: A stored procedure technique (hack?) I've used to avoid dynamic SQL for certain jobs is to have a unique sort column. I.e., SELECT name_last, name_first, CASE @sortCol WHEN 'name_last' THEN [name_last] ELSE 0 END as mySort FROM table ORDER BY mySort This one is easy to beat into submission -- you can concat fields in your mySort column, reverse the order with math or date functions, etc. Preferably though, I use my asp.net gridviews or other objects with build-in sorting to do the sorting for me AFTER retrieving the data fro Sql-Server. Or even if it's not built-in -- e.g., datatables, etc. in asp.net. A: There may be a third option, since your server has lots of spare cycles - use a helper procedure to do the sorting via a temporary table. Something like create procedure uspCallAndSort ( @sql varchar(2048), --exec dbo.uspSomeProcedure arg1,'arg2',etc. @sortClause varchar(512) --comma-delimited field list ) AS insert into #tmp EXEC(@sql) declare @msql varchar(3000) set @msql = 'select * from #tmp order by ' + @sortClause EXEC(@msql) drop table #tmp GO Caveat: I haven't tested this, but it "should" work in SQL Server 2005 (which will create a temporary table from a result set without specifying the columns in advance.) A: There's a couple of different ways you can hack this in. Prerequisites: * *Only one SELECT statement in the sp *Leave out any sorting (or have a default) Then insert into a temp table: create table #temp ( your columns ) insert #temp exec foobar select * from #temp order by whatever Method #2: set up a linked server back to itself, then select from this using openquery: http://www.sommarskog.se/share_data.html#OPENQUERY A: This approach keeps the sortable columns from being duplicated twice in the order by, and is a little more readable IMO: SELECT s.* FROM (SELECT CASE @SortCol1 WHEN 'Foo' THEN t.Foo WHEN 'Bar' THEN t.Bar ELSE null END as SortCol1, CASE @SortCol2 WHEN 'Foo' THEN t.Foo WHEN 'Bar' THEN t.Bar ELSE null END as SortCol2, t.* FROM MyTable t) as s ORDER BY CASE WHEN @dir1 = 'ASC' THEN SortCol1 END ASC, CASE WHEN @dir1 = 'DESC' THEN SortCol1 END DESC, CASE WHEN @dir2 = 'ASC' THEN SortCol2 END ASC, CASE WHEN @dir2 = 'DESC' THEN SortCol2 END DESC A: At some point, doesn't it become worth it to move away from stored procedures and just use parameterized queries to avoid this sort of hackery? A: I agree, use client side. But it appears that is not the answer you want to hear. So, it is perfect the way it is. I don't know why you would want to change it, or even ask "Is there a better way." Really, it should be called "The Way". Besides, it seems to work and suit the needs of the project just fine and will probably be extensible enough for years to come. Since your databases aren't taxed and sorting is really really easy it should stay that way for years to come. I wouldn't sweat it. A: When you are paging sorted results, dynamic SQL is a good option. If you're paranoid about SQL injection you can use the column numbers instead of the column name. I've done this before using negative values for descending. Something like this... declare @o int; set @o = -1; declare @sql nvarchar(2000); set @sql = N'select * from table order by ' + cast(abs(@o) as varchar) + case when @o < 0 then ' desc' else ' asc' end + ';' exec sp_executesql @sql Then you just need to make sure the number is inside 1 to # of columns. You could even expand this to a list of column numbers and parse that into a table of ints using a function like this. Then you would build the order by clause like so... declare @cols varchar(100); set @cols = '1 -2 3 6'; declare @order_by varchar(200) select @order_by = isnull(@order_by + ', ', '') + cast(abs(number) as varchar) + case when number < 0 then ' desc' else '' end from dbo.iter_intlist_to_tbl(@cols) order by listpos print @order_by One drawback is you have to remember the order of each column on the client side. Especially, when you don't display all the columns or you display them in a different order. When the client wants to sort, you map the column names to the column order and generate the list of ints. A: An argument against doing the sorting on the client side is large volume data and pagination. Once your row count gets beyond what you can easily display you're often sorting as part of a skip/take, which you probably want to run in SQL. For Entity Framework, you could use a stored procedure to handle your text search. If you encounter the same sort issue, the solution I've seen is to use a stored proc for the search, returning only an id key set for the match. Next, re-query (with the sort) against the db using the ids in a list (contains). EF handles this pretty well, even when the ID set is pretty large. Yes, this is two round trips, but it allows you to always keep your sorting in the DB, which can be important in some situations, and prevents you from writing a boatload of logic in the stored procedure. A: Yeah, it's a pain, and the way you're doing it looks similar to what I do: order by case when @SortExpr = 'CustomerName' and @SortDir = 'ASC' then CustomerName end asc, case when @SortExpr = 'CustomerName' and @SortDir = 'DESC' then CustomerName end desc, ... This, to me, is still much better than building dynamic SQL from code, which turns into a scalability and maintenance nightmare for DBAs. What I do from code is refactor the paging and sorting so I at least don't have a lot of repetition there with populating values for @SortExpr and @SortDir. As far as the SQL is concerned, keep the design and formatting the same between different stored procedures, so it's at least neat and recognizable when you go in to make changes. A: How about handling sorting on the stuff displaying the results -- grids, reports, etc. rather than on SQL? EDIT: To clarify things since this answer got down-voted earlier, I'll elaborate a bit... You stated you knew about client-side sorting but wanted to steer clear of it. That's your call, of course. What I want to point out, though, is that by doing it on the client-side, you're able to pull data ONCE and then work with it however you want -- versus doing multiple trips back and forth to the server each time the sort gets changed. Your SQL Server isn't getting taxed right now and that's awesome. It shouldn't be. But just because it isn't overloaded yet doesn't mean that it'll stay like that forever. If you're using any of the newer ASP.NET stuff for displaying on the web, a lot of that stuff is already baked right in. Is it worth adding so much code to each stored procedure just to handle sorting? Again, your call. I'm not the one who will ultimately be in charge of supporting it. But give some thought to what will be involved as columns are added/removed within the various datasets used by the stored procedures (requiring modifications to the CASE statements) or when suddenly instead of sorting by two columns, the user decides they need three -- requiring you to now update every one of your stored procedures that uses this method. For me, it's worth it to get a working client-side solution and apply it to the handful of user-facing displays of data and be done with it. If a new column is added, it's already handled. If the user wants to sort by multiple columns, they can sort by two or twenty of them. A: Sorry I'm late to the party, but here's another option for those who really want to avoid dynamic SQL, but want the flexibility it offers: Instead of dynamically generating the SQL on the fly, write code to generate a unique proc for every possible variation. Then you can write a method in the code to look at the search options and have it choose the appropriate proc to call. If you only have a few variations then you can just create the procs by hand. But if you have a lot of variations then instead of having to maintain them all, you would just maintain your proc generator instead to have it recreate them. As an added benefit, you'll get better SQL plans for better performance doing it this way too. A: You should avoid the SQL Server sorting, unless if necessary. Why not sort on app server or client side? Also .NET Generics does exceptional sortin A: This solution might only work in .NET, I don't know. I fetch the data into the C# with the initial sort order in the SQL order by clause, put that data in a DataView, cache it in a Session variable, and use it to build a page. When the user clicks on a column heading to sort (or page, or filter), I don't go back to the database. Instead, I go back to my cached DataView and set its "Sort" property to an expression I build dynamically, just like I would dynamic SQL. ( I do the filtering the same way, using the "RowFilter" property). You can see/feel it working in a demo of my app, BugTracker.NET, at http://ifdefined.com/btnet/bugs.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/149380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "136" }
Q: Low-level details of the implementation of performSelectorOnMainThread: Was wondering if anyone knows, or has pointers to good documentation that discusses, the low-level implementation details of Cocoa's 'performSelectorOnMainThread:' method. My best guess, and one I think is probably pretty close, is that it uses mach ports or an abstraction on top of them to provide intra-thread communication, passing selector information along as part of the mach message. Right? Wrong? Thanks! Update 09:39AMPST Thank you Evan DiBiase and Mecki for the answers, but to clarify: I understand what happens in the run loop, but what I'm looking for an answer to is; "where is the method getting queued? how is the selector information getting passed into the queue?" Looking for more than Apple's doc info: I've read 'em Update 14:21PST Chris Hanson brings up a good point in a comment: my objective here is not to learn the underlying mechanisms in order to take advantage of them in my own code. Rather, I'm just interested in a better conceptual understanding of the process of signaling another thread to execute code. As I said, my own research leads me to believe that it's takes advantage of mach messaging for IPC to pass selector information between threads, but I'm specifically looking for concrete information on what is happening, so I can be sure I'm understanding things correctly. Thanks! Update 03/06/09 I've opened a bounty on this question because I'd really like to see it answered, but if you are trying to collect please make sure you read everything, including all currently posed answers, comments to both these answers and to my original question, and the update text I posted above. I'm look for the lowest-level detail of the mechanism used by performSelectorOnMainThread: and the like, and as I mentioned earlier, I suspect it has something to do with Mach ports but I'd really like to know for sure. The bounty will not be awarded unless I can confirm the answer given is correct. Thanks everyone! A: The documentation for NSObject's performSelectorOnMainThread:withObject:waitUntilDone: method says: This method queues the message on the run loop of the main thread using the default run loop modes—that is, the modes associated with the NSRunLoopCommonModes constant. As part of its normal run loop processing, the main thread dequeues the message (assuming it is running in one of the default run loop modes) and invokes the desired method. A: One More Edit: To answer the question of the comment: what IPC mechanism is being used to pass info between threads? Shared memory? Sockets? Mach messaging? NSThread stores internally a reference to the main thread and via that reference you can get a reference to the NSRunloop of that thread. A NSRunloop internally is a linked list and by adding a NSTimer object to the runloop, a new linked list element is created and added to the list. So you could say it's shared memory, the linked list, that actually belongs to the main thread, is simply modified from within a different thread. There are mutexes/locks (possibly even NSLock objects) that will make sure editing the linked list is thread-safe. Pseudo code: // Main Thread for (;;) { lock(runloop->runloopLock); task = NULL; do { task = getNextTask(runloop); if (!task) { // function below unlocks the lock and // atomically sends thread to sleep. // If thread is woken up again, it will // get the lock again before continuing // running. See "man pthread_cond_wait" // as an example function that works // this way wait_for_notification(runloop->newTasks, runloop->runloopLock); } } while (!task); unlock(runloop->runloopLock); processTask(task); } // Other thread, perform selector on main thread // selector is char *, containing the selector // object is void *, reference to object timer = createTimerInPast(selector, object); runloop = getRunloopOfMainThread(); lock(runloop->runloopLock); addTask(runloop, timer); wake_all_sleeping(runloop->newTasks); unlock(runloop->runloopLock); Of course this is oversimplified, most details are hidden between functions here. E.g. getNextTask will only return a timer, if the timer should have fired already. If the fire date for every timer is still in the future and there is no other event to process (like a keyboard, mouse event from UI or a sent notification), it would return NULL. I'm still not sure what the question is. A selector is nothing more than a C string containing the name of a method being called. Every method is a normal C function and there exists a string table, containing the method names as strings and function pointers. That are the very basics how Objective-C actually works. As I wrote below, a NSTimer object is created that gets a pointer to the target object and a pointer to a C string containing the method name and when the timer fires, it finds the right C method to call by using the string table (hence it needs the string name of the method) of the target object (hence it needs a reference to it). Not exactly the implementation, but pretty close to it: Every thread in Cocoa has a NSRunLoop (it's always there, you never need to create on for a thread). PerformSelectorOnMainThread creates a NSTimer object like this, one that fires only once and where the time to fire is already located in the past (so it needs firing immediately), then gets the NSRunLoop of the main thread and adds the timer object there. As soon as the main thread goes idle, it searches for the next event in its Runloop to process (or goes to sleep if there is nothing to process and being woken up again as soon as an event is added) and performs it. Either the main thread is busy when you schedule the call, in which case it will process the timer event as soon as it has finished its current task or it is sleeping at the moment, in which case it will be woken up by adding the event and processes it immediately. A good source to look up how Apple is most likely doing it (nobody can say for sure, as after all its closed source) is GNUStep. Since the GCC can handle Objective-C (it's not just an extension only Apple ships, even the standard GCC can handle it), however, having Obj-C without all the basic classes Apple ships is rather useless, the GNU community tried to re-implement the most common Obj-C classes you use on Mac and their implementation is OpenSource. Here you can download a recent source package. Unpack that and have a look at the implementation of NSThread, NSObject and NSTimer for details. I guess Apple is not doing it much different, I could probably prove it using gdb, but why would they do it much different than that approach? It's a clever approach that works very well :) A: Yes, it does use Mach ports. What happens is this: * *A block of data encapsulating the perform info (the target object, the selector, the optional object argument to the selector, etc.) is enqueued in the thread's run loop info. This is done using @synchronized, which ultimately uses pthread_mutex_lock. *CFRunLoopSourceSignal is called to signal that the source is ready to fire. *CFRunLoopWakeUp is called to let the main thread's run loop know it's time to wake up. This is done using mach_msg. From the Apple docs: Version 1 sources are managed by the run loop and kernel. These sources use Mach ports to signal when the sources are ready to fire. A source is automatically signaled by the kernel when a message arrives on the source’s Mach port. The contents of the message are given to the source to process when the source is fired. The run loop sources for CFMachPort and CFMessagePort are currently implemented as version 1 sources. I'm looking at a stack trace right now, and this is what it shows: 0 mach_msg 1 CFRunLoopWakeUp 2 -[NSThread _nq:] 3 -[NSObject(NSThreadPerformAdditions) performSelector:onThread:withObject:waitUntilDone:modes:] 4 -[NSObject(NSThreadPerformAdditions) performSelectorOnMainThread:withObject:waitUntilDone:] Set a breakpoint on mach_msg and you'll be able to confirm it. A: As Mecki said, a more general mechanism that could be used to implement -performSelectorOn… is NSTimer. NSTimer is toll-free bridged to CFRunLoopTimer. An implementation of CFRunLoopTimer – although not necessarily the one actually used for normal processes in OS X – can be found in CFLite (open-source subset of CoreFoundation; package CF-476.14 in the Darwin 9.4 source code. (CF-476.15, corresponding to OS X 10.5.5, is not yet available.)
{ "language": "en", "url": "https://stackoverflow.com/questions/149388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Winforms threading problem, second thread can't access 1st main forms controls I have a winforms application, the issue has to do with threading. Since I am calling 'MyCustomCode() which creates a new thread, and calls the method 'SomeMethod()' which then accesses MessageBox.Show(...). The problem has to do with threading, since the newly created thread is trying to access a control that was created on another thread. I am getting the error: Cross-thread operation not valid: Control 'TestForm' accessed from a thread other than the thread it was created on. public TestForm() { InitializeComponent(); // custom code // MyCustomCode(); } public void SomeMethod() { // ***** This causes an error **** MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } private void InitializeAutoUpdater() { // Seperate thread is spun to keep polling for updates ThreadStart ts = new ThreadStart(SomeMethod); pollThread = new Thread(ts); pollThread.Start(); } Update If you look at this example http://www.codeproject.com/KB/cs/vanillaupdaterblock.aspx, the method CheckAndUpdate is calling MessageBox.Show(..) that is what my problem is. I would have thought that code was good to go! Funny thing is that this code was working just fine on Friday??? A: You cannot acces UI elements from multiple threads. One way to solve this is to call the Invoke method of a control with a delegate to the function wich use the UI elements (like the message box). Somethin like: public delegate void InvokeDelegate(); public void SomeMethod() { button1.Invoke((InvokeDelegate)doUIStuff); } void doUIStuff() { MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } A: to avoid cross-thread exceptions (InvalidOperationException), here is the code pattern: protected delegate void someGuiFunctionDelegate(int iParam); protected void someGuiFunction(int iParam) { if (this.InvokeRequired) { someGuiFunctionDelegate dlg = new someGuiFunctionDelegate(this.someGuiFunction); this.Invoke(dlg, new object[] { iParam }); return; } //do something with the GUI control here } i agree that this is annoying, but it is an artifact of the fact that windows GUI controls are not thread-safe. The exception can be turned off with a flag somewhere or other, but don't do that as it can lead to extremely hard to find bugs. A: To keep things simple you can look into using the BackGroundWorker class. This class will provide a framework for to handle your threading and progress notification events. Your ui thread will handle the progress event and display the error message you pass back. A: * *Use Control.BeginInvoke or Control.Invoke methods OR * *Use SynchronizationContext A: I know this is an older post, but I recently found an elegant solution to this problem using generics and extension methods. This is a combination of the authors works and some comments. A Generic Method for Cross-thread Winforms Access http://www.codeproject.com/KB/cs/GenericCrossThread.aspx public static void Manipulate<T>(this T control, Action<T> action) where T : Control { if (control.InvokeRequired) { control.Invoke(new Action<T, Action<T>>(Manipulate), new object[] { control, action }); } else { action(control); } } This can be called in the following manner, for simplicity I used a label. someLabel.Manipulate(lbl => lbl.Text = "Something"); A: You should NOT use BeginInvoke, you should use Invoke, then once you grasp that, you can look into using BeginInvoke if really needed. A: '******************************************************************* ' Get a new processor and fire it off on a new thread. '******************************************************************* fpProc = New Processor(confTable, paramFile, keyCount) AddHandler fpProc.LogEntry, AddressOf LogEntry_Handler Dim myThread As System.Threading.Thread = New System.Threading.Thread(AddressOf fpProc.ProcessEntry) myThread.Start() Then in the parent app you have: '************************************************************************* ' Sub: LogEntry_Handler() ' Author: Ron Savage ' Date: 08/29/2007 ' ' This routine handles the LogEntry events raised by the Processor class ' running in a thread. '************************************************************************* Private Sub LogEntry_Handler(ByVal logLevel As Integer, ByVal logMsg As String) Handles fProc.LogEntry writeLogMessage(logMsg); End Sub That's what I do. A: Check for InvokeRequired A: I praticularly like a recursive call. public delegate void InvokeDelegate(string errMessage); public void SomeMethod() { doUIStuff("my error message"); } void doUIStuff(string errMessage) { if (button1.InvokeRequired) button1.Invoke((InvokeDelegate)doUIStuff(errMessage)); else { MessageBox.Show(this, ex.Message, errMessage, MessageBoxButtons.OK, MessageBoxIcon.Error ); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/149394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: What are some ways of accessing Microsoft SQL Server from Linux? We have a Windows machine running SQL Server 2005, and we need to be able to run some database queries on it from a Linux box. What are some of the recommended ways of doing this? Ideally, we would want a command-line utility similar to sqlcmd on Windows. A: pymssql is a DB-API Python module, based on FreeTDS. It worked for me. Create some helper functions, if you need, and use it from Python shell. A: Mono contains an ADO.NET provider that should do this for you. I don't know if there is a command line utility for it, but you could definitely wrap up some C# to do the queries if there isn't. Have a look at http://www.mono-project.com/TDS_Providers and http://www.mono-project.com/SQLClient A: Since November 2011 Microsoft provides their own SQL Server ODBC Driver for Linux for Red Hat Enterprise Linux (RHEL) and SUSE Linux Enterprise Server (SLES). * *Download Microsoft ODBC Driver 11 for SQL Server on Red Hat Linux *Download Microsoft ODBC Driver 11 for SQL Server on SUSE - CTP *ODBC Driver on Linux Documentation It also includes sqlcmd for Linux. A: FreeTDS + unixODBC or iODBC Install first FreeTDS, then configure one of the two ODBC engines to use FreeTDS as its ODBC driver. Then use the commandline interface of the ODBC engine. unixODBC has isql, iODBC has iodbctest You can also use your favorite programming language (I've successfully used Perl, C, Python and Ruby to connect to MSSQL) I'm personally using FreeTDS + iODBC: $more /etc/freetds/freetds.conf [10.0.1.251] host = 10.0.1.251 port = 1433 tds version = 8.0 $ more /etc/odbc.ini [ACCT] Driver = /usr/local/freetds/lib/libtdsodbc.so Description = ODBC to SQLServer via FreeTDS Trace = No Servername = 10.0.1.251 Database = accounts_ver8 A: If you are using Java, have a look at JDBC. http://msdn.microsoft.com/en-us/library/ms378672(SQL.90).aspx http://en.wikipedia.org/wiki/Jdbc A: sql-cli is a nodejs based cross platform command line interface for sql server. You can install it via npm https://www.npmjs.org/package/sql-cli It can connect to both on-premise and sql azure instance. A: You don't say what you want to do with the resulting data, but if it's general queries for development/maintenance then I'd have thought Remote Desktop to the windows server and then using the actual SQL Server tools on their would always have been a more productive option over any hacked together solution on Linux itself. A: There is an abstraction lib available for PHP. Not sure what your client's box will support but if its Linux then certainly should support building a PHP query interface with this: http://adodb.sourceforge.net/ Hope that helps you. A: sqsh + freetds. sqsh was primarily an isql replacement for Sybase SQL Server (now ASE) but it works just fine for connecting to SQL Server (provided you use freetds). To compile, simply point $SYBASE to freetds install and it should work from there. I use it on my Mac all day. The best part of sqsh are the advanced features, such as dead simple server linking (no need to set up linked servers in SQL Server), flow control and looping (no more concatenating strings and executing dynamic SQL), and invisible bulk copy/load. Anyone who uses any other command line tool is simply crazy! :) A: I'd like to recommend Sqlectron. Besides being open source under MIT license it's multiplatform boosted by Electron. Its own definition is: A simple and lightweight SQL client desktop with cross database and platform support It currently supports PostgreSQL, MySQL, MS SQL Server, Cassandra and SQLite. A: Surprised no one has mentioned that, contrary to what other answers seem to suggest, FreeTDS is all you need. No need for unixODBC, iODBC or anything else on top of it. run some database queries [...] command-line utility similar to sqlcmd on Windows tsql does this and is part of the FreeTDS package (as are freebcp and other utilities). tsql does not have fancy UI, but if you want a command-line utility that is light, functional and performant, it'll do just fine. See e.g. How to run a SQL script in tsql And by light, I mean under 500kb in size (maybe under 60k depending on how it's compiled) and, as far as I have seen, extremely efficient with memory and CPU. A: I was not confortable with the freetds solution, it's why i coded a class (command history, autocompletion on tables and fields, etc.) http://www.phpclasses.org/package/8168-PHP-Use-ncurses-to-get-key-inputs-and-write-shell-text.html A: valentina-db it has free version for sql server .rpm and .deb serial id will be sent by email after registration https://www.valentina-db.com/en/ https://valentina-db.com/en/store/category/14-free-products A: If you use eclipse you can install Data Tools Platform plugin on it and use it for every DB engines including MS SQLServer. It just needs to get JDBC driver for that DB engine. A: There is a nice CLI based tool for accessing MSSQL databases now. It's called mssql-cli and it's a bit similar to postgres' psql. Gihub repository page Install for example via pip (global installation, for a local one omit the sudo part): sudo pip install mssql-cli
{ "language": "en", "url": "https://stackoverflow.com/questions/149395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "55" }
Q: Customizing Visual Studio's Intellisense A recent project had me working with C# again, and I noticed something I hadn't before -- C#'s Intellisense shows possible exceptions that can be thrown when calling a method Since I work mostly with VB.NET applications, it'd be really nice to have this feature in those applications as well, but it's unfortunately absent from VB's Intellisense Is there any quick and easy way I can customize Visual Studio's Intellisense to show exceptions (as well as other members from the XML comments)? Or am I looking at a full modification using the SDK? Update: 29-Sep-2008 1:49 PM -- I figure this will be more complicated than simply changing a configuration setting. Since the comments are XML-based, I was hoping for an XSLT file somewhere buried in the Visual Studio directory, but nothing has turned up so far. Looks like I'm going to have to dig into the Visual Studio SDK. A: Try going to Tool -> Options... Then Text Editor -> Basic and make sure both options "Auto list members" and "hide advanced members" are unchecked. Also check "Parameter information". I cannot validate this information because my current Visual Studio installation is C# standalone. Regards, Luís
{ "language": "en", "url": "https://stackoverflow.com/questions/149400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Manipulate Results in GridView RowDataBound or Directly in SQL? I have a curious question about efficiency. Say I have a field on a database that is just a numeric digit that represents something else. Like, a value of 1 means the term is 30 days. Would it be better (more efficient) to code a SELECT statement like this... SELECT CASE TermId WHEN 1 THEN '30 days' WHEN 2 THEN '60 days' END AS Term FROM MyTable ...and bind the results directly to the GridView, or would it be better to evaluate the TermId field in RowDataBound event of the GridView and change the cell text accordingly? Don't worry about extensibility or anything like that, I am only concerned about the differences in overall efficiency. For what it's worth, the database resides on the web server. A: Efficiency probably wouldn't matter here - code maintainability does though. Ask yourself - will these values change? What if they do? What would I need to do after 2 years of use if these values change? If it becomes evident that scripting them in SQL would mean better maintainability (easier to change), then do it in a stored Procedure. If it's easier to change them in code later, then do that. The benefits from doing either are quite low, as the code doesn't look complex at all. A: For a number of reasons, I would process the translation in the grid view. Reason #1: SQL resource is shared. Grid is distributed. Better scalability. Reason #2: Lower bandwidth to transmit a couple integers vs. strings. Reason #3: Code can be localized for other languages without affecting the SQL Server code. A: A field in a database table called TermID would imply itself to represent a foreign key to another table (perhaps called "Term"). If this is the case, then perhaps that table has (or should have), a Description field which could hold the "30 days" text. You could/should join to this table to retrieve the descriptive text. While this join might not improve efficiency, it it a light weight enough join to not get in the way.
{ "language": "en", "url": "https://stackoverflow.com/questions/149416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implementing a resizable textarea? How does Stackoverflow implement the resizable textarea? Is that something they rolled themselves or is it a publicly available component that I can easily attach to textareas on my sites? I found this question and it doesn't quite do what I want. autosizing-textarea That talks more about automatically resizing textareas whereas I want the little grab-area that you can drag up and down. A: At first I believed it was a built-in feature of the Wysiwym Markdown editor, but Shog9 is correct: it's not baked-in at all, but is courtesy of the jQuery plugin TextAreaResizer (I was lead astray by the browser was using to check on the editor demo because Google Chrome itself adds the expandable functionality on textareas—much like the Safari browser does). A: StackOverflow uses a jQuery plugin to accomplish this: TextAreaResizer. It's easy enough to verify this - just pull the JS files from the site. Historical note: when this answer was originally written, WMD and TextAreaResizer were two separate plugins, neither one of which was authored by the SO Dev Team (see also: micahwittman's answer). Also, the JavaScript for the site was quite easy to read... None of these are strictly true anymore, but TextAreaResizer still works just fine. A: I needed a similar functionality recently. Its called Autogrow and it is a Plugin of the amazing jQuery library A: Using AngularJS: angular.module('app').directive('textarea', function() { return { restrict: 'E', controller: function($scope, $element) { $element.css('overflow-y','hidden'); $element.css('resize','none'); resetHeight(); adjustHeight(); function resetHeight() { $element.css('height', 0 + 'px'); } function adjustHeight() { var height = angular.element($element)[0] .scrollHeight + 1; $element.css('height', height + 'px'); $element.css('max-height', height + 'px'); } function keyPress(event) { // this handles backspace and delete if (_.contains([8, 46], event.keyCode)) { resetHeight(); } adjustHeight(); } $element.bind('keyup change blur', keyPress); } }; }); This will transform all your textareas to grow/shrink. If you want only specific textareas to grow/shrink - change the top part to read like this: angular.module('app').directive('expandingTextarea', function() { return { restrict: 'A', Hope that helps! A: what about this, its work <textarea oninput='this.style.height = "";this.style.height = this.scrollHeight + "px"'></textarea>
{ "language": "en", "url": "https://stackoverflow.com/questions/149421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: How can circular dependencies be avoided when callbacks are used? How can you avoid circular dependencies when you're designing two classes with a producer/consumer relationship? Here ListenerImpl needs a reference to Broadcaster in order to register/unregister itself, and Broadcaster needs a reference back to the Listeners in order to send messages. This example is in Java but it can apply to any OO language. public interface Listener { void callBack(Object arg); } public class ListenerImpl implements Listener { public ListenerImpl(Broadcaster b) { b.register(this); } public void callBack(Object arg) { ... } public void shutDown() { b.unregister(this); } } public class Broadcaster { private final List listeners = new ArrayList(); public void register(Listener lis) { listeners.add(lis); } public void unregister(Listener lis) {listeners.remove(lis); } public void broadcast(Object arg) { for (Listener lis : listeners) { lis.callBack(arg); } } } A: I don't see that being a circular dependency. Listener depends on nothing. ListenerImpl depends on Listener and Broadcaster Broadcaster depends on Listener. Listener ^ ^ / \ / \ Broadcaster <-- ListenerImpl All arrows end at Listener. There's no cycle. So, I think you're OK. A: Any OOP language? OK. Here's a ten-minute version in CLOS. Broadcasting framework (defclass broadcaster () ((listeners :accessor listeners :initform '()))) (defgeneric add-listener (broadcaster listener) (:documentation "Add a listener (a function taking one argument) to a broadcast's list of interested parties")) (defgeneric remove-listener (broadcaster listener) (:documentation "Reverse of add-listener")) (defgeneric broadcast (broadcaster object) (:documentation "Broadcast an object to all registered listeners")) (defmethod add-listener (broadcaster listener) (pushnew listener (listeners broadcaster))) (defmethod remove-listener (broadcaster listener) (let ((listeners (listeners broadcaster))) (setf listeners (remove listener listeners)))) (defmethod broadcast (broadcaster object) (dolist (listener (listeners broadcaster)) (funcall listener object))) Example subclass (defclass direct-broadcaster (broadcaster) ((latest-broadcast :accessor latest-broadcast) (latest-broadcast-p :initform nil)) (:documentation "I broadcast the latest broadcasted object when a new listener is added")) (defmethod add-listener :after ((broadcaster direct-broadcaster) listener) (when (slot-value broadcaster 'latest-broadcast-p) (funcall listener (latest-broadcast broadcaster)))) (defmethod broadcast :after ((broadcaster direct-broadcaster) object) (setf (slot-value broadcaster 'latest-broadcast-p) t) (setf (latest-broadcast broadcaster) object)) Example code Lisp> (let ((broadcaster (make-instance 'broadcaster))) (add-listener broadcaster #'(lambda (obj) (format t "I got myself a ~A object!~%" obj))) (add-listener broadcaster #'(lambda (obj) (format t "I has object: ~A~%" obj))) (broadcast broadcaster 'cheezburger)) I has object: CHEEZBURGER I got myself a CHEEZBURGER object! Lisp> (defparameter *direct-broadcaster* (make-instance 'direct-broadcaster)) (add-listener *direct-broadcaster* #'(lambda (obj) (format t "I got myself a ~A object!~%" obj))) (broadcast *direct-broadcaster* 'kitty) I got myself a KITTY object! Lisp> (add-listener *direct-broadcaster* #'(lambda (obj) (format t "I has object: ~A~%" obj))) I has object: KITTY Unfortunately, Lisp solves most of the design pattern problems (such as yours) by eliminating the need for them. A: In contrast to Herms' answer, I do see a loop. It's not a dependency loop, it's a a reference loop: LI holds the B object, the B object holds (an Array of) LI object(s). They don't free easily, and care needs to be taken to ensure that they free when possible. One workaround is simply to have the LI object hold a WeakReference to the broadcaster. Theoretically, if the broadcaster has gone away, there's nothing to deregister with anyway, so then your deregistration will simply check if there is a broadcaster to deregister from, and do so if there is. A: I'm not a java dev, but something like this: public class ListenerImpl implements Listener { public Foo() {} public void registerWithBroadcaster(Broadcaster b){ b.register(this); isRegistered = true;} public void callBack(Object arg) { if (!isRegistered) throw ... else ... } public void shutDown() { isRegistered = false; } } public class Broadcaster { private final List listeners = new ArrayList(); public void register(Listener lis) { listeners.add(lis); } public void unregister(Listener lis) {listeners.remove(lis); } public void broadcast(Object arg) { for (Listener lis : listeners) { if (lis.isRegistered) lis.callBack(arg) else unregister(lis); } } } A: Use weak references to break the cycle. See this answer. A: Here's an example in Lua (I use my own Oop lib here, see references to 'Object' in the code). Like in Mikael Jansson's CLOS example, your can use functions directly, removing the need of defining listeners (note the use of '...', it's Lua's varargs): Broadcaster = Object:subclass() function Broadcaster:initialize() self._listeners = {} end function Broadcaster:register(listener) self._listeners[listener] = true end function Broadcaster:unregister(listener) self._listeners[listener] = nil end function Broadcaster:broadcast(...) for listener in pairs(self._listeners) do listener(...) end end Sticking to your implementation, here's an example that could be written in any dynamic language I guess: --# Listener Listener = Object:subclass() function Listener:callback(arg) self:subclassResponsibility() end --# ListenerImpl function ListenerImpl:initialize(broadcaster) self._broadcaster = broadcaster broadcaster:register(this) end function ListenerImpl:callback(arg) --# ... end function ListenerImpl:shutdown() self._broadcaster:unregister(self) end --# Broadcaster function Broadcaster:initialize() self._listeners = {} end function Broadcaster:register(listener) self._listeners[listener] = true end function Broadcaster:unregister(listener) self._listeners[listener] = nil end function Broadcaster:broadcast(arg) for listener in pairs(self._listeners) do listener:callback(arg) end end
{ "language": "en", "url": "https://stackoverflow.com/questions/149439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: IIS 6, Wildcard Application Mapping, and FrontPage While I'd love to get rid of requiring FrontPage Extensions on a heavy traffic site I host, the client requires it to administrate the site. Having just implemented Wildcard Application Mapping in IIS 6 on this site in order to provide integrated Forms Authentication security between ASP and ASP.NET resources, this breaks FrontPage extensions. Everything works like a charm, including encrypting and caching roles that are now available even to ASP, except for the loss of FrontPage. Specifically, you cannot even login to FrontPage administration (incorrect credentials). Has anyone gotten FrontPage to work with Wildcard Application Mapping routing through the ASP.NET 2.0 aspnet_isapi.dll? UPDATE: I've marked @Chris Hynes answer even though I have not had the time to test (and the current configuration is working for the client). It makes sense and goes along with what I thought was occurring and possibly how to deal with, but did not know where to route the request at that point (fpadmdll.dll). Much thanks! A: The issue here sounds like the wildcard mapping is taking precedence over the frontpage extensions ISAPI handler and/or messing up the request/response for that. I'd try creating a handler that does nothing and mapping it to fpadmdll.dll. Something like this: namespace YourNamespace { public IgnoreRequestHandler : IHttpHandler { public IsReusable { get { return true; } } public void ProcessRequest(HttpContext context) { } } } Then map it up in the web.config: <httpHandlers> <add verb="*" path="fpadmdll.dll" type="YourNamespace.IgnoreRequestHandler, YourDll" /> </httpHandlers>
{ "language": "en", "url": "https://stackoverflow.com/questions/149458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem with vector inside a class I have this code inside a class: void SendStones() { int currenthole = hole; int lastplace = 0; for(int i=0;i<stns.size();i++) { while(1) {//Calculate new currenthole if(currenthole == 13) { currenthole = 7; break;} if(currenthole == 14) { currenthole = 6; break;} if((currenthole<=12 && currenthole > 7) || (currenthole<=6 && currenthole > 1)) { currenthole--; break;} } lastplace = stns.size()-1; hole[currenthole]->ReciveStone(stns[lastplace]);//PROBLEM stns.pop_back(); } } vector<Stones*> stns; so it makes this error: invalid types `int[int]' for array subscript what's the problem?i don't understand. Thanks. A: It looks like hole is a simple int, and you're trying to subscript it. Is that what you mean to do? Where is hole declared? A: Hole is a really big class, SendStones is a function member in the class. I won't send the whole file but i can say that hole[currenthole] is a Hole *hole[14]; It's a big program and project so i sent the related code needed. Here's the code of the ReciveStones function: void ReciveStone(Stone *rcvstone) { stns.push_back(rcvstone); } A: Based on what you said in your answer, hole is a pointer to n Hole objects. That means your code isn't doing what you think it's doing. int currenthole = hole; This is storing an address value pointing to the first object in your array collection, which means that this code if(currenthole == 13) { currenthole = 7; break;} if(currenthole == 14) { currenthole = 6; break;} if((currenthole<=12 && currenthole > 7) || (currenthole<=6 && currenthole > 1)) { currenthole--; break;} is probably nonsense. It doesn't explain why you're getting the "invalid types `int[int]' for array subscript" error. Are you sure that there's not a second declaration of type int named hole? --Actually, re-reading what you wrote, I'm even more certain you're not doing what you think you're doing. SendStones is a member of the class Hole, correct? Check that your Hole class doesn't have a hole member variable inside it. That is probably the problem, since it will be found before any global variable called hole (if I remember my scoping rules correctly).
{ "language": "en", "url": "https://stackoverflow.com/questions/149463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I have a 100+MB XML file (sans-DTD/Schema). XSLT won't have it. Strategies for transforming/parsing? This XML file contained archived news stories for all of last year. I was asked to sort these stories by story categor[y|ies] into new XML files. big_story_export.xml turns into lifestyles.xml food.xml nascar.xml ...and so on. I got the job done using a one-off python script, however, I originally attempted this using XSLT. This resulted in frustration as my XPATH selections were crapping the bed. Test files were transformed perfectly, but putting the big file up against my style sheet resulted in ...nothing. What strategies do you recommend for ensuring that files like this will run through XSLT? This was handed to me by a vendor, so imagine that I don't have a lot of leverage when it comes to defining the structure of this file. If you guys want code samples, I'll put some together. If anything, I'd be satisfied with some tips for making XML+XSLT work together smoothly. @Sklivvz I was using python's libxml2 & libxslt to process this. I'm looking into xsltproc now. It seems like a good tool for these one-off situations. Thanks! @diomidis-spinellis It's well-formed, though (as mentioned) I don't have faculties to discover it's validity. As for writing a Schema, I like the idea. The amount of time I invest in getting this one file validated would be impractical if it were a one-time thing, though I foresee having to handle more files like this from our vendor. Writing a schema (and submitting it to the vendor) would be an excellent long-term strategy for managing XML funk like this. Thanks! A: The problem with using XSLT to process arbitrarily large XML documents is that XSLT processing begins by parsing the input document into a source tree. This tree gets parsed into memory. This means that eventually you'll encounter an input document large enough to cause problems even if you're using a robust XSLT processor like Saxon and you have plenty of virtual memory. (It may still work, but it'll be slow.) Another reason not to use XSLT for this is that you're producing multiple output documents, which (based on what you've said so far) means you're making multiple passes over your input document. It may (depending on a lot of factors about your situation that I don't know about) be better to take a SAX-based approach instead of using XSLT. Using a SAX processor, you may be able to write a method that makes a single, forward-only pass through the source document, parsing it as it goes, and writes all of the output documents as it encounters the elements that contain them. A: This sounds like a bug in the large XML file or the XSLT processor. There are two things you should check on your file. * *Is the file well-formed XML? That is, are all tags and attributes properly terminated and matched? An XML processor, like xmlstarlet, can tell you that. *Does the file contain valid XML? For this you need a schema and an XML validator (xmlstarlet can do this trick as well). I suggest you invest some effort to write the schema definition of your file. It will simplify a lot your debugging, because you can then easily pinpoint the exact source of problems you may be having. If the file is well-formed and valid, but the XSLT processor still refuses to give you the results you would expect, you can be sure that the problem lies in the processor, and you should try a different one. A: What language/parser were you using? For large files I try to use Unix command line tools. They are usually much, much more efficient than other solutions and don't "crap out" on large files. Try using xsltproc A: Can I recommend Saxon XSLT processor - I know for a fact it can handle large files, provided you give the Java JVM enough memory. Another thing is that there may be optimisations n your XSLT that could help, but its hard to make blanket statements about things like that. A: Check out Apache's Xalan C++. In my experience, where others (including Saxon) have failed on "large" XML files (>600 MB), this was able to run with memory to spare.
{ "language": "en", "url": "https://stackoverflow.com/questions/149474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding a caption to an equation in LaTeX Well, it seems simple enough, but I can't find a way to add a caption to an equation. The caption is needed to explain the variables used in the equation, so some kind of table-like structure to keep it all aligned and pretty would be great. A: The \caption command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example: \begin{figure} \[ E = m c^2 \] \caption{A famous equation} \end{figure} The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The \captionof command of the caption package can be used to place a caption outside of a floating environment. It is used like this: \[ E = m c^2 \] \captionof{figure}{A famous equation} This will also produce an entry for the \listoffigures, if your document has one. To align parts of an equation, take a look at the eqnarray environment, or some of the environments of the amsmath package: align, gather, multiline,... A: You may want to look at http://tug.ctan.org/tex-archive/macros/latex/contrib/float/ which allows you to define new floats using \newfloat I say this because captions are usually applied to floats. Straight ahead equations (those written with $ ... $, $$ ... $$, begin{equation}...) are in-line objects that do not support \caption. This can be done using the following snippet just before \begin{document} \usepackage{float} \usepackage{aliascnt} \newaliascnt{eqfloat}{equation} \newfloat{eqfloat}{h}{eqflts} \floatname{eqfloat}{Equation} \newcommand*{\ORGeqfloat}{} \let\ORGeqfloat\eqfloat \def\eqfloat{% \let\ORIGINALcaption\caption \def\caption{% \addtocounter{equation}{-1}% \ORIGINALcaption }% \ORGeqfloat } and when adding an equation use something like \begin{eqfloat} \begin{equation} f( x ) = ax + b \label{eq:linear} \end{equation} \caption{Caption goes here} \end{eqfloat} A: As in this forum post by Gonzalo Medina, a third way may be: \documentclass{article} \usepackage{caption} \DeclareCaptionType{equ}[][] %\captionsetup[equ]{labelformat=empty} \begin{document} Some text \begin{equ}[!ht] \begin{equation} a=b+c \end{equation} \caption{Caption of the equation} \end{equ} Some other text \end{document} More details of the commands used from package caption: here. A screenshot of the output of the above code:
{ "language": "en", "url": "https://stackoverflow.com/questions/149479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "54" }
Q: How do I execute conditional logic based upon the type passed to a VB.NET generic method I want to create a VB.NET generic factory method that creates instances of classes (as a home-grown inversion of control container). If I pass the interface IDoSomething as the generic parameter, I want to return an instance of DoSomething (that implements IDoSomething). I cannot figure out the syntax of the if statement. I want to write something like: Public Function Build(Of T) as T If T Is IDoSomething then Return New DoSomething() ElseIf T Is IAndSoOn Then Return New AndSoOn() Else Throw New WhatWereYouThinkingException("Bad") End If End Sub But this code does not compile. A: Public Function Build(Of T) As T Dim foo As Type = GetType(T) If foo Is GetType(IDoSomething) Then Return New DoSomething() ... End If End Function A: Public Function Build(Of T) as T If T.gettype Is gettype(IDoSomething) then Return New DoSomething() ElseIf T.gettype Is gettype(IAndSoOn) Then Return New AndSoOn() Else Throw New WhatWereYouThinkingException("Bad") End If End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/149484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to store configuration parameters in SVN? Like many projects, we deploy to many environments, QA, UA, Developer trunks, etc.. What is the best way to store sensitive configuration parameters in SVN? Or, should you not and just maintain a smaller unversioned file with credentials in it on the server? Mainly, we do not want to expose production credentials to every developer. A: I'd rather provide configuration examples than real config files. In my project there is setup.default.php file in root directory that every user need to copy as setup.php and amend to match local environment. Additionally, to prevent checking in back customised setup files there is a rule for it in .svnignore. $ echo 'setup.php' > .svnignore $ svn propset svn:ignore -F .svnignore . A: This is a problem I have run into as well. I think the answer is to check in a Template (such as you have with setup.php.default) and then use an automated tool such as Phing to make the push to development. If you use recognizable tokens in the setup.php file then Phing will be able to replace these tokens with individual server values. Also, an easy one step push live will be a helpful process to have. A: I would not store configuration information in the repository at all. That way you don't have to worry about SVN trying to update the config when you update your source. A: I would agree with adam. If its not something that benefits everybody who works on the project, it shouldn't be under version control. If somebody checks out a copy of your code, will your personal project files help them? Probably not. It would most likely just clutter things up.
{ "language": "en", "url": "https://stackoverflow.com/questions/149485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Disk-backed STL container classes? I enjoy developing algorithms using the STL, however, I have this recurring problem where my data sets are too large for the heap. I have been searching for drop-in replacements for STL containers and algorithms which are disk-backed, i.e. the data structures on stored on disk rather than the heap. A friend recently pointed me towards stxxl. Before I get too involved with it... Are any other disk-backed STL replacements available that I should be considering? NOTE: I'm not interested in persistence or embedded databases. Please don't mention boost::serialization, POST++, Relational Template Library, Berkeley DB, sqlite, etc. I am aware of these projects and use them when they are appropriate for my purposes. UPDATE: Several people have mentioned memory-mapping files and using a custom allocator, good suggestions BTW, but I would point them to the discussion here where David Abraham suggests that custom iterators would be needed for disk-backed containers. Meaning the custom allocator approach isn't likely to work. A: I've never had to do anything quite like this, but It might be possible to do what you want to do by writing a custom allocator that makes use of a memory mapped files to back your data. See boost::interprocesses for docs on their easy to use implementation of memory mapped files, this Dr. Dobbs article for a detailed discussion on writing allocators, and this IEEE Software column for a description of the problem and example code. A: If (as you write) you're not interested in persistence the simplest solution would be to increase your heap size and use your operating system's virtual memory facilities. The part of the heap that will not fit in your computer's physical memory will end up being paged on disk, giving you exactly what you want: normal STL access to data often stored on disk. The operating system will take care of caching the most used pages in the physical memory and evicting to disk those you don't use a lot. Your code will remain the same, and you can increase its performance simply by adding more physical memory. To increase your heap size check your operating system's parameters, like ulimit(1) on Unix systems and System properties - Advanced - Performance - Advanced - Virtual Memory on Windows XP. If you've hit the 32-bit 4GB limit consider moving to a 64 bit architecture or compiling your program for 64 bits. A: I don't know much about the subject, but it might be possible to write an STL-like interface to a memory mapped file? edit: This approach might be suitable if you're trying to get at a specific part of a huge file. If you're attempting to do something with the entire file, you'll likely generate a huge number of page faults as you read in uncached parts of the file. A: I have implemented some thing very similar. Implementing the iterators is the most challenging. I used boost::iterator_facade to implement the iterators. Using boost::iterator_facade you can easy adapt any cached on disk data structures to have a STL container interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/149488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: Pascal casing or Camel Casing for C# code? I've been arguing with my coworkers about Pascal casing (upper camel case) vs. lower CamelCasing. They are used to lower camel casing for everything from table names in SQL databases to property naming in C# code but I like Pascal casing better, lower camel casing for variables and Pascal casing for properties: string firstName; public string FirstName { ... } But they are used to this: string _firstname; public string firstName { ... } I try to keep up with their "standard" so the code looks the same but I just don't like it. I've seen that at least the .NET framework uses this convention and that is how I try to keep my code, e.g.: System.Console.WriteLine("string") What do you use/prefer and why? I'm sorry if somebody else asked this question but I searched and did not find anything. Update: I've given a method example and not a property but it's the same. As I stated in the first paragraph my colleagues use the Pascal convention for everything (variables, methods, table names, etc.) A: A link to the official design guidelines might help. Specifically, read the section on Capitalization styles. In the grand scheme of things, Pascal vs Camel doesn't matter that much and you're not likely to convince anyone to go back over an existing code base just to change the case of names. What's really important is that you want to be consistent within a given code base. I'm just happy as long as you're not using Hungarian. A: I use what the Framework uses, as it's the de-facto best practice. However, so long as the code in your company is consistently using their style, then you're much better off getting used to it. If every developer has their own standard, then there's no standard at all. A: I (and my team) prefer to reserve initial capitals for class names. Why? Java standards propagating, I think. A: You should have a look at Microsoft's new tool, StyleCop for checking C# source code. Also keep an eye on FxCop for checking compiled .Net assemblies. FxCop focuses more on the details of what the code does, not the layout, but it does have some naming rules related to publicly visible names. StyleCop defines a coding standard, which is now being promoted by Microsoft as an industry standard. It checks C# source code against the standard. StyleCop adheres to your PascalCase style. Getting people onto StyleCop (or any other standard for that matter) can be hard, it's quite a hurdle, and StyleCop is quite exhaustive. But code should be to a uniform standard - and a personal standard is better than none, company standard is better than a personal one, and an industry standard is best of all. It's a lot easier to convince people when a a project starts - team is being formed and there is no existing code to convert. And you can put tools (FxCop, StyleCop) in place to break the build if the code does not meet standards. You should use the standard for the language and framework - SQL code should use SQL standards, and C# code should use C# standards. A: For public interfaces you should stick with the MS .NET framework design guidelines: "Capitalization Conventions". For non-exposed members then whatever you and your colleagues can agree on. A: From .NET Framework Developer's Guide Capitalization Conventions, Case-Sensitivity: The capitalization guidelines exist solely to make identifiers easier to read and recognize. Casing cannot be used as a means of avoiding name collisions between library elements. Do not assume that all programming languages are case-sensitive. They are not. Names cannot differ by case alone. A: I just found Coding Standards for .Net. A: Pascal casing should be used for Properties. As far as varible names go, some people use _ and some poeple use m_ and some people just use plain old camel casing. I think that as long as you ae consistant here, it shouldn't matter. A: That example of .NET you posted was a function. The adopted "standard" for methods/functions is A capped camel-case (or Pascal, if you want to call it that). I stick to camel case where I can. It lets you easily know the difference between a variable and a method. Additionally, I'm a fan of sticking an underscore in front of local class variables. E.g.: _localVar. A: I guess you have to put up with what the coding standard says for your place of work, however much you personally dislike it. Maybe one day in the future you will be able to dictate your own coding standards. Personally I like databases to use names of the form "fish_name", "tank_id", etc for tables and fields, whereas the code equivalent of the database model would be "fishName" and "tankID". I also dislike "_fooname" naming when "fooName" is available. But I must repeat that this is subjective, and different people will have different ideas about what is good and bad due to their prior experience and education. A: Actually, there's no "standard" convention on this. There's a Microsoft edited guideline somewhere, and as with with any other naming convention guideline, surely there's another one refuting it, but here's what I've come to understand as "standard C# casing convention". * *PerWordCaps in type names (classes, enums), constants and properties. *camelCase for really long local variables and protected/private variables *No ALL_CAPS ever (well, only in compiler defines, but not in your code) *It seems some of the system classes use underscored names (_name) for private variables, but I guess that comes from the original writer's background as most of them came straight from C++. Also, notice that VB.NET isn't case sensitive, so you wouldn't be able to access the protected variables if you extended the class. Actually, FxCop will enforce a few of those rules, but (AFAIK) it ignores whatever spelling you use for local variables. A: I like the coding conventions laid out in the Aardvark'd project spec A: The day when i quit programming - its when Microsoft will make CamelCase in C# as standard. Because my grown logic has many reasons for PascalCase, unlike kid's logic, who cares only shorter names or easier to write. And BTW: CamelCasing comes primarily from C++ STD library style, the native old language inherited from C. So Java inherited from C++. But C# - is entirely new language - clean and beauty, with new rules. Oldfags must programm on Java or C++, new generation people must programm on C# - and they should never interact. Consider this example: 1) PascalCase: list.Capacity.ToString(); 2) CamelCase: list.capacity.toString(); In (1) we have CAMEL CASE in long TERM!!! means listCapacityToString. In (2) we have bullshit: listcapacitytoString. Thats how i read. And why CamelCase is illogical for itselt. I could kill for PascalCase, never touch it, kids of any age. Microsoft - forever or until they use PascalCase. A: Whichever you prefer is what matters, obviously adhering to the team's standard primarily. In private you code however you want, it doesn't affect the finished product whether you named your variable someVariable or SomeVariable.
{ "language": "en", "url": "https://stackoverflow.com/questions/149491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: What does the comma operator do? What does the following code do in C/C++? if (blah(), 5) { //do something } A: Comma operator is applied and the value 5 is used to determine the conditional's true/false. It will execute blah() and get something back (presumably), then the comma operator is employed and 5 will be the only thing that is used to determine the true/false value for the expression. Note that the , operator could be overloaded for the return type of the blah() function (which wasn't specified), making the result non-obvious. A: If the comma operator is not overloaded, the code is similar to this: blah(); if (5) { // do something } If the comma operator is overloaded, the result will be based on that function. #include <iostream> #include <string> using namespace std; string blah() { return "blah"; } bool operator,(const string& key, const int& val) { return false; } int main (int argc, char * const argv[]) { if (blah(), 5) { cout << "if block"; } else { cout << "else block"; } return 0; } (edited to show comma operator overloading scenario. thanks to David Pierre for commenting on this) A: I know one thing that this kind of code should do: it should get the coder fired. I would be quite a bit afraid to work next to someone who writes like this. A: In the pathological case, it depends on what the comma operator does... class PlaceHolder { }; PlaceHolder Blah() { return PlaceHolder(); } bool operator,(PlaceHolder, int) { return false; } if (Blah(), 5) { cout << "This will never run."; } A: I would say that depends on blah(). A: On a more broad answer. The comma operator (non overloaded) resolves as in, execute the first part and return the second part. So if you have (foo(),bar()) Both functions will be executed, but the value of the expression evaluates to bar() (and the type of the expression as well). While I won't say there are fair usages for that, is usually considered a bit hard to read code. Mainly because not many languages shares such constructs. So As a personal rule of thumb I avoid it unless I am adding code to a preexistent expression and don't want to change completely its format. Example: I have a Macro (not discussing if you should use macros or not, sometimes its not even you that wrote it) FIND_SOMETHING(X) (x>2) ? find_fruits(x) : find_houses(x) And I usually use it in assignments like my_possession = FIND_SOMETHING(34); Now I want to add log to it for debuggin purposes but I cannot change the find functions,. I could do : FIND_SOMETHING(X) (x>2)? (LOG("looking for fruits"),find_fruits(x)):(LOG("looking for houses"),find_houses(x)) A: The following was written assuming it is C code, either in a C file or within a C block of a C++ file: It is a pointless if. It will call blah(), however the result of blah() is not considered by if at all. The only thing being considered is 5, thus the if will always evaluate to true. IOW you could write this code as blah(); // do something without any if at all. A: I use sometimes constructs like this for debugging purposes. When I force the if close to be true regardless of the return value of blah. It's obvious that it should never appear in production code.
{ "language": "en", "url": "https://stackoverflow.com/questions/149500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "40" }
Q: annotation based Spring bean validation I'm investigating an annotation-based approach to validating Spring beans using spring modules. In this tutorial, the following bean (getters and setters omitted) is used as an example: public final class User { @NotBlank @Length(max = 80) private String name; @NotBlank @Email @Length(max = 80) private String email; @NotBlank @Length(max = 4000) private String text; } The error message that is used if a particular validation rule is disobeyed should follow this format: bean-class.bean-propery[validation-rule]=Validation Error message Examples for the class shown above include: User.email[not.blank]=Please enter your e-mail address. User.email[email]=Please enter a valid e-mail address. User.email[length]=Please enter no more than {2} characters. The fact that the message keys contain the class name presents a couple of problems: * *If the class is renamed, the message keys also need to be changed *If I have another class (e.g. Person) with an email property that is validated identically to User.email, I need to duplicate the messages, e.g. Person.email[not.blank]=Please enter your e-mail address. Person.email[email]=Please enter a valid e-mail address. Person.email[length]=Please enter no more than {2} characters. In fact, the documentation claims that is possible to configure a default message for a particular rule (e.g. @Email) like this: email=email address is invalid This default message should be used if a bean-specific message for the rule cannot be found. However, my experience is that this simply does not work. An alternative mechanism for avoiding duplicate messages is to pass the key of the error message to the rule annotation. For example, assume I have defined the following default error message for the @Email rule badEmail=Email address is invalid This message should be used if I annotate the relevant property like this: @Email(errorCode="badEmail") private String email; However I tried this, out and again, it just doesn't seem to work. Has anyone found a way to avoid duplicating error messages when using this validation framework? A: I took a quick look at the BeanValidator API, and it looks like you might want to try the errorCodeConverter property. You would need to implement your own ErrorCodeConverter, or use one of the provided implementations? .... <bean id="validator" class="org.springmodules.validation.bean.BeanValidator" p:configurationLoader-ref="configurationLoader" p:errorCodeConverter-ref="errorCodeConverter" /> <bean id="errorCodeConverter" class="contact.MyErrorCodeConverter" /> .... Note: configurationLoader is another bean defined in the config XML used in the tutorial Example converter: package contact; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springmodules.validation.bean.converter.ErrorCodeConverter; public class MyErrorCodeConverter implements ErrorCodeConverter { private Log log = LogFactory.getLog(MyErrorCodeConverter.class); @Override public String convertPropertyErrorCode(String errorCode, Class clazz, String property) { log.error(String.format("Property %s %s %s", errorCode, clazz.getClass().getName(), property)); return errorCode; // <------ use the errorCode only } @Override public String convertGlobalErrorCode(String errorCode, Class clazz) { log.error(String.format("Global %s %s", errorCode, clazz.getClass().getName())); return errorCode; } } Now the properties should work: MyEmailErrorCode=Bad email class Foo { @Email(errorCode="MyEmailErrorCode") String email } A: Spring validation does have an ErrorCodeConverter that does this: org.springmodules.validation.bean.converter.KeepAsIsErrorCodeConverter When this is used, the resource bundle will be checked for the following codes: [errorCode.commandBeanName.fieldName, errorCode.fieldName, errorCode.fieldClassName, errorCode] * *errorCode is the actual validation errorCode eg. not.blank, email. *commandBeanName is the same as the model key name that references the form backing bean. *fieldName is the name of the field. *fieldClassName is the field class name eg. java.lang.String, java.lang.Integer So for instance if I have a bean that is referenced in the model by the key "formBean" and the field emailAddress of type java.lang.String does not contain an email address, which causes the errorCode email. The validation framework will attempt to resolve the following message codes: [email.formBean.emailAddress, email.emailAddress, email.java.lang.String, email] If the errorCode is replaced by the errorCode "badEmail" like this: @Email(errorCode="badEmail") The messages codes that the framework will try resolve will be: [badEmail.formBean.emailAddress, badEmail.emailAddress, badEmail.java.lang.String, badEmail] I would suggest keeping the errodCode the same. Thus one message can be used for all fields that have that errorCode associated with them. If you need to be more specific with the message for a certain field you can add a message to the resource bundles with the code errorCode.commandBeanName.field. A: Add the following beans in your applicationContext.xml file. <bean id="configurationLoader" class="org.springmodules.validation.bean.conf.loader.annotation.AnnotationBeanValidationConfigurationLoader" /> <!-- Use the error codes as is. Don't convert them to <Bean class name>.<bean field being validated>[errorCode]. --> <bean id="errorCodeConverter" class="org.springmodules.validation.bean.converter.KeepAsIsErrorCodeConverter"/> <!-- shortCircuitFieldValidation = true ==> If the first rule fails on a field, no need to check other rules for that field --> <bean id="validator" class="org.springmodules.validation.bean.BeanValidator" p:configurationLoader-ref="configurationLoader" p:shortCircuitFieldValidation="true" p:errorCodeConverter-ref="errorCodeConverter"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/149506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: "Submit" button works in Firefox 3 but not in IE7 (ASP 1.1) I have code from an old website that I needed to modify. There are two pages that I modified some form code in. I modified the max length of a textbox and I modified slightly a line or two of code in a function. The "btnSubmit_Click" function as it happens. With the new code FTPed up on the webserver, when I click on the "Submit" button using Firefox 3, the button does what it is supposed to do. With IE7, nothing happens. No page load, no refresh, no error, no nothing. IE isn't busy, it doesn't time out, it does nada. On my development laptop however, when I run the project, the submit button works in IE7 as it is supposed to do. Any thoughts? Response to Mecki: It is method=POST, but it is a JavaScript postback thing alright. Also I checked the outputted HTML and the Submit button has a JS "onclick" event: onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(); " Absolutely though all the required fields have what they need. The validation also works as when I test it by leaving out info from a required field IE7 asks me to fill in the data. Strange one. A: The question was not complete, I left out a detail which in hindsight is very important: I also was moving the site from one host to another. The issue seems to have been differing versions of the Validating JavaScript code. I fixed the issue by copying the aspnet_client\systemweb\1_1_4322\*.* directory from the root of IIS to the root of the website. The website I had transferred, already had code in this directory and it must have been a different Build version or something from the ASP running on the new server. Apologies Mecki, if I was any good with JavaScript your answer would have lead me in the right direction, I'd say. Simon, it was while investigating your idea that I noticed the javascript includes for aspnet_client. End of the day the issue was fixed with trial and error on my part so I don't absolutely know what caused my problem. Thanks for helping. A: I've just seen exactly the same problem when porting an ASP site to ASP.NET. I have a form that submits just fine in Firefox, Safari, Chrome - but does absolutely nothing in IE or Opera. Like your form, it's not doing anything, not throwing any errors etc - it simply sits there doing nothing. Unlike your form, this is a plain old postback - it's not using anything client-side to trigger the form submission, no client-side validation etc. If I attach an onclick handler to the submit button, I can see that the button is being clicked - but if I attach an onsubmit handler to the form, I get nothing. If I make the button onclick handler submit the form through JavaScript, it works fine - it's just the direct submission that's not working. After banging my head against the desk for a while, I realised that there was another form on the page - in this case created by a function in a separate class, so out of sight and out of mind. In ASP, there was no problem - the two forms were separate. ASP.NET, of course, had wrapped the page in it's own form and HTML doesn't allow nested forms. I'd removed the form tags around the main form that I was working with, but I'd overlooked the second form because it was elsewhere on the page and elsewhere in the code. So IE and Opera were ignoring the nested form (correctly, I assume) but Firefox et al were being more forgiving and allowing the form to submit. This is a classic example of an error that one wouldn't make when writing the code from scratch but that's all too easy to make when porting code in bulk where something written long ago has a side effect that's not immediately visible in the code you're working on. This may or may not be related to your problem, but it might help anyone else with a similar problem who comes across this question looking for possible answers. A: Remove more than one <form> tag from the page. asp.NET allows only one <form> tag into the page. A: Is the submit button really submitting the form (sending out a post/get) or is it calling JavaScript code to perform checks or other actions? If so, my first guess is some JS error happening. You should have a look at the JS console? (In case IE has one, not using IE myself, however, according to this MS page, it has one, you just need to enable it). A: I just had the same problem. Just make sure you don't nest tags. Or if you are doing this with a google search box you can check out this guide for a work around: http://www.codeproject.com/KB/aspnet/CustomSearchEngine.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/149530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is StringBuilder's RAM consumption like? We have a few operations where we are doing a large number of large string concatenations, and have recently encountered an out of memory exception. Unfortunately, debugging the code is not an option, as this is occurring at a customer site. So, before looking into a overhaul of our code, I would like to ask: what is the RAM consumption characteristics of StringBuilder for large strings? Especially as they compare to the standard string type. The size of the strings are well over 10 MB, and we seem to run into the issues around 20 MB. NOTE: This is not about speed but RAM. A: Here is a nice study about String Concatenation vs Memory Allocation. If you can avoid concatenating, do it! This is a no brainer, if you don't have to concatenate but want your source code to look nice, use the first method. It will get optimized as if it was a single string. Don't use += concatenating ever. Too much changes are taking place behind the scene, which aren't obvious from my code in the first place. I advise to rather use String.Concat() explicitly with any overload (2 strings, 3 strings, string array). This will clearly show what your code does without any surprises, while allowing yourself to keep a check on the efficiency. Try to estimate the target size of a StringBuilder. The more accurate you can estimate the needed size, the less temporary strings the StringBuilder will have to create to increase its internal buffer. Do not use any Format() methods when performance is an issue. Too much overhead is involved in parsing the format, when you could construct an array out of pieces when all you are using are {x} replaces. Format() is good for readability, but one of the things to go when you are squeezing all possible performance out of your application. A: You might be interested by the ropes data structure. This article: Ropes: Theory and practice explains their advantages. Maybe there is an implementation for .NET. [Update, to answer the comment] Does it use less memory? Search memory in the article, you will find some hints. Basically, yes, despite the structure overhead, because it just adds memory when needed. StringBuilder, when exhausting old buffer, must allocate a much bigger one (which can already waste empty memory) and drops the old one (which will be garbage collected, but can still use lot of memory in the mean time). I haven't found an implementation for .NET, but there is at least a C++ implementation (in SGI's STL: http://www.sgi.com/tech/stl/Rope.html). Maybe you can leverage this implementation. Note the page I reference have a work on memory performance. Note that Ropes aren't the cure to all problems: their usefulness depends heavily how you build your large strings, and how you use them. The articles point out advantages and drawbacks. A: Each time StringBuilder runs out of space, it reallocates a new buffer twice the size of the original buffer, copies the old characters, and lets the old buffer get GC'd. It's possible that you're just using enough (call it x) such that 2x is larger than the memory you're allowed to allocate. You may want to determine a maximum length for your strings, and pass it to the constructor of StringBuilder so you preallocate, and you're not at the mercy of the doubling reallocation. A: Strigbuilder is a perfectly good solution to memory problems caused by concatenating strings. To answer your specific question, Stringbuilder has a constant-sized overhead compared to a normal string where the length of the string is equal to the length of the currently-allocated Stringbuilder buffer. The buffer could potentially be twice the size of the string that results, but no more memory allocations will be made when concatenating to the Stringbuilder until the buffer is filled, so it is really an excellent solution. Compared with string, this is outstanding. string output = "Test"; output += ", printed on " + datePrinted.ToString(); output += ", verified by " + verificationName; output += ", number lines: " + numberLines.ToString(); This code has four strings that stored as literals in the code, two that are created in the methods and one from a variable, but it uses six separate intermediate strings which get longer and longer. If this pattern is continued, it will increase memory usage at an exponential rate until the GC kicks in to clean it up. A: I don't know about the exactly memory pattern of string builder but the common string is not an option. When you use the common string every concatenation creates another couple of string objects, and the memory consumption skyrocket, making the garbage collector being called too often. string a = "a"; //creates object with a a += "b" /creates object with b, creates object with ab, assings object with ab to "a" pointer
{ "language": "en", "url": "https://stackoverflow.com/questions/149551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Using Subsonic for potentially heavily accessed ASPNET MVC Application I am about to start a project for a potentially heavily accessed ASPNET MVC application and I was thinking to use Subsonic for my DAL. I have some concern about the ability of Subsonic to handle thousands of concurrent requests. Can anyone give me some examples of popular web sites using Subsonic? Also if you have any suggestion regarding a possible substitute to Subsonic, besides NHibernate, that would be great as well. Thanks A: Thousands of concurrent requests? Are you sure that's likely? For what it's worth, DotNetKicks uses SubSonic, and never seems to have performance issues. A: I do about 4-5M requests a month through SubSonic without an issue, in fact it is super-quick and my server is hardly taxed. Those requests peak during the day so while we don't get up to 1000 concurrent requests I have been very impressed with SubSonic under load. Because it uses generated code it is actually going to be faster than most of the ORM you find out there. A: SubSonic is a tool and you have to use it wisely like adding Caching to your site and closing the IDataReader if you use them sometimes. A: As a guideline, if you have 1000 users, you won't have more than 1 or 2 concurrent users. At least in my experience. To have 1K concurrent users you should have at least 500K-1M users.
{ "language": "en", "url": "https://stackoverflow.com/questions/149557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Python desktop widgets I'm interested in making desktop widgets, similar to Apple's Dashboard or what Vista has. I'd like to make them cross-platform, if possible. Opera's widgets are cross-platform but require the user to have Opera installed, so that's a big limitation. I know most widgets are made with HTML/XML, CSS, and Javascript. Is there a way to create them using Python? Update: I did find a site talking about Pyjamas. Does anyone have experience with it and, if so, what are its capabilities/limitations? A: You should take a look at what the guys at Digsby are doing. Basically, they've written a port of WebKit to wxWidgets, and then use WebKit to render the interface, and wxPython for writing the rest of the app. Pretty neat, but very alpha at the moment. A: Take a look at gDesklets. AFAIK they're UNIX only, but mabybe porting them to other platforms make more sense than starting from scratch? They use python to create widgets (desklets). A: Screenlets is designed for this task. The Screenlets project is both a Python framework to simplify writing Cairo-drawn desktop widgets, similar to those found in the "Dashboard" feature of OS:X. Widgets can be written entirely in Python. A collection of widgets using the framework have already been developed. It is designed to work with Linux desktop. But it should be easy to port to other platforms, since Cairo is cross-platform, in my opinion. Disadvantages * *It's not updated frequently. The latest version, 0.1.6, was released on 2012-01-27 *Its home page has been down for some time. Launchpad works though. *Only Python 2 is supported. A: You can check out PyGTK, which will allow you to create desktop widgets, but they won't be managed by OSX's Dashboard. If you'd like to develop an OSX widget, you'll want to stick with HTML/CSS/JavaScript. A: Take a look at pyqt4. It has webkit integration. I was looking into this myself but haven't really had time to dig into the API.
{ "language": "en", "url": "https://stackoverflow.com/questions/149559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I write .NET unit tests? How do I write unit tests in .NET? Specifically Visual Studio 2005? A: If you're using one of the Visual Studio Team Suite products, you reference Microsoft.VisualStudio.TestTools.UnitTesting, decorate your test classes with the TestClass attribute, and decorate your test methods with the TestMethod attribute. The approach for NUnit is similar, except that you reference NUnit.Framework, the class will be decorated with TestFixture, and the test methods will be decorated with Test. A: If you decide for NUnit then it might be a good idea to take a look at testdriven.net since it offers a really nice integration with Visual Studio. There are multiple other unit test frameworks currently available. I would recommend you to consider xUnit. I know what you're thinking: "Why another unit test framework?". It is true that it is nothing that exceptionally better but still. Take a look at this blog post and if you decide you can use ReSharper plug-in for Visual Studio integration. A: You can either use one of the Team Suite products, or use a 3rd party tool like NUnit. A: Here's a basic idea using NUnit Create a test project. Reference the main project for your application in the test project. Create a test class in the test project. Add Imports nunit.Framework Decorate the class with <TestFixture()> E.g. <TestFixture()> Public Class MyTestClass ... Create test methods, each decorated with <Test()> and add your tests: <Test()> _ Public Sub harness() Assert.IsTrue(False) End Sub Build your test project. Open NUnit and open your test project there. Click 'run' Green is pass, Red is Fail. The 'harness' test above is merely to prove that you've hooked everything up before you start testing your own stuff. Once it's hooked up properly (and you get a fail on the test) switch to 'true' and NUnit should show green. From here, you start to add tests for your own project. A: There are plenty of ways you can write units tests. Not sure if you're asking about tools to perform the unit testing or if you're wondering about the process of unit testing. NUnit is a popular testing tool. Microsoft's MSTest which you can use along with Visual Studio Team Suite products is also very nice. I recommend reading about continuous integration if you plan on doing a lot of testing. As far as actually writing tests is concerned that is a very complicated topic for StackOverflow. I recommend reading articles about testing. There are plenty out there that cover this topic. A: In my opinion, MBUnit is the way to go. It's vastly superior to NUnit (very similar, but with Row Tests and Transaction support) and other MS tools (Team Suite was not really successful, I would discourage its use). MbUnit provides advanced unit testing support with advanced fixtures to enable developers and testers to test all aspects of their software. A: +1 on MbUnit and efinetly use testdriven.net i found it much faster particularly for datamodel tests A: SpecUnit makes a good addition to NUnit for BDD style unit tests. I really like the idea of having tests in a class called something like "When_x_happens", and the methods in that class describe the expected results for when x happens - "foo_should_do_bar()". SpecUnit also has a tool for generating reports from your tests, which is a great source of documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/149569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Continuations in Ruby Has anyone ever done work to get Ruby to do continuations (like Seaside on Smalltalk)? A: As others have said already, Ruby 1.8 supports continuations. Ruby 1.9 has not supported them for a while however. They have been added back some time this year, but most of the other Ruby interpreters (JRuby, IronRuby, etc) don't support them. If you want your code to be usable on other platforms than the mainline Ruby, I'd suggest not using them. Read this InfoQ article for a more comprehensive discussion on the topic. A: Btw this is an example of restartable exceptions (aka conditions) implemented using continuations. I used it few times and it's a cool thing to have in a Ruby toolbox. A: Yes, in most cases. MRI (1.8) have supported them as far as my memory reaches, Ruby 1.9 (YARV) does it, too, so does Rubinius. JRuby and IronRuby don't have continuations, and it's quite unlikely they will get them (JVM and CLR use stack-instrospection for security) Ruby as a language supports continuations via callcc keyword. They're used, for example, to implement Generator class from standard library. continuations on ruby-doc Continuation-based web frameworks (like seaside, or one from Arc's std. library) seem less popular. I've found wee that claim to let you do optional continuations, but I've never used it. A: neverblock uses 1.9 fibers for a single threaded ruby web server
{ "language": "en", "url": "https://stackoverflow.com/questions/149570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Check if option is selected with jQuery, if not select a default Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected. (The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get my head around those :) A: Here is my function changing the selected option. It works for jQuery 1.3.2 function selectOption(select_id, option_val) { $('#'+select_id+' option:selected').removeAttr('selected'); $('#'+select_id+' option[value='+option_val+']').attr('selected','selected'); } A: <script type="text/javascript"> $(document).ready(function() { if (!$("#mySelect option:selected").length) $("#mySelect").val( 3 ); }); </script> A: No need to use jQuery for this: var foo = document.getElementById('yourSelect'); if (foo) { if (foo.selectedIndex != null) { foo.selectedIndex = 0; } } A: I already came across the texotela plugin mentioned, which let me solve it like this: $(document).ready(function(){ if ( $("#context").selectedValues() == false) { $("#context").selectOptions("71"); } }); A: Easy! The default should be the first option. Done! That would lead you to unobtrusive JavaScript, because JavaScript isn't needed :) Unobtrusive JavaScript A: While I'm not sure about exactly what you want to accomplish, this bit of code worked for me. <select id="mySelect" multiple="multiple"> <option value="1">First</option> <option value="2">Second</option> <option value="3">Third</option> <option value="4">Fourth</option> </select> <script type="text/javascript"> $(document).ready(function() { if (!$("#mySelect option:selected").length) { $("#mySelect option[value='3']").attr('selected', 'selected'); } }); </script> A: Look at the selectedIndex of the select element. BTW, that's a plain ol' DOM thing, not JQuery-specific. A: This was a quick script I found that worked... .Result is assigned to a label. $(".Result").html($("option:selected").text()); A: This question is old and has a lot of views, so I'll just throw some stuff out there that will help some people I'm sure. To check if a select element has any selected items: if ($('#mySelect option:selected').length > 0) { alert('has a selected item'); } or to check if a select has nothing selected: if ($('#mySelect option:selected').length == 0) { alert('nothing selected'); } or if you're in a loop of some sort and want to check if the current element is selected: $('#mySelect option').each(function() { if ($(this).is(':selected')) { .. } }); to check if an element is not selected while in a loop: $('#mySelect option').each(function() { if ($(this).not(':selected')) { .. } }); These are some of the ways to do this. jQuery has many different ways of accomplishing the same thing, so you usually just choose which one appears to be the most efficient. A: lencioni's answer is what I'd recommend. You can change the selector for the option ('#mySelect option:last') to select the option with a specific value using "#mySelect option[value='yourDefaultValue']". More on selectors. If you're working extensively with select lists on the client check out this plugin: http://www.texotela.co.uk/code/jquery/select/. Take a look the source if you want to see some more examples of working with select lists. A: You guys are doing way too much for selecting. Just select by value: $("#mySelect").val( 3 ); A: if (!$("#select").find("option:selected").length){ // } A: I found a good way to check, if option is selected and select a default when it isn't. if(!$('#some_select option[selected="selected"]').val()) { //here code if it HAS NOT selected value //for exaple adding the first value as "placeholder" $('#some_select option:first-child').before('<option disabled selected>Wybierz:</option>'); } If #some_select has't default selected option then .val() is undefined A: $("option[value*='2']").attr('selected', 'selected'); // 2 for example, add * for every option A: $("#select_box_id").children()[1].selected This is another way of checking an option is selected or not in jquery. This will return Boolean (True or False). [1] is index of select box option A: Change event on the select box to fire and once it does then just pull the id attribute of the selected option :- $("#type").change(function(){ var id = $(this).find("option:selected").attr("id"); switch (id){ case "trade_buy_max": // do something here break; } }); A: I was just looking for something similar and found this: $('.mySelect:not(:has(option[selected])) option[value="2"]').attr('selected', true); This finds all select menus in the class that don't already have an option selected, and selects the default option ("2" in this case). I tried using :selected instead of [selected], but that didn't work because something is always selected, even if nothing has the attribute A: If you need to explicitly check each option to see if any have the "selected" attribute you can do this. Otherwise using option:selected you'll get the value for the first default option. var viewport_selected = false; $('#viewport option').each(function() { if ($(this).attr("selected") == "selected") { viewport_selected = true; } });
{ "language": "en", "url": "https://stackoverflow.com/questions/149573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "212" }
Q: need an algorithm for collapsing netblock ranges into lists of superset ranges My math-fu is failing me! I need an efficient way of reducing network ranges to supersets, e.g. if I input list of IP ranges: * *1.1.1.1 to 2.2.2.5 *1.1.1.2 to 2.2.2.4 *10.5.5.5 to 155.5.5.5 *10.5.5.6 to 10.5.5.7 I want to return the following ranges: * *1.1.1.1 to 2.2.2.5 *10.5.5.5 to 155.5.5.5 Note: the input lists are not ordered (though they could be?). The naive way to do this is to check every range in the list to see if the input range x is a subset, and if so, NOT insert range x. However, whenever you insert a new range it might be a superset of existing ranges, so you have to check the existing ranges to see if they can be collapsed (e.g., removed from my list). A: You know that you can easily convert IPv4 addresses to int numbers (int32 numbers), do you? Working with int numbers is much easier. So basically every address is a number in the range 0 to 2^32. Every range has a start number and an end number. Your example 1.1.1.1 to 2.2.2.5 1.1.1.2 to 2.2.2.4 can be written as 16,843,009 to 33,686,021 16,843,010 to 33,686,020 So it's pretty easy to see if one range is within the other range. A range is completely within the other range if the following condition is given startIP2 >= startIP1 && startIP2 <= endIP1 && endIP1 >= startIP1 && endIP2 <= endIP1 In that case the range startIP2-endIP2 is completely within startIP1-endIP1. If only the first line is true, then startIP2 is within the range startIP1-endIP1, but the end is beyond the range. If only the second line is true, the endIP is within the range, but the start IP is beyond the range. In that case, if only one line is true, you need to expand the range at the beginning or at the end. If both lines are false, the ranges are completely disjoint, in that case they are two completely independent ranges. A: This is a union of segments computation. An optimal algorithm (in O(nlog(n))) consists in doing the following: *sort all endpoints (starting and ending points) in a list L (each endpoint should know the segment it belongs to). If an endpoint is equal to a starting point, the starting point should be considered smaller than the enpoint. *go through the sorted list L from left to right and maintain the number LE-RE, where LE is the number of left endpoints that you have already passed, and RE is the number of right endpoints that you have already passed. *each time LE-RE reaches zero, you are at the end of a connected union of segments, and you know that the union of the segments you have seen before (since the previous return to zero) is one superset. *if you also maintained the min and max, between each return to zero, you have the bounds of the superset. At the end, you obtain a sorted list of disjoint supersets. Still, two supersets A and B can be adjacent (the endpoint of A is just before the starting point of B). If you want A and B to be merged, you can do this either by a simple postprocessing step, or by slightly modifying step 3: when LE-RE reaches zero, you would consider it the end of a superset only if the next element in L is not the direct successor of your current element. A: What you need to do is simply check the ranges for overlap. If two ranges overlap, then they get merged into a single range. Ranges overlap if the right hand side of one range is greater than the left hand side of another. A: Alright, my coworker came up with this answer, which I think is pretty excellent. Let me know if you see any issues: * *Order the IP ranges by StartingIP *For each row "x" to insert: * *If there is a previous row "y" in the list, fetch: * *If x and y are contiguous, extend y to x's EndingIP *Else if x.StartingIP <= y.StartingIP and x.EndingIP > y.EndingIP, extend y to x.EndingIP *Else if x is a subset of y, do nothing *Else, create a new range *Else, create a new range and insert into the list
{ "language": "en", "url": "https://stackoverflow.com/questions/149577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Viewing repository information from within Eclipse, when code was checked out using svn tortoise I am using svn tortoise to checkout a maven project from a repository, I then open eclispe, and use the m2eclipse plugin to import a maven project. The maven projeect comes in okay, and I can build it fine. The problem is that eclipse using subversive, isn't marking files/ resources as being in source control (even though I seem to have all the relevant .svn directories.) I get the same behaviour if I try and check the code in using -> import -> check out Maven Projects from SCM. ie the project imports okay, but the files aren't linked in to teh svn repository in eclipse. Are there any suggestions as to how I might proceed, as I find the tortoise svn checkin process pretty painful. A: Did you set up your project for team sharing (right click on project->Team->Share project)? If I remember correctly that should detect the existing .svn folders an enables version control inside of eclipse. A: You might wanna try using Subclipse. It's the Eclipse plug-in for Subversion and is really good. I've also found that interacting with a SVN repository with Tortoise while also having Eclipse open and accessing the same repository causes problems. You should avoid it if you can. A: I would highly recommend making sure that you commit using tortoise svn as I've had particularly spotty consistency with subclipse. If you do you in/out with tortoise, and then just update with subclipse you should be fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/149583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: BeautifulSoup's Python 3 compatibility Does BeautifulSoup work with Python 3? If not, how soon will there be a port? Will there be a port at all? Google doesn't turn up anything to me (Maybe it's 'coz I'm looking for the wrong thing?) A: About two months after I asked this question, a port has been released: http://groups.google.com/group/beautifulsoup/browse_thread/thread/f24882cc17a0625e It'll bet BS working, but that's about it. Not yet tried it though. A: http://www.crummy.com/software/BeautifulSoup/ says: Download Beautiful Soup If you're using Python 2.3 through 2.6, the 3.0 series is the best choice. The most recent release in the 3.0 series is 3.0.8, released November 30, 2009. If you're using Python 3.0, you must use the 3.1 series. Beautiful Soup version 3.1.0.1 was released January 6, 2009. You can use the 3.1 series with earlier versions of Python, but you might run into the problems described here. A: Beautiful Soup 4.x officially supports Python 3. pip install beautifulsoup4 A: There's a release candidate for Python 3.0 available, so you can always test BeautifulSoup's compatibility yourself :) A: I'm guessing the answer is "No". According to Python.org: Python 3000 (a.k.a. "Py3k", and released as Python 3.0) is a new version of the language that is incompatible with the 2.x line of releases. The language is mostly the same, but many details, especially how built-in objects like dictionaries and strings work, have changed considerably, and a lot of deprecated features have finally been removed. Also, the standard library has been reorganized in a few prominent places. A better place for this particular question might be the BeautifulSoup forum. A: yes,beautiful soup work in python 3, Linux apt-get install python3-bs4 Windows pip install beautifulsoup4 For more information see https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-beautiful-soup
{ "language": "en", "url": "https://stackoverflow.com/questions/149585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: How do you define a type in a Linq 2 SQL mapping? I'm trying to do my linq 2 sql objects manually, so I have the following code: var mapping = XmlMappingSource.FromXml(xml); using (DataContext ctx = new DataContext(conn_string, mapping)) { list = ctx.GetTable<Achievement>().ToList(); } and the XML looks like this: <?xml version="1.0" encoding="utf-8" ?> <Database Name="FatFights" xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007"> <Table Name="dbo.Achievements"> <Type Name="FatFights.Business.Objects.Achievement"> <Column Name="Id" Member="Id" DbType="UniqueIdentifier NOT NULL" IsPrimaryKey="true" /> <Column Name="UserId" Member="UserId" /> <Column Name="Achieved" Member="Achieved" /> <Column Name="AchievementId" Member="AchievementTypeId" /> <Association Name="AchievementType_Achievement" Member="AchievementTypeId" ThisKey="Id" OtherKey="Id" IsForeignKey="true" /> </Type> </Table> </Database> this returns the following error: System.InvalidOperationException: Could not find key member 'Id' of key 'Id' on type 'Int32'. The key may be wrong or the field or property on 'Int32' has changed names.. So I need to figure out how to tell Linq 2 SQL that Id is a GUID not an Int32... So I generated some Linq2SQL XML to see how they do it and they pass Type, but Type isn't a valid attribute according to the XSD, so it fails. Here is the SQL table: CREATE TABLE Achievements ( Id UNIQUEIDENTIFIER NOT NULL CONSTRAINT RG_Achievements ROWGUIDCOL CONSTRAINT DF_Achievements_Id DEFAULT (NEWID()), UserId UNIQUEIDENTIFIER NOT NULL, AchievementId INTEGER NOT NULL, Achieved DATETIME NOT NULL, CONSTRAINT FK_Achievements_Users FOREIGN KEY (UserId) REFERENCES aspnet_Users (UserId), CONSTRAINT FK_Achievements_AcheivementTypes FOREIGN KEY (AchievementId) REFERENCES AchievementTypes (Id), CONSTRAINT PK_Achievements PRIMARY KEY (Id), CONSTRAINT UQ_Achievements_1 UNIQUE (UserId, AchievementId) ) and the business object: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FatFights.Business.Objects { public class Achievement { public Guid Id { get; set; } public Guid UserId { get; set; } public int AchievementTypeId { get; set; } public DateTime Achieved { get; set; } } } A: I suspect the issue is here: Member="AchievementTypeId" For an association, you should be linking a typed member - for example you might have a property called "AchievementType" (of type AchievementType), and have Member="AchievementType". For example, in Northwind, linking Customer and Order shows (for Order): <Association Name="Customer_Order" Member="Customer" ThisKey="CustomerID" OtherKey="CustomerID" Type="Customer" IsForeignKey="true" /> The SqlMetal generated code then has some overly complex code linking the CustomerID and Customer properties.
{ "language": "en", "url": "https://stackoverflow.com/questions/149593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiple platform development I was currently developing a desktop application in C# using mono and testing in SuSE and Windows. The concept doesn't matter much, but it is a "web lint" program that will scan a web site and return possible issues with security and/or cross browser compatibility. However, I want to be able to offer binaries for multiple platforms. Should I stay with Mono, or is there another platform that would give me a better availablility of platforms, such as on Macs, Windows, Linux, and others (possibly mobile platforms), and make it easier to port? A: Well, your best bet always is to use a language that actually exists on all the platforms. That usually means Java, I think, though even perl has flavours for mobile platforms (depending on the mobile platform in question). I do most of my cross-platform work in C and perl, but there are some headaches with C (lots of #ifdef's), and perl may not be on a mobile platform you care about (yet). You'll have to evaluate the languages/compilers/interpreters that are common to all the platforms you want to target and then choose from that list. Without knowing the full list of such platforms, we'll have a hard time telling you what to use, though Java has enough buzz-wordness to likely be a strong candidate. A: Iff you know C++, Qt will cover many platforms. A: C# and Mono is probably cross-platform enough for most desktop environments. The trick will be the "mobile platform" requirement. Mobile operating systems are wildly diverse and there's not a lot you can do to generalize. Some have Java, like the Blackberry. C# may get you onto Windows Mobile-based platforms. iPhones do their own thing. You pretty much have to pick a platform and target that. That may end up informing your desktop platform choice. A: Just stick to the Mono, make sure that you have Gendarme code inspector (FxCop for Mono) checking your code for portability issues, and you should be fine. A: Java will run on Windows, Linux and Macs. Should be easy to transition from C# - use Apache HTTPClient for grabbing the web content you are scanning, and the scanning code should be more or less the same. However the downside is requiring the user to have the Java runtime installed. Python is another option - you can build stand-alone executables for Windows, and it comes with most Linux distributions by default, and also Mac OS X (citation needed ;) ). This is a lot less hassle for Windows users (language is compiled into the executable, no other downloads required). If mono runs on Mac OS X then surely that is a good platform as well? A: It really depends what you want to do. For web development, if HTML/JavaScript is enough then stick with it. If you need more advanced stuff I would use ASP.NET with Mono (what you probably did) since you already know that. (You can use Visual Studio here.) Another option might be (since you are a C# developer) to use Silverlight. That gives you Windows and Mac platforms covered and hopefully Moonlight will cover Linxu platform later. (You can use Visual Studio and Expression Blend here.) If you need desktop application then Java is probably the easiest since you already know C#. But if you know C/C++ try to take a look at wxWidgets for example. A: Why limit yourself to the traditional C#/Java? Have a look at Adobe AIR and Microsoft SilverLight
{ "language": "en", "url": "https://stackoverflow.com/questions/149596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Php code formatter / beautifier and php beautification in general Do you know any good tools for nicely formatting messy php code? Preferably a script for Aptana/Eclipse, but a standalone tool will do too. A: There's a pear module that formats your code. PHP Beautifier A: If you use Zend Development Environment, you can use the Indent Code feature (Ctrl+Shift+F). A: Use NetBeans PHP and press alt+shift+F. A: Well here is my very basic and rough script: #!/usr/bin/php <?php class Token { public $type; public $contents; public function __construct($rawToken) { if (is_array($rawToken)) { $this->type = $rawToken[0]; $this->contents = $rawToken[1]; } else { $this->type = -1; $this->contents = $rawToken; } } } $file = $argv[1]; $code = file_get_contents($file); $rawTokens = token_get_all($code); $tokens = array(); foreach ($rawTokens as $rawToken) { $tokens[] = new Token($rawToken); } function skipWhitespace(&$tokens, &$i) { global $lineNo; $i++; $token = $tokens[$i]; while ($token->type == T_WHITESPACE) { $lineNo += substr($token->contents, "\n"); $i++; $token = $tokens[$i]; } } function nextToken(&$j) { global $tokens, $i; $j = $i; do { $j++; $token = $tokens[$j]; } while ($token->type == T_WHITESPACE); return $token; } $OPERATORS = array('=', '.', '+', '-', '*', '/', '%', '||', '&&', '+=', '-=', '*=', '/=', '.=', '%=', '==', '!=', '<=', '>=', '<', '>', '===', '!=='); $IMPORT_STATEMENTS = array(T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE); $CONTROL_STRUCTURES = array(T_IF, T_ELSEIF, T_FOREACH, T_FOR, T_WHILE, T_SWITCH, T_ELSE); $WHITESPACE_BEFORE = array('?', '{', '=>'); $WHITESPACE_AFTER = array(',', '?', '=>'); foreach ($OPERATORS as $op) { $WHITESPACE_BEFORE[] = $op; $WHITESPACE_AFTER[] = $op; } $matchingTernary = false; // First pass - filter out unwanted tokens $filteredTokens = array(); for ($i = 0, $n = count($tokens); $i < $n; $i++) { $token = $tokens[$i]; if ($token->contents == '?') { $matchingTernary = true; } if (in_array($token->type, $IMPORT_STATEMENTS) && nextToken($j)->contents == '(') { $filteredTokens[] = $token; if ($tokens[$i + 1]->type != T_WHITESPACE) { $filteredTokens[] = new Token(array(T_WHITESPACE, ' ')); } $i = $j; do { $i++; $token = $tokens[$i]; if ($token->contents != ')') { $filteredTokens[] = $token; } } while ($token->contents != ')'); } elseif ($token->type == T_ELSE && nextToken($j)->type == T_IF) { $i = $j; $filteredTokens[] = new Token(array(T_ELSEIF, 'elseif')); } elseif ($token->contents == ':') { if ($matchingTernary) { $matchingTernary = false; } elseif ($tokens[$i - 1]->type == T_WHITESPACE) { array_pop($filteredTokens); // Remove whitespace before } $filteredTokens[] = $token; } else { $filteredTokens[] = $token; } } $tokens = $filteredTokens; function isAssocArrayVariable($offset = 0) { global $tokens, $i; $j = $i + $offset; return $tokens[$j]->type == T_VARIABLE && $tokens[$j + 1]->contents == '[' && $tokens[$j + 2]->type == T_STRING && preg_match('/[a-z_]+/', $tokens[$j + 2]->contents) && $tokens[$j + 3]->contents == ']'; } // Second pass - add whitespace $matchingTernary = false; $doubleQuote = false; for ($i = 0, $n = count($tokens); $i < $n; $i++) { $token = $tokens[$i]; if ($token->contents == '?') { $matchingTernary = true; } if ($token->contents == '"' && isAssocArrayVariable(1) && $tokens[$i + 5]->contents == '"') { /* * Handle case where the only thing quoted is the assoc array variable. * Eg. "$value[key]" */ $quote = $tokens[$i++]->contents; $var = $tokens[$i++]->contents; $openSquareBracket = $tokens[$i++]->contents; $str = $tokens[$i++]->contents; $closeSquareBracket = $tokens[$i++]->contents; $quote = $tokens[$i]->contents; echo $var . "['" . $str . "']"; $doubleQuote = false; continue; } if ($token->contents == '"') { $doubleQuote = !$doubleQuote; } if ($doubleQuote && $token->contents == '"' && isAssocArrayVariable(1)) { // don't echo " } elseif ($doubleQuote && isAssocArrayVariable()) { if ($tokens[$i - 1]->contents != '"') { echo '" . '; } $var = $token->contents; $openSquareBracket = $tokens[++$i]->contents; $str = $tokens[++$i]->contents; $closeSquareBracket = $tokens[++$i]->contents; echo $var . "['" . $str . "']"; if ($tokens[$i + 1]->contents != '"') { echo ' . "'; } else { $i++; // process " $doubleQuote = false; } } elseif ($token->type == T_STRING && $tokens[$i - 1]->contents == '[' && $tokens[$i + 1]->contents == ']') { if (preg_match('/[a-z_]+/', $token->contents)) { echo "'" . $token->contents . "'"; } else { echo $token->contents; } } elseif ($token->type == T_ENCAPSED_AND_WHITESPACE || $token->type == T_STRING) { echo $token->contents; } elseif ($token->contents == '-' && in_array($tokens[$i + 1]->type, array(T_LNUMBER, T_DNUMBER))) { echo '-'; } elseif (in_array($token->type, $CONTROL_STRUCTURES)) { echo $token->contents; if ($tokens[$i + 1]->type != T_WHITESPACE) { echo ' '; } } elseif ($token->contents == '}' && in_array($tokens[$i + 1]->type, $CONTROL_STRUCTURES)) { echo '} '; } elseif ($token->contents == '=' && $tokens[$i + 1]->contents == '&') { if ($tokens[$i - 1]->type != T_WHITESPACE) { echo ' '; } $i++; // match & echo '=&'; if ($tokens[$i + 1]->type != T_WHITESPACE) { echo ' '; } } elseif ($token->contents == ':' && $matchingTernary) { $matchingTernary = false; if ($tokens[$i - 1]->type != T_WHITESPACE) { echo ' '; } echo ':'; if ($tokens[$i + 1]->type != T_WHITESPACE) { echo ' '; } } elseif (in_array($token->contents, $WHITESPACE_BEFORE) && $tokens[$i - 1]->type != T_WHITESPACE && in_array($token->contents, $WHITESPACE_AFTER) && $tokens[$i + 1]->type != T_WHITESPACE) { echo ' ' . $token->contents . ' '; } elseif (in_array($token->contents, $WHITESPACE_BEFORE) && $tokens[$i - 1]->type != T_WHITESPACE) { echo ' ' . $token->contents; } elseif (in_array($token->contents, $WHITESPACE_AFTER) && $tokens[$i + 1]->type != T_WHITESPACE) { echo $token->contents . ' '; } else { echo $token->contents; } } A: Here's a php code beautifier (PHP of course) class: http://www.codeassembly.com/A-php-code-beautifier-that-works/ and online demo: http://www.codeassembly.com/examples/beautifier.php A: The Zend Development Environment is now an Eclipse plugin, you may be able to run it alongside Aptana and just use it's Indent Code feature. Zend Studio I haven't upgraded to the Eclipse plugin yet myself, I love the previous ZDE so much. Though now that I've started actually using Eclipse for other languages, I'm almost ready to make the leap. A: What about this one: http://universalindent.sourceforge.net/ It combines a bunch of formatters out there, and will generate the scripts you need so you can pass them out and get your team members to use them before committing next time... Though... formatters might mess up your code and render it unusable... A: The simplest solution is to just use an IDE that has this built in. If you're going to be writing code in PHP on a regular a regular basis, just drop the $60 for PHPStorm. You won't regret it. http://www.jetbrains.com/phpstorm/ It lets you format your code however you like using a simple keyboard shortcut at the file or directory level, and has a zillion other great features. A: http://en.sourceforge.jp/projects/pdt-tools/ ^^^ will give you a proper CTRL+SHIFT+F Eclipse/Aptana PHP formatter like Java. See here for installation help. A: PHP Code Beautifier is a useful free tool that should do what you're after, although their download page does require an account to be created. The tool has been declined into 3 versions: * *A GUI version which allow to process file visually. *A command line version which allow to be batched or integrated with other tools (CVS, SubVersion, IDE ...). *As an integrated tool of PHPEdit. Basically, it'll turn: if($code == BAD){$action = REWRITE;}else{$action = KEEP;} for($i=0; $i<10;$i++){while($j>0){$j++;doCall($i+$j);if($k){$k/=10;}}} into if ($code == BAD) { $action = REWRITE; } else { $action = KEEP; } for($i = 0; $i < 10;$i++) { while ($j > 0) { $j++; doCall($i + $j); if ($k) { $k /= 10; } } } A: Our PHP Formatter will reliably format your code. It uses a compiler-based front end to parse the code, so it doesn't misinterpret the code and damage it. Consequently its formatted output always works. A: This is an excellent question. I have an application that reads json and outputs php and html and css. I run a program and generate dozens (hundreds?) of files. I hope the answer here is useful. I started my project using heredocs, special include files, meta chars, etc but that quickly became a mess. I wanted a stand-alone solution that didn't require framework or ide. So I removed all the heredoc and other junk and created a generic text buffering class with no concern for formatting. It can all be one line for all I care. For html, I do tidy() built-in. For php, I use phpstylist. phpstylist is older but still works well for php format. To set up the phpstylist options I used UniversalIndent (updated Jan 2012) in windows gui. UniversalStylist lists 24 (!) formatter programs (c, php, ruby, html,...). It specifically knows the options for phpstylist and gives you a live refresh on a file as you turn options on and off. Very great. Then, when you have your style, it has an option to save the command line options and generates a script. For some formatting options you'll have to add paths to perl, python, etc. If you are using windows and want to try phpstylist with UniversalIndent, just add directory for php.exe to your env path. I use ampps so mine is set to c:\ampps\php. It was not very easy to find a good solid solution. I'm also interested in hearing what other people do for simple as possible batch formatting of auto-generated php/html files for code review and archiving purposes. A: phpformatter.com works best "This free online PHP Formatter is designed so that you can beautify all your PHP script with the style that you prefer" A: I've been having a lot of trouble finding a decent free formatter for PHP as well, there are many online and command-line tools but they just don't seem to work for some reason, the results are all still full of bad indenting with combinations of tabs and spaces, and they never get the braces the way you want them! I tried the snippet above and that didn't work for me either, indenting still full of spaces and tabs all mixed up. So I've had a go at writing a simple one too, this one just uses all regex, no fancy compiler magic, so it's possible that it could break things, and is still very beta and being tested on various messy code. The interface is very basic at the moment too, but should improve over the next few days. It's hardwired for MediaWiki's conventions, but you can modify it pretty easily (I may add options later). https://www.organicdesign.co.nz/Special:CodeTidy
{ "language": "en", "url": "https://stackoverflow.com/questions/149600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: C# "Using" Syntax Does the using catch the exception or throw it? i.e. using (StreamReader rdr = File.OpenText("file.txt")) { //do stuff } If the streamreader throws an exception is it caught by using or thrown so the calling function can handle it? A: When you see a using statement, think of this code: StreadReader rdr = null; try { rdr = File.OpenText("file.txt"); //do stuff } finally { if (rdr != null) rdr.Dispose(); } So the real answer is that it doesn't do anything with the exception thrown in the body of the using block. It doesn't handle it or rethrow it. A: It throws the exception, so either your containing method needs to handle it, or pass it up the stack. try { using ( StreamReader rdr = File.OpenText("file.txt")) { //do stuff } } catch (FileNotFoundException Ex) { // The file didn't exist } catch (AccessViolationException Ex) { // You don't have the permission to open this } catch (Exception Ex) { // Something happened! } A: Any exceptions that are thrown in the initialization expression of the using statement will propagate up the method scope and call stack as expected. One thing to watch out for, though, is that if an exception occures in the initialization expression, then the Dispose() method will not be called on the expression variable. This is almost always the behavior that you would want, since you don't want to bother disposing an object that was not actually created. However, there could be an issue in complex circumstances. That is, if multiple initializations are buried inside the constructor and some succeed prior to the exception being thrown, then the Dispose call may not occur at that point. This is usually not a problem, though, since constructors are usually kept simple. A: using statements do not eat exceptions. All "Using" does is scope your object to the using block, and automatically calls Dispose() on the object when it leaves the block. There is a gotcha though, if a thread is forcefully aborted by an outside source, it is possible that Dispose will never be called. A: The using does not interfere with exception handling apart from cleaning up stuff in its scope. It doesn't handle exceptions but lets exceptions pass through. A: In your example, if File.OpenText throws, the Dispose will not be called. If the exception happens in //do stuff, the Dispose will be called. In both cases, the exception is normally propagated out of the scope, as it would be without the using statement. A: If you don't specifically catch an exception it's thrown up the stack until something does A: using guarantees* the object created will be disposed at the end of the block, even if an exception is thrown. The exception is not caught. However, you need to be careful about what you do if you try to catch it yourself. Since any code that catches the exception is outside the scope block defined by the using statement, your object won't be available to that code. *barring the usual suspects like power failure, nuclear holocaust, etc A: using allows the exception to boil through. It acts like a try/finally, where the finally disposes the used object. Thus, it is only appropriate/useful for objects that implement IDisposable. A: You can imagine using as a try...finally block without the catch block. In the finally block, IDisposable.Dispose is called, and since there is no catch block, any exceptions are thrown up the stack. A: "using" does not catch exceptions, it just disposes of resources in the event of unhandled exceptions. Perhaps the question is, would it dispose of resources allocated in the parentheses if an error also occured in the declaration? It's hard to imagine both happening, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/149609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "49" }
Q: How could I guess a checksum algorithm? Let's assume that I have some packets with a 16-bit checksum at the end. I would like to guess which checksum algorithm is used. For a start, from dump data I can see that one byte change in the packet's payload totally changes the checksum, so I can assume that it isn't some kind of simple XOR or sum. Then I tried several variations of CRC16, but without much luck. This question might be more biased towards cryptography, but I'm really interested in any easy to understand statistical tools to find out which CRC this might be. I might even turn to drawing different CRC algorithms if everything else fails. Backgroud story: I have serial RFID protocol with some kind of checksum. I can replay messages without problem, and interpret results (without checksum check), but I can't send modified packets because device drops them on the floor. Using existing software, I can change payload of RFID chip. However, unique serial number is immutable, so I don't have ability to check every possible combination. Allthough I could generate dumps of values incrementing by one, but not enough to make exhaustive search applicable to this problem. dump files with data are available if question itself isn't enough :-) Need reference documentation? A PAINLESS GUIDE TO CRC ERROR DETECTION ALGORITHMS is great reference which I found after asking question here. In the end, after very helpful hint in accepted answer than it's CCITT, I used this CRC calculator, and xored generated checksum with known checksum to get 0xffff which led me to conclusion that final xor is 0xffff instread of CCITT's 0x0000. A: There are a number of variables to consider for a CRC: Polynomial No of bits (16 or 32) Normal (LSB first) or Reverse (MSB first) Initial value How the final value is manipulated (e.g. subtracted from 0xffff), or is a constant value Typical CRCs: LRC: Polynomial=0x81; 8 bits; Normal; Initial=0; Final=as calculated CRC16: Polynomial=0xa001; 16 bits; Normal; Initial=0; Final=as calculated CCITT: Polynomial=0x1021; 16 bits; reverse; Initial=0xffff; Final=0x1d0f Xmodem: Polynomial=0x1021; 16 bits; reverse; Initial=0; Final=0x1d0f CRC32: Polynomial=0xebd88320; 32 bits; Normal; Initial=0xffffffff; Final=inverted value ZIP32: Polynomial=0x04c11db7; 32 bits; Normal; Initial=0xffffffff; Final=as calculated The first thing to do is to get some samples by changing say the last byte. This will assist you to figure out the number of bytes in the CRC. Is this a "homemade" algorithm. In this case it may take some time. Otherwise try the standard algorithms. Try changing either the msb or the lsb of the last byte, and see how this changes the CRC. This will give an indication of the direction. To make it more difficult, there are implementations that manipulate the CRC so that it will not affect the communications medium (protocol). From your comment about RFID, it implies that the CRC is communications related. Usually CRC16 is used for communications, though CCITT is also used on some systems. On the other hand, if this is UHF RFID tagging, then there are a few CRC schemes - a 5 bit one and some 16 bit ones. These are documented in the ISO standards and the IPX data sheets. IPX: Polynomial=0x8005; 16 bits; Reverse; Initial=0xffff; Final=as calculated ISO 18000-6B: Polynomial=0x1021; 16 bits; Reverse; Initial=0xffff; Final=as calculated ISO 18000-6C: Polynomial=0x1021; 16 bits; Reverse; Initial=0xffff; Final=as calculated Data must be padded with zeroes to make a multiple of 8 bits ISO CRC5: Polynomial=custom; 5 bits; Reverse; Initial=0x9; Final=shifted left by 3 bits Data must be padded with zeroes to make a multiple of 8 bits EPC class 1: Polynomial=custom 0x1021; 16 bits; Reverse; Initial=0xffff; Final=post processing of 16 zero bits Here is your answer!!!! Having worked through your logs, the CRC is the CCITT one. The first byte 0xd6 is excluded from the CRC. A: It might not be a CRC, it might be an error correcting code like Reed-Solomon. ECC codes are often a substantial fraction of the size of the original data they protect, depending on the error rate they want to handle. If the size of the messages is more than about 16 bytes, 2 bytes of ECC wouldn't be enough to be useful. So if the message is large, you're most likely correct that its some sort of CRC. A: I'm trying to crack a similar problem here and I found a pretty neat website that will take your file and run checksums on it with 47 different algorithms and show the results. If the algorithm used to calculate your checksum is any of these algorithms, you would simply find it among the list of checksums produced with a simple text search. The website is https://defuse.ca/checksums.htm A: You would have to try every possible checksum algorithm and see which one generates the same result. However, there is no guarantee to what content was included in the checksum. For example, some algorithms skip white spaces, which lead to different results. I really don't see why would somebody want to know that though.
{ "language": "en", "url": "https://stackoverflow.com/questions/149617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: SQL clone record with a unique index Is there a clean way of cloning a record in SQL that has an index(auto increment). I want to clone all the fields except the index. I currently have to enumerate every field, and use that in an insert select, and I would rather not explicitly list all of the fields, as they may change over time. A: Not unless you want to get into dynamic SQL. Since you wrote "clean", I'll assume not. Edit: Since he asked for a dynamic SQL example, I'll take a stab at it. I'm not connected to any databases at the moment, so this is off the top of my head and will almost certainly need revision. But hopefully it captures the spirit of things: -- Get list of columns in table SELECT INTO #t EXEC sp_columns @table_name = N'TargetTable' -- Create a comma-delimited string excluding the identity column DECLARE @cols varchar(MAX) SELECT @cols = COALESCE(@cols+',' ,'') + COLUMN_NAME FROM #t WHERE COLUMN_NAME <> 'id' -- Construct dynamic SQL statement DECLARE @sql varchar(MAX) SET @sql = 'INSERT INTO TargetTable (' + @cols + ') ' + 'SELECT ' + @cols + ' FROM TargetTable WHERE SomeCondition' PRINT @sql -- for debugging EXEC(@sql) A: There's no easy and clean way that I can think of off the top of my head, but from a few items in your question I'd be concerned about your underlying architecture. Maybe you have an absolutely legitimate reason for wanting to do this, but usually you want to try to avoid duplicates in a database, not make them easier to cause. Also, explicitly naming columns is usually a good idea. If you're linking to outside code, it makes sure that you don't break that link when you add a new column. If you're not (and it sounds like you probably aren't in this scenario) I still prefer to have the columns listed out because it forces me to review the effects of the change/new column - even if it's just to look at the code and decide that adding the new column is not a problem. A: DROP TABLE #tmp_MyTable SELECT * INTO #tmp_MyTable FROM MyTable WHERE MyIndentID = 165 ALTER TABLE #tmp_MyTable DROP Column MyIndentID INSERT INTO MyTable SELECT * FROM #tmp_MyTable A: This also deals with a unique key projectnum as well as the primary key. CREATE TEMPORARY TABLE projecttemp SELECT * FROM project WHERE projectid='6'; ALTER TABLE projecttemp DROP COLUMN projectid; UPDATE projecttemp SET projectnum = CONCAT(projectnum, ' CLONED'); INSERT INTO project SELECT NULL,projecttemp.* FROM projecttemp; A: You could create an insert trigger to do this, however, you would lose the ability to do an insert with an explicit ID. It would, instead, always use the value from the sequence. A: You could create a trigger to do it for you. To make sure that trigger only works for cloning, you could create a separate username CLONE and log in with it. Or, even better, if your DBMS supports it, create a role named CLONE and any user can log in using that role and do the cloning. The trigger code would be something like: if (CURRENT_ROLE = 'CLONE') then new.ID = assign new id from generator/sequence Of course, you would grant that role only to the users who are allowed to clone records.
{ "language": "en", "url": "https://stackoverflow.com/questions/149627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Way to Stop a Windows Service when CanStop is set to False (C#) Ok so part two of I have no will power experiment is: Summary Question - Is there a way to set the CanStop property on a windows service dynamically? Whole Spiel - I have a service that is currently checking and killing processes (IE Games) I have told it to if it's day I'm not allowed. Great. I set the CanStop to false so that I can't just kill the service if I give into the addiction. I have a program that will have a password check (Someone else enters the password) that will stop the service if the password is correct. (If I have serious withdrawals) Problem is using the ServiceController class. Far as I can tell, ServiceController just is a decorator (yah design patern guess) and so I have no way to get at the actual service it represents. First attempt was Property Info, but I was too dumb to realize what that would be pointless. Second was Field Info because I thought there might be a private field that "represents" the service. As you might guess, both failed. Any ideas? EDIT 1 I'd like to avoid having the CanStop value somewhere I can get to it easily like a config file or registry. So I am attempting, though not successfully, to make this completely handled in program. New (Failed) Attempts: ManagementObject service; ManagementBaseObject stopService; service = new ManagementObject("Win32_Service.Name='StopProgram'"); stopService = service .InvokeMethod("StopService", null, null); Not sure this did anything. I assume it couldn't stop because of the CanStop situation. A: The "CanStop" is a attribute of the services registration in the windows service control manager. You can't change it mid-stride. And, of course, if you're smart enough to write your own service then you're smart enough to bring up task-man and simply kill the service process. CanStop will not prevent you from pulling the rug out from under the service. CanStop only tells the service control manager not to send "Stop" commands to the service. If you want to allow something to pass then use a global event to enable/disable the checking the service does -- or just remove the games from the PC! :-) A: Rather than trying to directly access and control the Service, could you set a flag somewhere, (like the registry or a file), that is then checked by your service before it executes the Event you're trying to control.
{ "language": "en", "url": "https://stackoverflow.com/questions/149632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JSON editor/formatter? I've got some JSON data, but it's all on one line. Does anyone know of a web or Windows editor that will format (e.g. indent and insert new lines) this data for me, so I can read it better? Preferably one that uses a GUI to display the JSON—instead of a command-line tool that outputs a reformatted document, for example. A: I have recently created JSON Editor Online, a tool to easily edit and format JSON online. JSON is displayed in a clear, editable treeview and in formatted plain text. http://jsoneditoronline.org/ A: Have you tried this? http://jsonformat.com/ A: You can download http://www.thomasfrank.se/json_editor.html and run it locally on your own data, although it is an editor rather than a formatter. http://www.jsonlint.com/ is also a useful validation and reformatting tool. A: On windows I go for: http://jsonviewer.codeplex.com/ Handy for pulling raw JSON responses from Firebug and parsing it for me. A: I use http://curiousconcept.com/jsonformatter to format computer generated jsons. It makes it much readable. A: Remember that JSON is just a Javascript Object Literal with fancy clothes. You should be able to use any Javascript Beautifier to clean it up. A: I like this one here: http://freeformatter.com/json-formatter.html The validation process is flexible if your doc does not adhere to the RFC standards. It also creates a tree with collapsible nodes which is cool when you want to work in a small area of the json tree A: Here's what I do: use the Aptana Eclipse Javascript Editor, which will check your syntax as you type. There's only one trick: you have to wrap your json in a tiny bit of javascript to make the whole thing a valid javascript file, and eliminate those red and yellow syntax errors. So, the outer-most {} becomes: x={}; ( with all your json stuff in the middle ). Now you just have to strip-off the x= and the ; before parsing as JSON. I do this in a function that wraps the jQuery ajax function: function get_json_file(url,options,callback){ var opts = {dataType:"text"}; opts.url = url; $.extend(opts,options); opts.success=function(data){ var json = data.substring(data.indexOf('{'),data.lastIndexOf('}')+1); var obj = JSON.parse(json); callback(obj); }; $.ajax(opts); } It's a bit crazy, but it's worth it to effectively have a really good syntax-checking JSON editor in eclipse.
{ "language": "en", "url": "https://stackoverflow.com/questions/149635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: SQL to reorder nodes in a hierarchy I've got a 'task list' database that uses the adjacency list model (see below) so each 'task' can have unlimited sub-tasks. The table has an 'TaskOrder' column so everything renders in the correct order on a treeview. Is there an SQL statement (MS-SQL 2005) that will select all the child nodes for a specified parent and update the TaskOder column when a sibling is deleted? Task Table ---------- TaskId ParentTaskId TaskOrder TaskName --etc-- Any ideas? Thanks. A: If you're only using TaskOrder for sorting, it would certainly be simpler to simply leave the holes in TaskOrder, because simply deleting items won't make the sorting incorrect. But then I'm not sure about your application's needs. A: Couple of different ways... Since the TaskOrder is scoped by parent id, it's not terribly difficult to gather it. In SQL Server, I'd put a trigger on delete that decrements all the ones 'higher' than the one you deleted, thereby closing the gap (pseudocode follows): CREATE TRIGGER ON yourtable FOR DELETE AS UPDATE Task SET TaskOrder = TaskOrder - 1 WHERE ParentTaskId = deleted.ParentTaskId AND TaskOrder > deleted.TaskOrder If you don't want a trigger, you can capture the parentID and TaskOrder in a query first, delete the row, then execute that same update statement but with literals rather than the trigger. Or if you want to minimize server round-trips, you could move the to-be-deleted task all the way to the bottom, then move the others up, then do the delete, but that seems overly complicated. A: Not directly. This is a Topological Sort where you are 'hanging' the child nodes off a parent. If there is no dependency within the children the order that they are executed does not matter. If the children must be executed in a certain order then you do not have enough information to infer this - they would have to have additional levels of hierarchy. Assuming that the order of children within a parent is irrelevant then a topoligical sort will get you what you want. You won't get this into a single query in most SQL dialects - you will have to write a sproc to do it. If the order of the children within the node is relevant then you need to maintain the task order within the parent. A query using ParentNodeID, TaskOrder and count (*) will pick out duplicates but unless the system has additional information to order the tasks you will still need manual intervention to select the correct order. Please add comments if you want me to clarify something. A: This looks like a job for ROW_Number. DECLARE @Tasks TABLE ( TaskId int PRIMARY KEY, ParentTaskId int, TaskOrder int, TaskName varchar(30) ) INSERT INTO @Tasks(TaskId, ParentTaskId, TaskOrder, TaskName) SELECT 1, null, 1, 'ParentTask' INSERT INTO @Tasks(TaskId, ParentTaskId, TaskOrder, TaskName) SELECT 2, 1, 2, 'B' INSERT INTO @Tasks(TaskId, ParentTaskId, TaskOrder, TaskName) SELECT 3, 1, 1, 'A' INSERT INTO @Tasks(TaskId, ParentTaskId, TaskOrder, TaskName) SELECT 4, 1, 3, 'C' --Initial SELECT * FROM @Tasks WHERE ParentTaskId = 1 ORDER BY TaskOrder DELETE FROM @Tasks WHERE TaskId = 2 --After Delete SELECT * FROM @Tasks WHERE ParentTaskId = 1 ORDER BY TaskOrder UPDATE t SET TaskOrder = NewTaskOrder FROM @Tasks t JOIN ( SELECT TaskId, ROW_Number() OVER(ORDER BY TaskOrder) as NewTaskOrder FROM @Tasks WHERE ParentTaskId = 1 ) sub ON t.TaskId = sub.TaskId --After Update SELECT * FROM @Tasks WHERE ParentTaskId = 1 ORDER BY TaskOrder A: Delete task 88: UPDATE TaskTable SET ParentTaskID = (SELECT ParentTaskID AS temp FROM Task_Table t1 WHERE TaskID = 88) WHERE TaskID IN (SELECT TaskID task2 FROM TaskTable t2 WHERE ParentTaskID = 88); Delete FROM TaskTable WHERE TaskID = 88; Of course, you could eliminate the delete, and just leave the record lying around for future reporting purposes. CAVEAT: NOT TESTED!!!
{ "language": "en", "url": "https://stackoverflow.com/questions/149639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Best way to make NSRunLoop wait for a flag to be set? In the Apple documentation for NSRunLoop there is sample code demonstrating suspending execution while waiting for a flag to be set by something else. BOOL shouldKeepRunning = YES; // global NSRunLoop *theRL = [NSRunLoop currentRunLoop]; while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]); I have been using this and it works but in investigating a performance issue I tracked it down to this piece of code. I use almost exactly the same piece of code (just the name of the flag is different :) and if I put a NSLog on the line after the flag is being set (in another method) and then a line after the while() there is a seemingly random wait between the two log statements of several seconds. The delay does not seem to be different on slower or faster machines but does vary from run to run being at least a couple of seconds and up to 10 seconds. I have worked around this issue with the following code but it does not seem right that the original code doesn't work. NSDate *loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1]; while (webViewIsLoading && [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate:loopUntil]) loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1]; using this code, the log statements when setting the flag and after the while loop are now consistently less than 0.1 seconds apart. Anyone any ideas why the original code exhibits this behaviour? A: At your code the current thread will check for the variable to have changed every 0.1 seconds. In the Apple code example, changing the variable will not have any effect. The runloop will run till it processes some event. If the value of webViewIsLoading has changed, no event is generated automatically, thus it will stay in the loop, why would it break out of it? It will stay there, till it gets some other event to process, then it will break out of it. This may happen in 1, 3, 5, 10 or even 20 seconds. And until that happens, it will not break out of the runloop and thus it won't notice that this variable has changed. IOW the Apple code you quoted is indeterministic. This example will only work if the value change of webViewIsLoading also creates an event that causes the runloop to wake up and this seems not to be the case (or at least not always). I think you should re-think the problem. Since your variable is named webViewIsLoading, do you wait for a webpage to be loaded? Are you using Webkit for that? I doubt you need such a variable at all, nor any of the code you have posted. Instead you should code your app asynchronously. You should start the "web page load process" and then go back to the main loop and as soon as the page finished loading, you should asynchronously post a notification that is processed within the main thread and runs the code that should run as soon as loading has finished. A: Runloops can be a bit of a magic box where stuff just happens. Basically you're telling the runloop to go process some events and then return. OR return if it doesn't process any events before the timeout is hit. With 0.1 second timeout, you're htting the timeout more often than not. The runloop fires, doesn't process any events and returns in 0.1 of second. Occasionally it'll get a chance to process an event. With your distantFuture timeout, the runloop will wait foreever until it processes an event. So when it returns to you, it has just processed an event of some kind. A short timeout value will consume considerably more CPU than the infinite timeout but there are good reasons for using a short timeout, for example if you want to terminate the process/thread the runloop is running in. You'll probably want the runloop to notice that a flag has changed and that it needs to bail out ASAP. You might want to play around with runloop observers so you can see exactly what the runloop is doing. See this Apple doc for more information. A: I’ve had similar issues while trying to manage NSRunLoops. The discussion for runMode:beforeDate: on the class references page says: If no input sources or timers are attached to the run loop, this method exits immediately; otherwise, it returns after either the first input source is processed or limitDate is reached. Manually removing all known input sources and timers from the run loop is not a guarantee that the run loop will exit. Mac OS X may install and remove additional input sources as needed to process requests targeted at the receiver’s thread. Those sources could therefore prevent the run loop from exiting. My best guess is that an input source is attached to your NSRunLoop, perhaps by OS X itself, and that runMode:beforeDate: is blocking until that input source either has some input processed, or is removed. In your case it was taking "couple of seconds and up to 10 seconds" for this to happen, at which point runMode:beforeDate: would return with a boolean, the while() would run again, it would detect that shouldKeepRunning has been set to NO, and the loop would terminate. With your refinement the runMode:beforeDate: will return within 0.1 seconds, regardless of whether or not it has attached input sources or has processed any input. It's an educated guess (I'm not an expert on the run loop internals), but think your refinement is the right way to handle the situation. A: Okay, I explained you the problem, here's a possible solution: @implementation MyWindowController volatile BOOL pageStillLoading; - (void) runInBackground:(id)arg { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; // Simmulate web page loading sleep(5); // This will not wake up the runloop on main thread! pageStillLoading = NO; // Wake up the main thread from the runloop [self performSelectorOnMainThread:@selector(wakeUpMainThreadRunloop:) withObject:nil waitUntilDone:NO]; [pool release]; } - (void) wakeUpMainThreadRunloop:(id)arg { // This method is executed on main thread! // It doesn't need to do anything actually, just having it run will // make sure the main thread stops running the runloop } - (IBAction)start:(id)sender { pageStillLoading = YES; [NSThread detachNewThreadSelector:@selector(runInBackground:) toTarget:self withObject:nil]; [progress setHidden:NO]; while (pageStillLoading) { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } [progress setHidden:YES]; } @end start displays a progress indicator and captures the main thread in an internal runloop. It will stay there till the other thread announces that it is done. To wake up the main thread, it will make it process a function with no purpose other than waking the main thread up. This is just one way how you can do it. A notification being posted and processed on main thread might be preferable (also other threads could register for it), but the solution above is the simplest I can think of. BTW it is not really thread-safe. To really be thread-safe, every access to the boolean needs to be locked by a NSLock object from either thread (using such a lock also makes "volatile" obsolete, as variables protected by a lock are implicit volatile according to POSIX standard; the C standard however doesn't know about locks, so here only volatile can guarantee this code to work; GCC doesn't need volatile to be set for a variable protected by locks). A: In general, if you are processing events yourself in a loop, you're Doing It Wrong. It can cause a ton of messy problems, in my experience. If you want to run modally -- for example, showing a progress panel -- run modally! Go ahead and use the NSApplication methods, run modally for the progress sheet, then stop the modal when the load is done. See the Apple documentation, for example http://developer.apple.com/documentation/Cocoa/Conceptual/WinPanel/Concepts/UsingModalWindows.html . If you just want a view to be up for the duration of your load, but you don't want it to be modal (eg, you want other views to be able to respond to events), then you should do something much simpler. For instance, you could do this: - (IBAction)start:(id)sender { pageStillLoading = YES; [NSThread detachNewThreadSelector:@selector(runInBackground:) toTarget:self withObject:nil]; [progress setHidden:NO]; } - (void)wakeUpMainThreadRunloop:(id)arg { [progress setHidden:YES]; } And you're done. No need to keep control of the run loop! -Wil A: If you want to be able to set your flag variable and have the run loop immediately notice, just use -[NSRunLoop performSelector:target:argument:order:modes: to ask the run loop to invoke the method that sets the flag to false. This will cause your run loop to spin immediately, the method to be invoked, and then the flag will be checked. A: Your second example just work around as you poll to check input of the run loop within time interval 0.1. Occasionally I find a solution for your first example: BOOL shouldKeepRunning = YES; // global NSRunLoop *theRL = [NSRunLoop currentRunLoop]; while (shouldKeepRunning && [theRL runMode:NSRunLoopCommonModes beforeDate:[NSDate distantFuture]]);
{ "language": "en", "url": "https://stackoverflow.com/questions/149646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: Implementation of AJP protocol in Java From Apache, you can use the "mod_jk" module to send HTTP requests to Tomcat using the "AJP" protocol, which is far more efficient that HTTP itself. I want to do the same, but from a Java program. I want to use "AJP" because of its good performances (and Tomcat is not bad after all). Does someone know about a Java implementation of the client side of "AJP" ? A: Doesn't the tomcat-ajp.jar present in %TOMCAT_HOME%/server/lib have the AJP implementation? A: There's open source Apache ajp-client available if someone needs it: This is a java implementation of an ajp13 client, allowing to send requests to a servlet container using this protocol. A: Whithout any real idea, but have you looked into Tomcat's source code, yet? Maybe Tomcat doesn't just implement the receiving end of AJP.
{ "language": "en", "url": "https://stackoverflow.com/questions/149662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Search for text between delimiters in MySQL I am trying to extract a certain part of a column that is between delimiters. e.g. find foo in the following test 'esf :foo: bar So in the above I'd want to return foo, but all the regexp functions only return true|false, is there a way to do this in MySQL A: This should work if the two delimiters only appear twice in your column. I am doing something similar... substring_index(substring_index(column,':',-2),':',1) A: Here ya go, bud: SELECT SUBSTR(column, LOCATE(':',column)+1, (CHAR_LENGTH(column) - LOCATE(':',REVERSE(column)) - LOCATE(':',column))) FROM table Yea, no clue why you're doing this, but this will do the trick. By performing a LOCATE, we can find the first ':'. To find the last ':', there's no reverse LOCATE, so we have to do it manually by performing a LOCATE(':', REVERSE(column)). With the index of the first ':', the number of chars from the last ':' to the end of the string, and the CHAR_LENGTH (don't use LENGTH() for this), we can use a little math to discover the length of the string between the two instances of ':'. This way we can peform a SUBSTR and dynamically pluck out the characters between the two ':'. Again, it's gross, but to each his own. A: A combination of LOCATE and MID would probably do the trick. If the value "test 'esf :foo: bar" was in the field fooField: MID( fooField, LOCATE('foo', fooField), 3); A: I don't know if you have this kind of authority, but if you have to do queries like this it might be time to renormalize your tables, and have these values in a lookup table. A: With only one set of delimeters, the following should work: SUBSTR( SUBSTR(fooField,LOCATE(':',fooField)+1), 1, LOCATE(':',SUBSTR(fooField,LOCATE(':',fooField)+1))-1 ) A: mid(col, locate('?m=',col) + char_length('?m='), locate('&o=',col) - locate('?m=',col) - char_length('?m=') ) A bit compact form by replacing char_length(.) with the number 3 mid(col, locate('?m=',col) + 3, locate('&o=',col) - locate('?m=',col) - 3) the patterns I have used are '?m=' and '&o'. A: select mid(col from locate(':',col) + 1 for locate(':',col,locate(':',col)+1)-locate(':',col) - 1 ) from table where col rlike ':.*:'; A: If you know the position you want to extract from as opposed to what the data itself is: $colNumber = 2; //2nd position $sql = "REPLACE(SUBSTRING(SUBSTRING_INDEX(fooField, ':', $colNumber), LENGTH(SUBSTRING_INDEX(fooField, ':', $colNumber - 1)) + 1)"; A: This is what I am extracting from (mainly colon ':' as delimiter but some exceptions), as column theline255 in table loaddata255: 23856.409:0023:trace:message:SPY_EnterMessage (0x2003a) L"{#32769}" [0081] WM_NCCREATE sent from self wp=00000000 lp=0023f0b0 This is the MySql code (It quickly did what I want, and is straight forward): select time('2000-01-01 00:00:00' + interval substring_index(theline255, '.', 1) second) as hhmmss , substring_index(substring_index(theline255, ':', 1), '.', -1) as logMilli , substring_index(substring_index(theline255, ':', 2), ':', -1) as logTid , substring_index(substring_index(theline255, ':', 3), ':', -1) as logType , substring_index(substring_index(theline255, ':', 4), ':', -1) as logArea , substring_index(substring_index(theline255, ' ', 1), ':', -1) as logFunction , substring(theline255, length(substring_index(theline255, ' ', 1)) + 2) as logText from loaddata255 and this is the result: # LogTime, LogTimeMilli, LogTid, LogType, LogArea, LogFunction, LogText '06:37:36', '409', '0023', 'trace', 'message', 'SPY_EnterMessage', '(0x2003a) L\"{#32769}\" [0081] WM_NCCREATE sent from self wp=00000000 lp=0023f0b0' A: This one looks elegant to me. Strip all after n-th separator, rotate string, strip everything after 1. separator, rotate back. select reverse( substring_index( reverse(substring_index(str,separator,substrindex)), separator, 1) ); For example: select reverse( substring_index( reverse(substring_index('www.mysql.com','.',2)), '.', 1 ) ); A: you can use the substring / locate function in 1 command here is a mice tutorial: http://infofreund.de/mysql-select-substring-2-different-delimiters/ The command as describes their should look for u: **SELECT substr(text,Locate(' :', text )+2,Locate(': ', text )-(Locate(' :', text )+2)) FROM testtable** where text is the textfield which contains "test 'esf :foo: bar" So foo can be fooooo or fo - the length doesnt matter :).
{ "language": "en", "url": "https://stackoverflow.com/questions/149690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Best strategy to implement stackoverflow style badges system in asp.net mvc I was wondering what would be the best strategy to implement a badges system using asp.net mvc. The one that stackoverflow has is pretty interesting. What do you suggest? I guess I need to clarify the question a bit. The problem would be the different criteria for earning every badges. How do make that logic extensible? A: I'd do it purely in T-SQL, and set up a SQL job that runs periodically (Jeff did it using C#, and has a goofy system where it runs the process based on a page request). Basicly, in your SQL Job, scan your member tables and calculate if anyone is qualified for a badge, if so, update the badge table(s). Then in the front end, do a query to retrieve new badges for a member on each request.
{ "language": "en", "url": "https://stackoverflow.com/questions/149697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Interlocked equivalent on Linux In a C++ Linux app, what is the simplest way to get the functionality that the Interlocked functions on Win32 provide? Specifically, a lightweight way to atomically increment or add 32 or 64 bit integers? A: Just few notes to clarify the issue which has nothing to do with Linux. RWM (read-modify-write) operations and those that do not execute in a single-step need the hardware-support to execute atomically; among them increments and decrements, fetch_and_add, etc. For some architecture (including I386, AMD_64 and IA64) gcc has a built-in support for atomic memory access, therefore no external libray is required. Here you can read some information about the API. A: Intel's open-source ThreadBuildingBlocks has a template, Atomic, that offers the same functionality as .NET's Interlocked class. Unlike gcc's Atomic built-ins, it's cross platform and doesn't depend on a particular compiler. As Nemanja Trifunovic correctly points out above, it does depend on the compare-and-swap CPU instruction provided by x86 and Itanium chips. I guess you wouldn't expect anything else from an Intel library : ) A: Strictly speaking, Linux cannot offer atomic "interlocked" functions like ones in Win32, simply because these functions require hardware support, and Linux runs on some platforms that don't offer that support. Having said that, if you can constrain yourself to Intel x86/x64, take a look at the implementation of reference counting in Boost shared pointers library. A: The atomic functions from the Apache Portable Runtime are really close to the Win32 InterlockedXXX functions. A: You can insert some assembly code in your source, to use x68 interlocked instructions directly. You should use a lock xadd operation. See for instance this. A: The fairly common glib library that's used in GTK and QT programming as well as standalone offers a variety of atomic operations. See http://library.gnome.org/devel/glib/2.16/glib-Atomic-Operations.html for a list. There are g_atomic functions for most of the operations that Interlocked supports on Win32, and on platforms where the hardware directly supports these, they are inlined as the needed assembly code. A: Upon further review, this looks promising. Yay stack overflow.
{ "language": "en", "url": "https://stackoverflow.com/questions/149710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Pitfalls/gotchas of ClickOnce/smart-client deployment in .NET I have several .NET Windows Forms applications that I'm preparing to convert into a ClickOnce/smart-client deployment scenario. I've read the isn't-this-great tutorials, but are there pitfalls or "gotchas" that I should be aware of? There are several minor applications used off and on, but the main application is in C#, runs 24/7, is quite large, but only changes every few weeks. It also writes to a log file locallly and talks to local hardware devices. A: * *When updates are deployed, the built-in dialog will make it appear as if the entire application is being re-downloaded. In fact, only the changed DLLs are being downloaded, and the progress bar displayed is misleading/wrong. Don't waste time trying to figure out why all the assemblies are being re-deployed only to discover that they actually aren't. Not that I did that or anything. *When the certificate that you used to sign the original deployment manifest expires and you are issued a new one, you're in for a world of hurt (clients will all need to uninstall and reinstall). Details are at the horse's mouth. A: Most issues have been addressed but several people mentioned not being able to create a desktop shortcut. In fact, you can create a desktop shortcut with Visual Studio 2008 SP1. Also, if you aren't using the latest version of Visual Studio, you can always write code to create a shortcut to the installed start menu shortcut. A: We had an app we were going to deploy as a ClickOnce app. We needed the user to be able to modify some settings in the installation (such as the deployment path - IT wants to serve the files from their network share, not known at build time). When you change any of the files in your deployment, you need to re-calculate all of the hashes, and re-sign everything. So, if this solution is internal, you may not have problems passing around a signing cert, but if this is for clients, you will need to architect a fancy solution to bypass this issue. I have heard rumblings from somewhere within the bowels of the internets that a future version of ClickOnce will remove some of this headache. A: One of the pitfalls with ClickOnce is the fact that you can't install to the GAC. This is a problem if you want to install multiple applications that share DLL files. Each application will require a local copy of the DLL files. Also, multiple user installs are out. See the list comparing Window Installer to ClickOnce. A: You can't silently uninstall ClickOnce deployed applications. Also I think it's impossible to add parameters to the startup shortcut. A: There are a whole lot of things you can't do with ClickOnce applications, like install a shortcut to the user's desktop or have any sayso in where the application gets installed. For some people these are dealbreakers. Also it's been a while since I used it, but there's a special way you can use to figure out and display the ClickOnce version/build number, which is separate from the application's version/build number. You have to do a try/catch and if the ClickOnce version/build number throws an exception then the application is not running as a ClickOnce-deployed application (that is, it's running as a regularly compiled application or from Visual Studio). For an application which is simple (that is, not Microsoft Word, but rather a quick-and-dirty application to do something) and needs a lot of regular deployment, ClickOnce is great. But you rather quickly hit the wall of "oh, this can't be done by ClickOnce, please choose MSI or something else). A: You'll have less system access than your normal .NET application. That's because you'll get a lower trust level. More about that in .NET Framework Developer's Guide: ClickOnce Deployment and Security. My biggest problem with that was that it's not possible to encrypt sections of your configuration file with the machine key, because you don't have the access to that key (when you think about it it makes sense to protect that key). A: In case someone refers to this in a search, we have found many customers concerned with the lack of security 'distributing' their application. The application must be available in a public location - without any authentication - for it to be able to check for updates. The only exception is if you have Windows NT authentication. I think Securing ClickOnce Applications explains what I mean. Desktop icons are fairly trivial to do via code, and as mentioned, with 3.5 SP1, baked in - so that is no longer an issue. There is still an unfixed bug with the xmlSerializer - it doesn't get deployed properly in some cases. An easy workaround is to manually add this file to the deployment. PITA, but it is easy enough... It can be shocking when your deployment suddenly fails though... A: I didn't know that SP1 allowed you to create the desktop icon. Here's how we have been doing it (now known as "the hard way"): try { string company = string.Empty; string product = string.Empty; if (Attribute.IsDefined(asm, typeof(AssemblyCompanyAttribute))) { AssemblyCompanyAttribute asCompany = (AssemblyCompanyAttribute)Attribute.GetCustomAttribute(asm, typeof(AssemblyCompanyAttribute)); company = asCompany.Company; } if (Attribute.IsDefined(asm, typeof(AssemblyProductAttribute))) { AssemblyProductAttribute asProduct = (AssemblyProductAttribute)Attribute.GetCustomAttribute(asm, typeof(AssemblyProductAttribute)); product = asProduct.Product; } if (!string.IsNullOrEmpty(company) && !string.IsNullOrEmpty(product)) { string desktopPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), product + ".appref-ms"); string shortcutPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs), Path.Combine(company, product + ".appref-ms")); File.Copy(shortcutPath, desktopPath, true); } } catch { // Shortcut could not be created } A: Here are a few that I am aware of. * *Can't put an icon on the desktop. You can now. *I can't install for all users. *I need to jump through hoops to move the deployment to a different server. It is not a problem if you are developing internally, and the users can see the server that you are publishing to or if you are deploying to the public web, but it is not great if you need to roll out to multiple customer sites independently. *Since .NET 3.5 SP1 you do not need to sign the deployment manifest anymore which makes it much easier to move deployments to new servers. *I can't install assemblies in the GAC. You can get around this by creating regular install packages that are pre-requisites of the ClickOnce application. A: You can't install if the client is behind a proxy that requires authentication.
{ "language": "en", "url": "https://stackoverflow.com/questions/149718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: Programs don't work on Vista and Server 2008 Many, if not all, of my old VC++ 6.0 MFC apps don't work in Vista and Server 2008. I had that migration was a problem, but now it's my problem :( How do I go about making these things work? Is that possible? I've searched, but is there some repository of knowledge on this subject? edit: Compatibility mode seems to work. A: There should be specific reasons why they don't work, and of course, what exactly does not work. Maybe you should break each issue into a separate question (maybe here at SO) and tell us exactly what kind of problems you have when you try to run them, and what is the code that makes those errors show up. Without the details, it's too vague. There is no magic you can apply to make applications simply work just like that. A: There's a document available here that explains how to develop UAC compliant applications. A: Without recompiling, have you tried setting the compatibility mode on the program to Windows 98 or ME?
{ "language": "en", "url": "https://stackoverflow.com/questions/149753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you determine if WPF is using Hardware or Software Rendering? I'm benchmarking a WPF application on various platforms and I need an easy way to determine if WPF is using hardware or software rendering. I seem to recall a call to determine this, but can't lay my hands on it right now. Also, is there an easy, code based way to force one rendering pipeline over the other? A: Maybe the following can help with the second part of your question, that is, can you force one rendering pipeline over another: You can change a registry setting to disable hardware acceleration and force software rendering to occur at all times. We often use this to see if a particular issue we are seeing ... is related to video drivers. As an example of what I am talking about see this WPF forum post. One obvious thing to note here though ... is that this affects all WPF applications and really should only be used for testing purposes. To disable hardware acceleration: [HKEY_CURRENT_USER\Software\Microsoft\Avalon.Graphics] "DisableHWAcceleration"=dword:00000001 To enable hardware acceleration: [HKEY_CURRENT_USER\Software\Microsoft\Avalon.Graphics] "DisableHWAcceleration"=dword:00000000 Check out this MSDN link for more info. A: Based on the RenderingTier links, here is some code: logger.InfoFormat("WPF Tier = {0}",RenderCapability.Tier / 0x10000); RenderCapability.TierChanged += (sender, args) => logger.InfoFormat("WPF Tier Changed to {0}", RenderCapability.Tier / 0x10000); I'm still testing and working on this. See future edits/answers for what I find. A: Or use the Profiling Tools... New checkbox was added to tint the target application elements that use SW rendered legacy Bitmap Effects. A: Check RenderCapability.Tier * *Graphics Rendering Tiers *RenderCapability Class [UPDATE] * *RenderCapability.IsPixelShaderVersionSupported - Gets a value that indicates whether the specified pixel shader version is supported. *RenderCapability.IsShaderEffectSoftwareRenderingSupported - Gets a value that indicates whether the system can render bitmap effects in software. *RenderCapability.Tier - Gets a value that indicates the rendering tier for the current thread. *RenderCapability.TierChanged - Occurs when the rendering tier has changed for the Dispatcher object of the current thread. RenderCapability.Tier >> 16 * *Rendering Tier 0 - No graphics hardware acceleration. The DirectX version level is less than version 7.0. *Rendering Tier 1 - Partial graphics hardware acceleration. The DirectX version level is greater than or equal to version 7.0, and lesser than version 9.0. *Rendering Tier 2 - Most graphics features use graphics hardware acceleration. The DirectX version level is greater than or equal to version 9.0. A: I agreee with the second answer but that just says something about the ability of the machine to run using hw rendering not if the app is actually hw rendered. I made a simple app using a canvas and just rotating a rectangle with RotateTransform uses way to much CPU for a hw rendered application. That and the 'RenderCapability.Tier' value is 2 so there's enough hw capability to do it. Why doesn't then? A: .NET 4.0 provides the ability to force software rendering in code: public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { if (WeThinkWeShouldRenderInSoftware()) RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly; } } See this post for more information. A: To answer the second half of your question, there is no way I believe really to force one way over the other. Hardware rendering is automatically used if available, otherwise, software is. If you need to test it in Software mode, you'll need to use a low spec machine or use Remote Desktop to view the application running on another computer. Apart from reduced performance/framerate however, there shouldn't be any visible differences in appearance between the two. Use the RenderCapability class to know if you should disable things such as animation or effects in favour of performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/149763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: How to use GROUP BY to concatenate strings in MySQL? Basically the question is how to get from this: foo_id foo_name 1 A 1 B 2 C to this: foo_id foo_name 1 A B 2 C A: SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id; https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat From the link above, GROUP_CONCAT: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values. A: SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id; :- In MySQL, you can get the concatenated values of expression combinations . To eliminate duplicate values, use the DISTINCT clause. To sort values in the result, use the ORDER BY clause. To sort in reverse order, add the DESC (descending) keyword to the name of the column you are sorting by in the ORDER BY clause. The default is ascending order; this may be specified explicitly using the ASC keyword. The default separator between values in a group is comma (“,”). To specify a separator explicitly, use SEPARATOR followed by the string literal value that should be inserted between group values. To eliminate the separator altogether, specify SEPARATOR ''. GROUP_CONCAT([DISTINCT] expr [,expr ...] [ORDER BY {unsigned_integer | col_name | expr} [ASC | DESC] [,col_name ...]] [SEPARATOR str_val]) OR mysql> SELECT student_name, -> GROUP_CONCAT(DISTINCT test_score -> ORDER BY test_score DESC SEPARATOR ' ') -> FROM student -> GROUP BY student_name; A: The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024 characters, so we first do: SET group_concat_max_len=100000000; and then, for example: SELECT pub_id,GROUP_CONCAT(cate_id SEPARATOR ' ') FROM book_mast GROUP BY pub_id A: SELECT id, GROUP_CONCAT(CAST(name as CHAR)) FROM table GROUP BY id Will give you a comma-delimited string A: SELECT id, GROUP_CONCAT( string SEPARATOR ' ') FROM table GROUP BY id More details here. From the link above, GROUP_CONCAT: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values. A: Great answers. I also had a problem with NULLS and managed to solve it by including a COALESCE inside of the GROUP_CONCAT. Example as follows: SELECT id, GROUP_CONCAT(COALESCE(name,'') SEPARATOR ' ') FROM table GROUP BY id; Hope this helps someone else
{ "language": "en", "url": "https://stackoverflow.com/questions/149772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "440" }
Q: Crystalspace vs. Irrlicht vs. .....? So, I use Linux, and I've been trying to find the time to get into game programming. I started out with Panda3d and had some pretty decent results and got a feel for many of the concepts in game programming. Not too long after that, I decided to step it up a notch and go to something more powerful and C or C++ based. I'm probably just really dumb, but I could never really figure out how to use Crystalspace correctly. If somebody has any useful resources on how to use it, I would appreciate that. But in the meantime, I was messing around with Irrlicht and I like it, but I would like to know what more knowledgable people have to say about the subject. And maybe theres another awesome option out there I don't know about. A: I've spent some time working in the game industry. I'm also a Linux guy. I used Irrlicht to make a couple games, and used those as part of my resume, which helped get me get a job as a game programmer. Irrlicht has a cleaner API, lower system requirements and works better across platforms than Ogre, in my opinion. I've had a blast making games with Irrlicht. It's also fairly lightweight (much lighter than Ogre), with a very open license for any use, commercial or otherwise. Working with that engine did a lot to prepare me for working within the commercial game industry. A: Ogre3D http://www.ogre3d.org/ Is typically named together with crystalspace and irrlicht. Ogre and Irrlicht both are said to have a cleaner design than crystalspace so I wouldn't worry to much about problems with the latter. A: If you ask me, Irrlich is the best open source engine - it has clear architecture, good performance and requires lesser code to be written by programmer. I can not honestly compare Irrlicht with Crystal Space or Orge. I consider CS as mess of code, written by many different programmers in different manners - I am hard to imagine how to use it too (due to absolute lack of documentation). As for Ogre, it is not easier than D3D. I've examined different samples and fount plenty multyline fragments of code that are done with a single line in D3D. So, I simply can not see a reason, why to spent months learning OGRE's terrible API - if one has free time, I would advice to learn D3D itself. I can say even more - Irrlicht is better, than many commercial engines, for example - Torque (absolute lack of documentation, forces to start project over existing one etc.), Truevision etc. Of course, Irrlicht lacks some great features, AAA grade engines must have, but it is quite sufficient for smaller projects. If you have not BIG money to acquire Gamebryo and similar grades engine, I would advice to stick with Irrlicht - for first several projects at least. A: If you're looking for productive game development, then my best bet would be to use Unity 3D. I started off by using Irrlicht but quickly backed out because of non intuitive tools and a lot of stress on programming. Ogre seemed to be even more complex. Unity on the other hand is rapidly gaining grounds with each release. The recent Unity 4 is packed with a ton of features. With very little game dev knowledge, I've managed to write my own flight sim engine in Unity Android. Even learned to write shaders easily. Though advanced Unity licenses are paid, but they are well worth it. But you can always use Unity free edition to make commercial PC games. In all, game development is all about getting the hang of a game engine. Master any, and you will rule.
{ "language": "en", "url": "https://stackoverflow.com/questions/149773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using respond_to for graceful degradation with ajax in RoR 2.x I was going through the AWDR book on web development with ruby on rails and one of the issues with the old code was it didn't use respond_to to make sure the view used would be the javascript view. Now in some updated examples I've seen people mention they later, when implementing graceful degradation, use request.xhr? to tell if the user has javascript enabled, and if not they redirect the user. I was wondering if you could use respond_to to get the same behaviour and if so, if this is considered good form or not and why? So what I'm thinking of doing is something like: def function respond_to do |format| format.js do basic_stuff end format.html do basic_stuff user_redirect end end end It does seem to sorta violate the DRY principle, and I'm probably missing something about how the user and the server are interacting here. To be honest the API documentation did not make it entirely clear to me. A: Well you can refactor like this: def function basic_stuff # executed regardless of the mime types accepted respond_to do |format| format.html do user_redirect end end # will fall back rendering the default view - which you should ensure will be js end request.xhr? looks at the request‘s X-Requested-With header (to see whether it contains "XMLHttpRequest"). respond_to looks at the mime types accepted. You can use either to implement some sort of graceful degredation. BUT You won't be able to use xhr? for graceful degredation unless your ajax calls are setting that header (Prototype does this automatically). Moreover, respond_to gives more flexibility i.e. sending xml, json, js, whatever it might be from the same block. So I'd recommend respond_to here.
{ "language": "en", "url": "https://stackoverflow.com/questions/149776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: what's the fundamental difference between a jsp taglib vs including a jsp page? i have several common elements (components), that will generate some html. it seems my options are creating a taglib, or just putting that logic into a jsp page and including the jsp. whats the difference? positives vs negatives? A: Taglibs allow you to define (typed) parameters which you can document. Also taglibs can be aware of their location in the object tree so act differently in a different context; or call a specific template over and over again to create iterators or statement constructs. Are you aware that taglibs don't necessarily have to be written in Java? There is also a concept called tagfiles which allows you to write your taglib in JSP; often more suitable for flat compononents... quite close to includes. A: When you use a taglib the container typically: * *Writes and calls a helper method from within _jspService *Inside the helper method an instance of the tag class is created and standard methods are called (setParent(), doStartTag(), doEndTag() etc...) This keeps all the code within the same resource (the request does not get passed on to another component) and hence allows you to build in looping behaviour and access other components on the current page. There is overhead in learning Tag Libraries. But once you have got your first tag working its all downhill. Also the end result will be easier for non-developers to understand (assuming you choose good names for the tags). A: Tags (which include the easy-to-use JSP-like tag file mechanism) support invocation with strongly-typed, named parameters. Another incredibly useful and surprisingly often overlooked feature of JSP tags is the the JspFragment attribute type. This allows you to pass a chunk of JSP code, as a parameter, into a tag to be invoked, perhaps repeatedly. Includes lack these powerful parameterization features. A: taglibs make it easier to define and handle parameters, but there's a significant overhead to developing them. Includes are simpler, but less powerful. Much depends on your style. In my experience, people generally just use includes because they don't want to take the time to learn to create tablibs. Leading to a fair mess. As long as your team small and your includes not too complex, it's not too bad. But it is a code smell.
{ "language": "en", "url": "https://stackoverflow.com/questions/149777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How do you copy a record in a SQL table but swap out the unique id of the new row? This question comes close to what I need, but my scenario is slightly different. The source table and destination table are the same and the primary key is a uniqueidentifier (guid). When I try this: insert into MyTable select * from MyTable where uniqueId = @Id; I obviously get a primary key constraint violation, since I'm attempting to copy over the primary key. Actually, I don't want to copy over the primary key at all. Rather, I want to create a new one. Additionally, I would like to selectively copy over certain fields, and leave the others null. To make matters more complex, I need to take the primary key of the original record, and insert it into another field in the copy (PreviousId field). I'm sure there is an easy solution to this, I just don't know enough TSQL to know what it is. A: I know my answer is late to the party. But the way i solved is bit different than all the answers. I had a situation, i need to clone a row in a table except few columns. Those few will have new values. This process should support automatically for future changes to the table. This implies, clone the record without specifying any column names. My approach is to, * *Query Sys.Columns to get the full list of columns for the table and include the names of columns to skip in where clause. *Convert that in to CSV as column names. *Build Select ... Insert into script based on this. declare @columnsToCopyValues varchar(max), @query varchar(max) SET @columnsToCopyValues = '' --Get all the columns execpt Identity columns and Other columns to be excluded. Say IndentityColumn, Column1, Column2 Select @columnsToCopyValues = @columnsToCopyValues + [name] + ', ' from sys.columns c where c.object_id = OBJECT_ID('YourTableName') and name not in ('IndentityColumn','Column1','Column2') Select @columnsToCopyValues = SUBSTRING(@columnsToCopyValues, 0, LEN(@columnsToCopyValues)) print @columnsToCopyValues Select @query = CONCAT('insert into YourTableName (',@columnsToCopyValues,', Column1, Column2) select ', @columnsToCopyValues, ',''Value1'',''Value2'',', ' from YourTableName where IndentityColumn =''' , @searchVariable,'''') print @query exec (@query) A: Try this: insert into MyTable(field1, field2, id_backup) select field1, field2, uniqueId from MyTable where uniqueId = @Id; Any fields not specified should receive their default value (which is usually NULL when not defined). A: insert into MyTable (uniqueId, column1, column2, referencedUniqueId) select NewGuid(), // don't know this syntax, sorry column1, column2, uniqueId, from MyTable where uniqueId = @Id A: I'm guessing you're trying to avoid writing out all the column names. If you're using SQL Management Studio you can easily right click on the table and Script As Insert.. then you can mess around with that output to create your query. A: Ok, I know that it's an old issue but I post my answer anyway. I like this solution. I only have to specify the identity column(s). SELECT * INTO TempTable FROM MyTable_T WHERE id = 1; ALTER TABLE TempTable DROP COLUMN id; INSERT INTO MyTable_T SELECT * FROM TempTable; DROP TABLE TempTable; The "id"-column is the identity column and that's the only column I have to specify. It's better than the other way around anyway. :-) I use SQL Server. You may want to use "CREATE TABLE" and "UPDATE TABLE" at row 1 and 2. Hmm, I saw that I did not really give the answer that he wanted. He wanted to copy the id to another column also. But this solution is nice for making a copy with a new auto-id. I edit my solution with the idéas from Michael Dibbets. use MyDatabase; SELECT * INTO #TempTable FROM [MyTable] WHERE [IndexField] = :id; ALTER TABLE #TempTable DROP COLUMN [IndexField]; INSERT INTO [MyTable] SELECT * FROM #TempTable; DROP TABLE #TempTable; You can drop more than one column by separating them with a ",". The :id should be replaced with the id of the row you want to copy. MyDatabase, MyTable and IndexField should be replaced with your names (of course). A: Specify all fields but your ID field. INSERT INTO MyTable (FIELD2, FIELD3, ..., FIELD529, PreviousId) SELECT FIELD2, NULL, ..., FIELD529, FIELD1 FROM MyTable WHERE FIELD1 = @Id; A: I have the same issue where I want a single script to work with a table that has columns added periodically by other developers. Not only that, but I am supporting many different versions of our database as customers may not all be up-to-date with the current version. I took the solution by Jonas and modified it slightly. This allows me to make a copy of the row and then change the primary key before adding it back into the original source table. This is also really handy for working with tables that do not allow NULL values in columns and you don't want to have to specify each column name in the INSERT. This code copies the row for 'ABC' to 'XYZ' SELECT * INTO #TempRow FROM SourceTable WHERE KeyColumn = 'ABC'; UPDATE #TempRow SET KeyColumn = 'XYZ'; INSERT INTO SourceTable SELECT * FROM #TempRow; DELETE #TempRow; Once you have finished the drop the temp table. DROP TABLE #TempRow; A: If "key" is your PK field and it's autonumeric. insert into MyTable (field1, field2, field3, parentkey) select field1, field2, null, key from MyTable where uniqueId = @Id it will generate a new record, copying field1 and field2 from the original record A: My table has 100 fields, and I needed a query to just work. Now I can switch out any number of fields with some basic conditional logic and not worry about its ordinal position. * *Replace the below table name with your table name SQLcolums = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE (TABLE_NAME = 'TABLE-NAME')" Set GetColumns = Conn.Execute(SQLcolums) Do WHILE not GetColumns.eof colName = GetColumns("COLUMN_NAME") *Replace the original identity field name with your PK field name IF colName = "ORIGINAL-IDENTITY-FIELD-NAME" THEN ' ASSUMING THAT YOUR PRIMARY KEY IS THE FIRST FIELD DONT WORRY ABOUT COMMAS AND SPACES columnListSOURCE = colName columnListTARGET = "[PreviousId field name]" ELSE columnListSOURCE = columnListSOURCE & colName columnListTARGET = columnListTARGET & colName END IF GetColumns.movenext loop GetColumns.close *Replace the table names again (both target table name and source table name); edit your where conditions SQL = "INSERT INTO TARGET-TABLE-NAME (" & columnListTARGET & ") SELECT " & columnListSOURCE & " FROM SOURCE-TABLE-NAME WHERE (FIELDNAME = FIELDVALUE)" Conn.Execute(SQL) A: You can do like this: INSERT INTO DENI/FRIEN01P SELECT RCRDID+112, PROFESION, NAME, SURNAME, AGE, RCRDTYP, RCRDLCU, RCRDLCT, RCRDLCD FROM FRIEN01P There instead of 112 you should put a number of the maximum id in table DENI/FRIEN01P. A: Here is how I did it using ASP classic and couldn't quite get it to work with the answers above and I wanted to be able to copy a product in our system to a new product_id and needed it to be able to work even when we add in more columns to the table. Cn.Execute("CREATE TEMPORARY TABLE temprow AS SELECT * FROM product WHERE product_id = '12345'") Cn.Execute("UPDATE temprow SET product_id = '34567'") Cn.Execute("INSERT INTO product SELECT * FROM temprow") Cn.Execute("DELETE temprow") Cn.Execute("DROP TABLE temprow")
{ "language": "en", "url": "https://stackoverflow.com/questions/149784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "148" }
Q: SNMP SET with ACL and Set Community Name I need to perform a SNMP Set operation in a printer in the network which as an Access Control List configured (ACL) and my host's IP Address is not in the ACL table. I'm getting a strange behavior: When I have a SNMPv1 Set community name configured, I am ONLY able to perform a SNMP Set if my host ip is in the ACL table. If there is no SNMPSet community name configured, I am able to perform SNMP Set normally even if my ip address is not in the ACL table. So, does anyone know if there is any relationship between the ACL table and the SNMP Set community name? I mean, the ACL is only "working" when the set community name is configured. Does this make sense? Thanks for any help A: The ACL is on the printer itself. We are connected through a network and the printer is in another subnet. The ACL contains only one entry and there is not a blocking rule. The issue itself is regarding the behavior related with the SNMP Set Community itself that I'd like to understand if there is any relationship between them. A: So the ACL is on a local router or the printer itself? What model of printer is it and how are you connected to it, are you on the same network or do you pass through the router to get to the printer which is on a seperate network range? I would check the full ACL list as perhaps there is a block all rule that is stopping you from accessing atm. A: As far as I know, such ACL is not a default part of SNMP, and its function can be varied by the vendor. Like your test revealed, this may be a security flaw. Consider reporting this issue to the vendor. If they have a fix, they will send to you.
{ "language": "en", "url": "https://stackoverflow.com/questions/149795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a disadvantage to blindly using INSERT in MySQL? Often I want to add a value to a table or update the value if its key already exists. This can be accomplished in several ways, assuming a primary or unique key is set on the 'user_id' and 'pref_key' columns in the example: 1. Blind insert, update if receiving a duplicate key error: // Try to insert as a new value INSERT INTO my_prefs (user_id, pref_key, pref_value) VALUES (1234, 'show_help', 'true'); // If a duplicate-key error occurs run an update query UPDATE my_prefs SET pref_value = 'true' WHERE user_id=1234 AND pref_key='show_help'; 2. Check for existence, then select or update: // Check for existence SELECT COUNT(*) FROM my_prefs WHERE user_id=1234 AND pref_key='show_help'; // If count is zero, insert INSERT INTO my_prefs (user_id, pref_key, pref_value) VALUES (1234, 'show_help', 'true'); // If count is one, update UPDATE my_prefs SET pref_value = 'true' WHERE user_id=1234 AND pref_key='show_help'; The first way seems to be preferable as it will require only one query for new inserts and two for an update, where as the second way will always require two queries. Is there anything I'm missing though that would make it a bad idea to blindly insert? A: There is the third MySQL way, which would be the preferred one in that RDBMS INSERT INTO my_prefs (user_id, pref_key, pref_value) VALUES (1234, 'show_help', 'true') ON DUPLICATE KEY UPDATE pref_value = 'true' A: Personally I am never a fan of exception based programming (expecting an exception in the normal operation of an application) and to me the second example is much more readable/maintainable. There are situations where this would make a difference (very tight loops for example) but I think there should be a good reason to write code like this rather than it being the default. A: If you want to avoid "the exception" by perhaps inserting a doublette and you want to use standard SQL (and your programming language / database returns the count of the updated rows) then use the following "SQL" - commands (pseudo-code): int i = SQL("UPDATE my_prefs ..."); if(i==0) { SQL("INSERT INTO my_prefs ..."); } This also takes in account that - for the most use cases - updates do occur more often than inserts. A: You may be able to use REPLACE instead, or if using a more current MySQL you get the option of using "INSERT ... ON DUPLICATE KEY UPDATE" The fact that several people brought this up in quick succession says "always check the MySQL docs" when you have an issue, as they're decent and in many cases, leads directly to the solution. A: Will there be concurrent INSERTs to these rows? DELETEs? "ON DUPLICATE" sounds great (the behavior is just what you want) provided that you're not concerned about portability to non-MySQL databases. The "blind insert" seems reasonable and robust provided that rows are never deleted. (If the INSERT case fails because the row exists, the UPDATE afterward should succeed because the row still exists. But this assumption is false if rows are deleted - you'd need retry logic then.) On other databases without "ON DUPLICATE", you might consider an optimization if you find latency to be bad: you could avoid a database round trip in the already-exists case by putting this logic in a stored procedure. The "check for existence" is tricky to get right if there are concurrent INSERTs. Rows could be added between your SELECT and your UPDATE. Transactions won't even really help - I think even at isolation level "serializable", you'll see "could not serialize access due to concurrent update" errors occasionally (or whatever the MySQL equivalent error message is). You'll need retry logic, so I'd say the person above who suggests using this method to avoid "exception-based programming" is wrong, as is the person who suggests doing the UPDATE first for the same reason. A: have a look at the ON DUPLICATE KEY syntax in http://dev.mysql.com/doc/refman/5.0/en/insert-select.html INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE] [INTO] tbl_name [(col_name,...)] SELECT ... [ ON DUPLICATE KEY UPDATE col_name=expr, ... ] A: The first way is the preferred way as far as I know. A: In your DAO model you could have an id field. * *If set to null / -1 / whatever, the data hasn't been persisted. *When you persist it (or retrieve from database), set it to the id value in the database. *Your persist method can check the ID and pass it onto the update() or add() implementation. *Flaws: Getting out of sync with the database, etc. I'm sure there are more, but I really should get some work done... A: So long as you're using MySQL, you can use the ON DUPLICATE keyword. For example: INSERT INTO my_prefs (user_id, pref_key, pref_value) VALUES (1234, 'show_help', 'true') ON DUPLICATE KEY UPDATE (pref_key, pref_value) VALUES ('show_help', 'true');
{ "language": "en", "url": "https://stackoverflow.com/questions/149796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Multi-line label in RadioButton component (AS3) I'm making a small quiz-application in Flash (and ActionScript 3). Decided to use the RadioButton-component for radiobuttons, but I'm having some problems getting the word-wrapping to work. The code for creating the button can be found below. _button = new RadioButton(); _button.setStyle("textFormat", _format); _button.label = _config.toString(); _button.width = Number(_defaults.@alen); _button.textField.width = Number(_defaults.@alen); _button.textField.multiline = true; _button.textField.wordWrap = true; _button.value = _config.@value; _button.group = _group; _button.x = _config.@x; _button.y = _config.@y; _config is a piece of XML, and _defaults is a piece of XML containing size-information and font-setup When I set _button.textField.wordWrap to true, the text gets split into multiple lines, but it's not split at _defaults.@alen, which I want, but looks like it happens pretty much after each word. Also, it sometimes splits it into several lines, but doesn't display it all until the mouse hovers over it. A: Two possibilities: width should be in pixels, not in characters. In addition, don't forget that the button itself uses up some of the width. If you can't get it to work, instead of banging your head on it, might want to just create the label separately, either a simple TextField, or using a Label component. Slightly more code, but might be worth it to spend an extra 10 minutes writing code versus two hours getting the component to work how you want. A: The passed width is in pixels. I previously had some problems with not being able to style the label with CSS (at least I couldn't figure out how), so went with a regular textfield. Was a bit of a hassle to get the aligning just right, so I was hoping it was possible to move back to just the component. I've been banging my head for two-three hours now, so I think it's back to a regular textfield again for me... A: I think a better solution is here . Check that out.
{ "language": "en", "url": "https://stackoverflow.com/questions/149800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Stored Procedure Ownership Chaining I have several stored procedures in my database that are used to load data from a datamart that is housed in a separate database. These procedures are, generally, in the form: CREATE PROCEDURE load_stuff WITH EXECUTE AS OWNER AS INSERT INTO my_db.dbo.report_table ( column_a ) SELECT column_b FROM data_mart.dbo.source_table WHERE foo = 'bar'; These run fine when I execute the query in SQL Server Management Studio. When I try to execute them using EXEC load_stuff, the procedure fails with a security warning: The server principal "the_user" is not able to access the database "data_mart" under the current security context. The OWNER of the sproc is dbo, which is the_user (for the sake of our example). The OWNER of both databases is also the_user and the_user is mapped to dbo (which is what SQL Server should do). Why would I be seeing this error in SQL Server? Is this because the user in question is being aliased as dbo and I should use a different user account for my cross-database data access? Edit I understand that this is because SQL Server disables cross database ownership chaining by default, which is good. However, I'm not sure of the best practice in this situation. If anyone has any input on the best practice for this scenario, it would be greatly appreciated. Edit 2 The eventual solution was to set TRUSTWORTHY ON on both of the databases. This allows for limited ownership chaining between the two databases without resorting to full database ownership chaining. A: Why not remove EXECUTE AS OWNER? Usually, my user executing the SP would have appropriate rights in both databases, and I don't have to do that at all. A: There is no need to create login, you can just enable guest user in target DB. grant connect to guest This allows executing user to enter DB under guest context, and when "db chaining is ON access will not be checked in target DB. A: Actually, DBO is a role (you can consider it as a group of users), not a user in himself. (Unless you can connect to SQL SERVER using dbo:passwordfordbo it's not a user). Usually, in the wonderful world of SQL Server, if you grant userX right to execute storedprocY then X gets the right to perform all the task Y contains even if he doesn't have all the permission on all the objects used in Y. That's an extremely useful feature to encapsulate business logic in a stored procedure. (Your user have NO access on the table but they do can EXECUTE one stored proc). When we talk about "ownership chaining" it means the following (please correct me if I am wrong though) - If ownership chaining is disabled: the right to execute procedureX will work as long as all the required objects are in the same database - Of chaining is enabled: That "privilege" will expands towards all databases. Hope that helps,
{ "language": "en", "url": "https://stackoverflow.com/questions/149808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Use jQuery to send Excel data using AJAX I have the following function that is pulling data from a database. The ajax call is working correctly. How can I send the tab delimited data in my success function to the user? Setting the contect type to "application/vnd.ms-excel" didn't work. The alert on success shows the correctly formatted data. function SendToExcel() { $.ajax({ type: "GET", url: "/Search.aspx", contentType: "application/vnd.ms-excel", dataType: "text", data: "{id: '" + "asdf" + "'}", success: function(data) { alert(data); }, error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR.responseText); }}); } I don't want to display the data in the browser--I want to send it to Excel. EDIT: I found a way to do what I wanted. Instead of redirecting the users to a new page that would prompt them to save/open an Excel file, I opened the page inside a hidden iframe. That way, the users click a button, and they are prompted to save/open an Excel file. No page redirection. Is it Ajax? No, but it solves the real problem I had. Here's the function I'm calling on the button click: function SendToExcel() { var dataString = 'type=excel' + '&Number=' + $('#txtNumber').val() + '&Reference=' + $('#txtReference').val() $("#sltCTPick option").each(function (i) { dataString = dataString + '&Columns=' + this.value; }); top.iExcelHelper.location.href = "/Reports/JobSearchResults.aspx?" + dataString;; } A: in HTML I have a Form with serial inputs elements and a button that calls a JavaScript function onclick="exportExcel(); then in JavaScript file: function exportExcel(){ var inputs = $("#myForm").serialize(); var url = '/ajaxresponse.php?select=exportExcel&'+inputs; location.href = url; } and finally a pivot file who response to something PHP code: case 'exportExcel':{ ob_end_clean(); header("Content-type: application/vnd.ms-excel"); header("Content-Disposition: attachment; filename=exportFile.xls"); echo $html->List($bd->ResultSet($_GET)); } $html is an object who handle html, and $bd is an object that returns data from Database send your own html table or whatever you want. A: Since it uses JavaScript, AJAX is bound by JavaScript's designed limitations, which includes interacting with other processes on the client's machine. In this case, it's a good thing; you wouldn't want a site to be able to automatically load an Excel document with a malicious macro in it. If you want to display the data in the browser, you can use AJAX; otherwise, you'll want to just give a link to an Excel document and let the browser's regular download handling capabilities figure out what to do. A: AJAX is... the wrong choice. Redirect the user to a server resource that will send the data down with the proper MIME type, and let the browser figure out what to do with it. A: It's possible that you don't want to do this with javascript. What I think you want to do is create a response page with the mine type application/csv then redirect the user to that page. I would probably do a window.open() since the user doesn't lose the page they're currently on.
{ "language": "en", "url": "https://stackoverflow.com/questions/149821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: Accessing a dynamitcally added buttoncolumn's (in a Datagrid) click event. C#/ASP.NET When I dynamically create a Datagrid and add in a new buttoncolumn how do I access the buttoncolumn_click event? Thanks. A: protected void Page_Load(object sender, EventArgs e) { DataGrid dg = new DataGrid(); dg.GridLines = GridLines.Both; dg.Columns.Add(new ButtonColumn { CommandName = "add", HeaderText = "Event Details", Text = "Details", ButtonType = ButtonColumnType.PushButton }); dg.DataSource = getDataTable(); dg.DataBind(); dg.ItemCommand += new DataGridCommandEventHandler(dg_ItemCommand); pnlMain.Controls.Add(dg); } protected void dg_ItemCommand(object source, DataGridCommandEventArgs e) { if (e.CommandName == "add") { throw new Exception("add it!"); } } protected DataTable getDataTable() { // returns your data table } A: This article on the MSDN site clearly explains how to go about adding a button into a datagrid. Instead of using the click event of the button you'll use the command event of the DataGrid. Each button will be passing specific commandarguments that you will set. This article shows how to use the command event with buttons. In it you use CommandArguments and CommandNames. A: Here is where I create the datagrid: System.Web.UI.WebControls.DataGrid Datagridtest = new System.Web.UI.WebControls.DataGrid(); Datagridtest.Width = 600; Datagridtest.GridLines = GridLines.Both; Datagridtest.CellPadding = 1; ButtonColumn bc = new ButtonColumn(); bc.CommandName = "add"; bc.HeaderText = "Event Details"; bc.Text = "Details"; bc.ButtonType = System.Web.UI.WebControls.ButtonColumnType.PushButton; Datagridtest.Columns.Add(bc); PlaceHolder1.Controls.Add(Datagridtest); Datagridtest.DataSource = dt; Datagridtest.DataBind(); And here is the event I am trying to use: protected void Datagridtest_ItemCommand(object source, DataGridCommandEventArgs e) { .... } Thought that might help because I can't seem to capture the event at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/149823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What the heck does loader.load((newSource is URLRequest)? newSource:new URLRequest(newSource)); do? I ran across the following code in Ely Greenfield's SuperImage from his Book component - I understand loader.load() but what does the rest of do? loader.load((newSource is URLRequest)? newSource:new URLRequest(newSource)); It looks like some kind of crazy inline if statement but still, I'm a little preplexed. And if it is an if statement - is this way better than a regular if statement? A: ? is called the 'ternary operator' and it's basic use is: (expression) ? (evaluate to this if expression is true) : (evaluate to this otherwise); In this case, if newSource is a URLRequest, loader.load will be passed newSource directly, otherwise it will be passed a new URLRequest built from newSource. The ternary operator is frequently used as a more concise form of if statement as it allows ifs to be inlined. The corresponding code in this case would be: if (newSource is URLRequest) loader.load(newSource); else loader.load(new URLRequest(newSource)); A: Basically what it says is: if newsource is a type of URLRequest, then pass the newSource variable into the load method, if its not a type of URLReuqest, create a new URLRequest and pass that into the load method. The basic syntax is: (condition) ? (code to execute if true) : (code to execute if false) A: this is using the ternary ?: operator. the first part is the condition, between the ? and : is what to return if the condition is true. after the : is what to return if the condition is false. a simpler example String str = null; int x = (str != null) ? str.length() : 0; would be the same as String str = null; int x; if (str != null) x = str.length() else x = 0; A: Basically what this means, as far as im aware of, is its asking wheter that variable newSource's class is String or URLRequest like workmad and jason explained. If its an URLRequest it will run loader.load(newSource:URLRequest). If its not an URLRequest it means automatically that it is a String (in other words the url). And in that case it will run loader.load(new URLrequest(newSource:String). The complete code could look something like this: function myFunction(newSource:Object):SomeClass { var loader:URLLoader = new URLLoader(); loader.load((newSource is URLRequest)? newSource:new URLRequest(newSource)); } Regards, Filipe A.
{ "language": "en", "url": "https://stackoverflow.com/questions/149825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Preferred path to applications on OSX? I want to be able to run a text editor from my app, as given by the user in the TEXT_EDITOR environment variable. Now, assuming there is nothing in that variable, I want to default to the TextEdit program that ships with OSX. Is it kosher to hardcode /Applications/TextEdit.app/Contents/MacOS/TextEdit into my app, or is there a better way to call the program? Edit: For the record, I am limited to running a specific application path, in C. I'm not opening a path to a text file. Edit 2: Seriously people, I'm not opening a file here. I'm asking about an application path for a reason. A: Mac OS X has a mechanism called "uniform type identifiers" that it uses to track associations between data types and applications that can handle them. The subsystem that manages this is Launch Services. You can do one of two things: * *If you have a file with a reasonably well-known path extension, e.g. .txt, you can just ask NSWorkspace to open the file in the appropriate application. *If you don't have a well-known path extension, but you know the type of data, you can ask Launch Services to look up the default application for that type, and then ask NSWorkspace to open the file in that specific application. If you do it this way you'll get the same behavior as the Finder, and you won't have to fork()/exec() or use system() just to open a file. A: In your second edit it makes it sound like you just want to get the path to TextEdit, this can be done easily by using NSWorkspace method absolutePathForAppBundleWithIdentifier: NSString *path = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:@"com.apple.TextEdit"]; A: I believe hardcoding "Applications" will not work if the user's language setting is not English. For example in Norsk the "Applications" folder is named "Programmer". The Apple document on internationalization is here. Starting on page 45 is a section on handling localized path names. A: I believe that Mac OS X provides a default application mechanism, so that .txt will open in TextEdit.app or Emacs or GVim or whatever the user has specified. I couldn't find anything online however. A: You could run following command from your application: open <full path to text file> This will open the text file in the default text editor. You can open any file type using open command.
{ "language": "en", "url": "https://stackoverflow.com/questions/149827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do you write Valid XHTML 1.0 Strict code when you are using javascript to fill an element that requires a child? I'm running my site through the W3C's validator trying to get it to validate as XHTML 1.0 Strict and I've gotten down to a particularly sticky (at least in my experience) validation error. I'm including certain badges from various services in the site that provide their own API and code for inclusion on an external site. These badges use javascript (for the most part) to fill an element that you insert in the markup which requires a child. This means that in the end, perfectly valid markup is generated, but to the validator, all it sees is an incomplete parent-child tag which it then throws an error on. As a caveat, I understand that I could complain to the services that their badges don't validate. Sans this, I assume that someone has validated their code while including badges like this, and that's what I'm interested in. Answers such as, 'Complain to Flickr about their badge' aren't going to help me much. An additional caveat: I would prefer that as much as possible the markup remains semantic. I.E. Adding an empty li tag or tr-td pair to make it validate would be an undesirable solution, even though it may be necessary. If that's the only way it can be made to validate, oh well, but please lean answers towards semantic markup. As an example: <div id="twitter_div"> <h2><a href="http://twitter.com/stopsineman">@Twitter</a></h2> <ul id="twitter_update_list"> <script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script> <script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=twitterCallback2&amp;count=1"></script> </ul> </div> Notice the ul tags wrapping the javascript. This eventually gets filled in with lis via the script, but to the validator it only sees the unpopulated ul. Thanks in advance! A: The following fragment is valid XHTML and does the job: <div id="twitter_div"> <h2 class="twitter-title"><a href="http://twitter.com/stopsineman" title="Tim's Twitter Page.">Twitter Updates</a></h2> <div id="myDiv" /> </div> <script type="text/javascript"> var placeHolderNode = document.getElementById("myDiv"); var parentNode = placeHolderNode.parentNode; var insertedNode = document.createElement("ul"); insertedNode .setAttribute("id", "twitter_update_list"); parentNode.insertBefore( insertedNode, placeHolderNode); parentNode.remove(placeHolderNode); </script> <script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script> <script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=twitterCallback2&amp;count=5"></script> A: Perhaps you could use javascript to write the initial badge HTML? You'd probably only want the badge code to be inserted in your document if javascript were available to populate it, right? You'd just need to make sure your document writing happens before the javascript for your various badges. Could you give a specific example of the HTML / link to a page with the invalid code? A: The solutions might be different for each badge. In Twitter's case, you can just write your own callback function. Here's an example based on their badge code: <div id="twitter_div"> <h2><a href="http://twitter.com/stopsineman">@Twitter</a></h2> <div id="twitter_update_list"></div> </div> <script type="text/javascript"> function updateTwitterCallback(obj) { var twitters = obj; var statusHTML = ""; var username = ""; for (var i = 0; i < twitters.length; i++) { username = twitters[i].user.screen_name; statusHTML += ('<li><span>' + twitters[i].text + '</span> <a style="font-size:85%" href="http://twitter.com/' + username + '/statuses/' + twitters[i].id + '">' + relative_time(twitters[i].created_at) + '</a></li>'); } document.getElementById('twitter_update_list').innerHTML = '<ul>' + statusHTML + '</ul>'; } </script> <script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script> <script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=updateTwitterCallback&amp;count=1"></script> A: I put a <li> with "display:none" in the <ul> Tag: <ul id="twitter_update_list"><li style="display:none;">A</li></ul> <script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script> <script type="text/javascript" src="http://twitter.com/statuses/user_timeline/01241.json?callback=twitterCallback2&amp;count=1"></script> This does not disturb the script and in this case it works, and I think its not a "undesirable solution" :) A: At some point the page becomes valid, right? That's the only time it can really be validated. I'm not sure a non-trivial page will remain valid at every point during its construction if it's constructed with a lot of DOM scripting. A: This might not be the most popular opinion on this topic, but... Don't worry about 100% validation. It's just not that big of a deal. The point of validation is to make your markup as standard as possible. Why? Because browsers that are given markup that doesn't conform to the spec (eg, markup that does not validate) do their own error checking to correct it and display the page the way you intended it to look to the user. The quality of the browsers error checking varies, yadda-yadda-yadda, it's better to have valid markup... But it's not even your code that's causing the validation to fail! The people who wrote those badges probably tested them in multiple browsers (and you should do the same, of course), if they work as expected then just leave it at that. In short, there's no prize for validating :)
{ "language": "en", "url": "https://stackoverflow.com/questions/149844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Classic ASP SQL Injection Protection What is a strong way to protect against sql injection for a classic asp app? FYI I am using it with an access DB. (I didnt write the app) A: Using parametrized querys, you need to create a command object, assign it parameters with a name and a value, if you do so you wouldn't need to worry about anything else (refering to sql injection of course ;)) http://prepared-statement.blogspot.com/2006/02/asp-prepared-statements.html And don't trust stored procedures, they can became a attack vector too if you don't use prepared statements. A: "A strong way to protect against sql injection for a classic asp app" is to ruthlessly validate all input. Period. Stored procedures alone and/or a different database system do not necessarily equal good security. MS recently put out a SQL Injection Inspection tool that looks for unvalidated input that is used in a query. THAT is what you should be looking for. Here's the link: The Microsoft Source Code Analyzer for SQL Injection tool is available to find SQL injection vulnerabilities in ASP code A: Stored Procedures and/or prepared statements: https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks Can I protect against SQL Injection by escaping single-quote and surrounding user input with single-quotes? Catching SQL Injection and other Malicious Web Requests With Access DB, you can still do it, but if you're already worried about SQL Injection, I think you need to get off Access anyway. Here's a link to the technique in Access: http://www.asp101.com/samples/storedqueries.asp Note that what typically protects from injection is not the stored procedure itself, but that fact that it is parameterized and not dynamic. Remember that even SPs which build dynamic code can be vulnerable to injection if they use parameters in certain ways to build the dynamic code. Overall, I prefer SPs because they form an interface layer which the applications get to the database, so the apps aren't even allowed to execute arbitrary code in the first place. In addition, the execution point of the stored procedure can be vulnerable if you don't use command and parameters, e.g. this is still vulnerable because it's dynamically built and can be an injection target: Conn.Execute("EXEC usp_ImOnlySafeIfYouCallMeRight '" + param1 + "', '" + param2 + "'") ; Remember that your database needs to defend its own perimeter, and if various logins have rights to INSERT/UPDATE/DELETE in tables, any code in those applications (or compromised applications) can be a potential problem. If the logins only have rights to execute stored procedures, this forms a funnel through which you can much more easily ensure correct behavior. (Similar to OO concepts where objects are responsible for their interfaces and don't expose all their inner workings.) A: Here are a couple of sqlinject scripts I made a long time ago a simple version and a extended version: function SQLInject(strWords) dim badChars, newChars, i badChars = array("select", "drop", ";", "--", "insert", "delete", "xp_") newChars = strWords for i = 0 to uBound(badChars) newChars = replace(newChars, badChars(i), "") next newChars = newChars newChars= replace(newChars, "'", "''") newChars= replace(newChars, " ", "") newChars= replace(newChars, "'", "|") newChars= replace(newChars, "|", "''") newChars= replace(newChars, "\""", "|") newChars= replace(newChars, "|", "''") SQLInject=newChars end function function SQLInject2(strWords) dim badChars, newChars, tmpChars, regEx, i badChars = array( _ "select(.*)(from|with|by){1}", "insert(.*)(into|values){1}", "update(.*)set", "delete(.*)(from|with){1}", _ "drop(.*)(from|aggre|role|assem|key|cert|cont|credential|data|endpoint|event|f ulltext|function|index|login|type|schema|procedure|que|remote|role|route|sign| stat|syno|table|trigger|user|view|xml){1}", _ "alter(.*)(application|assem|key|author|cert|credential|data|endpoint|fulltext |function|index|login|type|schema|procedure|que|remote|role|route|serv|table|u ser|view|xml){1}", _ "xp_", "sp_", "restore\s", "grant\s", "revoke\s", _ "dbcc", "dump", "use\s", "set\s", "truncate\s", "backup\s", _ "load\s", "save\s", "shutdown", "cast(.*)\(", "convert(.*)\(", "execute\s", _ "updatetext", "writetext", "reconfigure", _ "/\*", "\*/", ";", "\-\-", "\[", "\]", "char(.*)\(", "nchar(.*)\(") newChars = strWords for i = 0 to uBound(badChars) Set regEx = New RegExp regEx.Pattern = badChars(i) regEx.IgnoreCase = True regEx.Global = True newChars = regEx.Replace(newChars, "") Set regEx = nothing next newChars = replace(newChars, "'", "''") SqlInject2 = newChars end function A: if stored procedures are not an option - and even if they are - validate all inputs thoroughly A: Hey, any database as good as developer who uses it. Nothing more but nothing less. If you are good developer you can build e-commerce site using text files as a database. Yes it will not be as good as Oracle driven website but it will do just fine for small business like home based, custom jewelry manufacturing. And if you are good developer you will not use inline SQL statements on your ASP pages. Even in Access you have option to build and use queries.. Store procs with data verification, along with html encode -- is the best way to prevent any SQL Injection attacks. A: The Microsoft Source Code Analyzer for SQL Injection tool is available to find SQL injection vulnerabilities in ASP code A: Switching to SQL Express at the very least is a great option. It will make things much more secure. Even though using parameters and Stored Procedures can help greatly. I also recommend that you validate the inputs carefully to be sure they match what you're expecting. For values like numbers it is fairly easy to extract the number to verify that it is indeed just a number. Escape all special characters for SQL. Doing this will prevent the attempted attack from working.
{ "language": "en", "url": "https://stackoverflow.com/questions/149848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: .NET Log Soap Request on Client I'm consuming a third party .NET WebService in my client application. For debugging purposes I want to capture the SOAP requests that are being sent from my server. How would I go about doing this? This is being done on .NET 2.0 without the use of WCF or WSE. A: If it's for debugging purposes I'd just configure the web request to use a proxy and send the entire request though fiddler (http://www.fiddlertool.com) then you can see exactly what's getting transmitted over the wire. A: I wrote a post about this a while ago titled "Logging SOAP Messages in .NET". The easiest way is to use the tools already provided with .NET. 1. Extend the class SoapExtension. 2. override the method ProcessMessage to get a full output of your Soap Request, then output this information to a text file or event log. public class SoapMessageLogger : SoapExtension { //… public override void ProcessMessage(SoapMessage message) { switch(message.Stage) { case SoapMessageStage.BeforeDeserialize: LogResponse(message); break; case SoapMessageStage.AfterSerialize: LogResponse(message); break; // Do nothing on other states case SoapMessageStage.AfterDeserialize: case SoapMessageStage.BeforeSerialize: default: break; } } //… } A: There are many options you can use. There are certainly some commercial tools for this (like SOAPScope), but if you're just looking to capture the raw contents of the requests/responses there are several tools out there besides Fiddler (that Walden mentioned already). Personally, I've been a long time user of Simon Fell's TcpTrace and YATT. If you're interested in actually instrumenting the code so that it can do it on its own (say, by logging everything to a file or something), then you might want to look into implementing a SoapExtension on your server. A: You can use a SoapExtension to log the Soap calls. http://msdn.microsoft.com/en-us/magazine/cc164007.aspx A: I've used the Web Service, SOA and SOAP Testing Tool - soapUI with good success in the past. -Edoode A: Maybe wireshark ? I'm always using it for capturing traffic of my applications.
{ "language": "en", "url": "https://stackoverflow.com/questions/149851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: profile program's speed on Linux I have a couple variants of a program that I want to compare on performance. Both perform essentially the same task. One does it all in C and memory. The other calls an external utility and does file IO. How do I reliably compare them? 1) Getting "time on CPU" using "time" favors the second variant for calling system() and doing IO. Even if I add "system" time to "user" time, it'll still not count for time spent blocked on wait(). 2) I can't just clock them for they run on a server and can be pushed off the CPU any time. Averaging across 1000s of experiments is a soft option, since I have no idea how my server is utilized - it's a VM on a cluster, it's kind of complicated. 3) profilers do not help since they'll give me time spent in the code, which again favors the version that does system() I need to add up all CPU time that these programs consume, including user, kernel, IO, and children's recursively. I expected this to be a common problem, but still don't seem to find a solution. (Solved with times() - see below. Thanks everybody) A: If I've understood, typing "time myapplication" on a bash command line is not what you are looking for. If you want accuracy, you must use a profiler... You have the source, yes? Try something like Oprofile or Valgrind, or take a look at this for a more extended list. If you haven't the source, honestly I don't know... A: /usr/bin/time (not built-in "time" in bash) can give some interesting stats. $ /usr/bin/time -v xeyes Command being timed: "xeyes" User time (seconds): 0.00 System time (seconds): 0.01 Percent of CPU this job got: 0% Elapsed (wall clock) time (h:mm:ss or m:ss): 0:04.57 Average shared text size (kbytes): 0 Average unshared data size (kbytes): 0 Average stack size (kbytes): 0 Average total size (kbytes): 0 Maximum resident set size (kbytes): 0 Average resident set size (kbytes): 0 Major (requiring I/O) page faults: 9 Minor (reclaiming a frame) page faults: 517 Voluntary context switches: 243 Involuntary context switches: 0 Swaps: 0 File system inputs: 1072 File system outputs: 0 Socket messages sent: 0 Socket messages received: 0 Signals delivered: 0 Page size (bytes): 4096 Exit status: 0 A: Run them a thousand times, measure actual time taken, then average the results. That should smooth out any variances due to other applications running on your server. A: I seem to have found it at last. NAME times - get process times SYNOPSIS #include clock_t times(struct tms *buf); DESCRIPTION times() stores the current process times in the struct tms that buf points to. The struct tms is as defined in : struct tms { clock_t tms_utime; /* user time */ clock_t tms_stime; /* system time */ clock_t tms_cutime; /* user time of children */ clock_t tms_cstime; /* system time of children */ }; The children's times are a recursive sum of all waited-for children. I wonder why it hasn't been made a standard CLI utility yet. Or may be I'm just ignorant. A: I'd probably lean towards adding "time -o somefile" to the front of the system command, and then adding it to the time given by time'ing your main program to get a total. Unless I had to do this lots of times, then I'd find a way to take two time outputs and add them up to the screen (using awk or shell or perl or something).
{ "language": "en", "url": "https://stackoverflow.com/questions/149852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to prevent fgets blocks when file stream has no new data I have a popen() function which executes tail -f sometextfile. Aslong as there is data in the filestream obviously I can get the data through fgets(). Now, if no new data comes from tail, fgets() hangs. I tried ferror() and feof() to no avail. How can I make sure fgets() doesn't try to read data when nothing new is in the file stream? One of the suggestion was select(). Since this is for Windows Platform select doesn't seem to work as anonymous pipes do not seem to work for it (see this post). A: In Linux (or any Unix-y OS), you can mark the underlying file descriptor used by popen() to be non-blocking. #include <fcntl.h> FILE *proc = popen("tail -f /tmp/test.txt", "r"); int fd = fileno(proc); int flags; flags = fcntl(fd, F_GETFL, 0); flags |= O_NONBLOCK; fcntl(fd, F_SETFL, flags); If there is no input available, fgets will return NULL with errno set to EWOULDBLOCK. A: fgets() is a blocking read, it is supposed to wait until data is available if there is no data. You'll want to perform asynchronous I/O using select(), poll(), or epoll(). And then perform a read from the file descriptor when there is data available. These functions use the file descriptor of the FILE* handle, retrieved by: int fd = fileno(f); A: i solved my problems by using threads , specifically _beginthread , _beginthreadex. A: I you would use POSIX functions for IO instead of those of C library, you could use select or poll. A: You can instead try reading sometextfile using low-level IO functions (open(), read(), etc.), like tail itself does. When there's nothing more to read, read() returns zero, but will still try to read more the next time, unlike FILE* functions.
{ "language": "en", "url": "https://stackoverflow.com/questions/149860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Does ANSI C support signed / unsigned bit fields? Does it make sense to qualify bit fields as signed / unsigned? A: Yes. An example from here: struct { /* field 4 bits wide */ unsigned field1 :4; /* * unnamed 3 bit field * unnamed fields allow for padding */ unsigned :3; /* * one-bit field * can only be 0 or -1 in two's complement! */ signed field2 :1; /* align next field on a storage unit */ unsigned :0; unsigned field3 :6; }full_of_fields; Only you know if it makes sense in your projects; typically, it does for fields with more than one bit, if the field can meaningfully be negative. A: It's very important to qualify your variables as signed or unsigned. The compiler needs to know how to treat your variables during comparisons and casting. Examine the output of this code: #include <stdio.h> typedef struct { signed s : 1; unsigned u : 1; } BitStruct; int main(void) { BitStruct x; x.s = 1; x.u = 1; printf("s: %d \t u: %d\r\n", x.s, x.u); printf("s>0: %d \t u>0: %d\r\n", x.s > 0, x.u > 0); return 0; } Output: s: -1 u: 1 s>0: 0 u>0: 1 The compiler stores the variable using a single bit, 1 or 0. For signed variables, the most significant bit determines the sign (high is treated negative). Thus, the signed variable, while it gets stored as 1 in binary, it gets interpreted as negative one. Expanding on this topic, an unsigned two bit number has a range of 0 to 3, while a signed two bit number has a range of -2 to 1. A: I don't think Andrew is talking about single-bit bit fields. For example, 4-bit fields: 3 bits of numerical information, one bit for sign. This can entirely make sense, though I admit to not being able to come up with such a scenario off the top of my head. Update: I'm not saying I can't think of a use for multi-bit bit fields (having used them all the time back in 2400bps modem days to compress data as much as possible for transmission), but I can't think of a use for signed bit fields, especially not a quaint, obvious one that would be an "aha" moment for readers. A: Yes, it can. C bit-fields are essentially just limited-range integers. Frequently hardware interfaces pack bits together in such away that some control can go from, say, -8 to 7, in which case you do want a signed bit-field, or from 0 to 15, in which case you want an unsigned bit-field. A: Most certainly ANSI-C provides for signed and unsigned bit fields. It is required. This is also part of writing debugger overlays for IEEE-754 floating point types [[1][5][10]], [[1][8][23]], and [[1][10][53]]. This is useful in machine type or network translations of such data, or checking conversions double (64 bits for math) to half precision (16 bits for compression) before sending over a link, like video card textures. // Fields need to be reordered based on machine/compiler endian orientation typedef union _DebugFloat { float f; unsigned long u; struct _Fields { signed s : 1; unsigned e : 8; unsigned m : 23; } fields; } DebugFloat; Eric A: The relevant portion of the standard (ISO/IEC 9899:1999) is 6.7.2.1 #4: A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed int, unsigned int, or some other implementation-defined type. A: One place where signed bitfields are useful is in emulation, where the emulated machine has fewer bits than your default word. I'm currently looking at emulating a 48-bit machine and am trying to work out if it's reasonable to use 48 bits out of a 64-bit "long long" via bitfields... the generated code would be the same as if I did all the masking, sign-extending etc explicitly but it would read a lot better... A: According to this reference, it's possible: http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=/com.ibm.vacpp6m.doc/language/ref/clrc03defbitf.htm A: Bit masking signed types varies from platform hardware to platform hardware due to how it may deal with an overflow from a shift etc. Any half good QA tool will warn knowingly of such usage. A: if a 'bit' is signed, then you have a range of -1, 0, 1, which then becomes a ternary digit. I don't think the standard abbreviation for that would be suitable here, but makes for interesting conversations :)
{ "language": "en", "url": "https://stackoverflow.com/questions/149869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: How to design a fact table for delivery data I'm building a data warehouse that includes delivery information for restaurants. The data is stored in SQL Server 2005 and is then put into a SQL Server Analysis Services 2005 cube. The Deliveries information consists of the following tables: FactDeliveres * *BranchKey *DeliveryDateKey *ProductKey *InvoiceNumber (DD: degenerate dimension) *Quantity *UnitCosT *Linecost Note: * *The granularity of FactDeliveres is each line on the invoice *The Product dimension include supplier information And the problem: there is no primary key for the fact table. The primary key should be something that uniquely identifies each delivery plus the ProductKey. But I have no way to uniquely identify a delivery. In the source OLTP database there is a DeliveryID that is unique for every delivery, but that is an internal ID that meaningless to users. The InvoiceNumber is the suppliers' invoices number -- this is typed in manually and so we get duplicates. In the cube, I created a dimension based only on the InvoiceNumber field in FactDeliveres. That does mean that when you group by InvoiceNumber, you might get 2 deliveries combined only because they (mistakenly) have the same InvoiceNumber. I feel that I need to include the DeliveryID (to be called DeliveryKey), but I'm not sure how. So, do I: * *Use that as the underlying key for the InvoiceNumber dimension? *Create a DimDelivery that grows every time there is a new delivery? That could mean that some attributes come out of FactDeliveries and go into DimDelivery, like DeliveryDate,Supplier, InvoiceNumber. After all that, I could just ask you: how do I create a Deliveries cube when I have the following information in my source database DeliveryHeaders * *DeliveryID (PK) *DeliveryDate *SupplierID (FK) *InvoiceNumber (typed in manually) DeliveryDetails * *DeliveryID (PK) *ProductID (PK) *Quantity *UnitCosT A: I would have Quantity, UnitCode, InvoiceNumber, DeliveryID all in the fact table. Both InvoiceNumber and DeliveryID are degenerate dimensions, because they will change with every fact (or very few facts). It is possible that you could put them in their own dimension if you have a large number of items on each order. The model below may not be 100% correct if you have multiple deliveries on an invoice, but it will be close. Check out Kimball, he might have an example of a star schema for this business scenario. Fact table: OrderDateID (not in your model, but probably should be, date dimension in a role) DeliveryDateID (date dimension in a role) SupplierID (supplier dimension surrogate key) InvoiceID (invoice dimension surrogate key) ProductID (product dimension surrogate key) Quantity (fact) UnitCost (fact) InvoiceNumber (optional) DeliveryID (optional) with the usual date dimension table and the following dimensions: Supplier Dim: SupplierID (surrogate) SupplierCode and data Invoice Dim: InvoiceID (surrogate) InvoiceNumber (optional) DeliveryID (optional) Product Dim: ProductID (surrogate) ProductCode and Data Always remember, your (star schema) data warehouse is not going to be structured at all like your OLTP data - it's all about the facts and what dimensions describe them. A: Fact table PK's are almost always surrogate keys. Each fact is part of several dimensions, so the fact has FK's to the dimensions, but no real keys of it's own. A Delivery Fact (a Line Item) belongs to a Branch, it has a Product, it is part of a larger Delivery, it occurs on a particular Date. Sounds like 4 independent dimensions. The Delivery dimension has it's own PK and it has a dimension attribute of invoice number. Plus, perhaps, other attributes of the delivery as a whole. Each Delivery Line Item Fact is associated with one Delivery and the invoice number for that Delivery.
{ "language": "en", "url": "https://stackoverflow.com/questions/149871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issues working with JSF redirect and WebTrends On our new platform we are utilizing JSF. Our WebTrends tags are not reflecting the proper page title on this platform. It currently is displaying the name of the users previous page instead of the current page. We are making use of the JSF Navigation rule in which we have some "< redirect />" tags. Has anyone experienced this and is there a solution. I have made the suggestion that we move a way from this model, still use JSF but not the navigation rules. Thanks A: We solved this problem by using the webtrends javascript API to inject the correct page title into the page (instead of relying on the javascript to read the correct URL from the page). Since JSF mucks with your URLs, there really isn't much else you can do. The redirect tags will work, but you have to watch your managed bean's logic, since it breaks request scope.
{ "language": "en", "url": "https://stackoverflow.com/questions/149874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to transfer sql encrypted data between SQL Server 2005 databases? I have an existing SQL Server 2005 database that contains data encrypted using a Symmetric key. The symmetric key is opened using a password. I am working on an upgrade to the front end applications that use this database, which include adding dozens of new tables, stored procedures, UDFs, etc. and dozens of modifications to existing tables and database objects. To that end I am making a copy of the existing development database, so that the current system can be independently supported, maintained, and updated while new development takes place. What is a good way to go about copying the database? Normally, I'd take a backup of the existing database, and then restore it to the new database. However, will this be feasible given the encrypted data? Will I still be able to encrypt and more importantly decrypt data in the new database using the existing symmetric key and password? Might I instead want to use DTS to transfer the existing schema only. Create a new symmetric key/password in the new database. Then write ad hoc queries to transfer the data, decrypting using existing key/password, and encrypting using new key/password in new database. I guess at the heart of this is, are symmetric keys good for encrypting/decrypting data in a single database or in many databases on the same server? A: The Symmetric keys you are referring to are Database Master Keys (DMKs). They are held at the Database level, so a backup/restore to another SQL server should work OK (with the caveat of differing service accounts, which this thread alludes to) Before you do anything make sure you have a backup of your keys (presumably you've already done this): USE myDB GO BACKUP MASTER KEY TO FILE = 'path_to_file' ENCRYPTION BY PASSWORD = 'password' GO From this article: When you create a Database Master Key, a copy is encrypted with the supplied password and stored in the current database. A copy is also encrypted with the Service Master Key and stored in the master database. The copy of the DMK allows the server to automatically decrypt the DMK, a feature known as "automatic key management." Without automatic key management, you must use the OPEN MASTER KEY statement and supply a password every time you wish to encrypt and/or decrypt data using certificates and keys that rely on the DMK for security. With automatic key management, the OPEN MASTER KEY statement and password are not required.
{ "language": "en", "url": "https://stackoverflow.com/questions/149876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How Do I Profile the ADO.NET Connection Pool? I'm profiling a ASP.NET web application. I believe it is very database connection intensive (excessive use of the ADO.NET connection pool). How to I tell w/out debugging how many times it is going to the pool and on average how many connections are available in the pool? Are there counters that will give me this info in PerfMon or some other tool? A: Look at ADO.NET performance counters: http://msdn.microsoft.com/en-us/library/ms254503.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/149877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: preconditions and exceptions Suppose you have a method with some pre and post-conditions. Is it ok to create an exception class for each pre-condition that is not accomplished? For example: Not accomplishing pre1 means throwing a notPre1Exception instance. A: Yes and no. Yes - Violating a precondition is certainly an appropriate time to throw an exception. Throwing a more specific exception will make catching that specific exception simpler. No - Declaring a new exception class for every precondition in your program/api seems way overkill. This could result in hundreds or thousands of exceptions eventually. This seems a waste both mentally and computationally. I would recommend throwing exceptions for precondition violations. I would not, however, recommend defining a new exception for each precondition. Instead, I would recommend creating broader classes of exceptions that cover a specific type of precondition violation, rather than a specific precondition violation. (I would also recommend using existing exceptions where they fit well.) A: A failed precondition should throw an AssertException, or something similar. Before invoking a method, it's precondition must hold. If the caller doesn't do this check, it's a bug in the program, or an incorrect use of the method (API). A: Why wouldn't you want to define PreconditionFailedException(string precondition)? Throwing a different exception type for each failed precondition is overkill. A: Only if not accomplishing the pre-conditions would be a rare exceptional occurrence. A: Sounds like a useful use of exceptions to me. It certainly allows more fine-grained logging and debugging than just a general 'precondition failed' although you could also have a single 'preconditions failed' exception and put what preconditions have failed into the exception message. A: I think it's ok to create a different exception for all your exceptions as long as you plan on using and handling them. I have found that the better the error/exception handling the easier it is to debug software in the later stages. For example: If you have a generic excpeiton to handle all bad input then you must look at everything that was passed into the method if there is an error. If you have an excpetion of all the types of bad conditions you will know exaclty where to look. A: It looks possible to me, but if you want to continue this way of dealing with preconditions, you'll end up with N exception classes per class method. Looks like an explosive growth of 'non functional' classes. I always liked code where the 'core' functionality didn't handle violation of preconditions (apart from asserting them - a great help!). This code can then be wrapped in a 'precondition-checker', which does throw exceptions or notifies non-satisfaction otherwise. A: As a very very general way to determine if you should ever create a class or not (and an exception is a class), you should determine if there is some code that makes this class unique from all other classes (in this case exceptions). If not, I'd just set the string in the exception and call it a day. If you are executing code in your exception (perhaps a generic recovery mechanism that can handle multiple situations by calling exception.resolve() or something), then it might be useful. I realize that exceptions don't always follow this rule, but I think that's more or less because exceptions provided by the language can't have any business logic in them (because they don't know the business--libraries always tend to be full of exceptions to the OO rules) A: I think Ben is on target here. What's the point in throwing different exceptions if you're not going to catch them? If you really want to throw a different one I would at least have a common "PreconditionFailedException" base class that they all derive from, and try to organize them into some sort of heirachy so you can catch groups of them. Personlly, I'd not have different ones and just have a common exception you throw with the details of the failure in each one. A: No, you should not create a specific exception for each precondition because it will go against the principles of the Design-by-Contract. The corollaries of implementing pre-conditions is that they should be part of the documentation and that you should provide the necessary methods for the caller to check that all the preconditions are valid. (i.e. if a method execution is relying on the status of an object, the method to check the status should be available to the caller). So, the caller should be able to check if all prerequisites are met before calling your method. Implementing specific exceptions for each violated pre-condition would/could encourage the caller to use the try/catch pattern around the method call, what is in contradiction with the philosophy of the Design-by-Contract. A: I would say it's okay as long as you make them unchecked exceptions (subclass of RuntimeException in Java). However, in Java it is better to just use assertions. A: If you do this, make sure they all inherit from another common custom exception.
{ "language": "en", "url": "https://stackoverflow.com/questions/149898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I use a type with generic arguments as a constraint? I would like to specify a constraint which is another type with a generic argument. class KeyFrame<T> { public float Time; public T Value; } // I want any kind of Keyframe to be accepted class Timeline<T> where T : Keyframe<*> { } But this cannot be done in c# as of yet, (and I really doubt it will ever be). Is there any elegant solution to this rather than having to specify the type of the keyframe argument?: class Timeline<TKeyframe, TKeyframeValue> where TKeyframe : Keyframe<TKeyframeValue>, { } A: As TimeLine is most likely an aggregation of KeyFrames, wouldn't something like: class TimeLine<T> { private IList<KeyFrame<T>> keyFrameList; ... } fulfill your requirements nicely? A: Read about this from Eric Lippert's blog Basically, you have to find a way to refer to the type you want without specifying the secondary type parameter. In his post, he shows this example as a possible solution: public abstract class FooBase { private FooBase() {} // Not inheritable by anyone else public class Foo<U> : FooBase {...generic stuff ...} ... nongeneric stuff ... } public class Bar<T> where T: FooBase { ... } ... new Bar<FooBase.Foo<string>>() Hope that helps, Troy A: If the type T that Timeline<T> represents is the same as the type KeyFrame<T> represents you can just go with: class Timeline<T> { List<KeyFrame<T>> _frames = new List<KeyFrame<T>>(); //Or whatever... ... } If type T represents something different between the classes that implies that Timeline<T> can contain multiple types of KeyFrame's in which case you should create a more abstract implementation of KeyFrame and use that in Timeline<T>. A: Maybe nesting Timeline inside KeyFrame would make sense in your design: class KeyFrame<T> { public float Time; public T Value; class Timeline<U> where U : Keyframe<T> { } }
{ "language": "en", "url": "https://stackoverflow.com/questions/149909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Compatibility Mode for Web Services I have a web service that loads an unmanaged .dll made from VC++ 6. In Vista and Windows Server 2008, I can get applications using this to work by putting them in Win98 Compatibility mode. Is there a similar way I can do this with my web service, so it will run? A: It depends on your unmanaged DLL. I have successfuly deployed unmanaged DLLs that were exposing COM interfaces. After registering those COM components on the target machine (read web server) my managed web application (ASP.NET) were able to call those COM components. A: I believe all .dll's prior to VS.NET were "unmanaged". Do you have access to the source code for this .dll you are referring too?
{ "language": "en", "url": "https://stackoverflow.com/questions/149923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Naming conventions for threads? It's helpful to name threads so one can sort out which threads are doing what for diagnostic and debugging purposes. Is there a particular naming convention for threads in a heavily multi-threaded application that works better than another? Any guidelines? What kind of information should go into the name for a thread? What have you learned about naming your threads that could be helpful to others? A: There's to my knowledge no standard. Over the time I've found these guidelines to be helpful: * *Use short names because they don't make the lines in a log file too long. *Create names where the important part is at the beginning. Log viewers in a graphical user interface tend to have tables with columns, and the thread column is usually small or will be made small by you to read everything else. *Do not use the word "thread" in the thread name because it is obvious. *make the thread names easily grep-able. Avoid similar sounding thread names *if you have several threads of the same nature, enumerate them with IDs that are unique to one execution of the application or one log file, whichever fits your logging habits. *avoid generalizations like "WorkerThread" (how do you name the next 5 worker threads?), "GUIThread" (which GUI? is it for one window? for everything?) or "Calculation" (what does it calculate?). *if you have a test group that uses thread names to grep your application's log files, do not rename your threads after some time. Your testers will hate you for doing so. Thread names in well-tested applications should be there to stay. *when you have threads that service a network connection, try to include the target network address in the thread name (e.g. channel_123.212.123.3). Don't forget about enumeration though if there are multiple connections to the same host. If you have many threads and forgot to name one, your log mechanism should output a unique thread ID instead (API-specific, e.g. by calling pthread_self() ) A: Naming threads is useful and you should follow a naming convention that would for anything else, be that variables, methods or classes. Name them according to what they do and be succinct. If you ever run into a problem that requires a thread dump it will be nice to look at the name and know where to look in your code for the problem rather than examining stack traces and guessing. The only different is that if there are multiple threads of the same type you really should add an index of some sort as thread names should be unique to satisfy certain APIs. It can also help with logging if you show the thread name to know how your application behaves with partial execution happening on different threads. A: while Thorsten's answer is the most comprehensive, you might want to look at how Tomcat names its Threads. I've found that useful. We were running multiple threads with a quartz scheduler and many of the naming rules that Thorsten suggests were useful. Are you going to be using a Thread pool ? If yes, then that will reduce the chances that you can add more useful meta info. If not, the sky is the limit to how much useful info you can have. A: What about: [namespace].[Class][.Class...].[Method][current thread]? So you have the names: Biz.Caching.ExpireDeadItems1 Biz.Caching.ExpireDeadItems2 Biz.Caching.ExpireDeadItems3 etc., for each thread. A: I've seen several naming conventions for threads in .NET. Some prefer using 't' in the beginning of the name (ex. tMain Thread) but I don't think it has any real value. Instead why not just use plain descriptive names (line variables) such as HouseKeeping, Scheduler and so on. A: I tend to approach naming threads the same as naming methods or variables. Pick something that concisely describes the process that the thread is responsible for. I don't think there's a lot of extra information that you can or should put into a thread-name. Expressive but terse is the primary goal. The only convention might be to add an incremented suffix to threads that are part of a pool.
{ "language": "en", "url": "https://stackoverflow.com/questions/149932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "47" }
Q: MS Access MDE on Terminal Server I deployed an MDE file on the terminal server and when I double clicked the MDE i have the following error. " There isn't enough memory to perform this operation. Close unneeded programs and try again. I never had any issues on local machine. I tried de-compiling and compacting and again compiling. I can open other forms but only SwitchBoard is the issue. Any thoughts? Hardly there are 9 links from the MainMenu. A: If you're in the console session on the terminal server (at a KVM?), or if you enable "Install Mode" (after you remote desktop, running "CHANGE USER /INSTALL"), does the problem still occur? I don't know of any specific issues with MDE applications over terminal services, but trying those two things will let you know if it's related to the TS configuration, or if it's a problem running that MDE on the server itself. Can you update the question with the version of both Windows Server and Access you're using? This Microsoft KB article suggests a problem when you have Windows Server 2003 and Access 2000, so some more detail would be helpful here.
{ "language": "en", "url": "https://stackoverflow.com/questions/149936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creating non-reverse-engineerable Java programs Is there a way to deploy a Java program in a format that is not reverse-engineerable? I know how to convert my application into an executable JAR file, but I want to make sure that the code cannot be reverse engineered, or at least, not easily. Obfuscation of the source code doesn't count... it makes it harder to understand the code, but does not hide it. A related question is How to lock compiled Java classes to prevent decompilation? Once I've completed the program, I would still have access to the original source, so maintaining the application would not be the problem. If the application is distributed, I would not want any of the users to be able to decompile it. Obfuscation does not achieve this as the users would still be able to decompile it, and while they would have difficulty following the action flows, they would be able to see the code, and potentially take information out of it. What I'm concerned about is if there is any information in the code relating to remote access. There is a host to which the application connects using a user-id and password provided by the user. Is there a way to hide the host's address from the user, if that address is located inside the source code? A: If you know which platforms you are targeting, get something that compiles your Java into native code, such as Excelsior JET or GCJ. Short of that, you're never going to be able to hide the source code, since the user always has your bytecode and can Jad it. A: You're writing in a language that has introspection as part of the core language. It generates .class files whose specifications are widely known (thus enabling other vendors to produce clean-room implementations of Java compilers and interpreters). This means there are publicly-available decompilers. All it takes is a few Google searches, and you have some Java code that does the same thing as yours. Just without the comments, and some of the variable names (but the function names stay the same). Really, obfuscation is about all you can get (though the decompiled code will already be slightly obfuscated) without going to C or some other fully-compiled language, anyway. A: Don't use an interpreted language? What are you trying to protect anyway? If it's valuable enough, anything can be reverse engineered. The chances of someone caring enough to reverse engineer most projects is minimal. Obfuscation provides at least a minimal hurdle. Ensure that your intellectual property (IP) is protected via other mechanisms. Particularly for security code, it's important that people be able to inspect implementations, so that the security is in the algorithm, not in the source. A: I'm tempted to ask why you'd want to do this, but I'll leave that alone... The problem I see is that the JVM, like the CLR, needs to be able to intrepert you code in order to JIT compile and run it. You can make it more "complex" but given that the spec for bytecode is rather well documented, and exists at a much higher level than something like the x86 assembler spec, it's unlikely you can "hide" the process-flow, since it's got to be there for the program to work in the first place. A: Make it into a web service. Then you are the only one that can see the source code. A: The short answer is "No, it does not exist". Reverse engineering is a process that does not imply to look at the code at all. It's basically trying to understand the underlying mechanisms and then mimic them. For example, that's how JScript appears from MS labs, by copying Netscape's JavaScript behavior, without having access to the code. The copy was so perfect that even the bugs were copied. A: You could obfuscate your JAR file with YGuard. It doesn't obfuscate your source code, but the compiled classes, so there is no problem about maintaining the code later. If you want to hide some string, you could encrypt it, making it harder to get it through looking at the source code (it is even better if you obfuscate the JAR file). A: It can't be done. Anything that can be compiled can be de-compiled. The very best you can do is obfuscate the hell out of it. That being said, there is some interesting stuff happening in Quantum Cryptography. Essentially, any attempt to read the message changes it. I don't know if this could be applied to source code or not. A: Even if you compile the code into native machine language, there are all sorts of programs that let you essentially decompile it into assembly language and follow the process flow (OlyDbg, IDA Pro). A: It can not be done. This is not a Java problem. Any language that can be compiled can be decompiled for Java, it's just easier. You are trying to show somebody a picture without actually showing them. It is not possible. You also can not hide your host even if you hide at the application level. Someone can still grap it via Wireshark or any other network sniffer. A: As someone said above, reverse engineering could always decompile your executable. The only way to protect your source code(or algorithm) is not to distribute your executable. separate your application into a server code and a client app, hide the important part of your algorithm in your server code and run it in a cloud server, just distribute the client code which works only as a data getter and senter. By this even your client code is decompiled. You are not losing anything. But for sure this will decrease the performance and user convenience. I think this may not be the answer you are looking for, but just to raise different idea of protecting source code. A: With anything interpreted at some point it has to be processed "in the clear". The string would show up clear as day once the code is run through JAD. You could deploy an encryption key with your app or do a basic ceasar cipher to encrypt the host connect info and decrypt at runtime... But at some point during processing the host connection information must be put in the clear in order for your app to connect to the host... So you could statically hide it, but you can't hide it during runtime if they running a debugger A: This is impossible. The CPU will have to execute your program, i.e. your program must be in a format that a CPU can understand. CPUs are much dumber than humans. Ergo, if a CPU can understand your program, a human can. A: Having concerns about concealing the code, I'd run ProGuard anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/149937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: jsp create scripting variable like jsp:usebean does I would like to do something like <test:di id="someService"/`> <% someService.methodCall(); %> where <test:di gets and instantiates a service bean and creates a scripting variable for use. similar to how jsp:usebean works for example <jsp:useBean id="someDate" class="java.util.Date"/> <% someDate.getYear(); %> how do i make my own objects available as a scritping variable? A: The way this is done in a Tag Library is by using a Tag Extra Info (TEI) class. You can find an example here. A: I think you're trying to write your own tag library. Check out the tutorial at: http://www.ironflare.com/docs/tutorials/taglibs/ Edit: As Garth pointed out, you want to use the TagExtraInfo class after you've defined your tag lib. http://www.stardeveloper.com/articles/display.html?article=2001081601&page=2
{ "language": "en", "url": "https://stackoverflow.com/questions/149939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JMP0811I-U Fujitsu runtime error after compiling Fujitsu COBOL with DB2 SQL: cause/remedy? I'm able to (on Windows XP) precompile, compile and link a sample (Fujitsu NetCobol) COBOL test program which contains embedded SQL. This test program is to read and display the number of rows in a DB2 (UDB 9.5 on Linux) database table. At runtime I get following error message: JMP0811I-U [PID:... TID:...] FAILURE IN LINKAGE RULES OR PARAMETER OF THE 'sqlgstrt' PROGRAM. PGM=DB2TST1 The precompile source code this error refers to looks as follows: * ... in WORKING-STORAGE section: 01 SQLA-PROGRAM-ID. 05 SQL-PART1 pic 9(4) COMP-5 value 172. 05 SQL-PART2 pic X(6) value "AEAMAI". 05 SQL-PART3 pic X(24) value "gBSdTdJY01111 2 ". 05 SQL-PART4 pic 9(4) COMP-5 value 13. 05 SQL-PART5 pic X(13) value "ADMINISTRATOR". 05 SQL-PART6 pic X(115) value LOW-VALUES. 05 SQL-PART7 pic 9(4) COMP-5 value 8. 05 SQL-PART8 pic X(8) value "COBOL/DB". 05 SQL-PART9 pic X(120) value LOW-VALUES. * .. in PROCEDURE DIVISION: *EXEC SQL CONNECT TO :DB-SERVER USER :DB-USER USING :DB-PWD * END-EXEC CALL "sqlgstrt" USING BY CONTENT SQLA-PROGRAM-ID BY VALUE 0 BY REFERENCE SQLCA Does anybody know what this error message means? A: The error description was due to: *) the CHECK(LINKAGE) compiler option (only available in NetCOBOL for Windows, not for Linux) without this option, the error is still there, but even less descriptive The actual error was due to: *) the CALL "sqlgstrt" USING ... generated by the DB2 precompiler implies the wrong (= COBOL) calling convention => manually changing the calls to CALL "sqlgstrt" WITH STDCALL LINKAGE USING... has resolved the runtime error This solution implies changing the precompiler results though, so I'm still in search of a DB2 precompiler option to generate the right CALLs.
{ "language": "en", "url": "https://stackoverflow.com/questions/149945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to determine when copy finishes in VBScript? Does anyone know of a method to determine when a file copy completes in VBScript? I'm using the following to copy: set sa = CreateObject("Shell.Application") set zip = sa.NameSpace(saveFile) set Fol = sa.NameSpace(folderToZip) zip.copyHere (Fol.items) A: Do Until zip.Items.Count = Fol.Items.Count WScript.Sleep 300 Loop When the loop finishes your copy is finished. But if you only want to copy and not zip, FSO or WMI is better. If you are zipping and want them in a file you have to create the zip-file yourself, with the right header first. Else you only get compressed files/folders IIRC. Something like this: Set FSO = CreateObject( "Scripting.FileSystemObject" ) Set File = FSO.OpenTextFile( saveFile, 2, True ) File.Write "PK" & Chr(5) & Chr(6) & String( 18, Chr(0) ) File.Close Set File = Nothing Set FSO = Nothing The 2 in OpenTextFile is ForWriting. A: You may have better luck using the Copy method on a FileSystemObject. I've used it for copying, and it's a blocking call. A: Const FOF_CREATEPROGRESSDLG = &H0& Const ForReading = 1, ForWriting = 2, ForAppending = 8 Set fso = CreateObject("Scripting.FileSystemObject") strSource = " " ' Source folder path of log files strTarget = " .zip" ' backup path where file will be created AddFilesToZip strSource,strTarget Function AddFilesToZip (strSource,strTarget) Set r=fso.GetFolder(strSource) set file = fso.opentextfile(strTarget,ForWriting,true) file.write "PK" & chr(5) & chr(6) & string(18,chr(0)) file.Close Set shl = CreateObject("Shell.Application") i = 0 For each f in r.Files If fso.GetExtensionName(f) = "log" Or fso.GetExtensionName(f) = "Log" Or fso.GetExtensionName(f) = "LOG" Then shl.namespace(strTarget).copyhere(f.Path)', FOF_CREATEPROGRESSDLG Do until shl.namespace(strTarget).items.count = i wscript.sleep 300 Loop End If i = i + 1 Next set shl = Nothing End Function
{ "language": "en", "url": "https://stackoverflow.com/questions/149956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to avoid a postback in JavaScript? I have an ASP.NET page which has a button it it. The button click launches a modal dialog box using JavaScript. Based on the value returned by the modal dialog box, I want to proceed with, or cancel the post back that happens. How do I do this? A: Is this what you are trying to do? <input type="button" id="myButton" value="Click!" /> <script type="text/javascript"> document.getElementById('myButton').onclick = function() { var agree = confirm('Are you sure?'); if (!agree) return false; }; </script> A: Adding "return false;" to the onclick attribute of the button will prevent the automatic postback. A: function HandleClick() { // do some work; if (some condition) return true; //proceed else return false; //cancel; } set the OnClientClick attribute to "return HandleClick()" A: Basically what Wayne said, but you just need to put 'return false;' in the function that presents the modal. If it's the value you want, let the postback happen. If not, have the function return false and it will stop the submit.
{ "language": "en", "url": "https://stackoverflow.com/questions/149962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Problem accessing previousState in OnFlushDirty() event of Castle ActiveRecord I have this problem, I'm using Castle ActiveRecord and when I update I verify changes in the object in the OnFlushDirty event. However, when I access to the previouState["MyProperty"], it turns to be null and I can't get the old value. Do you know why? this is the code; protected override bool OnFlushDirty(object id, System.Collections.IDictionary previousState, System.Collections.IDictionary currentState, NHibernate.Type.IType[] types) { StringBuilder errors = new StringBuilder(); if (this._bankCode <= 0) errors.Append("Bank code is invalid" + Environment.NewLine); if (string.IsNullOrEmpty(this._name) || this._name.Trim().Length == 0) errors.Append("Name is invalid" + Environment.NewLine); //previousState["EnterpriseCode"] is always null if (previousState["EnterpriseCode"] != currentState["EnterpriseCode"]) { if (this._enterpriseCode == 0) errors.Append("Enterprise code is invalid" + Environment.NewLine); else ... A: I finally made it, it happens that in hibernate you must use merge() to make that hibernate "loads" the previuos data of the detached object, in Castle the equivalent is the SaveCopy() method .
{ "language": "en", "url": "https://stackoverflow.com/questions/149964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C# ResetBinding flip the DataGridView *Updated with example* I had a problem that was partially solved. To explain it quickly : I have a grid binded to a complex object that require to be serialized. When the object is build back from the serialization, event like on the grid doesn't refresh the table display. Someone told me to rebuild the event once unserialize, it works! But the event that refresh the grid doesn't seems to fire at all. I had to build an event from my complex object that told me that something change inside. From this event I added this code : this.bindingSource1.ResetBindings(false); The problem is the grid is flipping and the user doesn't have a good feeling (rows are moving up and down and than stop). How can I reset the binding without having this kind of flipping? How can I solve the original problem? (This will solve automaticly everything). Update Here is an example that do exactly the same behavior: Create a class: [Serializable()] class BOClient : INotifyPropertyChanged, IDataErrorInfo { private string name; private int len; public string Name { get { return name; } set { name = value; this.len = name.Length; if (this.PropertyChanged !=null) this.PropertyChanged(this, new PropertyChangedEventArgs("Name")); } } public int Len { get { return this.len; } } public BOClient(string name) { this.Name = name; } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion #region IDataErrorInfo Members public string Error { get { return ""; } } public string this[string columnName] { get { return ""; } } #endregion } Now, create a form with a BindingSource call "bindingSource1" and go use the class as datasource. Create a grid and bind the grid to the bindingsource1. In that form use this code in the load : private void Form1_Load(object sender, EventArgs e) { BindingList<BOClient> listClient = new BindingList<BOClient>(); listClient.Add(new BOClient("P1")); listClient.Add(new BOClient("P2")); listClient.Add(new BOClient("P3")); //using (MemoryStream mem = new MemoryStream()) //{ // BinaryFormatter b1 = new BinaryFormatter(); // try // { // b1.Serialize(mem, listClient); // } // catch (Exception ez) // { // MessageBox.Show(ez.Message); // } // BinaryFormatter b2 = new BinaryFormatter(); // try // { // mem.Position = 0; // listClient = (BindingList<BOClient>)b2.Deserialize(mem); // } // catch (Exception ez) // { // MessageBox.Show(ez.Message); // } //} this.bindingSource1.DataSource = listClient; } I put the serialization process in comment BECAUSE it seems that it do the same weird behavior without it... now start the application. Change a name of a client. Example "p1" for "New name" and click the cell under the changed one. You will see the "len" column NOT changing. BUT if you click the cell that has the len you will see the number changing to the right value. Any one have an idea why? A: I have solve this problem by adding in the BindingList (by inheritance) a method [OnDeserialization] within I added code that add event on the OnListChange. This way when 1 property change, the whole line is refreshed.
{ "language": "en", "url": "https://stackoverflow.com/questions/149977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting different header size by changing window size I have a C++ program representing a TCP header as a struct: #include "stdafx.h" /* TCP HEADER 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Port | Destination Port | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Sequence Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Acknowledgment Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Data | |U|A|P|R|S|F| | | Offset| Reserved |R|C|S|S|Y|I| Window | | | |G|K|H|T|N|N| | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Checksum | Urgent Pointer | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | data | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ typedef struct { // RFC793 WORD wSourcePort; WORD wDestPort; DWORD dwSequence; DWORD dwAcknowledgment; unsigned int byReserved1:4; unsigned int byDataOffset:4; unsigned int fFIN:1; unsigned int fSYN:1; unsigned int fRST:1; unsigned int fPSH:1; unsigned int fACK:1; unsigned int fURG:1; unsigned int byReserved2:2; unsigned short wWindow; WORD wChecksum; WORD wUrgentPointer; } TCP_HEADER, *PTCP_HEADER; int _tmain(int argc, _TCHAR* argv[]) { printf("TCP header length: %d\n", sizeof(TCP_HEADER)); return 0; } If I run this program I get the size of this header as 24 bytes, which is not the size I was expecting. If I change the type of the field "wWindow" to "unsigned int wWindow:16", which has the same number of bits as an unsigned short, the program tells me the size of the struct is now 20 bytes, the correct size. Why is this? I am using Microsoft Visual Studio 2005 with SP1 on a 32-bit x86 machine. A: Because the compiler is packing your bitfield into a 32-bit int, not a 16-bit entity. In general you should avoid bitfields and use other manifest constants (enums or whatever) with explicit bit masking and shifting to access the 'sub-fields' in a field. Here's one reason why bitfields should be avoided - they aren't very portable between compilers even for the same platform. from the C99 standard (there's similar wording in the C90 standard): An implementation may allocate any addressable storage unit large enough to hold a bitfield. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined. The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined. The alignment of the addressable storage unit is unspecified. You cannot guarantee whether a bit field will 'span' an int boundary or not and you can't specify whether a bitfield starts at the low-end of the int or the high end of the int (this is independant of whether the processor is big-endian or little-endian). A: Your series of "unsigned int:xx" bitfields use up only 16 of the 32 bits in an int. The other 16 bits (2 bytes) are there, but unused. This is followed by the unsigned short, which is on an int boundary, and then a WORD, which is along aligned on an int boundary which means that there 2 bytes of padding between them. When you switch to "unsigned int wWindow:16", instead of being a separate short, the compiler uses the unused parts of the previous bitfield, so no waste, no short, and no padding after the short, hence you save four bytes. A: See this question: Why isn't sizeof for a struct equal to the sum of sizeof of each member? . I believe that compiler takes a hint to disable padding when you use the "unsigned int wWindow:16" syntax. Also, note that a short is not guaranteed to be 16 bits. The guarantee is that: 16 bits <= size of a short <= size of an int. A: The compiler is padding the non-bitfield struct member to 32-bit -- native word alignment. To fix this, do #pragma pack(0) before the struct and #pragma pack() after. A: Struct boundaries in memory can be padded by the compiler depending on the size and order of fields. A: Not a C/C++ expert when it comes to packing. But I imagine there is a rule in the spec which says that when a non-bitfield follows a bitfield it must be aligned on the word boundary regardless of whether or not it fits in the remaining space. By making it an explicit bitvector you are avoiding this problem. Again this is speculation with a touch of experience. A: Interesting - I would think that "WORD" would evaluate to "unsigned short", so you'd have that problem in more than one place. Also be aware that you'll need to deal with endian issues in any value over 8 bits. A: You are seeing different values because of compiler packing rules. You can see rules specific to visual studio here. When you have a structure that must be packed (or adhere to some specific alignment requirements), you should use the #pragma pack() option. For your code, you can use #pragma pack(0) which will align all structure members on byte boundaries. You can then use #pragma pack() to reset structure packing to it's default state. You can see more information on the pack pragma here. A: I think Mike B got it right, but but not perfectly clear. When you ask for "short", it's aligned on 32bit boundary. When you ask for int:16, it's not. So int:16 fits right after th ebit fields, while short skips 2 bytes and starts at the next 32-bit block. The rest of what he is saying is perfectly applicable - the bit field must never be used to code an externally-visible structure, because there are no guarantee as to how they are allocated. At best, they belong in embedded programs where saving a byte is important. And even there, you can't use them to actually controly bits in memory-mapped ports.
{ "language": "en", "url": "https://stackoverflow.com/questions/149995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How do I persist a ByRef variable into .net winforms dialog form? I am creating a "department picker" form that is going to serve as a modal popup form with many of my "primary" forms of a Winforms application. Ideally the user is going to click on an icon next to a text box that will pop up the form, they will select the department they need, and when they click OK, the dialog will close and I will have the value selected for me to update the textbox with. I've already done the route with passing the owner of the dialog box into the dialog form and having the OK button click event do the proper update, but this forces me to do a DirectCast to the form type and I can then only reuse the picker on the current form. I have been able to use a ByRef variable in the constructor and successfully update a value, but it works only in the constructor. If I attempt to assign the ByRef value to some internal variable in the Department Picker class, I lose the reference aspect of it. This is my basic code attached to my form: Public Class DeptPicker Private m_TargetResult As String Public Sub New(ByRef TargetResult As String) InitializeComponent() ' This works just fine, my "parent" form has the reference value properly updated. TargetResult = "Booyah!" ' Once I leave the constructor, m_TargetResult is a simple string value that won't update the parent m_TargetResult = TargetResult End Sub Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click DialogResult = Windows.Forms.DialogResult.OK ' I get no love here. m_TargetResult is just a string and doesn't push the value back to the referenced variable I want. m_TargetResult = "That department I selected." Me.Close() End Sub Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click DialogResult = Windows.Forms.DialogResult.Cancel Me.Close() End Sub End Class Can somebody tell me what I'm missing here or a different approach to make this happen? Note: Code sample is in VB.NET, but I'll take any C# answers too. 8^D A: In such cases, I usually either * *Write a ShowDialog function that does what I want (e.g. return the value) or *Just let the result be a property in the dialog. This is how the common file dialogs do it in the BCL. The caller must then read the property to get the result. That's fine in my opinion. You can also combine these methods, by making the result value a property in the dialog and creating a ShowDialog method that returns that property value, either as ByRef as you want or as a return value, depending on your needs. I'll add this as a usage instruction, for example (sorry, no VB over here, and you said C# is welcome): using (var dlg = new DeptPicker()) { if (dlg.ShowDialog() == DialogResult.OK) { myTextBoxOrWhatEver.Text = dlg.TargetResult; } } In the dialog itself, just do this: void okButton_Click(object sender, EventArgs e) { TargetResult = whatever; // can also do this when the selection changes DialogResult = DialogResult.OK; Close(); } I didn't use the new ShowDialog implementation in this sample though. A: The problem is that assigning TargetResult in the constructor is using the string as a reference. The m_TargetResult string is just a copy of the ref string, not a reference to the original string. As for how to make a "pointer" to the original, I don't know. This is made even harder by the fact that VB.NET doesn't support unsafe code blocks, so you can't make a pointer reference to the string. A: You could pass the textbox reference to the modal form. Let the user choose any department. When user clicks OK, set the referred textbox's text property to chosen department's text or id (depends on what you need) I am using the code provided by you. Public Class DeptPicker Private m_TargetTextBox As TextBox Public Sub New(ByRef TargetTextBox As TextBox) InitializeComponent() m_TargetTextBox = TargetTextBox End Sub Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click DialogResult = Windows.Forms.DialogResult.OK ' I get no love here. m_TargetResult is just a string and doesn't push the value back to the referenced variable I want. m_TargetTextBox.Text = "That department I selected." Me.Close() End Sub Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click DialogResult = Windows.Forms.DialogResult.Cancel Me.Close() End Sub End Class A: Public Class DeptPicker dim dlgResult as DialogResult Public Function GetSelectedDepartment() As String Me.Show vbModal If (dlgResult = Windows.Forms.DialogResult.OK) Then return "selected department string here" Else return "sorry, you didnt canceled on the form" End If End Function Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click dlgResult = Windows.Forms.DialogResult.OK Me.Close() End Sub Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click dlgResult = Windows.Forms.DialogResult.Cancel Me.Close() End Sub End Class Note: I haven't tested this. I hope you get idea of what I mean. OregonGhost: Does this look better? The user can call new DeptPicker().GetSelectedDepartment(). I didnt know that I need not post the answer again & could use the same post. Thanks OregonGhost. Now, does it look ok? A: This may work: // This code in your dialog form. Hide the base showdialog method // and implement your own versions public new string ShowDialog() { return this.ShowDialog(null); } public new string ShowDialog(IWin32Window owner) { // Call the base implementation of show dialog base.ShowDialog(owner); // You get here after the close button is clicked and the form is hidden. Capture the data you want. string s = this.someControl.Text; // Now really close the form and return the value this.Close(); return s; } // On close, just hide. Close in the show dialog method private void closeButton_Click(object sender, EventArgs e) { this.Hide(); } // This code in your calling form MyCustomForm f = new MyCustomForm(); string myAnswer = f.ShowDialog();
{ "language": "en", "url": "https://stackoverflow.com/questions/150010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Precision of reals through writeln/readln in Delphi My clients application exports and imports quite a few variables of type real through a text file using writeln and readln. I've tried to increase the width of the fields written so the code looks like: writeln(file, exportRealvalue:30); //using excess width of field .... readln(file, importRealvalue); When I export and then import and export again and compare the files I get a difference in the last two digits, e.g (might be off on the actual number of digits here but you get it): -1.23456789012E-0002 -1.23456789034E-0002 This actually makes a difference in the app so the client wants to know what I can do about it. Now I'm not sure it's only the write/read that does it but I thought I'd throw a quick question out there before I dive into the hey stack again. Do I need to go binary on this? This is not an app dealing with currency or something, I just write and read the values to/from file. I know floating points are a bit strange sometimes and I thought one of the routines (writeln/readln) may have some funny business going on. A: You might try switching to extended for greater precision. As was pointed out though, floating point numbers only have so many significant digits of precision, so it is still possible to display more digits then are accurately stored, which could result in the behavior you specified. From the Delphi help: Fundamental Win32 real types | Significant | Size in Type | Range | digits | bytes ---------+----------------------------------+-------------+---------- Real | -5.0 x 10^–324 .. 1.7 x 10^308 | 15–16 | 8 Real48 | -2.9 x 10^–39 .. 1.7 x 10^38 | 11-12 | 6 Single | -1.5 x 10^–45 .. 3.4 x 10^38 | 7-8 | 4 Double | -5.0 x 10^–324 .. 1.7 x 10^308 | 15-16 | 8 Extended | -3.6 x 10^–4951 .. 1.1 x 10^4932 | 10-20 | 10 Comp | -2^63+1 .. 2^63–1 | 10-20 | 8 Currency | -922337203685477.5808.. | | 922337203685477.5807 | 10-20 | 8 Note: The six-byte Real48 type was called Real in earlier versions of Object Pascal. If you are recompiling code that uses the older, six-byte Real type in Delphi, you may want to change it to Real48. You can also use the {$REALCOMPATIBILITY ON} compiler directive to turn Real back into the six-byte type. The following remarks apply to fundamental real types. * *Real48 is maintained for backward compatibility. Since its storage format is not native to the Intel processor architecture, it results in slower performance than other floating-point types. *Extended offers greater precision than other real types but is less portable. Be careful using Extended if you are creating data files to share across platforms. Notice that the range is greater then the significant digits. So you can have a number larger then can be accurately stored. I would recommend rounding to the significant digits to prevent that from happening. A: If you want to specify the precision of a real with a WriteLn, use the following: WriteLn(RealVar:12:3); It outputs the value Realvar with at least 12 positions and a precision of 3. A: When using floating point types, you should be aware of the precision limitations on the specified types. A 4 byte IEEE-754 type, for instance, has only about 7.5 significant digits of precision. An eight byte IEEE-754 type has roughly double the number of significant digits. Apparently, the delphi real type has a precision that lies around 11 significant digits. The result of this is that any extra digits of formatting that you specify are likely to be noise that can result in conversions between base 10 formatted values and base 2 floating point values. A: First of all I would try to see if I could get any help from using Str with different arguments or increasing the precision of the types in your app. (Have you tried using Extended?) As a last resort, (Warning! Workaround!!) I'd try saving the customer's string representation along with the binary representation in a sorted list. Before writing back a floating point value I'd see if there already is a matching value in the table, whose string representation is already known and can be used instead. In order to make get this lookup quick, you can sort it on the numeric value and use binary search for finding the best match. A: Depending on how much processing you need to do, an alternative could be to keep the numbers in BCD format to retain original accuracy. A: It's hard to answer this without knowing what type your ExportRealValue and ImportRealValue are. As others have mentioned, the real types all have different precisions. It's worth noting, contrary to some thought, extended is not always higher precision. Extended is 10-20 significant figures where double is 15-16. As you are having trouble around the tenth sig fig perhaps you are using extended already. To get more control over the reading and writing you can convert the numbers to and from strings yourself and write them to a file stream. At least that way you don't have to worry if readln and writeln are up to no good behind your back.
{ "language": "en", "url": "https://stackoverflow.com/questions/150011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Load in memory text into WebBrowser control On the .Net WebBrowser control the only way I can see to load a page to it is to set the URL property. But I would like to instead give it some HTML code that I already have in memory without writing it out to a file first. Is there any way to do this? Or are there any controls that will do this? A: You use either WebBrowser.DeocumentText (http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.documenttext.aspx) or WebBrowser.DocumentStream (http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.documentstream.aspx) to change the HTML in the current document. You might need to navigate to about:blank, if you don't have a document. A: You want the DocumentText Property: http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.documenttext.aspx ? from http://www.codeguru.com/forum/showpost.php?p=1691329&postcount=9 : Also you should provide a couple things: * *Don't set DocumentText in the constructor. Use Form_Load or your own method. If you set DocumentText in the constructor, you will not be able to set it again anywhere in the application. Be sure to check that the Form Designer hasn't set it either. *You can only set DocumentText once per method call. This is odd and most likely a bug, but it's true. For example: setting DocumentText in a for-loop will only set properly on the first iteration of the loop. You can however, create a small method to set DocumentText to the passed in string, then call this method in a for-loop. A: Also, generally, anywhere you can use a Stream, you can use MemoryStream to wrap data you have in memory.
{ "language": "en", "url": "https://stackoverflow.com/questions/150014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }