def draw(self): if len(self.deck) == 0: self.life = 0 debug('Deckout!') return False self.hand.append(self.deck.pop()) return True
def __init__(self, scale=20, compass=(0, 88)): ''' Docstring goes here ''' # Dimensions self.dx = 2.0 * scale # Width of a white key self.dy = 13.5 * scale # Height of a white key self.bdx = 1.2 * scale # Width of a black key self.bdy = 8.5 * scale # Height of a black key # Settings self.keyUtils = Key(0, (self.dx, self.dy), (self.bdx, self.bdy)) # Key instance (gives us access to instance methods) self.compass = (self.keyUtils.normalize(compass[0]), self.keyUtils.normalize(compass[1])) # Range of keyboard debug(self.compass) # self.surface = pygame.Surface(self.size(padx=10, pady=10, compass=self.compass)) # TODO: Fix hard-coded values self.keys = self.build(self.compass) # Create the piano # Aesthetics self.labelOptions = {'fill': (0x0, 0x0, 0x0)} # self.padx = 10 self.pady = 10 # self.update() print('Range is {} to {}.'.format(*compass)) print('Range is {} to {}.'.format(*self.compass)) print('Index of {} is {}'.format(compass[0], self.compass[0])) print('Index of {} is {}'.format(compass[1], self.compass[1]))
def key(self, key): # TODO: Use Key alias utilities (...) # TODO: Take offset into account (...) # TODO: Rename (?) # TODO: Make sure this is correct and doesn't break after each change debug('Retrieving key {!r} from piano'.format(key)) debug('Number of keys: ', len(self.keys)) return self.keys[self.keyUtils.alias(key, to=int)-self.compass[0]]
def attack(self, p2): for atkr in self.creatures(): if atkr.sick: continue atkr.attacking = True for defr in p2.creatures(): if defr.toughness > atkr.power and (not defr.tapped): atkr.attacking = False break if atkr.attacking: debug('Attacking:', atkr)
def howdy(): # pylint: disable=unused-variable ''' Interactive Web Shell Provide a development/debug shell within the web browser at this endpoint. --- responses: 200: description: "Interactive shell" ''' utilities.debug() return "Interactive shell"
def defend(self, p1): for defr in self.creatures(): if defr.tapped: continue attackers = [a for a in p1.creatures() if a.attacking and \ a.blocker == None] for atkr in attackers: if defr.power >= atkr.toughness: defr.damage(atkr.power) atkr.damage(defr.power) atkr.blocker = defr debug(defr, 'blocked',atkr) break
def get_refs_for_subreddits_helper(subreddit_names, conn): num_subreddits = len(subreddit_names) get_subreddits_sql = \ """ SELECT name, refs FROM subreddits WHERE name IN ({}); """.format(",".join(["?"] * num_subreddits)) debug(get_subreddits_sql) debug(subreddit_names) cur = conn.execute(get_subreddits_sql, subreddit_names) return {u[0]: u[1] for u in cur.fetchall()}
def alias(self, key, to=int): # Converts between different representations (aliases) of a key # NOTE: Currently, this method will always return an index (int) # TODO: Implement multi-way mapping or translation (maybe via an A to B to C and C to B to A scheme) # TODO: More elegant scheme for lazy evaluation (?) # debug('key={!r}, to={!r}'.format(key, to)) frm = type(key) if frm is to: return key else: index = self.conversions[frm](self, key) debug('Index of %r is %d' % (key, index)) return self.aliases[to](self, index)
def play_card_type(self, card_type): if card_type == Land: for d in self.hand: if isinstance(d, card_type): self.battlefield.append(self.hand.pop(self.hand.index(d))) return True return False elif card_type == Creature: for d in self.hand: if isinstance(d, card_type): if self.try_to_pay_cost(d): debug('Casting', d, d.cost) self.battlefield.append(d) self.hand.remove(d) return True return False if debug_flag: assert False
def build(self, compass): ''' Builds the components of the piano ''' # TODO: Options # TODO: Animation # TODO: Wavefront 3D model # TODO: Padding # TODO: Individually accessible keys, colour changes # TODO: Convert to class (?) # TODO: Class for individual keys (press, play, etc.) dx, dy = self.dx, self.dy bdx, bdy = self.bdx, self.bdy # | | # | | # | | # _| |_ # | | # | | # | | # | | # |______| # return [Key(i, (dx, dy), (bdx, bdy), first=compass[0]) for i in range(*compass)] keys = [Key(i, (dx, dy), (bdx, bdy), first=compass[0]) for i in range(*compass)] first = keys[5] print('Shape:', first.shape) print('First: {!r}'.format(first)) debug('Creating {} keys.'.format(len(keys))) debug('Creating {} keys.'.format(self.compass[1]-self.compass[0])) if first.shape in (Key.LEFT, Key.MIDDLE): # HACK: Solves problem with accidentals as the first key first.shape == Key.LEFT first.fill = (255, 50, 25) first.vertices = first.makeVertices((dx-5, dy-5), (bdx, bdy)) return keys
def authorize(client_id, client_secret, config): """ A module method to authorize Spotify using a OAuth client ID and client secret. """ state = util.random_string(14) scope = 'playlist-modify-private' authorization_url = '{}?client_id={}&response_type=code'.format( REQUEST_TOKEN_URL, client_id ) authorization_url += '&redirect_uri={}&state={}&scope={}'.format( CALLBACK_URI, state, scope ) if config.verbose: util.debug('Authorization URL constructed: {}'.format(authorization_url)) # Prompt the user to authorize via a browser: util.info('Now opening a browser to authorize your Spotify account.') util.info('Once authorized, copy/paste the URL of that browser window here.') util.info('Finally, hit enter to complete the auhtorization process.') util.confirm('Do you want to continue?') util.open_url(authorization_url) # Deal with the return code: authorization_response = util.prompt('Enter the URL', None) parsed = urlparse.urlparse(authorization_response) authorization_args = urlparse.parse_qs(parsed.query) if config.verbose: util.debug('Authorization arguments: {}'.format(authorization_args)) # Check to make sure the states between request and response match: if state == authorization_args.get('state')[0]: if 'code' in authorization_args: # The authorization succeeded: params = { 'client_id': client_id, 'client_secret': client_secret, 'grant_type': 'authorization_code', 'code': authorization_args.get('code')[0], 'redirect_uri': CALLBACK_URI } r = requests.post(ACCESS_TOKEN_URL, data=params) if config.verbose: util.debug('Access response: {}'.format(r.content)) return r.json() else: # The authorization failed: if 'error' in authorization_args: raise music_service.AuthorizationError(authorization_args.get('error')[0]) else: raise music_service.AuthorizationError('unknown authorization error') else: raise SpotifyStateError()
def authorize(client_id, client_secret, config): # Get the resource OAuth keys: oauth = OAuth1(client_id, client_secret=client_secret, callback_uri=CALLBACK_URI) r = requests.post(url=REQUEST_TOKEN_URL, auth=oauth) if config.verbose: util.debug('Request token response: {}'.format(r.content)) credentials = urlparse.parse_qs(r.content) if credentials: # If the token request worked, proceed: resource_owner_key = credentials.get('oauth_token')[0] resource_owner_secret = credentials.get('oauth_token_secret')[0] authorize_url = BASE_AUTHORIZATION_URL + '?oauth_token=' authorize_url = authorize_url + resource_owner_key if config.verbose: util.debug('Authorization URL constructed: {}'.format(authorize_url)) util.info('Now opening a browser to authorize your Beatport account.') util.info('Once authorized, copy/paste the URL of that browser window here.') util.info('Finally, hit enter to complete the auhtorization process.') util.confirm('Do you want to continue?') util.open_url(authorize_url) # Deal with the return code: authorization_response = util.prompt('Enter the URL', None) parsed = urlparse.urlparse(authorization_response) authorization_args = urlparse.parse_qs(parsed.query) verifier = authorization_args.get('oauth_verifier')[0] if config.verbose: util.debug('Authorization arguments: {}'.format(authorization_args)) # Finally, get the access tokens: oauth = OAuth1(client_id, client_secret=client_secret, resource_owner_key=resource_owner_key, resource_owner_secret=resource_owner_secret, verifier=verifier) r = requests.post(url=ACCESS_TOKEN_URL, auth=oauth) if config.verbose: util.debug('Access response: {}'.format(r.content)) return urlparse.parse_qs(r.content) else: raise service.AuthorizationError('Invalid client ID and client secret...')
def fight(self): decks = self.decks for i in range(0, len(decks), 2): d1 = decks[i] d2 = [] if len(decks) - 1 == i: d2 = decks[i - 1] else: d2 = decks[i + 1] shuffle(d1.cards) shuffle(d2.cards) p1 = Player(deepcopy(d1), 1) p2 = Player(deepcopy(d2), 2) # A random player will start the game if random() < 0.5: p1, p2 = p2, p1 # p1 doesn't draw in the first turn p1.deck.cards.append(p1.hand.pop()) n_turns = 0 while p1.life > 0: p1.untap_and_upkeep() if (not p1.draw()): p1, p2 = p2, p1 n_turns += 1 break p1.play_card_type(Land) while p1.play_card_type(Creature): pass p1.attack(p2) p2.defend(p1) self.resolve_damage(p1, p2) if len(p1.hand) > 7: debug('Removing', p1.hand[0].name, 'from hand.') p1.hand.pop(0) if n_turns % 2 == 0: self.print_game_state(p1, p2, n_turns) p1, p2 = p2, p1 else: p1, p2 = p2, p1 self.print_game_state(p1, p2, n_turns) n_turns += 1 n_turns -= 1 debug('Game ended in', n_turns, 'turns.') if n_turns % 2 == 0: p1, p2 = p2, p1 debug('Lives:', p1.life, p2.life) assert len(d1) == 60 and len(d2) == 60 # Compute score if p1.life <= 0: if p1.id == 1: d1.loss += 1 d2.win += 1 else: d1.win += 1 d2.loss += 1 else: assert p2.life <= 0 if p2.id == 2: d1.win += 1 d2.loss += 1 else: d1.loss += 1 d2.win += 1 if partial_results: print '# Partial result: #' for w in decks: print '[' + str(w.id) + '] =', w.win, w.loss, w.ratio() print '###################'
def process_redditor(redditor_name, database_name, limit=1000, reddit_obj=None): if reddit_obj is None: reddit_obj = praw.Reddit(USER_AGENT) debug("Got reddit object") submission_gen = reddit.get_submissions_from_redditor( redditor_name, reddit_obj=reddit_obj, limit=limit) comment_gen = reddit.get_comments_from_redditor( redditor_name, reddit_obj=reddit_obj, limit=limit) debug("Got submissions and comments") subreddits = {} submissions = [] comments = [] for s in submission_gen: submission_id = s.name subreddit_name = s.subreddit.display_name.lower() title = s.title karma = s.score if s.is_self: link = "self" else: link = s.url is_nsfw = 1 if s.over_18 else 0 subreddits[subreddit_name] = subreddits.get(subreddit_name, 0) + 10 submissions.append((submission_id, redditor_name, subreddit_name, title, karma, link, is_nsfw)) for c in comment_gen: if c.author is None: # Deleted comment. continue comment_id = c.name submission_id = c.parent_id karma = c.score if c.subreddit_id in subreddit_display_names: subreddit_name = subreddit_display_names[c.subreddit_id] else: try: subreddit_name = c.subreddit.display_name.lower() subreddit_display_names[c.subreddit_id] = subreddit_name except ValueError: subreddit_name = None if subreddit_name: subreddits[subreddit_name] = subreddits.get(subreddit_name, 0) + 1 comments.append((comment_id, redditor_name, submission_id, karma)) # Add up the refs. conn = sqlite3.connect(database_name) refs = get_refs_for_subreddits(subreddits.keys(), conn) new_subreddits = {x: subreddits[x] for x in subreddits if x not in refs} old_subreddits = {x: subreddits[x] for x in subreddits if x in refs} old_subreddits = Counter(old_subreddits) + Counter(refs) timestamp = timegm(datetime.utcnow().utctimetuple()) old_subreddits = [(old_subreddits[u], u) for u in old_subreddits.keys()] new_subreddits = [(u, None, new_subreddits[u], None) for u in new_subreddits.keys()] debug("Old:", old_subreddits) debug("New:", new_subreddits) cur = conn.cursor() cur.executemany(insert_subreddit_sql, new_subreddits) cur.executemany(update_subreddit_refs_sql, old_subreddits) cur.executemany(insert_submission_sql, submissions) cur.executemany(insert_comment_sql, comments) cur.executemany(insert_redditor_sql, [(redditor_name, -1, timestamp)]) conn.commit()
def process_subreddit(subreddit_name, database_name, limit=1000, reddit_obj=None): if reddit_obj is None: reddit_obj = praw.Reddit(USER_AGENT) submission_gen = reddit.get_hot_from_subreddit(subreddit_name, reddit_obj=reddit_obj, limit=limit) redditors = {} submissions = [] comments = [] count = 0 for s in submission_gen: if (limit < 100) or (count % (limit / 10) == 0): print(" -> processing submission number", count) submission_id = s.name try: redditor_name = s.author.name.lower() except AttributeError: redditor_name = "" title = s.title karma = s.score if s.is_self: link = "self" else: link = s.url is_nsfw = 1 if s.over_18 else 0 if redditor_name != "": redditors[redditor_name] = redditors.get(redditor_name, 0) + 10 submissions.append((submission_id, redditor_name, subreddit_name, title, karma, link, is_nsfw)) for c in reddit.get_all_comments_from_submission(s, limit=5): if c.author is None: # Deleted comment. continue comment_id = c.name try: redditor_name = c.author.name.lower() except AttributeError: continue karma = c.score redditors[redditor_name] = redditors.get(redditor_name, 0) + 1 comments.append((comment_id, redditor_name, submission_id, karma)) count += 1 # Add up the refs. conn = sqlite3.connect(database_name) refs = get_refs_for_redditors(redditors.keys(), conn) new_redditors = {x: redditors[x] for x in redditors if x not in refs} old_redditors = {x: redditors[x] for x in redditors if x in refs} old_redditors = Counter(old_redditors) + Counter(refs) timestamp = timegm(datetime.utcnow().utctimetuple()) old_redditors = [(old_redditors[u], u) for u in old_redditors.keys()] new_redditors = [(u, new_redditors[u], None) for u in new_redditors.keys()] debug("old:", old_redditors) debug("new:", new_redditors) cur = conn.cursor() cur.executemany(insert_redditor_sql, new_redditors) cur.executemany(update_redditor_refs_sql, old_redditors) cur.executemany(insert_submission_sql, submissions) cur.executemany(insert_comment_sql, comments) subreddit_is_nsfw = reddit_obj.get_subreddit(subreddit_name).over18 subreddit_is_nsfw = 1 if subreddit_is_nsfw else 0 cur.executemany(insert_subreddit_sql, [(subreddit_name, subreddit_is_nsfw, -1, timestamp)]) conn.commit()
def fight(self): decks = self.decks for i in range(0, len(decks), 2): d1 = decks[i] d2 = [] if len(decks)-1 == i: d2 = decks [i-1] else: d2 = decks[i+1] shuffle(d1.cards) shuffle(d2.cards) p1 = Player(deepcopy(d1), 1) p2 = Player(deepcopy(d2), 2) # A random player will start the game if random() < 0.5: p1,p2=p2,p1 # p1 doesn't draw in the first turn p1.deck.cards.append(p1.hand.pop()) n_turns = 0 while p1.life > 0: p1.untap_and_upkeep() if(not p1.draw()): p1,p2=p2,p1 n_turns+=1 break p1.play_card_type(Land) while p1.play_card_type(Creature): pass p1.attack(p2) p2.defend(p1) self.resolve_damage(p1, p2) if len(p1.hand) > 7: debug('Removing', p1.hand[0].name, 'from hand.') p1.hand.pop(0) if n_turns % 2 == 0: self.print_game_state(p1,p2,n_turns) p1, p2 = p2, p1 else: p1, p2 = p2, p1 self.print_game_state(p1,p2,n_turns) n_turns+=1 n_turns-=1 debug('Game ended in', n_turns,'turns.') if n_turns % 2==0: p1,p2=p2,p1 debug('Lives:', p1.life, p2.life) assert len(d1) == 60 and len(d2) == 60 # Compute score if p1.life <= 0: if p1.id == 1: d1.loss += 1 d2.win += 1 else: d1.win += 1 d2.loss += 1 else: assert p2.life <= 0 if p2.id == 2: d1.win += 1 d2.loss += 1 else: d1.loss += 1 d2.win += 1 if partial_results: print '# Partial result: #' for w in decks: print '['+str(w.id)+'] =',w.win, w.loss, w.ratio() print '###################'
import PySimpleGUI as sg import utilities as util sg.theme('DarkAmber') layout = [ [sg.Text('Filename')], [], [], [sg.Input(), sg.FileBrowse()], [sg.Button('Ok'), sg.Button('Cancel')] ] window = sg.Window('Photos Organiser', layout) while True: event, values = window.read() util.debug(event) util.debug(values) if event == sg.WIN_CLOSED or event == 'Cancel': break window.close()