def updateBoard(self): # update rows for i in range(0, self.boardHeight): if self.board[i].update(): # player moves with logs if i == (self.height - 1 - self.player.y) and self.board[i].getType() == "RIVER": shift = 2 * (self.board[i].getDir() == DIR_RIGHT) - 1 self.player.x += shift * ( self.player.x + shift >= 0 and self.player.x + shift < self.width) # handle board scrolling if not self.buffer: type = random.randint(0, len(self.rowOptions) - 1) self.buffer.append( Row( self.width, random.randint( max(1, self.rowInterval - int(self.score / 100)), self.rowInterval), self.rowOptions[type])) self.buffer.append( Row( self.width, random.randint( max(1, self.rowInterval - int(self.score / 100)), self.rowInterval), self.rowOptions[type])) if self.count <= max(self.rowInterval, (self.updateInterval / max( 1, (self.score / 100)))) and self.forceUpdate == False: self.count = self.count + 1 return self.board.append(self.buffer.popleft()) self.player.y += 1 self.count = 0 self.forceUpdate = False
def get_row_from_insert_command(self): if len(self.sql_string_array) != 4: print( "PREPARE_SYNTAX_ERROR: the insert command takes three arguments - insert 1 name [email protected]" ) return False ## validate input ID try: user_id = int(self.sql_string_array[1]) if (user_id <= 0): print("row ID must be positive") return False except ValueError: print("Second argument must be an integer") return False ## validate input name name = self.sql_string_array[2] if (len(name) > constants.NAME_FIELD_SIZE): print("name too long: " + name) return False ## validate input email email = self.sql_string_array[3] if (len(email) > constants.EMAIL_FIELD_SIZE): print("email too long: " + email) return False row = Row(user_id, name, email) row.serialize() return row
def commit_transaction(self, transaction, is_replay=False): if not is_replay: transaction.save(self.data_path) h = transaction.hashed_data() if transaction.path() in self.transactions: return if not is_replay: self.commit_log("begin_transaction", transaction.revision, h) key_cache = {} for i in transaction.statements: rev_key = "%s_%s" % (i.target_key, i.target_hash) if rev_key in key_cache: prev = key_cache[rev_key] else: prev = self.get_revision(i.target_key, i.target_hash) if prev == None: if rev_key in key_cache: prev = key_cache[rev_key] else: prev = Row(i.target_key) new = prev.apply_statement(i) new.result_of = transaction.path() new.save_to(self.data_path) key_cache[rev_key] = new if not is_replay: self.commit_log( [i.target_key, prev.hashed_data(), new.hashed_data()] ) if not is_replay: self.commit_log("end_transaction", transaction.revision, h) for i in key_cache: obj = key_cache[i] if obj.data: self.save_doc(obj) else: hk = self.gen_key(i.split('_')[0]) rev = i.split('_')[1] drops = [] for i in self.objects[hk]: if i.hashed_data() == rev: drops.append(i) for i in drops: self.objects[hk].remove(i) if len(self.objects[hk]) == 0: self.objects.pop( hk ) self.transactions.append(transaction.path()) return key_cache
def test_put(self): self.init() x = self.connect() t = x.transaction() r = Row('test') t.add( r.statement('update', {'one':1}) ) x.commit_transaction(t) rows = x.get_rows('test') self.assertEqual([i.data for i in rows], [{'one':1}])
def __init__(self, *args, **kwargs): if 'id' in kwargs.keys(): unique_id = kwargs['id'] else: unique_id = self.id try: Row.__init__(self, unique_id, *args, **kwargs) except KeyError as k: print "KeyError: Column", k, "does not exist." finally: return
def get_revision(self, key, revision): hk = self.gen_key(key) if hk in self.objects: for i in self.objects[hk]: if i.hashed_data() == revision: return i if Row.exists(self.data_path, key, revision): row = Row.load_from(self.data_path, key, revision) return row return None else: return None
def judge(t,the,rules): now=t for n,(s,col) in enumerate(rules): less = now.clone() for x in selected(now.rows,*col): less.add(x) if (len(less.rows) == len(now.rows)): break if Row(t,now.mid()) < Row(t,less.mid()): break if len(less.rows) < 10: break shows(less.y() + [ f"round{n+1}", len(less.rows),col]) now=less
def __init__(self, playerNumber=1): """ Initialise placement - object with a top, middle and bottom row :return: None """ assert isinstance(playerNumber, int) assert 1 <= playerNumber <= 4 self.playerNumber = playerNumber self.bottomRow = Row(size=5, rowName="Bottom", playerNumber=playerNumber) self.middleRow = Row(size=5, rowName="Middle", playerNumber=playerNumber) self.topRow = Row(size=3, rowName="Top", playerNumber=playerNumber)
def createRowFromXml(rowNode, sourceApp=None): """ Parses a row xml node @param rowNode: Lxml representing a form or dashboard element @return: """ logger.debug("parsing dashboard row node") if rowNode.get('grouping'): rowGroupings = map( int, rowNode.get('grouping').replace(' ', '').strip(',').split(',')) logger.debug("Found row grouping=%s" % rowGroupings) else: rowGroupings = None row = Row(rowGroupings) if len(rowNode) is 0: logger.warn('Dashboard row is empty (line %d)', rowNode.sourceline) else: hasPanels = False hasVisualizations = False for panelElementNode in rowNode: if panelElementNode.tag == "panel": if hasVisualizations: raise Exception( _('Row, on line=%s, should not combine visualizations and panels. Panel, on line=%s' ) % (rowNode.sourceline, panelElementNode.sourceline)) hasPanels = True row.panels.append( createPanelFromXML(panelElementNode, sourceApp)) elif panelElementNode.tag == et.Comment: continue else: if hasPanels: raise Exception( _('Row, on line=%s, should not combine visualizations and panels. Visualization, on line=%s' ) % (rowNode.sourceline, panelElementNode.sourceline)) hasVisualizations = True try: panelElement = createPanelElementFromXml(panelElementNode) if panelElement: row.appendPanelElement(panelElement) except NotImplementedError: raise Exception( _('Row, on line=%s, conains unknown node=%s on line=%s.' ) % (rowNode.sourceline, panelElementNode.tag, panelElementNode.sourceline)) return row
def parseCSV(self): with open(self.data['retenciones'], 'r') as csvfile: first = True spamreader = csv.reader(csvfile, delimiter=',', quotechar='"') for row in spamreader: if first: first = False continue r = Row() r.setData(row) self.rows.append(r)
def __init__(self, type): if type == "skills": self.goals.append(Goal(["blue", "blue"])) self.goals.append(Goal(["blue"])) self.goals.append(Goal(["blue", "blue"])) self.goals.append(Goal(["blue"])) self.goals.append(Goal(["blue", "blue", "blue"])) self.goals.append(Goal(["blue"])) self.goals.append(Goal(["blue", "blue"])) self.goals.append(Goal(["blue"])) self.goals.append(Goal(["blue", "blue"])) self.rows.append(Row([self.goals[0], self.goals[1], self.goals[2]])) self.rows.append(Row([self.goals[3], self.goals[4], self.goals[5]])) self.rows.append(Row([self.goals[6], self.goals[7], self.goals[8]])) self.rows.append(Row([self.goals[0], self.goals[3], self.goals[6]])) self.rows.append(Row([self.goals[1], self.goals[4], self.goals[7]])) self.rows.append(Row([self.goals[2], self.goals[5], self.goals[8]])) self.rows.append(Row([self.goals[0], self.goals[4], self.goals[8]])) self.rows.append(Row([self.goals[2], self.goals[4], self.goals[6]]))
def addText(self, stringList, col=(255,255,255)): if isinstance(stringList, str): temp = stringList stringList = [] stringList.append(temp) for string in stringList: thisRow = Row(string, self.theFont, self.cursorY, self.imgFolder, self.mode) rowImage = thisRow.getImage() self.allElements.append(thisRow) self.checkResize(self.cursorY + rowImage.get_height()) self.image.blit(rowImage, (0, self.cursorY)) self.cursorY += rowImage.get_height() + self.CURSOR_BORDER_INCREMENT
def execute(self, key, action, args): rows = self.get_rows(key) if len(rows) == 0: row = Row(key) t = self.transaction() t.add( row.statement(action, args) ) self.commit_transaction(t) elif len(rows) == 1: row = rows[0] t = self.transaction() t.add( row.statement(action, args) ) self.commit_transaction(t) else: raise Exception("too many docs!!!")
def addGroceryList(self, groceryList, col=(255,255,255)): if isinstance(groceryList, Ingredient): temp = groceryList groceryList = [] groceryList.append(temp) for ingredient in groceryList: thisRow = Row(ingredient.getReadableName(), self.theFont, self.cursorY, self.imgFolder, self.mode, ingredient) rowImage = thisRow.getImage() self.allElements.append(thisRow) self.checkResize(self.cursorY + rowImage.get_height()) self.image.blit(rowImage, (0, self.cursorY)) self.cursorY += rowImage.get_height() + self.CURSOR_BORDER_INCREMENT
def __add__(i, cells): "add a row, update the column headers" for col in i.cols: col + cells[col.pos] row = Row(cells) i.all += [row] return row
def prepare_insert(user_input): # type: (Text) -> Tuple[Statement, PrepareStatementResult] try: _, str_id, username, email = user_input.split(" ") except ValueError: return Statement( StatementType.UNKNOWN), PrepareStatementResult.SYNTAX_ERROR if not all([str_id, username, email]): return Statement( StatementType.UNKNOWN), PrepareStatementResult.SYNTAX_ERROR if len(username) > Row.MAX_USERNAME_LENGTH or len( email) > Row.MAX_EMAIL_LENGTH: return Statement( StatementType.UNKNOWN), PrepareStatementResult.FIELD_TOO_LONG try: int_id = int(str_id) except ValueError: return Statement( StatementType.UNKNOWN), PrepareStatementResult.INVALID_ID else: row = Row(int_id, username, email) insert_statement = Statement(StatementType.INSERT, row) return insert_statement, PrepareStatementResult.SUCCESS
def read_csv(path): rows = [] with open(path, newline='', encoding='utf-8') as csvfile: reader = csv.DictReader(csvfile, delimiter=';') for row in reader: rows.append(Row(row[PLN], row[TYPE], row[PERSON])) return rows
def main(sidelen=4): global alllen global allones global side global comb global gsl global r global combcomb alllen = sidelen**2 allones = int(alllen / 2) side = sidelen if log and combcomb != sidelen: print('creating log') comb = [{} for i in range(sidelen + 1)] combcomb = sidelen print('done') if gsl != sidelen: r = [] print('generating rows:') for i in tqdm(range(2**sidelen)): num = f'{bin(i)[2:]:>{sidelen}}'.replace(' ', '0') r.append(Row(num)) print('combinating rows:') for item in tqdm(r): for i in range(2**sidelen): item.combine(r[i]) gsl = sidelen #for i in r: # print(i) # print(i.poss()) print(f'solving {sidelen}*{sidelen}:') for a in range(2**sidelen): mainsolve(r[a], r[a].ones, 0)
def build_rows(nb_rows, unavailables_slots, nb_slots_per_row): unavailables = defaultdict(list) for (line, slot) in unavailables_slots: unavailables[line].append(slot) rows = [Row(i, nb_slots_per_row, unavailables[i]) for i in range(nb_rows)] rows.sort(reverse=True, key=lambda r: r.getmax()) return rows
def row_object_from_csv(csv_row): if 'work_add_lat' in csv_row: work_add_lat = coord_from_csv(csv_row['work_add_lat']) work_add_lon = coord_from_csv(csv_row['work_add_lon']) home_add_lat = coord_from_csv(csv_row['home_add_lat']) home_add_lon = coord_from_csv(csv_row['home_add_lon']) else: work_add_lat = None work_add_lon = None home_add_lat = None home_add_lon = None return Row(terminal_id=csv_row['terminal_id'], customer_id=csv_row['customer_id'], amount=amount_from_csv(csv_row['amount']), city=csv_row['city'], country=country_from_csv(csv_row['country']), currency=country_from_csv(csv_row['currency']), mcc=mcc_from_csv(csv_row['mcc']), transaction_date=date_from_csv(csv_row['transaction_date']), atm_address=None, atm_address_lat=coord_from_csv(csv_row['atm_address_lat']), atm_address_lon=coord_from_csv(csv_row['atm_address_lon']), pos_address=None, pos_address_lat=coord_from_csv(csv_row['pos_address_lat']), pos_address_lon=coord_from_csv(csv_row['pos_address_lon']), work_add_lat=work_add_lat, work_add_lon=work_add_lon, home_add_lat=home_add_lat, home_add_lon=home_add_lon)
def __init__(self, cache_size, block_size, associativity, replacement): self._size = cache_size self._block_size = block_size self._associativity = associativity self._replacement = replacement self._indices = int((self._size * pow(2, 10)) / (self._block_size * self._associativity)) self._blocks = int(self._indices * self._associativity) temp_rows = [] for i in range(self._indices): rows = [] for a in range(associativity): rows.append(Row()) temp_rows.append(rows) self._rows = temp_rows self._index_size = int( math.log((self._size * pow(2, 10)), 2) - (math.log(self._block_size, 2) + math.log(self._associativity, 2))) self._offset = int(math.log(self._block_size, 2)) self._tag_size = 32 - self._index_size - self._offset self._num_blocks = int(self._indices * self._associativity) self._overhead_size = int(self._associativity * (1 + self._tag_size) * (self._indices / 8)) self._total_size = int((self._size * pow(2, 10)) + self._overhead_size)
def load_file(self, stream): """Given an open file handle, read Row lines into this RowSet """ if isinstance(stream, str): filename = stream stream = open(filename, 'r') else: filename = '(stream)' if len(self) > 0: raise ValueError( '{}: can only load files into an empty RowSet'.format(filename) ) opening_balance = 0 line_number = 0 for row in stream.readlines(): row = row.rstrip('\n') line_number += 1 if not row: # Skip blank lines continue if re.match(r'^#', row): # TODO # - add comments and pragmas into the rows array for 100% # round-triping match = re.match(r'^#balance ([-0-9.]+)', row) if match: given_balance = decimal.Decimal(match.group(1)) current_balance = opening_balance+self.balance if len(self.rows) == 0: # if the balance pragma is before any transaction # data then it sets the opening balance for the set opening_balance = given_balance continue elif given_balance != current_balance: raise ValueError( '{}:{} Failed to balance - expected {} but calcul' 'ated {}'. format( filename, line_number, given_balance, current_balance ) ) # - in future there might be additional meta/pragmas # skip adding comment or meta lines continue try: # TODO - the row class should handle fields inside the line self.append(Row(*re.split(r'\s+', row, maxsplit=2))) except: # noqa print("{}:{} Syntax error".format(filename, line_number)) raise
def patternrows(patternlist): """ takes a list of strings(per row) and returns a list of rows """ for r in range(len(patternlist)): string = patternlist[r] patternlist[r] = Row(string) return patternlist
def read(i, src): "Fo all rows in src, fill in the table." for lst in cells(cols(rows(src))): if i.cols: lst = [col + x for col, x in zip(i.cols.all, lst)] i.rows += [Row(lst)] else: i.cols = Cols(lst) return i
def _get_fk_data(self, table_name, fk, fk_value): reltable = Structure.get_fk_referenced_table(table_name, fk) reltable_pk = Structure.get_primary_key(reltable) if not self._cache.relation_exists(table_name, reltable): sql = SQLBuilder(reltable) sql.add_where_literal(Column(reltable, reltable_pk).in_(self._cache.get_all_keys(table_name, fk))) data = Query().execute_and_fetch(**sql.build_select()) self._cache.save_relation(table_name, reltable, data) return Row(self._cache.get_relation_row(reltable, reltable_pk, fk_value), reltable, self)
def __init__(self): filename = 'alunos.csv' mode = 'r' with open(filename, mode) as csv_file: csv_reader = csv.DictReader(csv_file) self.csv_list = [] for row in csv_reader: self.csv_list.append(Row(row))
def twenty_fifteen(f): soup = BeautifulSoup(open(os.path.join(folder, f)), "html.parser") table = soup.findAll("table")[1] rows = table.findChildren(['tr']) for data in rows: # skip table headers if len(data.findChildren(["th"])) < 1: csv_rows.append(Row("2015", data, 0, 1))
def _make_derivative_rows(self) -> None: # Add derivatives to the table ("bottom part" of table, ie. successors) for state in self._rows: for a in self._alphabet: if not self[state.label + a]: observations = tuple( self._teacher.accepts(state.label + a + c) for c in self._cols) new_row = Row(state.label + a, self._cols, observations) self._derivative_rows.append(new_row)
def execute_select(table): # type: (Table) -> ExecuteStatementResult cursor = Cursor.table_start(table) while not cursor.is_at_end_of_table: page, offset = cursor.location() row = Row.deserialize_from(page, offset) print(row) cursor.advance() return ExecuteStatementResult.SUCCESS
def startNewGame(self): self.score = 0 self.count = 0 self.player.x = int(self.width / 2) self.player.y = int(self.height - 1) self.board = deque([], self.boardHeight) self.buffer = deque([]) self.board.append( Row( self.width, random.randint( max(1, self.rowInterval - int(self.score / 100)), self.rowInterval))) self.board.append( Row( self.width, random.randint( max(1, self.rowInterval - int(self.score / 100)), self.rowInterval))) self.board.append( Row( self.width, random.randint( max(1, self.rowInterval - int(self.score / 100)), self.rowInterval))) self.board.append( Row( self.width, random.randint( max(1, self.rowInterval - int(self.score / 100)), self.rowInterval))) for i in range(4, self.boardHeight): if i % 2 == 0: type = random.choice(self.rowOptions) self.board.append( Row( self.width, random.randint( max(1, self.rowInterval - int(self.score / 100)), self.rowInterval), type))
def createRowFromXml(rowNode, sourceApp=None): """ Parses a row xml node @param rowNode: Lxml representing a form or dashboard element @return: """ logger.debug("parsing dashboard row node") if rowNode.get('grouping'): rowGroupings = map( int, rowNode.get('grouping').replace(' ', '').strip(',').split(',')) logger.debug("Found row grouping=%s" % rowGroupings) else: rowGroupings = None row = Row(rowGroupings) if len(rowNode) is 0: logger.warn('Dashboard row is empty (line %d)', rowNode.sourceline) else: hasPanels = False hasVisualizations = False for panelElementNode in rowNode: if panelElementNode.tag == "panel": if hasVisualizations: raise Exception(_('Row, on line=%s, should not combine visualizations and panels. Panel, on line=%s') % (rowNode.sourceline, panelElementNode.sourceline)) hasPanels = True row.panels.append(createPanelFromXML(panelElementNode, sourceApp)) elif panelElementNode.tag == et.Comment: continue else: if hasPanels: raise Exception(_('Row, on line=%s, should not combine visualizations and panels. Visualization, on line=%s') % (rowNode.sourceline, panelElementNode.sourceline)) hasVisualizations = True try: panelElement = createPanelElementFromXml(panelElementNode) if panelElement: row.appendPanelElement(panelElement) except NotImplementedError: raise Exception(_('Row, on line=%s, conains unknown node=%s on line=%s.') % (rowNode.sourceline, panelElementNode.tag, panelElementNode.sourceline)) return row
def load_file(self, stream, skip_balance_check=False): """Given an open file handle, read Row lines into this RowSet """ if isinstance(stream, str): filename = stream stream = open(filename, 'r') else: filename = '(stream)' line_number = 0 need_balance = True # TODO # - if we are loading just one file from a whole dir, its opening # balance will need to be added to any calculated balance to avoid # errors if skip_balance_check: need_balance = False last_error = None for row in stream.readlines(): row = row.rstrip('\n') line_number += 1 try: obj = Row.fromTxt(row) except Exception as e: print("{}:{} Syntax error".format(filename, line_number), file=sys.stderr) last_error = e if isinstance(obj, RowPragmaBalance): # TODO - move more of the pragma logic in to the pragma class if obj.balance != self.balance: raise ValueError( '{}:{} Failed to balance - expected {} but calcul' 'ated {}'.format(filename, line_number, obj.balance, self.balance)) need_balance = False if isinstance(obj, RowData) and need_balance: raise ValueError( '{}: trying to load a file that does not start with a' ' balance pragma'.format(filename)) self.append(obj) if last_error is not None: print("Error: at least one syntax error. Trace is from last", file=sys.stderr) raise last_error
def read(i, src): "Fo all rows in src, fill in the table." for n, lst in enumerate(cells(cols(rows(src)))): if n == 0: i.header = lst if i.cols: lst = [col + x for col, x in zip(i.cols.all, lst)] i.rows += [Row(lst)] else: i.cols = Cols(lst) return i
def get(self): rows = Row.all() logging.info('Found %d rows',rows.count()) template_vars = { 'rows': rows, 'rowcount': rows.count(), 'sep': cgi.escape(self.request.get("sep")) or ',' } path = os.path.join(os.path.dirname(__file__),"index.html") self.response.out.write(template.render(path,template_vars))
def dfs(root: Node, continues: Tuple[bool] = None): if continues is None: continues = tuple() yield Row(root, continues) if not root.children: return for child in root.children: is_last = root.children[-1] == child for grandchild in dfs(child, continues + (not is_last, )): yield grandchild
def ninety_six(f): """ Straight forward parsing of 1995-1996.html file """ soup = BeautifulSoup(open(os.path.join(folder, f)), "html.parser") table = soup.findAll("table")[1] rows = table.findChildren(['tr']) for data in rows: # skip table headers if len(data.findChildren(["th"])) < 1: csv_rows.append(Row("1996", data, 0, 7))
def process_counterexample(self, label: str, conjecture: DFA) -> bool: """Add counterexample and its prefixes to rows, and add derivative rows""" if conjecture.accepts(label) == self._teacher.accepts(label): print("False counter example, already both reject or both accept.") return False new_row = Row( label, self._cols, tuple(self._teacher.accepts(label + c) for c in self._cols)) self._rows.append(new_row) for i in range(len(label)): prefix = label[:i] if prefix not in list(map(lambda x: x.label, self._rows)): self._rows.append( Row( prefix, self._cols, tuple( self._teacher.accepts(prefix + col) for col in self._cols))) self._make_derivative_rows() return True
def __init__(self, teacher: Teacher, alphabet: Tuple[str, ...]): """ :param teacher: Implements `accepts` and `counterexample` methods :param alphabet: The alphabet of the target to be learned """ self._alphabet = alphabet self._teacher = teacher # we start with just the row & column for the empty word self._cols = ('', ) self._rows = [Row('', self._cols, (teacher.accepts(''), ))] self._derivative_rows = [] self._make_derivative_rows()
def get(self): rows = Row.all() logging.info('CSV requested. Found %d rows',rows.count()) if rows.count() > 0: self.response.headers['Content-Type'] = "application/csv" writer = encoding.UnicodeWriter(self.response.out,delimiter=cgi.escape(self.request.get("sep").__str__()),quotechar='"') for row in rows: writer.writerow(row.cols) else: print "Content-Type: text/html" print print "<h1>No data to display ...</h1>"
def test_many_keys_single_transaction(self): bunch_o_keys = [(i, gen()) for i in range(20)] self.init() x = self.connect() value = {} t = x.transaction() for index, i in bunch_o_keys: r = Row('test') t.add( r.statement('update', {i:index}) ) value.update({i:index}) x.commit_transaction(t) data = x.get_rows('test') data = data[0].data self.assertEqual(data, value)
def test_get_valid_row(self): dictrow = dict() dictrow['nome'] = 'Lucas Oliveira Barros' dictrow['matricula'] = '100591' dictrow['telefone'] = '99999-9980' dictrow['email'] = "*****@*****.**" dictrow['uffmail'] = "" dictrow['status'] = "Ativo" row = Row(dictrow) self.assertEqual(row, self.database.getrow(self.validid))
def post(self): text = self.request.get('lines') sep = self.request.get('sep') or ',' logging.info("line %s - sep %s",text,sep) rows = rows_from_string(text,sep) db.put(rows) all_rows = Row.all() template_vars = { 'rows': all_rows, 'rowcount': all_rows.count(), 'sep': cgi.escape(sep) } path = os.path.join(os.path.dirname(__file__),"index.html") self.response.out.write(template.render(path,template_vars))
class Placement(object): def __init__(self, playerNumber=1): """ Initialise placement - object with a top, middle and bottom row :return: None """ assert isinstance(playerNumber, int) assert 1 <= playerNumber <= 4 self.playerNumber = playerNumber self.bottomRow = Row(size=5, rowName="Bottom", playerNumber=playerNumber) self.middleRow = Row(size=5, rowName="Middle", playerNumber=playerNumber) self.topRow = Row(size=3, rowName="Top", playerNumber=playerNumber) def setRow(self, row="Bottom", cards=[]): """ Sets a given row with cards provided :param cards: List of Card objects :return: None """ assert isinstance(row, basestring) assert row.lower() in ["bottom", "middle", "top"] assert isinstance(cards, list) if row.lower() in ["bottom", "middle"]: assert len(cards) <= 5 elif row.lower() == "top": assert len(cards) <= 3 for i in range(1, len(cards) + 1): assert isinstance(cards[i - 1], Card) if row.lower() == "bottom": self.bottomRow.setPlacement(c=cards[i - 1], position=i) elif row.lower() == "middle": self.middleRow.setPlacement(c=cards[i - 1], position=i) else: self.topRow.setPlacement(c=cards[i - 1], position=i)
def create(self, key, value): row = Row(key) t = self.transaction() t.add( row.statement('set', value) ) self.commit_transaction(t)
import os import sys # Extension should have been built in parent directory. sys.path.append(os.path.dirname('..')) from row import Row methods = [ ('Slinky', Row('14523ET90786')), ('Top', Row('2134567890ET')), ('Up', Row('2134TE098765')), ('Strange', Row.reverse_rounds(12)), ('Down', Row('8765432190TE')), ('Charm', Row('6543217890TE')), ('Meson', Row('1287094365ET')), ('Gluon', Row('13527496E8T0')), ('Baryon', Row('E9T705836142')), ] LEAD_LIMIT = 4 def condensed_output(lead_heads, method_names): print(', '.join(method_names)) def full_output(lead_heads, method_names): print('1234567890ET ' + method_names[0])