def handle_download(download_page, params): """Original function""" global output_dir print(params) filename = archive_format(params) + ".pdf" volumes = { 'Α' : 'A', 'Β' : 'B', 'Γ' : 'C', 'Δ' : 'D', 'Α.ΕΙ.Δ.' : 'A.EI.D', 'Α.Σ.Ε.Π.': 'A.S.E.P', 'Δ.Δ.Σ.': 'D.D.S', 'Α.Π.Σ.': 'A.P.S', 'Υ.Ο.Δ.Δ.': 'Y.O.D.D', 'Α.Α.Π.' : 'A.A.P', 'Ν.Π.Δ.Δ.': 'N.P.D.D', 'ΠΑΡΑΡΤΗΜΑ': 'APPENDIX', 'Δ.Ε.Β.Ι.': 'D.E.B.I', 'ΑΕ-ΕΠΕ': 'AE-EPE', 'Ο.Π.Κ.': 'O.P.K', } vol = volumes[params['issue_type']] year = params['issue_date'].year dirs = '{}/{}/{}'.format(vol, year, filename[6:9]) os.system('mkdir -p {}/{}'.format(output_dir, dirs)) outfile = '{}/{}/{}'.format(output_dir, dirs, filename) if os.path.isfile(outfile): logging.info('{} already a file'.format(filename)) return try: # First we get the redirect link from the download page html = Helper.get_url_contents(download_page) beautiful_soup = BeautifulSoup(html, "html.parser") meta = beautiful_soup.find("meta", {"http-equiv": "REFRESH"}) download_link = meta['content'].replace("0;url=", "") # We do the same process twice because it involves 2 redirects. beautiful_soup = BeautifulSoup( Helper.get_url_contents(download_link), "html.parser") meta = beautiful_soup.find("meta", {"http-equiv": "REFRESH"}) download_link = meta['content'].replace("0;url=", "") except BaseException as e: logging.error("Exception occurred while processing a link",exc_info=True) print(e) return None print(filename) logging.info('Downloaded {}'.format(filename)) Helper.download(download_link, filename, output_dir + '/' + dirs) return outfile
def present_results(self): while 1: method = Helper.create_prompt('View results', 'YES', 'NO', 'Quit') if method == '1': self.open_results() elif method == '2': return 0 elif method == '3': Helper.confirm_quit()
def present_results(self): while 1: method = Helper.create_prompt('View results', 'YES', 'NO','Quit') if method == '1': self.open_results() elif method == '2': return 0 elif method == '3': Helper.confirm_quit()
def get_access_logs_today(): helper = Helper() year = int(datetime.now().year) month = int(datetime.now().month) day = int(datetime.now().day) initial_date = helper.naive_to_datetime(date(year, month, day)) final_date = helper.naive_to_datetime(initial_date + timedelta(days=1)) return AccessLog.objects.filter( access_to_room__range=(initial_date, final_date)).order_by('-access_to_room')
def get_method(self): while 1: method = Helper.create_prompt('Method', 'GET', 'POST', 'Quit') if method == '1': self.method = 'GET' return 0 elif method == '2': self.method = 'POST' return 0 elif method == '3': Helper.confirm_quit()
def _read_img(self, IM_ID): helper = Helper() # read rgb channels and mask rgb, mask = helper.load_im_polymask(IM_ID, '5', 'data/three_band/', 'data/train_wkt_v4.csv', 'data/grid_sizes.csv') # read m band m = tiff.imread(self.root_dir + '{}_M.tif'.format(IM_ID)) shape_0 = 3345 shape_1 = 3338 # rgb blue = cv2.resize(m[1, :, :], (shape_1, shape_0), interpolation=cv2.INTER_CUBIC)[:, :, np.newaxis] green = cv2.resize(m[2, :, :], (shape_1, shape_0), interpolation=cv2.INTER_CUBIC)[:, :, np.newaxis] red = cv2.resize(m[4, :, :], (shape_1, shape_0), interpolation=cv2.INTER_CUBIC)[:, :, np.newaxis] # nir1 = cv2.resize(m[6, :, :], (shape_1, shape_0), interpolation=cv2.INTER_CUBIC)[:, :, np.newaxis] # nir2 = cv2.resize(m[7, :, :], (shape_1, shape_0), interpolation=cv2.INTER_CUBIC)[:, :, np.newaxis] image = np.concatenate([red, green, blue], axis=2) img_rgb_norm = (image - np.array([426.98400879, 464.88424683, 329.17596436])) # swapaxes img_rgb_norm = img_rgb_norm img_rgb_norm = np.swapaxes(img_rgb_norm, 0, 2) img_rgb_norm = np.swapaxes(img_rgb_norm, 1, 2) img_rgb_norm = img_rgb_norm[np.newaxis, :] # random crop crop_size = 400 rand = random.Random() crop_max_x = img_rgb_norm.shape[3] - crop_size crop_max_y = img_rgb_norm.shape[2] - crop_size crop_x = rand.randint(0, crop_max_x) crop_y = rand.randint(0, crop_max_y) img_crop = img_rgb_norm[:, :, crop_y:crop_y + crop_size, crop_x:crop_x + crop_size] mask_croped = mask[crop_y:crop_y + crop_size, crop_x:crop_x + crop_size] mask_croped = np.expand_dims(mask_croped, axis=0) mask_croped = np.expand_dims(mask_croped, axis=0) return img_crop, mask_croped
def get_assessment_score(assessment): loop = True while loop: score = input("Enter student score for " + assessment['name'] + ":") if not Helper.is_int(score): print("\nScrole should be integer") if score and Helper.is_int(score): if int(score) > 100: print("\nScore can't be greater than 100") else: loop = False return score
def amenities(): """Returns listing amenities and missing amenities that the most popular listings offer""" id = request.args.get('id') db = dbConnector() helper = Helper() db.set_id(id) data = db.get_listing() zipcode = data[0]['zipcode'] price = data[0]['price'] listing_amenities = data[0]['amenities'] total_amenities = db.get_amens_by_zip(zipcode) amens = helper.amens(listing_amenities, total_amenities, price) return json.dumps(amens, use_decimal=True)
def start_fuzzing(self): Helper.delimiter_line() print "REST FUZZER" Helper.delimiter_line() self.get_url() self.get_method() self.insert_params() results = self.send_requests() self.save_data(results, "rest") if not self.present_results(): return 0
def tests(grid): print(grid.unicode()) stats = Maze_Statistics(grid) v = stats.size() p, w, e = stats.Euler_edge_counts() k, _ = Helper.find_components(grid) print("%s: %d cells" % (stats.name, v) + \ ", %d passages, %d walls, %d edges" % (p//2, w//2, e//2) + \ ", %d maze components" % k) degseq = stats.degree_counts() print(" Degree sequence: " + sorted_degrees(degseq)) # The maze is a tree if and only if both of the following # are true: # (a) the maze is passage-connected, and # (b) the number of passages is one less than the number # of cells. assert v is 35, "Vertex count error (got %s, expected v=5x7=35)" % v assert p is 68, "Passage count error (got %s, expected p=v-1=34)" % (p // 2) assert e is 126, "Edge count error (got %s, expected e=63)" % (e // 2) assert w is 58, "Wall count error (got %s, expected w=e-p=29)" % (w // 2) assert k is 1, "The maze is disconnected (got k=%d, expected k=1)" % k
def __init__(self, start_symbol, grammar, lr_type=0): self.grammar = grammar self.start_symbol = start_symbol self.state_sets = [] self.edges = {} self.ids = {} self.todo = [] self.done = set() self.maybe_compatible = {} self.goto_time = 0 self.add_time = 0 self.closure_time = 0 self.closure_count = 0 self.addcount = 0 self.weakly = 0 self.weakly_count = 0 self.mergetime = 0 helper = Helper(grammar) self.helper = helper if lr_type == LR0: self.closure = helper.closure_0 self.goto = helper.goto_0 self.start_set = StateSet( [LR0Element(Production(None, [self.start_symbol]), 0)]) elif lr_type == LR1 or lr_type == LALR: self.closure = helper.closure_1 self.goto = helper.goto_1 self.start_set = StateSet() self.start_set.add( LR0Element(Production(None, [self.start_symbol]), 0), set([FinishSymbol()]))
def start_fuzzing(self): Helper.delimiter_line() print "SOAP FUZZER" Helper.delimiter_line() self._wsdl = raw_input("WSDL URL: ") print("Please wait...") self._soap_client = SoapClient(wsdl=self._wsdl) self.get_ops_and_args() self.get_operations_to_fuzz() results = self.send_requests() self.save_data(results, "soap") self.present_results()
def admin_products(): if not g.user: return redirect('/') else: products = Product.query.all() form = ProductForm() #add product to db if form.validate_on_submit(): product = Product.form_to_model(form) #converting images into bytes like object #prepare images to be stored product.prepare_to_store() db.session.add(product) db.session.commit() flash('Product added to database', 'success') return redirect(f'/{get_route()}/view-products') else: for product in products: if product.available: product.availabile = 'Available' else: product.availabile = 'Sold' for product in products: product.prepare_to_show() organized_products = Helper.organize_products(products) return render_template('view-products.html', form=form, rows=organized_products, route=get_route())
def insert_params(self): more = True while more: Helper.delimiter_line() key = raw_input('Name of the parametar you want to fuzz :') fuzz = raw_input('Fuzz this parameter (Y/N):') if fuzz == 'Y' or fuzz == 'y' or fuzz == 'yes': self.request_params[key] = 'fuzz' else: self.request_params[key] = '' m = raw_input('Add more parameters (Y/N) ? ') if m == 'Y' or m == 'y' or m == 'yes' or m == '1': more = True else: more = False return 0
def _generate_decision_tree(self): self.root = Node(ROOT_NODE_NAME, assignment=self.assignment) if self.start_board is None: return Helper.generate_tree_level(self.root) Helper.generate_tree_level(self.root) Helper.generate_tree_level(self.root) Helper.generate_tree_level(self.root)
def return_products_page(): products = Product.query.filter_by(available=True).all() for product in products: product.prepare_to_show() for product in products: product.available = 'Available' organized_products = Helper.organize_products(products) return render_template('products2.html', rows=organized_products)
def __init__(self,dpi=100): self.dpi=dpi self.helper=Helper() logdir=os.path.join(os.getcwd(),'log') if not os.path.exists(logdir): os.mkdir(logdir) handlername=os.path.join(logdir,f'island.log') logpath=os.path.join(logdir,handlername) logging.basicConfig( handlers=[logging.handlers.RotatingFileHandler(logpath, maxBytes=10**6, backupCount=20)], level=logging.DEBUG, format="[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s", datefmt='%Y-%m-%dT%H:%M:%S') self.logger = logging.getLogger(handlername) self.klist=[3]#[2,4,6]#[25,50,100] self.resultsdictlist=[] self.figdict={} self.transform_record_dict={} self.TSHistogramlist=[] self.resultsDFdictlist=[] cwd=os.getcwd() self.datadir=os.path.join(cwd,'data') self.resultsdir=os.path.join(cwd,'results'); if not os.path.exists(self.resultsdir):os.mkdir(self.resultsdir) self.resultspath=os.path.join(self.resultsdir,'resultsdictlist.pickle') self.printdir=os.path.join(cwd,'print') if not os.path.exists(self.printdir): os.mkdir(self.printdir) self.datadictlistpath=os.path.join(self.datadir,'datadictlist.pickle') self.yeardummydict={f'dv_{i}':np.int16 for i in range(2002,2016)} self.yeardummylist=[key for key in self.yeardummydict] self.vardict,self.modeldict,self.std_transform=self.setmodel() self.varlist=[var for var in self.vardict] self.geogvars=['latitude','longitude'] self.fig=None;self.ax=None self.figheight=10;self.figwidth=10 DataView.__init__(self) IslandEffects.__init__(self)
def create_driver(): if EnvironmentConfig.BROWSER.lower() == "chrome": chrome_options = Options() chrome_options.add_argument("disable-infobars") chrome_options.add_argument("--start-maximized") return webdriver.Chrome( chrome_options=chrome_options, executable_path=Helper.get_file_by_relative_path( EnvironmentConfig.RESOURCES_FOLDER_PATH + "\chromedriver.exe")) if EnvironmentConfig.BROWSER.lower() == "firefox": return webdriver.Firefox()
def percentiles(): id = request.args.get('id') filter = request.args.get('filter') db = dbConnector() helper = Helper() db.set_id(id) data = db.get_listing() zipcode = data[0]['zipcode'] listing_price = data[0]['price'] prices = db.get_price_by_zip(zipcode) preds = helper.percents(float(listing_price), prices) property_type = data[0]['property_type'] data = db.get_percentile_totals(filter, zipcode, property_type) percentiles = [np.percentile(data, x) for x in range(10, 110, 10)] totals = helper.percentile_totals(percentiles, data) response = { 'total_listings': totals, 'filter': filter, 'pricing_percentiles': preds } return json.dumps(response, use_decimal=True)
def components(self, maze, v, e): """component count and characteristic""" k, _ = Helper.find_components(maze) key = 'k' if key not in self.legend: self.make_key(key, "Number of components (k)") self.make_moments(key, k) chi = v - e - k key = 'chi' if key not in self.legend: self.make_key(key, "Maze characteristic (v-e-k)") self.make_moments(key, chi) return k
def draw(self, widget, cr): helper = Helper(cr) alloc = widget.get_allocation() window = Rect.from_top_left(Point(0, 0), alloc.width, alloc.height) with helper.box(window.inset(5), clip=False) as bounds: radius = min(bounds.width, bounds.height) * 0.5 helper.circle(bounds.center, radius) cr.set_line_width(2.5) cr.stroke() cr.rotate(self.value) helper.circle(Point(radius/2, 0), radius/4) cr.fill()
def handle_download(download_page, params): """Original function""" global output_dir print(params) filename = archive_format(params) + ".pdf" volumes = {'Α': 'A', 'Β': 'B'} vol = volumes[params['issue_type']] year = params['issue_date'].year dirs = '{}/{}/{}'.format(vol, year, filename[6:9]) os.system('mkdir -p {}/{}'.format(output_dir, dirs)) outfile = '{}/{}/{}'.format(output_dir, dirs, filename) if os.path.isfile(outfile): print('Already a file') return try: # First we get the redirect link from the download page html = Helper.get_url_contents(download_page) beautiful_soup = BeautifulSoup(html, "html.parser") meta = beautiful_soup.find("meta", {"http-equiv": "REFRESH"}) download_link = meta['content'].replace("0;url=", "") # We do the same process twice because it involves 2 redirects. beautiful_soup = BeautifulSoup(Helper.get_url_contents(download_link), "html.parser") meta = beautiful_soup.find("meta", {"http-equiv": "REFRESH"}) download_link = meta['content'].replace("0;url=", "") except BaseException as e: print(e) return None print(filename) Helper.download(download_link, filename, output_dir + '/' + dirs) return filename
def getRenderEnv(self, cr, scale, window, stdin): return { 'cr': cr, 'cairo': cairo, 'math': math, 'stdin': stdin, 'window': window, 'scale_mm': scale, 'helpers': Helper(cr), 'Point': Point, 'Rect': Rect, 'time': time.time(), '__name__': 'render', 'params': self.getValues() }
def __init__(self, env=None, helper=None): if env is None: self.env = get_env() self.helper = Helper(self.env) else: self.env = env self.helper = helper assert (self.helper.env == env) # internal representation of the transition system self.state_vars = set() self.var_types = {} self.init = TRUE_PYSMT() self.trans = TRUE_PYSMT() self.final = FALSE_PYSMT()
def read_assessments(assessments_number): total_weight = 0 assessments_number = int(assessments_number) assessments = [] for x in range(0, assessments_number): print("\nData For assessment number:", x + 1) valid_assessment = False assessments_name_check = True assessments_weight_check = True while not valid_assessment: if assessments_name_check: assessments_name = input("Assessment name: ") if assessments_name: assessments_name_check = False if not assessments_name_check and assessments_weight_check: if x == (assessments_number - 1): valid_int_weight = True assessments_weight = 100 - total_weight valid_assessment = True assessments.append({ 'name': assessments_name, 'weight': assessments_weight }) else: assessments_weight = input("Assessment weight: ") valid_int_weight = Helper.is_int(assessments_weight) if not valid_int_weight: print( '\nInvalid, Please enter number greated than 0 and less than 100' ) else: assessments_weight = int(assessments_weight) if total_weight + assessments_weight > 100: print( '\nInvalid, total assessments weight can pass 100, weight available is', 100 - total_weight) else: assessments_weight = assessments_weight total_weight += assessments_weight valid_assessment = True assessments.append({ 'name': assessments_name, 'weight': assessments_weight }) return assessments
def _create_assignments(self, board): self.assignments_completed = 0 self.assignments_sent = 0 self.root = Node(ROOT_NODE_NAME, assignment=None) Helper.generate_tree_level(self.root, board) Helper.generate_tree_level(self.root) Helper.generate_tree_level(self.root)
def _get_relation_enc(self, edge_rel): """ Encode x' = Ax + b +- error as Ax + b - error <= x' /\ x' <= Ax + b + error """ assert len(self.pysmtvars) == len(edge_rel.A) assert len(self.pysmtvars) == len(edge_rel.b) assert len(self.pysmtvars) == len(edge_rel.error.l) assert len(self.pysmtvars) == len(edge_rel.error.h) rel_enc = [] for i in range(len(self.pysmtvars) * 2): if (i < len(self.pysmtvars)): i_index = i e_e_smt = self.to_real(edge_rel.error.h[i]) else: i_index = i - len(self.pysmtvars) e_e_smt = self.to_real(edge_rel.error.l[i_index]) a_row = edge_rel.A[i_index] b_e_smt = self.to_real(edge_rel.b[i_index]) current_var = self.pysmtvars[i_index] var_next = Helper.get_next_var(current_var, self.pysmt_env.formula_manager) # row - column product assert len(self.pysmtvars) == len(a_row) row_column = None for (var, a_el) in zip(self.pysmtvars, a_row): row_elem = Times(self.to_real(a_el), var) if row_column is None: row_column = row_elem else: row_column = Plus(row_column, row_elem) assert row_column is not None if (i < len(self.pysmtvars)): pred = LE(var_next, Plus(row_column, b_e_smt, e_e_smt)) else: pred = LE(Plus(row_column, Plus(b_e_smt, e_e_smt)), var_next) rel_enc.append(pred) return rel_enc
def RFID(request): logic = Logic() helper = Helper() if request.method == 'POST': rfid = str(request.body).split('"')[3].replace(" ", "") if settings.DEBUG: print(rfid) if rfid is None: if settings.DEBUG: print('no se recibio rfid') return HttpResponse('No se recibió RFID\n') else: access_logs = logic.get_access_logs_today() exists = False for log in access_logs: if rfid == log.RFID: exists = True break if exists: if settings.DEBUG: print('El usuario ya se ha registrado') return HttpResponse('El usuario ya se ha registrado') else: if len(rfid) < 7: try: diner = Diner.objects.get(RFID=rfid) new_access_log = AccessLog(diner=diner, RFID=rfid) new_access_log.save() except Diner.DoesNotExist: new_access_log = AccessLog(diner=None, RFID=rfid) new_access_log.save() else: if settings.DEBUG: print('RFID Inválido\n') return HttpResponse('RFID Inválido\n') return HttpResponse('Operacion Terminada\n') else: return redirect('diners:diners')
def new_module(): module_name_check = True module_code_check = True should_ask_for_assessment = False have_valid_assessment = False valid_assessments_number = 0 while module_name_check or module_code_check or should_ask_for_assessment: if module_name_check: module_name = input("Module name: ") if module_name: module_name_check = False if not module_name_check and module_code_check: module_code = input("Module Code: ") if module_code: module_code_check = False should_ask_for_assessment = True if should_ask_for_assessment: assessments_number = input("Number of Assessments: ") if assessments_number: valid_assessments_number = Helper.is_int( assessments_number) if not valid_assessments_number: print( '\nInvalid, Only integer number allowed, Please enter number greater than 1' ) else: should_ask_for_assessment = False have_valid_assessment = True module_assessments = Reader.read_assessments( assessments_number) module = { 'name': module_name, 'code': module_code, 'assessments': module_assessments } module = Module(module) Reader.save_module(module)
def __init__(self, module_name, init_cons, final_cons, pwa_graph, vs, init_ps, final_ps): self.module_name = module_name assert isinstance(init_cons, constraints.IntervalCons) self.init_cons = init_cons assert isinstance(final_cons, constraints.IntervalCons) self.final_cons = final_cons assert isinstance(pwa_graph, pwa.pwagraph.PWAGraph) self.pwa_graph = pwa_graph assert isinstance(vs, list) and (not len(vs) > 0 or isinstance(vs[0], unicode)) self.vs = vs assert isinstance(init_ps, set) and (not len(init_ps) > 0 or isinstance( next(iter(init_ps)), pwa.pwa.Partition)) self.init_ps = init_ps assert isinstance(final_ps, set) and (not len(final_ps) > 0 or isinstance( next(iter(final_ps)), pwa.pwa.Partition)) self.final_ps = final_ps self._ts = None # encoding of the graph locations self.pysmt_env = get_env() self.helper = Helper(self.pysmt_env) self._loc_enc = None # Object used to encode the location with a counter self.val2loc = None # map from value to locations (as represented in the graph) self.loc2val = None # map from location (as rep. in graph) to the encoding value self.val2edge = None # map from value to transition self.edge2val = None # map from transition to value self.pysmtvars = None # List of pysmt variables (same position as self.vs) self.pysmtvars2index = { } # map from variables in the ts to the index used in vs self.locval2bool = None self.edgeval2bool = None
def check_maze(grid): """check that the maze is perfect We want the maze to be a spanning tree of the grid. If v is the number of vertices, e the number of edges, and k the number of components, we want to satisfy both the following conditions: (1) k = 1 (the maze is connected) (2) v = e + 1 (every edge is a bridge, given k=1) Since edges are counted in the manner of Euler, we count each edge twice. Note: Loops are not counted here with multiplicity, but the assertion will fail (as it should) if any loops occur. """ m, n = grid.rows, grid.cols v = m * n # number of vertices e = 0 # number of arcs (2e) for cell in grid.each(): e += len(cell.arcs) # Euler counting k, _ = Helper.find_components(grid) # note: e is twice the number of edges assert e + 2 == 2 * v and k == 1, \ "v=%d, 2*e=%d, k=%d - not a tree" % (v, e, k)
destination = 'horse008.xlsx' wb = openpyxl.load_workbook(filename=source) sheet = wb.active # top start B4 top end DF4 bottom start B123 bottom end DF123 BOARD_RANGE = 'B4:DF123' # tuple of style_id where cell is empty EMPTY_CELLS = (1, 3, 4, 6, 7, 8, 9, 11, 18) top_border = 3 # sheet.BREAK_ROW left_border = 1 # sheet.BREAK_COLUMN rows = len(sheet.rows) - top_border cols = len(sheet.columns) - left_border print(rows, cols) start = (0, 0) # start point finish = (119, 108) # end point helper = Helper(rows, cols, start) queue = deque() # parents array with points parents = dict() results = [] coordinates = [] walls = dict() # matrix = [[0] * cols for i in range(rows)] for i, row in enumerate(sheet.iter_rows(BOARD_RANGE)): for j, cell in enumerate(row): if cell.style_id not in EMPTY_CELLS: # matrix[i][j] = -1 walls[(i, j)] = -1