Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am using Visual Studio 2008 | .NET 3.5 | C#. I have created an user control that has the following property: DisplayMode. DisplayMode is meant to either display a series of text boxes or a single text box. ``` [Browsable(true), Category("Appearance"), DefaultValue(DISPLAY_MODE_FIELDS), Description("Indicates whether to display the phone number as a single text box or separate fields.")] public string DisplayMode { get { return mDisplayMode; } set { mDisplayMode = value; } } ``` Therefore, I want the options of the property to either be 'Fields' or 'Single'. I specified above I want to make this browsable in the designer, but how do I set those two values as options rather than knowing to specify 'Fields', 'Single', etc. in the future? Is there another attribute that I can decorate the property with to list these options out or do I need to create an enum (which works)? Thanks in advance and please let me know if you need any other info!
The enum is the way to go. It will provide IntelliSense for the values in the Visual Studio HTML editor, and it will be more type-safe and easier to use in the code.
Just create an Enum In your user control - ``` public enum OrientationOption { Horizontal, Vertical } public OrientationOption Orientation { get; set; } ``` That's it ! this is how it will look like in your VS autocomplete ![Auto complete options in code view](https://i.stack.imgur.com/3ib00.jpg)
ASP.NET User Control Property Value Options In Designer Mode
[ "", "c#", "asp.net", ".net-3.5", "user-controls", "" ]
When overriding a non-virtual method in Java, use of the `@Override` annotation is recommended, but what if I implement an abstract method? Should I use `@Override` then as well?
I tend to prefer the use of `@Override` in this case, so that the method gets flagged in the subclasses if the superclass changes (either removing the method altogether, or changing its signature, etc.). The only real difference is that without the annotation, if the method in the superclass/interface is changed or removed, the implementation in question simply becomes a "normal" method of that class. Thus you should add the annotation if you're implementing the method solely to fulfil the contract; and you probably shouldn't add it if the method makes sense in your class regardless of any implemented interfaces or inherited abstract methods.
Yes - again, it tells the compiler, "I really want to be overriding a method here. If there *isn't* a corresponding method to override, I've made a mistake and want to be told about it!" Personally I think it's a pity that this is just an annotation rather than part of the language (as it is in C#) but that's the benefit of hindsight, of course.
Should I add an @Override annotation when implementing abstract methods in Java?
[ "", "java", "annotations", "overriding", "abstract", "" ]
Let's say that you are setting up a POJO. What do you define when you setup the class? Here's my list * Constructor to create an object with supplied fields (so that I can make fields final and hence immutable) * toString * equals * hashcode * implements comparable * get methods (where applicable) * [Optional] copy constructors for mutable fields - to guarantee immutability of the class * [Optional] Define interfaces to access fields and methods. * [Optional] implements Serializable and implement a versioning scheme. Is this overkill or sound engineering? Anything missing that you would add?
I'm assuming that because you mentioned a versioning scheme, that we're talking about persistable classes. I'd say you have a nice list there, but (depending on your ORM engine), I also tend to determine what values (other than the autoincrement ID), define the 'uniqueness' of any record. I only mention this because hibernate has weird behaviour with Sets, if you use the ID in hashCode, because it is liable to change halfway through the process. Also worth noting that it's worth your time to look at which collections are going to be Lazy or Eager, especially for the toString method (which may cause Lazy-Inits if you do a toString when you are detached from the persistence context).
If I know what I want to do usually write a test first and then write the class to make it run.
What do you do when you start a new POJO class?
[ "", "java", "pojo", "" ]
I'm developing a Silverlight app and would like to create a grouping of 5 toggle buttons (used for menu options) that animate when clicked (grow in size) and also cause any previously clicked buttons in the group to unclick and animate back to their shrunken size. I know I could use a brute force approach where the app is directly aware of each button, but if I add or change the menu (add/remove a button) I'd have to remember to modify the code (which is bad since I'm forgetful). Is there a way to more intelligently group the buttons so that when one is clicked is can tell all the others in the group to unclick? Thanks! Todd
Special shout-out to Michael S. Scherotter for pointing me in the right direction to use RadioButton and a control template! Here's the basic control template that I came up with. Put this in the App.xaml between the tags if you care to see it. The UX folks will give it a once over to pretty it up, but for now, it works as a radio button that looks like a toggle button (or just a button), but has a groupname. An important note: this template doesn't have any of the basic button animation, so it won't press down when clicked... That's the UX work I mentioned above. ``` <Style x:Key="MenuButton" TargetType="RadioButton"> <Setter Property="Width" Value="100"/> <Setter Property="Height" Value="25"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="RadioButton"> <Border BorderBrush="DarkGray" BorderThickness="3" CornerRadius="3" Background="Gray"> <!-- The ContentPresenter tags are used to insert on the button face for reuse --> <ContentPresenter></ContentPresenter> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> ```
I was trying to do the same thing and I found this old post. Let me update it a bit... Todd seems to be like many other lazy programmers, letting the UX guys do all the work. :) So here is Todd's solution with actual toggle buttons as radio buttons in a group: ``` <RadioButton GroupName="myGroup" Style="{StaticResource MenuButton}" Content="One" IsChecked="True" /> <RadioButton GroupName="myGroup" Style="{StaticResource MenuButton}" Content="Two" /> <RadioButton GroupName="myGroup" Style="{StaticResource MenuButton}" Content="Three" /> <Style x:Key="MenuButton" TargetType="RadioButton"> <Setter Property="Width" Value="100"/> <Setter Property="Height" Value="25"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="RadioButton"> <Border BorderBrush="DarkGray" BorderThickness="3" CornerRadius="3" Background="Gray"> <ToggleButton IsChecked="{Binding IsChecked, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"> <ToggleButton.Content> <ContentPresenter></ContentPresenter> </ToggleButton.Content> </ToggleButton> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> ``` And now you'll have your pretty button rollover effects and all that and only one toggle button will be able to be 'checked' at one time. Both radio buttons and toggle buttons can be three state, and you can bind the 'IsThreeState' property of the toggle button as well in the same manner that I bind 'IsChecked' here. But by default they are two state. Also, the long form binding is important here as the shortcut {TemplateBinding IsChecked} would default to one way and we need them to stay in sync both ways. This example does not, of course, animate the buttons with size changing and all that Todd originally posted, but it does give you regular buttons that you can easily distinguish as being checked or not.
Silverlight Toggle Button Grouping
[ "", "c#", "silverlight", "xaml", "" ]
I am working on a base encryption method. I am using RijndaelManaged. I got this code from somewhere a long time ago, but can't remember where. I had my code working before, but something changed and I cannot quite figure it out. When I run my code, I get the following error; > Specified initialization vector (IV) > does not match the block size for this > algorithm. Here is my code: ``` string textToEncrypt = "TEST STRING"; int keySize = 256; string hashAlgorithm = "SHA1"; string passPhrase = "AH!PSB0%FGHR$"; string saltValue = "LRT%YUR#VBNL@1"; string initVector = "HR$2pIjHR$2pIj"; byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector); byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue); byte[] plainTextBytes = Encoding.UTF8.GetBytes(textToEncrypt); var password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, 2); byte[] keyBytes = password.GetBytes(keySize / 8); RijndaelManaged symmetricKey = new RijndaelManaged(); symmetricKey.Mode = CipherMode.CBC; ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes,initVectorBytes); MemoryStream memoryStream = new MemoryStream(); var cryptoStream = new CryptoStream(memoryStream,encryptor,CryptoStreamMode.Write); cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); byte[] cipherTextBytes = memoryStream.ToArray(); memoryStream.Close(); cryptoStream.Close(); string cipherText = Convert.ToBase64String(cipherTextBytes); ``` Any help will be appreciated.
The problem is your initialization vector size needs to be 16 bytes. Your initial vector size is 14 bytes. You will need to increase the size of your initial vector by 2 bytes and your code will work. Example: ``` string initVector = "HR$2pIjHR$2pIj12"; ``` You will then get the output with your current code and the example IV (initialization vector) size provided: hAC8hMf3N5Zb/DZhFKi6Sg== This article provides a good explanation on what the initialization vector is. <http://en.wikipedia.org/wiki/Initialization_vector>
You should be able to check how many bytes the IV needs to be using: ``` algorithm.BlockSize / 8 ``` BlockSize is in bits, so 128 bits / 8 gives 16 bytes of ASCII, and you may also find `Rfc2898DeriveBytes` a useful class for producing keys. ``` algorithm.IV = rfc2898DeriveBytesForIV.GetBytes(algorithm.BlockSize / 8); ``` Hope it helps.
Specified initialization vector (IV) does not match the block size for this algorithm
[ "", "c#", "encryption", "rijndaelmanaged", "rijndael", "" ]
When I start tomcat 6 it freezes in certain point of the startup and stays there forever (I've waited 3 hours and nothing happened - not even an out of memory error). I don't have any clue of what could cause a behavior like that. I'm runnig tomcat with Jira and Confluence, and the problem seem to be when tomcat tries to load confluence: ``` ****************************************************************************************************** JIRA 3.13.3 build: 344 (Enterprise Edition) started. You can now access JIRA through your web browser. ****************************************************************************************************** 2009-06-02 19:38:21,272 JiraQuartzScheduler_Worker-1 INFO [jira.action.admin.DataExport] Export took 387ms 2009-06-02 19:38:21,291 JiraQuartzScheduler_Worker-1 INFO [jira.action.admin.DataExport] Wrote 392 entities to export 2009-06-02 19:38:21,606 INFO [main] [com.atlassian.confluence.lifecycle] contextInitialized Starting Confluence 2.10.3 (build #1519) 2009-06-02 19:38:21,711 INFO [main] [beans.factory.xml.XmlBeanDefinitionReader] loadBeanDefinitions Loading XML bean definitions from class path resource [bootstrapContext.xml] 2009-06-02 19:38:22,236 INFO [main] [beans.factory.xml.XmlBeanDefinitionReader] loadBeanDefinitions Loading XML bean definitions from class path resource [setupContext.xml] ``` After this line above nothing more happens. I thought it could be a problem with permGem or something like that, so to avoid permGem limitations, I configured catalina.sh with: ``` CATALINA_OPTS="$CATALINA_OPTS -Dorg.apache.jasper.runtime.BodyContentImpl.LIMIT_BUFFER=true" JAVA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 -server -Xms1536m -Xmx1536m -XX:PermSize=256m -XX:MaxPermSize=640m -XX:+DisableExplicitGC" ``` I incresed a lot jvm's space to see if it works, but it didn't help. Tomcat version: 6.0.18 Jira version: 3.13.3 Confluence Version: 2.10.3 So, anyone have already had this problem before? Could it be a memory(RAM) problem? A problem with Spring and Tomcat6? Or any other kind of problem?
Do you have any errors in your log? Have you checked if confluence is maybe waiting for the database or network?
Get a [thread dump](http://java.sun.com/developer/technicalArticles/Programming/Stacktrace/) for the application and check for threads which are BLOCKED, WAITING or TIMED\_WAITING. Also beware of threads in RUNNABLE *but* doing network I/O, e.g `InputStream.read()`.
Tomcat 6 freezes at startup
[ "", "java", "tomcat6", "" ]
I need to work out how many different instances occur on a different day, from many different ranges. Probably best to explain it with an example. ``` 18-JAN-09 to 21-JAN-09 19-JAN09 to 20-JAN-09 20-JAN-09 to 20-JAN-09 ``` Using the three examples above, I need it to collect this information and display something a little like... ``` 18th Jan: 1 19th Jan: 2 20th Jan: 3 21st Jan: 1 ``` ... I'll be grabbing the information from an Oracle database fwiw (hence the format above ^) and there will be hundreds, maybe thousands of records, so my lame attempt to do all sorts of loops and if statements would take forever to run. Is there any fairly simple and efficient way of doing this? I'm really not too sure where to start unfortunately... Thanks
Either your DB engine or your PHP code is going to have to loop over the date range. Here's some PHP code to do the summation. The day counts are stored by `year-month` to avoid having a huge array for a wide date range. ``` <?php // Get the date ranges from the database, hardcoded for example $dateRanges[0][0] = mktime(0, 0, 0, 1, 18, 2009); $dateRanges[0][1] = mktime(0, 0, 0, 1, 21, 2009); $dateRanges[1][0] = mktime(0, 0, 0, 1, 19, 2009); $dateRanges[1][1] = mktime(0, 0, 0, 1, 20, 2009); $dateRanges[2][0] = mktime(0, 0, 0, 1, 20, 2009); $dateRanges[2][1] = mktime(0, 0, 0, 1, 20, 2009); for ($rangeIndex = 0; $rangeIndex < sizeof($dateRanges); $rangeIndex++) { $startDate = $dateRanges[$rangeIndex][0]; $endDate = $dateRanges[$rangeIndex][1]; // Add 60 x 60 x 24 = 86400 seconds for each day for ($thisDate = $startDate; $thisDate <= $endDate; $thisDate += 86400) { $yearMonth = date("Y-m", $thisDate); $day = date("d", $thisDate); // Store the count by year-month, then by day $months[$yearMonth][$day]++; } } foreach ($months as $yearMonth => $dayCounts) { foreach ($dayCounts as $dayNumber => $dayCount) { echo $yearMonth . "-" . $dayNumber . ": " . $dayCount . "<br>"; } } ?> ```
You could use the method described in [another SO](https://stackoverflow.com/questions/987610/how-to-iterate-over-a-date-range-in-pl-sql/987788#987788 "How to iterate over a date range"): ``` SQL> WITH DATA AS ( 2 SELECT to_date('18-JAN-09', 'dd-mon-rr') begin_date, 3 to_date('21-JAN-09', 'dd-mon-rr') end_date FROM dual UNION ALL 4 SELECT to_date('19-JAN-09', 'dd-mon-rr'), 5 to_date('20-JAN-09', 'dd-mon-rr') FROM dual UNION ALL 6 SELECT to_date('20-JAN-09', 'dd-mon-rr'), 7 to_date('20-JAN-09', 'dd-mon-rr') FROM dual 8 ),calendar AS ( 9 SELECT to_date(:begin_date, 'dd-mon-rr') + ROWNUM - 1 c_date 10 FROM dual 11 CONNECT BY LEVEL <= to_date(:end_date, 'dd-mon-rr') 12 - to_date(:begin_date, 'dd-mon-rr') + 1 13 ) 14 SELECT c.c_date, COUNT(d.begin_date) 15 FROM calendar c 16 LEFT JOIN DATA d ON c.c_date BETWEEN d.begin_date AND d.end_date 17 GROUP BY c.c_date 18 ORDER BY c.c_date; C_DATE COUNT(D.BEGIN_DATE) ----------- ------------------- 18/01/2009 1 19/01/2009 2 20/01/2009 3 21/01/2009 1 ```
Working with date ranges in PHP/Oracle
[ "", "php", "oracle", "date", "range", "" ]
i'm searching for an equivalent function for php's "list()". i'd like to split a string with "split()" and put the array values in two different variables. hopefully there's another way to do this as short and performance-optimized as it could be. thanks for your attention!
Here's a list implementation in javascript: <http://solutoire.com/2007/10/29/javascript-left-hand-assignment/>
Maybe [PHP.JS](http://phpjs.org/) is worth looking at (for future stuff maybe). I noticed that the [list()](http://trac.plutonia.nl/projects/phpjs/browser/trunk/_experimental/array/list.js) was only experimental though but maybe it works.
searching equivalent function/way to "list()" from php
[ "", "javascript", "" ]
This may be quite simple but I'm rather new to Lambda's so bear with me. I have a function that uses a Lambda function to recurse. The main function receives a bool telling it to include certain information or not within the lambda. The function is designed to write out a custom class to XML - I think the code is pretty self explanitory. At the moment I have overcome the problem using a simple if statement, but it feels ugly so wondered if anyone knew a better way? ``` private XElement ErrorListToXml(ErrorList el, bool outputTagsOnly) { // Need to declare in advance to call within the lambda. Func<ErrorType, XElement> recursiveGenerator = null; if (outputTagsOnly) recursiveGenerator = error => new XElement (error.Name, error.ChildErrors.Select(recursiveGenerator)); else recursiveGenerator = error => new XElement (error.Name, new XAttribute("Ignore", error.Filter), error.ChildErrors.Select(recursiveGenerator)); var element = new XElement ("ErrorList", ChildErrors.Select(recursiveGenerator)); Console.WriteLine(element); return element; } ```
mquander's solution can be improved slightly to reduce duplication. You can use the fact that you can pass in `null` an element in the XElement constructor content, and it gets ignored. We can therefore move the condition further in: ``` Func<ErrorType, XElement> recursiveGenerator = null; recursiveGenerator = (error => new XElement(error.Name, outputTagsOnly ? null : new XAttribute("Ignore", error.Filter), error.ChildErrors.Select(recursiveGenerator)); var element = new XElement("ErrorList", ChildErrors.Select(recursiveGenerator)); ```
You can make a decision between values of the same type in a lambda pretty easily: ``` customer => flag ? customer.Name : customer.Address ``` You can use an if statement in a lambda with a little more effort: ``` customer => { if (flag) return customer.Name else return customer.Address } ``` Neither of these helps your method greatly.
If statement within Lambda function?
[ "", "c#", ".net", "c#-3.0", "lambda", "" ]
I'm having issues trying to read input whilst outputting at the same time. I need a server console for my game which can receive input whilst outputting and not mess up the buffer. For example, I'm typing "Hello world" and in the process, player deaths, kills, etc. are being outputted into the console, which would result in something like: > Hello \*Player killed Player2\*world Thanks in advance
Instead of writing output directly to the console, why not spawn a GUI window? Then, just have one area where output is directed, and a separate input area at the bottom where you can type commands. Kinda like how an irc client would look. If it has to be console only, I would suggest using something like ncurses (or PDCurses) to create a text based interface.
Without thinking too hard about this, it seems to me you either need a non-blocking input routine for stdin, something like getch() but just returns if there is nothing to read, which you call in a loop while also processing output, or you need two thraeds: one to read, one to write.
Asynchronous Windows Console input whilst outputting
[ "", "c++", "windows", "winapi", "console", "" ]
My PHP app has an import script that can import records. At the moment, it is importing from a CSV file. It is reading each line of the CSV file, one line at a time using fgetcsv, and for each line it is doing *a lot* of processing on that record, including database queries, and then moving on to the next line. It shouldn't need to keep accumulating more memory. After around 2500 records imported, PHP dies, saying that it has run over its memory limit (132 MB or so). The CSV file itself is only a couple of megs - the other processing that happens does a lot of string comparisons, diffs, etc. I have a huge amount of code operating on it and it would be difficult to come up with a 'smallest reproducing sample'. What are some good ways to go about finding and fixing such a problem? ***Cause of problem found*** *I have a debug class which logs all my database queries during runtime. So those strings of SQL, some 30KB long, were staying in memory. I realise this isn't suitable for scripts designed to run for a long time.* *There may be other sources of memory leaks, but I am fairly sure this is the cause of my problem.*
It would help to have a look at the code but if you want to debug it yourself, have a look at [Xdebug](http://www.xdebug.org/), it'll help profile your application. Of course, depending on what you are doing, it is possible it's accumulating some memory, although 132MB seems already high for 2500 records. Of course, you can [tweak your memory limit](http://www.php.net/manual/en/ini.core.php#ini.memory-limit) in php.ini if needed. How big is the CSV file you are reading? And what objects and kind of processing are you doing to it?
If you do in fact suspect that there are just one or two memory leaks in your script which are causing it to crash, then you should take the following steps: * Change `memory_limit` to something small, like 500KB * Comment out all but one of the processing steps which is applied to each row. * Run the limited processing over the whole CSV file and see if it can complete. * Gradually add more steps back in and watch to see if memory usage spikes. Example: ``` ini_set('memory_limit', 1024 * 500); $fp = fopen("test.csv", 'r'); while($row = fgetcsv($fp)) { validate_row($row); // step 1: validate // add these back in one by one and keep an eye on memory usage //calculate_fizz($row); // step 2: fizz //calculate_buzz($row); // step 3: buzz //triangulate($row); // step 4: triangulate } echo "Memory used: ", memory_get_peak_usage(), "\n"; ``` The worst case scenario is that *all* of your processing steps are moderately inefficient and you will need to optimize all of them.
How to go about fixing a memory leak in PHP
[ "", "php", "memory-leaks", "reference-counting", "" ]
``` int x; int iHateDataRows = dt.Rows.Count + 2; System.Data.DataRow[] dra = new System.Data.DataRow[1000]; for(x = 0; x < iHateDataRows; ++x) ``` So, this is obviously a loop but, my problem is that the `++x` tells me that it is unreachable. I don't know if this is just my IDE going crazy or something (I use SharpDevelop, mostly because VS2008 is too clunky and doesn't have neat little features that I like.) I hope I provided enough info for someone to guess at the problem. I have stared at this thing, changed the variables. Everything, it won't budge. EDIT: This is after the for loop: ``` if(dra[x].ItemArray[2].ToString() == "0") { return x.ToString(); } else { return "Fail"; } ``` I sure hope this code is correct as I never got to test it.
You are always returning from the loop before it goes to the next iteration. That is, both halves of the "if" statement return. You never go back to the top of the loop.
You probably have a `break` or `return` (or, heaven forbid, `goto`) inside the loop.
Where is the unreachable code?
[ "", "c#", "for-loop", "sharpdevelop", "" ]
So I've got a web app that is for all intents and purposes a photo viewer. When a thumbnail is clicked, the app 1. requests the image asset, 2. injects it into the DOM as an IMG tag 3. and disposes the other (MooTools `Asset.image`, `inject` and `dispose`). If they click on an image that has already been loaded I just inject it again since `dispose` stores it. Users look at the images for an average of 12 seconds (according to my stats), that's plenty of time to download a few more. So my question again, slightly rephrased: **Is it good or bad practice to determine if I should download other assets in the background based on the movement of their mouse?** So if the mouse isn't moving, download the next few assets. If it starts moving, stop and wait for the mouse to stop (and have a little interval before starting to download again, like 1 or two seconds). It seems like a good idea to me but it just feels like there are some secondary effects I'm not thinking about. Gracias.
To answer your question directly, I don't think there will be an issue except that checking for mouse movement will have a degree of performance overhead. I would measure the performance on a slow machine, once you are done, to see if this is a problem.
You might make your back and forward buttons have bigger areas (white/transparent backgrounds) and check for mouseover on those backgrounds and load the images when the cursor is on those areas. Basically load the image right before the user clicks the button.
Is checking mousemove a good way to determine whether or not to download assets?
[ "", "javascript", "web-applications", "mootools", "user-experience", "asset-management", "" ]
I have a messaging tool within the website I am currently working on. The idea is to have a header div and a details div (display="none") for each message. Ideally, if javascript enabled, I have just the header showing and when the user clicks on it, the details div slide open. This is fine but how should I work it if javascript is disabled? I was thinking of expanding all messages if disabled, but I don't want a flicker briefly when the page loads of all images open and, if javascript enabled, they collapse. I'm using ASP.NET and was thinking of checking javascript status of the browser server side but i found out that it can't be done cleanly. Any suggestions on how to achieve this?
Actually, the most semantically correct way that you could do this is to append another stylesheet to the head via javascript containing styles that will be implemented if javascript is enabled. In your example, you will retain the default display for the elements in question. Then you will create an additional stylesheet (js-enabled-styles.css for example), and place your display:none within that. Then, in a script tag in your head you will append an additional stylesheet. Using jquery this would be: ``` $('head').append('<link rel="stylesheet" href="js-enabled-styles.css" type="text/css" />'); ```
One option is to place this in your head (after the defined styles): ``` <noscript> <style type="text/css"> #mydivid {display: block;} </style> </noscript> ``` **EDIT:** Ive actually posted [a better answer](https://stackoverflow.com/questions/959538/dealing-with-expandable-jquery-content-if-javascript-disabled/959611#959611), which works off a correct default state.
Dealing with expandable jQuery content if javascript disabled
[ "", "asp.net", "javascript", "jquery", "" ]
I am starting to get a bit bored of programming little toys that I have been making recently, and I would love to starting programming and interacting with hardware. The only problem is that I am mostly a python guy who hasn't really learned or used any other language. Can I still interact with hardware with python? Also, what hardware can I interact with? I don't really have stuff lying around that I can use, so I would have to buy a kit or something. What are some cheap options for this?
Interacting with the serial port on a PC is fairly trivial and there is [Python Serial library](http://pyserial.wiki.sourceforge.net/pySerial) available. [The roomba robot is controllable via a serial port](http://www.gorobotics.net/the-news/hobbyiest/irobot-releases-roomba-serial-port-interface). There are probably other robots out there, but this might be a simple, smallish step to get you going. Personally, I learned a lot by buying [a PIC programmer](http://dkc1.digikey.com/us/en/ph/Microchip/pic32.html) and making some simple [circuits to flash LEDs](http://www.best-microcontroller-projects.com/rgb-led.html). I moved on to controlling those PICs via serial port and later using USB (via [libusb](http://libusb-win32.sourceforge.net/)). There's a bigger learning curve there as you'll have to program the PICs in C or assembler but you can achieve some pretty incredible results once you've picked up the basics. I warn you though, it's a slippery slope once you realise how many cool little gadgets you can build :-)
Definitely look at [Arduino](http://www.arduino.cc/). * The hardware design is open-source so you could even assemble your own if you wanted * The board includes digital and analog inputs and outputs so it's easy to get some LEDs flashing quickly * You program it in a 'language' called [Wiring](http://en.wikipedia.org/wiki/Arduino#Software) which hides a lot of complexities of C which is usually used on PICs On the PC side, you could then use pySerial to communicate with the board over USB as mentioned above
Programming with hardware in python
[ "", "python", "hardware", "" ]
Here is my situation. I have the following tables: * **Product**, * **Product Attribute**, * **Order Product** (references a product\_id and an order\_id), * **Order Product Attribute** (references an order\_product and a product\_attribute). When an admin goes in to edit a product attribute (for instance "color"), he may delete that attribute by mistake and later add it back. If orders have already been placed for that product, when he deletes and re-adds the attribute, its ID in the Product Attribute table changes. This make it so that the Order Product Attribute references a non-existent attribute ID (though the attribute does still exist). What is the best way to go about solving this problem? Maybe I'm just in need of a different perspective on the issue. Note: the issue could also occur (just as importantly) if when editing the product, all of the attributes are flushed and the ones currently selected, which may be the same, are re-added.
Don't allow 'deleting by mistake'... just have an 'active' or 'inactive' flag as a column in the product attribute table. You can always save the attributes with the order instead of the attribute id. If your design is such that the attribute ids continually change, then your orders have no historical validity. Either make new 'versions' of the product and set the old version to inactive when changes are made or save the state of the product in the order so that you have some historical record.
Use innodb as your table type and add proper foreign key relationships to your dependent tables. Then, you won't be able to accidentally delete rows upon which you depend. Of course, if you still want (in some circumstances) to allow this, you can set foreign\_key\_ checks to off.
Best practice for dealing with deleted table rows?
[ "", "mysql", "sql", "" ]
basically: ``` public delegate void RecvCommandHandler (ChatApplication sender, byte[] content); event RecvCommandHandler[] commands = new RecvCommandHandler[255]; ``` I want to activate a different method/function for each command number, but I am really uncertain of the syntax. How am I supposed to do it? I think I'll go with just an array of delegates for this one, but the question is still interesting.
There's really no concept of an array of events - it's like talking about an array of properties. Events are really just methods which let you subscribe and unsubscribe handlers. If you need to be able to do this by index, I suggest you just have a pair of methods. (`AddCommandHandler(int, RecvCommandHandler)` and `RemoveCommandHandler(int, RecvCommandHandler)`). That won't support the normal event handling syntactic sugar, of course, but I don't see that there's a lot of alternative.
You could create an array of a class with operator overloading to simulate the behavior you are interested in... ``` public delegate void EventDelegate(EventData kEvent); public class EventElement { protected event EventDelegate eventdelegate; public void Dispatch(EventData kEvent) { if (eventdelegate != null) { eventdelegate(kEvent); } } public static EventElement operator +(EventElement kElement, EventDelegate kDelegate) { kElement.eventdelegate += kDelegate; return kElement; } public static EventElement operator -(EventElement kElement, EventDelegate kDelegate) { kElement.eventdelegate -= kDelegate; return kElement; } } public EventElement[] commands = new EventElement[255]; commands[100] += OnWhatever; commands[100].Dispatch(new EventData()); commands[100] -= OnWhatever; ```
array of events in C#?
[ "", "c#", "arrays", "events", "" ]
Folks, Please does anyone know how to show a Form from an otherwise invisible application, *and* have it get the focus (i.e. appear on top of other windows)? I'm working in C# .NET 3.5. I suspect I've taken "completely the wrong approach"... I do **not** *Application.Run(new TheForm ())* instead I *(new TheForm()).ShowModal()*... The Form is basically a modal dialogue, with a few check-boxes; a text-box, and OK and Cancel Buttons. The user ticks a checkbox and types in a description (or whatever) then presses OK, the form disappears and the process reads the user-input from the Form, Disposes it, and continues processing. This works, except when the form is show it doesn't get the focus, instead it appears behind the "host" application, until you click on it in the taskbar (or whatever). This is a most annoying behaviour, which I predict will cause many "support calls", and the existing VB6 version doesn't have this problem, so I'm going backwards in usability... and users won't accept that (and nor should they). So... I'm starting to think I need to rethink the whole shebang... I should show the form up front, as a "normal application" and attach the remainer of the processing to the OK-button-click event. It should work, But that will take time which I don't have (I'm already over time/budget)... so first I really need to try to make the current approach work... even by quick-and-dirty methods. So please does anyone know how to "force" a .NET 3.5 Form (by fair means or fowl) to get the focus? I'm thinking "magic" windows API calls (I know **Twilight Zone:** This only appears to be an issue at work, we're I'm using Visual Studio 2008 on Windows XP SP3... I've just failed to reproduce the problem with an SSCCE (see below) at home on Visual C# 2008 on Vista Ulimate... This works fine. Huh? WTF? Also, I'd swear that at work yesterday showed the form when I ran the EXE, but not when F5'ed (or Ctrl-F5'ed) straight from the IDE (which I just put up with)... At home the form shows fine either way. Totaly confusterpating! It may or may not be relevant, but Visual Studio crashed-and-burned this morning when the project was running in debug mode and editing the code "on the fly"... it got stuck what I presumed was an endless loop of error messages. The error message was something about "can't debug this project because it is not the current project, or something... So I just killed it off with process explorer. It started up again fine, and even offered to recover the "lost" file, an offer which I accepted. ``` using System; using System.Windows.Forms; namespace ShowFormOnTop { static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new Form1()); Form1 frm = new Form1(); frm.ShowDialog(); } } } ``` **Background:** I'm porting an existing VB6 implementation to .NET... It's a "plugin" for a "client" GIS application called [MapInfo](http://www.mapinfo.com/). The existing client "worked invisibly" and my instructions are "to keep the new version as close as possible to the old version", which works well enough (after years of patching); it's just written in an unsupported language, so we need to port it. **About me:** I'm pretty much a noob to C# and .NET generally, though I've got a bottoms wiping certificate, I have been a professional programmer for 10 years; So I sort of "know some stuff". Any insights would be most welcome... and Thank you all for taking the time to read this far. Consiseness isn't (apparently) my forte. Cheers. Keith.
Simply ``` yourForm.TopMost = true; ```
`Form.Activate()` worked in my case.
How to show form in front in C#
[ "", "c#", "forms", "z-order", "" ]
I am using this piece of code to make text button on web page ``` <a href='#' onclick="new Ajax.Updater('history', '/responsesG', {parameters: {name: '%s', port: '%s', profil: '201', action: 'profile'}, insertion: Insertion.Top} ); return false;">Do something</a> ``` since it is costly call I would like to prevent user from multiple clicking it since it makes asynchronous call and they get for instance 3 responses for same thing (since response last for 3 to 5 seconds) i tried option > asynchronous: false with same success(failure). How can I do it? Edit: ``` <a href="#" onclick="diagnostika('mac_adresa');return false;">-Mac address</a> <script type="text/javascript"> function diagnostika(akcija) { if(!this.clicked) { this.clicked = true; button = this; new Ajax.Updater('history', '/responsesG', { parameters: { name: '%(name)s', port: '%(port)s', action: akcija}, insertion: Insertion.Top, onComplete: function() { button.clicked = false;}});} return false;}; </script> ``` This is what I implemented in the end.
You'll need to add something like: ``` if(!this.clicked) { this.clicked = true; button = this; new Ajax.Updater('history', '/responsesG', { parameters: { name: '%s', port: '%s', profile: '201', action: 'profile' }, insertion: Insertion.Top, onComplete: function() { button.clicked = false; } }); } return false; ``` But, really, bring this out of an inline onClick so that it's easier to read.
Give your link a unique ID attribute, e.g: ``` <a href="#" id="foo">Do something</a> ``` Then in your JavaScript you can do this: ``` $("foo").observe("click", function() { this.disabled = true; new Ajax.Updater("history", "/responsesG", { parameters: { name: "%s", port: "%s", profile: "201", action: "profile" }, insertion: Insertion.Top }); return false; }); ```
Prototype: How to prevent button pushing until response is made
[ "", "javascript", "html", "prototypejs", "" ]
I have a minified/packed javascript file which is causing problems. The issue is that the non-packed input file has some missing semicolons *somewhere* which aren't a problem when there's line breaks, but when the file is packed, the line breaks are removed and that causes a parser error. For example: ``` //input var x = function() { doSomething(); } // note: no semicolon var y = 'y'; //---- // output var x=function(){doSomething();}var y='y'; // error here: ^ ``` The strange thing is that when I do a replace on the output file to replace all semicolons with a semicolon and a new line, the file works! This is making it ludicrously hard to find the error, since AFAIK, I can't think of any situation where a line break after a semicolon should change anything. Any ideas about why doing this replace would make it work?
Uh... Have you tried [JSLint](http://www.jslint.com/lint.html)?
When there's a line break, there's an implied semi-colon.
Javascript packing problem
[ "", "javascript", "" ]
I have a table in SQL that has four columns. Two of these are property and value columns that store performance metrics for one of our servers. We're constantly coming up with new performance metrics and we didn't want to keep redesigning our schema, so thats why we designed the table this way. Trouble is, when I create a view to look at the table as if its properly normalized, I get a query that just screams "Oh my god this is crap code" since it involves a table joined to itself 12 times. Here is the query I used for the view. Basically, it feels like I'm doing something really wrong, but I can't figure out a better way to solve the problem. ``` SELECT astats.AQTORStatsID, astats.ServerName, astats.Remarks, astats.StatsBeginDateTime, astats.StatsEndDateTime, asi1.AQTORStatValue as 'QtCPU_Average', asi2.AQTORStatValue as 'QtCPU_TopQuintile', asi3.AQTORStatValue as 'QtCPU_TopOnePercent', asi4.AQTORStatValue as 'QtCl_Average', asi5.AQTORStatValue as 'QtCl_TopQuintile', asi6.AQTORStatValue as 'QtCl_TopOnePercent', asi7.AQTORStatValue as 'UpdPrcStd_Average', asi8.AQTORStatValue as 'UpdPrcStd_TopQuintile', asi9.AQTORStatValue as 'UpdPrcStd_TopOnePercent', asi10.AQTORStatValue as 'RcRsUPr_Average', asi11.AQTORStatValue as 'RcRsUPr_TopQuintile', asi12.AQTORStatValue as 'RcRsUPr_TopOnePercent' FROM tb_rAQTORStatsItem asi1 INNER JOIN tb_rAQTORStatsItem asi2 ON asi1.AQTORStatsID = asi2.AQTORStatsID INNER JOIN tb_rAQTORStatsItem asi3 ON asi2.AQTORStatsID = asi3.AQTORStatsID INNER JOIN tb_rAQTORStatsItem asi4 ON asi3.AQTORStatsID = asi4.AQTORStatsID INNER JOIN tb_rAQTORStatsItem asi5 ON asi4.AQTORStatsID = asi5.AQTORStatsID INNER JOIN tb_rAQTORStatsItem asi6 ON asi5.AQTORStatsID = asi6.AQTORStatsID INNER JOIN tb_rAQTORStatsItem asi7 ON asi6.AQTORStatsID = asi7.AQTORStatsID INNER JOIN tb_rAQTORStatsItem asi8 ON asi7.AQTORStatsID = asi8.AQTORStatsID INNER JOIN tb_rAQTORStatsItem asi9 ON asi8.AQTORStatsID = asi9.AQTORStatsID INNER JOIN tb_rAQTORStatsItem asi10 ON asi9.AQTORStatsID = asi10.AQTORStatsID INNER JOIN tb_rAQTORStatsItem asi11 ON asi10.AQTORStatsID = asi11.AQTORStatsID INNER JOIN tb_rAQTORStatsItem asi12 ON asi11.AQTORStatsID = asi12.AQTORStatsID INNER JOIN tb_dAQTORStats astats on asi12.AQTORStatsID = astats.AQTORStatsID WHERE asi1.AQTORStatName = 'QtCPU_Average' AND asi2.AQTORStatName = 'QtCPU_TopQuintile' AND asi3.AQTORStatName = 'QtCPU_TopOnePercent' AND asi4.AQTORStatName = 'QtCl_Average' AND asi5.AQTORStatName = 'QtCl_TopQuintile' AND asi6.AQTORStatName = 'QtCl_TopOnePercent' AND asi7.AQTORStatName = 'UpdPrcStd_Average' AND asi8.AQTORStatName = 'UpdPrcStd_TopQuintile' AND asi9.AQTORStatName = 'UpdPrcStd_TopOnePercent' AND asi10.AQTORStatName = 'RcRsUPr_Average' AND asi11.AQTORStatName = 'RcRsUPr_TopQuintile' AND asi12.AQTORStatName = 'RcRsUPr_TopOnePercent' ```
Here's how you do it: ``` SELECT astats.AQTORStatsID , astats.ServerName , astats.Remarks , astats.StatsBeginDateTime , astats.StatsEndDateTime , QtCPU_Average = max(case when asi.AQTORStatName = 'QtCPU_Average' then asi.AQTORStatValue end) , QtCPU_TopQuintile = max(case when asi.AQTORStatName = 'QtCPU_TopQuintile' then asi.AQTORStatValue end) , QtCPU_TopOnePercent = max(case when asi.AQTORStatName = 'QtCPU_TopOnePercent' then asi.AQTORStatValue end) , QtCl_Average = max(case when asi.AQTORStatName = 'QtCl_Average' then asi.AQTORStatValue end) , QtCl_TopQuintile = max(case when asi.AQTORStatName = 'QtCl_TopQuintile' then asi.AQTORStatValue end) , QtCl_TopOnePercent = max(case when asi.AQTORStatName = 'QtCl_TopOnePercent' then asi.AQTORStatValue end) , UpdPrcStd_Average = max(case when asi.AQTORStatName = 'UpdPrcStd_Average' then asi.AQTORStatValue end) , UpdPrcStd_TopQuintile = max(case when asi.AQTORStatName = 'UpdPrcStd_TopQuintile' then asi.AQTORStatValue end) , UpdPrcStd_TopOnePercent = max(case when asi.AQTORStatName = 'UpdPrcStd_TopOnePercent' then asi.AQTORStatValue end) , RcRsUPr_Average = max(case when asi.AQTORStatName = 'RcRsUPr_Average' then asi.AQTORStatValue end) , RcRsUPr_TopQuintile = max(case when asi.AQTORStatName = 'RcRsUPr_TopQuintile' then asi.AQTORStatValue end) , RcRsUPr_TopOnePercent = max(case when asi.AQTORStatName = 'RcRsUPr_TopOnePercent' then asi.AQTORStatValue end) from tb_dAQTORStats astats join tb_rAQTORStatsItem asi on asi.AQTORStatsID = astats.AQTORStatsID group by astats.AQTORStatsID , astats.ServerName , astats.Remarks , astats.StatsBeginDateTime , astats.StatsEndDateTime ``` Notes: 1. A good text editor with column mode or rectangular edit really helps with this kind of thing. UltraEdit or Emacs come to mind. I created the above in UltraEdit in about a minute. 2. Your original query with the INNER JOINs would have dropped all readings for a given server if one type of reading was missing. Not good. This query will return one row per server for any server with at least one reading. If you want to return all servers, regardless of whether there are any readings, change the INNER JOIN to LEFT JOIN. 3. You don't need a separate table for your stat names, unless you need to enforce data integrity through a foreign key.
IMHO, this kind of code (as well as trouble designing indices) is part of the price you pay for the flexibility of the "property table" idiom -- you pays your money, and you takes your choice!-)
How do I create a view off a property value table in SQL
[ "", "sql", "sql-server", "" ]
I'm on a Linux system where I am not allowed to use the 'ping' application (ping: icmp open socket: Operation not permitted). However, the script that I am writing (PHP, but I can use an exec() call to any script/program if needed) needs to determine if a host is 'alive'. How can I go about this without using 'ping'?
If ping can't do it, you can't do it in a different language. Here is an analogy that may help you understand why. Let's say there is a file on the file system and you want to its contents. You run `cat filename` and it says `cat: filename: Permission denied`. Do you think Perl (or any other language) will fair better than C did here? Let's try: ``` #!/usr/bin/perl use strict; use warnings; die "usage: $0 filename" unless @ARGV == 1; my $filename = shift; open my $fh, "<", $filename or die "could not open $filename: $!\n"; print while <$fh>; ``` When run against the file it says `could not open filename: Permission denied`. No matter what language you try to use, you are going to get `Operation not permitted`. That said, there are other methods of determining if a machine is alive. If there is a server that is known to always be running on the machine, you could try to connect to it. Note that you don't need to finish the connection (e.g. log in), just the fact that you can successfully initiate the connection is enough to know that box is up.
To do a ping (ICMP) you need root access. The only way you have is to do a **TCP or UDP ping**. If you want an example check the code of [Cacti](http://www.cacti.net/) or you can use hping to do it for you
Ping from Dynamic Language without using 'ping'
[ "", "php", "linux", "unix", "command-line-interface", "packet", "" ]
I'd like to empty read buffer of the socket so I wrote follow code... ``` byte[] tempBuffer = new byte[1024]; int readCount = 0; while ((readCount = tcpSocket.GetStream().Read(tempBuffer, 0, tempBuffer.Length)) != 0) { // do with tempBuffer } ``` But Read() method is blocked so I added **tcpSocket.ReceiveTimeout = 1;**. And it works just like before. As I know, this is usually used in C++. How can I solve this problem?
You can use the [DataAvailable](http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.dataavailable(VS.71).aspx) property to see if there is anything to be read before making a call into the Read method.
Use the [`NetworkStream.Read()`](http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.read.aspx) function directly, instead of using `GetStream()`: > If no data is available for reading, > the Read method returns 0. **The Read > operation reads as much data as is > available, up to the number of bytes > specified by the size parameter.** If > the remote host shuts down the > connection, and all available data has > been received, the Read method > completes immediately and return zero > bytes. NoteNote:
How to Call NetworkStream.Read() Without Blocking?
[ "", "c#", "sockets", "networkstream", "" ]
I have a list of lists like ``` [ [1, 2, 3], [4, 5, 6], [7], [8, 9] ] ``` How can I flatten it to get `[1, 2, 3, 4, 5, 6, 7, 8, 9]`? --- If your list of lists comes from a nested list comprehension, the problem can be solved more simply/directly by fixing the comprehension; please see [How can I get a flat result from a list comprehension instead of a nested list?](https://stackoverflow.com/questions/1077015). The most popular solutions here generally only flatten one "level" of the nested list. See [Flatten an irregular (arbitrarily nested) list of lists](https://stackoverflow.com/questions/2158395) for solutions that completely flatten a deeply nested structure (recursively, in general).
A list of lists named `xss` can be flattened using a nested [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions): ``` flat_list = [ x for xs in xss for x in xs ] ``` The above is equivalent to: ``` flat_list = [] for xs in xss: for x in xs: flat_list.append(x) ``` Here is the corresponding function: ``` def flatten(xss): return [x for xs in xss for x in xs] ``` This is the fastest method. As evidence, using the [`timeit`](https://docs.python.org/3/library/timeit.html) module in the standard library, we see: ``` $ python -mtimeit -s'xss=[[1,2,3],[4,5,6],[7],[8,9]]*99' '[x for xs in xss for x in xs]' 10000 loops, best of 3: 143 usec per loop $ python -mtimeit -s'xss=[[1,2,3],[4,5,6],[7],[8,9]]*99' 'sum(xss, [])' 1000 loops, best of 3: 969 usec per loop $ python -mtimeit -s'xss=[[1,2,3],[4,5,6],[7],[8,9]]*99' 'reduce(lambda xs, ys: xs + ys, xss)' 1000 loops, best of 3: 1.1 msec per loop ``` Explanation: the methods based on `+` (including the implied use in `sum`) are, of necessity, `O(L**2)` when there are L sublists -- as the intermediate result list keeps getting longer, at each step a new intermediate result list object gets allocated, and all the items in the previous intermediate result must be copied over (as well as a few new ones added at the end). So, for simplicity and without actual loss of generality, say you have L sublists of M items each: the first M items are copied back and forth `L-1` times, the second M items `L-2` times, and so on; total number of copies is M times the sum of x for x from 1 to L excluded, i.e., `M * (L**2)/2`. The list comprehension just generates one list, once, and copies each item over (from its original place of residence to the result list) also exactly once.
You can use [`itertools.chain()`](http://docs.python.org/library/itertools.html#itertools.chain): ``` >>> import itertools >>> list2d = [[1,2,3], [4,5,6], [7], [8,9]] >>> merged = list(itertools.chain(*list2d)) ``` Or you can use [`itertools.chain.from_iterable()`](http://docs.python.org/library/itertools.html#itertools.chain.from_iterable) which doesn't require unpacking the list with the `*` operator: ``` >>> import itertools >>> list2d = [[1,2,3], [4,5,6], [7], [8,9]] >>> merged = list(itertools.chain.from_iterable(list2d)) ``` This approach is arguably more readable than `[item for sublist in l for item in sublist]` and appears to be faster too: ``` $ python3 -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99;import itertools' 'list(itertools.chain.from_iterable(l))' 20000 loops, best of 5: 10.8 usec per loop $ python3 -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]' 10000 loops, best of 5: 21.7 usec per loop $ python3 -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])' 1000 loops, best of 5: 258 usec per loop $ python3 -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99;from functools import reduce' 'reduce(lambda x,y: x+y,l)' 1000 loops, best of 5: 292 usec per loop $ python3 --version Python 3.7.5rc1 ```
How do I make a flat list out of a list of lists?
[ "", "python", "list", "multidimensional-array", "flatten", "" ]
There is very simple task I want to do, that somehow makes the program crash. I have a list of number contained within, all unique. Past a certain number, I want to invert the order. Example : 5, 16, 11, **3, 8, 4** -> 5, 16, 11, **4, 8, 3** when using 3 as the pivot point. Below is one of the many methods I tried. ``` private List<int> ShiftPath(List<int> oldPath, int shift) { List <int> newPath = new List<int>(); int counter = 0; // Start reordering // Forwards while (oldPath[counter] != shift) { newPath.Add(oldPath[counter]); counter++; } // Backwards counter = oldPath.Count - 1; while (oldPath[counter] != shift) { newPath.Add(oldPath[counter]); counter--; } // New endpoint newPath.Add(shift); // Update return newPath; } ``` Now this works. It may not be the optimal solution, but it works. I've been using this methods for quite a while, but now I've reached a point where the number of items in the list becomes extremely big (above 6,000). Eventually, I get an StackOverFlowException when trying to add something to newPath. I'm 100% sure there is no infinite loop like VS claims. I've tried other methods such as getting the range of items directly, for and foreach loops instead of while, all crash eventually. It seems that the amount of data is just too big. And it's just going to get bigger (upwards to 20,000). Proof (?) : even this will make the program throw an exception : List <int> newPath = new List<int>(oldPath); Any idea on what is causing this/how to fix it? -From a beginner.
The stack overflow must not be in the code you're showing us, as there is no recursion there. Look for where your code does recursion. Better yet, what's the stack trace you get when you get your StackOverflowException? That will tell you where in your recursion that your code is going into an infinite recursive loop. A plain old infinite loop will not cause StackOverflowException. For that to occur, you need to have recursion that doesn't end, until your stack is exhausted.
A `StackOverflowException` doesn't occur because you have too many items in a `List` (that would be `OutOfMemoryException`), it happens when you make too many method calls, usually because of recursion. As a side note, 6,000 `int`s in a `List` is nothing. I just ran some test code and it adds up to 67 million integers to the list before I get an `OutOfMemoryException`.
StackOverflowException with large lists
[ "", "c#", "list", "" ]
I was wondering if it is possible to change the return type of a function based on the type of variable it is being assigned to. Here's a quick example of what I mean. I want to create a function that parses a variable of int, bool, or float from a string. For example... ``` Int value = parse("37"); Float value = parse("3.14"); Bool value = parse("true"); ``` I understand if I make this function a template, that the variable type must be determined from the argument list which is always going to be a string. Is there any other way of doing this with c++?
This can be done with a conversion function ``` struct proxy { string str; proxy(string const &str):str(str) { } template<typename T> operator T() { return boost::lexical_cast<T>(str); } }; proxy parse(string const &str) { return proxy(str); } ``` Now you just need to do ``` float a = parse("3.1"); ``` And it should work well. Incidentally, you may just use the class directly. I recommend renaming it to `conversion_proxy` to point to the fact that it's just a proxy to a happening conversion but that it itself doesn't do conversion ``` struct conversion_proxy { string str; conversion_proxy(string const &str):str(str) { } template<typename T> operator T() { return boost::lexical_cast<T>(str); } }; float a = conversion_proxy("3.1"); ```
I can't tell from your question if you know this or not, but you can indeed do this with a template. The only catch is that you will have to specify the type that you are converting from in each invocation instead of relying on inference (since as you said the argument type will always be the same). ``` template<typename T> T parse(const string& str) { /* do stuff for other types */ } template<> int parse<int>(const string& str) { /* do stuff for ints */ } template<> double parse<double>(const string& str) { /* do stuff for doubles */ } template<> bool parse<bool>(const string& str) { /* do stuff for bools */ } // etc. ``` And then invoke as ``` int value = parse<int>("37"); double value = parse<double>("3.14"); bool value = parse<bool>("true"); ``` If you already knew this just ignore this answer, but it's not clear from your question that you are aware that this is possible. Of course, if what you're doing isn't really generic (and so you have to specialize for each type you want to parse) then writing a template isn't the right thing to do anyway. By the way, you can do it pretty generically with a single function like this (assuming parse is what you really want to do): ``` #include <sstream> template<typename T> T parse(const string& str) { T t; std::istringstream sstr(str); sstr >> t; return t; } ``` This will work for any default-constructable, stream-extractable type, which includes all built-ins.
Changing return type of a function without template specialization. C++
[ "", "c++", "templates", "return", "" ]
I have an HTML file (encoded in utf-8). I open it with `codecs.open()`. The file architecture is: ``` <html> // header <body> // some text <table> // some rows with cells here // some cells contains tables </table> // maybe some text here <table> // a form and other stuff </table> // probably some more text </body></html> ``` I need to retrieve only first table (discard the one with form). Omit all input before first `<table>` and after corresponding `</table>`. Some cells contains also paragraphs, bolds and scripts. There is no more than one nested table per row of main table. How can I extract it to get a list of rows, where each elements holds plain (unicode string) cell's data and a list of rows for each nested table? There's no more than 1 level of nesting. I tried HTMLParse, PyParse and re module, but can't get this working. I'm quite new to Python.
Try [beautiful soup](http://www.crummy.com/software/BeautifulSoup/) In principle you need to use a real parser (which Beaut. Soup is), regex cannot deal with nested elements, for computer sciencey reasons (finite state machines can't parse context-free grammars, IIRC)
You may like [lxml](http://codespeak.net/lxml/). I'm not sure I really understood what you want to do with that structure, but maybe this example will help... ``` import lxml.html def process_row(row): for cell in row.xpath('./td'): inner_tables = cell.xpath('./table') if len(inner_tables) < 1: yield cell.text_content() else: yield [process_table(t) for t in inner_tables] def process_table(table): return [process_row(row) for row in table.xpath('./tr')] html = lxml.html.parse('test.html') first_table = html.xpath('//body/table[1]')[0] data = process_table(first_table)) ```
How to extract nested tables from HTML?
[ "", "python", "html", "html-table", "extract", "" ]
Let me first apologize if this question could sound perhaps sort of amateurish for the seasoned programmers among you, the thing is I've been having many arguments about this at work so I really want to get this straight and that's basically why I'm relying on the stackoverflow community to get this settled once and for all :) So, on the one hand according to MSDN, we have: > **TextWriter Class** > > Represents a writer that can write a > sequential series of characters. This > class is abstract. > > **FileStream Class** > > Exposes a Stream around a file, > supporting both synchronous and > asynchronous read and write > operations. > > **StreamWriter Class** > > Implements a TextWriter for writing > characters to a stream in a particular > encoding. On the other hand it's evident they all belong to System.IO but given that MSDN examples kind of mix some of them, I'm still not reaching the much desired a-ha moment. Any comment would be more than appreciated, thanks much in advance!
Streams handle *bytes*, Writers handle *characters*. Bytes != characters. A character may take more than one byte to represent. The mapping from characters to bytes is called an *encoding*. A `FileStream` refers to the bytes being written to a file, similar to how a `MemoryStream` refers to the bytes written to an in-memory buffer. In order to write characters to a stream, you'd need to convert them to a string of bytes. That's where a `StreamWriter` comes in to play. It takes a sequence of characters and an encoding, and turns it into a sequence of bytes. A `TextWriter` is an interface (well, abstract base class) that all of the Writers must adhere to. It has all operations based on characters. The equivalent for bytes is the `Stream` abstract base class. Things also go in the opposite direction. There is a `TextReader` abstract base class, describing how to read characters from somewhere, and a `StreamReader`, which allows you to read characters from a byte-oriented stream supplying an encoding - but this time used in reverse, to aggregate any multi-byte sequences into single characters where appropriate. A `Stream` can be used for both reading and writing, since bytes are the lowest-level items used in I/O operations.
I've always found the best thing to do is just look at what methods they provide and how you can build them. This is almost always the main, if not only, thing I care about when using an API. How do I build it and what can it do? You can't instantiate a TextWriter. It's abstract. That tells me the only real purpose it serves is, well, abstraction. If you write a function that takes any kind of writer as an argument, there's a good chance you should just take TextWriter to be more versatile. A StreamWriter you can instantiate, and it does just what it says, it writes to streams. That means it will need a stream to get any real writing done. Once you have that stream though, you can do all sorts of neat things like writing a whole line at once instead of having to deal with individual characters (or rather bytes) like you would directly on the stream. So basically, you get a stream so you can feed it to a StreamWriter (or Reader). If you're writing text, you probably don't want to work directly with a stream, no more than you want to work with a character array instead of a string. FileStreams can conveniently be instantiated directly from the File and FileInfo classes, and in my usage, this is how they're usually instantiated. Get a file (I like to use FileInfo) and call OpenWrite(). Pass it along to a StreamWriter (which is just a type of TextWriter) and you're on your way. To generalize: When you want to figure out a class, try looking at how you instantiate it and what it can do. This usually clears up a lot.
IO 101: Which are the main differences between TextWriter, FileStream and StreamWriter?
[ "", "c#", ".net-3.5", "io", ".net", "" ]
There are no examples of use anywhere, or even an explanation on how to use it.
Here's the source, make with it what you will. (Doesn't appear overly useful IMO). ``` 566 /** 567 * Adds a dynamic javascript to the response object. 568 * 569 * The first argument is an internal URI. 570 * The helper automatically adds the sf_format to the internal URI, so you don't have to. 571 * 572 * @see sfResponse->addJavascript() 573 */ 574 function use_dynamic_javascript($js, $position = '', $options = array()) 575 { 576 $options['raw_name'] = true; 577 578 return use_javascript(_dynamic_path($js, 'js'), $position, $options); 579 } ```
I know the question has its age, but I consider the problem is still there for many of us :) After banging my head against the wall several hours, I want to share some info with you :P How to use use\_dynamic\_javascript() helper in symfony [here](http://goodies.lemonsoftware.eu/doku.php?id=sym:dynamicjs).
How to use symfony's use_dynamic_javascript() helper?
[ "", "php", "frameworks", "symfony1", "" ]
Can GWT be used just for simple AJAX? I dont want the widgets, I just want to avoid coding javascipt. What I need is simple ajax, like clicking on a link and updating the contents of a div with data retrieved from the server, or things like that. Can GWT be used for that purpouse? if so, where can I get some help? All I find on the web is based around the widgets.
Yes indeed that is perfectly possible. The Widgets are only part of the story. You can use the RPC or RequestBuilder to handle server calls using RPC or JSON or XML. You can also use the DOM class and Element classes to manipulate the div blocks directly. You gain the productivity tools of Java (Eclipse) and you also get the benefit of optimized Javascript code that should work on all supported browsers. As for documentation you can find all you need in the javadocs: <http://google-web-toolkit.googlecode.com/svn/javadoc/1.6/index.html?overview-summary.html> The relevant packages are: ``` com.google.gwt.dom.client (Document is what you need for DOM manipulations) com.google.gwt.http.client if you want to send GETs/POSTs. com.google.gwt.user.client which contains the Window class com.google.gwt.json.client for sending/receiving json payloads to/from the server com.google.gwt.xml.client in case you want to send/receive XML data and parse it on the client side. ``` David
if you like jquery (but dont want to use javascript), there is a library for GWT that replicates that functionality called GWT Query, <http://code.google.com/p/gwtquery/> . Using that, you can update dom relatively easily, and yet still have the type safe checking of java, as well as the nice features of code obfuscation+minification for free.
Simple AJAX with GWT... I don't need widgets
[ "", "javascript", "ajax", "gwt", "" ]
I want to minimise my application, take a screenshot of the current desktop and return my application back to its original state. This has been working fine under windows XP, however under testing on different Vista machines the minimise time of 200 milliseconds is no longer valid. Is there a way to ask the operating system when it has finished these fancy effects or lookup how long it has been given to perform the operation?
The closest I can find is SPI\_GETUIEFFECTS, which tells you if such effects are enabled at all. If enabled, you could of course use SPI\_SETUIEFFECTS to turn them off. But that's a rather shotgun method - how would you restore them? It's probably better to temporarily turn off the ones that bother you most.
While I don't know of a way to do what you ask, I have a suggestion: instead of minimizing your application's window, why not hide it (with ShowWindow(SW\_HIDE))? That will not be subject to the animation effects, so should be pretty much instantaneous.
How do I detect desktop transition effects?
[ "", "c++", "desktop", "transition", "" ]
What is the best way to pick a random brush from the System.Drawing.Brushes collection in C#?
If you just want a solid brush with a random color, you can try this: ``` Random r = new Random(); int red = r.Next(0, byte.MaxValue + 1); int green = r.Next(0, byte.MaxValue + 1); int blue = r.Next(0, byte.MaxValue + 1); System.Drawing.Brush brush = new System.Drawing.SolidBrush(Color.FromArgb(red, green, blue)); ```
For WPF, use reflection: ``` var r = new Random(); var properties = typeof(Brushes).GetProperties(); var count = properties.Count(); var colour = properties .Select(x => new { Property = x, Index = r.Next(count) }) .OrderBy(x => x.Index) .First(); return (SolidColorBrush)colour.Property.GetValue(colour, null); ```
What is the best way to pick a random brush from the Brushes collection in C#?
[ "", "c#", "collections", "select", "brush", "" ]
In java, what does the private static method `registerNatives()` of the Object class do?
The other answers are technically correct, but not very useful for someone with no JNI experience. :-) Normally, in order for the JVM to find your native functions, they have to be named a certain way. e.g., for `java.lang.Object.registerNatives`, the corresponding C function is named `Java_java_lang_Object_registerNatives`. By using `registerNatives` (or rather, the JNI function `RegisterNatives`), you can name your C functions whatever you want. Here's the associated C code (from OpenJDK 6): ``` static JNINativeMethod methods[] = { {"hashCode", "()I", (void *)&JVM_IHashCode}, {"wait", "(J)V", (void *)&JVM_MonitorWait}, {"notify", "()V", (void *)&JVM_MonitorNotify}, {"notifyAll", "()V", (void *)&JVM_MonitorNotifyAll}, {"clone", "()Ljava/lang/Object;", (void *)&JVM_Clone}, }; JNIEXPORT void JNICALL Java_java_lang_Object_registerNatives(JNIEnv *env, jclass cls) { (*env)->RegisterNatives(env, cls, methods, sizeof(methods)/sizeof(methods[0])); } ``` (Notice that `Object.getClass` is not in the list; it will still be called by the "standard" name of `Java_java_lang_Object_getClass`.) For the functions listed, the associated C functions are as listed in that table, which is handier than writing a bunch of forwarding functions. Registering native functions is also useful if you are embedding Java in your C program and want to link to functions within the application itself (as opposed to within a shared library), or the functions being used aren't otherwise "exported", since these would not normally be found by the standard method lookup mechanism. Registering native functions can also be used to "rebind" a native method to another C function (useful if your program supports dynamically loading and unloading modules, for example). I encourage everybody to read the [JNI book](http://www.informit.com/store/java-native-interface-programmers-guide-and-specification-9780201325775), which talks about this and much more. :-)
What might be slightly confusing is that the code shown for `java.lang.Object.registerNatives` in a previous answer is just an *example* of how to register native functions. This is the code that (in the implementation of OpenJDK) registers native functions for class Object. To register native functions for your own class, you must call the JNI function `RegisterNatives` from the native code in your own library. This might sound a bit circular, but there are a couple ways to break the loop. 1. Follow the example of this implementation of class Object: a. In your Java class, declare a native method (preferably static) named `registerNatives` (or any other name. it doesn't matter). b. In your native code, define a function named `Java_<your fully qualified class name>_registerNatives`, which contains a call to the JNI function `RegisterNatives`. c. Make sure that in your Java code, your Java `registerNatives` method is called prior to any calls to other native methods. OR 2. Use `JNI_OnLoad` a. In your native library define a function `jint JNI_OnLoad(JavaVM *vm, void *reserved)`. In the body of this function, call the JNI function `RegisterNatives`. b. The Java VM will automatically look for and call `JNI_OnLoad` when your native library is loaded by `System.loadLibrary`, which you should already be calling, probably in a static initializer for your class. (You get the required `env` pointer by calling the `GetEnv` function in the table that the `vm` pointer points to.)
What does the registerNatives() method do?
[ "", "java", "c", "object", "methods", "java-native-interface", "" ]
I'm trying to code a user defined function under SQL Server 2005 that will increase integer part of alphanumeric value by one. For example, `uf_AlphanumericIncrease ('A000299')` should return 'A000300'. Here's what I've done so far; ``` ALTER FUNCTION uf_AlphaNumericIncrement ( @ID varchar(10) ) RETURNS VARCHAR(10) AS BEGIN DECLARE @RES varchar(10); IF SUBSTRING(@ID,LEN(@ID),1)='9' SET @RES=SUBSTRING(@ID,1,LEN(@ID)-2)+CAST (CAST(SUBSTRING(@ID,LEN(@ID)-1,1) AS smallint)+1 AS VARCHAR(10))+'0'; ELSE SET @RES=SUBSTRING(@ID,1,LEN(@ID)-1)+CAST (CAST(SUBSTRING(@ID,LEN(@ID),1) AS smallint)+1 AS VARCHAR(10)); RETURN @RES; END ``` But as you can see it only works for last digit. I need to get it under loop so it can work for A002999 and so on. Any ideas? Edit: Given value might have alpha prefix longer than one character, or none at all.
Now works with any length of prefix and number part (well upto 20 each) ``` DECLARE @prefix varchar(20), @numberstr varchar(20), @number int, @Val varchar(40) SELECT @Val = 'ABCD000006' --SELECT @Val = 'A03' SELECT @prefix = LEFT(@Val, PATINDEX ('%[0-9]%', @Val) -1) SELECT @numberstr = SUBSTRING(@Val, PATINDEX ('%[0-9]%', @Val), 8000) SELECT @number = CAST(@numberstr AS int) + 1 SELECT @prefix + RIGHT(REPLACE(SPACE(LEN(@numberstr)), ' ', '0') + CAST(@number AS varchar(20)), LEN(@numberstr)) ```
Assuming that the alpha part of your alphanumeric is always only the first character, this should work. EDIT: OK, if the alpha part varies in length this gets ugly pretty quickly for a UDF. This is just a quick-and-dirty solution, so it can probably be optimized a bit, but the logic should be sound. EDIT AGAIN: patindex() ftw - I learned something new today ;-) ``` ALTER FUNCTION uf_AlphaNumericIncrement ( @ID varchar(10) ) RETURNS VARCHAR(10) AS BEGIN DECLARE @RES varchar(10); DECLARE @num int; DECLARE @prefix varchar(10); set @prefix = left(@id, patindex('%[0-9]%', @id) -1) set @num = cast(right(@id, len(@id) - len(@prefix)) as int) + 1 set @res = @prefix + replicate('0', len(@id) - len(@prefix) - len(@num)) + cast(@num as varchar(10)) RETURN @RES; END ```
Increasing Alphanumeric value in user defined function
[ "", "sql", "sql-server", "t-sql", "identity", "alphanumeric", "" ]
I am learning about pointers and one concept is troubling me. I understand that if you have a pointer (e.g.'pointer1') of type INT that points to an array then you can fill that array with INTS. If you want to address a member of the array you can use the pointer and you can do pointer1 ++; to step through the array. The program knows that it is an array of INTs so it knows to step through in INT size steps. But what if the array is of strings whcih can vary in length. How does it know what to do when you try to increment with ++ as each element is a different length? Similarly, when you create a vector of strings and use the reserve keyword how does it know how much to reserve if strings can be different lengths? This is probably really obvious but I can't work it out and it doesn't fit in with my current (probably wrong) thinking on pointers. Thanks
Quite simple. An array of strings is different from a vector of strings. An array of strings (C-style pointers) is an array of pointers to an array of characters, "char\*\*". So each element in the array-of-strings is of size "Pointer-to-char-array", so it can step through the elements in the stringarray without a problem. The pointers in the array can point at differently size chunks of memory. With a vector of strings it is an array of string-objects (C++ style). Each string-object has the same *object* size, but contains, somewhere, a pointer to a piece of memory where the contents of the string are actually stored. So in this case, the elements in the vector are also identical in size, although different from "just a pointer-to-char-array", allowing simple element-address computation.
This is because a string (at least in C/C++) is not quite the same sort of thing as an integer. If we're talking C-style strings, then an array of them like ``` char* test[3] = { "foo", "bar", "baz" }; ``` what is actually happening under the hood is that "test" is an array of pointers, each of which point to the actual data where the characters are. Let's say, at random, that the "test" array starts at memory address 0x10000, and that pointers are four bytes long, then we might have ``` test[0] (memory location 0x10000) contains 0x10020 test[1] (memory location 0x10004) contains 0x10074 test[2] (memory location 0x10008) contains 0x10320 ``` Then we might look at the memory locations around 0x10020, we would find the actual character data: ``` test[0][0] (memory location 0x10020) contains 'f' test[0][1] (memory location 0x10021) contains 'o' test[0][2] (memory location 0x10022) contains 'o' test[0][3] (memory location 0x10023) contains '\0' ``` And around memory location 0x10074 ``` test[1][0] (memory location 0x10074) contains 'b' test[1][1] (memory location 0x10075) contains 'a' test[1][2] (memory location 0x10076) contains 'r' test[1][3] (memory location 0x10077) contains '\0' ``` With C++ std::string objects much the same thing is going on: the actual C++ string object doesn't "contain" the characters because, as you say, the strings are of variable length. What it actually contains is a pointer to the characters. (At least, it does in a simple implementation of std::string - in reality it has a more complicated structure to provide better memory use and performance).
Pointer arithmetic on string type arrays, how does C++ handle this?
[ "", "c++", "pointers", "" ]
I'm currently using Apache Tomcat 5.5.16 to serve a Lucene-based search API. Lately I've been having some NullPointerExceptions inside my servlet class. The class is called `com.my_company.search.servlet.SearchServlet`. With certain types of input I can routinely create a NullPointerException, but I'm having trouble figuring out where exactly it is. The StackTrace indicates that the bug is occuring here: `com.my_company.search.servlet.SearchServlet.doGet(Unknown Source)` The source and .class files for this class is all in: `$TOMCAT_HOME/webapps/my_servlet/WEB-INF/classes/com/my_company/search/servlet/` My question is, how can I get Tomcat to provide me with more descriptive error locations?
Tomcat cannot provide you more detailed information unless the classes in question were compiled with debugging information. Without this debugging information, the JVM cannot determine what line of code the error occurred on. **Edit:** You can ask the compiler to include this information by specifying the `-g` [option](http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javac.html#options) when running `javac` on the command line. You can also specify this option using the `debug` parameter of the [Javac Ant task](http://ant.apache.org/manual/Tasks/javac.html).
you have to add debugging information to your classes. compile them with the option `-g`: ``` javac -g YourServlet.java ```
Why does my servlet stacktrace show "Unknown Source" for my classes?
[ "", "java", "exception", "servlets", "stack-trace", "nullpointerexception", "" ]
I am trying to reuse an existing code ... but with no success . Here is the code snippet: ``` using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Reflection; namespace GenApp.Utils.Reflection { class FieldTraverser { public static string SearchFieldValue(object obj, int MaxLevel, string strFieldMeta , ref object fieldValue) { if (obj == null) return null; else { StringBuilder sb = new StringBuilder(); bool flagShouldStop = false; FieldTraverser.PrivDump(sb, obj, "[ObjectToDump]", 0, MaxLevel , ref flagShouldStop , ref fieldValue); return sb.ToString(); } } //eof method public static object GetFieldValue(object obj, string fieldName, ref bool flagShouldStop, ref object objFieldValue) { FieldInfo fi; Type t; t = obj.GetType(); fi = t.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (fi == null) return null; else { if (fi.Name.Equals(fieldName)) { objFieldValue = fi.GetValue(obj); flagShouldStop = true; } return fi.GetValue(obj); } //eof else } //eof method protected static void DumpType(string InitialStr, StringBuilder sb, object obj, int level, System.Type t, int maxlevel , ref bool flagShouldStop , ref object objFieldValue ) { FieldInfo[] fi; fi = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (t == typeof(System.Delegate)) return; foreach (FieldInfo f in fi) { PrivDump(sb, f.GetValue(obj), f.Name, level + 1, maxlevel , ref flagShouldStop , ref objFieldValue); if (flagShouldStop == true) return; } object[] arl; int i; if (obj is System.Array) { try { arl = (object[])obj; for (i = 0; i < arl.GetLength(0); i++) { PrivDump(sb, arl[i], "[" + i + "]", level + 1, maxlevel, ref flagShouldStop, ref objFieldValue); if (flagShouldStop == true) return; } } catch (Exception) { } } } protected static void PrivDump(StringBuilder sb, object obj, string objName, int level, int MaxLevel, ref bool flagShouldStop, ref object objFieldValue) { if (obj == null) return; if (MaxLevel >= 0 && level >= MaxLevel) return; string padstr; padstr = ""; for (int i = 0; i < level; i++) if (i < level - 1) padstr += "|"; else padstr += "+"; string str; string[] strarr; Type t; t = obj.GetType(); strarr = new String[7]; strarr[0] = padstr; strarr[1] = objName; strarr[2] = " AS "; strarr[3] = t.FullName; strarr[4] = " = "; strarr[5] = obj.ToString(); strarr[6] = "\r\n"; sb.Append(String.Concat(strarr)); if (obj.GetType().BaseType == typeof(ValueType)) return; FieldTraverser.DumpType(padstr, sb, obj, level, t, MaxLevel, ref flagShouldStop , ref objFieldValue); Type bt; bt = t.BaseType; if (bt != null) { while (!(bt == typeof(Object))) { str = bt.FullName; sb.Append(padstr + "(" + str + ")\r\n"); FieldTraverser.DumpType(padstr, sb, obj, level, bt, MaxLevel , ref flagShouldStop , ref objFieldValue); bt = bt.BaseType; if (bt != null) continue; break; } while (bt != typeof(Object)) ; } } //eof method }//eof class } //eof namespace ```
Note that it is very rare you need to mess with `FieldInfo`; fields are rarely public, and you should generally be using the `PropertyInfo`s (`GetProperties()`). However, `GetFields` will work. For public fields, just `GetFields()`; for private fields too you need `BindingFlags`: ``` class Foo { public string abc; } class Bar : Foo { private int def; } static class Program { static void Main() { object obj = new Bar(); FieldInfo[] fields = obj.GetType().GetFields( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); foreach(FieldInfo field in fields) { Console.WriteLine(field.Name + " = " + field.GetValue(obj)); } } } ```
Use [System.Type.GetFields()](http://msdn.microsoft.com/en-us/library/6ztex2dc.aspx)?
How to get a System.Collections.Generic.List<FieldInfo> which holds all FieldInfo's of an object of a Type T up to the Object in the class hierarchy?
[ "", "c#", "reflection", "field", "" ]
``` class object { public: void check() { std::cout<<"I am doing ok..."<<std::endl; } }; int main() { object *p = new object; p->check(); delete p; p->check(); delete p; p->check(); } ``` **EDIT**: Gurus, i am confused by many of the statements "it may crash or may not".. why isnt there a standard to say, this how we deal with a block of memory that is deleted using 'delete operator'..? Any inputs ?
Because what it actually looks like after the compiler has had its way, is something like this: ``` object::check( object* this ) { // do stuff without using this } int main() { object *p = new object; object::check( p ); delete p; object::check( p ); delete p; object::check( p ); } ``` Since you're not touching "this", you don't actually access any bad memory. Although, deleting p twice should be able to cause a crash: <http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.2>
Because the function is not doing anything with the object's member data or the `this` pointer. It's like calling a function ``` void check(object *self) { std::cout<<"I am doing ok..."<<std::endl; } ``` with an invalid pointer as the `self` argument. There is a double delete though, which can crash in some environments.
Why the below piece of code is not crashing , though i have deleted the object?
[ "", "c++", "" ]
I have learned that builds should be very straight forward and requires less human intervention. In my situation, I have 3 environments, DEV (development version), SIT (STG integration testing) and UAT (user acceptance testing). All these environments have different database connection details and other settings (such as logging). Currently when application needs to be deployed to SIT environment, what I need to do is to build the application. Install it on the target environment and modify the configuration file by hand. This is problematic as I may miss some entries. Things will get worse when configuration file is huge. **Questions** 1 - Is there anyway to specify the environment name when making a build from VS. So that the configuration file for that environment will be used. 2 - What are the other methods which will help to reduce human intervention in builds? 3 - Assume my applications name is "Foo". I have a package project in the solution which will create installable package. Is there anyway to specify the product title depending upon the environment? I mean if SIT is selected, product name when installing will be "Foo-SIT". I guess this will avoid confusion of what environment version one is installing. I would be happy to hear any better alternatives if there are any.
One way to handle this is to create 3 projects and put the environment in the name of the new projects. Then use a post-build event to copy the correct files based on the project name. Inside the post build event you can tell the project name based on the $(ProjectName) macro. So you can do things like ``` IF "$(ProjectName)"="devproject" ( copy ... copy ... ) ``` It's best to make these projects defer most of the real work (compilation) to a single project so that you don't have to keep settings up to date across multiple projects.
2 -- You're absolutely right -- you should attempt to automate your build and deployment process as much as possible. Your best bet is to set up an automated build / deploy script using something like [NAnt](http://nant.sourceforge.net/). Your script can have targets for each of your environments, e.g. ``` <project name="MyApp" xmlns="http://nant.sf.net/release/0.85/nant.xsd"> <target name="DEV"> <!-- execute any tasks needed to build the app, such as msbuild(1) --> <!-- execute any tasks needed to build the tweak the config files, such as xmlpeek / xmlpoke(2) --> <!-- execute any tasks needed to copy the now-built and configured project output the tweak the destination server, such as copy(3)--> </target> <target name="SIT">...</target> <target name="UAT">...</target> </project> ``` If you're not familiar with NAnt, it should take you less than a day to get up and running and writing scripts. The payoff is immediate and long-lasting, as you'll never have to VNC onto a server and tweak configuration files ever again. * (1) [msbuild](http://nantcontrib.sourceforge.net/release/0.85/help/tasks/msbuild.html) * (2) [xmlpeek](http://nant.sourceforge.net/release/latest/help/tasks/xmlpeek.html) / [xmlpoke](http://nant.sourceforge.net/release/latest/help/tasks/xmlpoke.html) * (3) [copy](http://nant.sourceforge.net/release/latest/help/tasks/copy.html)
Managing multiple configuration files in Visual Studio for a C# project
[ "", "c#", ".net", "visual-studio", "build-process", "" ]
**How do I toggle HTML links from being active / deactive using JavaScript?** Within my HTML, I have 2 hyper links that call a JavaScript function to sort a table: ``` <a href="javascript:sort('asc');">ASC</a> | <a href="javascript:sort('desc');">DESC</a> ``` What I would like to do is when someone clicks the "ASC" link, it then deactives the "ASC" hyperlink (no longer a link) so that only now the "DESC" link is active. Then, if the person presses the "DESC" link, it then disables the "DESC" link and re-enables the "ASC" link. Essentially, I want to toggle between which link is active, either: "ASC" or "DESC" I assume you can do this with JavaScript but am not sure how? Any ideas?
Doesn't strictly "remove" the A tag, but removes the "linkness" (by removing the href) from the tag. Edit: slightly better version (now tested): ``` <script type="text/javascript" > function mySort( sortorder) { // enable the other link otherOrder = (sortorder == 'asc') ? 'desc' : 'asc'; document.getElementById(otherOrder).setAttribute("href", "#"); document.getElementById(otherOrder).onclick = function() {mySort(this.id)}; //disable this link document.getElementById(sortorder).removeAttribute("href"); document.getElementById(sortorder).onclick = ""; //perform the sort doSort(sortorder); } </script> <a id="asc" href="#" onclick="mySort(this.id)" >ASC</a> | <a id="desc" href="#" onclick="mySort(this.id)" >DESC</a> ```
Don't make them links, use another element, for example a `span`. ``` <span onclick="sort('asc');">ASC</span> | <span onclick="sort('desc');">DESC</span> ``` Then use JavaScript to set a class that defines a visual style on the active item, you can toggle this on each `span`. Your sort function can also determine whether or not the supplied direction is valid and simply do nothing.
JavaScript: toggle links active/deactive
[ "", "javascript", "hyperlink", "toggle", "" ]
Is there difference between caching PHP objects on disk rather than not? If cached, objects would only be created once for ALL the site visitors, and if not, they will be created once for every visitor. Is there a performance difference for this or would I be wasting time doing this? Basically, when it comes down to it, the main question is: Multiple objects in memory, PER user (each user has his own set of instantiated objects) VS Single objects in cached in file for all users (all users use the same objects, for example, same error handler class, same template handler class, and same database handle class)
> Is there difference between caching PHP objects on disk rather than not? As with all performance tweaking, you should measure what you're doing instead of just blindly performing some voodoo rituals that you don't fully understand. When you save an object in `$_SESSION`, PHP will capture the objects state and generate a file from it (serialization). Upon the next request, PHP will then create a new object and re-populate it with this state. This process is much more expensive than just creating the object, since PHP will have to make disk I/O and then parse the serialized data. This has to happen both on read and write. In general, PHP is designed as a shared-nothing architecture. This has its pros and its cons, but trying to somehow sidestep it, is usually not a very good idea.
To use these objects, each PHP script would have to deserialize them anyway. So it's definitely not for the sake of saving memory that you'd cache them on disk -- it won't save memory. The reason to cache these objects is when it's too expensive to create the object. For an ordinary PHP object, this is not the case. But if the object represents the result of an costly database query, or information fetched from a remote web service, for instance, it could be beneficial to cache it locally. Disk-based cache isn't necessarily a big win. If you're using PHP and concerned about performance, you must be running apps in an opcode-caching environment like APC or Zend Platform. These tools also provide caching you can use to save PHP objects in your application. Memcached is also a popular solution for a fast memory cache for application data. Also keep in mind not all PHP objects can be serialized, so saving them in a cache, whether disk-based or in-memory, isn't possible for all data. Basically, if the object contains a reference to a PHP resource, you probably can't serialize it.
PHP Object Caching performance
[ "", "php", "performance", "oop", "caching", "object", "" ]
Is it possible? ``` function test() { echo "function name is test"; } ```
The accurate way is to use the `__FUNCTION__` [predefined magic constant](http://www.php.net/manual/en/language.constants.predefined.php). Example: ``` class Test { function MethodA(){ echo __FUNCTION__; } } ``` Result: `MethodA`.
You can use the [magic constants](http://www.php.net/manual/en/language.constants.predefined.php) `__METHOD__` (includes the class name) or `__FUNCTION__` (just function name) depending on if it's a method or a function... =)
How do I get the function name inside a function in PHP?
[ "", "php", "function", "" ]
I want to know the number of CPUs on the local machine using Python. The result should be `user/real` as output by `time(1)` when called with an optimally scaling userspace-only program.
If you're interested into the number of processors *available* to your current process, you have to check [cpuset](http://man7.org/linux/man-pages/man7/cpuset.7.html) first. Otherwise (or if cpuset is not in use), [`multiprocessing.cpu_count()`](http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_count) is the way to go in Python 2.6 and newer. The following method falls back to a couple of alternative methods in older versions of Python: ``` import os import re import subprocess def available_cpu_count(): """ Number of available virtual or physical CPUs on this system, i.e. user/real as output by time(1) when called with an optimally scaling userspace-only program""" # cpuset # cpuset may restrict the number of *available* processors try: m = re.search(r'(?m)^Cpus_allowed:\s*(.*)$', open('/proc/self/status').read()) if m: res = bin(int(m.group(1).replace(',', ''), 16)).count('1') if res > 0: return res except IOError: pass # Python 2.6+ try: import multiprocessing return multiprocessing.cpu_count() except (ImportError, NotImplementedError): pass # https://github.com/giampaolo/psutil try: import psutil return psutil.cpu_count() # psutil.NUM_CPUS on old versions except (ImportError, AttributeError): pass # POSIX try: res = int(os.sysconf('SC_NPROCESSORS_ONLN')) if res > 0: return res except (AttributeError, ValueError): pass # Windows try: res = int(os.environ['NUMBER_OF_PROCESSORS']) if res > 0: return res except (KeyError, ValueError): pass # jython try: from java.lang import Runtime runtime = Runtime.getRuntime() res = runtime.availableProcessors() if res > 0: return res except ImportError: pass # BSD try: sysctl = subprocess.Popen(['sysctl', '-n', 'hw.ncpu'], stdout=subprocess.PIPE) scStdout = sysctl.communicate()[0] res = int(scStdout) if res > 0: return res except (OSError, ValueError): pass # Linux try: res = open('/proc/cpuinfo').read().count('processor\t:') if res > 0: return res except IOError: pass # Solaris try: pseudoDevices = os.listdir('/devices/pseudo/') res = 0 for pd in pseudoDevices: if re.match(r'^cpuid@[0-9]+$', pd): res += 1 if res > 0: return res except OSError: pass # Other UNIXes (heuristic) try: try: dmesg = open('/var/run/dmesg.boot').read() except IOError: dmesgProcess = subprocess.Popen(['dmesg'], stdout=subprocess.PIPE) dmesg = dmesgProcess.communicate()[0] res = 0 while '\ncpu' + str(res) + ':' in dmesg: res += 1 if res > 0: return res except OSError: pass raise Exception('Can not determine number of CPUs on this system') ```
If you have python with a version >= 2.6 you can simply use ``` import multiprocessing multiprocessing.cpu_count() ``` <http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_count>
How to find out the number of CPUs using python
[ "", "python", "system-information", "" ]
I have a string, `12345.00`, and I would like it to return `12345.0`. I have looked at `trim`, but it looks like it is only trimming whitespace and `slice` which I don't see how this would work. Any suggestions?
You can use the [substring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring) function: ``` let str = "12345.00"; str = str.substring(0, str.length - 1); console.log(str); ``` This is the accepted answer, but as per the conversations below, the [slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) syntax is much clearer: ``` let str = "12345.00"; str = str.slice(0, -1); console.log(str); ```
You can use [slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice)! You just have to make sure you know how to use it. Positive #s are relative to the beginning, negative numbers are relative to the end. ``` js>"12345.00".slice(0,-1) 12345.0 ```
How do I chop/slice/trim off last character in string using Javascript?
[ "", "javascript", "slice", "trim", "" ]
I wanted to know if there is a solution using IIS6 for an application to get rid of the default.aspx text in the url. so for example if a user hits: www.website.com/default.aspx the browser only shows: www.website.com/ No matter what. It's just for SEO. I already use UrlRewriting.NET for some rewrites in my app but for I'm not that clever to create a rule for that. Any help is much appreciate. Thanks. Jose
If you have something to do URL rewriting, then all you need to do its ensure that your links point to the correct URL. If you don't fix your links, its up to the browser to decide if it wants to display the actual link it requested. If you would really like to do a dodgy job, you can use some javascript to make the address bar of the browser display whatever you like, even if its invalid.
I think ScottGu already has the topic of rewriting in ASP.NET covered: <http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx>. He covers things such as: * Rewriting using UrlRewriter.net, ISAPI Rewrite * ASP.NET Tricks, posting back (hitting the friendly version of the url) With your problem I think you need to use a combination of, never linking to 'default.aspx' ie. ONLY link to '/'. Then use Scott's Form Postback browser file to ensure postbacks always hit that same friendly version of the url. Redirecting 'default.aspx' to '/', which then gets served by 'default.aspx' sounds like a recipe for disaster to me. Just fix your links to ensure you never end up on 'default.aspx' explicitly.
Hiding default.aspx from the URL
[ "", "c#", "asp.net", "seo", "url-rewriting", "" ]
> **Possible Duplicate:** > [Need help solving Project Euler problem 200](https://stackoverflow.com/questions/778387/need-help-solving-project-euler-problem-200) Similar to [this question](https://stackoverflow.com/questions/778387/) [Project Euler Problem 200.](http://projecteuler.net/index.php?section=problems&id=200) I wrote up a brute force solution in Java that takes several hours to run, and produced the first 500+ sqube numbers, which I thought should be enough. However, none of the answers from 190 to 210 seems to be the correct answer. I'm wondering what I'm doing wrong here and how I could optimize this. Could the problem lie in `BigInteger.isProbablePrime()`? I'm not sure if Stackoverflow is the best place to ask this, but I seem to be stuck. I've included my code and the generated data. I'd really appreciate it if someone would give me some hints or pointers. **Edit:** I've run the program again simply with using the first 500,000 prime numbers; took a day to run but produced the correct answer.
I'm a Project Euler administrator. Please do not post information that can spoil the problem for others, particularly code and answers, even half-functioning code. Please edit your question accordingly. EDIT: Thank you for doing so! It's not unusual for solvers to use the web to search for information on solving a problem, and it would take away some fun if they stumbled upon such a spoiler. (Yes, I know there are sites with lots of solutions ready-made, but at least they're generally for the lowered numbered easy problems.) We have [forums](http://forum.projecteuler.net/) for discussing difficulties with problems and getting hints, which are aggressively edited for spoilers.
Aren't you supposed to think of a clever solution which doesn't take a day or even an hour to run? :D I think the problem is isProbablePrime, which doesn't guarantee that a number is a prime. It just says that a prime which was found could be a prime with a certain probability. You should use an algorithm which is certain that it has found a prime.
Help with Project Euler #200?
[ "", "java", "" ]
Is there any way to implement binary search in a ArrayList with objects? In this example the ArrayList will be sorted with the field 'id'. ``` class User{ public int id; public string name; } ArrayList<User> users = new ArrayList<User>(); sortById(users); int id = 66 User searchuser = getUserById(users,id); ``` How would the "User getUserById( ArrayList users, int userid )" look like if I it should return the user with a specified id using binary search? Is this even possible?
The [Object Ordering](http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html) article of The Java Tutorials has an example of writing your own [`Comparator`](http://java.sun.com/javase/6/docs/api/java/util/Comparator.html) in order to perform comparisons on custom types. Then, the `ArrayList` (or any other `List`), the key to find, along with `Comparator` can be passed into the [`Collections.binarySearch`](http://java.sun.com/javase/6/docs/api/java/util/Collections.html#binarySearch(java.util.List,%20T,%20java.util.Comparator)) method. Here's an example: ``` import java.util.*; class BinarySearchWithComparator { public static void main(String[] args) { // Please scroll down to see 'User' class implementation. List<User> l = new ArrayList<User>(); l.add(new User(10, "A")); l.add(new User(20, "B")); l.add(new User(30, "C")); Comparator<User> c = new Comparator<User>() { public int compare(User u1, User u2) { return u1.getId().compareTo(u2.getId()); } }; // Must pass in an object of type 'User' as the key. // The key is an 'User' with the 'id' which is been searched for. // The 'name' field is not used in the comparison for the binary search, // so it can be a dummy value -- here it is omitted with a null. // // Also note that the List must be sorted before running binarySearch, // in this case, the list is already sorted. int index = Collections.binarySearch(l, new User(20, null), c); System.out.println(index); // Output: 1 index = Collections.binarySearch(l, new User(10, null), c); System.out.println(index); // Output: 0 index = Collections.binarySearch(l, new User(42, null), c); System.out.println(index); // Output: -4 // See javadoc for meaning of return value. } } class User { private int id; private String name; public User(int id, String name) { this.id = id; this.name = name; } public Integer getId() { return Integer.valueOf(id); } } ```
You could also put the comparator in the User class: ``` public class User implements Comparable<User>, Comparator<User> { public User(int id, String name) { this.id = id; this.name = name; } @Override public int compareTo(User u) { return id - u.getID(); } @Override public int compare(User u1, User u2) { return u1.getID() - u2.getID(); } public int getID() { return id; } public String getName() { return name; } private int id; private String name; } ``` Then you would do the following to an ArrayList called users: ``` ArrayList<User> users = new ArrayList<User>(); users.add(new User(3, "Fred")); users.add(new User(42, "Joe")); users.add(new User(5, "Mary")); users.add(new User(17, "Alice")); Collections.sort(users); int index = Collections.binarySearch(users, new User(5, null)); if(index >= 0) System.out.println("The user name of id 5 is: "+users.get(index).getName()); else System.out.println("ID 5 is not in the list"); ```
Implement binary search in objects
[ "", "java", "search", "collections", "binary-search", "" ]
We are having this discussion in our team about code conventions for Java for: * `interface`: `Foo` or `IFoo` or `FooInterface`? * `abstract`: `Foo` or `AbstractFoo`? * `Enums`: `Foo` or `FooEnum`? I'm basically trying to put my personal preferences aside :) so reasons to back up one or other convention are very welcome.
In Java: `Foo`, `AbstractFoo` and `Foo` - although `AbstractFoo` could just be `Foo`. Evidence: * `java.util.List` (interface) * `java.util.AbstractList` (abstract class) * `java.util.Formatter.BigDecimalLayoutForm` (enum) For the interface part, see the [Naming Conventions](http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html) section of the Java Coding Conventions document. It doesn't talk about enums and abstract classes though.
From [my blog](http://blog.joda.org/2011/08/implementations-of-interfaces-prefixes.html): * **Foo** - The interface ultimately defines the concept, so it should have the best name. * **AbstractFoo** - An abstract implementation intended to be used as the base of a hierarchy of classes. * **BaseFoo** - An implementation intended to be used as the base of a hierarchy of classes, where the base class could be used on its own if necessary. * **DefaultFoo** - A "default" implementation that would be appropriate for the majority of typical use cases. * **SimpleFoo** - A "simple" implementation with no unexpected functionality, perhaps as an example or as a mock. A simple POJO would be a good "simple" implementation. * **{Descriptive}Foo** - Other implementations should describe what makes them unique. The blog also discusses reasons against some of the other names.
Java Interface, AbstractClass and Enum naming convention
[ "", "java", "naming-conventions", "" ]
I'm looking for a good, fully featured C++ assert macro for VisualStudio. With features like be able to ignore an assert once or always, to be able to break exactly where the macro gets called (and not inside macro code), and getting a stack trace. Before I have to hunker down and write one, I figured I'd ask if anyone knows about any available ones out there. Any suggestions? Thanks!
See [Charles Nicholson's blog](http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/) for a good discussion of an `assert` macro. His solution breaks the debugger at the faulting line of code (and not inside the failed assertion handler), and he also solves the problem of not getting warnings about unused variables when assertions are disabled without incurring any runtime costs.
Here's a link to an article I wrote for DDJ that described, among other things, a library that does much of what you're looking for. Although I don't just use macros, I also implement functions in a DLL. <http://www.ddj.com/architect/184406106> The article from a few years ago and, although I have made many additions, I still use it very liberally in my everyday code.
Fully Featured C++ Assert Dialog?
[ "", "c++", "visual-studio", "assertions", "" ]
When using database migrations, I obviously want none of the DAOs to be usable before the migrations are run. At the moment I'm declaring *a lot* of DAOs, all having a `depends-on=databaseMigrator` property. I find this troubling, especially since it's error prone. Is there a more compact way of doing this? --- Notes: * [the depends-on attribute is not 'inherited' from parent beans](http://jira.springframework.org/browse/SPR-5467); * I am not using Hibernate or JPA so I can't make the sessionFactory bean `depend-on` the migrator.
You could try writing a class that implements the [BeanFactoryPostProcessor](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/config/BeanFactoryPostProcessor.html) interface to automatically register the dependencies for you: **Warning:** This class has not been compiled. ``` public class DatabaseMigratorDependencyResolver implements BeanFactoryPostProcessor { @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { String[] beanNames = beanFactory.getBeanDefinitionNames(); for (String beanName : beanNames) { BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); // Your job is here: // Feel free to make use of the methods available from the BeanDefinition class (http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/config/BeanDefinition.html) boolean isDependentOnDatabaseMigrator = ...; if (isDependentOnDatabaseMigrator) { beanFactory.registerDependentBean("databaseMigrator", beanName); } } } } ``` You could then include a bean of this class alongside all your other beans. ``` <bean class="DatabaseMigratorDependencyResolver"/> ``` Spring will automatically run it before it starts initiating the rest of the beans.
I ended up creating a simple `ForwardingDataSource` class which appears in the context files as: ``` <bean id="dataSource" class="xxx.ForwardingDataSource" depends-on="databaseMigrator"> <property name="delegate"> <!-- real data source here --> </property> </bean> ``` If find it less elegant than [Adam Paynter's solution](https://stackoverflow.com/questions/959547/short-way-of-making-many-beans-depend-on-one-bean/960897#960897), but clearer.
Short way of making many beans depend-on one bean
[ "", "java", "spring", "" ]
Man, I just had this project given to me - expand on this they say. This is an example of ONE function: ``` <?php //500+ lines of pure wonder. function page_content_vc($content) { global $_DBH, $_TPL, $_SET; $_SET['ignoreTimezone'] = true; lu_CheckUpdateLogin(); if($_SESSION['dash']['VC']['switch'] == 'unmanned' || $_SESSION['dash']['VC']['switch'] == 'touchscreen') { if($content['page_name'] != 'vc') { header('Location: /vc/'); die(); } } if($_GET['l']) { unset($_SESSION['dash']['VC']); if($loc_id = lu_GetFieldValue('ID', 'Location', $_GET['l'])) { if(lu_CheckPermissions('vc', $loc_id)) { $timezone = lu_GetFieldValue('Time Zone', 'Location', $loc_id, 'ID'); if(strlen($timezone) > 0) { $_SESSION['time_zone'] = $timezone; } $_SESSION['dash']['VC']['loc_ID'] = $loc_id; header('Location: /vc/'); die(); } } } if($_SESSION['dash']['VC']['loc_ID']) { $timezone = lu_GetFieldValue('Time Zone', 'Location', $_SESSION['dash']['VC']['loc_ID'], 'ID'); if(strlen($timezone) > 0) { $_SESSION['time_zone'] = $timezone; } $loc_id = $_SESSION['dash']['VC']['loc_ID']; $org_id = lu_GetFieldValue('record_ID', 'Location', $loc_id); $_TPL->assign('loc_id', $loc_id); $location_name = lu_GetFieldValue('Location Name', 'Location', $loc_id); $_TPL->assign('LocationName', $location_name); $customer_name = lu_GetFieldValue('Customer Name', 'Organisation', $org_id); $_TPL->assign('CustomerName', $customer_name); $enable_visitor_snap = lu_GetFieldValue('VisitorSnap', 'Location', $loc_id); $_TPL->assign('EnableVisitorSnap', $enable_visitor_snap); $lacps = explode("\n", lu_GetFieldValue('Location Access Control Point', 'Location', $loc_id)); array_walk($lacps, 'trim_value'); if(count($lacps) > 0) { if(count($lacps) == 1) { $_SESSION['dash']['VC']['lacp'] = $lacps[0]; } else { if($_GET['changeLACP'] && in_array($_GET['changeLACP'], $lacps)) { $_SESSION['dash']['VC']['lacp'] = $_GET['changeLACP']; header('Location: /vc/'); die(); } else if(!in_array($_SESSION['dash']['VC']['lacp'], $lacps)) { $_SESSION['dash']['VC']['lacp'] = $lacps[0]; } $_TPL->assign('LACP_array', $lacps); } $_TPL->assign('current_LACP', $_SESSION['dash']['VC']['lacp']); $_TPL->assign('showContractorSearch', true); /* if($contractorStaff = lu_GetTableRow('ContractorStaff', $org_id, 'record_ID', 'record_Inactive != "checked"')) { foreach($contractorStaff['rows'] as $contractor) { $lacp_rights = lu_OrganiseCustomDataFunctionMultiselect($contractor[lu_GetFieldName('Location Access Rights', 'ContractorStaff')]); if(in_array($_SESSION['dash']['VC']['lacp'], $lacp_rights)) { $_TPL->assign('showContractorSearch', true); } } } */ } $selectedOptions = explode(',', lu_GetFieldValue('Included Fields', 'Location', $_SESSION['dash']['VC']['loc_ID'])); $newOptions = array(); foreach($selectedOptions as $selOption) { $so_array = explode('|', $selOption, 2); if(count($so_array) > 1) { $newOptions[$so_array[0]] = $so_array[1]; } else { $newOptions[$so_array[0]] = "Both"; } } if($newOptions[lu_GetFieldName('Expected Length of Visit', 'Visitor')]) { $alert = false; if($visitors = lu_OrganiseVisitors( lu_GetTableRow('Visitor', 'checked', lu_GetFieldName('Checked In', 'Visitor'), lu_GetFieldName('Location for Visit', 'Visitor').'="'.$_SESSION['dash']['VC']['loc_ID'].'" AND '.lu_GetFieldName('Checked Out', 'Visitor').' != "checked"'), false, true, true)) { foreach($visitors['rows'] as $key => $visitor) { if($visitor['expected'] && $visitor['expected'] + (60*30) < time()) { $alert = true; } } } if($alert == true) { $_TPL->assign('showAlert', 'red'); } else { //$_TPL->assign('showAlert', 'green'); } } $_TPL->assign('switch', $_SESSION['dash']['VC']['switch']); if($_SESSION['dash']['VC']['switch'] == 'touchscreen') { $_TPL->assign('VC_unmanned', true); } if($_GET['check'] == 'in') { if($_SESSION['dash']['VC']['switch'] == 'touchscreen') { lu_CheckInTouchScreen(); } else { lu_CheckIn(); } } else if($_GET['check'] == 'out') { if($_SESSION['dash']['VC']['switch'] == 'touchscreen') { lu_CheckOutTouchScreen(); } else { lu_CheckOut(); } } else if($_GET['switch'] == 'unmanned') { $_SESSION['dash']['VC']['switch'] = 'unmanned'; if($_GET['printing'] == true && (lu_GetFieldValue('Printing', 'Location', $_SESSION['dash']['VC']['loc_ID']) != "No" && lu_GetFieldValue('Printing', 'Location', $_SESSION['dash']['VC']['loc_ID']) != "")) { $_SESSION['dash']['VC']['printing'] = true; } else { $_SESSION['dash']['VC']['printing'] = false; } header('Location: /vc/'); die(); } else if($_GET['switch'] == 'touchscreen') { $_SESSION['dash']['VC']['switch'] = 'touchscreen'; if($_GET['printing'] == true && (lu_GetFieldValue('Printing', 'Location', $_SESSION['dash']['VC']['loc_ID']) != "No" && lu_GetFieldValue('Printing', 'Location', $_SESSION['dash']['VC']['loc_ID']) != "")) { $_SESSION['dash']['VC']['printing'] = true; } else { $_SESSION['dash']['VC']['printing'] = false; } header('Location: /vc/'); die(); } else if($_GET['switch'] == 'manned') { if($_POST['password']) { if(md5($_POST['password']) == $_SESSION['dash']['password']) { unset($_SESSION['dash']['VC']['switch']); //setcookie('email', "", time() - 3600); //setcookie('location', "", time() - 3600); header('Location: /vc/'); die(); } else { $_TPL->assign('switchLoginError', 'Incorrect Password'); } } $_TPL->assign('switchLogin', 'true'); } else if($_GET['m'] == 'visitor') { lu_ModifyVisitorVC(); } else if($_GET['m'] == 'enote') { lu_ModifyEnoteVC(); } else if($_GET['m'] == 'medical') { lu_ModifyMedicalVC(); } else if($_GET['print'] == 'label' && $_GET['v']) { lu_PrintLabelVC(); } else { unset($_SESSION['dash']['VC']['checkin']); unset($_SESSION['dash']['VC']['checkout']); $_TPL->assign('icon', 'GroupCheckin'); if($_SESSION['dash']['VC']['switch'] != 'unmanned' && $_SESSION['dash']['VC']['switch'] != 'touchscreen') { $staff_ids = array(); if($staffs = lu_GetTableRow('Staff', $_SESSION['dash']['VC']['loc_ID'], 'record_ID')) { foreach($staffs['rows'] as $staff) { $staff_ids[] = $staff['ID']; } } if($_GET['view'] == "tomorrow") { $dateStart = date('Y-m-d', mktime(0, 0, 0, date("m") , date("d")+1, date("Y"))); $dateEnd = date('Y-m-d', mktime(0, 0, 0, date("m") , date("d")+1, date("Y"))); } else if($_GET['view'] == "month") { $dateStart = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d"), date("Y"))); $dateEnd = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d")+30, date("Y"))); } else if($_GET['view'] == "week") { $dateStart = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d"), date("Y"))); $dateEnd = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d")+7, date("Y"))); } else { $dateStart = date('Y-m-d'); $dateEnd = date('Y-m-d'); } if(lu_GetFieldValue('Enable Survey', 'Location', $_SESSION['dash']['VC']['loc_ID']) == 'checked' && lu_GetFieldValue('Add Survey', 'Location', $_SESSION['dash']['VC']['loc_ID']) == 'checked') { $_TPL->assign('enableSurvey', true); } //lu_GetFieldName('Checked In', 'Visitor') //!= "checked" //date('d/m/Y'), lu_GetFieldName('Date of Visit', 'Visitor') if($visitors = lu_OrganiseVisitors(lu_GetTableRow('Visitor', $_SESSION['dash']['VC']['loc_ID'], lu_GetFieldName('Location for Visit', 'Visitor'), lu_GetFieldName('Checked In', 'Visitor').' != "checked" AND '.lu_GetFieldName('Checked Out', 'Visitor').' != "checked" AND '.lu_GetFieldName('Date of Visit', 'Visitor').' >= "'.$dateStart.'" AND '.lu_GetFieldName('Date of Visit', 'Visitor').' <= "'.$dateEnd.'"'))) { foreach($visitors['days'] as $day => $visitors_day) { foreach($visitors_day['rows'] as $key => $visitor) { $visitors['days'][$day]['rows'][$key]['visiting'] = lu_GetTableRow('Staff', $visitor['record_ID'], 'ID'); $visitors['days'][$day]['rows'][$key]['visiting']['notify'] = $_DBH->getRow('SELECT * FROM lu_notification WHERE ent_ID = "'.$visitor['record_ID'].'"'); } } //array_dump($visitors); $_TPL->assign('visitors', $visitors); } if($_GET['conGroup']) { if($_GET['action'] == 'add') { $_SESSION['dash']['VC']['conGroup'][$_GET['conGroup']] = $_GET['conGroup']; } else { unset($_SESSION['dash']['VC']['conGroup'][$_GET['conGroup']]); } } if(count($_SESSION['dash']['VC']['conGroup']) > 0) { if($conGroupResult = lu_GetTableRow('ContractorStaff', '1', '1', ' ID IN ('.implode(',', $_SESSION['dash']['VC']['conGroup']).')')) { if($_POST['_submit'] == 'Check-In Group >>') { $form = lu_GetForm('VisitorStandard'); $standarddata = array(); foreach($form['items'] as $key=>$item) { $standarddata[$key] = $_POST[lu_GetFieldName($item['name'], 'Visitor')]; } foreach($conGroupResult['rows'] as $conStaff) { $data = $standarddata; foreach($form['items'] as $key=>$item) { if($key != 'ID' && $key != 'record_ID' && $conStaff[lu_GetFieldName(lu_GetNameField($key, 'Visitor'), 'ContractorStaff')]) { $data[$key] = $conStaff[lu_GetFieldName(lu_GetNameField($key, 'Visitor'), 'ContractorStaff')]; } } $data['record_ID'] = $data[lu_GetFieldName('Visiting', 'Visitor')]; $data[lu_GetFieldName('Date of Visit', 'Visitor')] = date('Y-m-d'); $data[lu_GetFieldName('Time of Visit', 'Visitor')] = date('H:i'); $data[lu_GetFieldName('Checked In', 'Visitor')] = 'checked'; $data[lu_GetFieldName('Location for Visit', 'Visitor')] = $_SESSION['dash']['VC']['loc_ID']; $data[lu_GetFieldName('ConStaff ID', 'Visitor')] = $conStaff['ID']; $data[lu_GetFieldName('From', 'Visitor')] = lu_GetFieldValue('Legal Name', 'Contractor', $conStaff[lu_GetFieldName('Contractor', 'ContractorStaff')]); $id = lu_UpdateData($form, $data); lu_VisitorCheckIn($id); //array_dump($data); //array_dump($id); } unset($_SESSION['dash']['VC']['conGroup']); header('Location: /vc/'); die(); } if(count($conGroupResult['rows'])) { foreach($conGroupResult['rows'] as $key => $cstaff) { $conGroupResult['rows'][$key]['contractor'] = lu_GetTableRow('Contractor', $cstaff[lu_GetFieldName('Contractor', 'ContractorStaff')], 'ID'); } $_TPL->assign('conGroupResult', $conGroupResult); } $conGroupForm = lu_GetForm('VisitorConGroup'); $conGroupForm = lu_OrganiseVisitorForm($conGroupForm, $_SESSION['dash']['VC']['loc_ID'], 'Contractor'); $secure_options_array = lu_GetSecureOptions($org_id); if($secure_options_array[$_SESSION['dash']['VC']['loc_ID']]) { $conGroupForm['items'][lu_GetFieldName('Secure Area', 'Visitor')]['options']['values'] = $secure_options_array[$_SESSION['dash']['VC']['loc_ID']]; $conGroupForm['items'][lu_GetFieldName('Secure Area', 'Visitor')]['name'] = 'Secure Area'; } else { unset($conGroupForm['items'][lu_GetFieldName('Secure Area', 'Visitor')]); } if($secure_options_array) { $form['items'][lu_GetFieldName('Secure Area', 'Visitor')]['options']['values'] = $secure_options_array; $form['items'][lu_GetFieldName('Secure Area', 'Visitor')]['name'] = 'Secure Area'; } else { unset($form['items'][lu_GetFieldName('Secure Area', 'Visitor')]); } $_TPL->assign('conGroupForm', $conGroupForm); $_TPL->assign('hideFormCancel', true); } } if($_GET['searchVisitors']) { $_TPL->assign('searchVisitorsQuery', $_GET['searchVisitors']); $where = ''; if($_GET['searchVisitorsIn'] == 'Yes') { $where .= ' AND '.lu_GetFieldName('Checked In', 'Visitor').' = "checked"'; $_TPL->assign('searchVisitorsIn', 'Yes'); } else { $where .= ' AND '.lu_GetFieldName('Checked In', 'Visitor').' != "checked"'; $_TPL->assign('searchVisitorsIn', 'No'); } if($_GET['searchVisitorsOut'] == 'Yes') { $where = ''; $where .= ' AND '.lu_GetFieldName('Checked Out', 'Visitor').' = "checked"'; $_TPL->assign('searchVisitorsOut', 'Yes'); } else { $where .= ' AND '.lu_GetFieldName('Checked Out', 'Visitor').' != "checked"'; $_TPL->assign('searchVisitorsOut', 'No'); } if($searchVisitors = lu_OrganiseVisitors(lu_GetTableRow('Visitor', $_GET['searchVisitors'], '#search#', lu_GetFieldName('Location for Visit', 'Visitor').'="'.$_SESSION['dash']['VC']['loc_ID'].'"'.$where))) { foreach($searchVisitors['rows'] as $key => $visitor) { $searchVisitors['rows'][$key]['visiting'] = lu_GetTableRow('Staff', $visitor['record_ID'], 'ID'); } $_TPL->assign('searchVisitors', $searchVisitors); } else { $_TPL->assign('searchVisitorsNotFound', true); } } else if($_GET['searchStaff']) { if($_POST['staff_id']) { if(lu_CheckPermissions('staff', $_POST['staff_id'])) { $_DBH->query('UPDATE '.lu_GetTableName('Staff').' SET '.lu_GetFieldName('Current Location', 'Staff').' = "'.$_POST['current_location'].'" WHERE ID="'.$_POST['staff_id'].'"'); } } $locations = lu_GetTableRow('Location', $org_id, 'record_ID'); if(count($locations['rows']) > 1) { $_TPL->assign('staffLocations', $locations); } $loc_ids = array(); foreach($locations['rows'] as $location) { $loc_ids[] = $location['ID']; } // array_dump($locations); // array_dump($_POST); $_TPL->assign('searchStaffQuery', $_GET['searchStaff']); $where = ' AND record_Inactive != "checked"'; if($_GET['searchStaffIn'] == 'Yes' && $_GET['searchStaffOut'] != 'Yes') { $where .= ' AND ('.lu_GetFieldName('Staff Status', 'Staff').' = "" OR '.lu_GetFieldName('Staff Status', 'Staff').' = "On-Site")'. $_TPL->assign('searchStaffIn', 'Yes'); $_TPL->assign('searchStaffOut', 'No'); } else if($_GET['searchStaffOut'] == 'Yes' && $_GET['searchStaffIn'] != 'Yes') { $where .= ' AND ('.lu_GetFieldName('Staff Status', 'Staff').' != "" AND '.lu_GetFieldName('Staff Status', 'Staff').' != "On-Site")'. $_TPL->assign('searchStaffOut', 'Yes'); $_TPL->assign('searchStaffIn', 'No'); } else { $_TPL->assign('searchStaffOut', 'Yes'); $_TPL->assign('searchStaffIn', 'Yes'); } if($searchStaffs = lu_GetTableRow('Staff', $_GET['searchStaff'], '#search#', 'record_ID IN ('.implode(',', $loc_ids).')'.$where, lu_GetFieldName('First Name', 'Staff').','.lu_GetFieldName('Surname', 'Staff'))) { $_TPL->assign('searchStaffs', $searchStaffs); } else { $_TPL->assign('searchStaffNotFound', true); } } else if($_GET['searchContractor']) { $_TPL->assign('searchContractorQuery', $_GET['searchContractor']); //$where = ' AND '.lu_GetTableName('ContractorStaff').'.record_Inactive != "checked"'; $where = ' '; if($_GET['searchContractorIn'] == 'Yes' && $_GET['searchContractorOut'] != 'Yes') { $where .= ' AND ('.lu_GetFieldName('Onsite Status', 'ContractorStaff').' = "Onsite")'; $_TPL->assign('searchContractorIn', 'Yes'); $_TPL->assign('searchContractorOut', 'No'); } else if($_GET['searchContractorOut'] == 'Yes' && $_GET['searchContractorIn'] != 'Yes') { $where .= ' AND ('.lu_GetFieldName('Onsite Status', 'ContractorStaff').' != "Onsite")'. $_TPL->assign('searchContractorOut', 'Yes'); $_TPL->assign('searchContractorIn', 'No'); } else { $_TPL->assign('searchContractorOut', 'Yes'); $_TPL->assign('searchContractorIn', 'Yes'); } $join = 'LEFT JOIN '.lu_GetTableName('Contractor').' ON '.lu_GetTableName('Contractor').'.ID = '.lu_GetTableName('ContractorStaff').'.'.lu_GetFieldName('Contractor', 'ContractorStaff'); $extrasearch = array ( lu_GetTableName('Contractor').'.'.lu_GetFieldName('Legal Name', 'Contractor') ); if($searchContractorResult = lu_GetTableRow('ContractorStaff', $_GET['searchContractor'], '#search#', lu_GetTableName('ContractorStaff').'.record_ID = "'.$org_id.'" '.$where, lu_GetFieldName('First Name', 'ContractorStaff').','.lu_GetFieldName('Surname', 'ContractorStaff'), $join, $extrasearch)) { /* foreach($searchContractorResult['rows'] as $key=>$contractor) { $lacp_rights = lu_OrganiseCustomDataFunctionMultiselect($contractor[lu_GetFieldName('Location Access Rights', 'ContractorStaff')]); if(!in_array($_SESSION['dash']['VC']['lacp'], $lacp_rights)) { unset($searchContractorResult['rows'][$key]); } } */ if(count($searchContractorResult['rows'])) { foreach($searchContractorResult['rows'] as $key => $cstaff) { /* if($cstaff[lu_GetFieldName('Onsite_Status', 'Contractor')] == 'Onsite')) { if($visitor['rows'][0][lu_GetFieldName('ConStaff ID', 'Visitor')]) { $_DBH->query('UPDATE '.lu_GetTableName('ContractorStaff').' SET '.lu_GetFieldName('Onsite Status', 'ContractorStaff').' = "" WHERE ID="'.$visitor['rows'][0][lu_GetFieldName('ConStaff ID', 'Visitor')].'"'); } } */ if($cstaff[lu_GetFieldName('SACN Expiry Date', 'ContractorStaff')] != '0000-00-00') { if(strtotime($cstaff[lu_GetFieldName('SACN Expiry Date', 'ContractorStaff')]) < time()) { $searchContractorResult['rows'][$key]['sacn_expiry'] = true; } else { $searchContractorResult['rows'][$key]['sacn_expiry'] = false; } } else { $searchContractorResult['rows'][$key]['sacn_expiry'] = false; } if($cstaff[lu_GetFieldName('Induction Valid Until', 'ContractorStaff')] != '0000-00-00') { if(strtotime($cstaff[lu_GetFieldName('Induction Valid Until', 'ContractorStaff')]) < time()) { $searchContractorResult['rows'][$key]['induction_expiry'] = true; } else { $searchContractorResult['rows'][$key]['induction_expiry'] = false; } } else { $searchContractorResult['rows'][$key]['induction_expiry'] = false; } $searchContractorResult['rows'][$key]['contractor'] = lu_GetTableRow('Contractor', $cstaff[lu_GetFieldName('Contractor', 'ContractorStaff')], 'ID'); } $_TPL->assign('searchContractorResult', $searchContractorResult); } else { $_TPL->assign('searchContractorNotFound', true); } } else { $_TPL->assign('searchContractorNotFound', true); } } $occupancy = array(); $occupancy['staffNumber'] = $_DBH->getOne('SELECT count(*) FROM '.lu_GetTableName('Staff').' WHERE record_ID = "'.$_SESSION['dash']['VC']['loc_ID'].'" AND record_Inactive != "checked" AND '.lu_GetFieldName('Ignore Counts', 'Staff').' != "checked"'); $occupancy['staffNumberOnsite']= $_DBH->getOne( 'SELECT count(*) FROM '.lu_GetTableName('Staff').' WHERE ( (record_ID = "'.$_SESSION['dash']['VC']['loc_ID'].'" AND ('.lu_GetFieldName('Staff Status', 'Staff').' = "" OR '.lu_GetFieldName('Staff Status', 'Staff').' = "On-Site")) OR '.lu_GetFieldName('Current Location', 'Staff').' = "'.$_SESSION['dash']['VC']['loc_ID'].'") AND record_Inactive != "checked" AND '.lu_GetFieldName('Ignore Counts', 'Staff').' != "checked"'); $occupancy['visitorsOnsite'] = $_DBH->getOne('SELECT count(*) FROM '.lu_GetTableName('Visitor').' WHERE '.lu_GetFieldName('Location for Visit', 'Visitor').' = "'.$_SESSION['dash']['VC']['loc_ID'].'" AND '.lu_GetFieldName('Checked In', 'Visitor').' = "checked" AND '.lu_GetFieldName('Checked Out', 'Visitor').' != "checked"'); $_TPL->assign('occupancy', $occupancy); if($enotes = lu_GetTableRow('Enote', $org_id, 'record_ID', lu_GetFieldName('Note Emailed', 'Enote').' = "0000-00-00" AND '.lu_GetFieldName('Note Passed On', 'Enote').' != "Yes"')) { $_TPL->assign('EnoteNotice', true); } if($medical = lu_GetTableRow('MedicalRoom', $_SESSION['dash']['VC']['loc_ID'], 'record_ID', 'record_Inactive != "Yes"')) { $_TPL->assign('MedicalNotice', true); } if(lu_GetFieldValue('Printing', 'Location', $_SESSION['dash']['VC']['loc_ID']) != "No" && lu_GetFieldValue('Printing', 'Location', $_SESSION['dash']['VC']['loc_ID']) != "") { $_TPL->assign('UnmannedPrinting', true); } } else { if($_SESSION['dash']['VC']['printing'] == true) { $_TPL->assign('UnmannedPrinting', true); } } // enable if contractor check-in buttons should be enabled if(lu_GetFieldValue('Enable Contractor Check In', 'Location', $_SESSION['dash']['VC']['loc_ID']) == "checked") { $_TPL->assign('ContractorCheckin', true); } } if($_SESSION['dash']['entity_id'] && $_GET['fixupCon'] == 'true') { $conStaffs = lu_GetTableRow('ContractorStaff', $_SESSION['dash']['ModifyConStaffs']['org_ID'], 'record_ID', '', lu_GetFieldName('First Name', 'ContractorStaff').','.lu_GetFieldName('Surname', 'ContractorStaff')); foreach($conStaffs['rows'] as $key => $cstaff) { if($cstaff[lu_GetFieldName('Site Access Card Number', 'ContractorStaff')] && $cstaff[lu_GetFieldName('Site Access Card Type', 'ContractorStaff')]) { echo $cstaff['ID'].' '; $_DBH->query('UPDATE '.lu_GetTableName('Visitor').' SET '.lu_GetFieldName('Site Access Card Number', 'Visitor').' = "'.$cstaff[lu_GetFieldName('Site Access Card Number', 'ContractorStaff')].'", '.lu_GetFieldName('Site Access Card Type', 'Visitor').' = "'.$cstaff[lu_GetFieldName('Site Access Card Type', 'ContractorStaff')].'" WHERE '.lu_GetFieldName('ConStaff ID', 'Visitor').'="'.$cstaff['ID'].'"'); } } } } else { if($_SESSION['dash']['staffs']) { foreach($_SESSION['dash']['staffs']['rows'] as $staff) { if($staff[lu_GetFieldName('Reception Manager', 'Staff')] == 'checked') { $loc_id = $staff['record_ID']; unset($_SESSION['dash']['VC']); if($loc_id = lu_GetFieldValue('ID', 'Location', $loc_id)) { $_SESSION['dash']['VC']['loc_ID'] = $loc_id; header('Location: /vc/'); die(); } } } } $_TPL->assign('mode', 'public'); } $content['page_content'] = $_TPL->fetch('modules/vc.htm'); return $content; } ?> ``` This question will probably be closed - I just need some support from my coding brothers and sisters. \*SOB\*
Global search and replace are your friends. Start by: 1. Breaking the huge "if ... else" into individual functions which you can rename later once you figure out what they do. 2. Do global search/replace on the $\_GET[...] and $\_SESSION['dash'] variables to give them more meaningful names 3. Continue to clean up In short, use the basic computer programming technique: Divide and conquer. Divide the functionality into smaller parts, then clean up the individual parts. Shouldn't take more than an hour.
Software is a business. You have been handed code which is essentially unmaintainable, and been asked to do something with it. This will require heavy refactoring. The bad news is that it will **suck**. The good news is that in exchange for your time the company will give you **money**, which you will be able to exchange for **goods and services** such as food, clothing, beer and concert tickets. As long as everybody has a correct or at least approximate understanding of the time costs involved, you should be fine.
What would you do if you just had this code dumped in your lap?
[ "", "php", "" ]
I'm looking for a minimal and easy to learn C or C++ cross platform gui library. In a nutshell I only need the following functionality: * application window * menu bar * some simple dialogs, File-open and save. Maybe a user-written one. * user canvas where I can draw lines an circles on. * some kind of message/event loop mechanism. Target platforms would be Win32 and linux. MacOS would be nice to have but is not important at the moment. Why am I looking for something minimal? I don't want to spend much time to learn a big and full blown abstraction system for a really small application. The easier and leaner, the better. Any suggestions?
If you need something small, try [FLTK](http://www.fltk.org/) libs: I used them at work (embedded development) and I think it's a valid option. Maybe apps are not as "cool" as QT-based ones, but developing with FLTK libs is fast and easy.
I don't know about minimal, but [Qt](http://qtsoftware.com/) is pretty easy to learn. Its light-weight enough to run on embedded devices, so you be the judge. --- EDIT after seeing the comments: Yes, Qt is a fullblown application framework, but here's my case: an app with cross platform GUI but other platform-dependent code is not really platform independent. I don't think moving existing C++ code into Qt entails any work at all. If anything, this would allow Nils to use his existing C++ code, and only use Qt for a GUI. But of course, I assume that the existing C++ code is portable.
minimal cross-platform gui lib?
[ "", "c++", "c", "user-interface", "frameworks", "" ]
If I have an array that looks like this: ``` $str = ''; if( $_POST['first'] ) $str = $_POST['first']; if( $_POST['second'] ) $str .= ($str != '' ? ',' : '') . $_POST['second']; if( $_POST['third'] ) $str .= ($str != '' ? ',' : '') . $_POST['third']; if( $_POST['fourth'] ) $str .= ($str != '' ? ',' : '') . $_POST['second']; $str .= ($str != '' ? '.' : ''); ``` Which gives me something like this: Joe, Adam, Mike. However, I would like to add an "**and**" before the last item. So it would then read: Joe, Adam, **and** Mike. How can I modify my code to do this?
Arrays are awesome for this: ``` $str = array(); foreach (array('first','second','third','fourth') as $k) { if (isset($_POST[$k]) && $_POST[$k]) { $str[] = $_POST[$k]; } } $last = array_pop($str); echo implode(", ", $str) . " and " . $last; ``` You should probably special case the above for when there's one item. I, in fact, wrote a function called "conjunction" which does the above, and includes the special case: ``` function conjunction($x, $c="or") { if (count($x) <= 1) { return implode("", $x); } $ll = array_pop($x); return implode(", ", $x) . " $c $ll"; } ``` Nice question! **Updated**: General purpose way to do this: ``` function and_form_fields($fields) { $str = array(); foreach ($fields as $k) { if (array_key_exists($k, $_POST) && $v = trim($_POST[$k])) { $str[] = $v; } } return conjunction($str, "and"); } ... and_form_fields(array("Name_1","Name_2",...)); ``` I added correct $\_POST checking to avoid notices, and blank values.
The first ideea that comes to my mind is to always keep a last one name in an auxiliar variabile. When you have another one to put in, you take it put the 'comma' and get the next name in the aux. At the end, when you finished added the names, you add 'and' and the last name from aux.
How can I display an array in a human readable format?
[ "", "php", "arrays", "formatting", "" ]
In Java, is it faster to iterate through an array the old-fashioned way, ``` for (int i = 0; i < a.length; i++) f(a[i]); ``` Or using the more concise form, ``` for (Foo foo : a) f(foo); ``` For an ArrayList, is the answer the same? Of course for the vast bulk of application code, the answer is it makes no discernible difference so the more concise form should be used for readability. However the context I'm looking at is heavy duty technical computation, with operations that must be performed billions of times, so even a tiny speed difference could end up being significant.
If you're looping through an array, it shouldn't matter - the enhanced for loop uses array accesses anyway. For example, consider this code: ``` public static void main(String[] args) { for (String x : args) { System.out.println(x); } } ``` When decompiled with `javap -c Test` we get (for the `main` method): ``` public static void main(java.lang.String[]); Code: 0: aload_0 1: astore_1 2: aload_1 3: arraylength 4: istore_2 5: iconst_0 6: istore_3 7: iload_3 8: iload_2 9: if_icmpge 31 12: aload_1 13: iload_3 14: aaload 15: astore 4 17: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 20: aload 4 22: invokevirtual #3; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 25: iinc 3, 1 28: goto 7 31: return ``` Now change it to use an explicit array access: ``` public static void main(String[] args) { for (int i = 0; i < args.length; i++) { System.out.println(args[i]); } } ``` This decompiles to: ``` public static void main(java.lang.String[]); Code: 0: iconst_0 1: istore_1 2: iload_1 3: aload_0 4: arraylength 5: if_icmpge 23 8: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 11: aload_0 12: iload_1 13: aaload 14: invokevirtual #3; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 17: iinc 1, 1 20: goto 2 23: return ``` There's a bit more setup code in the enhanced for loop, but they're basically doing the same thing. No iterators are involved. Furthermore, I'd expect them to get JITted to even more similar code. Suggestion: if you really think it might make a significant difference (which it would only *ever* do if the body of the loop is absolutely miniscule) then you should benchmark it with your real application. That's the only situation which matters.
This falls squarely in the arena of [micro-optimization](http://www.codinghorror.com/blog/archives/000185.html). It really doesn't matter. Stylistically I always prefer the second because it's more concise, unless you need the loop counter for something else. And that's *far more important than this kind of micro-optimization*: readability. That being said, For an ArrayList there won't be much difference but a LinkedList will be much more efficient with the second.
Fastest way to iterate an Array in Java: loop variable vs enhanced for statement
[ "", "java", "performance", "iteration", "" ]
I need an Image that is grayed out when disabled (IsEnabled=False). A grayed out version of the image can be produced by reading the BitmapImage into a FormatConvertedBitmap which is shown [here](http://apocryph.org/2007/08/26/rendering_disabled_grayed_out_image_buttons_wpf/). I have been able to get this working with a UserControl but now **I would like the same behavior in a specialized Image class** for more flexibility. I don't care if this is implemented in XAML, code-behind or both, but it needs to be a subclass of Image. The usage could be: ``` <DisableableImage Source="Images/image1.png" /> <DisableableImage Source="Images/image1.png" IsEnabled="False" /> <!-- Since IsEnabled is inherited down the tree, the image will be grayed out like the rest of the button --> <Button IsEnabled="False"> <StackPanel Orientation="Horizontal"> <TextBlock>OK</TextBlock> <DisableableImage Source="Images/ok.png" /> </StackPanel> </Button> ```
Have a look at [this link](http://blogs.infragistics.com/blogs/andrew_smith/archive/2008/03/30/disabled-images-in-wpf.aspx) EDIT: Or [this one](http://weblogs.asp.net/thomaslebrun/archive/2009/03/03/wpf-how-to-gray-the-icon-of-a-menuitem.aspx) (all you need is the AutoGreyableImage class)
I made a little comparison based on the following solutions. * The approaches in the link provided by the OP * The links provided by *Thomas Levesque* + [AutoDisabledImage](http://www.infragistics.com/community/blogs/andrew_smith/archive/2008/03/30/disabled-images-in-wpf.aspx) + [AutoGreyableImage](http://weblogs.asp.net/thomaslebrun/archive/2009/03/03/wpf-how-to-gray-the-icon-of-a-menuitem.aspx) * [Greyscale Effect](http://windowsclient.net/wpf/wpf35/wpf-35sp1-more-effects.aspx) Since I already had a licens for the Infragistics *Net Advantage for WPF* it was easy to try it out Here is the result ![enter image description here](https://i.stack.imgur.com/h54LA.png) So the best approach depends on what results you are after. As for me, I think the result produced by `AutoDisabledImage` from Infragistics is too bright, `AutoGreyableImage` does a pretty good job *(Identical result to Approach 1 (OP link))* and `GreyscaleEffect` produces the best result.
How can I make a WPF Image disableable?
[ "", "c#", "wpf", "image", "xaml", "" ]
Does anyone know if it exists a Web IDE allowing to develop web application directly from a web application? The W3School website allows to write small piece of code in HTML or javascript but is there another solution more project oriented?
**CodeRun** <http://www.coderun.com/> --- **Bespin from Mozilla Labs** <http://labs.mozilla.com/projects/bespin/> > Bespin is a Mozilla Labs experiment > that proposes an open, extensible > web-based framework for code editing > that aims to increase developer > productivity, enable compelling user > experiences, and promote the use of > open standards.
[Web2py](http://www.web2py.com) is a python web-app framework where you can develop applications directly from within the browser
Web IDE tool
[ "", "javascript", "html", "ide", "" ]
first question here, so hopefully you'll all go gently on me! I've been reading an awful lot over the past few days about polymorphism, and trying to apply it to what I do in c#, and it seems there are a few different ways to implement it. I hope I've gotten a handle on this, but I'd be delighted even if I haven't for clarification. From what I can see, I've got 3 options: 1. I can just inherit from a base class and use the keyword '`virtual`' on any methods that I want my derived classes to override. 2. I could implement an abstract class with virtual methods and do it that way, 3. I could use an interface? From what I can see, if I don't require any implementation logic in the base, then an interface gives me the most flexibility (as I'm then not limiting myself with regards multiple inheritance etc.), but if I require the base to be able to do something on top of whatever the derived classes are doing, then going with either 1 or 2 would be the better solution? Thanks for any input on this guys - I have read so much this weekend, both on this site and elsewhere, and I *think* I understand the approaches now, yet I just want to clarify in a language specific way if I'm on the right track. Hopefully also I've tagged this correctly. Cheers, Terry
An interface offers the most abstraction; you aren't tied to any specific implementation (useful if the implementation must, for other reasons, have a different base class). For true polymorphism, `virtual` is a must; polymorphism is most commonly associated with type subclassing... You can of course mix the two: ``` public interface IFoo { void Bar(); } class Foo : IFoo { public virtual void Bar() {...} } class Foo2 : Foo { public override ... } ``` `abstract` is a separate matter; the choice of `abstract` is really: can it be sensibly defined by the base-class? If there is there no default implementation, it must be `abstract`. A common base-class can be useful when there is a lot of implementation details that are common, and it would be pointless to duplicate purely by interface; but interestingly - if the implementation will *never* vary per implementation, extension methods provide a useful way of exposing this on an `interface` (so that each implementation doesn't have to do it): ``` public interface IFoo { void Bar(); } public static class FooExtensions { // just a silly example... public static bool TryBar(this IFoo foo) { try { foo.Bar(); return true; } catch { return false; } } } ```
All three of the above are valid, and useful in their own right. There is no technique which is "best". Only programming practice and experience will help you to choose the right technique at the right time. So, pick a method that seems appropriate now, and implement away. Watch what works, what fails, learn your lessons, and try again.
implementing polymorphism in c#, how best to do it?
[ "", "c#", "oop", "polymorphism", "" ]
I have a tooltip for a Label and I want it to stay open until the user moves the mouse to a different control. I have tried the following properties on the tooltip: ``` StaysOpen="True" ``` and ``` ToolTipService.ShowDuration = "60000" ``` But in both cases the tooltip is only displayed for exactly 5 seconds. Why are these values being ignored?
Just put this code in initialization section. ``` ToolTipService.ShowDurationProperty.OverrideMetadata( typeof(DependencyObject), new FrameworkPropertyMetadata(Int32.MaxValue)); ```
If you want to set this for just one tooltip, set the duration on the object having the Tooltip, like this: ``` <Label ToolTipService.ShowDuration="12000" Name="lblShowTooltip" Content="Shows tooltip"> <Label.ToolTip> <ToolTip> <TextBlock>Hello world!</TextBlock> </ToolTip> </Label.ToolTip> </Label> ``` I'd say that this design was chosen because it allows same tooltip with different timeouts on different controls. If you want this globally for your whole app, see the accepted answer.
Forcing a WPF tooltip to stay on the screen
[ "", "c#", "wpf", "xaml", "tooltip", "" ]
I want to hash a char array in to an int or a long. The resulting value has to adhere to a given precision value. The function I've been using is given below: ``` int GetHash(const char* zKey, int iPrecision /*= 6*/) { /////FROM : http://courses.cs.vt.edu/~cs2604/spring02/Projects/4/elfhash.cpp unsigned long h = 0; long M = pow(10, iPrecision); while(*zKey) { h = (h << 4) + *zKey++; unsigned long g = h & 0xF0000000L; if (g) h ^= g >> 24; h &= ~g; } return (int) (h % M); } ``` The string to be hashed is similar to "SAEUI1210.00000010\_1". However, this produces duplicate values in some cases. Are there any good alternatives which wouldn't duplicate the same hash for different string values.
The very definition of a hash is that it produces duplicate values for some values, due to hash value range being smaller than the space of the hashed data. In theory, a 32-bit hash has enough range to hash all ~6 character strings (A-Z,a-z,0-9 only), without causing a collision. In practice, hashes are not a perfect permutation of the input. Given a 32-bit hash, you can expect to get hash collisions after hashing ~16 bit of random inputs, due to the [birthday paradox](http://en.wikipedia.org/wiki/Birthday_paradox). Given a static set of data values, it's always possible to construct a hash function designed specifically for them, which will never collide with itself (of course, size of its output will be at least `log(|data set|)`. However, it requires you to know all the possible data values ahead of time. This is called [perfect hashing](http://en.wikipedia.org/wiki/Perfect_hash_function). That being said, [here](http://www.cse.yorku.ca/~oz/hash.html) are a few alternatives which should get you started (they are designed to minimize collisions)
Every hash will have collisions. Period. That's called a [Birthday Problem](http://en.wikipedia.org/wiki/Birthday_paradox). You may want to check cryptographic has functions like MD5 (relatively fast and you don't care that it's insecure) but it also will have collisions.
String to Integer Hashing Function with Precision
[ "", "c++", "hash", "" ]
I have one million rows of data in .txt format. the format is very simple. For each row: ``` user1,value1 user2,value2 user3,value3 user1,value4 ... ``` You know what I mean. For each user, it could appear many times, or appear only once (you never know). I need to find out all the values for each user. Because user may appear randomly, I used Hashmap to do it. That is: HashMap(key: String, value: ArrayList). But to add data to the arrayList, I have to constantly use HashMap get(key) to get the arrayList, add value to it, then put it back to HashMap. I feel it is not that very efficient. Anybody knows a better way to do that?
You don't need to re-add the ArrayList back to your Map. If the ArrayList already exists then just add your value to it. An improved implementation might look like: ``` Map<String, Collection<String>> map = new HashMap<String, Collection<String>>(); ``` while processing each line: ``` String user = user field from line String value = value field from line Collection<String> values = map.get(user); if (values==null) { values = new ArrayList<String>(); map.put(user, values) } values.add(value); ``` **Follow-up April 2014** - I wrote the original answer back in 2009 when my knowledge of Google Guava was limited. In light of all that Google Guava does, I now recommend using its `Multimap` instead of reinvent it. ``` Multimap<String, String> values = HashMultimap.create(); values.put("user1", "value1"); values.put("user2", "value2"); values.put("user3", "value3"); values.put("user1", "value4"); System.out.println(values.get("user1")); System.out.println(values.get("user2")); System.out.println(values.get("user3")); ``` Outputs: ``` [value4, value1] [value2] [value3] ```
Use Multimap from Google Collections. It allows multiple values for the same key <https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/Multimap.html>
Best way to create a hashmap of arraylist
[ "", "java", "data-structures", "collections", "arraylist", "hashmap", "" ]
I have a table, schema is very simple, an ID column as unique primary key (uniqueidentifier type) and some other nvarchar columns. My current goal is, for 5000 inputs, I need to calculate what ones are already contained in the table and what are not. Tht inputs are string and I have a C# function which converts string into uniqueidentifier (GUID). My logic is, if there is an existing ID, then I treat the string as already contained in the table. My question is, if I need to find out what ones from the 5000 input strings are already contained in DB, and what are not, what is the most efficient way? BTW: My current implementation is, convert string to GUID using C# code, then invoke/implement a store procedure which query whether an ID exists in database and returns back to C# code. My working environment: VSTS 2008 + SQL Server 2008 + C# 3.5.
My first instinct would be to pump your 5000 inputs into a single-column temporary table X, possibly index it, and then use: ``` SELECT X.thecol FROM X JOIN ExistingTable USING (thecol) ``` to get the ones that are present, and (if both sets are needed) ``` SELECT X.thecol FROM X LEFT JOIN ExistingTable USING (thecol) WHERE ExistingTable.thecol IS NULL ``` to get the ones that are absent. Worth benchmarking, at least. Edit: as requested, here are some good docs & tutorials on temp tables in SQL Server. [Bill Graziano](http://www.sqlteam.com/article/temporary-tables) has a simple intro covering temp tables, table variables, and global temp tables. [Randy Dyess](http://www.sql-server-performance.com/articles/per/temp_tables_necessary_p1.aspx) and [SQL Master](http://sqlserver-qa.net/blogs/perftune/archive/2008/01/17/3228.aspx) discuss performance issue for and against them (but remember that if you're getting performance problems you do want to benchmark alternatives, *not* just go on theoretical considerations!-). MSDN has articles on [tempdb](http://msdn.microsoft.com/en-us/library/ms190768.aspx) (where temp tables are kept) and [optimizing](http://msdn.microsoft.com/en-us/library/ms175527.aspx) its performance.
Step 1. Make sure you have a problem to solve. Five thousand inserts isn't a lot to insert one at a time in a lot of contexts. Are you certain that the simplest way possible isn't sufficient? What performance issues have you measured so far?
how to improve SQL query performance in my case
[ "", "c#", "sql-server", "optimization", "" ]
The fact that the replace method returns a string object rather than replacing the contents of a given string is a little obtuse (but understandable when you know that strings are immutable in Java). I am taking a major performance hit by using a deeply nested replace in some code. Is there something I can replace it with that would make it faster?
This is what [StringBuilder](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html) is meant for. If you're going to be doing a lot of manipulation, do it on a `StringBuilder`, then turn that into a `String` whenever you need to. `StringBuilder` is described thus: > "A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization". It has `replace` (and `append`, `insert`, `delete`, et al) and you can use `toString` to morph it into a real `String`.
The previous posts are right, StringBuilder/StringBuffer are a solution. But, you also have to question if it is a good idea to do the replace on big Strings in memory. I often have String manipulations that are implemented as a stream, so instead of replacing it in the string and then sending it to an OutputStream, I do the replace at the moment that I send the String to the outputstream. That works much faster than any replace. This works much faster if you want this replace to implement a template mechanism. Streaming is always faster since you consume less memory and if the clients is slow, you only need to generate at a slow pace - so it scales much better.
Faster alternatives to replace method in a Java String?
[ "", "java", "replace", "" ]
I am developing an application in which I need to extract the audio from a video. The audio needs to be extracted in .wav format but I do not have a problem with the video format. Any format will do, as long as I can extract the audio in a wav file. Currently I am using Windows Media Player COM control in a windows form to play the videos, but any other embedded player will do as well. Any suggestions on how to do this? Thanks
[Here is a link](http://www.videohelp.com/forum/archive/how-to-extract-to-wav-from-avi-using-graphedit-t239907.html) on how to extract audio using GraphEdit, GraphEdit is an front end UI for the [DirectShow API](http://msdn.microsoft.com/en-us/library/ms783323.aspx) so everything it can do you can do with API. You can use the [DirectShow.NET](http://directshownet.sourceforge.net/) liberty which wraps the DirectShow API for the managed world.
If you want to do this with C#, take a look at [NAudio library](https://github.com/naudio/NAudio). It can analyze the audio format (like FFMpeg) and also provide the audio stream. Here's [one example](https://github.com/tompaana/hls-transcription-sample). Snippet from the sample: ``` using NAudio.Wave; using System.IO; ... // contentAsByteArray consists of video bytes MemoryStream contentAsMemoryStream = new MemoryStream(contentAsByteArray); using (WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream( new StreamMediaFoundationReader(contentAsMemoryStream))) { WaveStream blockAlignReductionStream = new BlockAlignReductionStream(pcmStream); // Do something with the wave stream } ```
Extract wav file from video file
[ "", "c#", "winforms", "video", "audio", "" ]
``` <input name="foo[]" ... > ``` I've used these before, but I'm wondering what it is called and if there is a specification for it? I couldn't find it in the [HTML 4.01 Spec](http://www.w3.org/TR/html401/interact/forms.html) and results in various Google results only call it an "array" along with many PHP examples of processing the form data.
There are some references and pointers in the comments [on this page at PHP.net](http://www.php.net/manual/en/faq.html.php#faq.html.arrays): Torsten says > "Section C.8 of the XHTML spec's compatability guidelines apply to the use of the name attribute as a fragment identifier. If you check the DTD you'll find that the 'name' attribute is still defined as CDATA for form elements." Jetboy says > "according to this: <http://www.w3.org/TR/xhtml1/#C_8> the type of the name attribute has been changed in XHTML 1.0, meaning that square brackets in XHTML's name attribute are not valid. > > Regardless, at the time of writing, the W3C's validator doesn't pick this up on a XHTML document."
It's just PHP, not HTML. It parses all HTML fields with [] into an array. So you can have ``` <input type="checkbox" name="food[]" value="apple" /> <input type="checkbox" name="food[]" value="pear" /> ``` and when submitted, PHP will make $\_POST['food'] an array, and you can access its elements like so: ``` echo $_POST['food'][0]; // would output first checkbox selected ``` or to see all values selected: ``` foreach( $_POST['food'] as $value ) { print $value; } ``` Anyhow, don't think there is a specific name for it
HTML input arrays
[ "", "php", "html", "arrays", "forms", "" ]
I create a new form and call from the parent form as follows: ``` loginForm = new SubLogin(); loginForm.Show(); ``` I need to display the child form at the centre of the parent. So,in the child form load I do the foll:` ``` Point p = new Point(this.ParentForm.Width / 2 - this.Width / 2, this.ParentForm.Height / 2 - this.Height / 2); this.Location = p; ``` But this is throwing error as parent form is null. I tried setting the Parent property as well, but didn't help. Any inputs on this?
Try: ``` loginForm.StartPosition = FormStartPosition.CenterParent; loginForm.ShowDialog(this); ``` Of course the child form will now be a blocking form (dialog) of the parent window, if that isn't desired then just replace `ShowDialog` with `Show`.. ``` loginForm.Show(this); ``` You will still need to specify the StartPosition though.
The setting of parent does not work for me unless I use `form.ShowDialog();`. When using `form.Show();` or `form.Show(this);` nothing worked until I used, `this.CenterToParent();`. I just put that in the *Load* method of the form. All is good. Start position to the center of parent was set and does work when using the blocking showdialog.
Show a child form in the centre of Parent form in C#
[ "", "c#", "winforms", "" ]
I have a C# library that is surfaced through a webpage UI. There's of course the UI layer, which makes calls through a business logic layer, which in turn hits the data access layer to retrieve the data. The data is actually retrieved via a web service which has the capability to query data asynchronously. I'm starting to learn how to deal with requests asynchronously to both speed up page time (grabbing multiple items from the web service as soon as I can with multiple threads), and for scalability by threads not being tied up all the time. Given the three-tier architecture of my code, would this mean that pages asynchronously make calls through the business layer (and therefore speed up by making concurrent requests), and the web service in the data layer in turn would also make its requests asynchronously? The logic of juggling all the callbacks is hurting my brain. Are there any resources out there for this type of approach?
If you can stand to introduce a new language, F# is terribly good at writing asynchronous code, one of its main strengths, IMHO, aside from its conciseness. Writing async code looks almost exactly like linear non-async code! Related links: * [Beyond Foundations of F# - Asynchronous Workflows](http://www.infoq.com/articles/pickering-fsharp-async) * [An introduction to F#](http://channel9.msdn.com/pdc2008/TL11/) (video) * [Concurrency in F#](http://www.langnetsymposium.com/2009/talks/21-AmanderLauter-FSharpConcurrency.html) (video - excellent short case study on speeding up an existing real-world C# insurance processing system with selective introduction of F# replacement modules) If you don't want to introduce a new language, here is a technique for using iterators to simplify your code: * [Asynchronous Programming in C# using Iterators](http://tomasp.net/blog/csharp-async.aspx)
There is a somewhat useful concept called `Future<T>`, which represents a unit of an asyncronous work to be done in future. So, in simple words, at the beginning of some action (like app start or page load) you can define, which values you will need in future and let the background threads to compute them for you. When your user demands a specific value, you just ask for it from the according `Future<T>`. If its already done, you get it immediately, otherwise you'll have to block your main thread, or somehow inform the user that the value is still not ready. Some discussion of that concept you can find [here](https://stackoverflow.com/questions/896936/asyncfuturet-or-what-futuret-obtained-in-a-background-thread-is-it-a-pattern).
Asynchronous architecture
[ "", "c#", "architecture", "asynchronous", "" ]
Are extension methods available on CE framework as well? I have an extension method for string that works fine in a windows forms project, however it wont build in PocketPC application. I figured this would be an easy thing to find out, however I was unable to find any info regarding extension methods on PocketPC. **Edit:** Ooops this was my mistake. I wrote the extension method in Visual Studio 2008, however the PocketPC project was being compiled in Visual Studio 2005, which I didn't realised. Well that's a hour of my life I'm never getting back. Thanks everyone for answers anyway.
Wanted to clear up a bit of confusion here. Extension methods are a feature of the compiler, not necessarily a particular version of the framework. Therefore, extension methods can be used on any platform where there is a version of the compiler that supports both extension methods and that platform. The C# 3.0 compiler can down target to 2.0 frameworks and supports extension methods so they should be available on the compact framework. The only thing the framework actually provides for extension methods is the ExtensionAttribute. However this doesn't have any functionality associated with it and can be defined by your application if it's not available. Here is a blog post I wrote on the subject * <http://blogs.msdn.com/jaredpar/archive/2007/11/16/extension-methods-without-3-5-framework.aspx>
Yes, they are supported in CF 3.5. If you are using CF 2.0 you will need to define the ExtensionAttribute and then they will work. ``` // this is a definition of a 3.5 class for use in 2.0. If we upgrade to target CF3.5, we will need to remove it... namespace System.Runtime.CompilerServices { public class ExtensionAttribute : Attribute { } } namespace TestExtension { public static class Extensions { public static int TestMethod(this string value) { return value.ToString(); } } } ```
C# Extension methods on PocketPC Windows CE
[ "", "c#", "compact-framework", "extension-methods", "pocketpc", "" ]
I'm currently using Prototype, but I'd like to rewrite this function to jQuery: ``` function post(div,url,formId) { new Ajax.Updater(div, url, { asynchronous:true, parameters:Form.serialize(formId) }); } ``` HTML example that goes with it: ``` <form method="post" action="" id="foo" onsubmit="post('result','getdata.php','foo');return false;"> <input type="text" name="data" /> </form> <div id="result"></div> ``` I've been looking at jQuery.load() and jQuery.post(), but I'm not sure which one to use and how exactly. Thanks in advance for your help.
With this HTML: ``` <form method="post" action="getdata.php" id="foo"> <input type="text" name="data" /> </form> <div id="result"></div> ``` You can do this with jQuery: ``` $(function() { // wait for the DOM to be ready $('#foo').submit(function() { // bind function to submit event of form $.ajax({ type: $(this).attr('method'), // get type of request from 'method' url: $(this).attr('action'), // get url of request from 'action' data: $(this).serialize(), // serialize the form's data success: function(responseText) { // if everything goes well, update the div with the response $('#result').html(responseText); } }); return false; // important: prevent the form from submitting }); }); ``` The reason I got rid of the `onsubmit` code is because it is considered bad practice to have inline JavaScript like that. You should strive to make your forms free of JavaScript and then bind all the JavaScript away from it. This is known as unobtrusive JavaScript and it is a Good Thing. **EDIT**: Since you have that code in many pages, this is a function that will do what you want using the same signature you currently have on the post function. I recommend you take a few hours to update all your forms over keeping this, but here it is anyways: ``` function post(div,url,formId) { $.post(url, $('#' + formId).serialize(), function(d) { $('#' + div).html(d); }); } ``` As far as your problem, the [livequery](http://docs.jquery.com/Plugins/livequery) plugin could help you there. Alternatively, it is as simple as encapsulating the binding code in a function and calling it whenever a form is added.
Use this and get rid of the onsubmit attribute in your HTML: ``` $(document).ready(function() { $("#foo").submit(function() { $.post($(this).attr("action"), $(this).serialize()); return false; // prevent actual browser submit }); }); ``` [jQuery serialize method docs](http://docs.jquery.com/Ajax/serialize)
Process form data using jQuery
[ "", "javascript", "jquery", "ajax", "prototypejs", "" ]
Let me preface this by saying I now realize how stupid I am and was. I have been developing for 1 year (to the day) and this was the first thing I wrote. I now have come back to it and I can't make heads or tails of it. It worked at one point on a very simple app but that was a while ago. Specifically I am having problems with `LocalDBConn` which uses `out` but for the life of me I can't remember why. Guidance, pointer's, refactoring, slaps up side the head are ALL welcome and appreciated! ``` public class MergeRepl { // Declare nessesary variables private string subscriberName; private string publisherName; private string publicationName; private string subscriptionDbName; private string publicationDbName; private MergePullSubscription mergeSubscription; private MergePublication mergePublication; private ServerConnection subscriberConn; private ServerConnection publisherConn; private Server theLocalSQLServer; private ReplicationDatabase localRepDB; public MergeRepl(string subscriber, string publisher, string publication, string subscriptionDB, string publicationDB) { subscriberName = subscriber; publisherName = publisher; publicationName = publication; subscriptionDbName = subscriptionDB; publicationDbName = publicationDB; //Create connections to the Publisher and Subscriber. subscriberConn = new ServerConnection(subscriberName); publisherConn = new ServerConnection(publisherName); // Define the pull mergeSubscription mergeSubscription = new MergePullSubscription { ConnectionContext = subscriberConn, DatabaseName = subscriptionDbName, PublisherName = publisherName, PublicationDBName = publicationDbName, PublicationName = publicationName }; // Ensure that the publication exists and that it supports pull subscriptions. mergePublication = new MergePublication { Name = publicationName, DatabaseName = publicationDbName, ConnectionContext = publisherConn }; // Create the local SQL Server instance theLocalSQLServer = new Server(subscriberConn); // Create a Replication DB Object to initiate Replication settings on local DB localRepDB = new ReplicationDatabase(subscriptionDbName, subscriberConn); // Check that the database exists locally CreateDatabase(subscriptionDbName); } public void RunDataSync() { // Keep program from appearing 'Not Responding' ///// Application.DoEvents(); // Does the needed Databases exist on local SQLExpress Install /////CreateDatabase("ContactDB"); try { // Connect to the Subscriber subscriberConn.Connect(); // if the Subscription exists, then start the sync if (mergeSubscription.LoadProperties()) { // Check that we have enough metadata to start the agent if (mergeSubscription.PublisherSecurity != null || mergeSubscription.DistributorSecurity != null) { // Synchronously start the merge Agent for the mergeSubscription // lblStatus.Text = "Data Sync Started - Please Be Patient!"; mergeSubscription.SynchronizationAgent.Synchronize(); } else { throw new ApplicationException("There is insufficient metadata to synchronize the subscription." + "Recreate the subscription with the agent job or supply the required agent properties at run time."); } } else { // do something here if the pull mergeSubscription does not exist // throw new ApplicationException(String.Format("A mergeSubscription to '{0}' does not exist on {1}", publicationName, subscriberName)); CreateMergeSubscription(); } } catch (Exception ex) { // Implement appropriaate error handling here throw new ApplicationException("The subscription could not be synchronized. Verify that the subscription has been defined correctly.", ex); //CreateMergeSubscription(); } finally { subscriberConn.Disconnect(); } } public void CreateMergeSubscription() { // Keep program from appearing 'Not Responding' // Application.DoEvents(); try { if (mergePublication.LoadProperties()) { if ((mergePublication.Attributes & PublicationAttributes.AllowPull) == 0) { mergePublication.Attributes |= PublicationAttributes.AllowPull; } // Make sure that the agent job for the mergeSubscription is created. mergeSubscription.CreateSyncAgentByDefault = true; // Create the pull mergeSubscription at the Subscriber. mergeSubscription.Create(); Boolean registered = false; // Verify that the mergeSubscription is not already registered. foreach (MergeSubscription existing in mergePublication.EnumSubscriptions()) { if (existing.SubscriberName == subscriberName && existing.SubscriptionDBName == subscriptionDbName && existing.SubscriptionType == SubscriptionOption.Pull) { registered = true; } } if (!registered) { // Register the local mergeSubscription with the Publisher. mergePublication.MakePullSubscriptionWellKnown( subscriberName, subscriptionDbName, SubscriptionSyncType.Automatic, MergeSubscriberType.Local, 0); } } else { // Do something here if the publication does not exist. throw new ApplicationException(String.Format( "The publication '{0}' does not exist on {1}.", publicationName, publisherName)); } } catch (Exception ex) { // Implement the appropriate error handling here. throw new ApplicationException(String.Format("The subscription to {0} could not be created.", publicationName), ex); } finally { publisherConn.Disconnect(); } } /// <summary> /// This will make sure the needed DataBase exists locally before allowing any interaction with it. /// </summary> /// <param name="whichDataBase">The name of the DataBase to check for.</param> /// <returns>True if the specified DataBase exists, False if it doesn't.</returns> public void CreateDatabase(string whichDataBase) { Database db; LocalDBConn(whichDataBase, out theLocalSQLServer, out localRepDB, out db); if (!theLocalSQLServer.Databases.Contains(whichDataBase)) { //Application.DoEvents(); // Create the database on the instance of SQL Server. db = new Database(theLocalSQLServer, whichDataBase); db.Create(); } localRepDB.Load(); localRepDB.EnabledMergePublishing = false; localRepDB.CommitPropertyChanges(); if (!mergeSubscription.LoadProperties()) { CreateMergeSubscription(); } } private void LocalDBConn(string databaseName, out Server server, out ReplicationDatabase replicationDatabase, out Database db) { db = server.Databases[replicationDatabase.Name]; } /// <summary> /// Checks for the existince of the Publication. If there is one it verify's Allow Pull is set /// </summary> /// <returns>True if Publication is present. False if not.</returns> public bool CheckForPublication() { // If LoadProperties() returns TRUE then the Publication exists and is reachable if (mergePublication.LoadProperties()) return true; if ((mergePublication.Attributes & PublicationAttributes.AllowPull) == 0) { mergePublication.Attributes |= PublicationAttributes.AllowPull; } return false; } // end CheckForPublication() /// <summary> /// Checks for the existence of a Subscription. /// </summary> /// <returns>True if a Subscription is present. False if not</returns> public bool CheckForSubscription() { // Check for the existence of the Subscription return mergeSubscription.IsExistingObject; } // end CheckForSubscription() } ``` ## Edit 1 Opps, I forgot the specific errors. On `server` and `replicationDatabase` I am getting a *"Out parameter might not be initialized before accessing"* ``` private void LocalDBConn(string databaseName, out Server server, out ReplicationDatabase replicationDatabase, out Database db) { db = server.Databases[replicationDatabase.Name]; } ```
Looks like you'd be safe to remove the out's. I'm not sure how that even compiled, unless maybe it was with VS2003 and the compiler didn't check for this type of error. From MSDN: Although variables passed as out arguments do not have to be initialized before being passed, the called method is required to assign a value before the method returns. ``` private void LocalDBConn(string databaseName, Server server, ReplicationDatabase replicationDatabase, out Database db) { db = server.Databases[replicationDatabase.Name]; } ``` or ``` private Database LocalDBConn(string databaseName, Server server, ReplicationDatabase replicationDatabase) { return server.Databases[replicationDatabase.Name]; } ``` Then update your code in CreateDatabase to: ``` Database db; LocalDBConn(whichDataBase, theLocalSQLServer, localRepDB, out db); ``` or ``` Database db = LocalDBConn(whichDataBase, theLocalSQLServer, localRepDB); ```
``` private void LocalDBConn(string databaseName, out Server server, out ReplicationDatabase replicationDatabase, out Database db) { db = server.Databases[replicationDatabase.Name]; } ``` This method will not build because the [out parameters](http://msdn.microsoft.com/en-us/library/t3c3bfhx(VS.71).aspx) are not initialized before the method returns. An out parameter allows the caller to pass an uninstantiated object into the method, which the method must then initialize through all paths before it returns (excluding if the method throws an exception). Basically, an out parameter is a statement by the method saying "I will instantiate this object before returning". In LocalDBConn, you are not doing this. In the C# 3.0 language specification this detailed in section 5.1.6.
Creating and executing a Merge Replication programmatically
[ "", "c#", ".net", "winforms", "refactoring", "replication", "" ]
I have a string, example: ``` s = "this is a string, a" ``` Where a `','` (comma) will always be the 3rd to the last character, aka `s[-3]`. I am thinking of ways to remove the ',' but can only think of converting the string into a list, deleting it, and converting it back to a string. This however seems a bit too much for simple task. How can I accomplish this in a simpler way?
Normally, you would just do: ``` s = s[:-3] + s[-2:] ``` The `s[:-3]` gives you a string up to, but not including, the comma you want removed (`"this is a string"`) and the `s[-2:]` gives you another string starting one character beyond that comma (`" a"`). Then, joining the two strings together gives you what you were after (`"this is a string a"`).
A couple of variants, using the "delete the last comma" rather than "delete third last character" are: ``` s[::-1].replace(",","",1)[::-1] ``` or ``` ''.join(s.rsplit(",", 1)) ``` But these are pretty ugly. Slightly better is: ``` a, _, b = s.rpartition(",") s = a + b ``` This may be the best approach if you don't know the comma's position (except for last comma in string) and effectively need a "replace from right". However [Anurag's answer](https://stackoverflow.com/questions/1010961/string-slicing-python/1010973#1010973) is more pythonic for the "delete third last character".
Ways to slice a string?
[ "", "python", "" ]
while programming in c++, Most of the times i get 'some symbol' has already been defined see previous definition of 'some symbol' I think this happens because improper order of headers file included. How can i find out all the definitions of 'some symbol' Thanks in advance, Uday EDIT: I am using visual studio I remember some command some thing like dumpbin /exports (I dont remember exactly) to get all the definition
Translating C++ into an executbale has two steps. In step one, the compiler works linearly through the inputs (typically .cpp files and the headers they include). In step 2, the linker combines the results from step 1. From your description of "symbol defined before", I conclude the problem must occur within a .cpp file, as those are processed linearly. dumpbin /exports works on the output of step 1, which you probably won't have. Header inclusion could be the culprit, as that's an early phase of compilation. You want the preprocessed input. IIRC, you can get that with the /EP switch.
That usually happens due to a couple of common problems: * you are redefining the same symbol * you are including a header file many times and it does not have include guards * you are incorrectly forward declaring with an incompatible type and then including I would start trying to fix the second. Make sure that all headers have include guards so that if you include them from different places it won't try to redefine the symbols: ``` #ifndef HEADER_FILE_NAME_GUARD // or something alike #define HEADER_FILE_NAME_GUARD // rest of file #endif ``` If you need to order your includes then you will run into troubles later, make sure that you can and do include all your dependencies at all places. (Or forward declare if you can)
see previous definition of 'some symbol'
[ "", "c++", "visual-studio", "" ]
As a long time user of Visual Studio, I feel comfortable using this as my primary IDE for editing code (I primarily code in C#/ASP.NET). Lately I've been looking more in depth into the Google Web Toolkit (or GWT) as a potential tool for building rapid web client tools for the web. I would therefore like to know whether it is possible to edit Java syntax, and otherwise set Visual Studio up to built web applications for GWT?
The option i m using is using Eclipse with an IntelliJ Idea key mapping ( i m a resharper fan and I miss it) Another option is take the plunge and get IntelliJ Idea, its a fantastic IDE and it was really easy to get used to it, it has some nice pluggins for GWT development too Cheers
What is Visual Studio's support for Java like, I assuming that its GWT support is not as good. ;) I think you are better off using an IDE which actually supports GWT. You could have a look at <http://www.jetbrains.com/idea/features/gwt.html> The demo is rather old (from 2006) but if you haven't seen IntelliJ it might be interesting.
Is it possible to use Visual Studio as an IDE for Google Web Toolkit?
[ "", "java", "visual-studio", "ide", "gwt", "" ]
I have a Visual Studio 2008 solution that contains a handful of projects. One project contains a [WCF Service](http://en.wikipedia.org/wiki/Windows_Communication_Foundation#WCF_Service) I'm deploying. That WCF Service references some code in one of the other projects. That code is trying to read a file that's in a folder in the WCF project. Pseudo-project structure: ``` Solution Project1 myclass.cs string file = Server.Mappath(""); Project2 filefolder myfile.txt ``` What is the correct syntax to put in the Mappath? I've tried all different variations such as: ``` ".filefolder/myfile.txt" "/filefolder/myfile.txt" "./filefolder/myfile.txt" "~/filefolder/myfile.txt" ``` None seem to be able to reach the file. One thing I thought of: Visual Studio 2008 runs the project and WCF in its own sandbox in [IIS](http://en.wikipedia.org/wiki/Internet_Information_Services). Could that be the issue? Would it work if setup and deployed in regular IIS?
The problem is that when invoking the WCF, the file system runs all the way out to the bin/Debug folder. So trying to MapMath from there doesnt work. Backtracking up the path worked: ``` filedata = File.ReadAllBytes("../../filefolder/myfile.txt"); ``` That worked. Thanks for all the help guys!
``` var serverPath = System.Web.Hosting.HostingEnvironment.MapPath("~/filefolder/myfile.txt"); ```
C#: How can Server.Mappath read a file?
[ "", "c#", "wcf", "file-io", "mapping", "" ]
I am getting the following error: Parse error: syntax error, unexpected T\_STRING, expecting T\_OLD\_FUNCTION or T\_FUNCTION or T\_VAR or '}' The referenced lines are: ``` class Food { private $q = array(); private $nutrients = array(); ... ``` How can I fix this error?
you can only use "private" in a php 5 environment. It looks like you're running that in PHP 4.
I think you're missing an ending curly brace '}'. (at least you did in the provided code). But it's hard to tell with as less code as you provided. Please provide more code on the issue.
PHP Class error
[ "", "php", "" ]
I have a piece of java code which reads strings from a file and creates a map out of the strings. As this code depends on a file, unit testing is clumsy. How does one design such pieces so that code can be unit tested? One approach that I can think of is, instead of this piece taking a file as an argument it can take an input stream. In actual scenario, pass the file input stream, while unit testing pass an input stream created from a string. But, this looks like an over kill to me. Is there a better way?
Look at it this way: no matter how you reorganize your code, the test data has to come from *some* file. I see 2 variants: 1. Data is encoded in-place, in one of the .java unit test source code files. It works only for small test data sets. You would need to refactor your code to take input stream and have another wrapper that works with file, as you described. 2. Test data file. You have to create a project-wide convention where to keep your test data files. Their location may be relative to the jave project location, or under a common test data files root. In any case, it helps to have a utility method that returns a full test data file path given a "logical" file name. It seems like in your case (just one test, a hundred words) the first solution may be enough. Yes, you would need to refactor the code a little. The second solution is more generic and personally I find it much more practical and applicable. Some people would say this is not a unit test if it works with data files. Well, it's a matter of definition of "unit test", and is quite irrelevant. If you need to test your code, just find the best / most convenient way *for your project*.
It's a design error not to provide a function that reads from an `InputStream` if all you do with the file is read it. Therefore, modify the function to take an `InputStream`, and provide a wrapper that takes a `File`. Using a [ByteArrayInputStream](http://java.sun.com/javase/6/docs/api/java/io/ByteArrayInputStream.html) or a StringInputStream to test it is fine.
File reading and testable code
[ "", "java", "unit-testing", "" ]
I've got the latest Mysql connector that allows you to use the Visual Studio Entity Framework designer. It's been working great, but I just added a stored proc. The Server Explorer loaded it up fine with the parameters specified, but then I added it to the Entity Model & the code it generates doesn't have any input parameters. Here's the stored procedure ``` CREATE PROCEDURE `GetViewableMenuNodes`(IN siteId INT, IN parentId INT, IN userName varchar(255)) BEGIN select m.* from menunode m where m.siteid = siteId and m.showinmenu = 1 and m.parentid = parentId and m.viewername = userName; END ``` and this is the code generated by the model ``` public global::System.Data.Objects.ObjectResult<MenuNode> GetViewableMenuNodes() { return base.ExecuteFunction<MenuNode>("GetViewableMenuNodes"); } ```
Check out this bug entry: <http://bugs.mysql.com/bug.php?id=44985> Sorry about your luck. Welcome to the club. Apparently having proper support for stored procedures in MySQL from the MySQL Connector/.NET Entity Framework is not available. As you can see from the dates in the thread there has been an incredibly slow response to introduce the feature.
In case you find this helpful, here is the approach I use for working with stored procedures with parameters in MySQL from the MySQL Connector/.NET Entity Framework provider. I call ExecuteStoreQuery(). This liberates me from having to deal with the challenges of mapping procedures with parameters in the model. This works for our needs. ``` public IList<SearchResultsMember> SearchMembers(int memberID, string countryCode, string regionCode, string cityCode, float distanceKm, int genderID, int ageMin, int ageMax, int offsetRowIndex, int maxRows) { MySqlParameter[] queryParams = new MySqlParameter[] { new MySqlParameter("memberIDParam", memberID), new MySqlParameter("countryCodeParam", countryCode), new MySqlParameter("regionCodeParam", regionCode), new MySqlParameter("cityCodeParam", cityCode), new MySqlParameter("distanceKmParam", distanceKm), new MySqlParameter("genderIDParam", genderID), new MySqlParameter("ageMinParam", ageMin), new MySqlParameter("ageMaxParam", ageMax), new MySqlParameter("offsetRowIndexParam", offsetRowIndex), new MySqlParameter("maxRowsParam", maxRows) }; StringBuilder sb = new StringBuilder(); sb.Append("CALL search_members(@memberIDParam, @countryCodeParam, @regionCodeParam, @cityCodeParam, @distanceKmParam, @genderIDParam, @ageMinParam, @ageMaxParam, @offsetRowIndexParam, @maxRowsParam)"); string commandText = sb.ToString(); var results = _context.ExecuteStoreQuery<SearchResultsMember>(commandText, queryParams); return results.ToList(); } ```
Using the entity framework with a MySQL DB and the model designer doesn't pickup stored proc parameters
[ "", "c#", "mysql", "entity-framework", "" ]
I'm writing a Java applet to run differently under different hardware. For instance if I know a computer has a large amount of RAM but a weak processor, I can alter the balance of some time-memory trade-offs. Being able to discover the exact make and model of the CPU on which the applet is running could be helpful. Having such information would allow me to benchmark my software against different systems and find bottlenecks. Generally what I'm looking for is: * Number of cores and/or processors * 32 bit vs 64 bit CPU * CPU Cache line size * Size of L1, L2, L3 cache * Set associativity of cache * Size of TLB * Exact Make/Model information on the CPU * FSB information * Amount of RAM * Amount of swap/virtual memory * The JVM in which the applet is being run * Operating System running JVM * System Load * Number of used/unused Kernal threads * Bandwidth of internet connection * Memory available * Graphics cards in use * If Operating System is being visualised * Network resource in use Is any of this information baked into Java Applets. Are there libraries for finding any of this information? Applet benchmarking tools to discover/guess some of it? Any clever tricks you can think of? Are their any aspects of computer hardware which are blocking. That is, could a Java applet detect that something is in use or unavailable by trying to access it and being denied (maybe a particular TCP port or graphics accelerator). Disclaimer: I know that caring about the hardware goes against the Java ideology of not caring about the hardware. While comments point this out may be helpful for other readers that see this question, please note that such answers are not what I am looking for. **EDIT** Added additional information: **java.lang.[management](http://java.sun.com/javase/6/docs/api/java/lang/management/package-summary.html)** provides all sorts of information on the system which the JVM is running on. **java.lang.management.[OperatingSystemMXBean](http://java.sun.com/javase/6/docs/api/java/lang/management/OperatingSystemMXBean.html)** provides: 1. [getAvailableProcessors()](http://java.sun.com/javase/6/docs/api/java/lang/management/OperatingSystemMXBean.html#getAvailableProcessors()) The number of available processors equivalent [Runtime.availableProcessors()](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#availableProcessors()) 2. [getSystemLoadAverage()](http://java.sun.com/javase/6/docs/api/java/lang/management/OperatingSystemMXBean.html#getSystemLoadAverage()) The average load on the system the system load average for the last minute. **java.lang.management.[ManagementFactory](http://java.sun.com/javase/6/docs/api/java/lang/management/ManagementFactory.html#getMemoryMXBean())** 1. **[getGarbageCollectorMXBeans()](http://java.sun.com/javase/6/docs/api/java/lang/management/GarbageCollectorMXBean.html)** returns a list ofGarbageCollectorMXBeans. Each [GarbageCollectorMXBean](http://java.sun.com/javase/6/docs/api/java/lang/management/GarbageCollectorMXBean.html) can be queried for the following information: 1. [getCollectionCount()](http://java.sun.com/javase/6/docs/api/java/lang/management/GarbageCollectorMXBean.html#getCollectionCount()) number of gc which have occured using this bean. 2. [getCollectionTime()](http://java.sun.com/javase/6/docs/api/java/lang/management/GarbageCollectorMXBean.html#getCollectionTime()) approximate accumulated time elapsed between gc's in milliseconds. (Note: The Java virtual machine implementation may use a high resolution timer to measure the elapsed time.) 3. [getName()](http://java.sun.com/javase/6/docs/api/java/lang/management/MemoryManagerMXBean.html#getName()) the name of the memory manager. 4. [getMemoryPoolNames()](http://java.sun.com/javase/6/docs/api/java/lang/management/MemoryManagerMXBean.html#getMemoryPoolNames()) the memory pools that this gc manages. 2. **[getThreadMXBean()](http://java.sun.com/javase/6/docs/api/java/lang/management/ManagementFactory.html#getThreadMXBean())** returns the [ThreadMXBean](http://java.sun.com/javase/6/docs/api/java/lang/management/ThreadMXBean.html) which provides: 1. [getCurrentThreadCpuTime()](http://java.sun.com/javase/6/docs/api/java/lang/management/ThreadMXBean.html#getCurrentThreadCpuTime()) Returns the total CPU time for the current thread in nanoseconds. If the implementation distinguishes between user mode time and system mode time, the returned CPU time is the amount of time that the current thread has executed in user mode or system mode. 3. **[getRuntimeMXBean](http://java.sun.com/javase/6/docs/api/java/lang/management/RuntimeMXBean.html)** returns [RuntimeMXBean](http://java.sun.com/javase/6/docs/api/java/lang/management/RuntimeMXBean.html) 1. [getUptime()](http://java.sun.com/javase/6/docs/api/java/lang/management/RuntimeMXBean.html#getStartTime()) uptime of the Java virtual machine in milliseconds. 2. [getStartTime()](http://java.sun.com/javase/6/docs/api/java/lang/management/RuntimeMXBean.html#getStartTime()) start time of the Java virtual machine in milliseconds. 3. [getInputArguments()](http://java.sun.com/javase/6/docs/api/java/lang/management/RuntimeMXBean.html#getInputArguments()) Returns the input arguments passed to the Java virtual machine which does not include the arguments to the main method. 4. **[getCompilationMXBean](http://java.sun.com/javase/6/docs/api/java/lang/management/CompilationMXBean.html)** returns the [CompilationMXBean](http://java.sun.com/javase/6/docs/api/java/lang/management/CompilationMXBean.html) 1. [getName()](http://java.sun.com/javase/6/docs/api/java/lang/management/CompilationMXBean.html#getName()) the name of the JIT 2. [getTotalCompilationTime()](http://java.sun.com/javase/6/docs/api/java/lang/management/CompilationMXBean.html#getTotalCompilationTime()) time in milliseconds it took to compile your code.
The ones that are quite simple to obtain are the information accessible via the [`System.getProperties`](http://java.sun.com/javase/6/docs/api/java/lang/System.html#getProperties()) (or [`System.getProperty`](http://java.sun.com/javase/6/docs/api/java/lang/System.html#getProperty(java.lang.String))) method. For example, `os.name` will return the name of the operating system. On my system, I got the `Windows XP` as the result. Some information available by [`System.getProperties`](http://java.sun.com/javase/6/docs/api/java/lang/System.html#getProperties()), which seems to be accessible by the applet include: * `java.vm.version` -- version of the JVM. * `java.vm.vendor` -- vendor name of the JVM. * `java.vm.name` -- name of the JVM. * `os.name` -- name of the operating system. (e.g. `Windows XP`) * `os.arch` -- architecture of system. (e.g. `x86`) * `os.version` -- version of the operating system. (e.g. `5.1`) * `java.specification.version` -- JRE specification version. The above is not a comprehensive list, but it can give some ideas about what the system is like. It should be noted that not all properties that are available through the `System.getProperties` can be read, as for some properties, the security manager will cause an `AccessControlException`. When I tried to read the `java.home` property, an exception was thrown. To obtain those properties which cause a `AccessControlException` by default, one would probably would have to be steps taken to give permissions to the applet to perform some of those information. (Here is a link to the [Security Restrictions](http://java.sun.com/docs/books/tutorial/deployment/applet/security_practical.html) section of the [Lesson: Applets](http://java.sun.com/docs/books/tutorial/deployment/applet/index.html) from [The Java Tutorials](http://java.sun.com/docs/books/tutorial/index.html).) The `Runtime` class can provide information such as: * Number of processors (or cores, or logical threads, presumably) available to the JVM by the [`Runtime.availableProcessors`](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#availableProcessors()) method. * Java virtual machine's memory information, such as [`freeMemory`](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#freeMemory()), [`maxMemory`](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#maxMemory()), and [`totalMemory`](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#totalMemory()). Beyond the information provided by the default `System` and `Runtime` classes would probably require making calls to the operating system, which would be platform-dependent. **Edit** The [Getting System Properties](http://java.sun.com/docs/books/tutorial/deployment/applet/properties.html) page from [Lesson: Applets](http://java.sun.com/docs/books/tutorial/deployment/applet/index.html) of [The Java Tutorials](http://java.sun.com/docs/books/tutorial/index.html) provides a list of properties which can be read, and a list of properties that cannot be read by applets.
Here are some more: [java.awt.Toolkit](http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Toolkit.html) may be able to tell the screen resolution and maybe even something more about the graphic card (from the used color model). You can also allocate some bigger array of bytes and measure access times to get approximate information about the cache (in the past we played with this to check if memory cache tricks work with Java at all; they do). However these tests may hang your applet for some time so you need to inform the user that your are doing. Applets that do modelling can measure the ratio of passed virtual time over the passed real time. After detecting a slow system, the applet can increase integration step and similar constants to requires less CPU time, even with the expense of the less perfect output. [Here](http://ultrastudio.org/en/Special%3aReview?review=8362de82-fc7d-3a1b-a245-812417fca6a3&pkg=0&cls=1&view=1) there is an example of such self tuning code that adjusts the step speed in the simulation of the bird flock behavior.
How many hardware details can a Java Applet Discover?
[ "", "java", "operating-system", "benchmarking", "" ]
This question is just for my better understanding of static variables in C++. I thought I could return a reference to a local variable in C++ if it was declared static since the variable should live-on after the function returns. Why doesn't this work? ``` #include <stdio.h> char* illegal() { char * word = "hello" ; return word ; } char* alsoNotLegal() { static char * word = "why am I not legal?" ; return word ; } int main() { // I know this is illegal //char * ill = illegal(); //ill[ 0 ] = '5' ; //puts( ill ) ; // but why is this? I thought the static variable should "live on" forever - char * leg = alsoNotLegal() ; leg[ 0 ] = '5' ; puts( leg ) ; } ```
The two functions are not itself illegal. First, you in both case return a copy of a pointer, which points to an object having static storage duration: The string literal will live, during the whole program duration. But your `main` function is all about undefined behavior. You are not allowed to write into a string literal's memory :) What your main function does can be cut down to equivalent behavior ``` "hello"[0] = '5'; "why am I not legal?"[0] = '5'; ``` Both are undefined behavior and on some platforms crash (good!). **Edit**: Note that string literals have a const type in C++ (not so in C): `char const[N]`. Your assignment to a pointer to a non-const character triggers a deprecated conversion (which a good implementation will warn about, anyway). Because the above writings to that const array *won't* trigger that conversion, the code will mis-compile. Really, your code is doing this ``` ((char*)"hello")[0] = '5'; ((char*)"why am I not legal?")[0] = '5'; ``` Read [`C++ strings: [] vs *`](https://stackoverflow.com/questions/308279/c-strings-vs/308724#308724)
Only the pointer is static and it points to a constant string. Doing leg[ 0 ] = '5' is not ok as it modifies the constant string. static make little difference in this case, this is really the same: ``` char* alsoNotLegal() { return "why am I not legal?"; } ```
Returning reference to static local variable in C++
[ "", "c++", "" ]
I am looking for a PHP function that creates a short hash out of a string or a file, similar to those URL-shortening websites like [tinyurl.com](http://tinyurl.com) The hash should not be longer than 8 characters.
URL shortening services rather use a auto incremented integer value (like a supplementary database ID) and encode that with [Base64](http://en.wikipedia.org/wiki/Base64) or other encodings to have more information per character (64 instead of just 10 like digits).
TinyURL doesn't hash anything, it uses Base 36 integers (or even base 62, using lower and uppercase letters) to indicate which record to visit. Base 36 to Integer: ``` intval($str, 36); ``` Integer to Base 36: ``` base_convert($val, 10, 36); ``` So then, instead of redirecting to a route like `/url/1234` it becomes `/url/ax` instead. This gives you a whole lot more use than a hash will, as there will be no collisions. With this you can easily check if a url exists and return the proper, existing, ID in base 36 without the user knowing that it was already in the database. Don't hash, use other bases for this kind of thing. (It's faster and can be made collision-proof.)
PHP short hash like URL-shortening websites
[ "", "php", "hash", "" ]
I have the following function ``` ALTER FUNCTION [dbo].[ActualWeightDIMS] ( -- Add the parameters for the function here @ActualWeight int, @Actual_Dims_Lenght int, @Actual_Dims_Width int, @Actual_Dims_Height int ) RETURNS varchar(50) AS BEGIN DECLARE @ActualWeightDIMS varchar(50); --Actual Weight IF (@ActualWeight is not null) SET @ActualWeightDIMS = @ActualWeight; --Actual DIMS IF (@Actual_Dims_Lenght is not null) AND (@Actual_Dims_Width is not null) AND (@Actual_Dims_Height is not null) SET @ActualWeightDIMS= @Actual_Dims_Lenght + 'x' + @Actual_Dims_Width + 'x' + @Actual_Dims_Height; RETURN(@ActualWeightDIMS); END ``` but when i tried to use it, i got the following error "Conversion failed when converting the varchar value 'x' to data type int." when i use the following select statement ``` select BA_Adjustment_Detail.ID_Number [ID_Number], BA_Adjustment_Detail.Submit_Date [Submit_Date], BA_Category.Category [category], BA_Type_Of_Request.Request [Type_Of_Request], dbo.ActualWeightDIMS(BA_Adjustment_Detail.ActualWeight,BA_Adjustment_Detail.Actual_Dims_Lenght,BA_Adjustment_Detail.Actual_Dims_Width,BA_Adjustment_Detail.Actual_Dims_Height) [Actual Weight/DIMS], BA_Adjustment_Detail.Notes [Notes], BA_Adjustment_Detail.UPSCustomerNo [UPSNo], BA_Adjustment_Detail.TrackingNo [AirbillNo], BA_Adjustment_Detail.StoreNo [StoreNo], BA_Adjustment_Detail.Download_Date [Download_Date], BA_Adjustment_Detail.Shipment_Date[ShipmentDate], BA_Adjustment_Detail.FranchiseNo [FranchiseNo], BA_Adjustment_Detail.CustomerNo [CustomerNo], BA_Adjustment_Detail.BillTo [BillTo], BA_Adjustment_Detail.Adjustment_Amount_Requested [Adjustment_Amount_Requested] from BA_Adjustment_Detail inner join BA_Category on BA_Category.ID = BA_Adjustment_Detail.CategoryID inner join BA_Type_Of_Request on BA_Type_Of_Request.ID = BA_Adjustment_Detail.TypeOfRequestID ``` What I want to do is if the ActualWeight is not null then return the ActualWeight for the "Actual Weight/DIMS" or else use the Actual\_Dims\_Lenght, Width and Height. If it is DIMS then i want to format the output to be LenghtxWidhtxHeight (15x10x4). The ActualWeight, Adcutal\_Dims\_Lenght, Width and Height are all int (integer) value but the output for "Actual Weight/DIMS" should be varchar(50). Where am i getting it wrong? thank edit: The user can only pick either Weight or DIMS on ASP.net page and if user selected DIMS then they must supply Length, Width and Height. Else it will throw error on the ASP.net page. Should i worry about it on the sql side?
A couple of quick notes: * It's "length" not "lenght" * Table aliases in your query would probably make it a lot more readable Now onto the problem... You need to explicitly convert your parameters to VARCHAR before trying to concatenate them. When SQL Server sees @my\_int + 'X' it thinks you're trying to add the number "X" to @my\_int and it can't do that. Instead try: ``` SET @ActualWeightDIMS = CAST(@Actual_Dims_Lenght AS VARCHAR(16)) + 'x' + CAST(@Actual_Dims_Width AS VARCHAR(16)) + 'x' + CAST(@Actual_Dims_Height AS VARCHAR(16)) ```
If you are using **SQL Server 2012+** you can use [**CONCAT**](https://msdn.microsoft.com/en-IN/library/hh231515.aspx) function in which we don't have to do any explicit conversion ``` SET @ActualWeightDIMS = Concat(@Actual_Dims_Lenght, 'x', @Actual_Dims_Width, 'x' , @Actual_Dims_Height) ```
How to Concatenate Numbers and Strings to Format Numbers in T-SQL?
[ "", "sql", "t-sql", "" ]
I'd like to bind a `ComboBox` to a `DataTable` (I cannot alter its original schema) ``` cbo.DataSource = tbldata; cbo.DataTextField = "Name"; cbo.DataValueField = "GUID"; cbo.DataBind(); ``` I want the `ComboBox` show `tbldata.Name + tbldata.Surname`. Of course adding the new name+surname as a field to the `tbldata` just before binding is possible, but I am hoping for a more elegant solution along the lines of (pseudocode) ``` cbo.DataTextField = "Name"; cbo.DataTextField += "Surname"; ```
The calculated column solution is probably the best one. But if you can't alter the data table's schema to add that, you can loop through the table and populate a new collection that will serve as the data source. ``` var dict = new Dictionary<Guid, string>(); foreach (DataRow row in dt.Rows) { dict.Add(row["GUID"], row["Name"] + " " + row["Surname"]); } cbo.DataSource = dict; cbo.DataTextField = "Value"; cbo.DataValueField = "Key"; cbo.DataBind(); ``` Obviously this isn't as performant as binding directly to the DataTable but I wouldn't worry about that unless the table has thousands of rows.
The easiest way is to create a new calculated column in the DataTable, using the Expression property : ``` tbldata.Columns.Add("FullName", typeof(string), "Name + ' ' + Surname"); ... cbo.DataTextField = "FullName"; ```
How do I bind a ComboBox so the displaymember is concat of 2 fields of source datatable?
[ "", "c#", "data-binding", "combobox", "" ]
``` class A { public override int GetHashCode() { return 1; } } class B : A { public override int GetHashCode() { return ((object)this).GetHashCode(); } } new B().GetHashCode() ``` this overflows the stack. How can I call `Object.GetHashCode()` from `B.GetHashCode()`? edit: `B` now inherits from `A`.
(edit - misread question) If you want to get the original `object.GetHashCode()` version; you can't - at least, not unless `A` makes it available via something like: ``` protected int GetBaseHashCode() { return base.GetHashCode();} ``` (and have `B` call `GetBaseHashCode()`). The reason it overflows is that `GetHashCode` is (obviously) virtual - it doesn't matter if you cast it to `object`; it still starts at the most-derived implementation in the actual object, i.e. `B.GetHashCode()` (hence the explosion).
You can use `RuntimeHelpers.GetHashCode(object)` to get the original hash code of the object: ``` class A { public override int GetHashCode() { Console.WriteLine("base hashcode is: " + base.GetHashCode()); return 1; } } class Program { public static void Main(string[] args) { A a = new A(); Console.WriteLine("A's hashcode: " + a.GetHashCode()); Console.WriteLine("A's original hashcode: " + RuntimeHelpers.GetHashCode(a)); } } ``` This produces the following result: > base hashcode is: 54267293 > A's hashcode: 1 > A's original hashcode: 54267293 If you take a look at `RuntimeHelpers.GetHashCode(object)` in Reflector, you'll see that it calls the internal static method `object.InternalGetHashCode(object)`. If you'd like to know more, have a look at [this question](https://stackoverflow.com/questions/720177/default-implementation-for-object-gethashcode) regarding the default implementation of GetHashCode.
How to call a second-level base class method like base.base.GetHashCode()
[ "", "c#", "inheritance", "" ]
I need to parse potentially huge XML files, so I guess this rules out DOM parsers. Is out there any good lightweight SAX parser for C++, comparable with TinyXML on footprint? The structure of XML is very simple, no advanced things like namespaces and DTDs are needed. Just elements, attributes and cdata. I know about Xerces, but its sheer size of over 50mb gives me shivers. Thanks!
If you are using C, then you can use [LibXML](http://www.xmlsoft.org/) from the [Gnome](http://www.gnome.org) project. You can choose from DOM and SAX interfaces to your document, plus lots of additional features that have been developed over years. If you really want C++, then you can use [libxml++](http://libxmlplusplus.sourceforge.net/), which is a C++ OO wrapper around LibXML. The library has been proven again and again, is high performance, and can be compiled on almost any platform you can find.
I like ExPat <http://expat.sourceforge.net/> It is C based but there are several C++ wrappers around to help.
A lightweight XML parser efficient for large files?
[ "", "c++", "xml", "parsing", "sax", "saxparser", "" ]
I have a multi page form which uses multiple tables in mysql for the entered values. One of the pages has a form which needs to have the option of enabling the user to click a + to add an extra line if they want to include extra information. There can be any number of lines added. When the user clicks the +, jquery and php inserts the current userid in a row in the database table, this is then updated when more information is entered. The problem I've got is to how to insert any number of rows for that particular id - when the data is entered, a blur event sends the data to the php code for updating the database. However, the problem I have is that it will update ALL the rows with that particular user id and not the current one. What would be the best way of taking the data entered on the new rows and updating the database - I assume that I will have to use the ID value rather than userid value as that will be unique, or is there another way of doing it? Thanks for any suggestions you can give, this one is clouding my mind currently...
Well, I think that you need to use a pair of identifiers, your userid and the field id. For editing only filedid would be enought but when you need to list all the user fields another reference will be necessary.
You are correct when you state that you should use the primary key of the table you are updating, rather than the foreign key (UserId in your case) which occurs many times on your table. This guarantees you will update the row you expect. An alternative would be to narrow down the rows you update - for example by only updating the most recent / the one with the highest ID or using a combination of fields that make the record unique. However, using the primary key is the best way to solve your issue.
Jquery -> php -> mysql and dynamic form fields
[ "", "php", "jquery", "mysql", "forms", "dynamic", "" ]
I'm writing a parser for an internal xml-based metadata format in python. I need to provide different classes for handling different tags. There will be a need for a rather big collection of handlers, so I've envisioned it as a simple plugin system. What I want to do is simply load every class in a package, and register it with my parser. My current attempt looks like this: (Handlers is the package containing the handlers, each handler has a static member tags, which is a tuple of strings) ``` class MetadataParser: def __init__(self): #... self.handlers={} self.currentHandler=None for handler in dir(Handlers): # Make a list of all symbols exported by Handlers if handler[-7:] == 'Handler': # and for each of those ending in "Handler" handlerMod=my_import('MetadataLoader.Handlers.' + handler) self.registerHandler(handlerMod, handlerMod.tags) # register them for their tags # ... def registerHandler(self, handler, tags): """ Register a handler class for each xml tag in a given list of tags """ if not isSequenceType(tags): tags=(tags,) # Sanity check, make sure the tag-list is indeed a list for tag in tags: self.handlers[tag]=handler ``` However, this does not work. I get the error `AttributeError: 'module' object has no attribute 'tags'` What am I doing wrong?
First off, apologies for poorly formated/incorrect code. Also thanks for looking at it. However, the culprit was, as so often, between the chair and the keyboard. I confused myself by having classes and modules of the same name. The result of my\_import (which I now realize I didn't even mention where it comes from... It's from SO: [link](https://stackoverflow.com/questions/211100/pythons-import-doesnt-work-as-expected/211101#211101)) is a module named for instance areaHandler. I want the class, also named areaHandler. So I merely had to pick out the class by eval('Handlers.' + handler + '.' + handler). Again, thanks for your time, and sorry about the bandwidth
Probably one of your `handlerMod` modules does not contain any `tags` variable.
Simple python plugin system
[ "", "python", "" ]
> **Possible Duplicate:** > [How are echo and print different in PHP?](https://stackoverflow.com/questions/234241/how-are-echo-and-print-different-in-php) UPDATE : I found to my relief an **exact** [duplicate](https://stackoverflow.com/questions/234241/how-are-echo-and-print-different-in-php) (it wasn't showing up when I typed this question at first, I found it with ... google): Please vote with me to close this question, because it's tiring, go hunt that other poor guy a bit ;-) --- Is there any difference between `print` and `echo` in PHP? If so, which should I use and when? If not, why are there two keywords? UPDATE : At the downvoters : please read the SO faq. SO was setup also to capture googleable questions. so you shouldn't downvote for that, this question is a valid question, answered on a lot of places and now on SO too. Of course you can downvote for another reason, but please leave a comment in the lines of -1 : downvoted for .. , cause for now, I'm not understanding the downvotes.
From [this link](http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40), suggested by the [PHP manual entry for the `echo()` function](http://www.php.net/echo): > 1. Speed. There is a difference between the two, but speed-wise it > should be irrelevant which one you > use. echo is marginally faster since > it doesn't set a return value if you > really want to get down to the nitty > gritty. > 2. Expression. print() behaves like a function in that you can do: $ret = > print "Hello World"; And $ret will be > 3. That means that print can be used as part of a more complex expression > where echo cannot. An example from > the PHP Manual: > > $b ? print "true" : print "false"; > > print is also part of the precedence > table which it needs to be if it is > to be used within a complex > expression. It is just about at the > bottom of the precedence list though. > Only "," AND, OR and XOR are lower. > > 3. Parameter(s). The grammar is: echo expression [, expression[, expression] > ... ] But echo ( expression, > expression ) is not valid. This would > be valid: echo ("howdy"),("partner"); > the same as: echo "howdy","partner"; > (Putting the brackets in that simple > example serves no purpose since there > is no operator precedence issue with a > single term like that.) > > So, echo without parentheses can take > multiple parameters, which get > concatenated: > > echo "and a ", 1, 2, 3; // > comma-separated without parentheses > echo ("and a 123"); // just one > parameter with parentheses > > print() can only take one parameter: > > print ("and a 123"); print "and > a 123";
some say echo is slightly faster than print since it has no return value. though here is someone who doesn't think the speed difference matters much... <http://fabien.potencier.org/article/8/print-vs-echo-which-one-is-faster>
Is there any difference between 'print' and 'echo' in PHP?
[ "", "php", "" ]
[Visual Studio 2008] I created a new project for console application and modified it to look like this: ``` class Program { static void Main (string[] args) { Thread.Sleep (2000); } } ``` Then I created another project for Windows Form application and modified it: ``` static class Program { //[STAThread] commented this line static void Main (string[] args) { //Added args //Commented following lines //Application.EnableVisualStyles (); //Application.SetCompatibleTextRenderingDefault (false); //Application.Run (new Form1 ()); commented this line Thread.Sleep (2000); } } ``` Now I have neither written Console functions (Console.Write etc.) in first application nor I have written forms related operations in second one. Looks identical to me. Still first application shows BLACK window and second one doesn't show anything. What makes it work like this?
If you inspect the exe files usine ILDASM you can see that there is a difference in the Manifest (look for "subsystem"). In a Winforms application: ``` .subsystem 0x0002 // WINDOWS_GUI ``` In a console application: ``` .subsystem 0x0003 // WINDOWS_CUI ``` There may be more differencies in the IL code. When it comes to what makes the compiler emit this differently in the two cases, this is controlled by the project file's OutputType value: In a Winforms application: ``` <OutputType>WinExe</OutputType> ``` In a console application: ``` <OutputType>Exe</OutputType> ``` Out of curiosity I also checked that value for a Class Library project: ``` <OutputType>Library</OutputType> ```
In project properties, Application Tab, Output Type you can set to 'Windows Application' or 'Console Application'. I believe that behind the scenes VS does exactly what Fredrik presented in his post. Also, setting it to Console Application will show you the black console application for the windows Forms project.
What makes an app console or Windows Form application?
[ "", "c#", ".net", "winforms", "visual-studio-2008", "console-application", "" ]
This is code from an exercise: ``` #include <iostream> using namespace std; int main() { int n = 13; int* ip = new int(n + 3); int* ip2 = ip; cout << *ip << endl; delete ip; cout << *ip2 << endl; cout << ip << tab << ip2 << endl; } ``` When the space allocated to the int on the heap is deleted, I thought that dereferencing the pointer would give some sort of memory error. Instead, it returns 0. Why is this?
Dereferencing an invalid pointer leads to undefined results per spec. It's not guaranteed to fail. *Usually (CPU/OS/compiler/... dependent)*, the compiler doesn't really care about it at all. It just gives what's currently at that memory address. For example, in x86 architecture, you just see an error only when the address is in a memory page that's not mapped to your process (or your process doesn't have permission to access that), thus an exception will be thrown by the CPU (protection fault) which the OS would handle appropriately (and probably, making your process fail). A trick is sometimes used to make accessing the address `0` always cause an access violation: The OS sets the read/write bits of the first page of the address space in the page table to 0 so that any access to that page will always generate an exception.
This behaviour is undefined, and so what will happen is implementation and system dependent.
Deleting a heap then dereferencing a pointer to that memory
[ "", "c++", "pointers", "heap-memory", "" ]
People say that the clojure implementation is excellent apart from the limitation of having no tail call optimisation - a limitation of the jvm not the clojure implementation. <http://lambda-the-ultimate.org/node/2547> It has been said that to implement TCO into Python would sacrifice * stack-trace dumps, and * debugging regularity. [Explain to me what the big deal with tail call optimization is and why Python needs it](https://stackoverflow.com/questions/890461/explain-to-me-what-the-big-deal-with-tail-call-optimization-is-and-why-python-nee) Would the same sacrifices have to be made for a jvm implementation of TCO? Would anything else have to be sacrificed?
Whilst different (in that the il instructions existed already) it's worth noting the additional effort the .Net [64 bit JIT team](http://blogs.msdn.com/clrcodegeneration/archive/2009/05/11/tail-call-improvements-in-net-framework-4.aspx) had to go through to respect all tail calls. I call out in particular the comment: > The down side of course is that if you have to debug or profile optimized code, be prepared to deal with call stacks that look like they’re missing a few frames. I would think it highly unlikely the JVM could avoid this either. Given that, in circumstances where a tail call optimization was requested, the JIT should assume that it is *required* to avoid a stack overflow this is not something that can just be switched off in Debug builds. They aren't much use for debugging if they crash before you get to the interesting part. The 'optimization' is in fact is a permanent feature and an issue for stack traces affected by it. It is worth pointing out that any optimization which avoids creating a real stack frame when doing an operation which the programmer conceptually describes/understands as being a stack operation (calling a function for example) will inherently cause a disconnect between what is presented to the user when debugging/providing the stack trace and reality. This is unavoidable as the code that describes the operation becomes further and further separated from the mechanics of the state machine performing the operation.
Work is [underway now](http://challenge.openjdk.org/projects/mlvm/subprojects.html) to add tail calls to the JVM. There's a [wiki page](http://wikis.sun.com/display/mlvm/TailCalls) talking about some details.
What would the jvm have to sacrifice in order to implement tail call optimisation?
[ "", "python", "clojure", "jvm", "stack-trace", "tail-call-optimization", "" ]
I want to determine the class name where my application started, the one with the main() method, at runtime, but I'm in another thread and my stacktrace doesn't go all the way back to the original class. I've searched System properties and everything that ClassLoader has to offer and come up with nothing. Is this information just not available? Thanks.
I figured it out. Can anyone tell me if this environment variable will always be around in other java implementations across operating systems? This on Oracle JVM yields a String like "org.x.y.ClassName" ``` public static String getMainClassName() { for (final Map.Entry<String, String> entry : System.getenv().entrySet()) if (entry.getKey().startsWith("JAVA_MAIN_CLASS")) // like JAVA_MAIN_CLASS_13328 return entry.getValue(); throw new IllegalStateException("Cannot determine main class."); } ```
See the comments on link given by Tom Hawtin. A solution is these days is (Oracle JVM only): ``` public static String getMainClassAndArgs() { return System.getProperty("sun.java.command"); // like "org.x.y.Main arg1 arg2" } ``` Tested only with Oracle Java 7. More information about special cases: <https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4827318>
How to determine main class at runtime in threaded java application?
[ "", "java", "runtime", "stack-trace", "classloader", "program-entry-point", "" ]
What is a Proxy Class in C++? Why it is created and where it is useful?
A proxy is a class that provides a modified interface to another class. Here is an example - suppose we have an array class that we only want to contain binary digits (1 or 0). Here is a first try: ``` struct array1 { int mArray[10]; int & operator[](int i) { /// what to put here } }; ` ``` We want `operator[]` to throw if we say something like `a[1] = 42`, but that isn't possible because that operator only sees the index of the array, not the value being stored. We can solve this using a proxy: ``` #include <iostream> using namespace std; struct aproxy { aproxy(int& r) : mPtr(&r) {} void operator = (int n) { if (n > 1 || n < 0) { throw "not binary digit"; } *mPtr = n; } int * mPtr; }; struct array { int mArray[10]; aproxy operator[](int i) { return aproxy(mArray[i]); } }; int main() { try { array a; a[0] = 1; // ok a[0] = 42; // throws exception } catch (const char * e) { cout << e << endl; } } ``` The proxy class now does our checking for a binary digit and we make the array's `operator[]` return an instance of the proxy which has limited access to the array's internals.
A proxy class in C++ is used to implement the [Proxy Pattern](http://en.wikipedia.org/wiki/Proxy_pattern) in which an object is an interface or a mediator for some other object. A typical use of a proxy class in C++ is implementing the [] operator since the [] operator may be used to get data or to set data within an object. The idea is to provide a proxy class which allows for the detection of a get data use of the [] operator versus the set data use of the [] operator. The [] operator of a class uses the proxy object to assist in doing the right thing by detecting whether the [] operator is being used to get or set data in the object. The C++ compiler selects the appropriate operators and conversion operators from the provided target class and the proxy class definitions in order to make a particular use of the [] operator work. However there are other uses for a proxy class in C++. For instance see this article on [Self-Registering Objects in C++](http://www.drdobbs.com/cpp/self-registering-objects-in-c/184410633) from Dr. Dobbs that describes using a proxy class as part of an object factory. The object factory provides a particular type of object depending on some criteria, in this example a graphics image format. Each of the different graphic image converters is represented by a proxy object. > All of these requirements can be met by using a "specialty store" in > which there is no single place in the code at compile time that knows > about all supported formats. The list of supported objects is built at > run time when each file-format object registers its existence with a > specialty-store object. > > There are four parts to building a specialty store: > > * Each class that goes in the store will be represented by a proxy class. The proxy knows how to create objects for the store and > provides a standard interface for information about the class. > * You must decide what criteria the specialty store will expose to callers, then implement interfaces for those criteria in the store, in > the proxy class, and in the original class. > * All proxy classes will derive from a common base class so that the specialty store can use them interchangeably. Each proxy class will be > implemented as a template that calls static functions in the original > class. > * Proxy classes will be registered automatically at program startup by defining a global variable for each proxy class whose constructor > will register the proxy class with the specialty store. See also this answer, <https://stackoverflow.com/a/53253728/1466970>, to a question about C++ iterators in which a proxy class is used to represent as a unique object each of the array members of a struct. The struct is a memory resident database for an embedded application. Several different kinds of mnemonics are stored as text character arrays in the memory resident database. The proxy class provides a representation which can then be used with an iterator to traverse the list of mnemonics in a particular area. The iterator accesses the proxy object through a base class and the intelligence as to the how many mnemonics the proxy object represents and the length of each mnemonic is in the proxy object itself. Another example would be how Microsoft DCOM (Distributed COM) objects use a proxy on the host machine of a user of the DCOM object to represent the actual object which resides on another host machine. The proxy provides an interface for the actual object on a different machine and handles the communication between the user of the object and the actual object. To sum up, a proxy object is used to act as an intermediary to the actual object. A proxy object is used when ever there needs to be some kind of conversion or transformation between the user of an object and the actual object with some kind of indirection which provides a service allowing the use of the actual object when there is some obstacle in using the actual object directly. **EDIT - A simple example using a proxy with operator [] for a simple array data store** The following source uses a proxy object for the operator[] of a class. The output of the test harness is provided below to show the creation and destruction of the various proxy objects as the proxy class is used to access and manipulate the actual class. It is instructive to run this in a debugger to watch it execute. ``` // proxy.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <string.h> #include <iostream> class TArrayProxy; // The actual class which we will access using a proxy. class TArray { public: TArray(); ~TArray (); TArrayProxy operator [] (int iIndex); int operator = (TArrayProxy &j); void Dump (void); char m_TarrayName[4]; // this is the unique name of a particular object. static char TarrayName[4]; // This is the global used to create unique object names private: friend class TArrayProxy; // allow the proxy class access to our data. int iArray[10]; // a simple integer array for our data store }; // The proxy class which is used to access the actual class. class TArrayProxy { public: TArrayProxy(TArray *p = 0, int i=0); ~TArrayProxy(); TArrayProxy & operator = (int i); TArrayProxy & operator += (int i); TArrayProxy & operator = (TArrayProxy &src); operator int (); int iIndex; char m_TarrayproxyName[4]; // this is the unique name of a particular object. static char TarrayproxyName[4]; // This is the global used to create unique object names private: TArray *pArray; // pointer to the actual object for which we are a proxy. }; // initialize the object names so as to generate unique object names. char TArray::TarrayName[4] = {" AA"}; char TArrayProxy::TarrayproxyName[4] = {" PA"}; // Construct a proxy object for the actual object along with which particular // element of the actual object data store that this proxy will represent. TArrayProxy::TArrayProxy(TArray *p /* = 0 */, int i /* = 0 */) { if (p && i > 0) { pArray = p; iIndex = i; strcpy (m_TarrayproxyName, TarrayproxyName); TarrayproxyName[2]++; std::cout << " Create TArrayProxy " << m_TarrayproxyName << " iIndex = " << iIndex << std::endl; } else { throw "TArrayProxy bad p"; } } // The destructor is here just so that we can log when it is hit. TArrayProxy::~TArrayProxy() { std::cout << " Destroy TArrayProxy " << m_TarrayproxyName << std::endl; } // assign an integer value to a data store element by using the proxy object // for the particular element of the data store. TArrayProxy & TArrayProxy::operator = (int i) { pArray->iArray[iIndex] = i; std::cout << " TArrayProxy assign = i " << i << " to " << pArray->m_TarrayName << " using proxy " << m_TarrayproxyName << " iIndex " << iIndex << std::endl; return *this; } TArrayProxy & TArrayProxy::operator += (int i) { pArray->iArray[iIndex] += i; std::cout << " TArrayProxy add assign += i " << i << " to " << pArray->m_TarrayName << " using proxy " << m_TarrayproxyName << " iIndex " << iIndex << std::endl; return *this; } // assign an integer value that is specified by a proxy object to a proxy object for a different element. TArrayProxy & TArrayProxy::operator = (TArrayProxy &src) { pArray->iArray[iIndex] = src.pArray->iArray[src.iIndex]; std::cout << " TArrayProxy assign = src " << src.m_TarrayproxyName << " iIndex " << src.iIndex << " to " << m_TarrayproxyName << " iIndex "<< iIndex << " from" << std::endl; return *this; } TArrayProxy::operator int () { std::cout << " TArrayProxy operator int " << m_TarrayproxyName << " iIndex " << iIndex << " value of " << pArray->iArray[iIndex] << std::endl; return pArray->iArray[iIndex]; } TArray::TArray() { strcpy (m_TarrayName, TarrayName); TarrayName[2]++; std::cout << " Create TArray = " << m_TarrayName << std::endl; for (int i = 0; i < sizeof(iArray)/sizeof(iArray[0]); i++) { iArray[i] = i; } } // The destructor is here just so that we can log when it is hit. TArray::~TArray() { std::cout << " Destroy TArray " << m_TarrayName << std::endl; } TArrayProxy TArray::operator [] (int iIndex) { std::cout << " TArray operator [" << iIndex << "] " << m_TarrayName << std::endl; if (iIndex > 0 && iIndex <= sizeof(iArray)/sizeof(iArray[0])) { // create a proxy object for this particular data store element return TArrayProxy(this, iIndex); } else throw "Out of range"; } int TArray::operator = (TArrayProxy &j) { std::cout << " TArray operator = " << m_TarrayName << " from" << j.m_TarrayproxyName << " index " << j.iIndex << std::endl; return j.iIndex; } void TArray::Dump (void) { std::cout << std::endl << "Dump of " << m_TarrayName << std::endl; for (int i = 0; i < sizeof(iArray)/sizeof(iArray[0]); i++) { std::cout << " i = " << i << " value = " << iArray [i] << std::endl; } } // ----------------- Main test harness follows ---------------- // we will output the line of code being hit followed by the log of object actions. int _tmain(int argc, _TCHAR* argv[]) { TArray myObj; std::cout << std::endl << "int ik = myObj[3];" << std::endl; int ik = myObj[3]; std::cout << std::endl << "myObj[6] = myObj[4] = 40;" << std::endl; myObj[6] = myObj[4] = 40; std::cout << std::endl << "myObj[5] = myObj[5];" << std::endl; myObj[5] = myObj[5]; std::cout << std::endl << "myObj[2] = 32;" << std::endl; myObj[2] = 32; std::cout << std::endl << "myObj[8] += 20;" << std::endl; myObj[8] += 20; myObj.Dump (); return 0; } ``` And here is the output of this example from a console application with Visual Studio 2005. ``` Create TArray = AA int ik = myObj[3]; TArray operator [3] AA Create TArrayProxy PA iIndex = 3 TArrayProxy operator int PA iIndex 3 value of 3 Destroy TArrayProxy PA myObj[6] = myObj[4] = 40; TArray operator [4] AA Create TArrayProxy PB iIndex = 4 TArrayProxy assign = i 40 to AA using proxy PB iIndex 4 TArray operator [6] AA Create TArrayProxy PC iIndex = 6 TArrayProxy assign = src PB iIndex 4 to PC iIndex 6 from Destroy TArrayProxy PC Destroy TArrayProxy PB myObj[5] = myObj[5]; TArray operator [5] AA Create TArrayProxy PD iIndex = 5 TArrayProxy operator int PD iIndex 5 value of 5 TArray operator [5] AA Create TArrayProxy PE iIndex = 5 TArrayProxy assign = i 5 to AA using proxy PE iIndex 5 Destroy TArrayProxy PE Destroy TArrayProxy PD myObj[2] = 32; TArray operator [2] AA Create TArrayProxy PF iIndex = 2 TArrayProxy assign = i 32 to AA using proxy PF iIndex 2 Destroy TArrayProxy PF myObj[8] += 20; TArray operator [8] AA Create TArrayProxy PG iIndex = 8 TArrayProxy add assign += i 20 to AA using proxy PG iIndex 8 Destroy TArrayProxy PG Dump of AA i = 0 value = 0 i = 1 value = 1 i = 2 value = 32 i = 3 value = 3 i = 4 value = 40 i = 5 value = 5 i = 6 value = 40 i = 7 value = 7 i = 8 value = 28 i = 9 value = 9 ```
What is Proxy Class in C++
[ "", "c++", "design-patterns", "proxy", "" ]
I am planning to build a RIA about a year from now (when my current contract ends). What technology would you recommend investing time in? I will need good cross browser/platform support for video, music, and canvas. And ideally I would like to leverage my Python skills. Silverlight looks interesting because I could use Python through .NET. But I'm on Linux so I'd always be a 2nd class citizen. And it has a low install base. Flash on the other hand has a large install base. And I'm not sure about JavaFX because of the Oracle deal. Or should I hold my hopes out for HTML 5? Thanks!
You should focus on “HTML5” where “HTML5” is the new “Ajax” buzzword aka. the “Open Web Platform”—not just the HTML 5 spec itself. Flash, Silverlight and JavaFX are all single-vendor plug-in offerings but “HTML5” is a multi-vendor browser-native thing. If you want to an IDE workflow, you can use the Google Web Toolkit to have a Java workflow that targets the browser-native plug-inless feature set. Unfortunately, there’s no GWT-like Python system yet.
If you have a year to prepare I recommend that you research all the technologies you can. Build the hello worlds for the different platforms. Then build the SAME simple RIA on each candidate framework to get a good feel for the differences. Obviously you will not uncover every little gotcha, but the gross architectures and styles will be evident.
What to learn for RIA
[ "", "python", "silverlight", "html", "ria", "" ]
What is the need of IDictionary interface. How can IDictionary interface be initialized. After all it is just an interface. The following code snippet is from msdn. I could not understand it. ``` IDictionary<string, string> openWith = new Dictionary<string, string>(); ```
It defines the important [functions](http://msdn.microsoft.com/en-us/library/s4ys34ea.aspx) that an Dictionary should implement. The line from MSDN means that you are creating an object *openWith* which implements the functions (methods) defined in **IDictionary** interface. When you use Dictionary to declare the variable like: ``` Dictionary<string,string> openWith=.....; ``` you are bind with the concrete type of object. But when you use ``` IDictionary<string,string> openWith=....; ``` you can use it with any object that implements **IDictionary** *interface*, maybe your own custom class :)
The whole point of interfaces is to provide... well, an interface to whatever module (I use "module" in a broad sense here) so that calling code will not have to worry about how this particular interface is implemented. As for "How can `IDictionary` interface be initialized", this is technically not correct. What can be initialized is a variable, whose type is `IDictionary<T, V>`. Sure enough variables have to be initialized, but that's usually hidden from the "client code". `IDictionary` is not very representative, however. Rather, consider an `IDataReader` interface. You've surely dealt with ADO.NET, so this should look familiar: ``` public Foo PopulateFromDataReader(SqlDataReader dataReader) ``` This particular method is tightly coupled to an `SqlDataReader`, so you'd have to rewrite it for it to support, say, Access or Oracle or MySQL or Firebird or whatever. In other words, you depend on implementation. Now consider: ``` public Foo PopulateFromDataReader(IDataReader dataReader) ``` This method can be used with whatever class that implements `IDataReader`, which means with basically any ADO.NET-compatible data provider.
Purpose of IDictionary interface
[ "", "c#", ".net", "idictionary", "" ]
Let's say I've sorted a list of files in Explorer by name, like so: 2009-06-02-4.0.9.txt 2009-06-02-4.0.10.txt 2009-06-02-4.0.11.txt 2009-06-02-4.0.12.txt I have a FileInfo Comparer that sorts an array of FileInfo objects by name: ``` class FileInfoComparer : IComparer<FileInfo> { public int Compare(FileInfo x, FileInfo y) { return string.Compare(x.FullName, y.FullName, StringComparison.OrdinalIgnoreCase); } } ``` Sorting that same list of files from above using this Comparer yields: 2009-06-02-4.0.10.txt 2009-06-02-4.0.11.txt 2009-06-02-4.0.12.txt 2009-06-02-4.0.9.txt which is problematic, as the order is extremely important. I would imagine there's a way to mimic what Windows is doing in C# code, but I have yet to find a way. Any help is appreciated! Thanks!
Windows Explorer uses an API called: ``` StrCmpLogicalW ``` to perform the sort in a "logical" manner. Someone has also [implemented a class in C#](http://www.codeproject.com/KB/recipes/csnsort.aspx) which will do this for you.
You can also use P/Invoke to call the win32 API. This would be the most consistent behavior, and might perform better (I would benchmark both options). Even the code project link isn't entirely consistent with the windows behavior and it isn't future proof.
How would I sort a list of files by name to match how Windows Explorer displays them?
[ "", "c#", ".net", "sorting", "" ]
I am working with the following SQL query: ``` SELECT a.AppointmentId, a.Status, a.Type, a.Title, b.Days, d.Description, e.FormId FROM Appointment a (nolock) LEFT JOIN AppointmentFormula b (nolock) ON a.AppointmentId = b.AppointmentId and b.RowStatus = 1 JOIN Type d (nolock) ON a.Type = d.TypeId LEFT JOIN AppointmentForm e (nolock) ON e.AppointmentId = a.AppointmentId WHERE a.RowStatus = 1 AND a.Type = 1 ORDER BY a.Type ``` I am unsure how to achieve the JOINs in LINQ. All my tables have foreign key relationships.
You may have to tweak this slightly as I was going off the cuff, but there are a couple of major things to keep in mind. If you have your relationships set up properly in your dbml, you should be able to do inner joins implicitly and just access the data through your initial table. Also, left joins in LINQ are not as straight forward as we may hope and you have to go through the DefaultIfEmpty syntax in order to make it happen. I created an anonymous type here, but you may want to put into a DTO class or something to that effect. I also didn't know what you wanted to do in the case of nulls, but you can use the ?? syntax to define a value to give the variable if the value is null. Let me know if you have additional questions... ``` var query = (from a in context.Appointment join b in context.AppointmentFormula on a.AppointmentId equals b.AppointmentId into temp from c in temp.DefaultIfEmpty() join d in context.AppointmentForm on a.AppointmentID equals e.AppointmentID into temp2 from e in temp2.DefaultIfEmpty() where a.RowStatus == 1 && c.RowStatus == 1 && a.Type == 1 select new {a.AppointmentId, a.Status, a.Type, a.Title, c.Days ?? 0, a.Type.Description, e.FormID ?? 0}).OrderBy(a.Type); ```
``` SELECT A.X, B.Y FROM A JOIN B ON A.X = B.Y ``` This linq method call (to Join) will generate the above Join. ``` var query = A.Join ( B, a => a.x, b => b.y, (a, b) => new {a.x, b.y} //if you want more columns - add them here. ); ``` --- ``` SELECT A.X, B.Y FROM A LEFT JOIN B ON A.X = B.Y ``` These linq method calls (to GroupJoin, SelectMany, DefaultIfEmpty) will produce the above Left Join ``` var query = A.GroupJoin ( B, a => a.x, b => b.y, (a, g) => new {a, g} ).SelectMany ( z => z.g.DefaultIfEmpty(), (z, b) => new { x = z.a.x, y = b.y } //if you want more columns - add them here. ); ``` The key concept here is that Linq's methods produce hierarchically shaped results, not flattened row-column shapes. * Linq's `GroupBy` produces results shaped in a hierarchy with a grouping key matched to a **collection** of elements (which may not be empty). SQL's `GroupBy` clause produces a grouping key with **aggregated values** - there is no sub-collection to work with. * Similarly, Linq's `GroupJoin` produces a hierarchical shape - a parent record matched to a **collection** of child records (which may be empty). Sql's `LEFT JOIN` produces a parent record matched to each child record, or a null child record if there are no other matches. To get to Sql's shape from Linq's shape, one must unpack the collection of child records with `SelectMany` - and deal with empty collections of child records using `DefaultIfEmpty`. --- And here's my attempt at linquifying that sql in the question: ``` var query = from a in Appointment where a.RowStatus == 1 where a.Type == 1 from b in a.AppointmentFormula.Where(af => af.RowStatus == 1).DefaultIfEmpty() from d in a.TypeRecord //a has a type column and is related to a table named type, disambiguate the names from e in a.AppointmentForm.DefaultIfEmpty() order by a.Type select new { a.AppointmentId, a.Status, a.Type, a.Title, b.Days, d.Description, e.Form } ```
JOIN and LEFT JOIN equivalent in LINQ
[ "", "sql", "linq", "join", "left-join", "" ]
I am using [Wicket](http://wicket.apache.org/) with the Wicket Auth Project for my presentation layer and I have therefore integrated it with Spring Security. This is the method which is called by Wicket for authentication for me: ``` @Override public boolean authenticate(String username, String password) { try { Authentication request = new UsernamePasswordAuthenticationToken( username, password); Authentication result = authenticationManager.authenticate(request); SecurityContextHolder.getContext().setAuthentication(result); } catch (AuthenticationException e) { return false; } return true; } ``` The contents (inside ) of my Spring Security XML configuration are: ``` <http path-type="regex"> <form-login login-page="/signin"/> <logout logout-url="/logout" /> </http> <global-method-security secured-annotations="enabled" /> <authentication-manager alias="authenticationManager"/> <authentication-provider user-service-ref="userService"> <password-encoder ref="bcryptpasswordencoder" /> </authentication-provider> ``` The section [2.3.6. Session Fixation Attack Protection](http://static.springframework.org/spring-security/site/docs/2.0.x/reference/ns-config.html#ns-session-fixation) of the reference documentation says: > Session fixation attacks are a potential risk where it is possible > for a malicious attacker to create a > session by accessing a site, then > persuade another user to log in with > the same session (by sending them a > link containing the session identifier > as a parameter, for example). Spring > Security protects against this > automatically by creating a new > session when a user logs in. If you > don't require this protection, or it > conflicts with some other requirement, > you can control the behaviour using > the session-fixation-protection > attribute on , which has three > options: > > * migrateSession - creates a new session and copies the existing > session attributes to the new session. This is the default. > * none - Don't do anything. The original session will be retained. > * newSession - Create a new "clean" session, without copying the > existing session data. **The authentication works, but I as I'm fairly new to Spring Security I have some questions which I need answers too:** * Normally for login, I would POST the authentication information to `j_spring_security_check` and let Spring Security perform the actual authentication code. I would like to have protection against session fixation attacks, will I get it when I perform a programmatic login as I do? And if not, what would I have to do to get it? * How do I perform programmatic logout? * As I will use programmatic login and logout, how do I disable Spring from intercepting those URL's? **Update:** For session fixation attack protection it seems that I need to call the method in the SessionUtils class with the signature `startNewSessionIfRequired(HttpServletRequest request, boolean migrateAttributes, SessionRegistry sessionRegistry)`. How do I get the SessionRegistry instance which I need to pass in? I can't find any way to create an alias ID for it, or how to get it's ID or name.
Maybe it's not a full answer to your questions, but maybe it might help you. The code being called when you do NOT use programmatic login, but a standard one is to be found here: `org.springframework.security.ui.webapp.AuthenticationProcessingFilter` I guess you were inspired by this in your code. It looks quite similar. Similarly the code executed when you access the `/j_spring_security_logout` in the standard approach, is to be found here: `org.springframework.security.ui.logout.LogoutFilter` The LogoutFilter calls multiple handlers. The handler we are using is called: `org.springframework.security.ui.logout.SecurityContextLogoutHandler`, so you might call the same code in your approach.
You will indeed be open to session fixations attacks. To remedy this you could again be "inspired" by the Spring code. To create a new session you'll obviously need access to the httpsession so you may have to do some refactoring. If you see the method [`SessionUtils`](https://fisheye.springsource.org/browse/~raw,r=3640/spring-security/trunk/web/src/main/java/org/springframework/security/web/session/SessionUtils.java).`startNewSessionIfRequired`. This will migrate the authentication to a new session. You might be able to call this method directly or else just refactor the code a little. As for programmatic logout you can't go too far wrong by simply calling `session.invalidate()` when you need to log the person out. This will do everything necessary from a general security perspective but bear in mind though you might need to cleanup some things on the session. If you have a very complicated set of filters etc. and you need to ensure that that the user is logged out for the rest of the request then you could add: ``` SecurityContextHolder.getContext().setAuthentication(null); ``` As for interception of the url's you could just set them to something unused and ignore it! I'm not sure if you can turn off the interception in configuration - if you really want to remove it then have a look at the `AuthenticationProcessingFilter` - you could customise this. If you do this then you'll have to manually setup the spring security xml and not use the provided namespaces. It's not too hard though - look at some older documentation and you'll see how to do this. Hope this helps!
Programmatic use of Spring Security
[ "", "java", "spring", "spring-security", "wicket", "" ]
Is there an efficient way to update a selection of rows' field to 0, but set One of these rows to 1 based on an ID. Basically, I have multiple objects in a database, and I want to toggle between which one is "inuse", so the query will set one of the rows (by id) to inuse=1 and the others to inuse=0. Thanks :)
``` UPDATE `table` SET `inuse` = (`id` = 23) ```
Sure ``` UPDATE table SET inuse=IF(id=ABCD, 1, 0) ``` would set the inuse field to 1 if id is ABCD and 0 otherwise.
MySQL: Updating all rows setting a field to 0, but setting one row's field to 1
[ "", "php", "mysql", "" ]
PHP: Output multiple line command-line outputs as different lines. Sorry if the title is difficult to understand. Basically I want my output like A, instead of B. It currently looks like B. I have tried nl2br. The script I am trying to run is: Script: ``` echo "Virus Scan Results:"; $scanme = system('cd /var/www/upload/files; clamscan --remove=yes '.$furl); printf(nl2br($scanme)); ``` A: ``` 802931t_e_s_t.txt: OK ----------- SCAN SUMMARY ----------- Known viruses: 574585 Engine version: 0.95.1 Scanned directories: 0 Scanned files: 1 Infected files: 0 Data scanned: 0.00 MB Data read: 0.00 MB (ratio 0.00:1) Time: 2.352 sec (0 m 2 s) Time: 2.352 sec (0 m 2 s) ``` B: ``` 802931t_e_s_t.txt: OK ----------- SCAN SUMMARY ----------- Known viruses: 574585 Engine version: 0.95.1 Scanned directories: 0 Scanned files: 1 Infected files: 0 Data scanned: 0.00 MB Data read: 0.00 MB (ratio 0.00:1) Time: 2.352 sec (0 m 2 s) Time: 2.352 sec (0 m 2 s) ```
why are you using nl2br if this is on the command line? nl2br outputs `<br />` tags for new lines... which would have no meaning on command line **Edit** Two things: **1** try ``` system('cd /var/www/upload/files; clamscan --remove=yes '.$furl, $scanme); ``` **2** You may want to use the [exec](https://www.php.net/manual/en/function.exec.php) function instead of system e.g. ``` exec('cd /var/www/upload/files; clamscan --remove=yes '.$furl, $scanme); $scanme = implode("\n",$scanme); ``` exec ( string $command [, array &$output [, int &$return\_var ]] )
Have you tried just printing the output of the command directly? ``` echo "Virus Scan Results:"; echo exec('cd /var/www/upload/files; clamscan --remove=yes '.$furl); ``` PS. You really should sanitise the input like so (if you are not doing so already): ``` $furl = escapeshellarg($furl) ``` [escapeshellarg()](http://au.php.net/manual/en/function.escapeshellarg.php) - Escape a string to be used as a shell argument
PHP: Output multiple line command-line outputs as different lines
[ "", "php", "command-line", "command", "lines", "" ]
I was trying to extract a text(string) from MS Word (.doc, .docx), Excel and Powerpoint using C#. Where can i find a free and simple .Net library to read MS Office documents? I tried to use NPOI but i didn't get a sample about how to use NPOI.
Using PInvokes you can use the [IFilter](http://msdn.microsoft.com/en-us/library/ms691105(VS.85).aspx) interface (on Windows). The IFilters for many common file types are installed with Windows (you can browse them using [this](http://www.citeknet.com/Products/IFilters/IFilterExplorer/tabid/62/Default.aspx) tool. You can just ask the IFilter to return you the text from the file. There are several sets of example code ([here](http://www.codeproject.com/KB/cs/IFilter.aspx) is one such example).
For Microsoft Word 2007 and Microsoft Word 2010 (.docx) files you can use the Open XML SDK. This snippet of code will open a document and return its contents as text. It is especially useful for anyone trying to use regular expressions to parse the contents of a Word document. To use this solution you would need reference DocumentFormat.OpenXml.dll, which is part of the OpenXML SDK. See: <http://msdn.microsoft.com/en-us/library/bb448854.aspx> ``` public static string TextFromWord(SPFile file) { const string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; StringBuilder textBuilder = new StringBuilder(); using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(file.OpenBinaryStream(), false)) { // Manage namespaces to perform XPath queries. NameTable nt = new NameTable(); XmlNamespaceManager nsManager = new XmlNamespaceManager(nt); nsManager.AddNamespace("w", wordmlNamespace); // Get the document part from the package. // Load the XML in the document part into an XmlDocument instance. XmlDocument xdoc = new XmlDocument(nt); xdoc.Load(wdDoc.MainDocumentPart.GetStream()); XmlNodeList paragraphNodes = xdoc.SelectNodes("//w:p", nsManager); foreach (XmlNode paragraphNode in paragraphNodes) { XmlNodeList textNodes = paragraphNode.SelectNodes(".//w:t", nsManager); foreach (System.Xml.XmlNode textNode in textNodes) { textBuilder.Append(textNode.InnerText); } textBuilder.Append(Environment.NewLine); } } return textBuilder.ToString(); } ```
How to extract text from MS office documents in C#
[ "", "c#", "ms-office", "text-extraction", "" ]
I'm trying to use python to sftp a file, and the code works great in the interactive shell -- even pasting it in all at once. When I try to import the file (just to compile it), the code hangs with no exceptions or obvious errors. How do I get the code to compile, or does someone have working code that accomplishes sftp by some other method? This code hangs right at the ssh.connect() statement: ``` """ ProblemDemo.py Chopped down from the paramiko demo file. This code works in the shell but hangs when I try to import it! """ from time import sleep import os import paramiko sOutputFilename = "redacted.htm" #-- The payload file hostname = "redacted.com" ####-- WARNING! Embedded passwords! Remove ASAP. sUsername = "redacted" sPassword = "redacted" sTargetDir = "redacted" #-- Get host key, if we know one. hostkeytype = None hostkey = None host_keys = {} try: host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) except IOError: try: # try ~/ssh/ too, because windows can't have a folder named ~/.ssh/ host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) except IOError: print '*** Unable to open host keys file' host_keys = {} if host_keys.has_key(hostname): hostkeytype = host_keys[hostname].keys()[0] hostkey = host_keys[hostname][hostkeytype] print 'Using host key of type %s' % hostkeytype ssh = paramiko.Transport((hostname, 22)) ssh.connect(username=sUsername, password=sPassword, hostkey=hostkey) sftp = paramiko.SFTPClient.from_transport(ssh) sftp.chdir (sTargetDir) sftp.put (sOutputFilename, sOutputFilename) ssh.close() ```
Weirdness aside, I was just using import to compile the code. Turning the script into a function seems like an unnecessary complication for this kind of application. Searched for alternate means to compile and found: ``` import py_compile py_compile.compile("ProblemDemo.py") ``` This generated a pyc file that works as intended. So the lesson learned is that import is not a robust way to compile python scripts.
That's indeed a bad idea to execute this kind of code at import time, although I am not sure why it hangs - it may be that import mechanism does something strange which interacts badly with paramiko (thread related issues maybe ?). Anyway, the usual solution is to implement the functionality into a function: ``` def my_expensive_function(args): pass if __name__ == '__main__': import sys my_expensive_functions(sys.args) ``` This way, just importing the module will not do anything, but running the script will execute the function with the given arguments at command line.
Why does this python code hang on import/compile but work in the shell?
[ "", "python", "shell", "compilation", "sftp", "" ]