def run(self): print_status("Generating payload") try: data = self.generate() except OptionValidationError as e: print_error(e) return if self.output == "elf": with open(self.filepath, 'w+') as f: print_status("Building ELF payload") content = self.generate_elf(data) print_success("Saving file {}".format(self.filepath)) f.write(content) elif self.output == "c": print_success("Bulding payload for C") content = self.generate_c(data) print_info(content) elif self.output == "python": print_success("Building payload for python") content = self.generate_python(data) print_info(content) else: raise OptionValidationError( "No such option as {}".format(self.output) )
def delete_password(self, parameter, env_list): utils.print_notice('Preparing to delete a password in the keyring ' 'for:', title='Keyring operation') print ' - Environments : %s' % '\n '.join(env_list) print ' - Parameter : %s' % parameter print '\nIf you really want to proceed, type yes and press enter:', try: confirm = raw_input('') except: confirm = "no" print if confirm != 'yes': error = 'Your keyring was not read or altered.' utils.print_error(error, title='Canceled') print for environment in env_list: username = '******' % (environment, parameter) try: delete_ok = self.multiclient.password_delete(username, parameter) except: delete_ok = False if delete_ok: msg = '%s->%s' % (environment, parameter) utils.print_notice(msg, title='Success') else: error = '%s->%s' % (environment, parameter) utils.print_error(error, title='Failed', exit=False) print utils.print_notice('If you encountered a failure deleting any of the' ' credentials then you\nshould check your keyring' ' configuration.', title='Complete')
def read_opts(self, argv): """ Uses gnu getopt to read command line arguments returns a tuple of (files, texts, options) """ from getopt import gnu_getopt, GetoptError short_opts = "hf:t:nvpu0axm:" long_opts = [ 'help', 'file=', 'text=', 'no-fork', 'version', 'paths', 'uris', 'null-terminate', 'window-title=', 'write-on-exit', 'write-async', 'get', 'name=', 'list' ] try: (options, arguments) = gnu_getopt(argv, short_opts, long_opts) except GetoptError, exception: print_error("%s" % exception) self.print_usage(usage_error=True)
def invoke(self, args, from_tty): # request to reload ~/.pretty_printer argv = args.split() if len(argv) != 0: self.usage() return succ, msgs = settings.load_config() if not succ: print_error(msgs) return else: print_warnings(msgs) # apply new configuration if settings.pretty_struct: lookup.turn_on_lookup() else: lookup.turn_off_lookup() lookup.turn_off_all_packages() for pckg in settings.get_active_packages(): succ, msgs = lookup.turn_on_package(pckg) if not succ: print_error(msgs) else: print_warnings(msgs) if from_tty: print ("Configuration successfully loaded from file %s!" % CONFIG_FILE)
def invoke(self, args, from_tty): # args should be: package_name + on/off (or 1/0 true/false) # request to turn on/off some package argv = args.split() if len(argv)!=2: self.usage() return package_name = argv[0] package_state = argv[1] package_state = parse_config_value(package_state,None) if package_state is None: self.usage() return if package_state == True: succ, msgs = lookup.turn_on_package(package_name) if succ: settings.turn_on_package(package_name) action = "activated" else: succ, msgs = lookup.turn_off_package(package_name) if succ: settings.turn_off_package(package_name) action = "deactivated" if not succ: print_error(msgs) else: print_warnings(msgs) if from_tty: print ("Package %s is %s!" % (package_name,action))
def init_seishub_instance(debug=False): """ Creates a new SeisHub instance at TEST_DIRECTORY. :param debug: If debug is True, the output will not be catched. """ print_info("Creating new SeisHub instance in %s..." % TEST_DIRECTORY) if os.path.exists(TEST_DIRECTORY): msg = "SeisHub temp directory already exists." print_error(msg) sys.exit(1) cmd = ["seishub-admin", "initenv", TEST_DIRECTORY] try: if debug is True: subprocess.call(cmd) else: subprocess.check_output(cmd, stderr=subprocess.STDOUT) except subprocess.CalledProcessError, e: print_error("Error creating seishub instance. Exited with return " "code %s. Full output follows:" % (str(e.returncode))) print "" print e.output print "" sys.exit(1)
def cook(path, caller_cwd): def delete_if_exists(path): if os.path.isfile(path): os.remove(path) local_cwd = os.getcwd() # Check if `path` is an absolute path to the recipe if os.path.isabs(path): recipe_path = os.path.realpath(path) recipe_basename = os.path.basename(recipe_path) mkdirp('.recipes') delete_if_exists(os.path.join(local_cwd, '.recipes', recipe_basename)) shutil.copyfile(recipe_path, os.path.join(local_cwd, '.recipes', recipe_basename)) recipe_path = os.path.join('/vagrant', '.recipes', recipe_basename) # Check if `path` is a relative path to the recipe (from the caller's perspective) elif os.path.isfile(os.path.realpath(os.path.join(caller_cwd, path))): recipe_path = os.path.realpath(os.path.join(caller_cwd, path)) recipe_basename = os.path.basename(recipe_path) mkdirp('.recipes') delete_if_exists(os.path.join(local_cwd, '.recipes', recipe_basename)) shutil.copyfile(recipe_path, os.path.join(local_cwd, '.recipes', recipe_basename)) recipe_path = os.path.join('/vagrant', '.recipes', recipe_basename) # Check if `path + (.sh)` is a relative path to the recipe (from the dev-box's perspective) elif os.path.isfile(os.path.realpath(os.path.join(local_cwd, 'recipes', path + '.sh'))): recipe_path = os.path.realpath(os.path.join(local_cwd, 'recipes', path + '.sh')) recipe_basename = os.path.basename(recipe_path) recipe_path = os.path.join('/vagrant', 'recipes', recipe_basename) # Recipe file was not found else: print_error('Error: recipe was not found') return print_green('# DevBox is now cooking') return run('sh {0}'.format(recipe_path))
def get_dbus_names(self): from dbuscontrol import list_names from utils import print_error try: names = list(list_names()) except Exception, info: print_error(info) return
def get_dbus_connection(self): """ Tries to connect to already running instance """ try: import dbuscontrol except ImportError, info: print_error(info) return None
def present_quick_feedback(self, error): if error: answer = error[u'answer'] expected = error[u'expected'] msg_or = _(u' or ') expected_options = msg_or.join(expected) msg_error = _(u'Error: %(ans)s -> %(exp)s') % {u'ans': answer, u'exp': expected_options} print_error(msg_error) else: print_ok(u'OK')
async def _create_submitter_did(self): try: utils.print_header("\n\tCreate DID to use when sending") self.submitter_did, _ = await signus.create_and_store_my_did( self.wallet_handle, json.dumps({'seed': self.seed})) except Exception as e: utils.print_error(str(e)) raise
def write_to_selection(self, selection, target_type): """ Tells the dragitem to write its representation to the selection with the type target_type """ if target_type == TARGET_TYPE_TEXT: selection.set_text(self.object, -1) else: from utils import print_error print_error("error with drag types?")
async def _open_pool(self): """ Open pool config and get wallet handle. """ try: utils.print_header("\n\tOpen pool ledger") self.pool_handle = await pool.open_pool_ledger( self.pool_name, None) except IndyError as e: utils.print_error(str(e))
def check_placeholders(self): if self.target_path: if self.source_placeholders != self.target_placeholders: for idx, sph in enumerate(self.source_placeholders): tph = self.target_placeholders[idx] if sph != tph: print(sph, tph) utils.print_error(name=self.source_name, error_type="Placeholder Mismatch", source_placeholders=self.source_placeholders, target_placeholders=self.target_placeholders) else: print(f"Cannot check file {self.source_name}")
async def haveibeenpwned(email: str) -> dict: try: async with aiohttp.request(method='GET', url=f'{haveibeenpwned_url}{email}', headers=get_headers()) as resp: if resp.status == 200: return result(email=email, service=__name__, is_leak=True) elif resp.status == 404: return result(email=email, service=__name__, is_leak=False) else: await unexpected_status(resp=resp, service=__name__) except Exception as e: print_error(e, service=__name__)
def search_by_date_range(self, tl): """Search by user-entered date range""" print("Search by date range") dates = input("Please use YYYYMMDD-YYYYMMDD for date range: ") date1_str, date2_str = dates.split('-') try: date1 = datetime.datetime.strptime(date1_str, utils.fmt) date2 = datetime.datetime.strptime(date2_str, utils.fmt) except ValueError as err: utils.print_error(err) return self.search_by_date_range(tl) else: return tl.findall_date_range(date1, date2)
async def _open_wallet(self): """ Open wallet and get wallet handle. """ try: utils.print_header("\n\tOpen wallet") self.wallet_handle = await wallet.open_wallet( self.wallet_name, None, None) except IndyError as e: utils.print_error(str(e)) raise
def get_item(self, item_id): try: self.cursor.execute("""\ SELECT i.name, i.price FROM items i WHERE i.id = %s """, (item_id,) ) return self.cursor.fetchone() except Exception as e: utils.print_error() self.is_error = True raise e
def cb_drag_data_received(self, widget, drag_context, x, y, selection_data, info, timestamp): """ Callback when something is dropped on the window """ source_widget = drag_context.get_source_widget() if source_widget: # this is an internal drag, do not handle return False if not self.item_control.handle_drop_data(info, selection_data): print_error("Drop data not handled") return drag_context.finish(True, False, timestamp) #Finished w succ
def get_tax(self, tax_id): try: self.cursor.execute("""\ SELECT bt.title, bt.amount FROM bill_taxes bt WHERE bt.id = %s """, (tax_id,) ) return self.cursor.fetchone() except Exception as e: utils.print_error() self.is_error = True raise e
async def avast_hackcheck(email: str) -> dict: data = json.dumps({'emailAddresses': [email]}) try: async with aiohttp.request(method='POST', url=avast_url, data=data, headers=get_headers(headers)) as resp: if resp.status == 200: return parse_resp(content=await resp.json(), email=email) else: await unexpected_status(resp=resp, service=__name__) except Exception as e: print_error(e, service=__name__)
def do_show_target_url(self, args): """ Displays the current target URL. """ # Check if target URL has been set before if globalvars.target_url == None: utils.print_error( "[*] Target URL is not currently set. Use 'set_target_url'.") return None # If we get here then we have a URL to show print("[*] Target URL set to: " + globalvars.target_url)
async def haveibeensold(email: str) -> dict: data = { 'email': email, 'action': 'check' } try: async with aiohttp.request(method='POST', url=haveibeensold_url, data=data, headers=get_headers()) as resp: if resp.status == 200: return parse_resp(content=await resp.json(), email=email) else: await unexpected_status(resp=resp, service=__name__) except Exception as e: print_error(e, service=__name__)
def train(epoch): net.train() total_step_train = 0 train_loss = 0.0 error_sum_train = {'MSE':0, 'RMSE':0, 'ABS_REL':0, 'LG10':0, 'MAE':0,\ 'DELTA1.02':0, 'DELTA1.05':0, 'DELTA1.10':0, \ 'DELTA1.25':0, 'DELTA1.25^2':0, 'DELTA1.25^3':0,} tbar = tqdm(trainloader) for batch_idx, sample in enumerate(tbar): [inputs, targets] = [sample['rgbd'] , sample['depth']] if use_cuda: inputs, targets = inputs.cuda(), targets.cuda() optimizer.zero_grad() inputs, targets = Variable(inputs), Variable(targets) outputs = net(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() train_loss += loss.item() error_str = 'Epoch: %d, loss=%.4f' % (epoch, train_loss / (batch_idx + 1)) tbar.set_description(error_str) targets = targets.data.cpu() outputs = outputs.data.cpu() error_result = utils.evaluate_error(gt_depth=targets, pred_depth=outputs) total_step_train += args.batch_size_train error_avg = utils.avg_error(error_sum_train, error_result, total_step_train, args.batch_size_train) if batch_idx % 500 == 0: utils.print_error('training_result: step(average)', epoch, batch_idx, loss, error_result, error_avg, print_out=True) error_avg = utils.avg_error(error_sum_train, error_result, total_step_train, args.batch_size_train) for param_group in optimizer.param_groups: old_lr = float(param_group['lr']) utils.log_result_lr(args.save_dir, error_avg, epoch, old_lr, False, 'train') tmp_name = "epoch_%02d.pth" % (epoch) save_name = os.path.join(args.save_dir, tmp_name) torch.save(net.state_dict(), save_name)
async def lifelock(email: str) -> dict: bemail = base64.b64encode(email.encode('UTF-8')) data = {'email': bemail.decode('UTF-8'), 'language': 'en', 'country': 'us'} try: async with aiohttp.request(method='POST', url=lifelock_url, data=data, headers=get_headers(headers)) as resp: if resp.status == 200: return parse_resp(content=await resp.json(), email=email) else: await unexpected_status(resp=resp, service=__name__) except Exception as e: print_error(e, service=__name__)
def check_file_exists(self, f, warn=True): """ Check if a file exists f: a local path warn: If True, print an error message and exit if nonexistant """ p = path.abspath(f) if path.exists(p): return p if not warn: return None print_error("The file %s does not exist" % f) raise SystemExit(1)
def input_parser(filename): if filename and not os.path.exists(filename): print_error('{} does not exists') if filename: with open(filename) as f: lines = f.readlines() else: lines = sys.stdin.readlines() lines = list(filter(bool, map(lambda s: s.split('#')[0].strip(), lines))) pattern = list(map(lambda x: list(map(int, x.split())), lines[1:])) return pattern
def get_bill_items(self, bill_id): try: self.cursor.execute("""\ SELECT i.id, i.name, i.price FROM items i WHERE i.bill_id = %s ORDER BY i.created_at """, (bill_id,) ) return self.cursor.fetchall() except Exception as e: utils.print_error() self.is_error = True raise e
def val(epoch): global best_rmse is_best_model = False net.eval() total_step_val = 0 eval_loss = 0.0 error_sum_val = {'MSE':0, 'RMSE':0, 'ABS_REL':0, 'LG10':0, 'MAE':0,\ 'DELTA1.02':0, 'DELTA1.05':0, 'DELTA1.10':0, \ 'DELTA1.25':0, 'DELTA1.25^2':0, 'DELTA1.25^3':0,} tbar = tqdm(valloader) for batch_idx, sample in enumerate(tbar): [inputs, targets] = [sample['rgbd'] , sample['depth']] with torch.no_grad(): if use_cuda: inputs, targets = inputs.cuda(), targets.cuda() inputs, targets = Variable(inputs, volatile=True), Variable(targets) outputs = net(inputs) loss = criterion(outputs, targets) targets = targets.data.cpu() outputs = outputs.data.cpu() loss = loss.data.cpu() eval_loss += loss.item() error_str = 'Epoch: %d, loss=%.4f' % (epoch, eval_loss / (batch_idx + 1)) tbar.set_description(error_str) error_result = utils.evaluate_error(gt_depth=targets, pred_depth=outputs) total_step_val += args.batch_size_eval error_avg = utils.avg_error(error_sum_val, error_result, total_step_val, args.batch_size_eval) utils.print_error('eval_result: step(average)', epoch, batch_idx, loss, error_result, error_avg, print_out=True) #log best_model if utils.updata_best_model(error_avg, best_rmse): is_best_model = True best_rmse = error_avg['RMSE'] for param_group in optimizer.param_groups: old_lr = float(param_group['lr']) utils.log_result_lr(args.save_dir, error_avg, epoch, old_lr, is_best_model, 'eval') # saving best_model if is_best_model: print('==> saving best model at epoch %d' % epoch) best_model_pytorch = os.path.join(args.save_dir, 'best_model.pth') torch.save(net.state_dict(), best_model_pytorch) #updata lr scheduler.step(error_avg['MAE'], epoch)
def __init__(self, init, cond, post, lineno): super().__init__("FOR_CLAUSE", children=[init, cond, post]) self.init = init self.cond = cond self.post = post self.lineno = lineno # signal the AST optimizer to not optimize these children self._no_optim = True if hasattr(cond, "type_") and getattr(cond, "type_") != "bool": print_error("Invalid condition", kind="TYPE ERROR") print("Cannot use non-binary expression in for loop") print_line_marker_nowhitespace(lineno)
def get_and_validate_crime_type(input_prompt): """ Prompt the user with input_prompt, get a crime, and then validate that's it's a valid crime. If anything goes wrong (they enter bad input), return false. Else return the date. """ # Consider doing a query on program start to populate a list of valid crimes to avoid always quering the db. crime_type = input(input_prompt).lower() if crime_type not in _VALID_CRIME_TYPES: utils.print_error( "\"{}\" is not a valid crime type.".format(crime_type)) return False # Note: We are returning the exact case of how the crime type is spelled in the database! return _VALID_CRIME_TYPES[crime_type]
def increasing_test(groundtruths_file, predictions_file, metric, tag): gts = read_item_tag(groundtruths_file) preds = read_item_tag(predictions_file) test_groundtruths = [] predictions = [] for isrc in preds: if isrc in gts: test_groundtruths.append(gts[isrc]) predictions.append(preds[isrc]) res = [] if "accuracy" in metric: res.append(accuracy_score(test_groundtruths, predictions)) elif "precision" in metric: res.append( precision_score(test_groundtruths, predictions, average=None)[tag]) elif "recall" in metric: res.append( recall_score(test_groundtruths, predictions, average=None)[tag]) elif "f1_score" in metric: res.append(f1_score(test_groundtruths, predictions, average=None)[tag]) else: utils.print_error("classify.py line 735 metric argument error") # print("Accuracy : " + str(accuracy_score(test_groundtruths, predictions))) # print("Precision: " + str(precision_score(test_groundtruths, predictions, average=None))) # print("Recall : " + str(recall_score(test_groundtruths, predictions, average=None))) # print("F-score : " + str(f1_score(test_groundtruths, predictions, average=None))) n_splits = 10 # for n_split in range(2, n_splits+1): for n_split in [2, 10, 100]: print("\t" + str(n_split)) feats_array, gts_array = split(predictions, test_groundtruths, n_split) tmp_acc = [] for feats, gts in zip(feats_array, gts_array): if "accuracy" in metric: cur_acc = accuracy_score(gts, feats) elif "precision" in metric: cur_acc = precision_score(gts, feats, average=None)[tag] elif "recall" in metric: cur_acc = recall_score(gts, feats, average=None)[tag] elif "f1_score" in metric: cur_acc = f1_score(gts, feats, average=None)[tag] tmp_acc.append(cur_acc) print("\t\t" + str(stdev(tmp_acc))) accuracy = sum(tmp_acc) / float(len(tmp_acc)) res.append(accuracy) return res
def start_dbus_service(self): """ Create a dbus Service object Set up signals for the service return the created service or None """ import dbuscontrol try: dserver = dbuscontrol.make_service(self.identifier) except Exception, info: from utils import print_debug, print_error print_debug(info) print_error("Failed to use dbus, might not be available") dbus_service = None
def select_lecture(driver, lectures): soup = BeautifulSoup(driver.page_source, features='html.parser') lectures = soup.find('div', id="recordings").findAll('a') print() for i, lecture in enumerate(lectures): print (str(i+1) + ") " + lecture['title'][6:].strip()) lecture_num = input('\nSelect lecture from the list above: ') while not validate_num_input(len(lectures), lecture_num): print_error('Your input is invalid.') lecture_num = input('Please enter a number between 1 and ' + str(len(lectures)) + ': ') url = 'https://leccap.engin.umich.edu' + lectures[int(lecture_num)-1]['href'] title = lectures[int(lecture_num) - 1]['title'][6:].strip() return (url, title)
def scan(self, timeout=10): try: adapter = bluezutils.find_adapter() except (bluezutils.BluezUtilError, dbus.exceptions.DBusException) as error: print_error(str(error) + "\n") else: try: adapter.StartDiscovery() time.sleep(timeout) adapter.StopDiscovery() except dbus.exceptions.DBusException as error: print_error(str(error) + "\n") self._scan_thread = None
def enter_title(self, task=None): """Obtain name of task""" print("Enter task title") if task: print('Current: {}'.format(task.title)) title = input("What is the name? ") try: if not title: raise ValueError("Title cannot be empty.") except ValueError as err: utils.print_error(err) utils.wait() return self.enter_title() else: return title
def __init__(self): if self.architecture == "armle": self.bigendian = False self.header = ARCH_ELF_HEADERS['armle'] elif self.architecture == "mipsbe": self.bigendian = True self.header = ARCH_ELF_HEADERS['mipsbe'] elif self.architecture == "mipsle": self.bigendian = False self.header = ARCH_ELF_HEADERS['mipsle'] else: print_error( "Define architecture. Supported architectures: armle, mipsbe, mipsle" ) return None
def p_decl_definition(p: Any) -> None: 'decl : kstate DEFINITION id LPAREN params RPAREN definition_body' k_tok, num_states = p[1] mods: Tuple[syntax.ModifiesClause, ...] expr: syntax.Expr mods, expr = p[7] if num_states != 2 and mods: utils.print_error(mods[0].span, "syntax error: modifies clause only allowed on twostate definitions or transitions") return p[0] = syntax.DefinitionDecl(is_public_transition=False, num_states=num_states, name=p[3].value, params=p[5], mods=mods, expr=expr, span=loc_join(k_tok, loc_join(p.slice[2], expr.span)))
def split_number(number, nb_folds): """Description of split_number Return an int array of size nb_folds where the sum of cells = number All the integers in cells are the same +-1 """ if not isinstance(number, int) and not isinstance(nb_folds, int): utils.print_error("Variable must be integer") if number < nb_folds: utils.print_error("Number of folds > Number of data available") min_num = int(number / nb_folds) folds = [min_num] * nb_folds for num in range(0, number - (min_num * nb_folds)): folds[num] = folds[num] + 1 return folds
def anova(data): """ return True is at least one mean is different from the other https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.f_oneway.html """ if len(data) == 3: statistic, pvalue = stats.f_oneway(data[0], data[1], data[2]) elif len(data) == 4: statistic, pvalue = stats.f_oneway(data[0], data[1], data[2], data[3]) else: utils.print_error("TODO ANOVA manage more values") print("ANOVA Statistic " + str(statistic) + " and p-value " + str(pvalue)) if pvalue < 0.05: return True else: return False
def read_config_file(file_name): settings = {} config = configparser.ConfigParser() try: config.read(file_name) except Exception as error: utils.print_error(error) return settings for section_name in config: section = {} for var in config[section_name]: section[var] = config[section_name][var] settings[section_name] = section return settings
def invoke(self, args, from_tty): # request to save ~/.pretty_printer argv = args.split() if len(argv) != 0: self.usage() return succ, msgs = settings.save_config() if not succ: print_error(msgs) return else: print_warnings(msgs) if from_tty: print ("Configuration successfully saved to file %s!" % CONFIG_FILE)
def __init__(self, pfa_path): JSONPFAValidator.__init__(self) if pfa_path is None: print_error( "Program expects an PFA_PATH environment variable that contains the path " "to PFA file to validate. Please refer to the associated README.md file " "for detailed usage instructions") sys.exit(1) # Check that the pfa path passed by the user exists if not os.path.exists(pfa_path): print_error("The path you provided does not exist:" + os.path.abspath(pfa_path)) sys.exit(1) self.pfa_path = pfa_path
def enter_minutes(self, task=None): """Obtain user-supplied task time in minutes""" print("Enter task time") if task: print('Current: {}'.format(task.minutes)) minutes_str = input("Please enter minutes: ") try: if not minutes_str: raise ValueError("Minutes cannot be empty.") minutes = int(minutes_str) except ValueError as err: utils.print_error(err) utils.wait() return self.enter_minutes() else: return round(minutes)
def main(): should_exit = False while should_exit is False: utils.print_menu() option = input() if option == "szyfrowanie": utils.print_text() utils.print_result(encryption.encrypt(input())) elif option == "deszyfrowanie": utils.print_text() utils.print_result(encryption.decrypt(input())) elif option == "wyjscie": should_exit = True else: utils.print_error() utils.print_end()
def do_show_extensions(self, args): """ Shows file extensions currently known to exist in the local repo. Populate that with 'findextensions' command. """ if len(globalvars.extensions) == 0: utils.print_error( "Currently no extensions are set. Use \"findextensions\" to do that" ) msg = "Found " + Fore.MAGENTA + "{0}" + Style.RESET_ALL + " extensions." print(msg.format(len(globalvars.extensions))) for ex in globalvars.extensions: print(ex)
def bartlett(data): """Description of bartlett https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.bartlett.html """ if len(data) == 3: statistic, pvalue = stats.bartlett(data[0], data[1], data[2]) elif len(data) == 4: statistic, pvalue = stats.bartlett(data[0], data[1], data[2], data[3]) else: utils.print_error("TODO barlett manage more values") print("Bartlett Statistic " + str(statistic) + " and p-value " + str(pvalue)) if pvalue > 0.05: return True else: return False
def display_header_infos(self, path): if os.path.isdir(path): self.display_header_infos_in_directory(path) elif os.path.isfile(path): if self.is_wave_file(path): self.analyze_wave_header(path) elif self.is_aiff_file(path): self.analyze_aiff_header(path) else: print_error( "File is neither a WAVE nor an AIFF file: {}".format(path)) else: print_error( "Given path is neither a file nor a directory: {}".format( path))
def try_get_data(self): """ Send get_data method to another instance and try to get its data """ from shelfitem import make_item if not self.dbus_connection: # dbus is not available or the requested name # is simply not there name = self.identifier and self.identifier or "Default" print_error("Shelf %s not found" % name) self.get_dbus_names() return False datas, types = self.dbus_connection.get_interface().get_data() writer = self.make_writer() for data, type in zip(datas, types): writer.print_item(None, make_item(data, type)) return True
def cleanup(): """ Simply removes the temporarily created SeisHub instance. """ print_info("Cleaning up...") # Try deleting it for some seconds... t = time.time() while (time.time() - t) < 10.0: time.sleep(0.1) try: if os.path.exists(TEST_DIRECTORY): shutil.rmtree(TEST_DIRECTORY) return except: pass print_error("Cleanup failed.")
async def _create_pool_config(self): """ Create pool configuration from genesis file. """ try: utils.print_header("\n\n\tCreate ledger config " "from genesis txn file") pool_config = json.dumps( {'genesis_txn': self.config.pool_genesis_file}) await pool.create_pool_ledger_config(self.pool_name, pool_config) except IndyError as e: if e.error_code == 306: utils.print_warning("The ledger already exists, moving on...") else: utils.print_error(str(e)) raise
def unhook(): if not os.path.isfile(hook_file_path): print_error("Error: there's not any active hook") return if os.path.isfile(hook_file_path): with open(hook_file_path) as hook_file: hook_hash = json.loads(hook_file.read()) vm_id = hook_hash['vm_id'] rc = 0 rc += vagrant_run('sudo umount -a -t vboxsf /home/vagrant/hook') rc += os.system('VBoxManage sharedfolder remove {0} --name hook --transient'.format(vm_id)) if rc == 0: remove_hook_file() hook_hash['status'] = 'destroyed' hook_json = json.dumps(hook_hash, sort_keys=False, indent=4, separators=(',', ': ')) print(hook_json) else: print_error('Error: something went bad! Hook was not properly released. Is there any active hook?')
async def _create_wallet(self): """ Create wallet. """ try: utils.print_header("\n\tCreate wallet") await wallet.create_wallet(self.pool_name, self.wallet_name, None, None, None) except IndyError as e: if e.error_code == 203: utils.print_warning( "Wallet '%s' already exists. " "Skipping wallet creation..." % str( self.wallet_name)) else: utils.print_error(str(e)) raise
def __init__(self): self.options = Options().args self.tester = None temp = 0 for mode in PerformanceTestRunner.modes: if mode in sys.argv: temp += 1 if temp == 0: utils.print_error( 'Cannot determine any kind of request for testing') utils.print_error( 'May be you missing arguments "-a" or "-b" or "-t" or "-l"') sys.exit(1) if temp > 1: utils.force_print_error_to_console( '"-a" and "-g" and "-t" and "-l" ' 'cannot exist at the same time\n') sys.exit(1) self.list_tester = list() self.start_time = self.finish_time = 0 self.lowest = self.fastest = 0 self.passed_req = self.failed_req = 0 self.result_path = os.path.join(os.path.dirname(__file__), 'results') utils.create_folder(self.result_path) log_path = os.path.join(os.path.dirname(__file__), 'logs') utils.create_folder(log_path) now = time.strftime("%d-%m-%Y_%H-%M-%S") self.result_path = os.path.join(self.result_path, 'result_{}.txt'.format(now)) log_path = os.path.join( log_path, self.create_log_file_name()) requests_sender.RequestsSender.init_log_file(log_path) utils.create_folder(self.options.info_dir)
def __init__(self, name, signature, access): self.name = name self.signature = signature self.access = access self.annotations = [] self.arg = Arg('value', self.signature) self.arg.annotations = self.annotations self.readable = False self.writable = False if self.access == 'readwrite': self.readable = True self.writable = True elif self.access == 'read': self.readable = True elif self.access == 'write': self.writable = True else: print_error('Invalid access type "{}"'.format(self.access)) self.doc_string = '' self.since = '' self.deprecated = False
def main(): # Setup option parser parser = OptionParser() parser.add_option('-f', '--file', dest='fname', help='read cause-effect pairs from FILE', metavar='FILE') # Interpret options passed (opts, args) = parser.parse_args() if not opts.fname: parser.error('File not provided. Use --file option.') ceg = CEGraph() # Initialize cause-effect graph # Read file of cause-effect pairs with open(opts.fname, 'r') as f: for line in f: cause, effect = line.rstrip().split() res = ceg.add(cause, effect) if not res[0]: print_error(res[1]) while True: try: src = raw_input('Source: ') sink = raw_input('Sink: ') res = ceg.resolve(src, sink) if res[0] and res[1]: print_path(res[1]) elif not res[1]: print_error('No path found.') else: print_error(res[1]) except KeyboardInterrupt: print exit('Goodbye!')
def get_password(self, parameter, env_list): error = ('If this operation is successful, the \'%s\' credentials ' 'stored \nfor the following environments will be displayed' ' in your terminal as plain text.' % parameter) utils.print_error(error, title='Warning', exit=False) print ' - Environments : %s' % '\n '.join(env_list) print ' - Parameter : %s' % parameter print '\nIf you really want to proceed, type yes and press enter:', try: confirm = raw_input('') except: confirm = "no" print if confirm != 'yes': error = 'Your keyring was not read or altered.' utils.print_error(error, title='Canceled') print for environment in env_list: username = '******' % (environment, parameter) try: password = self.multiclient.password_get(username, parameter) except: password = None if password: msg = '%s->%s: %s' % (environment, parameter, password) utils.print_notice(msg, title='Success') else: error = '%s->%s' % (environment, parameter) utils.print_error(error, title='Failed', exit=False) print utils.print_notice('If you encountered a failure retrieving the ' 'credentials then there\nare likely no credentials ' 'stored for that environment/parameter ' 'combination.', title='Complete')
def hook(path, caller_cwd): if os.path.isfile(hook_file_path): print_error("Error: there's an active hook; unhook it first") return if os.path.isfile(vm_id_file_path): with open(vm_id_file_path) as vm_id_file: vm_id = vm_id_file.read() else: print_error('Error: VM ID was not found') return if os.path.isabs(path): hook_path = os.path.realpath(path) else: hook_path = os.path.realpath(os.path.join(caller_cwd, path)) if not os.path.isdir(hook_path): print_error('Error: it is not a directory') return dev_box_path = os.path.realpath(root) if dev_box_path == hook_path: print_error('Error: Inceptions are not allowed here, sorry') return rc = 0 rc += os.system('VBoxManage sharedfolder add {0} --name hook --hostpath {1} --transient'.format(vm_id, hook_path)) rc += os.system('VBoxManage setextradata {0} VBoxInternal2/SharedFoldersEnableSymlinksCreate/hook 1'.format(vm_id)) rc += vagrant_run('sudo mkdir -p /home/vagrant/hook') rc += vagrant_run('sudo chown -R vagrant:vagrant /home/vagrant/hook') rc += vagrant_run('sudo mount -t vboxsf -o uid=1000,gid=1000 hook /home/vagrant/hook') if rc == 0: hook_hash = {} hook_hash['path'] = hook_path hook_hash['created_at'] = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S') hook_hash['vm_id'] = vm_id hook_hash['status'] = 'created' hook_json = json.dumps(hook_hash, sort_keys=False, indent=4, separators=(',', ': ')) hook_file = open(hook_file_path, 'w+') hook_file.write(hook_json) hook_file.write('\n') print(hook_json) else: print_error('Error: something went bad! Hook was not properly created')
def run_client(self): valid_envs = sorted(self.multiclient.get_environments()) self.parser.add_argument('-x', '--executable', default=self.executable, help='command to run instead of ' '%s' % self.executable) self.parser.add_argument('-d', '--debug', action='store_true', help='show client\'s debug output') self.parser.add_argument('env', help='environment to run the client against.', choices=valid_envs) multistack_args, client_args = self.parser.parse_known_args() if not client_args: error = 'No arguments were provided to pass along to the client.' utils.print_error(error, title='Missing client arguments') if multistack_args.env in self.multiclient.get_environments(): self.set_client_env(multistack_args.env) self.multiclient.run_client(client_args, multistack_args) else: error = ('Environment \'%s\' not in multistack configuration ' 'file' % multistack_args.env) utils.print_error(error, title='Missing environment')
def invoke(self, args, from_tty): # arg = number of "previous" steps - by default it is 1 # print arg-th node in backward direction from lastly printed # node in linked list argv = args.split() if len(argv) not in [0,1]: self.usage() return if lookup.lookup_state == False: print ("Pretty-struct system is currently deactivated.\n" "To activate invoke \"ps on\"") return if settings.link_list == False: print ("Service \"link-list pretty-printing\" is currently " "deactivated.\n" "To activate invoke \"ps link-list on\"") return if linked_list_printer is None: print ("Missing reference node!\nFirstly invoke " "\"ps link-list print <symbol>\" on initial " "linked-list node.") return if not argv: offset = 1 else: try: offset = int(argv[0]) except ValueError: self.usage() return val = linked_list_printer.val succ, msgs = linked_list_printer.shift(-offset) if not succ: print_error(msgs) else: print_warnings(msgs) lookup.register_onetime_printer(val,linked_list_printer) print str(val)