Search Results

Search found 4955 results on 199 pages for 'range'.

Page 58/199 | < Previous Page | 54 55 56 57 58 59 60 61 62 63 64 65  | Next Page >

  • How to do elif statments more elegantly if appending to array in python

    - by user1741339
    I am trying to do a more elegant version of this code. This just basically appends a string to categorynumber depending on the number. Would appreciate any help. number = [100,150,200,500] categoryNumber = [] for i in range (0,len(number)): if (number [i] >=1000): categoryNumber.append('number > 1000') elif (number [i] >=200): categoryNumber.append('200 < number < 300') elif (number [i] >=100): categoryNumber.append('100 < number < 200') elif (number [i] >=50): categoryNumber.append('50 < number < 100') elif (number [i] < 50): categoryNumber.append('number < 50') for i in range(0,len(categoryNumber)): print i

    Read the article

  • How would you write this Clojure snippet in Ruby and/or Haskell?

    - by dnolen
    I was working on a Rails template and was trying to write a bit of code that allows me to populate a table or multiple columns of ul tags "top-to-bottom" and "left-to-right" across however many columns I specify. I'm just getting the hang of Ruby so I couldn't figure this out. I'm also curious about an idiomatic Haskell version for this useful snippet. Improvements to Clojure version appreciated: (defn table [xs & {:keys [cols direction] :or {cols 1 direction 'right}}] (into [] (condp = direction 'down (let [c (count xs) q (int (/ c cols)) n (if (> (mod c q) 0) (inc q) q)] (apply map vector (partition n n (repeat nil) xs))) 'right (map vec (partition cols cols (repeat nil) xs))))) With this bit of code I can then do the following: (table (range 10) :cols 3) Printed out this would look like so: 0 1 2 3 4 5 6 7 8 9 And the trickier one: (table (range 10) :cols 3 :direction 'down) Looks like so: 0 4 8 1 5 9 2 6 3 7

    Read the article

  • why am i getting an error SyntaxError : invalid syntax for this code

    - by eragon1189
    This is a code in python which calculates f (x) =? ((-1)*x)/(x*x+n*n) n from 1 to infinite.... correct to 0.0001, for the range 1 < x < 100 in steps of 0.1.But i am getting an syntax error,as i am new to programming in python... from scipy import * from matplotlib.pyplot import * x=arange(0.1,100,0.1) f=zeros(len(x)) s=-1 for n in range (1,10000): t=s*x/(x*x+n*n) f +=t s =-s if max(abs(t))< 1e-4 break for xx in c_[x,f]: print "%f %f" % (xx[0],xx[1])

    Read the article

  • x86 linux - how to create custom malloc with address hint

    - by nandu
    Hi, I want to create a custom malloc which allocates memory blocks within a given address range. I am writing a pthreads application in which threads are bound to unique cores on a many-core machine. The memory controllers are statically mapped, so that certain range of addresses on main memory are electrically closer to a core. I want to minimize the latency of communication between cores and main memory by allocating thread memory on these "closer" regions. Any ideas would be most appreciated. Thank you! Nandu

    Read the article

  • Statistics help on 3 choices

    - by DaveSav
    I'm working on an Android app where, at one point, the user is asked to input whether something helped. Their options are 'Yes', 'No' and 'Don't Know'; or they could choose to ignore it. This is for multiple 'somethings' over a date range. A summary view for a date range shows the percentage of 'Yes', 'No' and 'Don't Know' entered for each 'something'. I'm also showing the 'Overall Effectiveness' as the percentage of 'Yes' inputs, which I realise is incorrect. I am thinking of changing that to 'Yes' minus 'No', but that doesn't address the 'Don't Know' inputs. How would I handle the data so that 'Overall Effectiveness' represents all 3 data inputs? So, for a 'something' which has a 'Yes' of 25%, a 'No' of 25% and a 'Don't Know' of 50%, would that be an 'Overall Effectiveness' of 0% ? Or would the 'Don't Know' affect that figure at all? As an additional to that, what graph type, other that Pie, would best display all 3 data?

    Read the article

  • Difference Between Two Lists with Many Duplicates in Python

    - by Paul
    I have several lists that contain many of the same items and many duplicate items. I want to check which items in one list are not in the other list. For example, I might have one list like this: l1 = ['a', 'b', 'c', 'b', 'c'] and one list like this: l2 = ['a', 'b', 'c', 'b'] Comparing these two lists I would want to return a third list like this: l3 = ['c'] I am currently using some terrible code that I made a while ago that I'm fairly certain doesn't even work properly shown below. def list_difference(l1,l2): for i in range(0, len(l1)): for j in range(0, len(l2)): if l1[i] == l1[j]: l1[i] = 'damn' l2[j] = 'damn' l3 = [] for item in l1: if item!='damn': l3.append(item) return l3 How can I better accomplish this task?

    Read the article

  • When dragged and on mouseup/mouseleave in the document I want to call my Ajax request

    - by Sappy
    For slider range - when dragged and on mouseup/mouseleave in the document I want to call my Ajax request. Explained: When I mousedown to slide my slider I want to say isDown = "true" But it doesn't works. Can anyone please help me with this and let me know how do I achieve this. // Default isDown = false $("#slider-range").find('a').mousedown(function(){ isDown=true; console.log(isDown); // It works here! }); console.log(isDown); // It doesn't works here if(isDown) { $(document).onmouseup(function() { return setAjaxRequest(); isDown = false; }); }

    Read the article

  • Find first cell in a row that contains a number?

    - by Dexter
    I'm working in Excel with an exported table such as this: |-------------------------------------------------------------------------------| | | A | B | C | D | E | F | G | H | I | |---|-------------------|-----|-----|-----|-----|-----|-------|-----|-----------| | 1 | Domain | JAN | FEB | MAR | APR | MAY | Start | End | Change | |---|-------------------|-----|-----|-----|-----|-----|-------|-----|-----------| | 2 | www.mydomain1.com | | 1 | 4 | 3 | 1 | 1 | 1 | 0 | |---|-------------------|-----|-----|-----|-----|-----|-------|-----|-----------| | 3 | www.mydomain2.com | 2 | 4 | 12 | 18 | 23 | 2 | 23 | 21 | |---|-------------------|-----|-----|-----|-----|-----|-------|-----|-----------| | 4 | www.mydomain3.com | | | 14 | 12 | | 14 | xxx | NOT FOUND | |-------------------------------------------------------------------------------| I'm trying to compare the current state (last cell) to the original cell (first cell with a value). In column I, I have the formula =IF(G2 = "xxx", "NOT FOUND", IF(H2 = "xxx", "NOT FOUND", H2 - G2)) In column H, I have the formula =IF(F2 = "", "xxx", F2) In column G, I need to find the first cell with a number. If there isn't one in that range, I need G to be "xxx". I suppose I only need to check for the first cell in the range (B2 to F2) that contains a value, not just a number. I tried using an Index and Match combo, but I couldn't quite understand it.

    Read the article

  • What to do with someone who can only use "the one true language"?

    - by Rob Wells
    G'day, How do you work with someone when they haven't been able to see that there is a range of other languages out there beyond "The One True Path"? I mean someone who hasn't grown up to realise that the modern software professional has a range of tools in his toolbox. Someone who has a well-equipped toolbox and then selects the best tool for the job at hand. The person who's knee jerk reaction is, for example, "We must do this is C++!" "Everything must be done in C++!" What's the best approach for these people? How do you open them up to the fact that "not everything is a nail." cheers,

    Read the article

  • The return value should be a list but doesn't return as expected?! - Python newbie

    - by user1432941
    Hi this must be a very simple solution that has eluded me this last hour. I've tried to build this test function where the return value of the test_cases list should match the values in the test_case_answers list but for some reason, test case 1 and test case 2 fail. When i print the return values for the test cases they return the correct answers, but for some reason test case 1 and test case 2 return False. Thanks for your help! import math test_cases = [1, 9, -3] test_case_answers = [1, 3, 0] def custom_sqrt(num): for i in range(len(test_cases)): if test_cases[i] >= 0: return math.sqrt(test_cases[i]) else: return 0 for i in range(len(test_cases)): if custom_sqrt(test_cases[i]) != test_case_answers[i]: print "Test Case #", i, "failed!" custom_sqrt(test_cases)

    Read the article

  • Firewall configuration. (Windows server 2008)

    - by Jon
    Hello. I'm having a little problem with configuring the firewall on my server. I only want a specific range of IPs to be able to access specific ports. For example, I'm having alot of password attempts to some of my servers, so I want to make it more safe by only allowing incoming connections from a specific range of domain. Example: My IP is usually adsl-324-4.somecompany.com so I want to allow *.somecpompany.com to connect, as my IP is dynamic. That would get rid of alot of attempts to hack into my servers. But I have no idea how to mask a domain like that for the firewall. How could I for example allow all incoming connections from *.is? Thanks.

    Read the article

  • Using Large Arrays in VB.NET

    - by Tim
    I want to extract large amounts of data from Excel, manipulate it and put it back. I have found the best way to do this is to extract the data from an Excel Range in to a large array, change the contents on the array and write it back to the Excel Range. I am now rewriting the application using VB.NET 2008/2010 and wish to take advantage of any new features. Currently I have to loop through the contents of the array to find elements with certain values; also sorting large arrays is cumbersome. I am looking to use the new features, including LINQ to manipulate the data in my array. Does anybody have any advice on the easiest ways to filter / query, sort etc. data in a large array. Also what are the reasonable limits to the size of the array? ~Many Thanks

    Read the article

  • what is this value means 1.845E-07 in excel ?

    - by Lalit
    Hi , i am reading the excel sheet from c# by using interop services. My sheet have one of cell value as 0.00. but run time when i checking the value of that cell in c# code I am getting "1.845E-07" this value. When i check in excel sheet, on that cell right clicked , say format cell I got "1.845E-07" value in sample section. How to get exact value? Please help me. code is huge, so i can't provide it here . that line is: if (Convert.ToString(((Excel.Range)worksheet.Cells[iRowindex, colIndex_q10]).Value2) != string.Empty) { drRow[dtSourceEXLData.Columns[constants.Floor]] = ((Excel.Range)worksheet.Cells[iRowindex, colIndex_q10]).Value2.ToString(); }

    Read the article

  • Dates search in Drupal (greater than, less than) using CCK / views / facelet?

    - by guillefar
    I'm working in a site that manage events (like parties). Each event could have several fields, including date, that the user could add thanks to CCK module. Now, the problem is when I have to search using those fields. I could not find how to search for events between a range of dates. I discover the facelet module, which is pretty good, and it is very useful for some kind of search, but as far as I can see it is not possible search in a range. Also I do some testing using views, but again, with no results. I can not find how to search a date "greater than" and "less than". I will really appreciate any help.

    Read the article

  • list within a list

    - by atm atm
    I'm working on this problem, but I cannot figure out the second part. I tried using reverse list but it did not work out how I planned it. Given a list L (e.g. [1,2,3,4]), write a program that generates the following nested lists: L1 = [[1],[1,2],[1,2,3],[1,2,3,4]], L2 = [[4],[3,4],[2,3,4],[1,2,3,4]]. My code that I have so far: mylist=[,1,2,3,4] print("Orginal list L=",mylist) n=len(mylist) l1=[] l2=[] for x in range(1,n+1,1): l1.append(mylist[0:x]) print("L1=",l1) #prints final product of l1 mylist.reverse() #this is where i get messed up for x in range(1,n+1,1): l2.append(mylist[0:x]) print("L2=",l2)

    Read the article

  • What is wrong with the below statement(C#3.0 / Lambda)

    - by Newbie
    what is wrong in the below Enumerable.Range(0, objEntityCode.Count - 1).Select(i => { options.Attributes[i] = new EntityCodeKey { EntityCode = objEntityCode[i].EntityCodes , OrganizationCode = Constants.ORGANIZATION_CODE }; }) .ToArray(); Throwing error The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly. But this works Enumerable.Range(0, objEntityCode.Count - 1).ToList().ForEach(i => { options.Attributes[i] = new EntityCodeKey { EntityCode = objEntityCode[i].EntityCodes , OrganizationCode = Constants.ORGANIZATION_CODE }; } ); Using C#3.0. Purpose: I am learning LINQ / LAMBDA and trying to do the same program in different way. Thanks.

    Read the article

  • Selecting the image after execCommand

    - by jerebear
    Have been banging my head against the wall on this one for a while now. I have an editor that is inserting an image but I can't get it to select the newly inserted image in Firefox after execCommand Runs. Here's my code. var editor = this; var sel = editor._getSelection(); var range = editor._createRange(sel); editor._doc.execCommand("insertimage", false, imgURL); img = range.startContainer.previousSibling; console.log(img);

    Read the article

  • process the data after using str.split

    - by juju
    I parse a .txt like this: def parse_file(src): for line in src.readlines(): if re.search('SecId', line): continue else: cols = line.split(',') Time = cols[4] output_file.write('{}\n'.format( Time)) I think cols are lists that I could use index. Although it succeeds in printing out correct result as I want, there exists an out of range error. What's the matter? File "./tdseq.py", line 37, in parse_file Time = cols[4] IndexError: list index out of range make: *** [all] Error 1 Data I use: I10.FE,--,2008-04-16,15:15:00,13450,13488,13450,13470,490,359,16APR2008:09:15:00 I10.FE,--,2008-04-16,15:16:00,13468,13473.8,13467,13467,306,521,16APR2008:09:16:00 ....

    Read the article

  • Linq - Grouping where items fall in multiple groups?

    - by PirateKitten
    Is it possible using Linq to create a group where items fall into more than one group? Using the following trivial example: public class Data { public string ID; public int From; public int To; } And this list: List<Data> data = new List<Data>() { new Data() { ID = "A", From = 1, To = 3 }, // Call this A new Data() { ID = "B", From = 1, To = 2 }, // Call this B new Data() { ID = "C", From = 2, To = 3 } // Call this C }; I'd like to group by each possible integer in the ranges From and To (though instead of finding the min + max I could supply the query with the range I want, for example 1 to 3), and in each group would be a reference to the Data instance where the grouping int fits in its range. Hard to explain, easier to show each group and the instances I'd expect in each: [Group 1] 1 - A, B [Group 2] 2 - A, B, C [Group 3] 3 - A, C Is this possible? Or must groups be mutually exclusive?

    Read the article

  • String manipulation appears to be inefficient

    - by user2964780
    I think my code is too inefficient. I'm guessing it has something to do with using strings, though I'm unsure. Here is the code: genome = FASTAdata[1] genomeLength = len(genome); # Hash table holding all the k-mers we will come across kmers = dict() # We go through all the possible k-mers by index for outer in range (0, genomeLength-1): for inner in range (outer+2, outer+22): substring = genome[outer:inner] if substring in kmers: # if we already have this substring on record, increase its value (count of num of appearances) by 1 kmers[substring] += 1 else: kmers[substring] = 1 # otherwise record that it's here once This is to search through all substrings of length at most 20. Now this code seems to take pretty forever and never terminate, so something has to be wrong here. Is using [:] on strings causing the huge overhead? And if so, what can I replace it with? And for clarity the file in question is nearly 200mb, so pretty big.

    Read the article

  • WDS DHCP same server on Windows Server 2008

    - by Richard
    I have been struggling with a problem on my Windows Server 2008 for the past 4 - 5 hours and cannot figure out whats wrong. I have tried pretty much everything that I found on google and all the links are purple. Hopefully you guys can help me. I am running a Windows Server 2008 Standard edition with the latest updates as of today. Furthermore I am running a Windows Server 2003. Both are virtual machines on my ESXi 5 server. My network is: 192.168.10.0/24 W2k8: 192.168.10.251 is the PDC running ADS, DHCP and WDS W2k3: 192.168.10.253 AND 192.168.1.175 running Routing and Remote Access and ISA 2006 Enterprise In my internal network (192.168.10.0/24) I have my client machine (192.168.10.10) that runs a VMWare Workstation. I am trying to deploy Windows 7 Home Premium to a virtual machine on my VMWorkstation via PXE. I have set the Workstation's VM network adapter to "bridged" so that it uses the physical network adapter and is connected to my internal network. The DHCP pool is configured to give IP addresses from 192.168.10.10-192.168.10.15 (works for normal clients and is not used up) When I start my VM with the PXE I get the error: PXE-E52:proxyDHCP offers were received. No DHCP offers were received Apperently this means "that means that WDS responded but the DHCP server did not." People suggested to direct the traffic to both WDS and DHCP on the router, since everything is on the same subnet there is no need for that as the broadcast is seen by everyone (WDS and DHCP) No reservation for the virtual mac addrs is made on the DHCP. Furthermore it was suggested to configure the DHCP options: Option 60= PXEClient Option 66= WDS server name or IP address Option 67= Boot file name However, this is not recommended by Microsoft, I tried it and it did not solve my problem. The configuration on the WDS (My System is German therefore the actual naming might be different): PXE response tab: PXE responses is set to "ALL (known and unknown)" DHCP Tab: Do not listen to port 67 is NOT ticked - if I tick this I do not get any responses and the PXE errors gets PXE-E51 that neither DHCP or proxyDHCP were received DHCP-Option 60 for "PXEClient" is ticked The confusing part here is that it is advised in the tab to tick the first option since it is on the same server. Network Configuration Tab: Use the following IP-Address range for Multicast-IP-Address: 224.0.1.0 - 224.0.10.0 Thats not the default one, however it is in the allowed range. The UDP port range is the default since it is not advised to change them. I tried to change the "networkprofile" from 100mbits/1gbits and custom. I am running a 1gbit network with CAT6 cables and 1gbit netgear switch 5 ports. Everything is configured to use 1gbit. The WDS is authorised for the DHCP server. My ISA 2006 configuration: For the internal networking i have configured the following policy array: Allow protocols on internal network including the w2k3 host: 67,68,53,ICMP, 4011 UDP receive, 64001-6500 UDP send receive, 69 UDP send Routing and Remote Access I tried the DHCP relay agent configuration that was suggested as well, but that did not work I would highly appreciate anykind of help because I am pretty much done here with my nerves. Thank you very much in advance.

    Read the article

  • I have a NGINX server configured to work with node.js, but many times a file of 1.03MB of js is not loaded by various browser and various pc

    - by Totty
    I'm using this in a local LAN so it should be quite fast. The nginx server use the node.js server to serve static files, so it must pass throught node.js to download the files, but that is not a problem when I'm not using the nginx. In chrome with debugger on I can see that the status is: 206 - partial content and it only has downloaded 31KB of 1.03MB. After 1.1 min it turns red and the status failed. Waiting time: 6ms Receiving: 1.1 min The headers in google chrom: Request URL:http://192.168.1.16/production/assembly/script/production.js Request Method:GET Status Code:206 Partial Content Request Headersview source Accept:*/* Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3 Accept-Encoding:gzip,deflate,sdch Accept-Language:pt-PT,pt;q=0.8,en-US;q=0.6,en;q=0.4 Connection:keep-alive Cookie:connect.sid=s%3Abls2qobcCaJ%2FyBNZwedtDR9N.0vD4Fi03H1bEdCszGsxIjjK0lZIjJhLnToWKFVxZOiE Host:192.168.1.16 If-Range:"1081715-1350053827000" Range:bytes=16090-16090 Referer:http://192.168.1.16/production/assembly/ User-Agent:Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4 Response Headersview source Accept-Ranges:bytes Cache-Control:public, max-age=0 Connection:keep-alive Content-Length:1 Content-Range:bytes 16090-16090/1081715 Content-Type:application/javascript Date:Mon, 15 Oct 2012 09:18:50 GMT ETag:"1081715-1350053827000" Last-Modified:Fri, 12 Oct 2012 14:57:07 GMT Server:nginx/1.1.19 X-Powered-By:Express My nginx configurations: File 1: user totty; worker_processes 4; pid /var/run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # Logging Settings ## access_log /home/totty/web/production01_server/node_modules/production/_logs/_NGINX_access.txt; error_log /home/totty/web/production01_server/node_modules/production/_logs/_NGINX_error.txt; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript; ## # nginx-naxsi config ## # Uncomment it if you installed nginx-naxsi ## #include /etc/nginx/naxsi_core.rules; ## # nginx-passenger config ## # Uncomment it if you installed nginx-passenger ## #passenger_root /usr; #passenger_ruby /usr/bin/ruby; ## # Virtual Host Configs ## autoindex on; include /home/totty/web/production01_server/_deployment/nginxConfigs/server/*; } File that is included by the previous file: server { # custom location for entry # using only "/" instead of "/production/assembly" it # would allow you to go to "thatip/". In this way # we are limiting to "thatip/production/assembly/" location /production/assembly/ { # ip and port used in node.js proxy_pass http://127.0.0.1:3000/; } location /production/assembly.mongo/ { proxy_pass http://127.0.0.1:9000/; proxy_redirect off; } location /production/assembly.logs/ { autoindex on; alias /home/totty/web/production01_server/node_modules/production/_logs/; } }

    Read the article

  • Download Microsoft’s Series of ‘Work Smart’ Guides for Windows 8

    - by Asian Angel
    The general release date for Windows 8 is almost here and Microsoft has released a terrific set of free ‘Work Smart’ guides to help you get started with the new operating system. Whether it is an overview of Windows 8 itself, shortcut keys, backups, and more these guides cover a nice range of topics. HTG Explains: How Antivirus Software Works HTG Explains: Why Deleted Files Can Be Recovered and How You Can Prevent It HTG Explains: What Are the Sys Rq, Scroll Lock, and Pause/Break Keys on My Keyboard?

    Read the article

  • Validation in Silverlight

    - by Timmy Kokke
    Getting started with the basics Validation in Silverlight can get very complex pretty easy. The DataGrid control is the only control that does data validation automatically, but often you want to validate your own entry form. Values a user may enter in this form can be restricted by the customer and have to fit an exact fit to a list of requirements or you just want to prevent problems when saving the data to the database. Showing a message to the user when a value is entered is pretty straight forward as I’ll show you in the following example.     This (default) Silverlight textbox is data-bound to a simple data class. It has to be bound in “Two-way” mode to be sure the source value is updated when the target value changes. The INotifyPropertyChanged interface must be implemented by the data class to get the notification system to work. When the property changes a simple check is performed and when it doesn’t match some criteria an ValidationException is thrown. The ValidatesOnExceptions binding attribute is set to True to tell the textbox it should handle the thrown ValidationException. Let’s have a look at some code now. The xaml should contain something like below. The most important part is inside the binding. In this case the Text property is bound to the “Name” property in TwoWay mode. It is also told to validate on exceptions. This property is false by default.   <StackPanel Orientation="Horizontal"> <TextBox Width="150" x:Name="Name" Text="{Binding Path=Name, Mode=TwoWay, ValidatesOnExceptions=True}"/> <TextBlock Text="Name"/> </StackPanel>   The data class in this first example is a very simplified person class with only one property: string Name. The INotifyPropertyChanged interface is implemented and the PropertyChanged event is fired when the Name property changes. When the property changes a check is performed to see if the new string is null or empty. If this is the case a ValidationException is thrown explaining that the entered value is invalid.   public class PersonData:INotifyPropertyChanged { private string _name; public string Name { get { return _name; } set { if (_name != value) { if(string.IsNullOrEmpty(value)) throw new ValidationException("Name is required"); _name = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Name")); } } } public event PropertyChangedEventHandler PropertyChanged=delegate { }; } The last thing that has to be done is letting binding an instance of the PersonData class to the DataContext of the control. This is done in the code behind file. public partial class Demo1 : UserControl { public Demo1() { InitializeComponent(); this.DataContext = new PersonData() {Name = "Johnny Walker"}; } }   Error Summary In many cases you would have more than one entry control. A summary of errors would be nice in such case. With a few changes to the xaml an error summary, like below, can be added.           First, add a namespace to the xaml so the control can be used. Add the following line to the header of the .xaml file. xmlns:Controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input"   Next, add the control to the layout. To get the result as in the image showed earlier, add the control right above the StackPanel from the first example. It’s got a small margin to separate it from the textbox a little.   <Controls:ValidationSummary Margin="8"/>   The ValidationSummary control has to be notified that an ValidationException occurred. This can be done with a small change to the xaml too. Add the NotifyOnValidationError to the binding expression. By default this value is set to false, so nothing would be notified. Set the property to true to get it to work.   <TextBox Width="150" x:Name="Name" Text="{Binding Name, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}"/>   Data annotation Validating data in the setter is one option, but not my personal favorite. It’s the easiest way if you have a single required value you want to check, but often you want to validate more. Besides, I don’t consider it best practice to write logic in setters. The way used by frameworks like WCF Ria Services is the use of attributes on the properties. Instead of throwing exceptions you have to call the static method ValidateProperty on the Validator class. This call stays always the same for a particular property, not even when you change the attributes on the property. To mark a property “Required” you can use the RequiredAttribute. This is what the Name property is going to look like:   [Required] public string Name { get { return _name; } set { if (_name != value) { Validator.ValidateProperty(value, new ValidationContext(this, null, null){ MemberName = "Name" }); _name = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Name")); } } }   The ValidateProperty method takes the new value for the property and an instance of ValidationContext. The properties passed to the constructor of the ValidationContextclass are very straight forward. This part is the same every time. The only thing that changes is the MemberName property of the ValidationContext. Property has to hold the name of the property you want to validate. It’s the same value you provide the PropertyChangedEventArgs with. The System.ComponentModel.DataAnnotation contains eight different validation attributes including a base class to create your own. They are: RequiredAttribute Specifies that a value must be provided. RangeAttribute The provide value must fall in the specified range. RegularExpressionAttribute Validates is the value matches the regular expression. StringLengthAttribute Checks if the number of characters in a string falls between a minimum and maximum amount. CustomValidationAttribute Use a custom method to validate the value. DataTypeAttribute Specify a data type using an enum or a custom data type. EnumDataTypeAttribute Makes sure the value is found in a enum. ValidationAttribute A base class for custom validation attributes All of these will ensure that an validation exception is thrown, except the DataTypeAttribute. This attribute is used to provide some additional information about the property. You can use this information in your own code.   [Required] [Range(0,125,ErrorMessage = "Value is not a valid age")] public int Age {   It’s no problem to stack different validation attributes together. For example, when an Age is required and must fall in the range from 0 to 125:   [Required, StringLength(255,MinimumLength = 3)] public string Name {   Or in one row like this, for a required Name with at least 3 characters and a maximum of 255:   Delayed validation Having properties marked as required can be very useful. The only downside to the technique described earlier is that you have to change the value in order to get it validated. What if you start out with empty an empty entry form? All fields are empty and thus won’t be validated. With this small trick you can validate at the moment the user click the submit button.   <TextBox Width="150" x:Name="NameField" Text="{Binding Name, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True, UpdateSourceTrigger=Explicit}"/>   By default, when a TwoWay bound control looses focus the value is updated. When you added validation like I’ve shown you earlier, the value is validated. To overcome this, you have to tell the binding update explicitly by setting the UpdateSourceTrigger binding property to Explicit:   private void SubmitButtonClick(object sender, RoutedEventArgs e) { NameField.GetBindingExpression(TextBox.TextProperty).UpdateSource(); }   This way, the binding is in two direction but the source is only updated, thus validated, when you tell it to. In the code behind you have to call the UpdateSource method on the binding expression, which you can get from the TextBox.   Conclusion Data validation is something you’ll probably want on almost every entry form. I always thought it was hard to do, but it wasn’t. If you can throw an exception you can do validation. If you want to know anything more in depth about something I talked about in this article let me know. I might write an entire post to that.

    Read the article

< Previous Page | 54 55 56 57 58 59 60 61 62 63 64 65  | Next Page >