def test_dotted_get(self): value = "foo" data = {"color": {"blue": value}} dotted = DottedDict(data) self.assertEqual(dotted.get("color").get("blue"), value)
def __init__(self): super(BlockTwoHit, self).__init__() self.block_states.update({ 1: DottedDict({'color': 7}), 2: DottedDict({'color': 6}) }) self.current_state = 2
def __init__(self): super(BlockInvisible, self).__init__() self.block_states.update({ 1: DottedDict({'color': 7}), 2: DottedDict({'color': 6}), 3: DottedDict({'color': 1}), }) self.current_state = 3
def test_not_valid_identifier(self): dotted = DottedDict({"foo-bar": 1, ".foo": 1, "foo baz": 1, 1: 2}) self.assertTrue(dotted.foo_bar, 1) self.assertTrue(dotted._foo, 1) self.assertTrue(dotted.foo_baz, 1) self.assertTrue(dotted._1, 2) # Reserved keyword with self.assertRaises(ValueError): DottedDict({"lambda": 1})
def __init__(self): super(BlockExplosive, self).__init__() self.block_states.update({ 1: DottedDict({'color': 2}), 2: DottedDict({'color': 4}) }) self.current_state = 1 self.is_animated = True self.last_update = 0 self.frame_duration = 8
def main(): parser = argparse.ArgumentParser( description='Simple Bugzilla triage helper bot for Slack.') parser.add_argument('-c', '--config', metavar='FILE', default='~/.triagebot', help='config file') parser.add_argument('-d', '--database', metavar='FILE', default='~/.triagebot-db', help='database file') args = parser.parse_args() # Read config with open(os.path.expanduser(args.config)) as fh: config = DottedDict(yaml.safe_load(fh)) config.database = os.path.expanduser(args.database) env_map = (('TRIAGEBOT_SLACK_APP_TOKEN', 'slack-app-token'), ('TRIAGEBOT_SLACK_TOKEN', 'slack-token'), ('TRIAGEBOT_BUGZILLA_KEY', 'bugzilla-key')) for env, config_key in env_map: v = os.environ.get(env) if v: setattr(config, config_key, v) # Connect to services client = WebClient(token=config.slack_token) # store our user ID config.bot_id = client.auth_test()['user_id'] bzapi = bugzilla.Bugzilla(config.bugzilla, api_key=config.bugzilla_key, force_rest=True) if not bzapi.logged_in: raise Exception('Did not authenticate') db = Database(config) # Start socket-mode listener in the background socket_client = SocketModeClient( app_token=config.slack_app_token, web_client=WebClient(token=config.slack_token)) socket_client.socket_mode_request_listeners.append( lambda socket_client, req: process_event(config, socket_client, req)) socket_client.connect() # Run scheduler Scheduler(config, client, bzapi, db).run()
def process_event(config, socket_client, req): '''Handler for a Slack event.''' payload = DottedDict(req.payload) if req.type == 'slash_commands': # Don't even acknowledge events in forbidden channels, to avoid # interfering with separate bot instances in other channels. if payload.channel_id in config.get('channels_deny', []): return if config.get('channels_allow' ) and payload.channel_id not in config.channels_allow: return # Acknowledge the event, as required by Slack. resp = SocketModeResponse(envelope_id=req.envelope_id) socket_client.send_socket_mode_response(resp) # Idempotency with Database(config) as db: if not db.add_event(payload.channel_id, payload.trigger_id): # When we ignore some events, Slack can send us duplicate # retries. Detect and ignore those after acknowledging. return # Process it CommandHandler(config, payload)() else: raise Fail(f'Unexpected event type "{req.type}"')
def __init__(self, low_latency, locator, account_id, json_config): pywingchun.Trader.__init__(self, low_latency, locator, "sim", account_id) config = json.loads(json_config) self.match_mode = config.get("match_mode", MatchMode.Custom) self.ctx = DottedDict() self.ctx.orders = {} if self.match_mode == MatchMode.Custom: path = config.get("path") simulator_dir = os.path.dirname(path) name_no_ext = os.path.split(os.path.basename(path)) sys.path.append(os.path.relpath(simulator_dir)) impl = importlib.import_module(os.path.splitext(name_no_ext[1])[0]) self.ctx.insert_order = getattr(impl, 'insert_order', lambda ctx, event: False) self.ctx.cancel_order = getattr(impl, "cancel_order", lambda ctx, event: False) self.ctx.req_account = getattr(impl, "req_account", lambda ctx: False) self.ctx.req_position = getattr(impl, "req_position", lambda ctx: False)
def simple_trial(): i = Innovator() r = Random() config = { "MUTATION_RATE": 0.0, "CONNECTION_MUTATION_RATE": 0.0, "NODE_MUTATION_RATE": 0.0, "DISABLED_GENE_INHERITING_CHANCE": 1.0, } config = DottedDict(config) nodes = 4 to_remove = 2 g1 = generate_complete_genome(1, nodes, r, i) g2 = generate_complete_genome(2, nodes, r, i) g1.fitness = 10.0 g2.fitness = 0.0 for key in r.sample(g1.connection_genes.keys(), to_remove): del g1.connection_genes[key] for key in r.sample(g2.connection_genes.keys(), to_remove): del g2.connection_genes[key] gc = Genome.generate_offspring(g1, 3, r, [TestNode], i, config, genomeB=g2) g1.vizualize_genome(1, "g1") g2.vizualize_genome(2, "g2") gc.vizualize_genome(3, "gc") plt.show()
def test_items_format_invocation(self): items = [("x", 1), ("y", 2), ("z", 3)] dotted = DottedDict(items) self.assertEquals(dotted.x, 1) self.assertEquals(dotted.y, 2) self.assertEquals(dotted.z, 3)
def test_to_dict(self): dotted = DottedDict( DottedDict({ "a": "b", "c": { "d": "e" }, "f": [{ "g": "h" }, 1] })) my_dict = dotted.to_dict() self.assertEquals(dotted, my_dict) self.assertEqual(type(dotted), DottedDict) self.assertEqual(type(dotted.f[0]), DottedDict) self.assertEqual(type(my_dict), dict) self.assertEqual(type(my_dict["f"][0]), dict)
def main(): parser = argparse.ArgumentParser( description='Slack bot to send periodic 1:1 invitations.') parser.add_argument('-c', '--config', metavar='FILE', default='~/.11bot', help='config file') parser.add_argument('-d', '--database', metavar='FILE', default='~/.11bot-db', help='database file') args = parser.parse_args() # Self-test Grouping.selftest() # Read config with open(os.path.expanduser(args.config)) as fh: config = DottedDict(yaml.safe_load(fh)) config.database = os.path.expanduser(args.database) env_map = ( ('ELEVENBOT_APP_TOKEN', 'app-token'), ('ELEVENBOT_TOKEN', 'token'), ) for env, config_key in env_map: v = os.environ.get(env) if v: setattr(config, config_key, v) # Connect to services client = WebClient(token=config.token) # store our user ID config.bot_id = client.auth_test()['user_id'] db = Database(config) # Start socket-mode listener in the background socket_client = SocketModeClient(app_token=config.app_token, web_client=WebClient(token=config.token)) socket_client.socket_mode_request_listeners.append( lambda socket_client, req: process_event(config, socket_client, req)) socket_client.connect() # Run scheduler Scheduler(config, client, db).run()
def test_setting_and_accessing(self): key = "x" value = 5 dotted = DottedDict({key: value}) self.assertEqual(dotted[key], value) self.assertEqual(dotted.x, value) self.assertEqual(dotted.x, dotted[key])
def __init__(self): #LOCAL_PATH self.WORKING_DIR = "/home/bortolossohurst/Documents/ambv_boot/selenium_spider.py" self.VALUE = DottedDict({ "PATH_PDF": self.WORKING_DIR + "/temp/pdf", "PATH_DRIVER": self.WORKING_DIR + "/driver/chromedriver75", "PATH_TEMP_CAPTCHA": self.WORKING_DIR + "/img_captcha.jpg", "TEMP_PDF": self.WORKING_DIR + "/temp/pdf/arelpesquisainternetprecatorio.pdf", "DIRECTORY_PATH": self.WORKING_DIR + "/format_pdf/" }) #WEB self.CAC_SCP = DottedDict({ "SP": { "URL": "https://www.tjsp.jus.br/cac/scp/webmenupesquisa.aspx" } }) self.WORKING_XPATH = "/html[1]/body[1]/form[1]/table[1]/tbody[1]/tr[3]/td[1]/table[1]/tbody[1]/tr[1]/td[1]/table[1]/tbody[1]" self.LOCAL_WEB = DottedDict({ "XPATH": { "BUTTOM_PRECA": self.WORKING_XPATH + "/tr[3]/td[1]/table[1]/tbody[1]/tr[2]/td[1]/table[1]/tbody[1]/tr[1]/td[2]/span[1]/a[1]", "SEND_INPUT": self.WORKING_XPATH + "/tr[2]/td[1]/table[1]/tbody[1]/tr[4]/td[2]/table[1]/tbody[1]/tr[1]/td[3]/input[1]", "URL_CAP": self.WORKING_XPATH + "/tr[5]/td[1]/table[1]/tbody[1]/tr[1]/td[2]/div[1]/div[1]/img[1]", "ERRO_CAPTCHA": self.WORKING_XPATH + "/tr[7]/td[1]/table[1]/tbody[1]/tr[1]/td[2]/input[1]", "NEW_CAPTCHA": self.WORKING_XPATH + "/tr[5]/td[1]/table[1]/tbody[1]/tr[1]/td[2]/div[1]/div[1]/a[1]", "ERRO": "//span[contains(text(),'Código digitado incorretamente!')]", "ROWS_TABLE": "//table[@id='Grid1ContainerTbl']/tbody[1]/tr[*]", "NEXT_TABLE": "//span[@class='PagingButtonsNext']" } })
def __init__(self): # Block States - 0 is the base and any other number denotes another state. # Hits on the block will reduce the state to 0, which is the base state self.block_states = { 0: DottedDict({'color': 0}), } self.current_state = 0 self.is_animated = False
def parse_config(self, config_path=None): if config_path: with open(config_path, 'r') as config_file: parsed_config = json.load(config_file) else: parsed_config = {} with open("default_config.json", 'r') as default_config_file: default_config = json.load(default_config_file) config_dict = {**default_config, **parsed_config} return DottedDict(config_dict)
def get_instance_metadata(): ''' Get the instance metadata and return an DottedDict with the values. ''' http = urllib3.PoolManager() response = http.request( 'GET', 'http://169.254.169.254/latest/dynamic/instance-identity/document') data = json.loads(response.data) return DottedDict({uncamel(k): v for k, v in data.items()})
def _sort_dirs(self): ''' Populate self.dirs with the 10 largest dirs. ''' for k, v in sorted(self._dirs_holder.items(), key=operator.itemgetter(1), reverse=True): self.dirs.append(DottedDict({'name': k, 'size': v})) del self._dirs_holder self.dir_count = len(self.dirs) self.dirs = self.dirs[0:10]
def install(ctx, target: str, config_file: Path): """Installs Quantotto product """ with config_file.open("rb") as f: config_buf = f.read() config = DottedDict(yaml.load(config_buf, Loader=yaml.SafeLoader)) pprint.pprint(config) if target == "standalone": install_standalone(ctx, config) elif target == "k8s": install_k8s(ctx, config)
def test_file_save(self): c = consumer.Consumer() c._writeToFile( DottedDict({ 'header': 'fname=test.txt', 'data': 'This is test'.encode() })) with open('output/test.txt') as f: s = f.readline() self.assertEqual(s, 'This is test')
def have_access(client, id): '''Return True if we have Slack API access to the specified channel.''' try: info = DottedDict(client.conversations_info(channel=id)['channel']) return ((info.is_channel or info.is_group) and not info.is_archived) except SlackApiError as e: # might get missing_scope for IM/MPIM conversations if e.response['error'] in ('channel_not_found', 'missing_scope'): return False else: raise
def create_bunch(particles): bunch = DottedDict() bunch.x = np.zeros(particles) bunch.px = np.zeros(particles) bunch.y = np.zeros(particles) bunch.py = np.zeros(particles) return bunch
def main(): resolution = (180, 50) config = DottedDict({ "HEIGHT": resolution[1], "WIDTH": resolution[0], "FRAME_DURATION": 10, "COUNT_GRAPHICS_UPDATES": 2, "COUNT_PHYSICS_UPDATES": 10, "ONE_FRAME_ONLY": False, "BORDER": True, }) win = WM(config) # Adds the paddle # Signature - width, height, color, (left, top) paddle_start = [int(resolution[0] / 2) - 10, resolution[1] - 2] paddle = Paddle(20, 1, 2, paddle_start) win.add_component(paddle, True, True) # Add a simple level in layer_res = [26, 30] layer_mat = [] for row_num in range(layer_res[0]): row = [] for col_num in range(layer_res[1]): # Conditions for blocks to be as they need to be explosive_conditions = [ row_num in [layer_res[0] - 1], col_num in [] ] other_all_conditions = [row_num % 3 == 0, col_num % 3 == 0] if any(explosive_conditions): row.append(BlockExplosive()) elif all(other_all_conditions): row.append( random.choice([ BlockOneHit, BlockTwoHit, BlockInvisible, BlockOneHit, BlockTwoHit, BlockInvisible, BlockInfHit ])()) else: row.append(None) layer_mat.append(row) level = Level(np.array(layer_mat).T) win.add_component(level, True) # Adds display for time time_bar = Time((resolution[0] - 19, 2), 7) win.add_component(time_bar, True, True) if name == 'posix': _ = system('tput civis') win.game_loop()
def __init__(self, target): self._dirs_holder = {} self.dir_count = 0 self.dirs = [] # A list of root level directores to ignore as do not contain traditional files self.exclude_root_dirs = ['dev', 'proc', 'selinux'] self.file_count = 0 self.files = [] self.partition = DottedDict({}) self.target = target # Exec data gathering for the object self._get_partition_usage(target) self._walk_filesystem(target)
def process(req, data): if data.get('slug', None): cv_queryset = CV.objects.filter(slug=data['slug']).select_related( 'color_profile', 'data') if not len(cv_queryset): return DottedDict({'success': False}) return DottedDict({'success': True, 'data': {'cv': cv_queryset[0]}}) color_profile = CVColorProfile.objects.get(pk=data['colorProfileId']) cv_data = CVDocument.objects.filter(on_main_page=True) if not color_profile or not len(cv_data): return DottedDict({'success': False}) return DottedDict({ 'success': True, 'data': { 'cv': { 'color_profile': color_profile, 'data': cv_data[0] } } })
def test_update(self): dotted = DottedDict( DottedDict({ "a": "b", "c": { "d": "e" }, "f": [{ "g": "h" }, 1] })) dotted.update({"a": "z"}) self.assertEquals(dotted.a, "z") dotted.update([("c", "v"), ("x", "y")]) self.assertEquals(dotted.c, "v") self.assertEquals(dotted.x, "y")
def postinstall(ctx, target: str, config_file: Path): """Configures Quantotto product post installation leveraging Management API """ k8s_config = {} with config_file.open("rb") as f: config_buf = f.read() config = DottedDict(yaml.load(config_buf, Loader=yaml.SafeLoader)) product_config = config.product if target == K8S: k8s_config = config.k8s if target == STANDALONE: customers = config.customers[0:1] else: customers = config.customers for c in customers: if target == K8S: prep_k8s_customer_env(c.id, k8s_config) create_objects(c, product_config)
def _get_file_data(self, filename): ''' Get file metadata and assemble dotted dict object containing filename, size, and modified time. ''' file_data = DottedDict({}) # Test for broken symlinks try: file_stat = os.stat(filename) file_data.name = filename file_data.modified = file_stat.st_mtime file_data.size = float(file_stat.st_size) except OSError: file_data.size = 0 return file_data
class TraderSim(pywingchun.Trader): def __init__(self, low_latency, locator, account_id, json_config): pywingchun.Trader.__init__(self, low_latency, locator, "sim", account_id) config = json.loads(json_config) self.match_mode = config.get("match_mode", MatchMode.Custom) self.ctx = DottedDict() self.ctx.orders = {} if self.match_mode == MatchMode.Custom: path = config.get("path") simulator_dir = os.path.dirname(path) name_no_ext = os.path.split(os.path.basename(path)) sys.path.append(os.path.relpath(simulator_dir)) impl = importlib.import_module(os.path.splitext(name_no_ext[1])[0]) self.ctx.insert_order = getattr(impl, 'insert_order', lambda ctx, event: False) self.ctx.cancel_order = getattr(impl, "cancel_order", lambda ctx, event: False) self.ctx.req_account = getattr(impl, "req_account", lambda ctx: False) self.ctx.req_position = getattr(impl, "req_position", lambda ctx: False) def on_start(self): pywingchun.Trader.on_start(self) def insert_order(self, event): if self.match_mode == MatchMode.Custom: return self.ctx.insert_order(self.ctx, event) else: order_input = event.data order = pywingchun.utils.order_from_input(order_input) min_vol = wc_utils.min_order_volume(order.instrument_id, order.exchange_id) if order_input.volume < min_vol: order.status = pywingchun.constants.OrderStatus.Error elif self.match_mode == MatchMode.Reject: order.status = pywingchun.constants.OrderStatus.Error elif self.match_mode == MatchMode.Pend: order.status = pywingchun.constants.OrderStatus.Pending elif self.match_mode == MatchMode.Cancel: order.status = pywingchun.constants.OrderStatus.Cancelled elif self.match_mode == MatchMode.PartialFillAndCancel: order.volume_traded = min_vol order.status = pywingchun.constants.OrderStatus.Filled if order.volume_traded == order.volume \ else pywingchun.constants.OrderStatus.PartialFilledNotActive elif self.match_mode == MatchMode.PartialFill: order.volume_traded = min_vol order.status = pywingchun.constants.OrderStatus.Filled if order.volume_traded == order.volume \ else pywingchun.constants.OrderStatus.PartialFilledActive elif self.match_mode == MatchMode.Fill: order.volume_traded = order_input.volume else: raise Exception("invalid match mode {}".format( self.match_mode)) order.volume_left = order.volume - order.volume_traded self.get_writer(event.source).write_data(0, order) if order.active: self.ctx.orders[order.order_id] = OrderRecord( source=event.source, dest=event.dest, order=order) return True def cancel_order(self, event): if self.match_mode == MatchMode.Custom: return self.ctx.cancel_order(self.ctx, event) else: order_action = event.data if order_action.order_id in self.ctx.orders: record = self.ctx.orders.pop(order_action.order_id) order = record.order order.status = pywingchun.constants.OrderStatus.Cancelled if order.volume_traded == 0 \ else pywingchun.constants.OrderStatus.PartialFilledNotActive self.get_writer(event.source).write_data(0, order) return True def re_account(self): if self.match_mode == MatchMode.Custom: return self.ctx.req_account(self.ctx) return False def req_position(self): if self.match_mode == MatchMode.Custom: return self.ctx.req_position(self.ctx) return False
return img final_size = (600, 600) # how large the final square should be draw_scale = 5 # probably don't need to touch this palette_name = "ink" for seed in range(10): draw_size = (final_size[0]*draw_scale, final_size[1]*draw_scale) palette = DottedDict() if palette_name == "browns": palette.background = "#E2D9A6" palette.line_shadow = "#231811" palette.line_options = [("#402F18", "#6E5538"), ("#A68E5E", "#6E5538")] use_noise = False elif palette_name == "ink": palette.background = "#ffffff" palette.line_shadow = "#ffffff" #"#011017" palette.line_options = [("#021a24", "#011017"), ("#062330", "#011017")] use_noise= False elif palette_name == "blue_brown": # https://www.colourlovers.com/palette/4777762/Dawn2Dark palette.background = "#E5D2A4" palette.line_shadow = "#272935" #"#011017" palette.line_options = [("#253A6A", "#12839E"), ("#6AC6AA", "#272935")]