Beispiel #1
0
    def test_asset_make_visible(self, mock_maya):
        mock_maya.text.return_value = 17
        self.mock_self.scroll_layout = "layout"
        self.mock_self.display_text = "text"
        self.called = 0

        def scroll(*args, **kwargs):
            self.called += 1
            if kwargs.get(
                    "query") and self.mock_self.scroll_layout == "layout":
                return [4, 0]
            elif kwargs.get("query"):
                return [0, 0]
            else:
                self.assertEqual(kwargs.get("scrollPage"), "up")
                self.mock_self.scroll_layout = "scrolled"

        mock_maya.scroll_layout = scroll
        Asset.make_visible(self.mock_self, 0)
        self.assertEqual(self.called, 3)

        def scroll(*args, **kwargs):
            self.called += 1
            self.assertEqual(kwargs.get("scrollByPixel"), ("down", 17))

        mock_maya.scroll_layout = scroll
        Asset.make_visible(self.mock_self, 5)
        self.assertEqual(self.called, 4)
 def _assets(self, resps):
     try:
         total = self._floatify(resps[0]["eth_balance"])
     except KeyError as error:
         msg = "ETH response could not be parsed"
         data = {"Original error": error, "Response": resps[0]}
         raise ExternalError(msg, data)
     assets = []
     if total > 0:
         assets.append(Asset({
             "name": "Ether",
             "symbol": "ETH",
             "location": "Wallet",
             "total": total
         }))
     for resp in resps:
         try:
             total = self._floatify(resp["balance"])
         except KeyError as error:
             # If we did not fail earlier with the ETH asset, then there's
             # the possibility that we got a valid response and we just
             # have unexpected data for a token. In that case, we don't
             # want to loose the information we got correctly, so we
             # don't interrupt the program's flow by `raising` the error.
             msg = "ERC-20 TOKEN response could not be parsed"
             data = {"Original error": error, "Response": resp}
             ExternalError(msg, data)
         if total > 0:
             assets.append(Asset({
                 "name": ERC20_TOKENS[resp["symbol"]]["name"],
                 "symbol": resp["symbol"],
                 "location": "Wallet",
                 "total": total
             }))
     return assets
Beispiel #3
0
 def _assets(self, resp):
     try:
         total = self._floatify(resp["NEO"]["balance"])
     except KeyError as error:
         msg = "NEO response could not be parsed"
         data = {"Original error": error, "Response": resp}
         raise ExternalError(msg, data)
     assets = []
     if total > 0:
         assets.append(Asset({
             "name": "Neo",
             "symbol": "NEO",
             "location": "Wallet",
             "total": total
         }))
     try:
         total = self._floatify(resp["GAS"]["balance"])
     except KeyError as error:
         msg = "GAS response could not be parsed"
         data = {"Original error": error, "Response": resp}
         raise ExternalError(msg, data)
     if total > 0:
         assets.append(Asset({
             "name": "Gas",
             "symbol": "GAS",
             "location": "Wallet",
             "total": total
         }))
     return assets
Beispiel #4
0
    def test_asset_display(self, mock_api):
        self.mock_self.path = "\\my\\local\\test_path"
        self.mock_self.label = "label"
        self.mock_self.note = "note"
        self.mock_self.exists = False

        Asset.display(self.mock_self, "ui", "layout", "scroll")
        mock_api.symbol_button.assert_called_with(
            image="fpe_someBrokenPaths.png",
            parent="layout",
            command=mock.ANY,
            height=17,
            annotation="Add search path")
        mock_api.text.assert_called_with("label",
                                         parent="layout",
                                         enable=False,
                                         annotation="note",
                                         align="left")
        self.assertEqual(self.mock_self.scroll_layout, "scroll")
        self.assertEqual(self.mock_self.frame, "ui")

        self.mock_self.exists = True
        Asset.display(self.mock_self, "ui", "layout", "scroll")
        mock_api.symbol_check_box.assert_called_with(
            annotation='Click to remove asset from submission',
            offCommand=mock.ANY,
            onCommand=mock.ANY,
            parent='layout',
            value=True)
Beispiel #5
0
 def get_variants(self):
     if not self.built:
         raise Exception("Asset pack not built; use self.build() to build")
     variants = {}
     assets = self.get_assets()
     right = lambda x: max(
         [block[-1].x_right for block in x.get_all_blocks()])
     # ground express, all single-carriageway roads <= 3.5L
     variants['express'] = [x for x in assets['base'] + assets['shift'] \
         + assets['trans'] + assets['ramp'] + assets['twoway'] if right(x) <= 5 * SW.LANE]
     # ground compact, all roads w/ traffic lights <= 3.5L
     variants['compact'] = [
         x for x in assets['base'] + assets['twoway']
         if x.has_trafficlight() and right(x) <= 3.5 * SW.LANE
     ]
     # uturn lanes, with median size 3L, 4L and 5L
     variants['uturn'] = []
     # BRT stations, comp segment with 2DC in the middle
     variants['brt'] = []
     for x in assets['twoway']:
         if str(x.left) == str(
                 x.right) and x.right.x0() / SW.LANE in ALLOWED_UTURN:
             y = Asset(x.right.x0(), x.right.nl(),
                       x.right.x0() - SW.LANE,
                       x.right.nl() + 1)
             variants['uturn'].append(TwoWayAsset(y, y))
         if str(x.left) == str(x.right) and x.right.x0() == 0 and len(
                 x.right.nlanes[0]) > 1:
             y = Asset(x.right.x0(), x.right.nlanes[0], medians=[2, 2])
             variants['brt'].append(TwoWayAsset(y, y))
     return variants
Beispiel #6
0
    def test_asset_check(self):
        new_file = mock.create_autospec(Asset)
        new_file.path = "C:\\TEST_file\\WeiRD_path"
        self.mock_self.path = "c:\\test_file\\Weird_path"

        check = Asset.is_duplicate(self.mock_self, [new_file])
        self.assertTrue(check)

        new_file.path = "C:\\TEST_file\\WeiRD_path\\different"
        check = Asset.is_duplicate(self.mock_self, [new_file])
        self.assertFalse(check)
Beispiel #7
0
    def test_asset_delete(self, mock_api):
        self.mock_self.parent_list = []
        self.mock_self.check_box = 1

        Asset.delete(self.mock_self)
        mock_api.delete_ui.assert_called_with(1, control=True)
        self.assertEqual(self.mock_self.parent_list, [])

        self.mock_self.parent_list = [self.mock_self]
        Asset.delete(self.mock_self)
        mock_api.delete_ui.assert_called_with(1, control=True)
        self.assertEqual(self.mock_self.parent_list, [])
Beispiel #8
0
    def test_asset_include(self, mock_api):
        self.mock_self.check_box = 1
        self.mock_self.parent_list = []
        Asset.include(self.mock_self)
        self.assertEqual(self.mock_self.parent_list, [self.mock_self])
        mock_api.symbol_check_box.assert_called_with(
            1, edit=True, annotation="Click to remove asset from submission")

        Asset.include(self.mock_self)
        self.assertEqual(self.mock_self.parent_list, [self.mock_self])
        mock_api.symbol_check_box.assert_called_with(
            1, edit=True, annotation="Click to remove asset from submission")
Beispiel #9
0
    def test_asset_included(self, mock_api):
        self.mock_self.exists = False
        self.mock_self.check_box = None

        val = Asset.included(self.mock_self)
        self.assertFalse(val)

        self.mock_self.check_box = 1
        val = Asset.included(self.mock_self)
        self.assertFalse(val)

        self.mock_self.exists = True
        val = Asset.included(self.mock_self)
        mock_api.symbol_check_box.assert_called_with(1, query=True, value=True)
Beispiel #10
0
 def from_corp_name(corp_name, corp_assets=None):
     pos_mod_dict = {}
     pos_list = []
     corp_assets = corp_assets or Asset.from_entity_name(corp_name)
     assets = [a for a in corp_assets if Pos.is_pos_mod(a)]
     pos_mods = [m for m in assets if m.group.name != 'Control Tower']
     mod_locations = item_locations([m.item_id for m in pos_mods])
     pos_assets = {
         p.item_id: p
         for p in assets if p.group.name == 'Control Tower'
     }
     pos_locations = item_locations(
         [p.item_id for p in pos_assets.values()])
     for mod in pos_mods:
         mod.xyz = mod_locations[mod.item_id]
         mods = pos_mod_dict.setdefault(nearest(mod.xyz, pos_locations), [])
         mods.append(mod)
     corp_id = name_to_id(corp_name, 'corporation')
     poses_request = esi.op['get_corporations_corporation_id_starbases'](
         corporation_id=corp_id)
     poses_response = esi_client.request(poses_request)
     if not poses_response.status == 200:
         raise HTTPError(poses_response.data['error'])
     poses = {s.starbase_id: s for s in poses_response.data}
     for pos_id, pos in poses.iteritems():
         pos.update(pos_assets[pos.starbase_id].__dict__)
         pos['xyz'] = pos_locations[pos.starbase_id]
         pos_object = Pos.from_id(corp_id=corp_id,
                                  mods=pos_mod_dict.get(pos_id, []),
                                  **pos)
         pos_list.append(pos_object)
     return pos_list
Beispiel #11
0
 def from_corporation(cls, corporation_name, assets=None):
     structure_list = []
     corporation_id = name_to_id(corporation_name, 'corporation')
     assets = assets or Asset.from_entity_id(corporation_id, 'corporations')
     endpoint = 'get_corporations_corporation_id_structures'
     structures_request = esi.op[endpoint](corporation_id=corporation_id)
     structures_response = esi_client.request(structures_request)
     structures = structures_response.data
     endpoint = 'get_corporation_corporation_id_mining_extractions'
     detonations_request = esi.op[endpoint](corporation_id=corporation_id)
     detonations_response = esi_client.request(detonations_request)
     detonations = detonations_response.data
     detonations = {
         d['structure_id']: d['chunk_arrival_time']
         for d in detonations
     }
     structure_keys = [
         'structure_id', 'corporation_id', 'system_id', 'type_id',
         'services', 'fuel_expires', 'state', 'state_timer_end'
     ]
     for s in structures:
         sid = s['structure_id']
         kwargs = {k: v for k, v in s.items() if k in structure_keys}
         kwargs['type_name'] = ids_to_names([s['type_id']])[s['type_id']]
         kwargs['detonation'] = detonations.get(sid)
         structure_contents = [a for a in assets if a.location_id == sid]
         if structure_contents:
             kwargs['fitting'] = Fitting.from_assets(structure_contents)
             kwargs['fuel'] = [
                 a for a in structure_contents
                 if a.location_flag == 'StructureFuel'
             ]
         structure_list.append(cls(**kwargs))
     return structure_list
Beispiel #12
0
 def _assets(self, resp):
     try:
         success = resp["success"]
     except KeyError as error:
         msg = "ARK response could not be parsed"
         data = {"Original error": error, "Response": resp}
         raise ExternalError(msg, data)
     assets = []
     if success:
         try:
             total = self._fix_decimals(resp["balance"])
         except KeyError as error:
             msg = "ARK response could not be parsed"
             data = {"Original error": error, "Response": resp}
             raise ExternalError(msg, data)
         if total > 0:
             assets.append(
                 Asset({
                     "name": "Ark",
                     "symbol": "ARK",
                     "location": "Wallet",
                     "total": total
                 }))
     else:
         # If not successful, we assume that the account has not
         # received any transfers yet, so it's not registered in
         # the blockchain. Therefore, we'll say it has 0 balance.
         # We create an error object to make sure the proper
         # information is printed to the screen, but we don't
         # `raise`it, so it won't interrupt the program's flow.
         msg = "ARK response indicates failure"
         data = {"Response": resp}
         ExternalError(msg, data)
     return assets
Beispiel #13
0
def reuse(cached_lists, source_assets, staged_assets, list_path):
    logging.info("Recycling client Python...")

    def iter_python_paks():
        for (client_directory, extension), entries in cached_lists.items():
            if client_directory.lower() == "python" and extension.lower(
            ) == "pak":
                for i in entries:
                    yield i.file_name, list_path.joinpath(i.file_name)

    if not any(iter_python_paks()):
        logging.critical("No Python pak files were found to recycle.")
        logging.critical("No client python code will be available!")
        return

    for pak_client_path, source_path in iter_python_paks():
        if not source_path.exists():
            logging.error(
                f"Cannot recycle '{pak_client_path}' from '{source_path}'!")
            continue

        logging.debug(f"Recycling Python pak '{pak_client_path}'")
        source_assets[pak_client_path] = Asset(None, source_path,
                                               pak_client_path,
                                               set(("python", )))
        staged_asset = staged_assets[pak_client_path]
        staged_asset.file_name = pak_client_path
        # This was already encrypted (I hope?) by a previous run.
        staged_asset.flags |= ManifestFlags.dont_encrypt
Beispiel #14
0
def _package(source_assets, staged_assets, module_code, output_path,
             droid_key):
    # Python.pak format:
    # uint32_t numFiles
    #     - safeStr filename
    #     - uint32_t offset
    # ~~~~~
    # uint32_t filesz
    # uint8_t data[filesz]

    logging.info("Building Python.pak...")
    if not module_code:
        logging.error("No marshalled python code available for packaging!")
        return

    pak_client_path = Path("Python", "Python.pak")
    pak_source_path = output_path.joinpath(pak_client_path)
    pak_source_path.parent.mkdir(parents=True, exist_ok=True)

    # We are using an encrypted strean, which doesn't seek at all.
    # Therefore, we will go ahead and calculate the size of the index block so
    # there is no need to seek around to write offset values
    base_offset = 4  # uint32_t numFiles
    data_offset = 0
    pyc_info = []  # sad, but makes life easier...
    for module_name, compyled_code in module_code.items():
        pyc_info.append((module_name, data_offset, compyled_code))

        # index offset overall
        base_offset += 2  # writeSafeStr length
        # NOTE: This assumes that libHSPlasma's hsStream::writeSafeStr converts
        #       the Python unicode/string object to UTF-8. Currently, this is true.
        base_offset += len(module_name.encode("utf-8"))  # writeSafeStr
        base_offset += 4

        # current file data offset
        data_offset += 4  # uint32_t filesz
        data_offset += len(compyled_code)

    kwargs = dict(mode=encryption.Mode.WriteBinary,
                  enc=encryption.Encryption.BTEA,
                  key=droid_key)
    with plasmoul.stream(encryption.stream, pak_source_path,
                         **kwargs) as stream:
        stream.writeu32(len(pyc_info))
        for module_name, data_offset, compyled_code in pyc_info:
            stream.write_safe_string(module_name)
            # offset of data == index size (base_offset) + offset to data blob (data_offset)
            stream.writeu32(base_offset + data_offset)
        for module_name, data_offset, compyled_code in pyc_info:
            stream.writeu32(len(compyled_code))
            stream.write(compyled_code)

    source_assets[pak_client_path] = Asset(None, pak_source_path,
                                           pak_client_path, set(("python", )))
    staged_asset = staged_assets[pak_client_path]
    staged_asset.file_name = pak_client_path
    # Prevent a spurious warning about naughty encryption
    staged_asset.flags |= ManifestFlags.dont_encrypt
 def _asset(self, asset):
     return Asset({
         "address": asset["CryptoAddress"],
         "available": asset["Available"],
         "symbol": asset["Currency"],
         "total": asset["Balance"],
         "location": "Bittrex",
     })
Beispiel #16
0
def asset_from_blocks(block_start, block_end=None):
    if block_end:
        x0, n0, m0 = parse_blocks(block_start)
        x1, n1, m1 = parse_blocks(block_end)
        return Asset(x0, n0, x1, n1, medians=[m0, m1])
    else:
        x, n, m = parse_blocks(block_start)
        return BaseAsset(x, *n, median=m)
Beispiel #17
0
    def test_asset_create(self):
        test_asset = Asset(self.mock_file, "parent", "batch")
        self.assertEqual(test_asset.label, "    test_path")
        self.assertEqual(test_asset.path, "\\my\\local\\test_path")
        self.assertEqual(test_asset.note, "Can't find \\my\\local\\test_path")
        self.assertFalse(test_asset.exists)

        with mock.patch.object(os.path, 'exists') as exist:
            with mock.patch.object(os.path, 'getmtime') as mod:
                with mock.patch.object(os.path, 'getsize'):
                    exist.return_value = True
                    mod.return_value = 1453766301
                    test_asset = Asset(self.mock_file, "parent", "batch")
                    self.assertEqual(test_asset.note, "\\my\\local\\test_path")
                    self.assertTrue(test_asset.exists)
                    self.assertEqual(
                        test_asset.pathmap['\\my\\local']('Linux'), 'my/local')
Beispiel #18
0
def find_access(nlane, base, name=None, codes=['5', '5P', '6P', '7P', '8P']):
    access_roads = []
    nlane_g = base.get_blocks()[0].nlanes
    x0 = base.x0()
    offsets = [offset_x(code) for code in codes]
    for i_a in range(2, nlane_g - nlane):
        if x0 + i_a * SW.LANE + SW.MEDIAN in offsets:
            access_roads.append(
                Asset(x0, nlane_g, x0,
                      [i_a - 1, nlane, nlane_g - nlane - i_a]))
    return access_roads
Beispiel #19
0
def connect(start, end):
    x0_l = start.x0()
    x1_l = end.x0()
    x0_r = start.get_blocks()[-1].x_right
    x1_r = end.get_blocks()[-1].x_right

    if len(start.get_blocks()) == 1 and len(end.get_blocks()) == 1:
        n0 = start.get_blocks()[0].nlanes
        n1 = end.get_blocks()[0].nlanes
        # Look for shift
        if n0 == n1:
            if abs(x0_l - x1_l) > N_SHIFT_MAX * SW.LANE:
                raise ValueError("Invalid shift increment! %d->%d" %
                                 (x0_l, x1_l))
            return Asset(x0_l, n0, x1_l, n0)
        # Look for transition
        else:
            if abs(n0 - n1) > DN_TRANS:
                raise ValueError("Invalid transition increment! %s=%s" %
                                 (start, end))
            elif x0_l != x1_l and x0_r != x1_r:
                raise ValueError("Invalid transition alignment! %s=%s" %
                                 (start, end))
            return Asset(x0_l, n0, x1_l, n1)
    else:
        # Look for ramp
        n0 = [c.nlanes for c in start.get_blocks()]
        n1 = [c.nlanes for c in end.get_blocks()]
        if abs(sum(n0) - sum(n1)) > DN_RAMP or (x0_l != x1_l and x0_r != x1_r):
            raise ValueError("Invalid ramp combination! %s=%s" % (start, end))
        n_medians = [1, 1]
        if len(n0) > 1:
            n_medians[0] = int(
                (start.get_blocks()[1].x_left - start.get_blocks()[0].x_right)
                // SW.MEDIAN)
        if len(n1) > 1:
            n_medians[1] = int(
                (end.get_blocks()[1].x_left - end.get_blocks()[0].x_right) //
                SW.MEDIAN)
        return Asset(x0_l, n0, x1_l, n1, medians=n_medians)
Beispiel #20
0
    def load_data(self, symbols, itype, timeframe):
        assets = {}
        missing = []
        for s in symbols:
            a = Asset()
            try:
                a.load_av_data(s, itype, timeframe)
            except FileNotFoundError:
                missing.append(s)
            else:
                assets[s] = a

        if missing:
            print('Missing: ', ', '.join(missing))
            print('Downloading...')
            ask_av_history(missing, itype, timeframe)
            for m in missing:
                try:
                    a.load_av_data(m, itype, timeframe)
                except FileNotFoundError:
                    print('DATA LOADING ERROR')
                else:
                    assets[m] = a

        self.timeframe = timeframe
        self.loaded = True
        self.canvas.update(assets)
        self.reset_range()
Beispiel #21
0
    def test_asset_upload(self, mock_maya):

        queue = Queue()
        self.mock_self.path = "/my/test/path/file.txt"
        self.mock_self.display_text = "display"
        self.mock_self.included.return_value = False
        self.mock_self.storage_path = "my/test/path/file.txt"
        self.mock_self.size = 10
        prog = mock.create_autospec(ProgressBar)
        prog.done = False

        Asset.upload(self.mock_self, 0, prog, queue, "container")
        self.mock_self.batch.file.upload.assert_called_with(
            "/my/test/path/file.txt",
            "container",
            "my/test/path/file.txt",
            progress_callback=mock.ANY)
        self.assertEqual(queue.qsize(), 7)

        self.mock_self.batch.file.upload.side_effect = ValueError('boom')
        Asset.upload(self.mock_self, 0, prog, queue, "container")
        self.assertEqual(queue.qsize(), 13)

        prog.done = True
        Asset.upload(self.mock_self, 0, prog, queue, "container")
        self.assertEqual(queue.qsize(), 14)
Beispiel #22
0
 def create_proposal(site, type_of_asset):
     new_proposal = Proposal.Proposal()
     site.add_proposal(new_proposal)
     if (type_of_asset == "Pkg" or type_of_asset == "Rtu"
             or type_of_asset == "PKG" or type_of_asset == "RTU"):
         x_asset = Pkg.Pkg()
         n_asset = Pkg.Pkg()
     elif (type_of_asset == "Ahu" or type_of_asset == "AHU"):
         x_asset = Ahu.Ahu()
         n_asset = Ahu.Ahu()
     elif (type_of_asset == "Cdu" or type_of_asset == "CDU"):
         x_asset = Cdu.Cdu()
         n_asset = Cdu.Cdu()
     elif (type_of_asset == "UH" or type_of_asset == "OTH"):
         x_asset = Asset.Asset()
         n_asset = Asset.Asset()
     else:
         raise TypeError("Invalid Asset Type Creation: " +
                         str(type_of_asset))
     new_proposal.add_existing_asset(x_asset)
     new_proposal.add_new_asset(n_asset)
     x_asset.run_hours_yearly = site.run_hours_yearly
     n_asset.run_hours_yearly = site.run_hours_yearly
     return new_proposal
Beispiel #23
0
 def __init__(self,
              system_id,
              moon_id,
              state,
              unanchor_at,
              reinforced_until,
              onlined_since,
              fuel_bay_view,
              fuel_bay_take,
              anchor,
              unanchor,
              online,
              offline,
              allow_corporation_members,
              allow_alliance_members,
              use_alliance_standings,
              attack_if_other_security_status_dropping,
              attack_if_at_war,
              fuels=[],
              mods=[],
              attack_security_status_threshold=None,
              attack_standing_threshold=None,
              *args,
              **kwargs):
     super(Pos, self).__init__(*args, **kwargs)
     self.system_id = system_id
     self.moon_id = moon_id
     self.state = state
     self.unanchor_at = unanchor_at
     self.reinforced_until = reinforced_until
     self.onlined_since = onlined_since
     self.fuel_bay_view = fuel_bay_view
     self.fuel_bay_take = fuel_bay_take
     self.anchor = anchor
     self.unanchor = unanchor
     self.online = online
     self.offline = offline
     self.allow_corporation_members = allow_corporation_members
     self.allow_alliance_members = allow_alliance_members
     self.use_alliance_standings = use_alliance_standings
     self.attack_standing_threshold = attack_standing_threshold
     self.attack_security_status_threshold = attack_security_status_threshold
     self.attack_if_other_security_status_dropping = attack_if_other_security_status_dropping
     self.attack_if_at_war = attack_if_at_war
     self.fuels = [
         Asset.from_id(t.type_id, quantity=t.quantity) for t in fuels
     ]
     self.mods = mods
Beispiel #24
0
 def _assets(self, resp):
     try:
         total = self._floatify(resp)
     except KeyError as error:
         msg = "BTC response could not be parsed"
         data = {"Original error": error, "Response": resp}
         raise ExternalError(msg, data)
     assets = []
     if total > 0:
         assets.append(
             Asset({
                 "name": "Bitcoin",
                 "symbol": "BTC",
                 "location": "Wallet",
                 "total": total
             }))
     return assets
 def _assets(self, resp):
     try:
         total = self._floatify(resp["balances"][0])
     except KeyError as error:
         msg = "IOTA response could not be parsed"
         data = {"Original error": error, "Response": resp}
         raise ExternalError(msg, data)
     assets = []
     if total > 0:
         assets.append(Asset({
             "name": "IOTA",
             "symbol": "MIOTA",
             "location": "Wallet",
             # NOTE: We follow CoinMarketCap's convention of using MIOTA
             #       as the base unit, which is equivalent to 1,000,000
             #       IOTAs. This is to simplify price calculations.
             "total": total / 1000000
         }))
     return assets
Beispiel #26
0
    def test_asset_search(self, mock_api):
        from assets import USR_SEARCHPATHS
        self.mock_self.frame = mock.create_autospec(AssetsUI)
        mock_api.file_select.return_value = None
        Asset.search(self.mock_self)
        self.assertEqual(USR_SEARCHPATHS, [])
        self.assertEqual(self.mock_self.frame.refresh.call_count, 0)

        mock_api.file_select.return_value = []
        Asset.search(self.mock_self)
        self.assertEqual(USR_SEARCHPATHS, [])
        self.assertEqual(self.mock_self.frame.refresh.call_count, 0)

        mock_api.file_select.return_value = ["selected_path"]
        Asset.search(self.mock_self)
        self.assertEqual(USR_SEARCHPATHS, ["selected_path"])
        self.mock_self.frame.refresh.assert_called_with()
Beispiel #27
0
    def test_asset_exclude(self, mock_api):
        self.mock_self.check_box = 1
        self.mock_self.parent_list = []
        Asset.exclude(self.mock_self)
        self.assertEqual(self.mock_self.parent_list, [])
        self.assertEqual(mock_api.symbol_check_box.call_count, 0)

        self.mock_self.parent_list = ["test"]
        Asset.exclude(self.mock_self)
        self.assertEqual(self.mock_self.parent_list, ["test"])
        self.assertEqual(mock_api.symbol_check_box.call_count, 0)

        self.mock_self.parent_list = [self.mock_self]
        Asset.exclude(self.mock_self)
        self.assertEqual(self.mock_self.parent_list, [])
        mock_api.symbol_check_box.assert_called_with(
            1, edit=True, annotation="Click to include asset in submission")
Beispiel #28
0
    def cache_asset(self, path, callback=None):

        if self.cache is None:
            return callback()
        else:
            asset = Asset.from_hash(self, self.cache_get_hash(path))
            if asset and asset.is_fresh(self):
                return asset
            elif callback:
                asset = callback()

                if asset:
                    asset_hash = {}
                    asset_hash = asset.encode_with(asset_hash)

                    self.cache_set_hash(path, asset_hash)

                    if path != asset.pathname:
                        self.cache_set_hash(asset.pathname, asset_hash)

                    return asset

        return None
Beispiel #29
0
	def cache_asset(self,path,callback=None):

		if self.cache is None:
			return callback()
		else:
			asset = Asset.from_hash(self,self.cache_get_hash(path))
			if asset and asset.is_fresh(self):
				return asset
			elif callback:
				asset = callback()

				if asset:
					asset_hash = {}
					asset_hash = asset.encode_with(asset_hash)

					self.cache_set_hash(path,asset_hash)

					if path != asset.pathname:
						self.cache_set_hash(asset.pathname,asset_hash)

					return asset

		return None
Beispiel #30
0
#STOCKS = ['T']
black = 0
white = 0
doji = 0
hammer = 0
ss = 0
gapup = 0
gapdown = 0
ssum = 0
bs = 0
ccup = 0
ccupc = 0

for s in STOCKS:
    chart = Asset()
    chart.load_av_history('AVHD', s)
    chart.range_from_last(750)

    for i in range(chart.range_from, chart.range_to):
        this = chart.get()
        prev = chart.get(-1)

        ssum += this.close_price - this.open_price

        delta = this.close_price - prev.close_price
        #delta = this.close_price - this.open_price

        if prev.is_bullish():
            white = white + delta
        if prev.is_bearish():
Beispiel #31
0
    else:
        canvas.save(os.path.join(ROOT, "thumbnails/%s" % asset + suffix))


if __name__ == "__main__":
    '''
    from builder import Builder
    max_lane = 6
    codes_all = [['1', '2', '2P', '3', '3P', '4', '4P', '5P'],
                    ['2', '3', '4', '4P', '5P', '6P', '7'],
                    ['3', '4', '5P', '6P'],
                    ['4', '5', '6P'],
                    ['5', '6'],
                    ['6', '7'],
                ]
    builder = Builder(codes_all, MAX_UNDIVIDED=4).build()
    assetpack = builder.get_assets()
    asset_list = []
    for k in assetpack.keys():
        asset_list.extend(assetpack[k])
    print(len(asset_list))
    for asset in asset_list:
        if not asset.is_twoway():
            draw(asset)
    '''
    #asset2 = Asset(3*1.875, 2)
    asset = Asset(3.75 * 3, 2)
    #asset = TwoWayAsset(asset2, asset)
    for mode in [None, 'disabled', 'hovered', 'focused', 'pressed']:
        draw(asset, "C:/Work/roads/CSUR/img/color.ini", "example", mode=mode)
    #'''