Search Results

Search found 95 results on 4 pages for 'iterable'.

Page 1/4 | 1 2 3 4  | Next Page >

  • Implementig Java Iterable<E> interface

    - by Metz
    Hi, i wrote this code: public class C1 implements Iterable<NC1> { private LinkedList<NC1> list; public static class NC1 { ... } ... x public Iterator<NC1> iterator() { return list.iterator(); } } but eclipse whines (at the x-ed line): - The return type is incompatible with Iterable<NC1>.iterator() - implements java.lang.Iterable<NC1>.iterator i don't understand where the mistake is. thanks in advance.

    Read the article

  • Django filter bool not iterable

    - by dana
    I want to filter all Relation Objects where (relation= following relation in a virtual community) the date one has initiated the following is in the past, related to the moment now. The following declaration seems to be wrong, as a bool object is not iterable. Is there another way to do that? d = Relations.objects.filter(date_follow < datetime.now())

    Read the article

  • Redirect print in Python: val = print(arg) to output mixed iterable to file

    - by emcee
    So lets say I have an incredibly nested iterable of lists/dictionaries. I would like to print them to a file as easily as possible. Why can't I just redirect print to a file? val = print(arg) gets a SyntaxError. Is there a way to access stdinput? And why does print take forever with massive strings? Bad programming on my side for outputting massive strings, but quick debugging--and isn't that leveraging the strength of an interactive prompt? There's probably also an easier way than my gripe. Has the hive-mind an answer?

    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

  • How can I get a iterable resultset from the database using pdo, instead of a large array?

    - by Tchalvak
    I'm using PDO inside a database abstraction library function query. I'm using fetchAll(), which if you have a lot of results, can get memory intensive, so I want to provide an argument to toggle between a fetchAll associative array and a pdo result set that can be iterated over with foreach and requires less memory (somehow). I remember hearing about this, and I searched the PDO docs, but I couldn't find any useful way to do that. Does anyone know how to get an iterable resultset back from PDO instead of just a flat array? And am I right that using an iterable resultset will be easier on memory? I'm using Postgresql, if it matters in this case. . . . The current query function is as follows, just for clarity. /** * Running bound queries on the database. * * Use: query('select all from players limit :count', array('count'=>10)); * Or: query('select all from players limit :count', array('count'=>array(10, PDO::PARAM_INT))); **/ function query($sql_query, $bindings=array()){ DatabaseConnection::getInstance(); $statement = DatabaseConnection::$pdo->prepare($sql_query); foreach($bindings as $binding => $value){ if(is_array($value)){ $statement->bindParam($binding, $value[0], $value[1]); } else { $statement->bindValue($binding, $value); } } $statement->execute(); // TODO: Return an iterable resultset here, and allow switching between array and iterable resultset. return $statement->fetchAll(PDO::FETCH_ASSOC); }

    Read the article

  • How to compose a Matcher[Iterable[A]] from a Matcher[A] with specs testing framework

    - by Garrett Rowe
    If I have a Matcher[A] how do create a Matcher[Iterable[A]] that is satisfied only if each element of the Iterable satisfies the original Matcher. class ExampleSpec extends Specification { def allSatisfy[A](m: => Matcher[A]): Matcher[Iterable[A]] = error("TODO") def notAllSatisfy[A](m: => Matcher[A]): Matcher[Iterable[A]] = allSatisfy(m).not "allSatisfy" should { "Pass if all elements satisfy the expectation" in { List(1, 2, 3, 4) must allSatisfy(beLessThan(5)) } "Fail if any elements do not satisfy the expectation" in { List(1, 2, 3, 5) must notAllSatisfy(beLessThan(5)) } } }

    Read the article

  • scala implicit or explicit conversion from iterator to iterable

    - by landon9720
    Does Scala provide a built-in class, utility, syntax, or other mechanism for converting (by wrapping) an Iterator with an Iterable? For example, I have an Iterator[Foo] and I need an Iterable[Foo], so currently I am: val foo1: Iterator[Foo] = .... val foo2: Iterable[Foo] = new Iterable[Foo] { def elements = foo1 } This seems ugly and unnecessary. What's a better way?

    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

  • Is there an equivalent in Scala to Python's more general map function?

    - by wheaties
    I know that Scala's Lists have a map implementation with signature (f: (A) => B):List[B] and a foreach implementation with signature (f: (A) => Unit):Unit but I'm looking for something that accepts multiple iterables the same way that the Python map accepts multiple iterables. I'm looking for something with a signature of (f: (A,B) => C, Iterable[A], Iterable[B] ):Iterable[C] or equivalent. Is there a library where this exists or a comparable way of doing similar?

    Read the article

  • Passing a non-iterable to list.extend ()

    - by JS
    Hello, I am creating a public method to allow callers to write values to a device, call it write_vals() for example. Since these values will by typed live, I would like to simplify the user's life by allowing them type in either a list or a single value, depending on how many values they need to write. For example: write_to_device([1,2,3]) or write_to_device(1) My function would like to work with a flat list, so I tried to be clever and code something like this: input_list = [] input_list.extend( input_val ) This works swimmingly when the user inputs a list, but fails miserably when the user inputs a single integer: TypeError: 'int' object is not iterable Using list.append() would create a nested list when a list was passed in, which would be an additional hassle to flatten. Checking the type of the object passed in seems clumsy and non-pythonic and wishing that list.extend() would accept non-iterables has gotten me nowhere. So has trying a variety of other coding methods. Suggestions (coding-related only, please) would be greatly appreciated.

    Read the article

  • Java->Scala Remove Iterator<T>-Element from a JavaConversions-wrapped Iterable

    - by ifischer
    I have to translate the following code from Java to Scala: for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext();) { ExceptionQueuedEvent event = i.next(); try { //do something } finally { i.remove(); } } I'm using the JavaConversions library to wrap the Iterable. But as i'm not using the original Iterator, i don't know how to remove the current element correctly from the collection the same way as i did in Java: import scala.collection.JavaConversions._ (...) for (val event <- events) { try { //do something } finally { //how can i remove the current event from events? } } Can someone help me? I guess it's easy, but i'm still kinda new to Scala and don't understand what's going on when Scala wraps something of Java.

    Read the article

  • Implementing Iterable in Java

    - by Artium
    I have the following code public class A extends Iterable<Integer> { ... public Iterator<Integer> iterator() { return new Iterator<Integer>() { A a; public boolean hasNext() { ... } public Integer next() { ... } public void remove(){ ... } }; I would like to initialize the "a" field in the anonymous class with the instance of A that iterator method was called on. Is it possible? Thank you.

    Read the article

  • Exception handling in Iterable

    - by Maas
    Is there any way of handling -- and continuing from -- an exception in an iterator while maintaining the foreach syntactic sugar? I've got a parser that iterates over lines in a file, handing back a class-per-line. Occasionally lines will be syntactically bogus, but that doesn't necessarily mean that we shouldn't keep reading the file. My parser implements Iterable, but dealing with the potential exceptions means writing for (Iterator iter = myParser.iterator(); iter.hasNext(); ) { try { MyClass myClass = iter.next(); // .. do stuff .. } catch (Exception e) { // .. do exception stuff .. } } .. nothing wrong with that, but is there any way of getting exception handling on the implicit individual iter.next() calls in the foreach construct?

    Read the article

  • Output of Iterable.sliding as Tuple

    - by ziggystar
    The method sliding on collections returns a sliding window of given size in the form of X[Iterable[A]] with X being the type of the collection and A the element type. Often I need two or three elements and I prefer to have them named. One ugly workaround for sliding(2) is the following: points.sliding(2).foreach{ twoPoints => val (p1,p2) = (twoPoints.head,twoPoints.last) //do something } This sucks and only works for two elements. Also note that (a,b) = (twoPoints(0),twoPoints(1)) doesn't work. Help me!

    Read the article

  • Java: why can't iterate over an iterator?

    - by noamtm
    I read http://stackoverflow.com/questions/839178/why-is-javas-iterator-not-an-iterable and http://stackoverflow.com/questions/27240/why-arent-enumerations-iterable, but I still don't understand why this: void foo(Iterator<X> it) { for (X x : it) { bar(x); baz(x); } } was not made possible. In other words, unless I'm missing something, the above could have been nice and valid syntactic sugar for: void foo(Iterator<X> it) { for (X x; it.hasNext();) { x = it.next(); bar(x); baz(x); } }

    Read the article

  • min() and max() give error: TypeError: 'float' object is not iterable

    - by PythonUser3.3
    markList=[] Lmark=0 Hmark=0 while True: mark=float(input("Enter your marks here(Click -1 to exit)")) if mark == -1: break markList.append(mark) markList.sort() mid = len(markList)//2 if len(markList)%2==0: median=(markList[mid]+ markList[mid-1])/2 print("Median:", median) else: print("Median:" , markList[mid]) Lmark==(min(mark)) print("The lowest mark is", Lmark) Hmark==(max(mark)) print("The highest mark is", Hmark) My program is a basic grade calculator using lists. My program asks the user to input their grades into a list in which it then calculates your average and finds your lowest and highest mark. I have found the average but I can't seem to figure out how to find the lowest and highest grade. Can you please show me pr tell me what to do?

    Read the article

  • Adapting non-iterable containers to be iterated via custom templatized iterator

    - by DAldridge
    I have some classes, which for various reasons out of scope of this discussion, I cannot modify (irrelevant implementation details omitted): class Foo { /* ... irrelevant public interface ... */ }; class Bar { public: Foo& get_foo(size_t index) { /* whatever */ } size_t size_foo() { /* whatever */ } }; (There are many similar 'Foo' and 'Bar' classes I'm dealing with, and it's all generated code from elsewhere and stuff I don't want to subclass, etc.) [Edit: clarification - although there are many similar 'Foo' and 'Bar' classes, it is guaranteed that each "outer" class will have the getter and size methods. Only the getter method name and return type will differ for each "outer", based on whatever it's "inner" contained type is. So, if I have Baz which contains Quux instances, there will be Quux& Baz::get_quux(size_t index), and size_t Baz::size_quux().] Given the design of the Bar class, you cannot easily use it in STL algorithms (e.g. for_each, find_if, etc.), and must do imperative loops rather than taking a functional approach (reasons why I prefer the latter is also out of scope for this discussion): Bar b; size_t numFoo = b.size_foo(); for (int fooIdx = 0; fooIdx < numFoo; ++fooIdx) { Foo& f = b.get_foo(fooIdx); /* ... do stuff with 'f' ... */ } So... I've never created a custom iterator, and after reading various questions/answers on S.O. about iterator_traits and the like, I came up with this (currently half-baked) "solution": First, the custom iterator mechanism (NOTE: all uses of 'function' and 'bind' are from std::tr1 in MSVC9): // Iterator mechanism... template <typename TOuter, typename TInner> class ContainerIterator : public std::iterator<std::input_iterator_tag, TInner> { public: typedef function<TInner& (size_t)> func_type; ContainerIterator(const ContainerIterator& other) : mFunc(other.mFunc), mIndex(other.mIndex) {} ContainerIterator& operator++() { ++mIndex; return *this; } bool operator==(const ContainerIterator& other) { return ((mFunc.target<TOuter>() == other.mFunc.target<TOuter>()) && (mIndex == other.mIndex)); } bool operator!=(const ContainerIterator& other) { return !(*this == other); } TInner& operator*() { return mFunc(mIndex); } private: template<typename TOuter, typename TInner> friend class ContainerProxy; ContainerIterator(func_type func, size_t index = 0) : mFunc(func), mIndex(index) {} function<TInner& (size_t)> mFunc; size_t mIndex; }; Next, the mechanism by which I get valid iterators representing begin and end of the inner container: // Proxy(?) to the outer class instance, providing a way to get begin() and end() // iterators to the inner contained instances... template <typename TOuter, typename TInner> class ContainerProxy { public: typedef function<TInner& (size_t)> access_func_type; typedef function<size_t ()> size_func_type; typedef ContainerIterator<TOuter, TInner> iter_type; ContainerProxy(access_func_type accessFunc, size_func_type sizeFunc) : mAccessFunc(accessFunc), mSizeFunc(sizeFunc) {} iter_type begin() const { size_t numItems = mSizeFunc(); if (0 == numItems) return end(); else return ContainerIterator<TOuter, TInner>(mAccessFunc, 0); } iter_type end() const { size_t numItems = mSizeFunc(); return ContainerIterator<TOuter, TInner>(mAccessFunc, numItems); } private: access_func_type mAccessFunc; size_func_type mSizeFunc; }; I can use these classes in the following manner: // Sample function object for taking action on an LMX inner class instance yielded // by iteration... template <typename TInner> class SomeTInnerFunctor { public: void operator()(const TInner& inner) { /* ... whatever ... */ } }; // Example of iterating over an outer class instance's inner container... Bar b; /* assume populated which contained items ... */ ContainerProxy<Bar, Foo> bProxy( bind(&Bar::get_foo, b, _1), bind(&Bar::size_foo, b)); for_each(bProxy.begin(), bProxy.end(), SomeTInnerFunctor<Foo>()); Empirically, this solution functions correctly (minus any copy/paste or typos I may have introduced when editing the above for brevity). So, finally, the actual question: I don't like requiring the use of bind() and _1 placeholders, etcetera by the caller. All they really care about is: outer type, inner type, outer type's method to fetch inner instances, outer type's method to fetch count inner instances. Is there any way to "hide" the bind in the body of the template classes somehow? I've been unable to find a way to separately supply template parameters for the types and inner methods separately... Thanks! David

    Read the article

  • Object directing to a property when accessed as an iterable

    - by ThE_JacO
    I'm trying to figure out if there's an elegant and concise way to have a class accessing one of its own properties when "used" as a dictionary, basically redirecting all the methods that'd be implemented in an ordered dictionary to one of its properties. Currently I'm inheriting from IterableUserDict and explicitly setting its data to another property, and it seems to be working, but I know that UserDict is considered sort of old, and I'm concerned I might be overlooking something. What I have: class ConnectionInterface(IterableUserDict): def __init__(self, hostObject): self._hostObject= hostObject self.ports= odict.OrderedDict() self.inputPorts= odict.OrderedDict() self.outputPorts= odict.OrderedDict() self.data= self.ports This way I expect the object to behave and respond (and be used) the way I mean it to, except I want to get a freebie ordered dictionary behaviour on its property "ports" when it's iterated, items are gotten by key, something is looked up ala if this in myObject, and so on. Any advice welcome, the above seems to be working fine, but I have an odd itch that I might be missing something. Thanks in advance.

    Read the article

  • Python enumerate built-in error when using the start parameter

    - by TheJuice
    I'm modifying some code that calls enumerate on a list declared via a list comprehension e.g. self.groups = [Groups(self, idx) for idx in range(n_groups)] then later: for idx, group in enumerate(self.groups): # do some stuff but when I change the enumerate call to start at the 2nd list element via the start parameter e.g. for idx, group in enumerate(self.groups[1]): I get an exception: exceptions.TypeError: 'Group' object is not iterable Could someone explain why this is?

    Read the article

  • Why does Option not extend the Iterable trait directly?

    - by oxbow_lakes
    Option is implicitly convertible to an Iterable - but why does it not just just implement Iterable directly: def iterator = new Iterator[A] { var end = !isDefined def next() = { val n = if (end) throw new NoSuchElementException() else get end = true n } def hasNext = !end } EDIT: In fact it's even weider than that because in 2.8 Option does declare an iterator method: def iterator: Iterator[A] = if (isEmpty) Iterator.empty else Iterator.single(this.get)

    Read the article

  • Python method to remove iterability

    - by Debilski
    Suppose I have a function which can either take an iterable/iterator or a non-iterable as an argument. Iterability is checked with try: iter(arg). Depending whether the input is an iterable or not, the outcome of the method will be different. Not when I want to pass a non-iterable as iterable input, it is easy to do: I’ll just wrap it with a tuple. What do I do when I want to pass an iterable (a string for example) but want the function to take it as if it’s non-iterable? E.g. make that iter(str) fails.

    Read the article

1 2 3 4  | Next Page >