Search Results

Search found 1006 results on 41 pages for 'istream iterator'.

Page 11/41 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Manually iterating over a selection of XML elements (C#, XDocument)

    - by user316117
    What is the “best practice” way of manually iterating (i.e., one at a time with a “next” button) over a set of XElements in my XDocument? Say I select the set of elements I want thusly: var elems = from XElement el in m_xDoc.Descendants() where (el.Name.LocalName.ToString() == "q_a") select el; I can use an IEnumerator to iterate over them, i.e., IEnumerator m_iter; But when I get to the end and I want to wrap around to the beginning if I call Reset() on it, it throws a NotSupportedException. That’s because, as the Microsoft C# 2.0 Specification under chapter 22 "Iterators" says "Note that enumerator objects do not support the IEnumerator.Reset method. Invoking this method causes a System.NotSupportedException to be thrown ." So what IS the right way of doing this? And what if I also want to have bidirectional iteration, i.e., a “back” button, too? Someone on a Microsoft discussion forum said I shouldn’t be using IEnumerable directly anyway. He said there was a way to do what I want with LINQ but I didn’t understand what. Someone else suggested dumping the XElements into a List with ToList(), which I think would work, but I wasn’t sure it was “best practice”. Thanks in advance for any suggestions!

    Read the article

  • VBA - Access 03 - Iterating through a list box, with an if statement to evaluate

    - by Justin
    So I have a one list box with values like DeptA, DeptB, DeptC & DeptD. I have a method that causes these to automatically populate in this list box if they are applicable. So in other words, if they populate in this list box, I want the resulting logic to say they are "Yes" in a boolean field in the table. So to accomplish this I am trying to use this example of iteration to cycle through the list box first of all, and it works great: dim i as integer dim myval as string For i = o to me.lstResults.listcount - 1 myVal = lstResults.itemdata(i) Next i if i debug.print myval, i get the list of data items that i want from the list box. so now i am trying to evaluate that list so that I can have an UPDATE SQL statement to update the table as i need it to be done. so, i know this is a mistake, but this is what i tried to do (giving it as an example so that you can see what i am trying to get to here) dim sql as string dim i as integer dim myval as string dim db as database sql = "UPDATE tblMain SET " for i = 0 to me.lstResults.listcount - 1 myval = lstResults.itemdata(i) If MyVal = "DeptA" Then sql = sql & "DeptA = Yes" ElseIF myval = "DeptB" Then sql = sql & "DeptB = Yes" ElseIf MyVal = "DeptC" Then sql = sql & "DeptC = Yes" ElseIf MyVal = "DeptD" Then sql = sql & "DeptD = Yes" End If Next i debug.print (sql) sql = sql & ";" set db= currentdb db.execute(sql) msgbox "Good Luck!" So you can see why this is going to cause problems because the listbox that these values (DeptA, DeptB, etc) automatically populate in are dynamic....there is rarely one value in the listbox, and the list of values changes per OrderID (what the form I am using this on populates information for in the first place; unique instance). I am looking for something that will evaluate this list one at a time (i.e. iterate through the list of values, and look for "DeptA", and if it is found add yes to the SQL string, and if it not add no to the SQL string, then march on to the next iteration). Even though the listbox populates values dynamically, they are set values, meaning i know what could end up in it. Thanks for any help, Justin

    Read the article

  • Optimizing a large iteration of PHP objects (EAV-based)

    - by Aron Rotteveel
    I am currently working on a project that utilizes the EAV model. This turns out to work quite well, but like many others I am now stumbling upon some performance issues. The data set in this particular case consists of aproximately 2500 entities, each with aprox. 150 attributes. Each entity and each attribute is represented by a PHP-object. Since most parts of the application only iterate through a filtered set of entities, we have not had very large issues yet. Now, however, I am working on an algorithm that requires iteration over the entire dataset, which causes a major impact on performance. This information is perhaps not very much to work with, but since this is an architectural problem, I am hoping for a architectural pattern to help me on the way as well. Each entity, including it's attributes takes up aprox. 500KB of memory.

    Read the article

  • More pythonic way to iterate

    - by fmark
    I am using a module that is part of a commercial software API. The good news is there is a python module - the bad news is that its pretty unpythonic. To iterate over rows, the follwoing syntax is used: cursor = gp.getcursor(table) row = cursor.Next() while row: #do something with row row = cursor.next() What is the most pythonic way to deal with this situation? I have considered creating a first class function/generator and wrapping calls to a for loop in it: def cursor_iterator(cursor): row = cursor.Next() while row: yield row row = cursor.next() [...] cursor = gp.getcursor(table) for row in cursor_iterator(cursor): # do something with row This is an improvement, but feels a little clumsy. Is there a more pythonic approach? Should I create a wrapper class around the table type?

    Read the article

  • Pair-wise iteration in C# or sliding window enumerator

    - by f3lix
    If I have an IEnumerable like: string[] items = new string[] { "a", "b", "c", "d" }; I would like to loop thru all the pairs of consecutive items (sliding window of size 2). Which would be ("a","b"), ("b", "c"), ("c", "d") My solution was is this public static IEnumerable<Pair<T, T>> Pairs(IEnumerable<T> enumerable) { IEnumerator<T> e = enumerable.GetEnumerator(); e.MoveNext(); T current = e.Current; while ( e.MoveNext() ) { T next = e.Current; yield return new Pair<T, T>(current, next); current = next; } } // used like this : foreach (Pair<String,String> pair in IterTools<String>.Pairs(items)) { System.Out.PrintLine("{0}, {1}", pair.First, pair.Second) } When I wrote this code, I wondered if there are already functions in the .NET framework that do the same thing and do it not just for pairs but for any size tuples. IMHO there should be a nice way to do this kind of sliding window operations. I use C# 2.0 and I can imagine that with C# 3.0 (w/ LINQ) there are more (and nicer) ways to do this, but I'm primarily interested in C# 2.0 solutions. Though, I will also appreciate C# 3.0 solutions.

    Read the article

  • Joining the previous and next sentence using python

    - by JudoWill
    I'm trying to join a set of sentences contained in a list. I have a function which determines whether a sentence in worth saving. However, in order to keep the context of the sentence I need to also keep the sentence before and after it. In the edge cases, where its either the first or last sentence then, I'll just keep the sentence and its only neighbor. An example is best: ex_paragraph = ['The quick brown fox jumps over the fence.', 'Where there is another red fox.', 'They run off together.', 'They live hapily ever after.'] t1 = lambda x: x.startswith('Where') t2 = lambda x: x'startswith('The ') The result for t1 should be: ['The quick brown fox jumps over the fence. Where there is another red fox. They run off together.'] The result for t2 should be: ['The quick brown fox jumps over the fence. Where there is another red fox.'] My solution is: def YieldContext(sent_list, cont_fun): def JoinSent(sent_list, ind): if ind == 0: return sent_list[ind]+sent_list[ind+1] elif ind == len(sent_list)-1: return sent_list[ind-1]+sent_list[ind] else: return ' '.join(sent_list[ind-1:ind+1]) for sent, sentnum in izip(sent_list, count(0)): if cont_fun(sent): yield JoinSent(sent_list, sent_num) Does anyone know a "cleaner" or more pythonic way to do something like this. The if-elif-else seems a little forced. Thanks, Will PS. I'm obviously doing this with a more complicated "context-function" but this is just for a simple example.

    Read the article

  • Fast iterating over first n items of an iterable in python

    - by martinthenext
    Hello! I'm looking for a pythonic way of iterating over first n items of a list, and it's quite important to do this as fast as possible. This is how I do it now: count = 0 for item in iterable: do_somethin(item) count += 1 if count >= n: break Doesn't seem neat to me. Another way of doing this is: for item in itertools.islice(iterable, n): do_something(item) This looks good, the question is it fast enough to use with some generator(s)? For example: pair_generator = lambda iterable: itertools.izip(*[iter(iterable)]*2) for item in itertools.islice(pair_generator(iterable), n): so_something(item) Will it run fast enough as compared to the first method? Is there some easier way to do it?

    Read the article

  • Fast iterating over first n items of an iterable (not a list) in python

    - by martinthenext
    Hello! I'm looking for a pythonic way of iterating over first n items of an iterable (upd: not a list in a common case, as for lists things are trivial), and it's quite important to do this as fast as possible. This is how I do it now: count = 0 for item in iterable: do_something(item) count += 1 if count >= n: break Doesn't seem neat to me. Another way of doing this is: for item in itertools.islice(iterable, n): do_something(item) This looks good, the question is it fast enough to use with some generator(s)? For example: pair_generator = lambda iterable: itertools.izip(*[iter(iterable)]*2) for item in itertools.islice(pair_generator(iterable), n): so_something(item) Will it run fast enough as compared to the first method? Is there some easier way to do it?

    Read the article

  • Loop over a file and write the next line if a condition is met

    - by 111078384259264152964
    Having a hard time fixing this or finding any good hints about it. I'm trying to loop over one file, modify each line slightly, and then loop over a different file. If the line in the second file starts with the line from the first then the following line in the second file should be written to a third file. !/usr/bin/env python with open('ids.txt', 'rU') as f: with open('seqres.txt', 'rU') as g: for id in f: id=id.lower()[0:4]+'_'+id[4] with open(id + '.fasta', 'w') as h: for line in g: if line.startswith(''+ id): h.write(g.next()) All the correct files appear, but they are empty. Yes, I am sure the if has true cases. :-) "seqres.txt" has lines with an ID number in a certain format, each followed by a line with data. The "ids.txt" has lines with the ID numbers of interest in a different format. I want each line of data with an interesting ID number in its own file. Thanks a million to anyone with a little advice!

    Read the article

  • Get number of times in loop over Hash object

    - by Matt Huggins
    I have an object of type Hash that I want to loop over via hash.each do |key, value|. I would like to get the number of times I've been through the loop starting at 1. Is there a method similar to each that provides this (while still providing the hash key/value data), or do I need to create another counter variable to increment within the loop?

    Read the article

  • Iterating over key and value of defaultdict dictionaries

    - by gf
    The following works as expected: d = [(1,2), (3,4)] for k,v in d: print "%s - %s" % (str(k), str(v)) But this fails: d = collections.defaultdict(int) d[1] = 2 d[3] = 4 for k,v in d: print "%s - %s" % (str(k), str(v)) With: Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable Why? How can i fix it?

    Read the article

  • Need help iteratating over an array, retrieve two possibilites, no repeats, for Poker AI

    - by elguapo-85
    Can't really think of a good way to word this question, nor a good title, and maybe the answer is so ridiculously simple that I am missing it. I am working on a poker AI, and I want to calculate the number of hands that exist which are better then mine, I understand how to that, but want I can't figure out is the best way to iterate over a group of cards. So I am at the flop, I know what my two cards are and there are 3 cards on the board. So there are 47 unknown cards and I want to iterate over all possible combination of those 47 cards assuming that two are passed out, so you can't have two cards of the same rank and suit, and you if you have previously calculated a set you don't want to do it over again, because I will being wasting time, and this will be called many times. If you don't understand want I am asking please tell me and I will clarify more. So I can set something up like this, if that element equals one, it means it is not in my hand and not on the board, 4 for each suit, and 13 for each rank. setOfCards[4][13] If I do a simple set of for loops like this: (pseudocode) //remove cards I know are in play from setOfCards by setting values to zero for(int i = 0; i < 4; i++) for(int j = 0; j < 13; j++) for(int k = 0; k < 4; k++) for(int l = 0; l < 4; l++) //skip if values equal zero card1 = setOfCards[i][j] card2 = setOfCards[k][l] //now compare card1, card2 and set of board cards So this is actually going to repeat many values, for example: card1 = AceOfHearts, card2 = KingOfHearts is the same as card1 = KingOfHearts, card2 = AceOfHearts. It will also alter my calculations. How should I go about avoiding this? Also is there a name for this technique? Thank you.

    Read the article

  • Haskell - function (that returns a list) on each element in a list

    - by Ben
    The assignment is to create a multiples function and I essentially want todo the following code: map (\t -> scanl (\x y -> x+y) t (repeat t)) listofnumbers The problem is that the scanl function returns a list of results rather than the one which the map function requires. So is there a function that will allow the return of lists?

    Read the article

  • Java iteration reading & parsing

    - by Patrick Lorio
    I have a log file that I am reading to a string public static String Read (String path) throws IOException { StringBuilder sb = new StringBuilder(); InputStream in = new BufferedInputStream(new FileInputStream(path)); int r; while ((r = in.read()) != -1) { sb.append(r); } return sb.toString(); } Then I have a parser that iterates over the entire string once void Parse () { String con = Read("log.txt"); for (int i = 0; i < con.length; i++) { /* parsing action */ } } This is hugely a waste of cpu cycles. I loop over all the content in Read. Then I loop over all the content in Parse. I could just place the /* parsing action */ under the while loop in the Read method, which would be find but I don't want to copy the same code all over the place. How can I parse the file in one iteration over the contents and still have separate methods for parsing and reading? In C# I understand there is some sort of yield return thing, but I'm locked with Java. What are my options in Java?

    Read the article

  • d2: assigning ranges/iterators to array slices

    - by modchan
    Consider following code: enum size = 16; double[size] arr1 = [...]; double[size] arr2 = [...]; process = (double x) { return (x + 1); }; arr2[] = map!(process)(arr1[]); // here I have trouble converting results of map back to my plain array. Problem applies not only to map, but also to take, repeat and all those fine tools from std.algorithm and std.range that operate on ranges. On this assignment, I get Error: cannot implicitly convert expression (map(arr1[])) of type Result to double[]. How can I evaluate range to array without using uint i = 0; foreach (x; map!(process)(arr1[])) { arr2[i] = x; i++; } ? Additionally, can someone please explain, why I must call map!(process)(arr1[]) instead of map!(process)(arr1) with static arrays? Shouldn't static arrays be compatible with dynamic for means of iteration, or I don't get something? Also, it seems that straightforward enumeration syntax foreach (index, item; sequence) does not work for ranges - are there workarounds? I guess the reason is the same as why ranges cannot be assigned to array slices.

    Read the article

  • recursive_directory_iterator exception

    - by Jon
    I'm writing a simple program which moves files on my desktop to new location. I don't understand why it crashes after the file has been moved. for(recursive_directory_iterator it(desktop), end; it != end; ++it) { if(it->path().leaf() == fileToMove) { rename(*it, newPath); } } A point in the right direction would be appropriated. Thanks!

    Read the article

  • How do you iterate through each email in your inbox using python?

    - by djblue2009
    I'm completely new to programming and I'm trying to build an autorespoder to send a msg to a specific email address. Using an if statement, I can check if there is an email from a certain address in the inbox and I can send an email, but if there are multiple emails from that address, how can I make a for loop to send an email for every email from that specific address. I tried to do use this as a loop: for M.search(None, 'From', address) in M.select(): but I get the error: "can't assign to function call" on that line

    Read the article

  • what is the pattern for modifying a collection in C#

    - by macias
    What is the pattern (best practice) for such problem -- modifying elements (values) in collection? Conditions: size of the collection is not changed (no element is deleted or added) modification is in-place In C++ it was easy and nice, I just iterated trough a collection and changed the elements. But in C# iterating (using enumerator) is read-only operation (speaking in terms of C++, only const_iterator is available). So, how to do this in C#? Example: having sequence of "1,2,3,4" modification is changing it to "1, 2, 8, 9" but not "1, 2, 3" or "1, 2, 3, 4, 5".

    Read the article

  • Is there any short way to load data to the properties of a class, for each column name matching the properties of the class?

    - by Ugur Gümüshan
    I want to load data to an instance of an object using its constructor and I write $this->property=$row["colname"] each time for each property. the mysql_fetch_object function fetches the data as an object but I am not sure if the instance of an object can be assigned to some object from inside. othwerwise I would use __construct($object) { $this=$object; } //doesn't give any syntax error Maybe I should look into iteration of properties and use foreach($object as $key => $value) $value=$object[$key]; or can I assign like $this=$object; within the constructor?

    Read the article

  • displaying structs in an array using enumerator

    - by Mostaguen
    In an object I have : public IEnumerable<voiture> recup_voitures() { foreach (voiture v in _arrVCollection) { yield return (v); } } voiture being a struct and _arrVCollection being an array containing some struct voiture. In my main class I have : foreach (CarCollection.voiture o in collection.recup_voitures()) { //some code to display the content of each struct } What is happening is that if I have an array of length 5 and only 1 struct voiture in it, it will do the displaying code 5 times instead of only 1. What am I doing wrong?

    Read the article

  • Is there any way to get all the controls on a container control?

    - by Mason Wheeler
    I've got a form with a bunch of controls on it, and I wanted to iterate through all the controls on a certain panel and enable/disable them. I tried this: var component: TComponent; begin for component in myPanel do (component as TControl).Enabled := Value; end; But that did nothing. Turns out all components are in the form's component collection, not their parent object's. So does anyone know if there's any way to get all the controls inside a control? (Besides an ugly workaround like this, which is what I ended up having to do): var component: TComponent; begin for component in myPanel do if (component is TControl) and (TControl(component).parent = myPanel) then TControl(component).Enabled := Value; end; Someone please tell me there's a better way...

    Read the article

  • Are there any C# collections where modification does not invalidate iterators?

    - by young-phillip
    Are there any data structures in the C# Collections library where modification of the structure does not invalidate iterators? Consider the following: List<int> myList = new List<int>(); myList.Add( 1 ); myList.Add( 2 ); List<int>.Enumerator myIter = myList.GetEnumerator(); myIter.MoveNext(); // myIter.Current == 1 myList.Add( 3 ); myIter.MoveNext(); // throws InvalidOperationException

    Read the article

  • Python: concatenate generator and item

    - by TarGz
    I have a generator (numbers) and a value (number). I would like to iterate over these as if they were one sequence: i for i in tuple(my_generator) + (my_value,) The problem is, as far as I undestand, this creates 3 tuples only to immediately discard them and also copies items in "my_generator" once. Better approch would be: def con(seq, item): for i in seq: yield seq yield item i for i in con(my_generator, my_value) But I was wondering whether it is possible to do it without that function definition

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >