def print_table(table): # Print colorized counts for each status # Do not print if count is 0 headers = list() cells = list() global retval ths = table.find_all('th') tds = table.find_all('td') for th in ths: headers.append(th.getText()) for td in tds: cells.append(td.getText()) results = dict(zip(headers,cells)) for key, val in results.items(): if key in ("Up Ok") and val != "0": print "{0}: {1}".format(key, green(val)) elif key in ("Down Critical") and val != "0": print "{0}: {1}".format(red(key), red(val)) retval = 2 elif key in ("Warning") and val != "0": print "{0}: {1}".format(key, yellow(val)) retval = 1 elif key in "Pending" and val != "0": print "{0}: {1}".format(key, val) elif key in ("Unreachable Unknown") and val != "0": print "{0}: {1}".format(key, val) retval = 3 else: continue
def abort(msg): """ Abort execution, print ``msg`` to stderr and exit with error status (1.) This function currently makes use of `SystemExit`_ in a manner that is similar to `sys.exit`_ (but which skips the automatic printing to stderr, allowing us to more tightly control it via settings). Therefore, it's possible to detect and recover from inner calls to `abort` by using ``except SystemExit`` or similar. .. _sys.exit: http://docs.python.org/library/sys.html#sys.exit .. _SystemExit: http://docs.python.org/library/exceptions.html#exceptions.SystemExit """ from fabric.state import output, env if not env.colorize_errors: red = lambda x: x else: from colors import red if output.aborts: sys.stderr.write(red("\nFatal error: {0!s}\n".format(_encode(msg, sys.stderr)))) sys.stderr.write(red("\nAborting.\n")) if env.abort_exception: raise env.abort_exception(msg) else: # See issue #1318 for details on the below; it lets us construct a # valid, useful SystemExit while sidestepping the automatic stderr # print (which would otherwise duplicate with the above in a # non-controllable fashion). e = SystemExit(1) e.message = msg raise e
def add_floating_ip(self, server): ips = self.client.floating_ips.findall(instance_id=None) if ips: print "Assigning floating IP." server.add_floating_ip(ips[0]) return print red("No more floating IPs available! Skipping assignment.")
def __init__(self, loggerName , logFile, globalLogLevel): self.__logFile = logFile self.__logFileMaxSize = None self.__loggerName = loggerName # create logger obj self.__logger = logging.getLogger(self.__loggerName) if globalLogLevel == LOGLEVEL[0]: self.__logger.setLevel(logging.DEBUG) elif globalLogLevel == LOGLEVEL[1]: self.__logger.setLevel(logging.INFO) elif globalLogLevel == LOGLEVEL[2]: self.__logger.setLevel(logging.WARN) elif globalLogLevel == LOGLEVEL[3]: self.__logger.setLevel(logging.ERROR) else: print red('log level :{logLevel} set error!'.format(logLevel = globalLogLevel)) sys.exit() self.__fileHandler = logging.FileHandler(self.__logFile) self.__fileHandler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s: %(message)s') self.__fileHandler.setFormatter(formatter) self.__logger.addHandler(self.__fileHandler)
def initdomain(self): print red(''' INIT CONFIG FILES. ''') domain_name = self.bind_deployschema.schema_name cmdbobserver = XMLCMDBObserver() domain_dict = {} host_ip_dict = {} for host in cmdbobserver.getHostlist(): ipaddrs = {'bindPrivateIP' : []} ethernets = host.findall('./Hardware/EthernetIF') for ethernet in ethernets: if ethernet.attrib['bindPrivateIP']: ipaddrs['bindPrivateIP'].append(ethernet.attrib['bindPrivateIP']) if ethernet.attrib['bindPublicIP']: ipaddrs['bindPublicIP'] = ethernet.attrib['bindPublicIP'] host_ip_dict[host.attrib['name']] = ipaddrs domain_dict[host.attrib['name']] = host.attrib['name'] + '.' + domain_name + '.com' print "init domain name and hostname config... \n" jsondata = json.dumps(domain_dict) with open(DOMAIN_FILE, 'w+') as f: f.write(jsondata) time.sleep(1) print "init ip node..." j = json.dumps(host_ip_dict) with open(HOST_IP_FILE, 'w+') as f: f.write(j) time.sleep(1)
def check_option(cp, src, dst): def has_explicit_option(section, key): # David tried to avoid poking into cp's guts in https://rbcommons.com/s/twitter/r/1451/ but # that approach fails for the important case of boolean options. Since this is a ~short term # tool and its highly likely its lifetime will be shorter than the time the private # ConfigParser_sections API we use here changes, it's worth the risk. if section == 'DEFAULT': # NB: The 'DEFAULT' section is not tracked via `has_section` or `_sections`, so we use a # different API to check for an explicit default. return key in cp.defaults() else: return cp.has_section(section) and (key in cp._sections[section]) def sect(s): return cyan('[{}]'.format(s)) src_section, src_key = src if has_explicit_option(src_section, src_key): if dst is not None: dst_section, dst_key = dst print('Found {src_key} in section {src_section}. Should be {dst_key} in section ' '{dst_section}.'.format(src_key=green(src_key), src_section=sect(src_section), dst_key=green(dst_key), dst_section=sect(dst_section)), file=sys.stderr) elif src not in notes: print('Found {src_key} in section {src_section} and there is no automated migration path' 'for this option. Please consult the ' 'codebase.'.format(src_key=red(src_key), src_section=red(src_section))) if (src_section, src_key) in notes: print(' Note for {src_key} in section {src_section}: {note}' .format(src_key=green(src_key), src_section=sect(src_section), note=yellow(notes[(src_section, src_key)])))
def abort(msg): """ Abort execution, print ``msg`` to stderr and exit with error status (1.) This function currently makes use of `sys.exit`_, which raises `SystemExit`_. Therefore, it's possible to detect and recover from inner calls to `abort` by using ``except SystemExit`` or similar. .. _sys.exit: http://docs.python.org/library/sys.html#sys.exit .. _SystemExit: http://docs.python.org/library/exceptions.html#exceptions.SystemExit """ from fabric.state import output, env if not env.colorize_errors: red = lambda x: x else: from colors import red if output.aborts: sys.stderr.write(red("\nFatal error: %s\n" % _encode(msg, sys.stderr))) sys.stderr.write(red("\nAborting.\n")) if env.abort_exception: raise env.abort_exception(msg) else: sys.exit(1)
def sshdo(args, sshdo_dir): servers = raw_input('Servers: ') command = raw_input('Command: ') #if not os.path.exists('logs'+datetime): os.makedirs('logs/'+datetime) if not os.path.exists("{0}/logs/{1}".format(sshdo_dir, log_dir)): os.makedirs("{0}/logs/{1}".format(sshdo_dir, log_dir)) list = server_list(servers) fail_to_connect = [] for host in list: try: ssh.connect(host, username='******', allow_agent=True, timeout=5) except Exception: print red(host + "\n Could not connect \n") fail_to_connect.append(host) else: # log_f = open('logs/'+datetime+'/'+host+'.log', 'w') log_f = open("{0}/logs/{1}/{2}.log".format(sshdo_dir, log_dir, host), 'w') log_f.write(command+"/n/n") if args.debug: paramiko.util.log_to_file("{0}/logs/debug.log".format(sshdo_dir)) print green("\n" + host + "\n") stdin, stdout, stderr = ssh.exec_command(command) for data_line in stdout: print data_line.rstrip() log_f.write(data_line) log_f.close() ssh.close() if len(fail_to_connect) > 0: print red("Failed to connect to these hosts %s" % (fail_to_connect)) print "Log files are in logs/%s" % (log_dir) return
def sshget(): #prompt for info servers = raw_input('Servers: ') remote_file = raw_input('Remote File: ') local_dir = raw_input('Local Drop Directory: ') remote_base_file = os.path.basename(remote_file) list = server_list(servers) fail_to_connect = [] for host in list: try: ssh.connect(host, username='******', allow_agent=True, timeout=5) except Exception: print red(host + "\n Could not connect \n") fail_to_connect.append(host) else: print green("\n" + host + "\n") local_file = local_dir + host + "." + remote_base_file sftp = ssh.open_sftp() sftp.get(remote_file,local_file) ssh.close() if len(fail_to_connect) > 0: print red("Failed to connect to these hosts %s" % (fail_to_connect)) return "sshget"
def sshput(): print "sshput block" #prompt for info servers = raw_input('Servers: ') local_file = raw_input('Local File or Direcotry: ') remote_dir = raw_input('Remote Location: ') remote_base_file = os.path.basename(local_file) remote_file = remote_dir + remote_base_file list = server_list(servers) fail_to_connect = [] for host in list: try: ssh.connect(host, username='******', allow_agent=True, timeout=5) except Exception: print red(host + "\n Could not connect \n") fail_to_connect.append(host) else: print green("\n" + host + "\n") sftp = ssh.open_sftp() sftp.put(local_file,remote_file,confirm=True) ssh.close() if len(fail_to_connect) > 0: print red("Failed to connect to these hosts %s" % (fail_to_connect)) return "sshput"
def addError(error_seq_string,base,is_error=False): """Either changes the base to be an error or not if is_error is false and adds it to the error sequence (in red) >>> addError('','G',False) 'G' >>> addError('A','A',False) 'AA' """ """Either adds the unchanged base to the error string or chooses a random base to add depending on is_error :param str error_seq_string: :param str base: the current base in the sequence, either remains unchanged or gets changed to a random other base :param boolean is_error: defaults false, if true, adds a random base to the error_seq_string, else adds base :return: str error_seq_string: modified error sequence """ if is_error: #There's an error! Pick a base from a set of three not including the base that needs to change error_base = 'AGCTAG' error_base_index = random.randint(0,2) if base == 'T': #Add the new, error base to the error string out of the first set error_seq_string += red(error_base[error_base_index],style = 'bold') elif base == 'A': #The '+ 1' is checking the second set of three bases error_seq_string += red(error_base[error_base_index + 1],style = 'bold') elif base == 'G': error_seq_string += red(error_base[error_base_index + 2],style = 'bold') elif base == 'C': error_seq_string += red(error_base[error_base_index + 3],style = 'bold') else: error_seq_string += base return error_seq_string
def print_msg(code, msg): if code == -1: print red("[ERROR]\t" + msg) elif code == 1: print yellow("[WARNING]\t"+msg) else: print green("[INFO]\t" + msg)
def main(argv): # Parse the username, hostname, and keyfile from the command line arguments username, hostname = argv[1].split('@') keyfile = argv[2] # Construct an SSH connection ssh = SSHConnection(hostname, username, keyfile) ssh.connect() # Run an interactive prompt, until the user enters an empty line or closes the input stream print colors.red(ssh.read()) while True: try: command_to_run = raw_input('> ') except EOFError: command_to_run = '' if command_to_run.strip() == '': break ssh.send(command_to_run + '\n') print colors.red(ssh.read()) # Cleanly close the SSH connection exit_status = ssh.disconnect() return exit_status
def add_error(error_seq_string, base, is_error=False): """Either changes the base to be an error or not. Adds to error_seq_string >>> add_error('', 'G', False) 'G' >>> add_error('A', 'A', False) 'AA' 'Either adds the unchanged base to the error string or chooses a random base to add :param str error_seq_string: Current error string :param str base: current base in the sequence, either unchanged or gets changed to a random base :param boolean is_error: defaults false :return: str error_seq_string: modified error sequence' """ # asserttrue for both doctest and unittest put acceptable answers in a list if is_error: # There's an error! Picks base from set of three not including the base that needs to change error_base = 'AGCTAG' error_base_index = random.randint(0, 2) if base == 'T': # Add the new, error base to the error string out of the first set error_seq_string += red(error_base[error_base_index], style='bold') elif base == 'A': # The '+ 1' is checking the second set of three bases error_seq_string += red(error_base[error_base_index + 1], style='bold') elif base == 'G': error_seq_string += red(error_base[error_base_index + 2], style='bold') elif base == 'C': error_seq_string += red(error_base[error_base_index + 3], style='bold') else: error_seq_string += base return error_seq_string
def parse_expr(expr): tokens_list = [] tokens = [] token_val = "" last_token = None for elem in expr: if elem in operator_table.ops and elem != "@": if token_val != "": tokens.append(token_val) token_val = "" if elem == "-" and (last_token in operator_table.ops or last_token == None): tokens.append("-1") tokens.append("@") last_token = "a" pass elif elem == "+" and (last_token in operator_table.ops or last_token == None): tokens.append("1") tokens.append("@") last_token = "a" pass else: tokens.append(elem) elif elem in " \t\n": if token_val != "": tokens.append(token_val) token_val = "" elif elem.isdigit() or elem.isalpha() or elem in "_.": token_val = token_val + elem elif elem == "#": break elif elem == ";": if token_val != "": tokens.append(token_val) tokens_list.append(tokens) tokens = [] token_val = "" last_token = None else: print colors.red("(error) token {") + colors.yellow(elem) + colors.red("} is not a valid token") return [] last_token = elem if token_val != "": tokens.append(token_val) token_val = "" tokens_list.append(tokens) return tokens_list
def fetch_command(cmd, **kwargs): if cmd == "--help": print "usage: stackctl [--help] <command> [<args>, --force]\n" print tabulate([[name, cmd.__doc__ ] for name, cmd in CMDS.iteritems()]) elif cmd in CMDS: return CMDS[cmd](**kwargs) else: print red("'{}' is not a valid command.".format(cmd))
def import_missing(module): exctype, exc = sys.exc_info()[:2] print red('Error:', bold=True), 'Missing module', module print str(exc) print 'To fix the issue please run:' print '$', white('sudo pip install %s' % module, bold=True) sys.exit(1)
def execute(self, *args): self.valid_args(args) self.flags = self.extract_flags(args) self.nova = NovaWrapper() if self.needs_auth else None if 'force' in self.flags or self.safety_check(*args): self.run(*args) else: print red("Cancelled.")
def genCfg(): # init a cfg obj try: cfg = ConfigParser.ConfigParser() cfg.read('../conf/crawler.ini') return cfg except Exception, e: print red(sys.exec_info())
def run(self, *args): servers = self.nova.servers() for server in self.nova.servers(): # TODO: Add the IPs of each instance. if server.status == u"ACTIVE": print green(server.name) else: print red(server.name) return servers
def __init__(self, xml_file_path=""): if xml_file_path=="" or xml_file_path ==None: print red("please add xml file path.") if not os.path.exists(xml_file_path): print red("xml file is not exists! please check over it!") self.xml_file_path = xml_file_path
def program(sharefile, config): target_month = raw_input('[VHL ROBOT] Enter target month: ') team_leaders = [leader for leader in sharefile.list('Team Leaders/Monthly Paperwork')] if not team_leaders: print(red('[VHL ROBOT] Could not find team leader files. Quitting.')) return alphabet_segments = sharefile.list('Dependent E-Files') alphabet_segments = {key: value for key, value in alphabet_segments.iteritems() if len(key) == 3} for indexed_team_leader in enumerate(team_leaders): print('[VHL ROBOT] [%d] %s' % indexed_team_leader) input_recognized = False while not input_recognized: indices = raw_input('[VHL ROBOT] Enter team leaders (space separated), or Ctrl-C to quit: ') try: indices = [int(index) for index in indices.rstrip().split(' ')] input_recognized = True except: print(red('[VHL ROBOT] Could not parse input...')) for index in indices: target_folder = 'Team Leaders/Monthly Paperwork/%s/%s' % (team_leaders[index], target_month) print('[VHL ROBOT] Searching "%s"' % target_folder) month = sharefile.list(target_folder) for filename in month: if filename.find('VHL') == -1: print(blue('[VHL ROBOT] "%s" does not seem to be a VHL file' % filename)) continue try: pieces = filename.split() if not (len(pieces) == 4): raise Error child_name = pieces[2] print('[VHL ROBOT] "%s" is a VHL file for child %s' % (filename, child_name)) except: print(blue('[VHL ROBOT] "%s" might be a VHL file with a nonstandard name. Ignoring it.' % filename)) continue found = False for segment in alphabet_segments: range_pair = segment.split('-') if child_name[0] >= range_pair[0] and child_name[0] <= range_pair[1]: found = True item = filename source = 'Team Leaders/Monthly Paperwork/%s/%s' % (team_leaders[index], target_month) destination = 'Dependent E-Files/%s/%s/CASA Internal Documents' % (segment, child_name[:-1] + ' ' + child_name[-1]) sharefile.copy(item, source, destination, ' '.join(filename.split()[1:])) if not found: print(red('[VHL ROBOT] Could not alphabetize %s in %s', child_name, str(alphabet_segments)))
def islink(self, path): try: sftp = self.connection.open_sftp() try: return sftp.readlink(path) except IOError: return False sftp.close() except EOFError: print red("open sftp failed.")
def unlink(self, link_target): try: sftp = self.connection.open_sftp() try: sftp.unlink(link_target) print green("unlink success") except IOError: print red("assume path is a folder(directory).") except EOFError: print red("open sftp failed.")
def check_ssh_connect(self): self.connection.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: self.connection.connect(self.server_info['hostname'], username=self.server_info['username'], password=self.server_info['password'], port=self.server_info['port']) return True except paramiko.SSHException: print red("Connection Failed.") quit()
def addLog(self, message, logLevel): if logLevel == LOGLEVEL[0]: self.__logger.debug(message) elif logLevel == LOGLEVEL[1]: self.__logger.info(message) elif logLevel == LOGLEVEL[2]: self.__logger.warn(message) elif logLevel == LOGLEVEL[3]: self.__logger.error(message) else: print red('you arg logLevel: {level} is not valid!'.format(level = logLevel))
def compile_to_rpn(tokens): operator_stack = [] rpn_code = [] for token in tokens: if is_num(token): rpn_code.append(token) elif token == "(": operator_stack.append(token) elif token == ")": try: while True: current_operator = operator_stack.pop() if current_operator == "(": break rpn_code.append(current_operator) except IndexError: print colors.red("(error) mismatched parens") return elif token in operator_table.ops: while len(operator_stack) > 0 and ((operator_table.ops[token][2] == "left" and operator_table.ops[token][1] <= operator_table.ops[operator_stack[-1]][1]) or (operator_table.ops[token][2] == "right" and operator_table.ops[token][1] < operator_table.ops[operator_stack[-1]][1])): operator = operator_stack.pop() if operator != "(": rpn_code.append(operator) else: operator_stack.append("(") break operator_stack.append(token) else: rpn_code.append(token) while len(operator_stack) > 0: operator = operator_stack.pop() if operator == "(": print colors.red("(error) mismatched parens") return [] rpn_code.append(operator) return rpn_code
def check_md5(self): global rmd5sum def md5_checksum(file_path): with open(file_path, 'rb') as fh: m = hashlib.md5() while True: data = fh.read(8192) if not data: break m.update(data) return m.hexdigest() try: sftp = self.connection.open_sftp() local_path = os.path.join(self.server_info['local_path'], self.server_info['release_version']) ok_number = 0 file_number = 0 for (dirname, subdir, subfile) in os.walk(local_path): remote_path = os.path.join(self.server_info['remote_path'], self.server_info['release_version'], dirname[len(local_path)+1:]) for fname in subfile: file_abs_path = (os.path.join(dirname, fname)) lmd5sum = md5_checksum(file_abs_path) file_number += 1 remote_file_abs_path = (os.path.join(remote_path, fname)) try: command = "md5sum %s | awk '{print $1}'" % remote_file_abs_path stdin, stdout, stderr = self.connection.exec_command(command) for line in stdout.readlines(): rmd5sum = line.strip('\n') if lmd5sum != rmd5sum: print red("%s md5sum check failed.") % fname else: ok_number += 1 except Exception: print red("%s is not exsits.") % fname print green("The File number is %d md5sum check %d is OK") % (file_number, ok_number) sftp.close() except Exception as e: print ('*** caught exception: %s: %s' % (e.__class__, e)) traceback.print_exc() # try: # sftp.close() # except: # pass sys.exit(1)
def followUser(self, userid): # Get rand user and login randindex = randint(1, len(self.alluser)) randloginuser = self.Login.retrieveIndividual(randindex) self.Login.removeIndividual(randloginuser) api.loginUser(randloginuser['email'], randloginuser['password']) # Follow user api.followUser(userid) print(red("Follow - " + randloginuser['firstname'] + " followed Stephen")) self.numoffollower+=1 print(red("Follow - Followers: " + str(self.numoffollower))) api.logoutUser() self.show = True
def checkSSL(a): """Get SSL Cert CN""" # Return None because we can't navigate to a CIDR for ssl. if "/" in a: print red("[!] Viper can't get certicate information for a CIDR! Supply a hostname or single IP.") return None else: next try: # Connect over port 443. cert = ssl.get_server_certificate((a, 443)) except Exception, e: # If it can't connect, return nothing/fail return None
def printMap(self): for y in range(0, self.height): print("") for x in range(0, self.width): if (self.tiles[x][y].color == "cyan"): sys.stdout.write(cyan(self.tiles[x][y].type)) elif (self.tiles[x][y].color == "white"): sys.stdout.write(white(self.tiles[x][y].type)) elif (self.tiles[x][y].color == "green"): sys.stdout.write(green(self.tiles[x][y].type)) elif (self.tiles[x][y].color == "yellow"): sys.stdout.write(yellow(self.tiles[x][y].type)) elif (self.tiles[x][y].color == "blue"): sys.stdout.write(blue(self.tiles[x][y].type)) elif (self.tiles[x][y].color == "magenta"): sys.stdout.write(magenta(self.tiles[x][y].type)) elif (self.tiles[x][y].color == "red"): sys.stdout.write(red(self.tiles[x][y].type)) elif (self.tiles[x][y].colorX != None): sys.stdout.write( color(self.tiles[x][y].type, self.tiles[x][y].colorX)) else: sys.stdout.write(self.tiles[x][y].type)
def test_req_one_two(driver): print("Test: Delete Attraction test.") driver.get("http://" + ip + ":12345/attractions/") driver.get("http://" + ip + ":12345/edit_attraction/") driver.execute_script( "localStorage.setItem('edited', JSON.stringify({lat:31.2625444444,lng:34.8019111199}));" ) first = driver.current_url # needs to be http://10.0.0.6:12345/edit_attraction/ # driver.find_element_by_id('delete_point').click() driver.execute_script("document.querySelector('#delete_point').click();") driver.get("http://" + ip + ":12345/attractions/") second = driver.current_url # needs to be http://10.0.0.6:12345/attractions/ bool1 = first == 'http://' + ip + ':12345/edit_attraction/' bool2 = second == 'http://' + ip + ':12345/attractions/' if bool1 and bool2: # if bool1: print(green('--- test passed!!! ---')) else: print(red('--- test failed!!! ---')) return
def choose(options, prompt = None, autoplay=None): prompt = prompt or '' autoplay = autoplay or False if autoplay: choice = random.choice(options) print(colors.negative("You chose %s from %s"%(choice, options))) else: choice = None while choice is None: try: if prompt != '' and prompt[-1]!=' ': prompt += ' ' print("%s(type a number then hit Enter)" % prompt) print("\n".join(["%i: %s" % (idx,option) for idx, option in enumerate(options)])) number = int(input("enter a number: ")) if number < 0 or number >= len(options): raise IndexError("INVALID INPUT: that number is not an option") choice = options[number] print(colors.negative("YOU CHOSE %s" % choice)) except Exception as e: print(colors.red('Invalid Input. Try again.')) the.load.choice=choice return choice
def main(): # TODO: Make it portable locations = [ "/usr/bin", "/bin"] current = set() # If `bin` does not exist create it first if not os.path.isdir(bin_dir): os.mkdir(bin_dir) for f in os.listdir(bin_dir): current.add(f) for f in os.listdir(tags_dir): basename = util.strip_whole_config(f) if not basename: continue if basename in current: print(" > " + basename + " is present in " + tags_dir) continue if not try_find(locations, basename): print(" > " + colors.red(basename + " not found anywhere"))
def test_req_one_eight_two(driver): print("Test: Delete Hint to attraction.") # print(get_length_from_url('http://10.0.0.6:12344/managementsystem/attraction/68/hint/')) driver.get("http://" + ip + ":12345/attractions/") driver.get("http://" + ip + ":12345/edit_attraction/") driver.execute_script( "localStorage.setItem('edited', JSON.stringify({lat:31.2625444444,lng:34.8019111199}));" ) first = driver.current_url # needs to be http://10.0.0.6:12345/edit_attraction/ editHintBTN = driver.find_element( By.CSS_SELECTOR, "#sideMenu > div.sidenav > a:nth-child(6)") editHintBTN.click() second = driver.current_url # needs to be http://10.0.0.6:12345/pick_hint_edit/ edHintBTN = driver.find_element( By.CSS_SELECTOR, "#sideMenu > div.sidenav > a:nth-child(4)") edHintBTN.click() delHintBTN = driver.find_element( By.CSS_SELECTOR, "#sideMenu > div.sidenav > a:nth-child(5)") delHintBTN.click() third = driver.current_url # needs to be http://10.0.0.6:12345/pick_hint_edit/ the_id = check_json_for_uc1p8p2('http://' + ip + ':12344/managementsystem/attraction/') driver.find_element_by_id('delete_chosen_hint').click() fourth = driver.current_url # needs to be http://10.0.0.6:12345/pick_hint_edit/ bool1 = first == 'http://' + ip + ':12345/edit_attraction/' bool2 = second == 'http://' + ip + ':12345/pick_hint_edit/' bool3 = third == 'http://' + ip + ':12345/pick_hint_edit/' bool4 = fourth == 'http://' + ip + ':12345/pick_hint_edit/' if bool1 and bool2 and bool3 and bool4: print(green('--- test passed!!! ---')) else: print(red('--- test failed!!! ---')) return
def uc1p2(driver): print("Use Case: Delete Attraction.") # number_of_points_start = get_length_from_url('http://'+ip+':12344/managementsystem/attraction/') driver.get("http://" + ip + ":12345/edit_attraction/") # point = driver.find_element(By.XPATH, "//*[@id='map']/div/div/div[1]/div[3]/div/div[3]/div[1]/img") # point.click() # driver.find_element_by_id('edit_attraction').click() driver.execute_script( "localStorage.setItem('edited', JSON.stringify({lat:31.2625444444,lng:34.8019111199}));" ) first = driver.current_url # needs to be http://10.0.0.6:12345/edit_attraction/ driver.execute_script("document.querySelector('#delete_point').click();") # second = driver.current_url # needs to be http://10.0.0.6:12345/attractions/ bool1 = first == 'http://' + ip + ':12345/edit_attraction/' # if bool1 and bool2: if bool1: print(green('--- test passed!!! ---')) else: print(red('--- test failed!!! ---')) return
def test_req_one_six_two(driver): print("Test: Delete American Question from attraction.") driver.get("http://" + ip + ":12345/attractions/") driver.get("http://" + ip + ":12345/edit_attraction/") driver.execute_script( "localStorage.setItem('edited', JSON.stringify({lat:31.2625444444,lng:34.8019111199}));" ) first = driver.current_url # needs to be http://10.0.0.6:12345/edit_attraction/ driver.find_element_by_id('edit_aqs').click() second = driver.current_url # needs to be http://10.0.0.6:12345/pick_aq_edit/ driver.find_element_by_id('want_to_delete_aq').click() driver.find_element_by_id('delete_chosen_aq').click() third = driver.current_url # needs to be http://10.0.0.6:12345/pick_aq_edit/ bool1 = first == 'http://' + ip + ':12345/edit_attraction/' bool2 = second == 'http://' + ip + ':12345/pick_aq_edit/' bool3 = third == 'http://' + ip + ':12345/pick_aq_edit/' if bool1 and bool2 and bool3: print(green('--- test passed!!! ---')) else: print(red('--- test failed!!! ---')) return
def uc1p8p3(driver): print("Use Case: Edit Hint to attraction.") # print(get_length_from_url('http://10.0.0.6:12344/managementsystem/attraction/68/hint/')) driver.get("http://" + ip + ":12345/attractions/") driver.get("http://" + ip + ":12345/edit_attraction/") # point = driver.find_element(By.XPATH, "//*[@id='map']/div/div/div[1]/div[3]/div/div[3]/div[1]/img") # point.click() # driver.find_element_by_id('edit_attraction').click() driver.execute_script( "localStorage.setItem('edited', JSON.stringify({lat:31.2625444444,lng:34.8019111199}));" ) first = driver.current_url # needs to be http://10.0.0.6:12345/edit_attraction/ driver.find_element_by_id('edit_hints').click() second = driver.current_url # needs to be http://10.0.0.6:12345/pick_hint_edit/ driver.find_element_by_id('editHintBTNmenu').click() third = driver.current_url # needs to be http://10.0.0.6:12345/pick_hint_edit/ driver.execute_script( "document.getElementById('edit_cb').selectedIndex = 0;") driver.find_element_by_id('edit_chosen_hint').click() fourth = driver.current_url # needs to be http://10.0.0.6:12345/edit_hint_edit/ # driver.execute_script("document.querySelector('#write_hint_id_to_edit').value='chuchuchi';") fifth = driver.current_url # needs to be http://10.0.0.6:12345/pick_hint_edit/ bool1 = first == 'http://' + ip + ':12345/edit_attraction/' bool2 = second == 'http://' + ip + ':12345/pick_hint_edit/' bool3 = third == 'http://' + ip + ':12345/pick_hint_edit/' #bool4 = fourth == 'http://' + ip + ':12345/edit_hint_edit/' bool4 = fourth == 'http://' + ip + ':12345/pick_hint_edit/' bool5 = fifth == 'http://' + ip + ':12345/pick_hint_edit/' if bool1 and bool2 and bool3 and bool4 and bool5: print(green('--- test passed!!! ---')) else: print(red('--- test failed!!! ---')) return
def uc3p1(driver): print("Use Case: Add Feedback Question.") driver.get("http://" + ip + ":12345/main/") c1 = make_check_uc2p123('http://' + ip + ':12344/managementsystem/feedback/') driver.find_element( By.CSS_SELECTOR, "#sideMenu > div.sidenav > button:nth-child(7)").click() driver.find_element( By.CSS_SELECTOR, "#sideMenu > div.sidenav > div:nth-child(8) > a:nth-child(1)").click() first = driver.current_url # needs to be http://10.0.0.1:12345/feedback/ driver.find_element_by_id('fbquestion').send_keys("how are you today?") driver.find_element(By.CSS_SELECTOR, "#feedback_type").click() driver.find_element(By.CSS_SELECTOR, "#feedback_type > option:nth-child(2)").click() driver.find_element(By.CSS_SELECTOR, "#send_feedback").click() second = driver.current_url # needs to be http://10.0.0.1:12345/main/ c2 = make_check_uc2p123('http://' + ip + ':12344/managementsystem/feedback/') bool1 = first == 'http://' + ip + ':12345/feedback/' bool2 = second == 'http://' + ip + ':12345/main/' bool3 = c1 + 1 == c2 if bool1 and bool2 and bool3: print(green('--- test passed!!! ---')) else: print(red('--- test failed!!! ---')) return
def main(proxy): global valid global invalid global retries code = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(6)) try: check = requests.get('https://prnt.sc/%s' % (code), headers=headers, proxies={'https': 'http://%s' % (proxy)}).text except: retries += 1 os.system('title [Lightshot Brute Force] - Scrape Screenshots ^| Checked: %s ^| Valid: %s ^| Invalid: %s ^| Retries: %s ^| CPM: %s' % (valid + invalid, valid, invalid, retries, cpm())) else: if 'name="twitter:image:src" content="' in check and not '0_173a7b_211be8ff' in check and not 'ml3U3Pt' in check: lock.acquire() sys.stdout.write('[%sVALID%s] https://prnt.sc/%s\n' % (green(), reset(), code)) lock.release() valid += 1 os.system('title [Lightshot Brute Force] - Scrape Screenshots ^| Checked: %s ^| Valid: %s ^| Invalid: %s ^| Retries: %s ^| CPM: %s' % (valid + invalid, valid, invalid, retries, cpm())) url = check.split('name="twitter:image:src" content="')[ 1].split('"/> <meta')[0] save(url) with open('Image Links.txt', 'a', encoding='UTF-8') as f: f.write('https://prnt.sc/%s\n' % (code)) else: lock.acquire() sys.stdout.write('[%sINVALID%s] https://prnt.sc/%s\n' % (red(), reset(), code)) lock.release() invalid += 1 os.system('title [Lightshot Brute Force] - Scrape Screenshots ^| Checked: %s ^| Valid: %s ^| Invalid: %s ^| Retries: %s ^| CPM: %s' % (valid + invalid, valid, invalid, retries, cpm()))
def uc1p3(driver): print("Use Case : Edit Attraction.") driver.get("http://" + ip + ":12345/edit_attraction/") # point = driver.find_element(By.XPATH, "//*[@id='map']/div/div/div[1]/div[3]/div/div[3]/div[1]/img") # point.click() # driver.find_element_by_id('edit_attraction').click() driver.execute_script( "localStorage.setItem('edited', JSON.stringify({lat:31.2625444444,lng:34.8019111199}));" ) first = driver.current_url # needs to be http://10.0.0.6:12345/edit_attraction/ driver.find_element_by_id('attr_name').send_keys(Keys.CONTROL, 'a') driver.find_element_by_id('attr_name').send_keys('this is a test') driver.find_element_by_id('desc').send_keys(Keys.CONTROL, 'a') driver.find_element_by_id('desc').send_keys('this is a test') driver.execute_script( "document.getElementById('attr_name').value='this is a test';") driver.execute_script( "document.getElementById('desc').value='this is a test';") driver.execute_script( "getRequestAttractions(getFieldsValuesOfExistingAttraction);" "finishEditingAttraction();") # submitButton = driver.find_element(By.CSS_SELECTOR, "body > div.paging > div > form > div.container > button:nth-child(11)") # submitButton.click() second = driver.current_url # needs to be http://10.0.0.6:12345/attractions/ bool1 = first == 'http://' + ip + ':12345/edit_attraction/' bool2 = second == 'http://' + ip + ':12345/attractions/' bool3 = check_json_for_uc1p3('http://' + ip + ':12344/managementsystem/attraction/') if bool1 and bool2 and bool3: print(green('--- test passed!!! ---')) else: print(red('--- test failed!!! ---')) return
def test_req_one_three(driver): print("Test: Edit Attraction test.") driver.get("http://" + ip + ":12345/attractions/") driver.get("http://" + ip + ":12345/edit_attraction/") driver.execute_script( "localStorage.setItem('edited', JSON.stringify({lat:31.2625444444,lng:34.8019111199}));" ) first = driver.current_url # needs to be http://10.0.0.6:12345/edit_attraction/ driver.find_element_by_id('attr_name').send_keys(Keys.CONTROL, 'a') driver.find_element_by_id('attr_name').send_keys('this is a test') driver.execute_script("document.querySelector('#saveEditBTN').click();") # submitButton = driver.find_element(By.XPATH, "/html/body/div[1]/div/form/div[2]/button[1]") # submitButton.click() second = driver.current_url # needs to be http://10.0.0.6:12345/attractions/ bool1 = first == 'http://' + ip + ':12345/edit_attraction/' bool2 = second == 'http://' + ip + ':12345/attractions/' if bool1 and bool2: print(green('--- test passed!!! ---')) else: print(red('--- test failed!!! ---')) return
def uc1p6p1(driver): print("Use Case: Add American Question to attraction.") driver.get("http://" + ip + ":12345/edit_attraction/") # point = driver.find_element(By.XPATH, "//*[@id='map']/div/div/div[1]/div[3]/div/div[3]/div[1]/img") # point.click() # driver.find_element_by_id('edit_attraction').click() driver.execute_script( "localStorage.setItem('edited', JSON.stringify({lat:31.2625444444,lng:34.8019111199}));" ) first = driver.current_url # needs to be http://10.0.0.6:12345/edit_attraction/ editAqBTN = driver.find_element( By.CSS_SELECTOR, "#sideMenu > div.sidenav > a:nth-child(5)") editAqBTN.click() second = driver.current_url # needs to be http://10.0.0.6:12345/pick_aq_edit/ addAqBTN = driver.find_element(By.CSS_SELECTOR, "#sideMenu > div.sidenav > a:nth-child(3)") addAqBTN.click() third = driver.current_url # needs to be http://10.0.0.6:12345/add_aq_edit/ driver.find_element_by_id('ques').send_keys('this is a test') driver.find_element_by_id('finish_add_aq_btn').click() # fourth = driver.current_url # needs to be http://10.0.0.6:12345/pick_aq_edit/ bool1 = first == 'http://' + ip + ':12345/edit_attraction/' bool2 = second == 'http://' + ip + ':12345/pick_aq_edit/' bool3 = third == 'http://' + ip + ':12345/add_aq_edit/' # bool4 = fourth == 'http://10.0.0.6:12345/pick_aq_edit/' bool5 = check_json_for_uc1p6p1('http://' + ip + ':12344/managementsystem/attraction/') # if bool1 and bool2 and bool3 and bool4: if bool1 and bool2 and bool3: # and bool5: print(green('--- test passed!!! ---')) else: print(red('--- test failed!!! ---')) return
def setup_database_conn(): """Function to setup the database connection to the Neo4j project containing the BloodHound data. """ try: database_uri = config_section_map("Database")["uri"] database_user = config_section_map("Database")["username"] database_pass = config_section_map("Database")["password"] print( yellow( "[!] Attempting to connect to your Neo4j project using {}:{} @ {}." .format(database_user, database_pass, database_uri))) neo4j_driver = GraphDatabase.driver(database_uri, auth=(database_user, database_pass)) print(green("[+] Success!")) return neo4j_driver except Exception: neo4j_driver = None print( red("[X] Could not create a database connection using the details provided in \ your database.config! Please check the URI, username, and password. Also, make sure your Neo4j \ project is running. Note that the bolt port can change sometimes.")) exit()
def uc2p4(driver): print("Use Case: Delete Point from Path.") c1 = make_check_uc2p4('http://' + ip + ':12344/managementsystem/track/') driver.get("http://" + ip + ":12345/main/") driver.find_element( By.CSS_SELECTOR, "#sideMenu > div.sidenav > button:nth-child(3)").click() driver.find_element( By.CSS_SELECTOR, "#sideMenu > div.sidenav > div:nth-child(4) > button:nth-child(3)" ).click() driver.find_element( By.CSS_SELECTOR, "#sideMenu > div.sidenav > div:nth-child(4) > div:nth-child(4) > a:nth-child(1)" ).click() second = driver.current_url # needs to be http://10.0.0.6:12345/edit_short_path/ driver.execute_script( "document.querySelector('#map > div > div > div:nth-child(1) > div:nth-child(3) > div > div:nth-child(3) > div:nth-child(1) > img').click();" ) driver.find_element(By.CSS_SELECTOR, "#delete_from_path_med").click() driver.get("http://" + ip + ":12345/main/") third = driver.current_url # needs to be http://10.0.0.6:12345/main/ bool2 = second == 'http://' + ip + ':12345/edit_short_path/' bool3 = third == 'http://' + ip + ':12345/main/' c2 = make_check_uc2p4('http://' + ip + ':12344/managementsystem/track/') bool4 = c1 - 1 == c2 if bool2 and bool3: #and bool4: print(green('--- test passed!!! ---')) else: print(red('--- test failed!!! ---')) return
def run(verbose=False): me = singleton.SingleInstance() logPrint("My PID is %d" % os.getpid()) playMusic('ping.mp3') logPrint(colors.blue("Starting!")) lastFail = 0 failCount = 0 keepRunning = True while keepRunning: try: with GateControl(verbose=verbose) as gateControl: keepRunning = gateControl.mainLoop() except: last_error = traceback.format_exc() logPrint(colors.bold(colors.red(last_error))) time.sleep(2) if 60 < (time.time() - lastFail): failCount = 1 else: failCount += 1 logPrint("System error %d" % failCount) lastFail = time.time() if MAX_FAILS_IN_A_ROW < failCount: reboot_system()
def regain_health(player_health, kibble): """Heal player using kibble :param player_health: an int :precondition: must be a positive integer :param kibble: an int :precondition: must be a positive integer :postcondition: increase player_health using kibble :return: two integers (player_health, kibble) """ if kibble != 0: if player_health < 9: player_health += 2 kibble -= 1 print( f'You ate a bit of kibble\nCurrent health: {colors.cyan(player_health)}' ) return player_health, kibble elif player_health == 9: player_health += 1 kibble -= 1 print( f'You ate a bit of kibble\nCurrent health: {colors.cyan(player_health)}' ) return player_health, kibble else: print( f'You are max health\nCurrent health: {colors.cyan(player_health)}' ) return player_health, kibble else: print(colors.red("You are out of kibble")) return player_health, kibble
def get_problem_input(n): if not os.path.exists(n+'.in') or (os.path.exists(n+'.in') and not open(n+'.in').read().strip()): link = 'https://adventofcode.com/' + event + '/day/' + n + '/input' data = requests.get(link, cookies=cookie).text if "Please don't repeatedly request this endpoint before it unlocks!" in data: print red('Input not available!', bg='black') else: with open(n+'.in', 'w') as f: f.write(data.strip('\n')) print green('Data saved in Input file '+n+'.in!', bg='black') else: print red('Input file '+n+'.in'+' already exits!', bg='black') template = open('../template.js', 'r').read() for l in ['A', 'B']: if not os.path.exists(n+l+'.js'): with open(n+l+'.js', 'w') as f: f.write(template.format(n)) print green('Javascrypt file '+n+l+'.js generated!', bg='black') else: print red('Javascrypt file '+n+l+'.js'+' already exits!', bg='black')
def join(self, token, server, proxy): headers = {'Authorization': token, 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36', 'Accept': '*/*',} try: join_server = session.post('https://discord.com/api/v6/invites/%s' % (server), headers=headers, proxies={'https': 'http://%s' % (proxy)}, timeout=4).text if 'You need to verify your account' in join_server: self.variables['completed'] += 1 self.write('%s[%s%s%s] Account not verified%s.' % (red(), reset(), strftime('%H:%M:%S', gmtime()), red(), reset())) elif 'Unauthorized' in join_server: self.variables['completed'] += 1 self.write('%s[%s%s%s] Invalid token%s.' % (red(), reset(), strftime('%H:%M:%S', gmtime()), red(), reset())) elif 'banned from this guild' in join_server: self.variables['completed'] += 1 self.write('%s[%s%s%s] User banned from this server%s.' % (red(), reset(), strftime('%H:%M:%S', gmtime()), red(), reset())) elif 'Maximum number of guilds reached' in join_server: self.variables['completed'] += 1 self.write('%s[%s%s%s] User already in 100 servers%s.' % (red(), reset(), strftime('%H:%M:%S', gmtime()), red(), reset())) elif '"vanity_url_code"' in join_server: self.write('%s[%s%s%s] %sSuccessfully Joined%s: %s' % (red(), reset(), strftime('%H:%M:%S', gmtime()), red(), green(), reset(), server)) self.variables['joined_tokens'].append(token) self.variables['joined'] += 1 self.variables['completed'] += 1 elif 'Access denied' in join_server: self.variables['retries'] += 1 self.join(token, server, choice(self.variables['proxies'])) else: self.variables['completed'] += 1 self.write('%s[%s%s%s] Error %s| %s%s' % (red(), reset(), strftime('%H:%M:%S', gmtime()), red(), reset(), red(), join_server)) except: self.variables['retries'] += 1 self.join(token, server, choice(self.variables['proxies']))
def wpscan(): os.system("clear") red() print(banner) blue() print("") purple() web = input("Web whith https:// -->> ") yellow() print("Do you want to save it on web.txt? y/n") if input("-->> ") == "y": os.system("wpscan --url " + web + ">> web.txt") red() print("Saved!!") time.sleep(1) while True: start_menu() else: os.system("wpscan --url " + web) red() input("Press INTRO to exit") while True: start_menu()
def __str__(self): return_str = red("[PYACS ERROR] Could not read: %s" % (self.file_name)) return (return_str)
def trailing(key, secret, pushover_user, pushover_app, pushbullet_token, redis_password): import sys, os, json, time, threading, requests, redis from datetime import datetime from bittrex import bittrex from pushover import send_pushover from pushbullet import send_pushbullet from colors import white, red, green, yellow from colorama import Fore, Back, Style, init try: r = redis.Redis(host='redis.pontstrader.com', port=6380, db=0, password=redis_password) except: white( 'Unable to connect to redis.pontstrader.com, trying redis2.pontstrader.com...' ) try: r = redis.Redis(host='redis2.pontstrader.com', port=6380, db=0, password=redis_password) except: white( 'Unable to connect to redis2.pontstrader.com... I am sorry but you can not continue now, please contact p0nts!' ) global messages try: messages except NameError: messages = {} else: pass white((40 * '-')) green(' T R A I L I N G S T O P L O S S') white((40 * '-')) while True: status_update = False gobuy = False try: threads = threading.enumerate() thread_counter = 0 for t in threading.enumerate(): if t.name.startswith('tsl-'): thread_counter += 1 if thread_counter > 0: yellow('There are currently {0} active tsl trade(s):'.format( thread_counter)) else: yellow('There are currently no active tsl trades') white( 'Would you like to make another tsl trade or check the status/history of your tsl trades?' ) green('1. New trade') yellow('2. Status / History') red('3. Back to Main Menu') try: yes_no = raw_input(Fore.WHITE + 'Enter your choice [1-3] : ') yes_no = int(yes_no) white((30 * '-')) except: white('\nInvalid number... going back to Main Menu') time.sleep(1) break if yes_no == 1: pass elif yes_no == 2: while True: try: trades = 0 for k, v in messages.iteritems(): trades += 1 if v.startswith('tsl-'): print v if trades == 0: red('There is currently no tsl trade status/history available!' ) white((30 * '-')) white('Refresh, new trade or back to Main Menu?') green('1. Refresh') yellow('2. New Trade') red('3. Back to Main Menu') go_break = False try: yes_no = raw_input(Fore.WHITE + 'Enter your choice [1-3] : ') yes_no = int(yes_no) white((30 * '-')) except: go_break = True white( '\nInvalid number... going back to Main Menu') time.sleep(1) break if yes_no == 1: pass elif yes_no == 2: break elif yes_no == 3: white('\nOk... going back to Main Menu') time.sleep(1) break else: go_break = True white( '\nInvalid number... going back to Main Menu') time.sleep(1) break except: red('\nUnable to retrieve active threads data... going back to Main Menu' ) break if yes_no == 3 or go_break == True: break elif yes_no == 3: white('\nOk... going back to Main Menu') time.sleep(1) break else: white('\nInvalid number... going back to Main Menu') time.sleep(1) break except: red('\nUnable to retrieve active threads... there is something wrong please contact p0nts!' ) break try: market = raw_input( Fore.WHITE + 'Market? (e.g. BTC-NEO / ETH-LTC / USDT-OMG) : ') market = str(market.upper()) trade = market.split('-')[0] currency = market.split('-')[1] check_status = r.exists(market) if check_status != True: white('Unsupported market... going back to Main Menu') time.sleep(1) break except: white('\nInvalid input... going back to Main Menu') time.sleep(1) break try: value = raw_input(Fore.WHITE + 'How much {0}? (excl. fee) : '.format(trade)) value = float(value) except: white('\nInvalid number... going back to Main Menu') time.sleep(1) break try: trailing = raw_input(Fore.WHITE + 'Trailing percentage? (without %) : ') trailing = float(trailing) except: white('\nInvalid number... going back to Main Menu') time.sleep(1) break if market.startswith('BTC'): trade = 'BTC' elif market.startswith('ETH'): trade = 'ETH' elif market.startswith('USDT'): trade = 'USDT' else: white('Unsupported market... going back to Main Menu') time.sleep(1) break try: api = bittrex(key, secret) values = r.hmget(market, 'Ask', 'MarketName', 'BaseVolume', 'Volume', 'OpenBuyOrders', 'OpenSellOrders', 'High', 'Low', 'Last', 'Bid') available = api.getbalance(trade) price = float(values[0]) except: white( 'API error: Unable to retrieve pricing information... going back to Main Menu' ) time.sleep(1) break if available['Available'] < 0.00100000: red('Not enough {0} to make a buy... going back to Main Menu'. format(trade)) time.sleep(1) break white((40 * '-')) green(' M A R K E T I N F O R M A T I O N') white((40 * '-')) yellow('- Market: {0}'.format(market)) yellow('- Volume: {0:.8f}'.format(float(values[2]))) yellow('- 24H volume: {0:.8f}'.format(float(values[3]))) yellow('- Open buy orders: {0}'.format(values[4])) yellow('- Open sell orders: {0}'.format(values[5])) yellow('- 24H high: {0:.8f}'.format(float(values[6]))) yellow('- 24H low: {0:.8f}'.format(float(values[7]))) yellow('- Last: {0:.8f}'.format(float(values[8]))) yellow('- Ask: {0:.8f}'.format(float(values[0]))) yellow('- Bid: {0:.8f}'.format(float(values[9]))) white((40 * '-')) white('Proceed?') green('1. yes') red('2. no') try: proceed = raw_input(Fore.WHITE + 'Enter your choice [1-2] : ') proceed = int(proceed) except: white('\nCancelled... going back to Main Menu') time.sleep(1) break if proceed == 1: try: values = r.hmget(market, 'Ask', 'Bid') ask = float(values[0]) bid = float(values[1]) amount = float(value) / float(ask) orderbook = api.getorderbook(market, type='sell') orderbook_rate = orderbook[0]['Rate'] orderbook_quantity = orderbook[0]['Quantity'] if float(amount) < float(orderbook_quantity): gobuy = True break else: while float(amount) > float(orderbook_quantity): time.sleep(1) orderbook = api.getorderbook(market, type='sell') orderbook_rate = orderbook[0]['Rate'] orderbook_quantity = orderbook[0]['Quantity'] values = r.hmget(market, 'Ask', 'Bid') ask = float(values[0]) bid = float(values[1]) amount = float(value) / float(ask) yellow( 'Waiting for the volume to rise on lowest Ask to buy all for the same price.' ) gobuy = True break except: white( 'API error: Unable to create a buyorder... going back to Main Menu' ) time.sleep(1) break elif proceed == 2: white('Ok... going back to Main Menu') time.sleep(1) break else: white('\nInvalid number... going back to Main Menu') time.sleep(1) break if gobuy == True: def start_thread(market, currency, amount, ask, trailing): time.sleep(1) global messages thread_name = threading.current_thread().name while True: try: buy = api.buylimit(market, amount, ask) time.sleep(0.5) buy_uuid = buy['uuid'] time.sleep(0.5) buyorder = api.getorder(uuid=buy_uuid) push_send = False while buyorder['IsOpen'] == True: message = '{0}: Made a buyorder, waiting until it is filled! Remaining: {1:.8f} {2}'.format( thread_name, buyorder['QuantityRemaining'], currency) messages[thread_name] = message if push_send == False: send_pushover(pushover_user, pushover_app, message) send_pushbullet(pushbullet_token, message) push_send = True buyorder = api.getorder(uuid=buy_uuid) time.sleep(10) trailing_percentage = float(ask) / 100 * float(trailing) trailing_stop_loss = float(ask) - float( trailing_percentage) stop_loss_percentage = '-{0:.2f}'.format(trailing) buyprice = float(ask) lastprice = 0 except: message = '{0}: API error: Was unable to create the buyorder... it was cancelled due to:\n{1}'.format( thread_name, buy) messages[thread_name] = message send_pushover(pushover_user, pushover_app, message) send_pushbullet(pushbullet_token, message) break while float(ask) > float(trailing_stop_loss): try: time.sleep(0.5) values = r.hmget(market, 'Ask') ask = float(values[0]) except: message = 'Unable to retrieve data from redis.pontstrader.com, trying to recover...' messages[thread_name] = message else: percentage = 100 * (float(ask) - float(buyprice)) / float(buyprice) trailing_percentage = float(ask) / 100 * float( trailing) if float(ask) > float(buyprice) and ask != lastprice: if float(ask) > lastprice and float(ask) > float( buyprice): new_trailing_stop_loss = float(ask) - float( trailing_percentage) if float(new_trailing_stop_loss) > float( trailing_stop_loss): trailing_stop_loss = float(ask) - float( trailing_percentage) stop_loss_percentage = 100 * ( float(trailing_stop_loss) - float(buyprice)) / float(buyprice) message = '{0}: {1} | Buy price {2:.8f} | Price {3:.8f} | Profit: {4:.2f}% | Stop Loss: {5:.8f} ({6:.2f}%)'.format( thread_name, currency, float(buyprice), float(ask), float(percentage), float(trailing_stop_loss), float(stop_loss_percentage)) messages[thread_name] = message else: message = '{0}: {1} | Buy price {2:.8f} | Price {3:.8f} | Profit: {4:.2f}% | Stop Loss: {5:.8f} ({6:.2f}%)'.format( thread_name, currency, float(buyprice), float(ask), float(percentage), float(trailing_stop_loss), float(stop_loss_percentage)) messages[thread_name] = message else: message = '{0}: {1} | Buy price {2:.8f} | Price {3:.8f} | Profit: {4:.2f}% | Stop Loss: {5:.8f} ({6:.2f}%)'.format( thread_name, currency, float(buyprice), float(ask), float(percentage), float(trailing_stop_loss), float(stop_loss_percentage)) messages[thread_name] = message elif float(ask) < float(buyprice) and float( ask) != float(lastprice): message = '{0}: {1} | Buy price {2:.8f} | Price {3:.8f} | Profit: {4:.2f}% | Stop Loss: {5:.8f} ({6:.2f}%)'.format( thread_name, currency, float(buyprice), float(ask), float(percentage), float(trailing_stop_loss), float(stop_loss_percentage)) messages[thread_name] = message elif float(ask) == float( buyprice) and float(ask) != float(lastprice): pass lastprice = float(ask) profit_percentage = 100 * (float(trailing_stop_loss) - float(buyprice)) / float(buyprice) try: sell = api.selllimit(market, amount, trailing_stop_loss) sell_uuid = sell['uuid'] time.sleep(0.5) sellorder = api.getorder(uuid=sell_uuid) while sellorder['IsOpen'] == True: message = '{0}: Stop Loss triggered, waiting until the sell order is completely filled! Remaining: {1:.8f}'.format( thread_name, sellorder['QuantityRemaining']) messages[thread_name] = message try: sellorder = api.getorder(uuid=sell_uuid) except: pass time.sleep(2) message = '{0}: {1} SOLD | Buy price {2:.8f} | Sell price {3:.8f} | Profit {4:.2f}% (excl. fee)'.format( thread_name, currency, buyprice, trailing_stop_loss, profit_percentage) messages[thread_name] = message send_pushover(pushover_user, pushover_app, message) send_pushbullet(pushbullet_token, message) break except: message = '{0}: API error: Was unable to create the sellorder... it was cancelled due to:\n{1}'.format( thread_name, sell) messages[thread_name] = message send_pushover(pushover_user, pushover_app, message) send_pushbullet(pushbullet_token, message) break try: datetime = datetime.now().strftime("%d-%m-%Y.%H:%M:%S") threadname = 'tsl-{0}'.format(datetime) thread = threading.Thread(name=threadname, target=start_thread, args=(market, currency, amount, ask, trailing)) thread.daemon = True thread.start() green( 'Made a buy order, to check its status go to the Trailing Stop Loss menu again... going back to Main Menu in 2 seconds' ) time.sleep(2) except: red('Unable to start thread... there is something wrong please contact p0nts!' )
def __init__(self): self.variables = { 'tokens': [], 'joined_tokens': [], 'proxies': [], 'num': 0, 'proxy_num': 0, 'completed': 0, 'sent': 0, 'joined': 0, 'retries': 0 } print("""%s ___ _ ____ ___ ____ _ _ _ _ ____ ____ | \ | [__ |__] |__| |\/| |\/| |___ |__/ |__/ | ___] | | | | | | | |___ | \ \n\n %sFastest Discord Spammer by Reyz\n\n""" % (red(), reset())) Thread(target=self.grab_proxies).start()
def red(self, s: str) -> str: return cast(str, red(s)) if self.colors_enabled else s
def singledevicedecoderinfo(*args): ivpid = request.args.get('ivpid') ip = paserip(str(ivpid)) #print readyboards(str(ip) info = readyboards(str(ip), neededencodergroup, neededdecodergroup) decoder = info[2] print yellow('info is it===========================> ' + str(info)) print blue(str(decoder)) decoderall = {} for i in decoder: print i decoder = {} #http://192.168.0.181/cgi-bin/boardcontroller.cgi?action=get&object=slot3&key=status print 'http://192.168.0.181/cig-bin/boardcontroller.cgi?action=get&object=slot' + str( i) + '&key=status' ins1 = 'http://' + str( ip) + '/cgi-bin/boardcontroller.cgi?action=get&object=slot' + str( i) + '&key=status' print blue(ins1) info1 = requests.get( 'http://' + str(ip) + '/cgi-bin/boardcontroller.cgi?action=get&object=' + str(i) + '&key=status').text info2 = requests.get( 'http://' + str(ip) + '/cgi-bin/boardcontroller.cgi?action=get&object=' + str(i) + '&key=avinfo&value=0').text info3 = requests.get( 'http://' + str(ip) + '/cgi-bin/boardcontroller.cgi?action=get&object=' + str(i) + '&key=avinfo&value=1').text decoder['info1'] = info1 decoder['info2'] = info2 decoder['info3'] = info3 #decoderall[str(i)]=decoder print yellow('info1------>' + str(info1)) selectedinfo1 = ast.literal_eval(info1) selectedinfo2 = ast.literal_eval(info2) selectedinfo3 = ast.literal_eval(info3) print red(str(selectedinfo1)) requirement1 = selectedinfo1['Body'] requirement2 = selectedinfo2['Body'] requirement3 = selectedinfo3['Body']['audinfo'] decoding_status = requirement1['status_str'] videoinfo = { 'format': requirement2['format'], 'chroma': requirement2['chroma'], 'biterate': requirement2['bitrate'] } audioinfo = { 'audio1': requirement3[0], 'audio2': requirement3[1], 'audio3': requirement3[2], 'audio4': requirement3[3] } avinfo = { 'decoding status': decoding_status, 'video info': videoinfo, 'audioallinfo': audioinfo } print info1, info2 print type(decoderall) #return json.dumps(decoderall) return json.dumps(avinfo) '''
def singledeviceencoderinfo(): ivpid = request.args.get('ivpid') ip = paserip(str(ivpid)) #print readyboards(str(ip) info = readyboards(str(ip), neededencodergroup, neededdecodergroup) encoder = info[1] encoderall = {} for i in encoder: print i encoder = {} #http://192.168.0.181/cgi-bin/boardcontroller.cgi?action=get&object=slot3&key=status #print 'http://192.168.0.181/cig-bin/boardcontroller.cgi?action=get&object='+str(i)+'&key=status' info1 = requests.get( 'http://' + str(ip) + '/cgi-bin/boardcontroller.cgi?action=get&object=' + str(i) + '&key=status').text info2 = requests.get( 'http://' + str(ip) + '/cgi-bin/boardcontroller.cgi?action=get&object=' + str(i) + '&key=all').text selectedinfo1 = ast.literal_eval(info1) selectedinfo2 = ast.literal_eval(info2) print red(str(selectedinfo1)) requirement1 = selectedinfo1['Body'] requirement2 = selectedinfo2['Body'] encoder_status = { 'encoding_status': requirement1['status_str'], 'video input': requirement1['videoinfo_str'], 'audio1to4input': { 'audio1input': requirement1['audioinfo_str0'], 'audio2input': requirement1['audioinfo_str1'], 'audio3input': requirement1['audioinfo_str2'], 'audio4input': requirement1['audioinfo_str3'], } } print(yellow(str(requirement2))) bitratesettingmode = requirement2['bitMode'] programparameters = { 'service': requirement2['videoSerName'], 'provider': [requirement2['videoPrivoder']], 'biterate': [x.strip() for x in requirement2['systemParam'].split(',')][0] } vp = [x.strip() for x in requirement2['videoParam'].split(',')] videoparameters = { 'source': vp[0], 'format': vp[1], 'horizontal size': vp[2], 'biterate': vp[3], 'loss input': vp[-1] } ap1 = [x.strip() for x in requirement2['audioParam0']] ap2 = [x.strip() for x in requirement2['audioParam1']] ap3 = [x.strip() for x in requirement2['audioParam2']] ap4 = [x.strip() for x in requirement2['audioParam3']] ap = [ap1, ap2, ap3, ap4] audioparameters = {} i = 0 for k in ap: i = i + 1 audioparameters['channel' + str(i)] = { 'source': k[0], 'audio enable': k[1], 'format': k[2], 'loss of input': k[-2] } #spree bigbang = { 'encoder status': encoder_status, 'encoder_setting': { 'bitrate settingmode': bitratesettingmode, 'videoParam': videoparameters, 'programparameters': programparameters, 'audioparameters': audioparameters } } encoder['info1'] = info1 encoder['info2'] = info2 encoderall[str(i)] = encoder #print info1,info2 print """ return info """ #print type(encoderall) #print encoderall print red('i will print big bang') print bigbang #return json.dumps(encoderall) return json.dumps(bigbang) '''
info = json.loads(open("model_info.json").read()) m2f = [] f2m = [] for model in info: m2f.append((model["name"], np.mean(model["m2f"]))) f2m.append((model["name"], np.mean(model["f2m"]))) m2f.sort(key=lambda x: x[1]) f2m.sort(key=lambda x: x[1]) for i, m in enumerate(m2f): colors.blue( "-----------------------------------------------------------------------" ) best = joblib.load(os.path.join("models", m[0])) params = best.get_params() keys = list(params.keys()) keys.sort() for key in keys: print( colors.underline(key) + ": " + str(params[key]).replace("\n", "")) print("\033[92mmodel\033[0m: " + str(params["regressor"].model)) colors.red("m2f: " + str(m[1])) colors.red("f2m: " + str(f2m[i][1])) input("")
FinalTimes.append(TimesAppeared[i]) AllTuple = MostUsed.items() for i in xrange(80): for j in xrange(NumbersToPlay): if AllTuple[i][1] == FinalTimes[j]: Final.append(AllTuple[i][0]) Final = list(set(Final)) n, l = [], [] for num in Final: for j in xrange(80): if num == AllTuple[j][0]: n.append(AllTuple[j][0]) l.append(AllTuple[j][1]) d = dict(zip(n, l)) Sorted_d = sorted(d.items(), key=operator.itemgetter(1)) Reverse_Sorted_d = sorted(d.items(), key=operator.itemgetter(1), reverse = True) print '\nYour numbers are (', red('red'), 'are optional ):', for fn in xrange(NumbersToPlay): print green(str(Reverse_Sorted_d[fn][0])), for fn in xrange(NumbersToPlay, len(Reverse_Sorted_d)): print red(str(Reverse_Sorted_d[fn][0])), print
def print_ces(self): for case, ce in self.ces.items(): print(colors.red(self.basename) + ': '+ ('without_args' if not case else case)) print(ce)
if vl == "Y": try: os.system("pip3 install hashlib") os.system("pip install hashlib") os.system("cls") import hashlib except ValueError: os.system( "You dont have PIP installed, download it from https://pypi.python.org/" ) elif vl == "n": print("Exiting...") exit() elif vl == "N": print("Exiting...") exit() else: print("WRONG OPTION") print("Exiting...") os.system("cls") # End module import <=== print( red("WARNING: This script is written for python 3 only, if you use python 2 the script may fail." )) print(">> Loading...") time.sleep(3) print("Generating an 14 characters ultra-secure password...") from utils import password password()