def check_one_color(self): if len(self.colors_to_check) == 0: self.save_answer() return color_to_check = self.colors_to_check.pop() self.gui.configure(bg=_from_rgb(self.colors[color_to_check])) self.gui.update() time.sleep(0.5) image = self.provider.get_pil_image() image.save("runData/" + color_to_check + ".bmp") map_box = Positions.get("cam_minimap_ul") + Positions.get( "cam_minimap_lr") new_rgb = (_get_mean_rgb(image.crop(map_box))) self.corrected_colors[color_to_check] = new_rgb print(color_to_check) print("old rgb:", self.colors[color_to_check]) print("new rgb:", new_rgb) self.gui.after(50, self.check_one_color)
def __init__(self, configuration, initial_price, forecast, env_memory): self.params = configuration self.display = self.params.display self.log = self.params.log self.initial_budget = scale(self.params.initial_budget, 0., self.params.fcast_file.max_support) self.positions = Positions(configuration, self.initial_budget) self.reset(initial_price, forecast, env_memory)
def get_pil_image(self): if self.reapeat_window: return Image.open("window.bmp") r, frame = self.vid.read() ul = Positions.get("cam_tibia_window_ul") lr = Positions.get("cam_tibia_window_lr") return Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)).crop(ul + lr)
def setup_positions(self, config, manual): # If doing manual, need to initiate Positions differently than if random, # so key presses work properly self.manual = manual if self.manual: del self.pos # print 'manual positions' self.pos = Positions(config) else: del self.pos # print 'auto positions' self.pos = Positions(config).get_position(self.depth, True)
def next(self): #print 'xwin', self.base.win.getProperties().getXSize() if self.mode == 0: self.pos = Positions(self.config).get_position(self.depth, 'small') self.mode = 1 square = self.make_square() try: square.setPos(Point3(self.pos.next())) print square.getPos() except StopIteration: print 'done'
def all(self): pos = None if self.mode == 0: self.make_circle() pos = Positions(self.config).get_position(self.depth) self.mode = 1 #print pos #for i, j in enumerate(pos): while True: try: position = pos.next() except StopIteration: break square = self.make_square() square.setPos(Point3(position))
def __init__(self, person_name, person_socials, ico_name, ico_token, ico_url, unclear_role): self.name = person_name self.socials = Social(person_socials) self.positions = Positions() self.uncertain_positions = Positions() roles = Role.detect_roles(unclear_role) for role in roles: self.positions.add(ico_name, ico_token, ico_url, role) if len(roles) == 1 and "UNCERTAIN" in roles: self.uncertain_positions.add(ico_name, ico_token, ico_url, unclear_role)
def degree_positions(self): # set center, than 4 squares in cardinal directions at interval of 5 degree angles if self.mode == 0: self.pos = Positions(self.config).get_degree_positions(self.depth) self.mode = 1 # get the center position square = self.make_square() square.setPos(Point3(self.pos.next())) #print 'first', square.getPos() else: try: for i in range(4): square = self.make_square() square.setPos(Point3(self.pos.next())) print square.getPos() except StopIteration: print 'done'
def test_visual_angle_positions(self): # make sure furthest out positions are plotted are at the correct visual angle # for this test, just test whatever is in the config file, and make sure it # is following whatever is there, regardless of if that is really correct (more # likely it is me sitting a foot or two away from the laptop, but not going to change # the view_dist and screen size since it doesn't really matter... max_x = self.config['MAX_DEGREES_X'] max_y = self.config['MAX_DEGREES_Y'] deg_per_pixel = visual_angle(self.config['SCREEN'], self.config['WIN_RES'], self.config['VIEW_DIST']) # # Key 9 should get you the max visual degrees for both x and y. Of course, it will # really be farther than the max visual angle, since we are maximizing both x and y, # but as long as the cardinal directions are the right visual angle, we understand the # corners are really further out, and will take this under consideration pos = Positions(self.config) pos_9 = pos.get_key_position(self.depth, key=9) #print pos_9 self.assertAlmostEqual(pos_9[0], max_x / deg_per_pixel[0], 4) self.assertAlmostEqual(pos_9[2], max_y / deg_per_pixel[1], 4)
def workerToString(self): print('Name: ', self.fullName) print('Position: ', Positions(self.position).name) if self.position == -1: print('Payment: ', f'{-0.0001}') else: print( 'Payment: ', f'{(self.position * self.position * self.position * self.position * self.position * self.position)+0.3}$' )
def main_function(): """ Body of main_function from where all necessary execution of the program starts """ try: print "Welcome to Casino...Try your Luck..." print print "*****************INSTRUCTIONS*********************" print "Please note that for the position values you can enter it in any format." print "Program will only catch correct input values from the entered string. In case of other cases appropriate error message will be thrown." print "**************************************************" string_of_pos = raw_input("please enter a list of positions : ") num_trials = raw_input("please enter a number of trials : ") Positions.ValidateInput(string_of_pos, num_trials) # to validate the input list_of_pos_pattern = "(-?\d+)" # pattern to fetch integer value list_of_pos = re.findall(list_of_pos_pattern, string_of_pos) # to find all positions from the user input list_of_pos_objects = [] for pos in list_of_pos: positions_obj = Positions(pos) # Instance creation of Interval class list_of_pos_objects.append(positions_obj) # appends the position objects in the list Positions.remove_old_files() # Remove all old output files # iterate over all position and perform all actions for each position for i in range(len(list_of_pos_objects)): list_of_pos_objects[i].grand_return(num_trials) list_of_pos_objects[i].calculate_statistics() list_of_pos_objects[i].write_in_output_file() list_of_pos_objects[i].plot_graphs() print print "You have your results now. It is obvious that you should go for the position for which you got maximum mean daily return and less standard deviation" print "apparently single investment of 1000 looks more profitable if you use to go to casino everyday." print print "Run the program again if you want to check for other positions...Thanks !!!" except KeyboardInterrupt: print "Program Interrupted...Plz run the program again !!!" except Position_Exception as exception: print "Error:", exception sys.exit()
def __init__(self): self._benchmark = None self._benchmark_history = None self._benchmark_return = None self._portfolio_history = None self._portfolio_return = None self._trading_days = None self._positions = Positions() self._auto_fill_positions() self._load_benchmark() if not os.path.isfile(HISTORY_IMG_FILE): self._draw_history_timeline() self._snapshot = Snapshot(self._benchmark, self._positions.get_current_position())
def test_non_random_list_pops(self): # make sure all positions are yielded. # number of positions total = self.config['X_POINTS'] * self.config['Y_POINTS'] count = 0 pos = Positions().get_position(self.depth) # generator object, will output until done for i in pos: #print i count += 1 #print self.pos.get_position(self.depth) #self.pos.get_position(self.depth) # Try to get another, should not work self.assertRaises(StopIteration, next, pos) self.assertEqual(count, total)
def test_random_list_pops(self): # make sure all positions are yielded. # number of positions pos = Positions().get_position(self.depth, True) total = self.config['X_POINTS'] * self.config[ 'Y_POINTS'] * self.config['POINT_REPEAT'] count = 0 #for i in range(self.config['X_LIMITS'] * self.config['X_LIMITS']): for i in pos: #print i count += 1 #print self.pos.get_position(self.depth) #self.pos.get_position(self.depth) # Try to get another, should not work self.assertRaises(StopIteration, next, pos) self.assertEqual(count, total)
def __init__(self, n, tf, **kwargs): quants = kwargs['quants'] # word sets preps = kwargs['preps'] nominals = kwargs['noms'] self.context = kwargs.get('context', 'phrase_atom') # set up variables needed for processing / storing P = Positions(n, self.context, tf).get quants = quants preps = preps self.P = P self.kids = {} self.explain = {} # set up evaluator with namespace as is # NB: Evaluator will rely on variables in # __init__, including P, quants, and preps self.conddict = Evaluator(locals()).conddict
def __init__(self, tf): ''' Input: instance of Text Fabric Output: a series of sets containing custom quantifier nodes ''' F = tf.api.F quants = set() quants |= set(F.ls.s('card')) & set(F.otype.s('word')) # -- contextual cases -- for w in F.otype.s('word'): P = Positions(w, 'phrase_atom', tf).get # -- custom lexemes-- custom = { 'KL/', 'M<V/', 'JTR/', 'M<FR/', 'XYJ/', '<FRWN/', 'C>R=/', 'MSPR/', 'RB/', 'RB=/', 'XMJCJT/' } if F.lex.v(w) in custom: quants.add(w) continue # -- the Hebrew idiom: בנ + quantifier for age -- conds = [ P(0, 'lex') == 'BN/', P(0, 'st') == 'c', P(0, 'nu') == 'sg', P(1, 'ls') == 'card', ] if all(conds): quants.add(w) continue self.quants = quants
def change_square_size(self): pos = None if self.mode == 0: self.config['MAX_DEGREES_X'] = 20 self.config['MAX_DEGREES_Y'] = 20 self.make_circle() pos = Positions(self.config).get_position(self.depth) self.mode = 1 res = [1024, 768] # Screen size screen = [1337, 991] v_dist = 1219 b = 0 scale = 1 size_list = [] for i, j in enumerate(pos): #b += 0.04 # covers all of the values if using 25 points #b += 0.08 b += 0.03 scale += 0.5 #print b #print i #print j square = self.make_square(scale) square.setPos(Point3(j)) #print square.getPos() #print square.getTightBounds() sq_min, sq_max = square.getTightBounds() size = sq_max - sq_min #print size[0], size[2] deg_per_pixel = visual_angle(screen, res, v_dist) #print deg_per_pixel print scale print 'size in degrees, x', size[0] * deg_per_pixel[0] print 'size in degrees, y', size[2] * deg_per_pixel[1] size_list.append(size[0] * deg_per_pixel[0]) print size_list import pickle pickle.dump(size_list, open('size_list', 'wb'))
class EventEmitter: handlers = {'pitch': [], 'K': []} positions = Positions() def emitter(self, event_code): if ord(event_code) in range(ord('B'), ord('Z')): return self.emit_pitch if event_code.isnumeric(): return self.emit_pickoff return { '>': self.emit_stealattempt, '.': self.emit_play_not_involving_batter, '*': self.emit_blocked_pitch, '+': self.emit_pickoff_throw_by_catcher }[event_code] def add_handler(self, event, handler): self.handlers[event].append(handler) def emit_pickoff_throw_by_catcher(self, pickoff, game_state): print('emitting pickoff throw by catcher'.format(pickoff)) def emit_blocked_pitch(self, blocked_pitch, game_state): print('emitting blocked pitch'.format(blocked_pitch)) def emit_play_not_involving_batter(self, play, game_state): print('emitting play not involving batter'.format(play)) def emit_stealattempt(self, steal_attempt, game_state): print('runner goes!') def emit_pickoff(self, pickoff, game_state): print('emitting pickoff: {}'.format(pickoff)) def emit_pitch(self, pitch, game_state): print('Here comes the pitch...') pitcher_index = '1' if game_state['inning'][0] == 'T' else '0' pitcher = game_state['players'][pitcher_index]['1'] for handler in self.handlers['pitch']: handler(pitch, pitcher, game_state) balls = int(game_state['count'].split('-')[0]) strikes = int(game_state['count'].split('-')[1]) if (pitch in 'SC'): strikes += 1 if (pitch == 'S'): print('Swung on and missed.') elif (pitch == 'C'): print('Called Strike.') elif (pitch in 'BIPV'): print('ball.') balls += 1 elif (pitch == 'F'): print('Fouled off.') if (strikes < 2): strikes += 1 elif (pitch == 'X'): print('Ball in play...') game_state['count'] = str(balls) + '-' + str(strikes) print('Count now {}'.format(game_state['count'])) def emit_advance(self, advance, game_state): print('emitting advance: {}'.format(advance)) print('runners state before advance: {}'.format(game_state['runners'])) if ('X' in advance): print('emitting out on advance') players = advance.split('X') assister = players[0] put_out = players[1] self.emit_out(game_state) else: start_base = advance.split('-')[0].strip() end_base = advance.split('-')[1].strip()[0:1] runner = game_state['runners'][start_base] game_state['runners'].pop(start_base) if (end_base == 'H'): self.emit_run(runner, game_state) else: game_state['runners'][end_base] = runner print('runners now: {}'.format(game_state['runners'])) def emit_modifier(self, modifier, game_state): print('emitting modifier: {}'.format(modifier)) def next_inning(self, game_state): inning = game_state['inning'] inning_number = inning[1:len(inning)] top_bottom = '' if (inning[0:1] == 'T'): game_state['inning'] = 'B' + inning_number top_bottom = 'bottom' else: game_state['inning'] = 'T' + str(int(inning_number) + 1) top_bottom = 'top' game_state['outs'] = 0 game_state['runners'] = {} print('----------------------') print('We move to the {} of the {}.'.format(top_bottom, game_state['inning'])) def emit_out(self, game_state): outs = int(game_state['outs']) outs += 1 game_state['outs'] = outs print('There are now {} outs.'.format(outs)) if (outs == 3): self.next_inning(game_state) def emit_run(self, scorer, game_state): print('A run scores. {} crosses the plate.'.format(scorer)) runs = game_state['score'].split('-') visitor_runs = int(runs[0]) home_runs = int(runs[1]) if (game_state['inning'].startswith('T')): visitor_runs += 1 else: home_runs += 1 score = '{}-{}'.format(visitor_runs, home_runs) game_state['score'] = score print('score is now: {}'.format(game_state['score'])) def emit_walk(self, play, game_state): print('Walked him.') game_state['runners']['1'] = game_state['batter'] def emit_hit_by_pitch(self, play, game_state): print('Hit by pitch.') game_state['runners']['1'] = game_state['batter'] def emit_strikeout(self, play, game_state): print('Struck him out.') pitcher = self.get_pitcher(game_state) self.emit_out(game_state) for handler in self.handlers['K']: handler(pitcher, game_state) def emit_stolen_base(self, play, game_state): stolen_base = play[2:3] next_base = int(stolen_base) prev_base = next_base - 1 runner = game_state['runners'][str(prev_base)] print('{} safe at {} with a stolen base.'.format(runner, stolen_base)) game_state['runners'][stolen_base] = runner game_state['runners'][str(prev_base)] = None def emit_pickoff(self, play, game_state): pickoff_play = play[2:len(play)] print('pickoff play: '.format(pickoff_play)) def emit_homerun(self, play, game_state): print('{} homers!'.format(game_state['batter'])) self.emit_run(game_state['batter'], game_state) def parse_outs(self, play, game_state): print('out on play: {}'.format(play)) #check for fielder's choice if play.startswith('FC'): pos = play[2:3] print('pos: {}'.format(pos)) print( 'batter reaches on a fielders choice. Out made by {}'.format( self.positions.get_player_and_position(pos, game_state))) else: pos = play[0:1] print('out on a play to {}'.format( self.positions.get_player_and_position(pos, game_state))) self.emit_out(game_state) def emit_play(self, play, game_state): if (play.startswith('SB')): self.emit_stolen_base(play, game_state) elif (play.startswith('S')): self.emit_single(play, game_state) elif (play.startswith('W')): self.emit_walk(play, game_state) elif (play.startswith('E')): print('{} reaches on an error by {}'.format( game_state['batter'], self.positions.get_player_and_position(play[1:2], game_state))) game_state['runners']['1'] = game_state['batter'] elif (play.startswith('C')): print('catchers interference. batter awarded first base') game_state['runners']['1'] = game_state['batter'] elif (play.startswith('DGR')): print('{} hits a ground rule double.'.format(game_state['batter'])) game_state['runners']['2'] = game_state['batter'] elif (play.startswith('DI')): print('Runner Advances from on defensive indifference') elif (play.startswith('D')): print('{} doubles to {}'.format( game_state['batter'], self.positions.get_player_and_position(play[1:2], game_state))) game_state['runners']['2'] = game_state['batter'] elif (play.startswith('T')): print('{} triples to {}'.format( game_state['batter'], self.positions.get_player_and_position(play[1:2], game_state))) game_state['runners']['3'] = game_state['batter'] elif (play.startswith('FC')): print('{} reaches on a fielders choice.'.format( game_state['batter'])) game_state['runners']['1'] = game_state['batter'] self.parse_outs(play, game_state) elif (play.startswith('HP')): self.emit_hit_by_pitch(play, game_state) elif (play.startswith('H')): self.emit_homerun(play, game_state) elif (play.startswith('IW')): game_state['runners']['1'] = game_state['batter'] elif (play.startswith('K')): self.emit_strikeout(play, game_state) elif (play.startswith('NP')): print('No play.') elif (play.startswith('OA')): print('Baserunning play.') elif (play.startswith('PB')): print('Passed ball.') elif (play.startswith('PO')): self.emit_pickoff(play, game_state) elif (play.startswith('BK')): print('Balk') else: self.parse_outs(play, game_state) def emit_batter(self, batter, game_state): game_state['batter'] = batter game_state['count'] = '0-0' game_state['runners']['B'] = batter print(game_state) print('batter is now: {}'.format(batter)) def get_pitcher(self, game_state): if game_state['inning'].startswith('T'): return game_state['players']['1']['1'] return game_state['players']['0']['1'] def emit_single(self, play, game_state): print('{} singles to {}.'.format( game_state['batter'], self.positions.get_player_and_position(play[1:2], game_state))) game_state['runners']['1'] = game_state['batter'] def emit_events(self, event_data, game_state): self.emit_batter(event_data[3], game_state) pitches = event_data[5] for pitch in pitches: self.emitter(pitch)(pitch, game_state) play = event_data[6] desc = play.split('/')[0] plays_modifiers_and_advances = play.split('.') plays_and_modifiers = plays_modifiers_and_advances[0].split('/') if len(plays_modifiers_and_advances) > 1: advances = plays_modifiers_and_advances[1].split(';') if (len(plays_and_modifiers) > 1): modifiers = plays_and_modifiers[1].split('/') for modifier in modifiers: self.emit_modifier(modifier.strip(), game_state) for advance in advances: self.emit_advance(advance, game_state) self.emit_play(desc, game_state)
class Portfolio: configuration: Dictionary memory = None initial_budget = 0. budget = 0. latest_price: float = 0. forecast: float = 0. konkorde = 0. failed_actions = ['f.buy', 'f.sell'] # These are the variables that MUST be saved by the `dump()` method # in `environment`, in order to be able to resume the state. state_variables = [ 'initial_budget', 'budget', 'latest_price', 'forecast', 'cost', 'portfolio_value', 'profit', 'shares', 'konkorde' ] def __init__(self, configuration, initial_price, forecast, env_memory): self.params = configuration self.display = self.params.display self.log = self.params.log self.initial_budget = scale(self.params.initial_budget, 0., self.params.fcast_file.max_support) self.positions = Positions(configuration, self.initial_budget) self.reset(initial_price, forecast, env_memory) def reset(self, initial_price, forecast, env_memory): """ Initializes portfolio to the initial state. """ self.budget = self.initial_budget self.latest_price = initial_price self.forecast = forecast self.memory = env_memory self.konkorde = 0. self.positions.reset() self.log.debug('Portfolio reset. Initial budget: {:.1f}'.format( self.initial_budget)) def wait(self): """ WAIT Operation """ action_name = 'wait' rw = reward.decide(action_name, self.positions) msg = ' WAIT: ' + \ 'prc({:.2f})|bdg({:.2f})|val({:.2f})|prf({:.2f})|cost({:.2f})' self.log.debug( msg.format(self.latest_price, self.budget, self.positions.value(), self.positions.profit(), self.positions.cost())) return action_name, rw def buy(self, num_shares: float = 1.0) -> object: """ BUY Operation :param num_shares: number of shares. Default to 1. :return: The action executed and the reward obtained by the operation. """ action_name = 'buy' buy_price = num_shares * self.latest_price if buy_price > self.budget: action_name = 'f.buy' self.log.debug(' FAILED buy') rw = reward.failed() else: rw = reward.decide(action_name, self.positions) self.budget -= self.positions.buy(num_shares, self.latest_price, self.params.mode) # self.update_after_buy(action_name, num_shares, buy_price) return action_name, rw def sell(self, num_shares=1.0): """ SELL Operation :param num_shares: number of shares. Default to 1. :return: The action executed and the reward obtained by the operation. """ action_name = 'sell' if num_shares > self.positions.num_shares(): action_name = 'f.sell' self.log.debug(' FAILED sell') rw = reward.failed() else: rw = reward.decide(action_name, self.positions) income, profit = self.positions.sell(num_shares, self.latest_price) self.budget += (income + profit) self.log.debug(' Sell op -> income:{:.2f}, profit:{:.2f}'.format( income, profit)) self.log.debug(' Budget -> {:.2f} + {:.2f}'.format( self.budget, (income + profit))) return action_name, rw def update(self, price, forecast, konkorde=None): """ Updates portfolio after an iteration step. :param price: new price registered :param forecast: new forecast registered :param konkorde: the konkorde value (computed from green & blue read the data file, if applicable) :return: the portfolio object """ self.latest_price = price self.forecast = forecast if konkorde is not None: self.konkorde = konkorde self.positions.update(self.latest_price) # self.portfolio_value = self.num_shares * self.latest_price self.log.debug(' Updating portfolio after STEP.') msg = ' > portfolio_value={:.2f}, latest_price={:.2f}, forecast={:.2f}' self.log.debug( msg.format(self.positions.value(), self.latest_price, self.forecast)) self.positions.debug() return self def values_to_record(self): cost = self.positions.cost() profit = self.positions.profit() values = [ self.latest_price, self.forecast, self.budget, cost, self.positions.value(), profit, self.budget + cost + profit, self.positions.num_shares() ] if self.params.have_konkorde: values += [self.konkorde] values += ['', 0., 0., ''] return values def failed_action(self, action, price): """ Determines if the action can be done or will be a failed operation """ if action == self.params.action.index('buy'): if price > self.budget: return True else: return False elif action == self.params.action.index('sell'): if self.positions.num_shares() == 0.: return True else: return False else: return False @property def gain(self): return self.positions.profit() > 0 @property def last_gain(self): return self.memory.last('profit') > 0. @property def prev_last_gain(self): return self.memory.prevlast('profit') > 0. @property def have_shares(self): return self.positions.num_shares() > 0 @property def can_buy(self) -> bool: return self.budget >= self.latest_price @property def can_sell(self) -> bool: return self.positions.num_shares() > 0. @property def prediction_upward(self): msg = ' Pred sign ({}) latest price({:.2f}) vs. last_forecast({:.2f})' self.log.debug( msg.format('↑' if self.latest_price <= self.forecast else '↓', self.latest_price, self.forecast)) return self.latest_price <= self.forecast @property def last_forecast(self): self.log.debug(' Last forecast in MEM = {:.2f}'.format( self.memory.last('forecast'))) return self.memory.last('forecast') @property def last_price(self): # self.log.debug( # ' Last price in MEM = {:.2f}'.format(self.memory.last('price'))) return self.memory.last('price') @property def prevlast_forecast(self): # self.log.debug( # ' PrevLast forecast in MEM = {:.2f}'.format( # self.memory.prevlast('forecast'))) return self.memory.prevlast('forecast') @property def prevlast_price(self): # self.log.debug( # ' PrevLast price in MEM = {:.2f}'.format( # self.memory.prevlast('price'))) return self.memory.prevlast('price') @property def prevprevlast_forecast(self): # self.log.debug( # ' PrevPrevLast forecast in MEM = {:.2f}'.format( # self.memory.prevprevlast('forecast'))) return self.memory.prevprevlast('forecast') @property def prevprevlast_price(self): # self.log.debug( # ' PrevPrevLast price in MEM = {:.2f}'.format( # self.memory.prevprevlast('price'))) return self.memory.prevprevlast('price')
def init_pos(mode='bull'): my_positions = Positions(None) my_positions.buy(0.7, 100, mode=mode) my_positions.buy(0.1, 90, mode=mode) return my_positions
def __init__(self, tf): F, L = tf.api.F, tf.api.L self.preps = set(w for w in F.otype.s('word') if F.pdp.v(w) == 'prep') # -- ETCBC "potential preps" -- # דרך is excluded since this is speculative self.preps |= set(w for w in F.otype.s('word') if F.ls.v(w) == 'ppre' and F.lex.v(w) != 'DRK/') # -- context-specific prepositions -- # prepare manually annotated contexts # - ראשׁ with open('../annotations/rosh_constructs.csv', 'r') as infile: rosh_annotes = list(csv.reader(infile))[1:] rosh_kids = [row[-2] for row in rosh_annotes if row[-1] == 'y'] # begin word loop for w in F.otype.s('word'): # skip unnecessary pos if F.sp.v(w) not in {'prep', 'subs', 'adjv', 'advb'}: continue P = Positions(w, 'phrase_atom', tf).get # Set up potential construct position # NB! still requires a check for construct state construct = (P(1) if P(1, 'sp') != 'art' else None or P(2) if P(1, 'sp') == 'art' else None) # -- lexemes that must be preceded by another prep -- # These sets could benefit from further investigation preprep = {'PNH/', 'TWK/', 'QY/', 'QYH=/', 'QYT/', '<WD/'} conds = [ P(0, 'lex') in preprep, P(0, 'prs') == 'absent', (P(-1, 'pdp') == 'prep' or P(-1, 'ls') == 'ppre' or P(-1, 'lex') == 'KL/'), P(1, 'lex') != 'W' ] if all(conds): self.preps.add(w) continue # -- בד "alone" when preceded by ל, with a meaning of "except" -- elif (F.lex.v(w) == 'BD/' and P(-1, 'lex') == 'L'): self.preps.add(w) continue # -- cases of אחרית -- ''' Some are prep and some are substantival. e.g. subs. אחרית רשׁעים "end of evil doers" (Ps 37:38) others are used prepositionally to indicate position the semantics of the components are important for determining which sense is employed. All cases in Time function phrases appear prepositional. Cases with animate nouns appear to be substantival; those cases can be manually excluded with a lexeme exclusion. NB: גים in Jer 50:12 is used non-personally and thus not excluded Excluded: איוב and רשעים ''' conds = [ P(0, 'lex') == '>XRJT/', P(0, 'lex') == 'c', F.lex.v(construct) not in {'>JWB/', 'RC</'} ] if all(conds): self.preps.add(w) continue # -- prepositional ראשׁ -- ''' רֹאשׁ "head" is a word seems to become prepositional when attached to inanimate nouns. However, BHSA currently has no way of separating animate and inanimate nouns. This is a case where my current research on noun embeddings could soon provide the necessary data. The method applied there distinguishes animate from inanimate nouns with fairly good success. Eventually it could be possible to identify prepositions like ראשׁ by searching for words in construct to it with an animacy rating below a given threshold. However, since the embeddings do not yet account for various word senses, more work is needed before more reliable results can be procured. For now, this case is tagged as one which in the near future might be improved with empirical semantic data. The possibility of automatically distinguishing prepositional cases of ראשׁ also opens the possibility for other similar body part prepositional uses such as פֶּה "mouth", יָד "hand", שָׂפָה "lip", and potentially others. For now, a brute force method is applied which filters cases out by testing validity of the lexeme subservient to ראשׁ. The lexemes have been manually selected by examining a set of noun lexemes in construct to ראשׁ and by double checking the context. The process is accomplished through a simple manual annotation. A spreadsheet has been exported and hand annotated. The results are drawn in and applied to ראשׁ. ''' conds = [ P(0, 'lex') == 'R>C/', P(0, 'st') == 'c', P(-1, 'pdp') == 'prep', (F.lex.v(construct) in rosh_kids or P(1, 'ls') == 'card') ] if all(conds): self.preps.add(w) continue # ETSEM (time phrase) conds = [ P(0, 'lex') == '<YM/', P(0, 'st') == 'c', F.function.v(L.u(w, 'phrase')[0]) == 'Time' ] if all(conds): self.preps.add(w) continue
app = Flask(__name__) # The handler classes for each route type about = About() help = Help() events = Events() index = Index() inventory = Inventory() people = People() requests_ = Requests_() robohash = Robohash() test = Test() vms = VMs() presentations = Presentations() positions = Positions() # parsed config from config.ini config = globals.config # Two helper functions to save typing def encode_id(id): id = globals.base58_hashids.encode(id) if id == None: return None return id def decode_id(id): id = globals.base58_hashids.decode(id) if id == None: return None
class World(DirectObject): def __init__(self): # Program just to demonstrate where we are putting the positions for calibration # Unlike the actual calibration routine, can see all of the squares at once DirectObject.__init__(self) #ShowBase.__init__(self) self.base = ShowBase() #print self.base.win.getRejectedProperties() self.config = {} #execfile('config_test.py', self.config) execfile('config.py', self.config) resolution = self.config['WIN_RES'] if not resolution or resolution == 'Test': #print 'test' # assume testing, small window resolution = (800, 600) print resolution wp = WindowProperties() wp.setSize(int(resolution[0]), int(resolution[1])) wp.setOrigin(0, 0) wp.setUndecorated(True) self.base.win.requestProperties(wp) # depth completely doesn't matter for this, since just 2d, and no layers #self.depth = 55 self.depth = 0 self.base.setBackgroundColor(115/255, 115/255, 115/255) # set up a 2d camera camera = self.base.camList[0] lens = OrthographicLens() #print 'xwin', self.base.win.getProperties().getXSize() lens.setFilmSize(int(resolution[0]), int(resolution[1])) lens.setNearFar(-100, 100) camera.node().setLens(lens) # reparent it to pixel2d, so renders in pixel coordinates camera.reparentTo(self.base.render) #print 'xwin2', self.base.win.getXSize() #print self.base.win.getYSize() #print camera.ls() self.accept("escape", sys.exit) self.accept('space', self.next) self.accept('a', self.all) self.accept('d', self.degree_positions) self.accept('s', self.change_square_size) self.mode = 0 self.pos = [] #self.root = self.base.render.attachNewNode("Root") self.make_circle() def next(self): #print 'xwin', self.base.win.getProperties().getXSize() if self.mode == 0: self.pos = Positions(self.config).get_position(self.depth, 'small') self.mode = 1 square = self.make_square() try: square.setPos(Point3(self.pos.next())) print square.getPos() except StopIteration: print 'done' #square.setColor(175 / 255, 175 / 255, (i * 7) / 255, 1.0) #print square.getColor() def all(self): pos = None if self.mode == 0: self.make_circle() pos = Positions(self.config).get_position(self.depth) self.mode = 1 #print pos #for i, j in enumerate(pos): while True: try: position = pos.next() except StopIteration: break square = self.make_square() square.setPos(Point3(position)) #print square.getPos() #print square.getTightBounds() #sq_min, sq_max = square.getTightBounds() #size = sq_max - sq_min #print size[0], size[2] def change_square_size(self): pos = None if self.mode == 0: self.config['MAX_DEGREES_X'] = 20 self.config['MAX_DEGREES_Y'] = 20 self.make_circle() pos = Positions(self.config).get_position(self.depth) self.mode = 1 res = [1024, 768] # Screen size screen = [1337, 991] v_dist = 1219 b = 0 scale = 1 size_list = [] for i, j in enumerate(pos): #b += 0.04 # covers all of the values if using 25 points #b += 0.08 b += 0.03 scale += 0.5 #print b #print i #print j square = self.make_square(scale) square.setPos(Point3(j)) #print square.getPos() #print square.getTightBounds() sq_min, sq_max = square.getTightBounds() size = sq_max - sq_min #print size[0], size[2] deg_per_pixel = visual_angle(screen, res, v_dist) #print deg_per_pixel print scale print 'size in degrees, x', size[0] * deg_per_pixel[0] print 'size in degrees, y', size[2] * deg_per_pixel[1] size_list.append(size[0] * deg_per_pixel[0]) print size_list import pickle pickle.dump(size_list, open('size_list', 'wb')) def degree_positions(self): # set center, than 4 squares in cardinal directions at interval of 5 degree angles if self.mode == 0: self.pos = Positions(self.config).get_degree_positions(self.depth) self.mode = 1 # get the center position square = self.make_square() square.setPos(Point3(self.pos.next())) #print 'first', square.getPos() else: try: for i in range(4): square = self.make_square() square.setPos(Point3(self.pos.next())) print square.getPos() except StopIteration: print 'done' def make_square(self, scale=None): square = self.base.loader.loadModel("models/plane") square.reparentTo(self.base.render) #square.ls() #square.setScale(0.05) if scale: square.setScale(scale) else: square.setScale(8.5) square.setDepthTest(False) square.setTransparency(1) square.setTexture(self.base.loader.loadTexture("textures/calibration_square.png"), 1) # gray #square.setColor(150 / 255, 150 / 255, 150 / 255, 1.0) # yellow #square.setColor(175 / 255, 175 / 255, 130 / 255, 1.0) square.setColor(0.9, 0.9, 0.6, 1.0) #print square.getX() #print square.getY() #sq_min, sq_max = square.getTightBounds() #size = sq_max - sq_min #print size[0], size[2] return square def make_circle(self, angle_deg=360): ls = LineSegs() angle_radians = np.deg2rad(angle_deg) # assume visual angle is approximately the same for x and y, # which probably is not true, maybe need to change #radius = 1 * Positions().visual_angle()[0] res = [1024, 768] # Screen size screen = [1337, 991] v_dist = 1219 # number of visual angles want circle radius to be # (so twice this is the x and y of the square) angle = 0.25 # visual angle returns degrees per pixel, so invert since # we want pixel per degree deg_per_pixel = visual_angle(screen, res, v_dist) x_radius = angle * 1 / deg_per_pixel[0] y_radius = angle * 1 / deg_per_pixel[0] for i in range(50): a = angle_radians * i / 49 y = y_radius * np.sin(a) #print y x = x_radius * np.cos(a) #print x ls.drawTo(x, self.depth, y) #node = ls.create() node = self.base.render.attachNewNode(ls.create(True)) return NodePath(node)
class Square(object): def __init__(self, config, key_map, base): self.key_map = key_map self.base = base # self.depth needs to be more than zero for stuff to show up, # otherwise arbitrary. This is used for positioning squares (Z) self.depth = 55 self.pos = None self.manual = None # scale 17 is one visual angle, linear so just multiply by 17 self.square = self.create_square(config['SQUARE_SCALE'] * 17) # print 'scale', config['SQUARE_SCALE']*17 def create_square(self, scale): # setting up square object obj = self.base.loader.loadModel("models/plane") # don't turn on yet # make depth greater than eye positions so eye positions are on top of squares # initial position of Square obj.setPos(Point3(0, self.depth, 0)) # Set initial position # need to scale to be correct visual angle # obj.setScale(1) obj.setScale(scale) # obj.setTransparency(1) square = self.base.loader.loadTexture( "textures/calibration_square.png") obj.setTexture(square, 1) # starting color, should be set by model, but let's make sure obj.setColor(150 / 255, 150 / 255, 150 / 255, 1.0) return obj def setup_positions(self, config, manual): # If doing manual, need to initiate Positions differently than if random, # so key presses work properly self.manual = manual if self.manual: del self.pos # print 'manual positions' self.pos = Positions(config) else: del self.pos # print 'auto positions' self.pos = Positions(config).get_position(self.depth, True) # Square methods def turn_on(self): # print 'square on' # make sure in correct color self.square.setColor(150 / 255, 150 / 255, 150 / 255, 1.0) # and render self.square.reparentTo(self.base.render) def fade(self): # print 'square fade' self.square.setColor(0.9, 0.9, 0.6, 1.0) def turn_off(self): # print 'square off' self.square.clearColor() self.square.detachNode() def move_for_manual_position(self): # used for manual move, called from sequences # if a key was pressed, use that for next position if self.key_map["switch"]: # print 'manual move' # print('switch', self.key_map["switch"]) self.move( self.pos.get_key_position(self.depth, self.key_map["switch"])) self.key_map["switch"] = 0 # remove the switch flag else: # default is the center, which is key 5 self.move(self.pos.get_key_position(self.depth, 5)) def move(self, position=None): # print 'square move' # print 'square position', position if not position: # print 'trying to get a auto position' try: position = self.pos.next() # print position except StopIteration: # print('stop iterating!') messenger.send("s") # Switch to manual and wait # need to set a position position = (0, self.depth, 0) # self.close() # print position self.square.setPos(Point3(position))
class Terminal(object): """ 用于和前端交互的数据终端,可用于交互的方法和属性有: - update_position(pos_string): 接收前端的持仓字符串,刷新position和snapshot,仅在交易日09:30-15:00有效 - save(): 保存最新的仓位,仅在交易日15:00后有效 - reload_snapshot: 刷新snapshot,返回刷新后的overall_info和detail_info - snapshot_overall_info: 最新的overall_info - snapshot_detail_info: 最新的detail_info - latest_position_string: 最新的position的简单字符串形式,以供修改 """ def __init__(self): self._benchmark = None self._benchmark_history = None self._benchmark_return = None self._portfolio_history = None self._portfolio_return = None self._trading_days = None self._positions = Positions() self._auto_fill_positions() self._load_benchmark() if not os.path.isfile(HISTORY_IMG_FILE): self._draw_history_timeline() self._snapshot = Snapshot(self._benchmark, self._positions.get_current_position()) def _auto_fill_positions(self): now = datetime.now() today = now.strftime("%Y-%m-%d") yesterday = get_trading_days_relatively(today, -1)[0] trading_days_raw = self._positions._trading_days latest_valid_date = trading_days_raw[-1] latest_position = self._positions.get_position(latest_valid_date) trading_days_new = get_trading_days(latest_valid_date, yesterday)[1:] self._trading_days = trading_days_raw + trading_days_new if today in TRADING_DAYS_DICT: self._positions.set_current_info(today, deepcopy(latest_position)) else: self._positions.set_current_info(yesterday, deepcopy(latest_position)) if trading_days_new: logger.info("Filling positions data of {} through scraper, referring position at {}...".format(trading_days_new, latest_valid_date)) for date in trading_days_new: temp_pos = deepcopy(latest_position) universe = temp_pos['securities'].keys() data = load_crossectional_close_prices(universe, date) value = temp_pos['cash'] for sec, p in data.iteritems(): temp_pos['securities'][sec]['price'] = p value += p * temp_pos['securities'][sec]['amount'] temp_pos['value'] = value self._positions.set_info(date, temp_pos, is_new_date=True) logger.info("Successfully filled positions data!") self._positions.save_all() logger.info("Latest positions data saved at /lib/posdb/.") self._portfolio_history = self._positions.history_values v0 = self._portfolio_history[0] self._portfolio_return = [v/v0 - 1 for v in self._portfolio_history] def _load_benchmark(self): logger.info("Loading benchmark data file...") config = json.load(file(CONFIG_FILE)) benchmark = config["benchmark"] start = self._trading_days[0] end = self._trading_days[-1] redraw = False try: benchmark_info = json.load(file(BENCHMARK_CACHE_FILE)) assert benchmark_info['sec_id'] == benchmark assert benchmark_info['start'] == start assert benchmark_info['end'] == end logger.info("Successfully loaded benchmark data file!") except: redraw = True logger.info("Benchmark data file is outdated. Downloading benchmark data ({}) from {} to {} through scraper...".format(benchmark, start, end)) data = load_daily_close_prices(universe=[benchmark], start=start, end=end) assert len(data[benchmark]) == len(self._trading_days) logger.info("Successfully downloaded benchmark data!") benchmark_info = { "sec_id": benchmark, "start": start, "end": end, "data": data[benchmark], } f = open(BENCHMARK_CACHE_FILE, 'w') f.write(json.dumps(benchmark_info, sort_keys=True, indent=4)) f.close() logger.info("Benchmark data saved at ./static/temp/benchmark.json.") self._benchmark = benchmark self._benchmark_history = benchmark_info['data'] assert len(self._benchmark_history) == len(self._portfolio_history) v0 = self._benchmark_history[0] self._benchmark_return = [v/v0 - 1 for v in self._benchmark_history] if redraw: self._draw_history_timeline() def _draw_history_timeline(self): fig = Figure(figsize=(7, 3)) canvas = FigureCanvas(fig) ax_ret = fig.add_subplot(121, axisbg='white') ax_val = fig.add_subplot(122, axisbg='white') d = len(self._trading_days) xseries = range(d) xlabels = [t[-5:] for t in self._trading_days] pct = lambda x, _: '{0:1.1f}%'.format(100 * x) if d > 5: tseries = xseries[::d//5+1] + xseries[-1:] tlabels = xlabels[::d//5+1] + xlabels[-1:] # draw return lines ax_ret.clear() ax_ret.plot(xseries, self._portfolio_return, label='portfolio', linewidth=1.0, color='r') ax_ret.plot(xseries, self._benchmark_return, label='benchmark', linewidth=1.0, color='b') ax_ret.yaxis.set_major_formatter(FuncFormatter(pct)) for item in ax_ret.get_yticklabels(): item.set_size(9) ax_ret.set_xlim(0, d-1) ax_ret.set_xticks(tseries) ax_ret.set_xticklabels(tlabels, fontsize=9) ax_ret.set_title('Cumulative Return', fontsize=10) ax_ret.grid(True) ax_ret.legend(loc=2, prop={'size': 8}) # draw value line ax_val.clear() ax_val.plot(xseries, self._portfolio_history, label='portfolio', linewidth=1.0, color='r') for item in ax_val.get_yticklabels(): item.set_size(9) ax_val.set_xlim(0, d-1) ax_val.set_xticks(tseries) ax_val.set_xticklabels(tlabels, fontsize=9) ax_val.set_title('Portfolio Value', fontsize=10) ax_val.grid(True) fig.tight_layout() fig.savefig(HISTORY_IMG_FILE) logger.info("History image saved at ./static/temp/history.") def update_position(self, pos_string): new_position = self._parse_new_pos_string(pos_string) now = datetime.now() today = now.strftime("%Y-%m-%d") minute = now.strftime("%H:%M") if today in TRADING_DAYS_DICT and "09:30" <= minute <= "15:00": self._snapshot.update_position(new_position) self._positions.set_current_info(today, self._snapshot.latest_position()) def _parse_new_pos_string(self, pos_string): pos_info = [r.strip() for r in pos_string.strip().split("\n")] pos_dict = {} pos_dict["cash"] = float(pos_info[0]) pos_dict["securities"] = {} pos_dict["value"] = 0.0 for r in pos_info[1:]: sec, amount = r.split("|") sec += ".XSHG" if sec[0] == "6" else ".XSHE" pos_dict["securities"][sec] = { "amount": float(amount), "price": 0.0, "name": None, } short_names = load_sec_shortname(pos_dict["securities"].keys()) for sec, name in short_names.iteritems(): pos_dict["securities"][sec]["name"] = name return pos_dict @property def save(self): now = datetime.now() today = now.strftime("%Y-%m-%d") minute = now.strftime("%H:%M") if today in TRADING_DAYS_DICT and minute > "15:00": self._snapshot.save() self._positions.set_current_info(today, self._snapshot.latest_position()) self._positions.save_current_position() return "" @property def reload_snapshot(self): now = datetime.now() self._today = now.strftime("%Y-%m-%d") self._yesterday = get_trading_days_relatively(self._today, -1) self._minute = now.strftime("%H:%M") self._is_trading_day = self._today in TRADING_DAYS_DICT self._snapshot.refresh() return { "snapshot_overall_info": self.snapshot_overall_info, "snapshot_detail_info": self.snapshot_detail_info } @property def snapshot_overall_info(self): return self._snapshot.latest_overall_info_in_html() @property def snapshot_detail_info(self): return self._snapshot.latest_securities_details_in_html() @property def latest_position_string(self): return self._snapshot.latest_position_in_simple_string()
class Square(object): def __init__(self, config, key_map, base): self.key_map = key_map self.base = base # self.depth needs to be more than zero for stuff to show up, # otherwise arbitrary. This is used for positioning squares (Z) self.depth = 55 self.pos = None self.manual = None # scale 17 is one visual angle, linear so just multiply by 17 self.square = self.create_square(config['SQUARE_SCALE']*17) # print 'scale', config['SQUARE_SCALE']*17 def create_square(self, scale): # setting up square object obj = self.base.loader.loadModel("models/plane") # don't turn on yet # make depth greater than eye positions so eye positions are on top of squares # initial position of Square obj.setPos(Point3(0, self.depth, 0)) # Set initial position # need to scale to be correct visual angle # obj.setScale(1) obj.setScale(scale) # obj.setTransparency(1) square = self.base.loader.loadTexture("textures/calibration_square.png") obj.setTexture(square, 1) # starting color, should be set by model, but let's make sure obj.setColor(150 / 255, 150 / 255, 150 / 255, 1.0) return obj def setup_positions(self, config, manual): # If doing manual, need to initiate Positions differently than if random, # so key presses work properly self.manual = manual if self.manual: del self.pos # print 'manual positions' self.pos = Positions(config) else: del self.pos # print 'auto positions' self.pos = Positions(config).get_position(self.depth, True) # Square methods def turn_on(self): # print 'square on' # make sure in correct color self.square.setColor(150 / 255, 150 / 255, 150 / 255, 1.0) # and render self.square.reparentTo(self.base.render) def fade(self): # print 'square fade' self.square.setColor(0.9, 0.9, 0.6, 1.0) def turn_off(self): # print 'square off' self.square.clearColor() self.square.detachNode() def move_for_manual_position(self): # used for manual move, called from sequences # if a key was pressed, use that for next position if self.key_map["switch"]: # print 'manual move' # print('switch', self.key_map["switch"]) self.move(self.pos.get_key_position(self.depth, self.key_map["switch"])) self.key_map["switch"] = 0 # remove the switch flag else: # default is the center, which is key 5 self.move(self.pos.get_key_position(self.depth, 5)) def move(self, position=None): # print 'square move' # print 'square position', position if not position: # print 'trying to get a auto position' try: position = self.pos.next() # print position except StopIteration: # print('stop iterating!') messenger.send("s") # Switch to manual and wait # need to set a position position = (0, self.depth, 0) # self.close() # print position self.square.setPos(Point3(position))
class Person: def __init__(self, person_name, person_socials, ico_name, ico_token, ico_url, unclear_role): self.name = person_name self.socials = Social(person_socials) self.positions = Positions() self.uncertain_positions = Positions() roles = Role.detect_roles(unclear_role) for role in roles: self.positions.add(ico_name, ico_token, ico_url, role) if len(roles) == 1 and "UNCERTAIN" in roles: self.uncertain_positions.add(ico_name, ico_token, ico_url, unclear_role) @staticmethod def find_duplicate(people, person_name, person_socials): for person in people: name_match = distance(person.name, person_name) < MIN_DISTANCE if name_match: social_match = Social.match(person.socials.get_socials(), Social.normalize(person_socials)) if social_match: return people.index(person) return None def update(self, person_socials, ico_name, ico_token, ico_url, unclear_role): self.socials.update(person_socials) roles = Role.detect_roles(unclear_role) for role in roles: self.positions.add(ico_name, ico_token, ico_url, role) if len(roles) == 1 and "UNCERTAIN" in roles: self.uncertain_positions.add(ico_name, ico_token, ico_url, unclear_role) def roles_check(self): self.positions.roles_check() def get_count_roles(self): return self.positions.get_count_roles() def get_count_people_by_role_name(self): return self.positions.get_count_people_by_role_name() def get_data(self): data = dict() data["name"] = self.name data["socials"] = list(self.socials.get_socials()) data["positions"] = self.positions.get_data() return data def has_uncertain_roles(self): return not self.uncertain_positions.is_empty() def get_data_uncertain_roles(self): data = dict() data["name"] = self.name data["socials"] = list(self.socials.get_socials()) data["positions"] = self.uncertain_positions.get_data() return data
def update(self): self.latest_input_image = self._img_provider.get_pil_image() map_box = Positions.get("cam_minimap_ul") + Positions.get( "cam_minimap_lr") self.minimap.update(self.latest_input_image.crop(map_box))