def reset(cls): """Reset to default state.""" Box.reset() Note.reset() Figure.reset() Table.reset() Video.reset()
class TestPot(unittest.TestCase): """Do we have a fully functional pot object?""" def setUp(self): self.p0 = Player('p0', 100) self.p1 = Player('p1', 100) self.p2 = Player('p2', 100) self.p3 = Player('p3', 100) self.p4 = Player('p4', 100) self.p5 = Player('p5', 100) self.s0 = Seat('s0') self.s1 = Seat('s1') self.s2 = Seat('s2') self.s3 = Seat('s3') self.s4 = Seat('s4') self.s5 = Seat('s5') players = [self.p0, self.p1, self.p2, self.p3, self.p4, self.p5] seats = [self.s0, self.s1, self.s2, self.s3, self.s4, self.s5] self.table = Table(seats, 5, 10, 0) self.dealer = Dealer(self.table) self.table.dealer = self.dealer player = 0 for seat in seats: seat.player = players[player] seat.player.seat = seat seat.active = True seat.player.table = self.table player += 1 self.table.init_hand() def test_who_is_first_pre_flop(self): """Do we make the proper player act first pre-flop??""" self.dealer.deal_hole() self.assertTrue(self.table.seats[self.table.under_the_gun].player.action) def test_who_is_first_post_flop(self): """Do we make the proper player act first post-flop""" self.dealer.deal_hole() self.table.seats[self.table.under_the_gun].player.action = False self.dealer.deal() self.assertTrue(self.table.seats[self.table.first].player.action) def test_bet(self): """Can each player bet 50?""" self.dealer.deal_hole() i = 0 while i < 6: i += 1 for seat in self.table.pots[-1].seats: print(seat.player.name, seat.player.equity, seat.player.action) if seat.player.action: seat.player.bet(50) self.table.pots[-1].betting_round() break print(seat.player.name, seat.player.equity, seat.player.action) print(self.table.pots[-1].pot)
def _on_register(self, username): self.nick = username self.send({'registered': self.nick}) #score = self._get_score(self.nick) #self.send({'update_score': score}) while self._waiting: opponent = self._waiting.pop() if opponent.is_closed: continue self._opponents[self.session].append(opponent) self._opponents[opponent.session].append(self) self.send({'status': "playing against " + opponent.nick, 'ready': True}) opponent.send({'status': "playing against " + self.nick, 'ready': True}) table_id = Table.new_table_id() players = [self, opponent] for player in players: player.table_id = table_id player.changes = 0 table = Table(players) self._tables[table_id] = table # could be more table.deal_5_cards_each() for player in table.players: player.send({'hand': player.cards}) else: self._waiting.append(self) self.send({'status': 'Waiting', 'color': 'orange'})
def generate_speedup_table(self): table = Table() # prepare header header = ["procedure"] for size in self.data.sizes: header.append('%d B' % size) table.set_header(header) reference_time = {} for size in self.data.sizes: time = self.data.get(self.data.procedures[0], size) reference_time[size] = time # get data for proc in self.data.procedures: measurments = self.data.data_for_procedure(proc) row = [proc] for item in measurments: speedup = reference_time[item.size] / item.time row.append('%0.2f' % speedup) table.add_row(row) return table
def format_table(data): table = Table() keys = data[1].keys() # prepare header header1 = ["number of spaces"] header2 = [""] for key in keys: header1.append(("%s [cycles/byte]" % key, 3)) header2.extend(["avg (min)", "avg (max)", "best"]) table.add_header(header1) table.add_header(header2) # add data for cardinality in xrange(1, 64+1): row = ['%d' % cardinality] measurements = data[cardinality] for meas in measurements.values(): row.append('%0.3f' % min(meas.values)) row.append('%0.3f' % max(meas.values)) row.append('%0.3f' % meas.best) table.add_row(row) return table
def load_table(filename): t = Table() seen_header = False for line in file(filename): if not seen_header: seen_header = True continue line = line.rstrip("\n") (id, status, price, genres, policy, countries) = line.split("\t") def split_ints(commasep): if commasep == '': return set() return set([int(s) for s in commasep.split(",")]) t.append_row( id, { 'status': status, 'price': int(float(price)*100), 'genre': split_ints(genres), 'policy': policy, 'country': split_ints(countries) }) return t
def generate_time_table(self): table = Table() # prepare header header = ["procedure"] for size in self.data.sizes: header.append('%d B' % size) table.set_header(header) # get data for procedure in self.data.procedures: data = self.data.data_for_procedure(procedure) row = [procedure] for item in data: fmt = TIME_PATTERN % item.time if item.time == self.data.get_shortest_time(item.size): row.append('**%s**' % fmt) else: row.append(fmt) table.add_row(row) return table
def display_addr_refs(refs, ref_statuses): table = Table( num_cols=len(REF_COL_NAMES), width=TABLE_WIDTH, alignment='right') table.header[:] = REF_COL_NAMES for ref, ref_status in zip(refs, ref_statuses): if ref.tag is not None: ref_tag = ref.tag else: ref_tag = 'n/a' if ref.index is not None: ref_index = ref.index else: ref_index = 'n/a' if ref.offset is not None: ref_offset = ref.offset else: ref_offset = 'n/a' # Display data for each address as a row in the table table.rows.append(( ref.word_addr, prettify_bin_addr(ref.bin_addr, MIN_BITS_PER_GROUP), prettify_bin_addr(ref_tag, MIN_BITS_PER_GROUP), prettify_bin_addr(ref_index, MIN_BITS_PER_GROUP), prettify_bin_addr(ref_offset, MIN_BITS_PER_GROUP), ref_status)) print(table)
def result(self): """ Perform the query, and return the result as a Table object """ BaseQuery.logger.log( "With arguments: " + str(self.arguments) ) BaseQuery.logger.log( "Running query: \n" + str(self.complete_query) ) cursor = self.db_connection.cursor() start_time = time.time() cursor.execute( self.complete_query ) self.elapsed_time = time.time() - start_time BaseQuery.logger.log( str(self.elapsed_time) + " seconds" ) results_table = Table() for col in cursor.description: results_table.append_column( col[0] ) row = cursor.fetchone() while row: results_table.append_row( [self.output_clean_function(i) for i in row] ) row = cursor.fetchone() self.rows_fetched = len(results_table) BaseQuery.logger.log( str(self.rows_fetched) + " rows fetched" ) return results_table
def createTable(**kwargs): """ CREATE table. kwargs['cols'] is a list of consecutive column name - type pairs i.e. [col1_name, col1_type, col2_name, col2_type, ...] which is why it gets split when calling Table.create() """ Table.create(kwargs['table'], kwargs['cols'][::2], kwargs['cols'][1::2])
def test_get_length(self): try: data = TG.build_table_from_txt(D.analog_1) table = Table(data) length = table.get_length() self.assertEqual(len(data), length) except: self.assert_(False)
def login(self, *args): global w name = w.loginEdit.text() password = w.passwordEdit.text() if User.login(name, password): w = Table() w.show()
def test_get_table(self): try: data = TG.build_table_from_txt(D.analog_1) table = Table(data) check = table.get_table() self.assertIs(data, check) except: self.assert_(False)
def __call__(self, category, player_id, dct): table_name = 'gc_cur_team_stats_{0}'.format(category) table = Table(table_name) table.insert( self.cursor, getattr(values, table_name)( self.gc_cur_team_id, player_id, dct))
def apply(self, tables): columns = self.get_columns(tables) table = tables[0] measure_column = table[self['measure']] new_column_headers = [] header_column = columns[0] start_row = 0 end_row = table.rows() for v in header_column.data: if(not v in new_column_headers): new_column_headers.append(v) key_columns = filter(lambda x: not x.name in [measure_column.name, header_column.name], table) reduction = {} reduction_index = 0 new_table = Table() for col in key_columns: new_table.add_column(col.name, {}) #this name lookup is needed since table implementation changes names under certain circumstances name_lookup = {} for header in new_column_headers: col = new_table.add_column(header, {}) name_lookup[header] = col.name for row in range(start_row, end_row): key = '*'.join([col[row] for col in key_columns]) if(not reduction.has_key(key)): reduction[key] = reduction_index for col in key_columns: new_table[col.name][reduction_index] = col[row] reduction_index += 1 index = reduction[key] header = header_column[row] measure = measure_column[row] new_table[name_lookup[header]][index] = measure table.clear() for col in new_table: table.insert_column(col, {})
def drop(self, force=False): Table.drop(self, force) # Try to also drop the corresponding view if one exists. sql = self.DROP_VIEW.format(table=self.table_name) try: self.connection.execute(sql) except IntegrityError: self.log_error("Unable to drop view")
def make_table(items, args, columns): table = Table() if args.c is not None: columns = args.c elif columns is None: columns = _get_names(items) if args.H: columns = [name for name in columns if name not in args.H] table.add_dictionaries(items, columns) return table
def transfer(self): doc = ElementTree.parse(self.filepath) root = doc.getroot() database = root.getchildren() for table in database: datatable = Table(table.attrib['tablename']) columns = table.getchildren() for column in columns: datatable.add(column.attrib['columnname'], column.attrib['columntype'],column.attrib['columnwidth']) self.datatables.append(datatable)
def main(): table = Table() reg = FunctionRegistry() table.set_header(["procedure", "description"]) for proc, dsc in reg.functions.iteritems(): table.add_row([proc, dsc]) print table
class TestColumnContainer(unittest.TestCase): def setUp(self): self.table = createTable(TABLE_NAME) column1 = cl.Column(COLUMN1) column1.addCells(COLUMN1_CELLS) self.table.addColumn(column1) column2 = cl.Column(COLUMN2) column2.addCells(COLUMN2_CELLS) error = self.table.addColumn(column2) if error is not None: import pdb; pdb.set_trace() self.column5 = cl.Column(COLUMN5) self.column5.addCells(COLUMN5_CELLS) self.table.addColumn(self.column5) self.columns = self.table.getColumns() self.subtable = Table(SUBTABLE) self.table.addChild(self.subtable) self.subtable_column = self.subtable.getChildAtPosition(0) self.subtable_column_name = 'row' def testColumnFromIndex(self): if IGNORE_TEST: return column = self.table.columnFromIndex(0) self.assertEqual(column.getName(), 'row') index = self.table.numColumns() with self.assertRaises(ValueError): self.table.columnFromIndex(index) def testColumnFromName(self): if IGNORE_TEST: return global_name = self.table.createGlobalName(self.subtable_column) column = self.table.columnFromName(global_name, is_relative=False) self.assertTrue(column.isEquivalent(self.subtable_column)) column = self.table.columnFromName(COLUMN5, is_relative=True) self.assertTrue(column.isEquivalent(self.column5)) self.assertIsNone(self.table.columnFromName(SUBTABLE, is_relative=True)) def testGetColumnNames(self): if IGNORE_TEST: return names = self.subtable.getColumnNames() self.assertEqual(names, [self.subtable_column.getName()]) names = self.table.getColumnNames() self.assertTrue(not SUBTABLE in names) def testGetColumns(self): columns = self.subtable.getColumns() self.assertEqual(columns, [self.subtable_column]) table_columns = self.table.getColumns() self.assertTrue(not self.subtable in table_columns) columns = self.table.getColumns(is_recursive=False) self.assertEqual(len(columns) + 1, len(table_columns))
def _preprocess(self): # Set time offsets starttime = min([ trace.get_init_time() for trace in self.traces ]) for trace in self.traces: trace.time_offset = trace.get_init_time() - starttime trace_times = [ trace.get_next_event_time() for trace in self.traces ] if self.export_data: place_counters = [place_counter_name(p) for p in self.project.nets[0].places() if p.trace_tokens] ri = ExportRunInstance( self, [ t for t in self.project.nets[0].transitions() if t.trace_fire ], [ (p, i) for p in self.project.nets[0].places() for i, tracing in enumerate(p.trace_tokens_functions) if tracing.return_numpy_type != 'O' ], ExportRunInstance.basic_header + place_counters) else: ri = RunInstance( self.project, self.process_count) index = 0 timeline = Table([("process", "<i4"), ("pointer", "<i4")], 100) full_timeline = Table([("process", "<i4"), ("pointer", "<i4")], 100) while True: # Searching for trace with minimal event time minimal_time_index = utils.index_of_minimal_value(trace_times) if minimal_time_index is None: break trace = self.traces[minimal_time_index] full_timeline.add_row((minimal_time_index, trace.pointer)) # Timeline update if trace.is_next_event_visible(): timeline.add_row(full_timeline[index]) trace.process_event(ri) trace_times[minimal_time_index] = trace.get_next_event_time() index += 1 self.data = Table([], 0) if self.export_data: self.data = ri.get_table() timeline.trim() full_timeline.trim() self.timeline, self.full_timeline = timeline, full_timeline self.missed_receives = ri.missed_receives
def print_results(result_files, out_format): """Builds a table with the parsed results. Used when there is only one result file. """ categories = transpose_result_data(result_files) columns = [result.short_name() for result in result_files] columns.insert(0, "Benchmark") table = Table(columns) geomean = None for key in categories: scores = [run[1] for run in categories[key]] entries = ["%.2f +- %.2f" % score for score in scores] entries.insert(0, key) if key == 'Geomean': geomean = entries else: table.add_row(entries) if geomean is not None: table.add_row(geomean) if out_format == 'terminal': table.dump_to_terminal() elif out_format == 'remarkup': table.dump_to_remarkup() else: raise RuntimeError("Unknown output format: %s" % out_format)
def format_table(data): vector_size = list(set(key[0] for key in data.iterkeys())) vector_count = list(set(key[1] for key in data.iterkeys())) procedures = data.values()[0].keys() vector_size.sort() vector_count.sort() # prepare header table = Table() table.add_header(["procedure"] + [("%d vectors" % c, 2) for c in vector_count]) h = [""] t = ["avg cycles", "speedup"] for _ in vector_count: h.extend(t) table.add_header(h) # prepare data for size in vector_size: table.add_row([("*vector size %d*" % size, len(vector_count)*2 + 1)]) for procedure in procedures: row = [] row.append(procedure) for count in vector_count: key = (size, count) measurement = data[key] row.append('%0.3f' % measurement[procedure].avg) row.append('%0.2f' % measurement[procedure].speedup) table.add_row(row) print table
def testIsEquivalentNestedLists(self): if IGNORE_TEST: return try: [column1, column2] = Table.getCapture("column_is_equivalent") self.assertTrue(column1.isEquivalent(column2)) [column1, column2] = Table.getCapture("column_is_equivalent2") self.assertTrue(column1.isEquivalent(column2)) except AttributeError as err: # Can't handle the captured pickle file return
class GcGameTeamInserter(object): def __init__(self, cursor, gc_game_id): self.cursor = cursor self.gc_game_id = gc_game_id self.table = Table('gc_game_team') def __call__(self, abbr, dct): self.table.insert( self.cursor, values.gc_game_team(self.gc_game_id, abbr, dct))
def login(*args): global w name = w.loginEdit.text() password = w.passwordEdit.text() if User.login(name, password): ret = QMessageBox.question(w, 'Приветствие', 'Ура, Вы вошли!', QMessageBox.Ok) if ret == QMessageBox.Ok: w = Table() w.show()
class GcTeamInserter(object): def __init__(self, cursor, gc_id): self.cursor = cursor self.gc_id = gc_id self.table = Table('gc_team') def __call__(self, dct): for ah in ('away', 'home',): self.table.insert( self.cursor, values.gc_team(self.gc_id, ah, dct[ah]))
def main(): options = parse_args() out = subprocess.Popen(options.testtool,stdout=subprocess.PIPE).stdout table = Table() reporter = ReportToTable() reporter.process_xml(out,table) output = None if options.output == '/dev/stdout': output = sys.stdout else: output = open(options.output,'w') table.to_format(options.format,output)
class GcCurTeamStatsTeamInserter(object): def __init__(self, cursor, gc_cur_team_id): self.cursor = cursor self.gc_cur_team_id = gc_cur_team_id self.table = Table('gc_cur_team_stats_team') def __call__(self, dct): self.table.insert( self.cursor, values.gc_cur_team_stats_team( self.gc_cur_team_id, dct))
def setUp(self): self.mines = Table.from_nested_list([ [False, False, False, False], [False, True, False, False], [False, False, False, False], [False, False, False, False], ]) self.flags = Table.from_nested_list([ [Flags.Unknown, Flags.Unknown, Flags.Unknown, Flags.Unknown], [Flags.Unknown, Flags.Unknown, Flags.Unknown, Flags.Unknown], [Flags.Unknown, Flags.Unknown, Flags.Unknown, Flags.Unknown], [Flags.Unknown, Flags.Unknown, Flags.Unknown, Flags.Unknown], ])
from symbol import KEYWORDS, OPERATORS, DELIMITERS, SYM, ident, number, IDi, NUM from node import Node from table import Table, Entry, isConst, KIND from inst import Code p = 0 pid = 0 pnum = 0 root = Node('<程序>') table = Table() #table表 code = [] #CODE数组 startCode = Code('JMP', 0, None) code.append(startCode) code.append(Code) tableList = [] def error(): # 出错 print("Error:", p) exit(-1) def advance(): global p p = p + 1 def block(): tableList.append(table) A(root, table)
def find_table(image): # Convert resized RGB image to grayscale NUM_CHANNELS = 3 if len(image.shape) == NUM_CHANNELS: grayscale = cv.cvtColor(image, cv.COLOR_BGR2GRAY) # ===================================================== # IMAGE FILTERING (using adaptive thresholding) # ===================================================== MAX_THRESHOLD_VALUE = 255 BLOCK_SIZE = 15 THRESHOLD_CONSTANT = 0 # Filter image filtered = cv.adaptiveThreshold(~grayscale, MAX_THRESHOLD_VALUE, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, BLOCK_SIZE, THRESHOLD_CONSTANT) # ===================================================== # LINE ISOLATION # ===================================================== SCALE = 15 # Isolate horizontal and vertical lines using morphological operations horizontal = filtered.copy() vertical = filtered.copy() horizontal_size = int(horizontal.shape[1] / SCALE) horizontal_structure = cv.getStructuringElement(cv.MORPH_RECT, (horizontal_size, 1)) utils.isolate_lines(horizontal, horizontal_structure) vertical_size = int(vertical.shape[0] / SCALE) vertical_structure = cv.getStructuringElement(cv.MORPH_RECT, (1, vertical_size)) utils.isolate_lines(vertical, vertical_structure) # ===================================================== # TABLE EXTRACTION # ===================================================== # Create an image mask with just the horizontal # and vertical lines in the image. Then find # all contours in the mask. mask = horizontal + vertical (contours, _) = cv.findContours(mask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) # Find intersections between the lines # to determine if the intersections are table joints. intersections = cv.bitwise_and(horizontal, vertical) # Get tables from the images tables = [] # list of tables for i in range(len(contours)): # Verify that region of interest is a table (rect, table_joints) = utils.verify_table(contours[i], intersections) if rect == None or table_joints == None: continue # Create a new instance of a table table = Table(rect[0], rect[1], rect[2], rect[3]) # Get an n-dimensional array of the coordinates of the table joints joint_coords = [] for i in range(len(table_joints)): joint_coords.append(table_joints[i][0][0]) joint_coords = np.asarray(joint_coords) # Returns indices of coordinates in sorted order # Sorts based on parameters (aka keys) starting from the last parameter, then second-to-last, etc sorted_indices = np.lexsort((joint_coords[:, 0], joint_coords[:, 1])) joint_coords = joint_coords[sorted_indices] # Store joint coordinates in the table instance table.set_joints(joint_coords) tables.append(table) if len(tables)!=0: return tables else: return []
def create_table(self, seats, sb_amount, bb_amount, buy_in, ante=0): table = Table(self, seats, sb_amount, bb_amount, buy_in, ante) self.tables.append(table)
def __init__(self): self.err_no = 0 self.total_lines = 0 self.ignored_lines = 0 self.illegal_lines = 0 self.table = Table()
'font_size': 10, }) table_content_format2 = workbook.add_format({ 'font_name': 'Arial', 'color': '#633333', 'valign': 'vcenter', # 垂直居中 }) # 重复表的张数 repet_table = [] for table in doc.tables: rows = table.rows length = len(rows) i = 0 t = Table() listRow = [] validateTable = True while i < length: cells = rows[i].cells row_index = i + 1 if i == 0: t.headName = cells[0].text # originalName = t.headName t.tableName = t.headName.replace("Example:", "").lstrip(" \n") if t.headName.find("Example:") != -1: if t.tableName.find("+RESP:") != -1: separator_Num1 = t.tableName.find(':') separator_Num2 = t.tableName.find(',') t.tableName = t.tableName[separator_Num1 + 1:separator_Num2]
def get_relation(self, alias: str): from table import Table, Grid rel = self.tbl.get_relation(alias) if self.db.cnxn.system == 'postgres': base_name = rel.base + '.' + rel.schema else: base_name = rel.base or rel.schema db = Database(self.db.cnxn, base_name) tbl_rel = Table(db, rel.table) grid = Grid(tbl_rel) tbl_rel.limit = 500 # todo: burde ha paginering istedenfor tbl_rel.offset = 0 tbl_rel.fields = tbl_rel.get_fields() tbl_rel.pkey = tbl_rel.get_primary_key() # Find index used slice_obj = slice(0, len(rel.foreign)) rel_indexes = tbl_rel.get_indexes() for index in rel_indexes.values(): if index.columns[slice_obj] == rel.foreign: rel.index = index break # todo: filter # Don't get values for new records that's not saved if hasattr(self, 'pk') and len(set(self.pk)): rec_values = self.get_values() or self.pk # Add condition to fetch only rows that link to record conds = Dict() pkey = {} for idx, col in enumerate(rel.foreign): ref_key = rel.primary[idx].lower() val = None if len(self.pk) == 0 else rec_values[ref_key] if (len(self.pk) and tbl_rel.fields[col].nullable and col != rel.foreign[0] and rel.primary == list(self.pk.keys()) and rel.index.unique is True ): grid.add_cond(expr = f"({rel.table}.{col} = ? or {rel.table}.{col} is null)", value = val) else: grid.add_cond(f"{rel.table}.{col}", "=", val) conds[col] = val pkey[col] = val # grid.add_cond(f"coalesce({rel.table}.{col}, '-')", "IN", [val, '-']) relation = grid.get() relation.conds = conds # Don't get values for new records that's not saved if hasattr(self, 'pk') and len(set(self.pk)): rec_values = self.get_values() values = [None if len(self.pk) == 0 else rec_values[key] for key in rel.primary] for idx, col in enumerate(rel.foreign): relation.fields[col].default = values[idx] relation.fields[col].defines_relation = True tbl_rel.pkey = tbl_rel.get_primary_key() # If foreign key columns contains primary key if set(tbl_rel.pkey) <= set(rel.foreign): rec = Record(self.db, tbl_rel, pkey) relation.records = [rec.get()] relation.relationship = "1:1" else: relation.relationship = "1:M" return relation
(contours, _) = cv.findContours(mask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) # Find intersections between the lines # to determine if the intersections are table joints. intersections = cv.bitwise_and(horizontal, vertical) # Get tables from the images tables = [] # list of tables for i in range(len(contours)): # Verify that region of interest is a table (rect, table_joints) = utils.verify_table(contours[i], intersections) if rect == None or table_joints == None: continue # Create a new instance of a table table = Table(rect[0], rect[1], rect[2], rect[3]) # Get an n-dimensional array of the coordinates of the table joints joint_coords = [] for i in range(len(table_joints)): joint_coords.append(table_joints[i][0][0]) joint_coords = np.asarray(joint_coords) # Returns indices of coordinates in sorted order # Sorts based on parameters (aka keys) starting from the last parameter, then second-to-last, etc sorted_indices = np.lexsort((joint_coords[:, 0], joint_coords[:, 1])) joint_coords = joint_coords[sorted_indices] # Store joint coordinates in the table instance table.set_joints(joint_coords)
from table import Table t = Table() t.initialize(['ID', 'Name', 'Email']) t.addrow(['1', 'Test', '*****@*****.**']) t.addrow(['2', 'Test2', '*****@*****.**']) t.addrow(['3', 'Test3', '*****@*****.**']) t.addrow(['4', 'Test4', '*****@*****.**']) t.render(-1)
def create_table(self): return Table() \ .with_name("POSTS") \ .with_column("id", "INTEGER", "not null") \ .with_column("title", "varchar(10)", "not null")
import pylab as plt from table import Table from wallet import * from player import * from bet import * # create table to bet on import random from errors import * # get some money # Geldsack = Wallet(1000) # french testtable testtable = Table(None, "a") # init ball ball = Ball(testtable) # main betting bet = SingleBet(0, 5, testtable, ball) # bet on 0 with 2 dollars each endavg = [] for t in range(1000): # for 10 betting trials start with 1000$ Geldsack = Wallet(0, negative=True) history = [] for i in range(50): Geldsack.change_wealth(bet.bet_single()) history.append(Geldsack.get_wealth()) endavg.append(history[-1]) plt.plot([i for i in range(len(history))], history) plt.title(f"End average = {(sum(endavg)/len(endavg))}") plt.show()
class Playersim(object): """Parent class to model the basic characteristics of a simulated Player""" def __init__(self, tablebias, tabletype, startmoney, canHaveDebt, betting_amount, maxrounds, playercount): """[initialize a Playersim which initializes playercount player and plays maxrounds of ] Args: tablebias ([list]): [bias for the roulette table] tabletype ([str]): [type of roulette table to initialize] startmoney ([int]): [money every player starts with] canHaveDebt ([bool]): [ability for players to have debt] betting_amount ([int]): [amount of money player will bet every round] maxrounds ([int]): [maximum of rounds player plays if he is not elimineted earlier (if canHaveDebt = Fasle)] playercount ([int]): [How many players are simulated] """ self.tablebias = tablebias self.tabletype = tabletype self.startmoney = startmoney self.canHaveDebt = canHaveDebt self.betting_amount = betting_amount self.maxrounds = maxrounds self.playercount = playercount # list for simplayers self.simplayers = [] # init table """Note every player plays on same table""" self.simtable = Table(self.tablebias, self.tabletype) self.tablepockets = self.simtable.get_all_pockets() # init players for playernum in range(self.playercount): self.simplayers.append( SimPlayer(self.simtable, self.startmoney, self.canHaveDebt, playernum)) def basic_sim(self, bettype, debug=False, plothist=False, plotlin=False, plotmean=False, returnmean=False): """run a basic sim where every player bets one random number""" for run in range(self.maxrounds): for player in self.simplayers: # random choice if bettype == "Single": choice = random.choice(list(self.tablepockets.keys())) elif bettype == "Color": choice = random.choice(["r", "b"]) player.bet(self.betting_amount, "Color", choice) num, col = self.simtable.play_round_new() for player in self.simplayers: # update player.update_balance(num, col) if debug: print(player.get_SimPlayer_Number(), player.get_current_balance()) # all wealth histories: if True: # plothist or plotlin or plotmean: wealthhistory = [] for player in self.simplayers: wealthhistory.append(player.get_wallet().get_wealth_history()) if plothist: out = [x[-1] for x in wealthhistory] print(f"mean: {stat.mean(out)} stdev: {stat.stdev(out)}") plt.hist(out) plt.show() if plotlin: x = list(range(self.maxrounds+1)) y = wealthhistory m = [] for l in y: plt.plot(x, l) m.append(l[-1]) plt.title(f"Mean: {sum(m)/len(m)}") plt.show() if returnmean: return sum([l[-1]for l in wealthhistory])/len(wealthhistory) if plotmean: x = list(range(self.maxrounds+1))
def __init__(self, cur, wb): Table.sheet_name = u'activitybox(声望宝箱)' Table.sql = 'select * from activitybox' Table.titles = (u'序号', u'宝箱ID', u'宝箱数量', u'需求的活跃度') Table.__init__(self, cur, wb)
def main(): obj = Database("test") # table = Table("students", [IntColumn("id"), StrColumn("name")]) # obj.add_table(table) # table.insert_record([Value(Schema(IntColumn), 1), Value(Schema(StrColumn), "lokesh")]) # table.print_all_records() table = Table("users", [StrColumn("name"), StrColumn("email"), StrColumn("contact")]) obj.add_table(table) table.insert_record([Value(Schema(StrColumn), "lokesh"), Value(Schema(StrColumn), "*****@*****.**"), Value(Schema(StrColumn), "abcdef")]) table.insert_record([Value(Schema(StrColumn), None), Value(Schema(StrColumn), "*****@*****.**"), Value(Schema(StrColumn), "xyzzz")]) table.insert_record([Value(Schema(StrColumn), "baljit"), Value(Schema(StrColumn), "*****@*****.**"), Value(Schema(StrColumn), "hello_world")]) table.insert_record([Value(Schema(StrColumn), "asdfasfasfasfasdfasdfasfadfasdfasdffasd"), Value(Schema(StrColumn), "*****@*****.**"), Value(Schema(StrColumn), "hello_world")]) table.filter_records("name", "lokesh")
def get_relations(self, count = False, alias: str = None, types: list = None): """ Get all back references to record Params: - count: return just number of records - alias: return only relation with this alias - types: set condition for showing relation based on type """ # todo: Altfor lang og rotete funksjon from table import Table, Grid # Don't get values for new records that's not saved if hasattr(self, 'pk') and len(set(self.pk)): rec_values = self.get_values() relations = {} for key, rel in self.tbl.get_relations().items(): if alias and alias != key: continue db = Database(self.db.cnxn, rel.base) tbl_rel = Table(db, rel.table) grid = Grid(tbl_rel) # todo: too slow # permission = tbl_rel.get_user_permission(tbl_rel.name) # if not permission.view: continue tbl_rel.pkey = tbl_rel.get_primary_key() # If foreign key columns contains primary key if (set(tbl_rel.pkey) <= set(rel.foreign)): rel.type_ = '1:1' else: rel.type_ = '1:M' parts = tbl_rel.name.split("_") suffix = parts[-1] if types and (len(types) and suffix in types): show_if = {'type_': suffix} else: show_if = None pk = {} # Add condition to fetch only rows that link to record for idx, col in enumerate(rel.primary): ref_key = rel.foreign[idx] val = None if len(self.pk) == 0 else rec_values[ref_key] grid.add_cond(f"{rel.table}.{col}", "=", val) pk[col] = val if rel.get('filter', None): grid.add_cond(rel.filter) if count: #TODO: Burde vel være unødvendig med egen kode for å telle. #Skulle vel kunne kjøre spørringene og kun returnere antallet dersom count == True if len(self.pk): count_records = grid.get_rowcount() else: count_records = 0 relation = Dict({ 'count_records': count_records, 'name': rel.table, 'conditions': grid.get_client_conditions(), 'base_name': rel.base, 'relationship': rel.type_ }) if show_if: relation.show_if = show_if else: # todo: Are these necessary? tbl_rel.limit = 500 tbl_rel.offset = 0 tbl_rel.csv = False # Filter the list on highest level when necessary if self.tbl.name != tbl_rel.name: tbl_rel.user_filtered = False relation = tbl_rel.get_grid() # Find condition for relation # todo: Har håndtert at pk ikke er satt i php-koden values = [None if len(self.pk) == 0 else rec_values[key] for key in rel.foreign] for idx, col in enumerate(rel.primary): relation.fields[col].default = values[idx] relation.fields[col].defines_relation = True if rel.type == "1:1": rec = Record(self.db, tbl_rel, pk) relation.records = [rec.get()] relation.relationship == "1:1" else: relation.relationship == "1:M" relations[key] = relation return relations
def bot_battle_chip_graph(checkpoint_dir_0, name_agent_0, checkpoint_dir_1, name_agent_1): starting_stack = 10000 print("Loading ", checkpoint_dir_0) policy_0 = action_policy.RlBot(agent_name=name_agent_0, training=False, epsilon_testing=0.0, checkpoint_dir=checkpoint_dir_0) print("") print("Loading ", checkpoint_dir_1) policy_1 = action_policy.RlBot(agent_name=name_agent_1, training=False, epsilon_testing=0.0, checkpoint_dir=checkpoint_dir_1) policy_0.agent.write_state_action = False policy_1.agent.write_state_action = False player_0 = Player(name_agent_0, starting_stack, policy=policy_0.get_action) player_1 = Player(name_agent_1, starting_stack, policy=policy_1.get_action) players_list = [player_0, player_1] table = Table(players_list) hand_count = 0 games_played = 0 player_0_wins = 0 player_1_wins = 0 player_0_stack_gross = 0 player_1_stack_gross = 0 p0_stack_history = [player_0.stack] p1_stack_history = [player_1.stack] p0_stack_gross_history = [0] p1_stack_gross_history = [0] hands_played = 0 while hands_played < 1000: print(hands_played) table.play_single_hand() table.prepare_next_hand() hand_count += 1 p0_stack_history.append(player_0.stack) p1_stack_history.append(player_1.stack) p0_change = (p0_stack_history[-1] - starting_stack) p1_change = (p1_stack_history[-1] - starting_stack) player_0_stack_gross += p0_change player_1_stack_gross += p1_change p0_stack_gross_history.append(player_0_stack_gross) p1_stack_gross_history.append(player_1_stack_gross) player_0.stack = starting_stack player_1.stack = starting_stack hands_played += 1 plt.plot(range(hands_played + 1), p0_stack_gross_history, label="p0", color='green') plt.plot(range(hands_played + 1), p1_stack_gross_history, label="p1", color='red') plt.savefig(checkpoint_dir_0 + str(int(policy_0.agent.model.get_count_states().numpy())) + ".pdf") plt.close() plt.clf()
def test_table(self): table = Table(); table.addPlayer(Player("Test Player 1", buildHand(7), 'unique_id1', 100, True, False, 9, PlayerAction.CALL_CHECK_RAISE)) table.addPlayer(Player("Test Player 2", buildHand(7), 'unique_id2', 78, False, False, 10, PlayerAction.NONE)) table.addPlayer(Player("Test Player 3", buildHand(7), 'unique_id3', 16, False, True, 11, PlayerAction.NONE)) table.addPlayer(Player("Test Player 4", buildHand(7), 'unique_id4', 250, False, True, 11, PlayerAction.NONE)) table.pot = 25 table.cards.append(table.deck.deal()); table.blind = 4 originalDeck = table.deck; jsondata = json.dumps(table,default=jsob.convert_to_dict,indent=None, sort_keys=False) logger.info("From Object: " + jsondata) playerTable = db.tableCreateDelete.dynamodb.Table("TestPokerTable") playerTable.put_item( Item={ 'tableId': table.tableId, 'table': jsondata } ) # response = playerTable.get_item( Key={ 'tableId': table.tableId } ) tableJSONFromDB = response['Item']['table'] logger.info("From Database: " + tableJSONFromDB) tableII = json.loads(tableJSONFromDB, object_hook=jsob.dict_to_obj) self.assertEqual(table.players[0].name, tableII.players[0].name) self.assertEqual(table.cards[0], tableII.cards[0]) self.assertEqual(table.pot, tableII.pot) self.assertEqual(table.currentBet, tableII.currentBet) self.assertEqual(len(originalDeck.cards), len(tableII.deck.cards), "Needs to be the same number of cards in deck") playerTable.put_item( Item={ 'tableId': table.tableId, 'table': jsondata } ) # response = playerTable.get_item( Key={ 'tableId': table.tableId } ) tableJSONFromDB = response['Item']['table'] logger.info("From Database: " + tableJSONFromDB) tableIII = json.loads(tableJSONFromDB, object_hook=jsob.dict_to_obj) self.assertEqual(51, len(tableIII.deck.cards))
def setUp(self): self.wheel = Wheel() self.table = Table(self.wheel) self.player = Player57(self.table) self.game = Game(self.wheel, self.table)
from table import Table, Wheel, Bet import unittest t = Table(1000, 10) w=Wheel() class TestTableMethods(unittest.TestCase): def test_init(self): self.assertEqual(t.limit, 1000) self.assertEqual(t.minimum, 10) def test_place_bet(self): t.place_bet(10) self.assertEqual(len(t.bets), 1) def test_iter(self): self.assertEqual(t.__iter__(), t.bets) class TestWheelMethods(unittest.TestCase): def test_init(self): if __name__ == '__main__': unittest.main()
def process_specification(self, specification): if self._specification is None: self.load_specification(specification) spec = self._specification if spec.get("dataset_id"): base_uri = f"{DEFAULT_BASE_URI}{spec.get('dataset_id')}" else: base_uri = f"{DEFAULT_BASE_URI}{pathify(spec.get('title'))}" def prepend_base_uri(function, base_uri=spec.get("dataset_uri", base_uri)): def wrapper(name=None): uri = f"{base_uri}{function(name)}" return (uri) return wrapper @prepend_base_uri def make_local_dimension_uri(name): uri = f"#dimension/{pathify(name)}" return (uri) @prepend_base_uri def make_local_measure_uri(name): uri = f"#measure/{pathify(name)}" return (uri) @prepend_base_uri def make_local_component_uri(name): uri = f"#component/{pathify(name)}" return (uri) @prepend_base_uri def make_local_concept_uri(name): uri = f"#concept/{pathify(name)}/{{{namify(name)}}}" return (uri) @prepend_base_uri def make_local_concept_scheme_uri(name): uri = f"#scheme/{pathify(name)}" return (uri) @prepend_base_uri def make_local_class_uri(name): uri = f"#class/{classify(name)}" return (uri) @prepend_base_uri def make_dataset_contents_uri(name=None): uri = f"#dataset" return (uri) @prepend_base_uri def make_dataset_definition_uri(name=None): uri = f"#structure" return (uri) @prepend_base_uri def make_tables_uri(name=None): uri = f"#tables" return (uri) @prepend_base_uri def make_observation_uri(keys): uri = "/" + "/".join([f"{{{key}}}" for key in keys]) return (uri) self._components = [] self._columns = {} self._column_names = [x["name"] for x in spec["columns"]] self._keys = [ namify(x["name"]) for x in spec["columns"] if x["component_type"] == "dimension" ] for column in spec["columns"]: self._columns[column["name"]] = Column( name=namify(column["name"]), titles=[column["title"]], datatype=column.get("datatype"), suppressOutput=column.get("suppress_output"), virtual=column.get("virtual"), required=column.get("required"), propertyUrl=column.get("component_uri"), valueUrl=column.get("value_uri")) # DIMENSIONS ----------------------------------------------------------------------------------------------- if column["component_type"] == "dimension": if column.get("preset"): pass # If component_uri is specified, use that - failing that, coin a dimension URI dimension_uri = column.get( "component_uri", make_local_dimension_uri(column.get('name'))) #CODELISTS --------------------------------------------------------------------------------------------- # If codelist_filename and codelist_uri not specified, no codelist # If codelist_uri is specified, use that # If codelist_filepath is True but codelist_uri is unspecified, create a default # If codelist_filepath and codelist_uri are specified just use both if not column.get("codelist_filename") and not column.get( "codelist_uri"): codelist_uri = None # When no codelist, we set the dimension's range to rdfs:Resource # TODO we need to be careful setting such a wide range if a parent property is set dimension_range = 'https://www.w3.org/2000/01/rdf-schema#Resource' elif column.get("codelist_uri"): codelist_uri = column.get("codelist_uri") elif column.get("codelist_filename"): codelist_uri = make_local_concept_scheme_uri( column.get('name')) if column.get("codelist_uri") or column.get( "codelist_filename"): # When there is a codelist, we set the dimension's range to skos:Concept dimension_range = 'http://www.w3.org/2004/02/skos/core#Concept' if column.get("codelist_filename"): if not column.get("value_uri"): value_uri = make_local_concept_uri(column.get('name')) self._external_tables.append({ "@context": "http://www.w3.org/ns/csvw", "@id": codelist_uri, "url": column["codelist_filename"], "dcterms:title": column.get("codelist_title"), "dcterms:description": column.get("codelist_description"), "tableSchema": { # I make strong assumptions here about the format of the local codelist csv. These # should be loosened. "columns": [{ "titles": "Label", "name": "label", "datatype": "string", "required": True, "propertyUrl": "rdfs:label" }, { "titles": "Notation", "name": "notation", "datatype": { "base": "string", "format": "^-?[\\w\\.\\/\\+]+(-[\\w\\.\\/\\+]+)*$" }, "required": True, "propertyUrl": "skos:notation" }, { "titles": "Parent Notation", "name": "parent_notation", "datatype": { "base": "string", "format": "^(-?[\\w\\.\\/\\+]+(-[\\w\\.\\/\\+]+)*|)$" }, "required": False, "propertyUrl": "skos:broader", "valueUrl": re.sub("{.*?}", "{parent_notation}", value_uri) }, { "titles": "Sort Priority", "name": "sort", "datatype": "integer", "required": False, "propertyUrl": "http://www.w3.org/ns/ui#sortPriority" }, { "titles": "Description", "name": "description", "datatype": "string", "required": False, "propertyUrl": "rdfs:comment" }, { "virtual": True, "propertyUrl": "rdf:type", "valueUrl": "skos:Concept" }, { "virtual": True, "propertyUrl": "skos:inScheme", "valueUrl": codelist_uri }], "primaryKey": ["notation", "parent_notation"], "aboutUrl": re.sub("{.*?}", "{notation}", value_uri) }, "prov:hadDerivation": { "@id": codelist_uri, "@type": "skos:ConceptScheme" } }) #------------------------------------------------------------------------------------------------------- self._components.append( DimensionComponent( at_id=URI(make_local_component_uri( column.get('name'))), qb_componentProperty=Resource( at_id=URI(dimension_uri)), qb_dimension=DimensionProperty( at_id=URI(dimension_uri), qb_codeList=ConceptScheme( at_id=URI(codelist_uri), rdfs_label=column.get("codelist_title"), rdfs_comment=column.get( "codelist_description"), ) if codelist_uri else None, # Note that the current implementation sets the range to #class/Name # make_local_class_uri(column.get('name')) coins a URI in that form rdfs_range=Resource(at_id=URI(dimension_range)), rdfs_label=column.get("title"), rdfs_comment=column.get("description"), rdfs_subPropertyOf=URI(column.get("parent_uri")), rdfs_isDefinedBy=URI(column.get("defined_by"))))) # If component_uri is not specified then use the coined default dimension URI if not column.get("component_uri"): self._columns[column["name"]] = self._columns[ column["name"]]._replace( propertyUrl=URI(dimension_uri)) # If a value_uri is not set then default behaviour is to treat each cell entry as a typed literal, # but if a default codelist is created, then default URIs should be created for each cell entry also # and if a codelist_uri is specified then value_uri must be set. # We make an assumption that if a codelist_uri is specified, a value_uri will be also. if not column.get("value_uri") and column.get('codelist_uri'): raise ValueError( f"{column['name']} has a codelist_uri specified but no value_uri specified." ) if not column.get("value_uri") and ( column.get('codelist_filename') and not column.get('codelist_uri')): value_uri = make_local_concept_uri(column.get('name')) self._columns[column["name"]] = self._columns[ column["name"]]._replace(valueUrl=URI(value_uri)) # MEASURES ------------------------------------------------------------------------------------------------- elif column["component_type"] == "measure": # If component_uri is specified, use that - failing that, coin a measure URI measure_uri = column.get( "component_uri", make_local_measure_uri(column.get('name'))) self._components.extend([ DimensionComponent( at_id=URI(make_local_component_uri("measure-type")), qb_componentProperty=Resource(at_id=URI( "http://purl.org/linked-data/cube#measureType")), qb_dimension=DimensionProperty( at_id=URI( "http://purl.org/linked-data/cube#measureType" ), rdfs_range=Resource(at_id=URI( "http://purl.org/linked-data/cube#MeasureProperty" )))), MeasureComponent( at_id=URI(make_local_component_uri( column.get('name'))), qb_componentProperty=Resource(at_id=URI(measure_uri)), qb_measure=MeasureProperty( at_id=URI(measure_uri), # Range of the measure is an xsd datatype - default is xsd:decimal rdfs_range=Resource(at_id=URI( f"http://www.w3.org/2001/XMLSchema#{column.get('datatype', 'decimal')}" )), # Added in additional rdfs stuff which would have been defined in ref_common previously rdfs_label=column.get("title"), rdfs_comment=column.get("description"), rdfs_subPropertyOf=URI(column.get("parent_uri")), rdfs_isDefinedBy=URI(column.get("defined_by")))) ]) # If component_uri is not specified then use the coined default measure URI if not column.get("component_uri"): self._columns[column["name"]] = self._columns[ column["name"]]._replace(propertyUrl=URI(measure_uri)) if not column.get("datatype"): self._columns[column["name"]] = self._columns[ column["name"]]._replace(datatype=URI( 'http://www.w3.org/2001/XMLSchema#decimal')) self._columns["virtual_measure"] = Column( name="virtual_measure", virtual=True, propertyUrl=URI( "http://purl.org/linked-data/cube#measureType"), valueUrl=URI(measure_uri)) # If units are specified add as an attribute if column.get("units_uri"): self._components.append( AttributeComponent( at_id=URI(make_local_component_uri("unit")), qb_componentProperty=Resource(at_id=URI( "http://purl.org/linked-data/sdmx/2009/attribute#unitMeasure" )), qb_attribute=AttributeProperty(at_id=URI( "http://purl.org/linked-data/sdmx/2009/attribute#unitMeasure" )))) self._columns["virtual_unit"] = Column( name="virtual_unit", virtual=True, propertyUrl=URI( "http://purl.org/linked-data/sdmx/2009/attribute#unitMeasure" ), valueUrl=URI(column.get("units_uri"))) # ATTRIBUTES ----------------------------------------------------------------------------------------------- elif column["component_type"] == "attribute": self._components.append( AttributeComponent( at_id=URI(make_local_component_uri( column.get('name'))), qb_componentProperty=Resource( at_id=URI(column.get("component_uri"))), qb_attribute=AttributeProperty( at_id=URI(column.get("component_uri")), rdfs_range=Resource(at_id=URI( "http://www.w3.org/2000/01/rdf-schema#Class") )))) self._columns[column["name"]] = self._columns[ column["name"]]._replace( propertyUrl=URI(column.get("component_uri")), valueUrl=URI(column.get("value_uri"))) # VIRTUAL COLUMNS ---------------------------------------------------------------------------------------------- self._columns["virtual_dataset"] = Column( name="virtual_dataset", virtual=True, propertyUrl=URI("http://purl.org/linked-data/cube#dataSet"), valueUrl=URI(make_dataset_contents_uri())) self._columns["virtual_type"] = Column( name="virtual_type", virtual=True, propertyUrl=URI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), valueUrl=URI("http://purl.org/linked-data/cube#Observation")) table_uri = URI(self._specification["csv_filename"]) # if self._metadata_filename is not None: # table_uri = URI(self._csv_filename.relative_to(self._metadata_filename.parent)) # Additional changes could be made here to include dataset metadata such as the dataset title/description. # It is a requirement that virtual columns are at the end of the metadata file, so we reorder. columns = list(self._columns.values()) columns.sort(key=lambda x: x.virtual is True) main_table = Table(url=table_uri, tableSchema=TableSchema( columns=columns, primaryKey=self._keys, aboutUrl=URI(make_observation_uri(self._keys)), foreignKeys=self._foreign_keys)) self._validate() self._map = { "@context": ["http://www.w3.org/ns/csvw", { "@language": "en" }], "tables": [main_table] + self._external_tables, "@id": make_tables_uri(), "prov:hadDerivation": DataSet(at_id=make_dataset_contents_uri(), dcterms_title=spec.get("title"), dcterms_description=spec.get("description"), dcterms_publisher=spec.get("publisher"), dcterms_issued=spec.get("published"), dcterms_modified=spec.get("modified"), dcat_landingPage=spec.get("landing_page"), qb_structure=DSD(at_id=make_dataset_definition_uri(), qb_component=self._components)) }
def create_tab(self, name): self.count+=1 tab = Table(self.notebook, name) self.notebook.add(tab, text=tab.title.get())
def get_relation_count(self, types: list = None): from table import Table, Grid relations = {} for key, rel in self.tbl.get_relations().items(): if self.db.cnxn.system == 'postgres': base_name = rel.base + '.' + rel.schema else: base_name = rel.base or rel.schema if rel.base == self.db.cat and rel.schema == self.db.schema: db = self.db else: db = Database(self.db.cnxn, base_name) tbl_rel = Table(db, rel.table) if rel.table not in self.db.user_tables: continue tbl_rel.fields = tbl_rel.get_fields() grid = Grid(tbl_rel) grid2 = Grid(tbl_rel) # Used to count inherited records # Find index used slice_obj = slice(0, len(rel.foreign)) rel_indexes = tbl_rel.get_indexes() for index in rel_indexes.values(): if index.columns[slice_obj] == rel.foreign: rel.index = index if index.unique: break # todo: filtrate on highest level # Don't get values for new records that's not saved if hasattr(self, 'pk') and len(set(self.pk)): rec_values = self.get_values() or self.pk # Add condition to fetch only rows that link to record conds = Dict() count_null_conds = 0 for idx, col in enumerate(rel.foreign): ref_key = rel.primary[idx].lower() val = None if len(self.pk) == 0 else rec_values[ref_key] if (tbl_rel.fields[col].nullable and col != rel.foreign[0] and rel.primary == list(self.pk.keys()) and rel.index.unique is True ): grid2.add_cond(expr = f"{rel.table}.{col}", operator = "IS NULL") count_null_conds += 1 else: grid2.add_cond(f"{rel.table}.{col}", "=", val) grid.add_cond(f"{rel.table}.{col}", "=", val) conds[col] = val if len(self.pk): count_records = grid.get_rowcount() else: count_records = 0 count_inherited = 0 if count_null_conds: count_inherited = grid2.get_rowcount() tbl_rel.pkey = tbl_rel.get_primary_key() if set(tbl_rel.pkey) <= set(rel.foreign): relationship = "1:1" else: relationship = "1:M" relation = Dict({ 'count_records': count_records + count_inherited, 'count_inherited': count_inherited, 'name': rel.table, 'conditions': grid.get_client_conditions(), 'conds': conds, 'base_name': rel.base, 'schema_name': rel.schema, 'relationship': relationship, 'delete_rule': rel.delete_rule }) # Tables with suffixes that's part of types # should just be shown when the specific type is chosen parts = tbl_rel.name.split("_") suffix_1 = parts[-1] suffix_2 = '' if len(parts) == 1 else parts[-2] show_if = None for type_ in types: if (suffix_1.startswith(type_) or suffix_2.startswith(type_)): show_if = {'type_': type_} if show_if: relation.show_if = show_if relations[key] = relation return relations
class IncomeDocs(BaseFrame, Frame): def __init__(self, master=None, **kwargs): Frame.__init__(self, master, **kwargs) self._columns = [ "Nr Dok", "Kontrahent", "Nazwa", "Data Dok", "Data Ksiegowania", "Ilosc", "Cena", "Wartosc", ] self._disabled_columns = ["Nr Dok", "Wartosc"] self.master = master self.table = None self.row_id_input = None self.new_rows_count = 0 master.title("Dokumenty Przychodowe") master.geometry("850x650+300+200") self.init_table() self.init_table_btns(True) def init_table(self): inf_about_kontrahent = self.get_inf_about_kontrahent() comboboxes = {"Kontrahent": inf_about_kontrahent} self.table = Table( self.master, self._columns, disabled_columns=self._disabled_columns, comboboxes=comboboxes, ) self.table.pack(fill=X, padx=10, pady=10) self.init_table_data() def init_table_data(self): rows = get_income_docs() result = [] for row in rows: r = row[:2] + row[3:] result.append(r) if result: self.table.set_data(result) @staticmethod def get_inf_about_kontrahent(): kontrahents_names = [] rows = select_agent() for row in rows: kontrahents_names.append(row[0]) return kontrahents_names @staticmethod def get_storage_names(): storage_names = [] rows = get_storage_names() for row in rows: storage_names.append(row[0]) return storage_names def add_row(self): last_row_index = self.table.number_of_rows index = get_doc_mag_max_index() or 0 self.table.append_n_rows(1) self.table.cell(last_row_index, 0, index + 1 + self.new_rows_count) self.new_rows_count += 1 def save(self): cleaned_data = self.clean() if cleaned_data is None: return for d in cleaned_data: insert_income_docs(**d) insert_income_docs_into_kartoteka(**d) self.init_table_data() self.new_rows_count = 0 def clean(self): result = [] if self.new_rows_count < 1: return None data = self.table.get_data() data = data[-self.new_rows_count:] for first_row in data: d = dict( nr_dok=first_row[0], kontrahent=first_row[1], nazwa=first_row[2], data_dok=first_row[3], data_ksiegowania=first_row[4], ilosc=first_row[5], cena=first_row[6], ) if not is_datetime_validate(d["data_dok"]): messagebox.showwarning("Zle wpisywana data", "Sporobuj ponownie") return d["wartosc"] = int(d["ilosc"]) * float(d["cena"]) result.append(d) return result def delete_row(self): row_id = self.row_id_input.get() if len(row_id) == 0 or not row_id.isnumeric(): messagebox.showwarning("Zle podane ID", "Sporobuj ponownie") return table_data = self.table.get_data() index = -1 for i, row in enumerate(table_data): if row[0] == row_id: index = i break if index == -1: messagebox.showwarning("Zle podane ID", "Sporobuj ponownie") return self.table.delete_row(index) delete_doc(row_id) def ksieguj(self): datetime = get_current_datetime() last_row_index = self.table.number_of_rows self.table.cell(last_row_index - 1, 4, datetime)
class Game: players = [] last_round = False winner = " " maximum_scores = 0 def __init__(self): self.az_table = Table() self.az_player = Player("MyPlayer", self.az_table) self.ai_player = AiPlayer("AiPlayer", self.az_table) self.players.append(self.az_player) self.players.append(self.ai_player) self.ai_player.get_opponents(self.players) def play_game(self): self.az_table.fill_boxes() while not self.last_round: self.az_table.print_table() if self.az_table.has_tile(): for player in self.players: if self.az_table.has_tile(): print("Player = %s" % player.name) player.play() self.az_table.print_table() else: break for player in self.players: if player.is_last_round(): self.last_round = player.is_last_round() for player in self.players: player.move_tiles_to_board() if not self.last_round and not self.az_table.has_tile(): self.az_table.fill_boxes() for player in self.players: player.calculate_scores_after_round() if player.scores > self.maximum_scores: self.maximum_scores = player.scores self.winner = player.name print("The winner is %s" % self.winner)
#!env python2 from table import Table from random import randint as rand t = Table(6, width="fit", align=">>>>>>", fmt="d|d|d|d|d|d") # fixed width, 3 columns t.set_header("$$ Amount", "Cookies", "No.1", "No.2", "No.3", "No.4") for i in xrange(13): for x in xrange(6): t << rand(0, 999999) print t print print "Try different styles easily:" print t.header_sep = "-" t.tbl_style = "closed" t.line = "-" t.spacer = " | " print t print print t.set_col_format(2, ".4e") t.set_col_format(3, "15,.5f") t.set_col_format(4, "010d") t.header_sep = "=" t.width_method = "full" print t # -----------------------------------------------------------------------------
def __init__(self): self.queue_a = Queue() self.queue_b = Queue() self.table = Table() self.robot = Robot(self.queue_a, self.queue_b, self.table)
def main(): mytable = Table(num_ai_players=3, verbose=2) mytable.play() mytable.score()
def __init__(self, cur, wb): Table.sheet_name = u'event(事件)' Table.sql = 'select * from event' Table.titles = (u'事件ID', u'actNum', u'发送邮件', u'邮件标题', u'邮件内容', u'发送聊天消息', u'消息内容', u'频道', u'子频道', u'sendWin', u'winStartId', u'sendPChat', u'chatP内容', u'chatPChannel', u'chatPChildChannel') Table.__init__(self, cur, wb)
import time import pygame from coin import Coin from table import Table table_radius = 100 coin_radius = 25 table = Table((0, 0), table_radius) width = 500 height = 500 pygame.init() window = pygame.display.set_mode((500, 500)) pygame.display.set_caption("COINS") window.fill((255, 255, 255)) pygame.display.update() font = pygame.font.SysFont("monospace", 15) set_of_coins = set() set_of_coins.add(Coin(table.center, coin_radius)) for coin in set_of_coins: window.fill((255, 255, 255)) pygame.draw.circle(window, (0, 0, 0), (width // 2 + table.center[0], height // 2 - table.center[1]), table_radius, 1) pygame.draw.circle(window, (255, 0, 0), (width // 2 + coin.center[0], height // 2 - coin.center[1]), coin_radius, 1) text1 = font.render("YOUR TURN TO PLAY", 1, (0, 0, 0)) window.blit(text1, (width // 2 - 110, 20)) pygame.display.update() end_of_game = False while not end_of_game: pygame.time.delay(50) pos = (0, 0)
def mainThread(): table = Table() table.addpiece(1, 0, Pawn(1, 0, pawn_color, table.table_map)) table.addpiece(1, 1, Pawn(1, 1, pawn_color, table.table_map)) table.addpiece(1, 2, Pawn(1, 2, pawn_color, table.table_map)) table.addpiece(1, 3, Pawn(1, 3, pawn_color, table.table_map)) table.addpiece(1, 4, Pawn(1, 4, pawn_color, table.table_map)) table.addpiece(1, 5, Pawn(1, 5, pawn_color, table.table_map)) table.addpiece(1, 6, Pawn(1, 6, pawn_color, table.table_map)) table.addpiece(1, 7, Pawn(1, 7, pawn_color, table.table_map)) table.addpiece(0, 0, Tower(0, 0, tower_color, table.table_map)) table.addpiece(0, 1, Horse(0, 1, horse_color, table.table_map)) table.addpiece(0, 2, Bishop(0, 2, bishop_color, table.table_map)) table.addpiece(0, 3, King(0, 3, king_color, table.table_map)) table.addpiece(0, 4, Queen(0, 4, quin_color, table.table_map)) table.addpiece(0, 5, Bishop(0, 5, bishop_color, table.table_map)) table.addpiece(0, 6, Horse(0, 6, horse_color, table.table_map)) table.addpiece(0, 7, Tower(0, 7, tower_color, table.table_map)) table.addpiece(6, 0, Pawn(6, 0, pawn_color, table.table_map, True)) table.addpiece(6, 1, Pawn(6, 1, pawn_color, table.table_map, True)) table.addpiece(6, 2, Pawn(6, 2, pawn_color, table.table_map, True)) table.addpiece(6, 3, Pawn(6, 3, pawn_color, table.table_map, True)) table.addpiece(6, 4, Pawn(6, 4, pawn_color, table.table_map, True)) table.addpiece(6, 5, Pawn(6, 5, pawn_color, table.table_map, True)) table.addpiece(6, 6, Pawn(6, 6, pawn_color, table.table_map, True)) table.addpiece(6, 7, Pawn(6, 7, pawn_color, table.table_map, True)) table.addpiece(7, 0, Tower(7, 0, tower_color, table.table_map)) table.addpiece(7, 1, Horse(7, 1, horse_color, table.table_map)) table.addpiece(7, 2, Bishop(7, 2, bishop_color, table.table_map)) table.addpiece(7, 3, King(7, 3, king_color, table.table_map)) table.addpiece(7, 4, Queen(7, 4, quin_color, table.table_map)) table.addpiece(7, 5, Bishop(7, 5, bishop_color, table.table_map)) table.addpiece(7, 6, Horse(7, 6, horse_color, table.table_map)) table.addpiece(7, 7, Tower(7, 7, tower_color, table.table_map)) while True: for evento in py.event.get(): if evento.type == py.QUIT: py.quit() display.fill((255,255,255)) table.render(display, py, font) py.display.flip() time.tick(64)
def __init__(self, connection, *args, **kwargs): Table.__init__(self, connection) self._table_name = kwargs.get('table_name') self._db_metrics = kwargs.get('metrics_db')