Daily Archives

Articles indexed Friday January 7 2011

Page 2/34 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • C#/.NET &ndash; Finding an Item&rsquo;s Index in IEnumerable&lt;T&gt;

    - by James Michael Hare
    Sorry for the long blogging hiatus.  First it was, of course, the holidays hustle and bustle, then my brother and his wife gave birth to their son, so I’ve been away from my blogging for two weeks. Background: Finding an item’s index in List<T> is easy… Many times in our day to day programming activities, we want to find the index of an item in a collection.  Now, if we have a List<T> and we’re looking for the item itself this is trivial: 1: // assume have a list of ints: 2: var list = new List<int> { 1, 13, 42, 64, 121, 77, 5, 99, 132 }; 3:  4: // can find the exact item using IndexOf() 5: var pos = list.IndexOf(64); This will return the position of the item if it’s found, or –1 if not.  It’s easy to see how this works for primitive types where equality is well defined.  For complex types, however, it will attempt to compare them using EqualityComparer<T>.Default which, in a nutshell, relies on the object’s Equals() method. So what if we want to search for a condition instead of equality?  That’s also easy in a List<T> with the FindIndex() method: 1: // assume have a list of ints: 2: var list = new List<int> { 1, 13, 42, 64, 121, 77, 5, 99, 132 }; 3:  4: // finds index of first even number or -1 if not found. 5: var pos = list.FindIndex(i => i % 2 == 0);   Problem: Finding an item’s index in IEnumerable<T> is not so easy... This is all well and good for lists, but what if we want to do the same thing for IEnumerable<T>?  A collection of IEnumerable<T> has no indexing, so there’s no direct method to find an item’s index.  LINQ, as powerful as it is, gives us many tools to get us this information, but not in one step.  As with almost any problem involving collections, there are several ways to accomplish the same goal.  And once again as with almost any problem involving collections, the choice of the solution somewhat depends on the situation. So let’s look at a few possible alternatives.  I’m going to express each of these as extension methods for simplicity and consistency. Solution: The TakeWhile() and Count() combo One of the things you can do is to perform a TakeWhile() on the list as long as your find condition is not true, and then do a Count() of the items it took.  The only downside to this method is that if the item is not in the list, the index will be the full Count() of items, and not –1.  So if you don’t know the size of the list beforehand, this can be confusing. 1: // a collection of extra extension methods off IEnumerable<T> 2: public static class EnumerableExtensions 3: { 4: // Finds an item in the collection, similar to List<T>.FindIndex() 5: public static int FindIndex<T>(this IEnumerable<T> list, Predicate<T> finder) 6: { 7: // note if item not found, result is length and not -1! 8: return list.TakeWhile(i => !finder(i)).Count(); 9: } 10: } Personally, I don’t like switching the paradigm of not found away from –1, so this is one of my least favorites.  Solution: Select with index Many people don’t realize that there is an alternative form of the LINQ Select() method that will provide you an index of the item being selected: 1: list.Select( (item,index) => do something here with the item and/or index... ) This can come in handy, but must be treated with care.  This is because the index provided is only as pertains to the result of previous operations (if any).  For example: 1: // assume have a list of ints: 2: var list = new List<int> { 1, 13, 42, 64, 121, 77, 5, 99, 132 }; 3:  4: // you'd hope this would give you the indexes of the even numbers 5: // which would be 2, 3, 8, but in reality it gives you 0, 1, 2 6: list.Where(item => item % 2 == 0).Select((item,index) => index); The reason the example gives you the collection { 0, 1, 2 } is because the where clause passes over any items that are odd, and therefore only the even items are given to the select and only they are given indexes. Conversely, we can’t select the index and then test the item in a Where() clause, because then the Where() clause would be operating on the index and not the item! So, what we have to do is to select the item and index and put them together in an anonymous type.  It looks ugly, but it works: 1: // extensions defined on IEnumerable<T> 2: public static class EnumerableExtensions 3: { 4: // finds an item in a collection, similar to List<T>.FindIndex() 5: public static int FindIndex<T>(this IEnumerable<T> list, Predicate<T> finder) 6: { 7: // if you don't name the anonymous properties they are the variable names 8: return list.Select((item, index) => new { item, index }) 9: .Where(p => finder(p.item)) 10: .Select(p => p.index + 1) 11: .FirstOrDefault() - 1; 12: } 13: }     So let’s look at this, because i know it’s convoluted: First Select() joins the items and their indexes into an anonymous type. Where() filters that list to only the ones matching the predicate. Second Select() picks the index of the matches and adds 1 – this is to distinguish between not found and first item. FirstOrDefault() returns the first item found from the previous clauses or default (zero) if not found. Subtract one so that not found (zero) will be –1, and first item (one) will be zero. The bad thing is, this is ugly as hell and creates anonymous objects for each item tested until it finds the match.  This concerns me a bit but we’ll defer judgment until compare the relative performances below. Solution: Convert ToList() and use FindIndex() This solution is easy enough.  We know any IEnumerable<T> can be converted to List<T> using the LINQ extension method ToList(), so we can easily convert the collection to a list and then just use the FindIndex() method baked into List<T>. 1: // a collection of extension methods for IEnumerable<T> 2: public static class EnumerableExtensions 3: { 4: // find the index of an item in the collection similar to List<T>.FindIndex() 5: public static int FindIndex<T>(this IEnumerable<T> list, Predicate<T> finder) 6: { 7: return list.ToList().FindIndex(finder); 8: } 9: } This solution is simplicity itself!  It is very concise and elegant and you need not worry about anyone misinterpreting what it’s trying to do (as opposed to the more convoluted LINQ methods above). But the main thing I’m concerned about here is the performance hit to allocate the List<T> in the ToList() call, but once again we’ll explore that in a second. Solution: Roll your own FindIndex() for IEnumerable<T> Of course, you can always roll your own FindIndex() method for IEnumerable<T>.  It would be a very simple for loop which scans for the item and counts as it goes.  There’s many ways to do this, but one such way might look like: 1: // extension methods for IEnumerable<T> 2: public static class EnumerableExtensions 3: { 4: // Finds an item matching a predicate in the enumeration, much like List<T>.FindIndex() 5: public static int FindIndex<T>(this IEnumerable<T> list, Predicate<T> finder) 6: { 7: int index = 0; 8: foreach (var item in list) 9: { 10: if (finder(item)) 11: { 12: return index; 13: } 14:  15: index++; 16: } 17:  18: return -1; 19: } 20: } Well, it’s not quite simplicity, and those less familiar with LINQ may prefer it since it doesn’t include all of the lambdas and behind the scenes iterators that come with deferred execution.  But does having this long, blown out method really gain us much in performance? Comparison of Proposed Solutions So we’ve now seen four solutions, let’s analyze their collective performance.  I took each of the four methods described above and run them over 100,000 iterations of lists of size 10, 100, 1000, and 10000 and here’s the performance results.  Then I looked for targets at the begining of the list (best case), middle of the list (the average case) and not in the list (worst case as must scan all of the list). Each of the times below is the average time in milliseconds for one execution as computer over the 100,000 iterations: Searches Matching First Item (Best Case)   10 100 1000 10000 TakeWhile 0.0003 0.0003 0.0003 0.0003 Select 0.0005 0.0005 0.0005 0.0005 ToList 0.0002 0.0003 0.0013 0.0121 Manual 0.0001 0.0001 0.0001 0.0001   Searches Matching Middle Item (Average Case)   10 100 1000 10000 TakeWhile 0.0004 0.0020 0.0191 0.1889 Select 0.0008 0.0042 0.0387 0.3802 ToList 0.0002 0.0007 0.0057 0.0562 Manual 0.0002 0.0013 0.0129 0.1255   Searches Where Not Found (Worst Case)   10 100 1000 10000 TakeWhile 0.0006 0.0039 0.0381 0.3770 Select 0.0012 0.0081 0.0758 0.7583 ToList 0.0002 0.0012 0.0100 0.0996 Manual 0.0003 0.0026 0.0253 0.2514   Notice something interesting here, you’d think the “roll your own” loop would be the most efficient, but it only wins when the item is first (or very close to it) regardless of list size.  In almost all other cases though and in particular the average case and worst case, the ToList()/FindIndex() combo wins for performance, even though it is creating some temporary memory to hold the List<T>.  If you examine the algorithm, the reason why is most likely because once it’s in a ToList() form, internally FindIndex() scans the internal array which is much more efficient to iterate over.  Thus, it takes a one time performance hit (not including any GC impact) to create the List<T> but after that the performance is much better. Summary If you’re concerned about too many throw-away objects, you can always roll your own FindIndex() method, but for sheer simplicity and overall performance, using the ToList()/FindIndex() combo performs best on nearly all list sizes in the average and worst cases.    Technorati Tags: C#,.NET,Litte Wonders,BlackRabbitCoder,Software,LINQ,List

    Read the article

  • Connect to Postgres remotely, open port 5432 for Postgres in iptables

    - by Victor
    I am trying to connect to Postgres remotely but I need to open port 5432 in iptables. My current iptables configuration is as follows: *filter # Allows all loopback (lo0) traffic and drop all traffic to 127/8 that doesn't use lo0 -A INPUT -i lo -j ACCEPT -A INPUT ! -i lo -d 127.0.0.0/8 -j REJECT # Accepts all established inbound connections -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # Allows all outbound traffic # You can modify this to only allow certain traffic -A OUTPUT -j ACCEPT # Allows HTTP and HTTPS connections from anywhere (the normal ports for websites) -A INPUT -p tcp --dport 80 -j ACCEPT -A INPUT -p tcp --dport 443 -j ACCEPT # Allows SSH connections # # THE -dport NUMBER IS THE SAME ONE YOU SET UP IN THE SSHD_CONFIG FILE # -A INPUT -p tcp -m state --state NEW --dport 30000 -j ACCEPT # Allow ping -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT # log iptables denied calls -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7 # Reject all other inbound - default deny unless explicitly allowed policy -A INPUT -j REJECT -A FORWARD -j REJECT COMMIT What would I have to add in iptables to open the port? I'm trying to install phppgadmin on a different server to access the postgres database. Thank you.

    Read the article

  • Does a VPN requirement kill the concept of having a Web Application in the Cloud?

    - by Christian
    Recently I posted a question in SO, but so far I got no answers. I wonder if I'm asking the wrong question. This is the problem: We need to design an application which offers a public http web service, but at the same time it must consume some services through a VPN connection from other existing company. There is no other alternative but to use a VPN connection to access those services. We want to host our application in some cloud infrastructure like Heroku or Amazon EC2. But there is no direct way to access the VPN services of the other company from there. The solution I'm thinking, but I don't like is to have a different server to expose the services from that VPN. But this will require the setup of another server which I prefer to avoid. In the case this is the solution, can I use an Amazon EC2 instance to connect to a VPN? This is what I was thinking, is it correct? I don't have experience using VPNs, tunnels or those kind of networking stuff. I will really appreciate if you can propose me an alternative solution, or just give me a comment.

    Read the article

  • Is it possible to cause email to my domain to be handled by gmail?

    - by pitosalas
    [This is a very narrow question, and I don't think it is covered in similar sounding questions] I want to configure my server's DNS so that when someone sends email to [email protected] it is actually deliver it to [email protected] Note: My question is whether this is possible to do ONLY with DNS not with myserver.com's own sendmail. I think the answer is "NO" it is not possible, because when I add an MX record to DNS the email that was delivered to gmail's SMPT server would be TO: [email protected] and it would not know that account. (But I hasten to add that I am just vaguely starting to grok how this all works.)

    Read the article

  • Debian, Apache2, CGI: paths issue

    - by Bubnoff
    I have a perl form email script on the servers cgi-bin directory ( /usr/lib/cgi-bin ). /etc/apache2/sites-enabled/000-default ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Directory "/usr/lib/cgi-bin"> AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch AddHandler cgi-script cgi pl Order allow,deny Allow from all </Directory> The issue is with paths. html calls script here: <form name="Request" method="post" action="http://server-test.local/cgi-bin/formprocessorpro.pl" onsubmit="return checkWholeForm49874(this)"> The directory with the templates and configs is passed here: <input type="hidden" name="base_path" value="../contact" /> The path to this form is: http://server-test.local/formstest/contact.htm No matter what variation I try for the base_path I get an error from the formprocessor script that it can't find the directory: An error occurred when opening the Form Configuration File (../contact/form.cfg): No such file or directory. I need to move this script from an old server, configured by a previous sysadmin, to a new server. Since cgi-bin is automatically linked to /usr/lib/cgi-bin and linked such that the script resides: http://server-test.local/cgi-bin/formprocessorpro.pl I would imagine that, given that the templates are in the webroot in a directory called contact, the correct path would be: ../contact Any ideas? It's been awhile since I've messed with CGI. Bubnoff

    Read the article

  • Why does my 5.1 surround work in testing only?

    - by Mike Pateras
    I've got a 5.1 speaker setup. In both this SoundMax utility (I think it came with my motherboard), and in the Windows 7 sound test, all 5.1 speakers work properly, but that's the only time that I can get audio to come out of the rear speakers and the center channel. When playing games, video, music, etc., I only seem to get 2.1 speakers worth of sound, even though I've configured everything for 5.1 surround sound. How can I get my 5.1 surround sound working during actual use?

    Read the article

  • Windows 7 Backup - Does the "system image" include all the files on my drive?

    - by Vaccano
    I have a new Dell Laptop that I have setup the way I like it. I want to use Windows 7 to do a backup and then restore that backup on a different hard drive (solid state). When I setup the backup info (manually) for Windows 7 Backup there is a little checkbox at the the bottom that says: Include a system image of drives: RECOVERY, OS (C:) I can also select to backup all my data on the C: drive (the only hard drive I have anything on) as well as some libraries (which are on my C: drive so no point in selecting those). The question I have is, does Windows 7 Backup just somehow know what needs to be restored (ie program files and Windows and the registry ....? Or is it really making a full restorable copy of the C: drive? (If the later is true then I don't need select the C: drive to be "backed up" if I don't plan to access the files except by restoring them right? (Because the system image will already have it all.)) So, which way is it? What is saved in the System Image?

    Read the article

  • How do I crop an image in the Mac version of Microsoft Word?

    - by Bec
    I know how to do it in the Windows version of Word but I can't work out how in the Mac version. In Windows there's a crop tool where you can just drag to move the edges in to crop the image, how do I do that on the Mac? Also on the old version of Windows there was a command to delete the cropped sections of all images in a document to save file space, I can't find that in Word 2007 or Word for Mac.

    Read the article

  • Changing Administrator password Windows Home Server

    - by Brettski
    Is there a problem using Computer Management Local User and Groups Users to change the Administrator password in Windows Home Server? Is there a chance it will cause any issues with the system? I ask as the system warns against using server tools to change settings. I have access to the system with my account, but the Administrator password isn't working,forgotten whatever and needs to be changed.

    Read the article

  • In vim, prevent caret moving back when I leave edit mode?

    - by romkyns
    In vim, if I enter and leave edit mode without doing anything, the caret ends up one character to the left. And if I enter and leave append mode, the caret moves forwards and then backwards. Any way to configure vim to leave the caret alone in these cases? Ideally I just want to always enter append mode, but without moving the caret when I enter or exit the mode. (Currently I usually use insert mode because it doesn't mess up my caret position upon entry. That is, except when I need to append to the end of the line, in which case I swear at vim for behaving in such an archaic fashion, press Esc and enter append mode.)

    Read the article

  • invoke zsh, having it run a command, and then enter interactive mode instead of exiting

    - by Autoplectic
    i'd like to start zsh similar to zsh -c 'my_prog option1 option2' but instead of exiting after running that command, leaving me at the propt of the invoked zsh (not wherever it is being called from). one particular use-case for this is in screenrc files, you could do something like: screen -t my_prog 0 zsh -c 'my_prog opt1 opt2' and after running that command you're left with a shell there instead of it closing.

    Read the article

  • Pinging computer name in LAN results in public IP?

    - by Bob
    Hi, I recently introduced a new machine to my LAN. The computer name for this machine is 'server'. Historically I've been able to access machines from my home network (from a web browser or RDP) using the machine name and it resolves to a local IP address just fine. However, I can't seem to do this anymore. When I ping the computer name, I get the following: C:\Users\Robert>ping server Pinging server.router [67.215.65.132] with 32 bytes of data: Reply from 67.215.65.132: bytes=32 time=24ms TTL=54 Reply from 67.215.65.132: bytes=32 time=23ms TTL=54 Reply from 67.215.65.132: bytes=32 time=24ms TTL=54 Reply from 67.215.65.132: bytes=32 time=24ms TTL=54 I notice also that it appends the 'router' suffix to my domain name for some reason. 'router' is the name of my router, obviously. I'm also using OpenDNS as my DNS provider (configured through my router so it gets passed down through DHCP). Why is this not working for me? Can someone explain how the DNS resolution should take place? For LAN resolution, it shouldn't go straight to OpenDNS. I thought that each Windows machine kept it's own sort of "mini DNS server" that knows about all machines on the local network and it first tries to resolve using that. Please let me know what I can do to get this working!

    Read the article

  • Different approaches to share files over local network & playlists "collaboration"

    - by exTyn
    I know, that I can use Google to find methods to share files over local network [1]. But, I have never shared files over local network, and I want to do this in a good, professional way. Also, this could be a good community wiki, I think. Well, what I am asking for, is: what are pros and cons of different methods to sharing files ofver local network? In my case, I need to share files between Linux & Win 7, and I want it to be secure (= without access for anyone else but me & people in my room). Another question (connected with above topic) is about playing music over the local network. Let's say, I live with 2 other guys in a room, one of us have speakers and we want to collaborate in creating playlists (e.g. everyone is choosing 3 songs to be played). Is it possible? How to do this? I am asking this question on SuperUser, because it (question) is connected with hardware & software (network, connecting computers, software for managing playlists in network etc.). I think it is most accurate place for such question (I have considered SO and SF). [1] And I have already done this! But, I do not have an experience in this field (sharing files over local network), do I am asking about pros and cons.

    Read the article

  • SQL SERVER – DMV – sys.dm_exec_query_optimizer_info – Statistics of Optimizer

    - by pinaldave
    Incredibly, SQL Server has so much information to share with us. Every single day, I am amazed with this SQL Server technology. Sometimes I find several interesting information by just querying few of the DMV. And when I present this info in front of my client during performance tuning consultancy, they are surprised with my findings. Today, I am going to share one of the hidden gems of DMV with you, the one which I frequently use to understand what’s going on under the hood of SQL Server. SQL Server keeps the record of most of the operations of the Query Optimizer. We can learn many interesting details about the optimizer which can be utilized to improve the performance of server. SELECT * FROM sys.dm_exec_query_optimizer_info WHERE counter IN ('optimizations', 'elapsed time','final cost', 'insert stmt','delete stmt','update stmt', 'merge stmt','contains subquery','tables', 'hints','order hint','join hint', 'view reference','remote query','maximum DOP', 'maximum recursion level','indexed views loaded', 'indexed views matched','indexed views used', 'indexed views updated','dynamic cursor request', 'fast forward cursor request') All occurrence values are cumulative and are set to 0 at system restart. All values for value fields are set to NULL at system restart. I have removed a few of the internal counters from the script above, and kept only documented details. Let us check the result of the above query. As you can see, there is so much vital information that is revealed in above query. I can easily say so many things about how many times Optimizer was triggered and what the average time taken by it to optimize my queries was. Additionally, I can also determine how many times update, insert or delete statements were optimized. I was able to quickly figure out that my client was overusing the Query Hints using this dynamic management view. If you have been reading my blog, I am sure you are aware of my series related to SQL Server Views SQL SERVER – The Limitations of the Views – Eleven and more…. With this, I can take a quick look and figure out how many times Views were used in various solutions within the query. Moreover, you can easily know what fraction of the optimizations has been involved in tuning server. For example, the following query would tell me, in total optimizations, what the fraction of time View was “reference“. As this View also includes system Views and DMVs, the number is a bit higher on my machine. SELECT (SELECT CAST (occurrence AS FLOAT) FROM sys.dm_exec_query_optimizer_info WHERE counter = 'view reference') / (SELECT CAST (occurrence AS FLOAT) FROM sys.dm_exec_query_optimizer_info WHERE counter = 'optimizations') AS ViewReferencedFraction Reference : Pinal Dave (http://blog.SQLAuthority.com) Filed under: Pinal Dave, PostADay, SQL, SQL Authority, SQL DMV, SQL Optimization, SQL Performance, SQL Query, SQL Scripts, SQL Server, SQL Tips and Tricks, SQLServer, T SQL, Technology

    Read the article

  • Technical Article: Oracle Magazine Java Developer of the Year Adam Bien on Java EE 6 Simplicity by Design

    - by janice.heiss(at)oracle.com
    Java Champion and Oracle Magazine Java Developer of the Year, Adam Bien, offers his unique perspective on how to leverage new Java EE 6 features to build simple and maintainable applications in a new article in Oracle Magazine. Bien examines different Java EE 6 architectures and design approaches in an effort to help developers build efficient, simple, and maintainable applications.From the article: "Java EE 6 consists of a set of independent APIs released together under the Java EE name. Although these APIs are independent, they fit together surprisingly well. For a given application, you could use only JavaServer Faces (JSF) 2.0, you could use Enterprise JavaBeans (EJB) 3.1 for transactional services, or you could use Contexts and Dependency Injection (CDI) with Java Persistence API (JPA) 2.0 and the Bean Validation model to implement transactions.""With a pragmatic mix of available Java EE 6 APIs, you can entirely eliminate the need to implement infrastructure services such as transactions, threading, throttling, or monitoring in your application. The real challenge is in selecting the right subset of APIs that minimizes overhead and complexity while making sure you don't have to reinvent the wheel with custom code. As a general rule, you should strive to use existing Java SE and Java EE services before expanding your search to find alternatives." Read the entire article here.

    Read the article

  • What would one call this architecture?

    - by Chris
    I have developed a distributed test automation system which consists of two different entities. One entity is responsible for triggering tests runs and monitoring/displaying their progress. The other is responsible for carrying out tests on that host. Both of these entities retrieve data from a central DB. Now, my first thought is that this is clearly a server-client architecture. After all, you have exactly one organizing entity and many entities that communicate with said entity. However, while the supposed clients to communicate to the server via RPC, they are not actually requesting services or information, rather they are simply reporting back test progress, in fact, once the test run has been triggered they can complete their tasks without connection to the server. The request for a service is actually made by the supposed server which triggers the clients to carry out tests. So would this still be considered a server-client architecture or is this something different?

    Read the article

  • Use a GUI designer or write it yourself for the desktop?

    - by TheLQ
    Writing a GUI for a program has always been a daunting, depressing, and frustrating task. It doesn't matter which language, its extremely hard to get what I want. Especially in compiled languages like Java where a change takes a minute or two to build. The result is that I increasingly use GUI designers for some of my project. Sure their is some spagetti code, but as long as I leave the configuration and a note saying "This was designed with X" I have no qualms with doing this. Is this an okay way to design a GUI? More importantly, is this what most people do? Or is the common way to just sit down and write it out?

    Read the article

  • Double confirmation on exit

    - by Sean
    I am trying to make it so that the user is prompted to confirm exiting my program in c#, but for some reason, if they say "yes" they would like to exit, the confirmation box would pop up again. I can't figure out why. if (MessageBox.Show("Are you sure you want to exit?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { e.Cancel = true; } else { Application.Exit(); }

    Read the article

  • How does twitter server get to know single tweet ID from URL fragment segment?

    - by Morgan Cheng
    Each tweet has a single URL such as http://twitter.com/#!/DeliciousHot/status/23189589820702720. The tweet identification (/DeliciousHot/status/23189589820702720) is in the URL fragment segment which is not actually sent to server. Originally, I thought it works this way: The URL response doesn't have this tweet specific info. It is JavaScript module that extracts tweet id from current browser URL and fetch tweet payload with AJAX. The page content is then updated with the tweet payload. To my surprise, it is doesn't work this way! With Firebug, you can view that response of http://twitter.com/#!/DeliciousHot/status/23189589820702720 has tweet payload "10 Signs of a True Gentleman" text in inline JavaScript. The tweet payload is not fetched by another AJAX. So, how does Twitter server get to know the expected tweet ID even it is in URL fragment segment?

    Read the article

  • Why do Pascal control structures appear to be inconsistent?

    - by 70Mike
    Most Pascal control structures make sense to me, like: for ... do {statement}; if (condition) then {statement}; while (condition) do {statement}; where the {statement} is either a single statement, or a begin ... end block. I have a problem with: repeat {statement-list} until (expression); try {statement-list} except {statement-list} end; Wouldn't it be better that repeat and try have the same general structure, accepting only a single statement or a begin ... end block, instead of having a statement-list that's not formally blocked with a begin and an end?

    Read the article

  • routing problem with startpage in rails3

    - by DannyRe
    Hey, I deleted the Index.html in my /public/ folder. I added a "application" folder in my views. In it I put a new index.html.erb. This I want to be my startpage/homepage. In my new "index.html.erb" I set: link_to 'sign in', {:controller => 'devise/sessions', :action => 'new'} But it redirects me to the "application#index". I set root :to => "application#index How can I set this to route it to "posts#index" after I sign in, for example? Is there a chance to use .erb oder .haml in my /public/index.html? Many thanks!!

    Read the article

  • Reinitialize the current month name, when i click button

    - by EswaraMoorthyNEC
    Hi,In my richCalendar.jsp page, first time i click the showCurrentMonth button and display the current month using rich:calendar. i select some other month i click SelectedMonth button. I show the selected month name. My problem is : I go to any other page. then i come visit the richCalendar.jsp and again click showCurrentMonth button, this time the rich:calendar show the already selected month instead of current month . Each time, i want to show current month when i click showCurrentMonth. richCalendar.jsp <body> <h:form id="calendarForm" binding="#{CalenderBean.initForm}"> <rich:panel> <a4j:outputPanel id="calendarOutputPanel"> <h:panelGrid> <a4j:commandButton value="showCurrentMonth" action="#{CalenderBean.showCurrentMonthAction}" reRender="monthlyPanelGridId,monthlyCalendarId,calendarOutputPanel"/> <h:panelGrid id="monthlyPanelGridId" rendered="#{CalenderBean.monthlyCalendarRendered}" > <rich:calendar boundaryDatesMode="scroll" id="monthlyCalendarId" showWeekDaysBar="false" oncurrentdateselected="event.rich.component.selectDate(event.rich.date)" showFooter="false" popup="false" value="#{CalenderBean.selectedMonth}"/> </h:panelGrid> <h:panelGrid id = "SearchButtonGrid"> <a4j:commandButton id="SelectedMonth" value="SelectedMonth" action="#{CalenderBean.selectedMonthButtonAction}" reRender="calendarOutputPanel"/> <h:outputText value="#{CalenderBean.selectedMonthName}" /> </h:panelGrid> </h:panelGrid> </a4j:outputPanel> <rich:panel></h:form></body> CalenderBean.java import java.util.Calendar; import java.util.Date; import javax.faces.component.html.HtmlForm; public class CalenderBean { private HtmlForm initForm; private boolean monthlyCalendarRendered; private Date selectedMonth; private String selectedMonthName; public CalenderBean() { } public String showCurrentMonthAction() { monthlyCalendarRendered = true; Calendar calendar = Calendar.getInstance(); int startingDate = calendar.getActualMinimum(Calendar.DAY_OF_MONTH); calendar.set(Calendar.DATE, startingDate); selectedMonth = calendar.getTime(); return ""; } public String selectedMonthButtonAction() { selectedMonthName = selectedMonth.toString(); return ""; } public HtmlForm getInitForm() { selectedMonth = null; monthlyCalendarRendered = false; return initForm; } public void setInitForm(HtmlForm initForm){ this.initForm = initForm; } public boolean isMonthlyCalendarRendered(){ return monthlyCalendarRendered; } public void setMonthlyCalendarRendered(boolean monthlyCalendarRendered){ this.monthlyCalendarRendered = monthlyCalendarRendered; } public Date getSelectedMonth(){ return selectedMonth; } public void setSelectedMonth(Date selectedMonth){ this.selectedMonth = selectedMonth; } public String getSelectedMonthName(){ return selectedMonthName; } public void setSelectedMonthName(String selectedMonthName){ this.selectedMonthName = selectedMonthName; } } First time i visit this page perfectly show the current month. Then i go to any othe page and then come to see this page, click showCurrentMonth button not show the current month. Help me. Thanks in advance.

    Read the article

  • Iterating Through a jQuery Object Array

    - by DeltaFox
    I know this has been asked and answered a couple times already, but I'm still confused about how to reference the current object when iterating over a jQuery array. For example, the following code gives me the error "TypeError: genH3Array[i].next is not a function". What is the right way to reference the current array object? var genH3Array = $('#Generation_II').parent(); genH3Array.push($('#Generation_III').parent());; genH3Array.push($('#Generation_IV').parent()) $.each(genH3Array, function(i, value) { if(genH3Array[i].next().attr("align") == "center") { genH3Array[i].next().next().next().insertBefore(heading.next()) } genH3Array[i].next().next().insertBefore(heading.next()) genH3Array[i].next().insertBefore(heading.next()) })

    Read the article

  • Can mouseenter be made to not fire in IE on DOMready?

    - by mrclay
    jQuery emulates IE's mouseenter event on non-IE browsers. In IE, however, mouseenter is being triggered when the page loads (maybe due to jQuery's use of doScroll in the $.ready implementation), even if the mouse is not moved at all. This doesn't happen in other browsers and definitely doesn't follow Microsoft's own spec, which says (emphasis mine): The event fires only if the mouse pointer is outside the boundaries of the object and the user moves the mouse pointer inside the boundaries of the object. If the mouse pointer is currently inside the boundaries of the object, for the event to fire, the user must move the mouse pointer outside the boundaries of the object and then back inside the boundaries of the object. This only becomes an issue of usability if hover (or the hoverIntent plugin) is applied to a navigational item to display a drop down or "mega-menu": In IE, mouseenter will fire immediately after $.ready, obscuring the content with the menu. I've put together a demonstration of both the mouseenter inconsistency and the usability issue it creates.

    Read the article

  • KitchenSink tools/apkbuilder error when trying to run for Android

    - by Lukasz
    When I run KitchenSink example project on iPhone emulator everything is OK, but trying to launch for Android emulator produces errors: [ERROR] /Users/lukasz/Android/android-sdk-mac_x86/tools/apkbuilder [ERROR] Failed installing com.appcelerator.kitchensink: pkg: /data/local/tmp/app.apk It happens whatever Androig API I choose (from 1.5 to 2.2 or from APIs 1.5 to APIs 2.2). I am using Titanium Developer 1.2.1, titanium SDK 1.4.1.11 Where is the problem? As far as I can see Android SDKs and platforms work correctly because I can successfully compile Android projects from diffrent IDE (Netbeans).

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >