Exemple #1
0
 def __init__(self):
     super(BlockTwoHit, self).__init__()
     self.block_states.update({
         1: DottedDict({'color': 7}),
         2: DottedDict({'color': 6})
     })
     self.current_state = 2
Exemple #2
0
 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
Exemple #3
0
 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})
Exemple #4
0
    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 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 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()
Exemple #7
0
    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)
Exemple #8
0
    def test_dotted_get(self):
        value = "foo"
        data = {"color": {"blue": value}}

        dotted = DottedDict(data)

        self.assertEqual(dotted.get("color").get("blue"), value)
Exemple #9
0
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}"')
Exemple #10
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")
Exemple #11
0
    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])
Exemple #12
0
    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']"
            }
        })
Exemple #13
0
 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)
Exemple #14
0
    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
Exemple #15
0
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()})
Exemple #16
0
 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 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')
Exemple #18
0
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)
Exemple #19
0
 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]
Exemple #20
0
 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
Exemple #21
0
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()
Exemple #22
0
 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]
            }
        }
    })
Exemple #24
0
 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
Exemple #25
0
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()
Exemple #26
0
def linear_default(debug=False):
    config = DottedDict()
    config.optimizer = "sgd"
    config.device = 'cuda:1' if torch.cuda.is_available() else 'cpu'
    config.batch_size = 256
    config.base_lr = 0.5
    config.num_workers = 8
    config.num_epochs = 100
    config.optimizer_args = {
        "lr": config.base_lr,
        "weight_decay": 5e-4,  # adapted, paper says 0
        "momentum": 0.9
    }
    config.scheduler = "cosine_decay"
    config.scheduler_args = {"T_max": config.num_epochs, "eta_min": 0}
    return config
Exemple #27
0
 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)
Exemple #28
0
def simsiam_default(debug=False):
    config = DottedDict()
    config.fs_ckpt = "model_{}_epoch_{:0>6}.ckpt"
    config.mean_std = [[0.485, 0.456, 0.406], [0.229, 0.224, 0.225]]
    config.dataset = "imagenet"
    config.backbone = "resnet50"
    config.batch_size = 512
    config.num_epochs = 100
    config.img_size = 224
    config.projector_args = {
        "hidden_dim": 2048,
        "out_dim": 2048,
        "n_hidden_layers": 1
    }
    config.predictor_args = {
        "hidden_dim": config.projector_args["out_dim"] // 4,  # see Appendix B.
        "in_dim": config.projector_args["out_dim"],
        "out_dim": config.projector_args["out_dim"]
    }
    config.optimizer = "sgd"
    config.base_lr = 0.05
    config.optimizer_args = {
        "lr": config.base_lr * (config.batch_size / 256),
        "weight_decay": 0.0001,  # used always
        "momentum": 0.9
    }
    config.scheduler = "cosine_decay"
    config.scheduler_args = {
        "T_max": config.num_epochs,
        "eta_min": 0,
    }
    config.debug = False
    config.num_workers = 8
    config.device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
    config.resume = False
    #
    # Frequencies (epochs)
    #
    config.freq_knn = 1
    #
    # debug settings
    if config.debug:
        config.batch_size = 2
        config.num_epochs = 5  # train only one epoch
        config.num_workers = 1

    return config
Exemple #29
0
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()
Exemple #30
0
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)