def __init__(self): super(MainWindow, self).__init__() uic.loadUi(BASEDIR + '/ui/main.ui', self) self.setWindowIcon(QtGui.QIcon(BASEDIR + '/resources/icon.png')) self.config = config.load_config() self.login_dialog = Login(parent=self) self.secret_dialog = Secret(parent=self) self.error_dialog = Error(parent=self) self.statusBar().showMessage('Ready') # Bind our actions such as exit, refresh, connect, etc. self.actionExit.triggered.connect(sys.exit) self.actionRefresh.triggered.connect(self.refresh) self.actionConnect.triggered.connect(self.login_dialog.show) self.actionAdd.triggered.connect(self.new_secret) self.actionRemove.triggered.connect(self.delete_secret) # Handle our path tree being selected. self.pathTreeWidget.clicked.connect(self.refresh_objects) pathTreeModel = self.pathTreeWidget.selectionModel() pathTreeModel.selectionChanged.connect(self.refresh_objects) self.selected_path = [] # Handle our objects viewer being selected. objectsModel = self.objectsViewer.selectionModel() objectsModel.selectionChanged.connect(self.update_object_viewer) self.objectsViewer.doubleClicked.connect(self.edit_secret) self.objectsViewer.clicked.connect(self.update_object_viewer) # Handle our secret viewer being selected. self.secretTableWidget.doubleClicked.connect( self.update_secret_viewer_selection)
def run(self, args): """ Load the images from a tub and create a movie from them. Movie """ import moviepy.editor as mpy args, parser = self.parse_args(args) if args.tub is None: parser.print_help() return cfg = load_config() self.tub = Tub(args.tub) self.num_rec = self.tub.get_num_records() self.iRec = 0 print('making movie', args.out, 'from', self.num_rec, 'images') clip = mpy.VideoClip( self.make_frame, duration=(self.num_rec // cfg['VEHICLE']['DRIVE_LOOP_HZ']) - 1) clip.write_videofile(args.out, fps=cfg['VEHICLE']['DRIVE_LOOP_HZ']) print('done')
def run(self, args): cfg = load_config() if args: args = self.parse_args(args) self.view(cfg=cfg,model_path=args.model,tub=args.tub) else: self.view(cfg)
def run(self, args): cfg = load_config() args = self.parse_args(args) self.train(cfg, tub_names=args.tub, new_model_path=args.model, base_model_path=args.base_model)
def __init__(self): super(MainWindow, self).__init__() uic.loadUi(BASEDIR + '/ui/main.ui', self) self.setWindowIcon(QtGui.QIcon(BASEDIR + '/resources/icon.png')) self.config = config.load_config() self.login_dialog = Login(parent=self) self.secret_dialog = Secret(parent=self) self.error_dialog = Error(parent=self) self.statusBar().showMessage('Ready') # Bind our actions such as exit, refresh, connect, etc. self.actionExit.triggered.connect(sys.exit) self.actionRefresh.triggered.connect(self.refresh) self.actionConnect.triggered.connect(self.login_dialog.show) self.actionAdd.triggered.connect(self.new_secret) self.actionRemove.triggered.connect(self.delete_secret) # Handle our path tree being selected. self.pathTreeWidget.clicked.connect(self.refresh_objects) pathTreeModel = self.pathTreeWidget.selectionModel() pathTreeModel.selectionChanged.connect(self.refresh_objects) self.selected_path = [] # Handle our objects viewer being selected. objectsModel = self.objectsViewer.selectionModel() objectsModel.selectionChanged.connect(self.update_object_viewer) self.objectsViewer.doubleClicked.connect(self.edit_secret) self.objectsViewer.clicked.connect(self.update_object_viewer) # Handle our secret viewer being selected. self.secretTableWidget.doubleClicked.connect(self.update_secret_viewer_selection)
def run(self, args): cfg = load_config() if args: args = self.parse_args(args) self.drive(cfg=cfg, model_path=args.model, imglist_Path=args.imglist_path)
def run(self, args): cfg = load_config() if args: args = self.parse_args(args) self.drive( cfg=cfg, model_path=args.model, ) else: self.drive(cfg)
def test_load_config_not_on_disk(): os.remove(config.get_config_path()) config.load_config() assert config.config is not None assert os.path.exists(config.get_config_path())
def test_load_config(): config.load_config() assert config.config is not None
from PIL import Image import random import numpy as np from core.config import load_config cfg=load_config() # 进行图像的预处理 def transform(img_batch): img_batch = img_batch.reshape(-1, cfg['CNN']['CNN_IMG_HEIGHT'], cfg['CNN']['CNN_IMG_WIDTH'], 3) for i in range(len(img_batch)): img = Image.fromarray(img_batch[i]) if(random.random()<1): ranH = np.random.randn()*10+10 if(ranH>20): ranH = 20 if(ranH<0): ranH = 0 crop = (0, 0+ranH, 256, 124+ranH) trans1 =img.transform((256,144), Image.EXTENT, crop) # trans1.show() if(random.random()<1): rand = random.random() rotate = np.random.randn()*30 if(rotate>30): rotate = 30 if(rotate<-30): rotate = -30 if(rotate>=0): trans3 = trans1.transform((256,144), Image.QUAD, (0,rotate,rotate,144,256,144-rotate,256-rotate,0)) if(rotate<0):
type=int, default=16, help="batch size") parser.add_argument("-w", "--weights", default=None, type=str, nargs=argparse.ONE_OR_MORE, help="weights to eval") parser.add_argument("-t", "--threshold", default=0.5, type=float, help="threshold for classification") args = parser.parse_args() config = load_config(args.config_file, args.config_name) random.seed(42) # fix global seed weights = args.weights if weights is None: print("Please specify some weights.") sys.exit(1) threshold = args.threshold assert 0. <= threshold <= 1., "range of threshold should be [0, 1]" model = config.create_model(weights) model.trainable = False logger.info(f"evaluate weight: {weights}") test_loader = config.get_test_loader() test_loader.batch_size = args.batch_size
def init(): """ Initialise all of the needed prerequisites for Lancer. This should: - Register the signal handler for Ctrl+C - Load the config file - Parse command line arguments - Show the header - Check that we're on a supported Python version - Show an option to update the VirtualTerminal registry key if on Win 10 - Show a warning that localisation support is not yet implemented if there is a non-default -l parameter - Display a legal disclaimer about using Lancer for illegal use - Warn if the cache is over 500mb in size - Clear the cache if we want to """ # Register the signal handler for a more graceful Ctrl+C signal.signal(signal.SIGINT, utils.signal_handler) # Load the config file config.load_config() # Parse the arguments ArgHandler.parse_arguments(sys.argv[1:]) # Display the header utils.display_header() time.sleep(1.25) # Check we're on a supported Python version utils.python_version() # Update the Windows virtual terminal if necessary # If we're on Windows 10, import winutils if platform.system().lower() == "windows" and platform.release() == "10": from core.winutils import update_windows_virtual_terminal update_windows_virtual_terminal() # Language warning - not yet implemented if ArgHandler.get_language_code() != 'en': print(utils.error_message(), "Multi-language support is not yet implemented...") # Show a legal disclaimer disclaimer = utils.terminal_width_string( "Legal Disclaimer: Usage of Lancer for attacking targets without prior mutual" " authorisation is illegal. It is the end user's responsibility to adhere to all local" " and international laws. The developers of this tool assume no liability and are not" " responsible for any misuse or damage caused by the use of this program." ) print(utils.error_message(), disclaimer) print() # Cache warning # If it is more than 1GB, we display an error-style warning root_directory = Path(config.get_cache_path()) size = sum(f.stat().st_size for f in root_directory.glob('**/*') if f.is_file()) / 1048576 # Bytes -> MB if size >= 2048: print(utils.error_message(), "Cache is {SIZE}gb in size. It is recommended to clear it with --clear-cache." .format(SIZE="{:.1f}".format(size/1024))) # If it is more than 500, we display a warning elif size >= 512: print(utils.warning_message(), "Cache is {SIZE}mb in size. You can clear it with --clear-cache." .format(SIZE="{:.1f}".format(size))) # Clear the cache if ArgHandler.get_clear_cache(): files = os.listdir(config.get_cache_path()) for filename in files: file_path = os.path.join(config.get_cache_path(), filename) if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path) and file_path != config.get_current_cache_path(): shutil.rmtree(file_path) print(utils.normal_message(), "Removed {NUM} items from the cache".format(NUM=len(files))) # Check if we are admin, display a relevant message if utils.is_user_admin(): print(utils.normal_message(), "Lancer running with elevated permissions") else: non_admin_warning = utils.terminal_width_string("Lancer doesn't appear to being run with elevated" " permissions. Some functionality may not work" " correctly") print(utils.warning_message(), non_admin_warning) # Display warning about your IP address ip_address = utils.terminal_width_string( "Your IP Address has been detected as {IP}. This can be changed with -a [IP]" ) print(utils.normal_message(), ip_address.format(IP=get_ip())) print() # Preload all of the modules ModuleProvider.load()
"-f", "--wsi_files", type=str, nargs=argparse.ONE_OR_MORE, help="path to WSI file or txt recording WSI file list.") parser.add_argument("--intermediate", default=False, action="store_true", help="save intermediate results") args = parser.parse_args() config_file = args.config_file wsi_files = args.wsi_files intermediate = args.intermediate cfg = load_config(config_file, None) logger.info(f"inference config: \n{cfg}") inference = Inference(cfg) # parse wsi file logger.info("parsing wsi file ...") wsi_dict = {"others": []} for wsi_file in wsi_files: if wsi_file.endswith(".txt"): grp_name = os.path.basename(wsi_file).split('.')[0] with open(wsi_file, 'r') as f: wsi_dict[grp_name] = [l.strip() for l in f.readlines()] logger.info( f"Group: {grp_name} - {len(wsi_file[grp_name])} slides") else: wsi_dict["others"].append(wsi_file)
def index(): if User.query.count() == 0: load_config() return render_template("setup.html") projects = sorted(Project.query.all(), key=lambda p: p.name) if os.path.exists("static/logo.png"): avatar = os.path.join("static/logo.png") else: avatar = ("//www.gravatar.com/avatar/" + hashlib.md5(_cfg("your-email").encode("utf-8")).hexdigest()) selected_project = request.args.get("project") if selected_project: try: selected_project = int(selected_project) except Exception: current_app.logger.exception( "Error while trying to select project: %s" % selected_project, exc_info=True, ) selected_project = None active_recurring = (Donation.query.filter( Donation.type == DonationType.monthly).filter( Donation.active == True).filter(Donation.hidden == False)) recurring_count = active_recurring.count() recurring_sum = sum([d.amount for d in active_recurring]) limit = datetime.now() - timedelta(days=30) month_onetime = Donation.query.filter( Donation.type == DonationType.one_time).filter( Donation.created > limit) onetime_count = month_onetime.count() onetime_sum = sum([d.amount for d in month_onetime]) access_token = _cfg("patreon-access-token") campaign = _cfg("patreon-campaign") if access_token and campaign: try: import patreon client = patreon.API(access_token) campaign = client.fetch_campaign() attrs = campaign.json_data["data"][0]["attributes"] patreon_count = attrs["patron_count"] patreon_sum = attrs["pledge_sum"] except Exception as e: current_app.logger.warning("Error to get patreon information: %s" % e, exc_info=True) patreon_count = 0 patreon_sum = 0 else: patreon_count = 0 patreon_sum = 0 liberapay = _cfg("liberapay-campaign") if liberapay: try: lp = (requests.get( "https://liberapay.com/{}/public.json".format(liberapay), timeout=5)).json() except Exception: traceback.print_exc() print("Error while trying to get data from liberapay") lp_count = 0 lp_sum = 0 else: lp_count = lp["npatrons"] lp_sum = int(float(lp["receiving"]["amount"]) * 100) # Convert from weekly to monthly lp_sum = lp_sum * 52 // 12 else: lp_count = 0 lp_sum = 0 github_token = _cfg("github-token") if github_token: query = """ { viewer { login sponsorsListing { tiers(first:100) { nodes { monthlyPriceInCents adminInfo { sponsorships(includePrivate:true) { totalCount } } } } } } } """ r = requests.post( "https://api.github.com/graphql", json={"query": query}, headers={"Authorization": f"bearer {github_token}"}, ) result = r.json() nodes = result["data"]["viewer"]["sponsorsListing"]["tiers"]["nodes"] cnt = lambda n: n["adminInfo"]["sponsorships"]["totalCount"] gh_count = sum(cnt(n) for n in nodes) gh_sum = sum(n["monthlyPriceInCents"] * cnt(n) for n in nodes) gh_user = result["data"]["viewer"]["login"] else: gh_count = 0 gh_sum = 0 gh_user = 0 return render_template( "index.html", projects=projects, avatar=avatar, selected_project=selected_project, recurring_count=recurring_count, recurring_sum=recurring_sum, onetime_count=onetime_count, onetime_sum=onetime_sum, patreon_count=patreon_count, patreon_sum=patreon_sum, lp_count=lp_count, lp_sum=lp_sum, currency=currency, gh_count=gh_count, gh_sum=gh_sum, gh_user=gh_user, version=version(), )