コード例 #1
0
    def _colorize_row(conf: ColorizeConfig, converted_row, row):
        row_as_list = list(row)
        truthy = []
        for cd in conf.descriptors:
            filtered_type_values = list(
                filter(lambda x: type(x) == cd.type,
                       row_as_list[cd.scan_range[0]:cd.scan_range[1]]))
            match_count = 0
            for idx, val in enumerate(filtered_type_values):
                if val == cd.value:
                    match_count += 1
            if cd.match_type == MatchType.ANY and match_count > 0:
                truthy.append(cd)
            elif cd.match_type == MatchType.ALL and match_count == len(
                    filtered_type_values):
                truthy.append(cd)

        for cd in truthy:
            color_args = {cd.color_type.value: cd.color.value}
            for i in range(*cd.colorize_range):
                # Color multiline strings line by line
                if "\n" in str(converted_row[i]):
                    lines = converted_row[i].splitlines()
                    colored = []
                    for idx, line in enumerate(lines):
                        colored.append(color(line, **color_args))
                    converted_row[i] = "\n".join(colored)
                else:
                    converted_row[i] = color(converted_row[i], **color_args)
            if conf.eval_method == EvaluationMethod.FIRST_TRUTHY:
                break
コード例 #2
0
 def process_tag(tag, i1, i2, j1, j2):
     if tag == 'insert':
         return color('......', fore='black', back='orange')
     elif tag != 'equal':
         return color(matcher.a[i1:i2], fore='black', back='orange')
     else:
         return matcher.a[i1:i2]
コード例 #3
0
ファイル: core.py プロジェクト: akshaykurmi/rl-cookbook
 def render(self, mode='human'):
     grid = self._bitboard_to_grid()
     symbols = {
         0: ' ',
         1: color('●', fore='#8e86ff'),
         -1: color('●', fore='#cfff00')
     }
     turns = {1: 'BLUE', -1: 'YELLOW'}
     status = self._game_status()
     result = {
         Connect4.GameStatus.IN_PROGRESS:
         f'TURN : {turns[self.turn.value]}',
         Connect4.GameStatus.DRAW: f'Draw!',
         Connect4.GameStatus.BLUE_WON: f'BLUE Won!',
         Connect4.GameStatus.YELLOW_WON: f'YELLOW Won!',
     }[status]
     result = result.center(29)
     result += '\n┌' + ('───┬' * 7)[:-1] + '┐\n'
     for i, row in enumerate(grid):
         for v in row:
             result += f'| {symbols[v]} '
         result += '|\n'
         if i < 5:
             result += '├' + ('───┼' * 7)[:-1] + '┤\n'
     result += '└' + ('───┴' * 7)[:-1] + '┘\n'
     result += ''.join([f'  {i} ' for i in range(7)])
     return result
コード例 #4
0
    def mark_rNc_position(self, marker):
        '''
        helps to mark current position if no mark is already present
        returns True if mark was successfully placed else returns False
        '''
        new_mark = self._validate_marker(marker)
        can_mark_position = self._check_mark_presence()

        # give different color to different player's mark symbol
        if new_mark == "p1":
            new_mark = color(new_mark, fore="red")
        else:
            new_mark = color(new_mark, fore="blue")

        # curRow and curCol doesn't start from 0 and our list is 0 indexed
        # whenever curRow and curCol is not 0 we will always subtract 1

        if self._current_row != 0 and self._current_column != 0:
            if can_mark_position:
                self._board[self._current_row - 1].pop(self._current_column -
                                                       1)
                self._board[self._current_row - 1].insert(
                    self._current_column - 1, new_mark)
                return True

        else:
            if can_mark_position:
                self._board[self._current_row].pop(self._current_column)
                self._board[self._current_row].insert(self._current_column,
                                                      new_mark)
                return True

        return False
コード例 #5
0
    def parse(self, args):
        result = self.driver.GetAll('org.chemlab.UChroma.Device')
        keylen = max_keylen(result)
        props = OrderedDict(
            sorted({camel_to_snake(k): v
                    for k, v in result.items()}.items()))

        for dumpable in self._dumpables:
            for v in dumpable.current_state.values():
                if len(v.keys()) == 0:
                    continue
                kk = max_keylen(v.keys())
                if kk > keylen:
                    keylen = kk

        print('\n Device properties:\n')

        device_index = "device-%s" % props.pop('device_index')
        device_name = props.pop('name')

        self.columns(keylen, color(device_index, style='bright'),
                     color(device_name, style='bright'))
        self.seperator(keylen)

        for k, v in props.items():
            self.columns(keylen, color(k, style='bright'), v)

        print('\n')

        for dumpable in self._dumpables:
            dumpable.dump(keylen=keylen)
コード例 #6
0
ファイル: tictactoe.py プロジェクト: afsalshan/Python
def switch_player():
    global player_no
    if player_no == 1:
        print(color("turn of player o", fore='red'))
        player_no = 0
    else:
        print(color("turn of player x", fore='green'))
        player_no = 1
コード例 #7
0
def generate_repo(directoryname):

    print(color().bright().blue(pyfiglet.figlet_format("Create Jupyter Git")))

    # determine all the important paths needed
    current_working_directory = pathlib.Path(os.getcwd()).absolute()
    current_directory_path = pathlib.Path(__file__).parent.absolute()
    repo_template_path = os.path.join(current_directory_path, 'repo_template')

    target_directory_path = os.path.join(current_working_directory,
                                         directoryname)
    target_script_path = os.path.join(target_directory_path,
                                      'scripts/ipynb_output_filter.py')

    script_absolute_path = os.path.join(target_directory_path,
                                        "scripts/ipynb_output_filter.py")
    git_attributes_path = os.path.join(target_directory_path, ".gitattributes")

    # ensure the taret directory exists first
    if not os.path.exists(target_directory_path):
        pathlib.Path(target_directory_path).mkdir(parents=True, exist_ok=True)

    # move into that target directory to perform some system commands
    os.chdir(target_directory_path)

    # don't attempt to do anything if we are already inside a repo
    if (is_cwd_git_repo()):
        print(color().bright().red(
            'already within a repository, exiting with no changes'))
        return

    # copy the repo template over
    shutil.copytree(repo_template_path,
                    target_directory_path,
                    dirs_exist_ok=True)

    # make our magic script executable
    st = os.stat(target_script_path)
    os.chmod(target_script_path, st.st_mode | stat.S_IEXEC)

    # initialize the git repo
    os.system("git init")
    print(color().bright().green('git repository initialized'))

    # setup .gitattributes
    with open(git_attributes_path, "w") as git_attributes_file:
        print("*.ipynb    filter=dropoutput_ipynb", file=git_attributes_file)
        git_attributes_file.flush()

    # update git configs to utilize the filter script
    os.system("git config core.attributesfile {}".format(git_attributes_path))
    os.system("git config filter.dropoutput_ipynb.clean {}".format(
        script_absolute_path))
    os.system("git config filter.dropoutput_ipynb.smudge cat")

    # switch back to the original current working directory to be a good steward
    os.chdir(current_working_directory)
コード例 #8
0
def printBinaryImage(image_vector, dimensions, bg=False):
    for index, pixel in enumerate(image_vector, start=1):
        if bg:
            back = (pixel*255, pixel*255, pixel*255)
        else:
            back = (255-(pixel*255), 255-(pixel*255), 255-(pixel*255))
        if(index%dimensions[0]==0):
            print(color(' ', fore=back, back=back))
        else:
            print(color(' ', fore=back, back=back), end="")
コード例 #9
0
def printMnist(image_vector, dimensions=[28, 28], bg=False):
    for index, pixel in enumerate(image_vector, start=1):
        if bg:
            back = (pixel, pixel, pixel)
        else:
            back = (255 - pixel, 255 - pixel, 255 - pixel)
        if (index % dimensions[0] == 0):
            print(color(' ', fore=back, back=back))
        else:
            print(color(' ', fore=back, back=back), end="")
コード例 #10
0
def get_profit(buying_price, current):
    """Compute the variation since the order was placed"""
    variation = 100 * (float(current) -
                       float(buying_price)) / float(buying_price)
    if variation > 0:
        variation = '+' + str(round(variation, 2)) + '%'
        variation = color(variation, fore='green')
    else:
        variation = str(round(variation, 2)) + '%'
        variation = color(variation, fore='red')
    return variation
コード例 #11
0
def printImage(image_path, bg=False):
    img_pil = Image.open(image_path)
    dimensions = img_pil.size
    image_vector = list(img_pil.getdata())
    for index, pixel in enumerate(image_vector, start=1):
        if bg:
            back = (pixel[3], pixel[3], pixel[3])
        else:
            back = (255-pixel[3], 255-pixel[3], 255-pixel[3])
        if(index%dimensions[0]==0):
            print(color(' ', fore=back, back=back))
        else:
            print(color(' ', fore=back, back=back), end="")
コード例 #12
0
ファイル: tictactoe.py プロジェクト: afsalshan/Python
def board_draw():
    print(
        color(board[0] + "|" + board[1] + "|" + board[2],
              fore='yellow',
              back='red'))
    print(
        color(board[3] + "|" + board[4] + "|" + board[5],
              fore='yellow',
              back='red'))
    print(
        color(board[6] + "|" + board[7] + "|" + board[8],
              fore='yellow',
              back='red'))
コード例 #13
0
	def _paint_axes(self):
		# paint x and y axis if in scope
		# x
		if self._in_scope(y=0):
			row = self.screen_dims[1] - 1 - self._screen_pos(y=0)
			for col in range(self.screen_dims[0]):
				ink_before = self.screen[row][col]
				self.screen[row][col] = color(ink_before, back="#d75880")
		# y
		if self._in_scope(x=0):
			col = self._screen_pos(x=0)
			for row in range(self.screen_dims[1]):
				ink_before = self.screen[row][col]
				self.screen[row][col] = color(ink_before, back="#d75880")
コード例 #14
0
ファイル: test_colr.py プロジェクト: welbornprod/colr
    def test_strip_codes(self):
        """ strip_codes() should strip all color and reset codes. """
        self.assertEqual(
            'hello world',
            strip_codes(
                Colr('hello world', fore='green', back='blue', style='bright')
            ),
            msg=test_msg('Failed to strip codes from Colr string.'))

        self.assertEqual(
            'hello world',
            strip_codes(
                color('hello world', fore='red', back='blue', style='bright')
            ),
            msg=test_msg('Failed to strip codes from color string.'))

        self.assertEqual(
            'hello world',
            strip_codes(
                Colr().red().bggreen().bright('hello world')
            ),
            msg=test_msg('Failed to strip codes from chained Colr string.'))

        self.assertEqual(
            'hello world',
            strip_codes(
                Colr('hello world').rainbow()
            ),
            msg=test_msg('Failed to strip codes from Colr.rainbow string.'))
コード例 #15
0
def saveImageForSearch(dir_path, filename):
    global colors
    i = 0
    line = 5

    width = getWidth(searchFile(dir_path, filename))
    height = getHeight(searchFile(dir_path, filename))

    #print(f"{width} -> {height}")

    image = Image.new('RGB', (width, height), color='white')
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype('bahnschrift.ttf', 18)

    for root, dirs, files in os.walk(dir_path):
        for file in files:
            if filename in file:
                if i == len(colors):
                    i = 0
                draw.text((5, line),
                          os.path.join(root, file),
                          fill=colors[i],
                          font=font)
                i += 1
                line += 22

    filename = "DTG_CMD_" + str(dt.now().year) + str(dt.now().month) + str(
        dt.now().day) + "_" + str(dt.now().hour) + str(dt.now().minute) + str(
            dt.now().second) + str(dt.now().microsecond) + '.png'

    image.save(filename)
    print(color("Image saved successfully as " + filename + ".", fore='green'))
    image.show(command='display')
コード例 #16
0
def display_departures(station_name, limit=10, mode=None):
    station_name = get_station_name(station_name)
    departuresJSON = get_departures_by_name(station_name)
    departures = []
    if mode is not None:
        for d in departuresJSON:
            if mode.upper() in d['product']:
                departures += [Departure(d)]
    else:
        departures = [Departure(i) for i in departuresJSON]

    departures = departures[:limit]

    print('\nStation: ' + station_name + '\n')

    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_cols_dtype(['t', 't', 'i'])
    table.set_cols_align(['l', 'l', 'r'])

    rows = []
    rows.append([
        '\x1b[38;5;231m\x1b[48;5;23mline\x1b[0m', 'destination',
        'departure (min)'
    ])
    for dep in departures:
        rows.append([
            dep.get_label_colored(), dep.destination,
            dep.departure_time_minutes
        ])
    table.add_rows(rows)
    print(color(table.draw(), fore=MVG_FG, back=MVG_BG))
コード例 #17
0
def main(argd):
    """ Main entry point, expects doctopt arg dict as argd. """
    if argd['--color']:
        enable()
    maxwidth = get_terminal_size()[0]

    testfuncs = []
    userargs = argd['NAME'] or ['.+']
    for namearg in userargs:
        testfuncs.extend(find_tests(namearg))
    if not testfuncs:
        raise InvalidArg('No tests found with: {}'.format(', '.join(
            a for a in userargs)))

    print('Running {}'.format(color(VERSIONSTR, fore='red', style='bright')))

    test_args = {
        'display_test_name_data': {
            'width': maxwidth // 20,
            'namewidth': 20
        },
    }

    for func in sorted(testfuncs, key=lambda f: f.__name__):
        customargs = test_args.get(func.__name__, {'maxwidth': maxwidth})
        func(**customargs)

    if disabled():
        print('\nColr was disabled.')
    return 0
コード例 #18
0
ファイル: Model.py プロジェクト: justinwei2/traffic
    def display(self, flush=True):
        self.elapseTime.append(self.clock)
        width = 6
        empty = "___"
        empty += " " * (width - len(empty))

        str_rep = "\033c\r" if flush else ""
        occupancy_rate = ""
        wait_rate = ""
        for slot in self.slots[:self.n_slots]:
            if slot.entity:
                temp = str(slot.entity.id)
                temp = temp + " " * (width - len(temp))
                gradient = 255 - min(
                    int(
                        max(0, slot.entity.time_to_move) * Entity.lambda_ *
                        255 / 2), 255)
                str_rep += color(temp, fore=(gradient, 0, 0))
            else:
                str_rep += empty

        for i in range(self.n_slots):
            occ = 100 * self.occupancy[i] / sum(self.occupancy) if sum(
                self.occupancy) != 0 else 0
            self.percentOcc[i].append(occ)
            temp = "{0:.2f}".format(occ)
            occupancy_rate += temp + " " * (width - len(temp))
            wait = 100 * self.wait_time[i] / self.occupancy[
                i] if self.occupancy[i] != 0 else 0
            self.percentWait[i].append(wait)
            temp = "{0:.2f}".format(wait)
            wait_rate += temp + " " * (width - len(temp))
        print(str_rep + "\n" + occupancy_rate + "\n" + wait_rate + "\n")

        self.numOccCells.append(self.num_occupied)
コード例 #19
0
    def __colourise__(self, help_str):
        r = help_str
        for title in [
                'Options', 'Description', 'Examples', 'Legend', 'Synopsis'
        ]:
            r = r.replace(
                title,
                color(title,
                      fore=self.template['theme']['colors']['titles']['fg'],
                      style='bright'))

        for highlight in self.template['theme']['colors']['highlight']:
            r = r.replace(
                highlight['text'],
                color(highlight['text'], fore=highlight['fg'], style='bright'))
        return r
コード例 #20
0
def Controls():
    print("\n")
    print(color("CONTROLS MAIN MENU:", fore=green))
    print(color("Blue -> Vector (you)", fore=blue))
    print(color("Brown -> doors that lead to exit", fore=brown))
    print(color("Purple -> Storyline", fore=purple))
    print(color("Darkbrown & Orange -> Level 1", fore=orange, back=darkbrown))
    print(color("Cyan -> Level 2", fore=cyan))
    print(color("Grey -> Level 3", fore=dimgrey))
    print(color("Gold & orange -> Level 4", fore=orange, back=gold))
    print(color("Red -> Level 5 (Boss fight)", fore=red))
    print("\n")
    ENTERING_MAIN_MENU()
コード例 #21
0
 def write(self, wait_after_wait=1.0 / 36.0):
     if self.test:
         from colr import color
         print(''.join(
             color('  ', back=(x[0], x[1], x[2])) for x in self.leds))
     else:
         self.leds.write()
     time.sleep(wait_after_wait)
コード例 #22
0
def generateTree(path):
    global colors
    i = 0
    text = ""

    for root, dirs, files in os.walk(path):
        root = root.replace(path, "")
        # count the seperator -> it tells the level
        level = root.count(os.sep)

        if level == 0:
            text += color(path + "\n", fore='brown')
            for file in files:
                text += color("  " * level + "|---", 'brown')
                text += color(file + "\n", colors[i])
                i += 1

        else:
            text += color("|" + "----" * level + root + "\n",
                          fore='brown',
                          style='bright')
            for file in files:
                if i == len(colors): i = 0
                text += color("|" + "  " * level + "|----", 'brown')
                text += color(file + "\n", colors[i])
                i += 1

        text += color("|\n", fore='brown')
    return text
コード例 #23
0
def terminal_led(dmx_data):
    """
    Send the LED sequence to the terminal for emulation
    """
    cursor.hide()
    vumeter = ""
    for i in range(0, len(dmx_data), 3):
        vumeter = vumeter + color("█", fore=(dmx_data[i:i + 3]))
    print("\r[" + vumeter + "]", end="")
コード例 #24
0
 def __init__(self, time_index=1, logging=True):
     self.time_index = time_index
     self.prediction_market = PredictionMarketAdapter()
     self.logging = logging
     self.account = ACCOUNT_0
     if self.logging:
         print(
             color('Oracle : Aggregate consumption data oracle.',
                   fore='595959'))
コード例 #25
0
def print_ranks(ranks):
    for queue in ranks:
        queue_type = queue[0]
        tier = queue[1][0]
        rank = queue[1][1]
        lp = queue[1][2]
        print(
            color('{}: {} {} - {}LP'.format(queue_type, tier, rank, lp),
                  back='blue'))
コード例 #26
0
def Controls_Level_1():
    print("\n")
    print(color("CONTROLS LEVEL 1:", fore=green))
    print(color("Pink -> Vector", fore=pink))
    print(color("Grey -> wall", fore=dimgrey))
    print(color("Brown -> wood bucket", fore=brown))
    print(color("Gold -> sand", fore=gold))
    print(color("Blue -> Water", fore=water))
    print(color("Red -> fire", fore=red))
    print(color("Purple -> flag", fore=purple))
    print("\n")
コード例 #27
0
def Controls_Level_2():
    print("\n")
    print(color("CONTROALE NIVEL 2:", fore=purple))
    print(color("Roz -> Vector", fore=pink))
    print(color("Rosu -> Prima atingere", fore=red))
    print(color("Albastru -> A doua atingere", fore=blue))
    print(color("Verde -> Stare normala", fore=green))
    print(color("Gri -> Perete", fore=dimgrey))
    print(color("Galben -> Placa de presiune", fore=gold))
    print(color("Alb -> Piatra de temelie", fore=white))
    print("\n")
コード例 #28
0
def Controls_Level_1():
    print("\n")
    print(color("CONTROALE NIVEL 1:", fore=green))
    print(color("Roz -> Vector", fore=pink))
    print(color("Gri -> Perete", fore=dimgrey))
    print(color("Maro -> Galeata maro", fore=brown))
    print(color("Galben -> Nisip", fore=gold))
    print(color("Albastru -> Apa", fore=water))
    print(color("Rosu -> Foc", fore=red))
    print(color("Mov -> Cheie catre gradina castelului", fore=purple))
    print("\n")
コード例 #29
0
    def show_meta(self, trait_data, indent):
        meta = ArgsDict({k: v for k, v in trait_data._asdict().items() \
                if k not in 'traits'})
        if len(meta) < 3:
            return

        self.seperator(indent)

        for k, v in sorted(meta.items()):
            self.columns(indent, color(k, style='bright'), v)
コード例 #30
0
def display_title_bar():
    """ Print a title bar. """

    color_it_mvg = lambda x: color(x, fore=MVG_FG, back=MVG_BG)
    bar_mvg_colored = color_it_mvg("*" * 48)
    fifteen_stars = "*" * 15

    print(bar_mvg_colored)
    print(color_it_mvg(fifteen_stars + " MVG - Departures " + fifteen_stars))
    print(bar_mvg_colored + "\n")
コード例 #31
0
def kuaishouURL(id='WJKGYL_0921', flag=False, debug=False):
    '''
    @tips { 获取某个`id`用户的作品 }
    @parmas {str} - id
    @parmas {bool} - flag 是否生成 `markdown` 文件
    @parmas {bool} - debug 调试
    @retrun {list}
  '''
    if debug:
        print('GET:', color(_api + id, fore="red"))
    if not id:
        print(color('请输入用户id', fore="green"))
        exit()
    _r = requests.get(_api + id, headers=_headers)
    data_obj = str2JSON(_r.text)

    _key = '$ROOT_QUERY.publicFeeds({"count":24,"pcursor":"","principalId":"' + id + '"})'

    _lists = data_obj[_key]
    if not len(_lists['list']):
        print(color('  => 获取失败,对方可能没有作品或者`id`错误', fore='red'))
        return []
    _result = []
    for _index, _list in enumerate(_lists['list']):
        _now = _key + '.list.' + str(_index)
        _result.append(data_obj[_now])
    if debug:
        '''
      @tips 打印获取的数据,方便测试
    '''
        _fs = open(_Path('env', debug=True), 'w+')
        _fs.write(json.dumps(_result))
    _INFO = data_obj['User:'******'''
      @tips 将用户信息写入 `.md` 文件
    '''
        markdown(_INFO)

    return {
        "result": _result,
        "path": _INFO['name']
    }
コード例 #32
0
ファイル: run.py プロジェクト: welbornprod/colr
def main(argd):
    """ Main entry point, expects doctopt arg dict as argd. """
    print('Running {}'.format(color(VERSIONSTR, fore='red', style='bright')))

    justify_tests()
    join_tests()
    gradient_override_tests()
    gradient_mix_tests()
    rainbow_tests()

    if disabled():
        print('\nColr was disabled.')
    return 0