def rule_MetaExpression(self): """ Meta expression. (@see page 12) func func[arg] func[arg;...;arg] """ with self: _s = [] _func = self.token_ATOM() _args = [] if self[0] == '[': _delim = '[' while self[0] != ']': assert self[0] == _delim _s += [self.consume(1)] # '[' or ';' _delim = ';' _e = self.rule_SymbolicExpression() _s += [_e.s] _args += [_e] _s += [self.consume(1)] # ']' _s = tuple(_s) _args = tuple(_args) return self.MetaExpression(s=_s, func=_func, args=_args)
def get_all(cls, conn, book_id=None, title=None, publisher_name=None, publisher_id=None): query = """ SELECT * FROM {} WHERE B.bookId IS NOT NULL """ tables = ['Book B'] values = [] if book_id: query+= ' AND bookId = ?' values.append(book_id) if title: query+= ' AND title LIKE ?' values.append('%'+title+'%') if publisher_name: tables.append('Publisher P') query+= ' AND B.publisherId = P.publisherId' query+= ' AND P.name LIKE ?' values.append('%'+publisher_name+'%') if publisher_id: query+= ' AND B.publisherId = ?' values.append(publisher_id) try: c = conn.cursor() c.execute(query.format(','.join(tables)), tuple(values)) rows = c.fetchall() except sqlite3.Error as e: raise e books = [Book.create_from_books(conn, row) for row in rows] return books
def rule_DataLine(self): r""" rule_DataLine = token_WHITESPACE? ( token_DATA token_WHITESPACE? )+ rule_EmptyLine ;; the token_WHITESPACE at the start is the indent """ with self: # revert state on error _s = [] _lineNumber = self.state.lineNumber _indent = self.maybe(self.token_WHITESPACE) if _indent is None: _indent = self.consume(0) _s += [_indent] _tokens = [] while True: try: _token = self.token_TOKEN() _tokens += [_token] _s += [_token] _whitespace = self.maybe(self.token_WHITESPACE) if _whitespace is not None: _s += [_whitespace] except AssertionError: break # no more tokens _empty_line = self.rule_EmptyLine() _s += [_empty_line.s] assert len(_tokens) > 0 # expecting a token _s = tuple(_s) return self.DataLine(s=_s, indent=_indent, tokens=_tokens, lineNumber=_lineNumber)
def rule_Literal(self): r""" literal singleton range exclude '"' characters '"' """ # NOTE range must come first because it starts with a singleton try: with self: # restore state on error _range = self.rule_Range() _exclude = self.rule_Exclude() return tuple(list(_range) + ['.exclude', _exclude]) except AssertionError: pass try: _singleton = self.rule_Singleton() return _singleton except AssertionError: pass try: with self: # restore state on error _discard = self._str('"') _characters = self.token_CHARACTERS() _discard = self._str('"') return ( 'Characters', '.str', _characters, ) except AssertionError: pass assert False, (self.state, ) # not a rule_Literal?
def rule_Exclude(self): r""" exclude "" space '-' space singleton exclude space '-' space range exclude """ _exclude = [] # zero or more while True: # NOTE range must come first because it starts with a singleton try: with self: # restore state on error _discard = self.token_SPACE() _discard = self._str('-') _discard = self.token_SPACE() _range = self.rule_Range() _exclude += [_range] continue except AssertionError: pass try: with self: # restore state on error _discard = self.token_SPACE() _discard = self._str('-') _discard = self.token_SPACE() _singleton = self.rule_Singleton() _exclude += [_singleton] continue except AssertionError: pass break # ignore the rest return tuple(_exclude)
def tuple_processor(data): if not isinstance(data, __builtin__.tuple) and not coerce_: raise DataTypeError('tuple') else: if not isinstance(data, basestring): try: data = __builtin__.tuple(data) except TypeError: data = (data, ) else: data = (data, ) cleandata = [] for element in data: cleandata.append(checker.process(element)) return __builtin__.tuple(cleandata)
def rule_Codepoint(self): """ rule_Codepoint = byte_Leading byte_Continuation* """ _sub_rules = [ # _prefix, _prefix_mask, _data_mask, _n_continuation ( self.HIGH_0, self.HIGH_1, self.LOW_7, 0, ), # 0xxxxxxx ( self.HIGH_2, self.HIGH_3, self.LOW_5, 1, ), # 110xxxxx 10xxxxxx ( self.HIGH_3, self.HIGH_4, self.LOW_4, 2, ), # 1110xxxx 10xxxxxx 10xxxxxx ( self.HIGH_4, self.HIGH_5, self.LOW_3, 3, ), # 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx ( self.HIGH_5, self.HIGH_6, self.LOW_2, 4, ), # 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx ( self.HIGH_6, self.HIGH_7, self.LOW_1, 5, ), # 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx # 11111110 is 0xFE, used for the BOM in UTF-16, currently meaningless in utf8 # 11111111 is 0xFF, used for the BOM in UTF-16, currently meaningless in utf8 ] with self: _leading = self.byte_Leading() _b = _leading.b for _prefix, _prefix_mask, _data_mask, _n_continuations in _sub_rules: if _prefix == (_b & _prefix_mask): _codepoint = (_b & _data_mask) break else: assert False, _b # invalid utf8? _s = [_leading.s] for _ in range(_n_continuations): _continuation = self.byte_Continuation() _b = _continuation.b _codepoint = (_codepoint << 6) + (_b & self.LOW_6) _s += [_continuation.s] return self.Codepoint(codepoint=_codepoint, s=tuple(_s))
def rule_DataNode(self, parent_indent=None): r""" rule_DataNode = ( rule_EmptyLine )* rule_DataLine rule_DataNode* ;; the rule_DataNode at the end must be children """ with self: # revert cursor on error _s = [] _lineNumber = self.state.lineNumber while True: _emptyline = self.maybe(self.rule_EmptyLine) if _emptyline is None: break # no more empty lines _s += [_emptyline.s] _dataline = self.rule_DataLine() _indent = _dataline.indent if parent_indent is None: assert _dataline.indent == '' # must be at line start else: assert _dataline.indent != parent_indent # must be a child assert _dataline.indent.startswith(parent_indent) # must match _s += [_dataline.s] _children = [] while True: try: with self: _child = self.rule_DataNode(parent_indent=_indent) if _children: assert _children[0].indent == _child.indent, ( _children[0].indent, child.indent, ) # must be at the same level _children += [_child] _s += [_child.s] except AssertionError as err: break # no more children _s = tuple(_s) _tokens = tuple(_dataline.tokens) _lines = slice(_lineNumber, self.state.lineNumber) _children = tuple(_children) _datanode = self.DataNode(s=_s, indent=_indent, tokens=_tokens, lines=_lines, children=_children) return _datanode
def rule_SymbolicExpression(self, abbreviation=False): """ Symbolic expression. (@see pages 11-12) Can be: ATOM (e1·e2) Abbreviations: (m) -> (m·NIL) (m1,...,mn) -> (m1·(...·(mn·NIL))) (m1,...,mn·x) -> (m1·(...·(mn·x))) ((AB,C),D) -> ((AB·(C·NIL))·(D·NIL)) ((A,B),C,D·E) -> ((A·(B·NIL))·(C·(D·E))) """ with self: _atom = self.maybe(self.token_ATOM) if _atom is not None: # ATOM return _atom _s = [] _e1 = None _e2 = None if abbreviation: _comma = self.token_COMMA() _s += [_comma.s] else: assert self[0] == '(' _s += [self.consume(1)] # '(' _e1 = self.rule_S_expression() _s += [_e1.s] if self[0] == '·': # (e1·e2) _s += [self.consume(1)] # '·' _e2 = self.rule_S_expression() _s += [_e2.s] assert self[0] == ')' _s += [self.consume(1)] # ')' elif self[0] == ')': # abbreviation (m) -> (m·NIL) _e2 = self.ImplicitNilAtom(s=self.consume(0)) _s += [self.consume(1)] # ')' else: # abbreviation (m1,...,mn) -> (m1·(...·(mn·NIL))) # abbreviation (m1,...,mn·x) -> (m1·(...·(mn·x))) _e2 = self.rule_S_expression(abreviation=True) _s += [_e2.s] _s = tuple(_s) assert _e1 is not None assert _e2 is not None return self.SymbolicExpression(s=_s, e1=_e1, e2=_e2)
def _determine_arguments(self, arguments): # # '''Determine right set of arguments for different method types.''' '''Avoid to add object or class references twice.''' if not self.arguments_determined: if self.method_type is builtins.classmethod: arguments = [self.class_object] + builtins.list(arguments) elif not (self.object is None or self.method_type is builtins.staticmethod): arguments = [self.object] + builtins.list(arguments) if self.wrapped_decorator is not None: self.wrapped_decorator.arguments_determined = True return builtins.tuple(arguments)
def rule_Alternatives(self): r""" alternatives alternative alternative alternatives """ _alternatives = [self.rule_Alternative()] # one or more while True: _alternative = self.maybe(self.rule_Alternative) if _alternative is None: break _alternatives += [_alternative] return tuple(_alternatives)
def rule_Items(self): r""" items item item space items """ _items = [self.rule_Item()] # one or more while True: with self: # restore state on error _space = self.maybe(self.token_SPACE) if _space is None: break _item = self.maybe(self.rule_Item) if _item is None: break _items += [_item] return tuple(_items)
def rule_Rules(self): r""" rules rule rule newline rules """ _rules = [self.rule_Rule()] # one or more while True: try: with self: # restore state on error _discard = self.token_NEWLINE() _rule = self.rule_Rule() _rules += [_rule] continue except AssertionError: pass break # ignore the rest return tuple(_rules)
def get_available_gui_toolkits(cls): # # ''' Determines available gui toolkits. Examples: >>> __test_globals__['qt'] = __test_globals__['gtk'] = None >>> Browser('google.de').available_gui_toolkits ('default',) ''' toolkits = [] for toolkit in builtins.globals(): if(builtins.globals()[toolkit] is not None and '_initialize_%s_browser' % toolkit in cls.__dict__): toolkits.append(toolkit) toolkits.append('default') return builtins.tuple(toolkits)
def rule_EmptyLine(self): r""" rule_EmptyLine = token_WHITESPACE? token_COMMENT? token_NEWLINE ; """ with self: # revert state on error _s = [] _whitespace = self.maybe(self.token_WHITESPACE) if _whitespace is not None: _s += [_whitespace] _comment = self.maybe(self.token_COMMENT) if _comment is not None: _s += [_comment] _newline = self.token_NEWLINE() _s += [_newline] _s = tuple(_s) _lineNumber = self.state.lineNumber return self.EmptyLine(s=_s, lineNumber=_lineNumber)
def most_borrowed_books(self, limit=None): query = """ SELECT bookId, Times FROM MostBorrowed WHERE libId = ? """ values = [self.lib_id] if limit is not None: query += ' LIMIT ?' values.append(limit) try: c = self.conn.cursor() c.execute(query, tuple(values)) rows = c.fetchall() except sqlite3.Error: raise result = [dict(book=Books.get(self.conn, row[0]), times=row[1]) for row in rows] return result
def frequent_borrowers(self, limit=None): query = """ SELECT readerId, Times FROM FrequentBorrower WHERE libId = ? """ values = [self.lib_id] if limit: query += ' LIMIT ?' values.append(limit) try: c = self.conn.cursor() c.execute(query, tuple(values)) rows = c.fetchall() except sqlite3.Error: raise results = [dict(reader=Readers.get(self.conn, row[0]), times=row[1]) for row in rows] return results
# return a memoized closure that's lazy and only executes when evaluated def flazy(f, *a, **k): sortedtuple, state = fcompose(builtins.sorted, builtins.tuple), {} def lazy(*ap, **kp): A, K = a+ap, sortedtuple(k.items() + kp.items()) return state[(A, K)] if (A, K) in state else state.setdefault((A, K), f(*A, **builtins.dict(k.items()+kp.items()))) return lazy fmemo = flazy # return a closure with the function's arglist partially applied fpartial = functools.partial # return a closure that applies the provided arguments to the function ``f``. fapply = lambda f, *a, **k: lambda *ap, **kp: f(*(a+ap), **builtins.dict(k.items() + kp.items())) # return a closure that will use the specified arguments to call the provided function. fcurry = lambda *a, **k: lambda f, *ap, **kp: f(*(a+ap), **builtins.dict(k.items() + kp.items())) # return a closure that applies the initial arglist to the end of function ``f``. frpartial = lambda f, *a, **k: lambda *ap, **kp: f(*(ap + builtins.tuple(builtins.reversed(a))), **builtins.dict(k.items() + kp.items())) # return a closure that applies the arglist to function ``f`` in reverse. freversed = freverse = lambda f, *a, **k: lambda *ap, **kp: f(*builtins.reversed(a + ap), **builtins.dict(k.items() + kp.items())) # return a closure that executes function ``f`` and includes the caught exception (or None) as the first element in the boxed result. def fcatch(f, *a, **k): def fcatch(*a, **k): try: return builtins.None, f(*a, **k) except: return sys.exc_info()[1], builtins.None return functools.partial(fcatch, *a, **k) fexc = fexception = fcatch # boolean inversion of the result of a function fcomplement = fnot = frpartial(fcompose, operator.not_) # converts a list to an iterator, or an iterator to a list ilist, liter = fcompose(builtins.list, builtins.iter), fcompose(builtins.iter, builtins.list) # converts a tuple to an iterator, or an iterator to a tuple ituple, titer = fcompose(builtins.tuple, builtins.iter), fcompose(builtins.iter, builtins.tuple)
lista = ['A', 'B', 'C'] # Tuplas # Semelhantes as lista, porem sao imutaveis: # nao se pode alterar itens, apaga-los ou adicionar novos itens # AS tuplas sao mais eficientes do que as listas convencionais, consomente # menos recursos computacionais(memoria), por serem estruturaas mais simples # igualmente sao as strings imutaveis em relacao as mutaveis tupla = (1,[],2,3,4,10) # os parentes sao opcionais # TypeError: 'tuple' object does not support item assignment # tupla[0] = 12 # uma lista pode ser convertida para uma tupla tuplaA = tuple(lista) # mesmo uma tupla formada por elementos mutaveis, nao pode # ter seus elementos modificados #tuplaA[1] = 'a' #tuplaA += ['a'] #tuplaA[0].append('Z') #tupla[0].append(6) tupla[1].append(3) tupla[1].append(56) def addToTuple(tup, pos, e): tup = tup[:pos] + (e,) + tup[pos:] return tup print tupla, (11,) print addToTuple(tupla, 2, 100)
#!/usr/bin/python from __builtin__ import tuple kurt_tupleEx = ('Kurt', 'Von', 'Scholtens', 49, '750 Navaronne Way', 'Concord', 'CA', 94518, '925-429-1724') print kurt_tupleEx[4] kurt_tupleEx2 = tuple('925-222-0566') print kurt_tupleEx2 print kurt_tupleEx2[4:-1]
def as_tuple(iterable): return builtins.tuple(iterable)
def get_all(cls, conn, book_id=None, lib_id=None, number=None, available=None): query = """ SELECT C.copyId, C.number, C.bookId, C.libId FROM {} WHERE C.copyId IS NOT NULL """ tables = ['Copy C'] values = [] if available is True: query += """ AND NOT EXISTS (SELECT R.copyId FROM Reserved R WHERE C.copyId = R.copyID AND R.isReserved = ? UNION SELECT B.copyId FROM Borrowed B WHERE C.copyId = B.copyId AND B.rDatetime IS NULL) """ values.append(True) elif available is False: query += """ AND NOT EXISTS (SELECT R.copyId FROM Reserved R WHERE C.copyId = R.copyID AND R.isReserved = ? UNION SELECT B.copyId FROM Borrowed B WHERE C.copyId = B.copyId AND B.rDatetime IS NOT NULL) AND EXISTS (SELECT B.copyId FROM Borrowed B WHERE C.copyId = B.copyId UNION SELECT R.copyId FROM Reserved R WHERE C.copyId = R.copyId) """ values.append(False) if book_id: query += ' AND C.bookId = ?' values.append(book_id) if lib_id: query += ' AND C.libId = ?' values.append(lib_id) if number: query += ' AND C.number = ?' values.append(number) try: c = conn.cursor() c.execute(query.format(','.join(tables)), tuple(values)) rows = c.fetchall() except sqlite3.Error as e: raise e copies = [Copy.create_from_copies(conn, row) for row in rows] return copies
# return a memoized closure that's lazy and only executes when evaluated def flazy(f, *a, **k): sortedtuple, state = fcompose(__builtin__.sorted, __builtin__.tuple), {} def lazy(*ap, **kp): A, K = a+ap, sortedtuple(k.items() + kp.items()) return state[(A,K)] if (A,K) in state else state.setdefault((A,K), f(*A, **__builtin__.dict(k.items()+kp.items()))) return lazy fmemo = flazy # return a closure with the function's arglist partially applied fpartial = partial = functools.partial # return a closure that applies the provided arguments to the function ``f``. fapply = lambda f, *a, **k: lambda *ap, **kp: f(*(a+ap), **__builtin__.dict(k.items() + kp.items())) # return a closure that will use the specified arguments to call the provided function. fcurry = lambda *a, **k: lambda f, *ap, **kp: f(*(a+ap), **__builtin__.dict(k.items() + kp.items())) # return a closure that applies the initial arglist to the end of function ``f``. frpartial = lambda f, *a, **k: lambda *ap, **kp: f(*(ap + __builtin__.tuple(__builtin__.reversed(a))), **__builtin__.dict(k.items() + kp.items())) # return a closure that applies the arglist to function ``f`` in reverse. freversed = frev = lambda f, *a, **k: lambda *ap, **kp: f(*__builtin__.reversed(a + ap), **__builtin__.dict(k.items() + kp.items())) # return a closure that executes function ``f`` and includes the caught exception (or None) as the first element in the boxed result. def fcatch(f, *a, **k): def fcatch(*a, **k): try: return __builtin__.None, f(*a, **k) except: return sys.exc_info()[1], __builtin__.None return functools.partial(fcatch, *a, **k) fexc = fexception = fcatch # take ``count`` number of elements from an iterator itake = lambda count: compose(iter, fap(*(next,)*count), tuple) # get the ``nth`` element from an iterator iget = lambda count: compose(iter, fap(*(next,)*(count)), tuple, operator.itemgetter(-1)) # copy from itertools imap, ifilter = itertools.imap, itertools.ifilter