content
stringlengths
22
815k
id
int64
0
4.91M
async def send_ping(ws): """Send pings to the web browser""" while True: await ws.send(f'{datetime.utcnow().timestamp()}') await asyncio.sleep(1)
44,400
def zip_to_file(item_name): """Zips a folder to a .zip file and deletes the folder. Args: item_name (str): The name of the folder to zip. """ try: subprocess.run('7z a "' + sys.argv[1] + '.zip" "' + sys.argv[1] + '"') except Exception as e: print(f"A problem occured when zi...
44,401
def simplify(expr, *exprs, **kwargs): """Simplify the given expression[s].""" if exprs: return _coconut_tail_call((tuple), (map)(lambda x: x.simplify(**kwargs), (expr,) + exprs)) else: return _coconut_tail_call(expr.simplify, **kwargs)
44,402
def ratek_fit_info(rxn_dstr): """ Read the information describing features of the fits to the rate constants """ # Read the temperatures and the Errors from the lines pressure_ptt = ( 'Pressure:' + app.SPACES + app.capturing(app.one_of_these([app.FLOAT, 'High'])) ) trang...
44,403
def get_news_story(story_id, raw_output=False, debug=False): """ Return a single news story corresponding to the identifier provided in story_id Parameters ---------- story_id: string The story id is a field you will find in every headline you retrieved with the function get_news_headlines....
44,404
def p_constants_def(p): """constants_def : LPAREN CONSTANTS_KEY typed_constants_lst RPAREN""" domain_constants = p[3] for term in domain_constants: domain_constants_types[term.value.value] = term.type
44,405
def append_to_output(read, output_file): """Appends read to output file. Keyword arguments ================= :param read: list List of the four strings of one fastq read (no default) :param output_file: str Name of file to append new lines to (no default) :return: append...
44,406
def ifrt2(a): """Compute the 2-dimensional inverse finite radon transform (iFRT) for an (n+1) x n integer array. Parameters ---------- a : array_like A 2-D (n+1) row x n column integer array. Returns ------- iFRT : 2-D n x n ndarray Inverse Finite Radon Transform array ...
44,407
def get_levelized_cost(solution, cost_class='monetary', carrier='power', group=None, locations=None, unit_multiplier=1.0): """ Get the levelized cost per unit of energy produced for the given ``cost_class`` and ``carrier``, optionally for a subset of technologie...
44,408
def weighting_system_c(): """C-weighting filter represented as polynomial transfer function. :returns: Tuple of `num` and `den`. See equation E.1 of the standard. """ f1 = _POLE_FREQUENCIES[1] f4 = _POLE_FREQUENCIES[4] offset = _NORMALIZATION_CONSTANTS['C'] numerator = np....
44,409
def make_fully_qualified_url(url): """ Ensure url is qualified """ if url.startswith("//"): return "https:" + url if url.startswith("/"): return "https://en.wikipedia.org" + url assert url.startswith("http"), "Bad URL (relative to unknown location): " + url return url
44,410
def reduce_range_overlaps(ranges): """Given a list with each element is a 2-tuple of min & max, returns a similar list simplified if possible. """ ranges = [ea for ea in ranges if ea] if len(ranges) < 2: return ranges first, *ranges_ordered = list(reversed(sorted(ranges, key=lambda ea: ea[1] - e...
44,411
async def setup_comp_2(hass): """Initialize components.""" _setup_sensor(hass, 45) hass.states.async_set(ENT_SWITCH, STATE_OFF) await hass.async_block_till_done() assert await async_setup_component( hass, DOMAIN, { "humidifier": { "platform": "gene...
44,412
def run_cache(mode, start_datetime: str, end_datetime: str, yes: bool): """Cache CLI entrypoint""" if mode not in MODES: raise ValueError(f"`mode` must be one of `{MODES}`. Value `{mode}` is given") start_datetime_parsed = dateutil.parser.parse(start_datetime) if start_datetime else None end_dat...
44,413
def get_averages_by_addon_from_bigquery(today, exclude=None): """This function is used to compute the 'hotness' score of each add-on (see also `update_addon_hotness()` cron task). It returns a dict with top-level keys being add-on GUIDs and values being dicts containing average values.""" client = c...
44,414
def tune_mean_shift(x, y, bandwidth_range=None, save_path='meanshift-tune.csv', disable_tqdm=False): """ x, y are testing set """ from tqdm import tqdm rows = [] if bandwidth_range is None: bandwidth_range = np.arange(0.05, 1, 0.05) for bandwidth in tqdm(bandwidth_range, disable=d...
44,415
def main_menu(): """Dialog for the ATM Main Menu.""" # Determines action taken by application. action = questionary.select( "Would you like to check your balance, make a deposit or make a withdrawal?", choices=["check balance", "deposit", "withdrawal"], ).ask() return action
44,416
def load_sentences_from_naf(iteration, root, naf_entity_layer, modify_entities): """Load sentences from a single NAF file (already loaded). Potentially replace entity mentions with their identity.""" if modify_entities: to_replace=map_mentions_to_identity(root, naf_entity_layer) # Create list of l...
44,417
def aggregate_similar_keywords(kw1: str, kw2: str): """Maps 2 keywords to one entity if the are similar. Example: {battery life, battery} -> battery {graphic, graphics} -> graphics {graphic quality, graphics} PASS! 1st run: Unigrams: Base algorithm on edit distance; map to longer element (takes...
44,418
def connect(configFile=False, conf=False, do_logging=False, data=False, dataFormat='n3'): """ Load desired configuration and open the database :param configFile: (Optional) The configuration file for PyOpenWorm :param conf: (Optional) If true, initialize...
44,419
async def test_shutdown(zeus): """Test that the homepage responds with 200 and contains the service name""" await zeus.app.shutdown()
44,420
def get_detection_eff_matrix(summary_table, num): """Computes the detection efficiency matrix for the input detection summary table. Input argument num sets the maximum number of true objects per blend in the test set for which the detection efficiency matrix is to be created for. Detection efficiency ...
44,421
def unicode_to_base64(text, strip_newlines=True): """Safe conversion of ``text`` to base64 representation using utf-8 bytes. Strips newlines from output unless ``strip_newlines`` is `False`. """ text = to_unicode(text) if strip_newlines: return text.encode('utf-8').encode('bas...
44,422
def init_permission(request, user_obj): """ 初始化用户权限, 写入session :param request: :param user_obj: :return: """ #模块ID列表 phead_menu_item_list = user_obj.roles.filter(permissions__status=1).values('permissions__menu__parent_id').distinct() if user_obj.is_superuser == 1: phead_men...
44,423
def _valid_path(g, path, master_nodes): """ Test if path contains masternodes. """ valid = True if path[0] not in master_nodes: valid = False if path[-1] not in master_nodes: valid = False for n in path[1:-1]: if 'pin' in g.node[n]: # if _is_master(g, n): # ...
44,424
def usgs_stonecr_call(*, resp, year, **_): """ Convert response for calling url to pandas dataframe, begin parsing df into FBA format :param url: string, url :param resp: df, response from url call :param year: year :return: pandas dataframe of original source data """ df_raw_data_tw...
44,425
def read_line(**kwargs): """ Gets next line in input. If `skip_empty` is True, only lines with at least one non-whitespace character are returned. :return: str """ tokenizer = _get_tokenizer(kwargs) skip_empty, rstrip = kwargs['skip_empty'], kwargs['rstrip'] try: if skip_empty: ...
44,426
def _coco17_category(): """ Get class id to category id map and category id to category name map of COCO2017 dataset """ clsid2catid = { 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, ...
44,427
def identical_sort(df_true, df_subm): """ Check if 2 DataFrames are sorted the same This check is only conducted whenever a perfect F1 score is achieved. It only verifies whether or not the first and last tuple have the same relative order in both DataFrames. It is thus not an explicit check! ...
44,428
def bigbird_block_sparse_attention( query_layer, key_layer, value_layer, band_mask, from_mask, to_mask, from_blocked_mask, to_blocked_mask, rand_attn, num_attention_heads, num_rand_blocks, size_per_head, batch_size, from_seq_length, to_seq_length, from_block_size, to_block_size): """BigBird attention ...
44,429
def color_diff(rgb_x: np.array, rgb_y: np.array) -> float: """ Computes the distance between two colors using Euclidean distance. :param rgb_x: a vector of one rbg color :param rgb_y: a vector of another rgb color :return: the distance between two vectors """ return np.sum((rgb_x - rgb_y) *...
44,430
def parse_args(args): """ Parses the arguments of the benchmark plot cli Arguments: args: Program arguments, excluding first argument (filename being executed) """ parser = argparse.ArgumentParser(description="Jet benchmark plot tool") parser.add_argument( "-c", "--config...
44,431
def update(): """ Adds, commits and pushes changes to git repos. Prints a message if source is not present. """ fullpaths = [] py = os.listdir("/home/mic/python/") site = os.listdir("/usr/share/nginx/html/") clean_site = [i for i in site if i != "setup.cfg"] for i in py: ...
44,432
def functions(node): """:returns: list of function tags for node, or an empty list.""" if not node.source: return [] a = node.source[FUNC] if a == '--' or a == '' or a is None: return [] return a.split('-')
44,433
def test_cql_not_like(cql_config): """Testing query for filter, startindex and CQL filter expression""" p = GeoJSONProvider(cql_config) results = p.query(cql_expression='name NOT LIKE "%Lake%"') assert len(results['features']) == 7 assert results['numberMatched'] == 7 assert results['numberRetu...
44,434
def _calibrate_bg_and_psf_im(im, divs=5, keep_dist=8, peak_mea=11, locs=None): """ Run background & PSF calibration for one image. These are typically combined from many fields and for each channel to get a complete calibration. This returns the accepted locs so that a z-stack can be estimated ...
44,435
def get_default_database_engine(rm: ResourceManager, database_name: str) -> Engine: """ Get the default engine of the database. If the default engine doesn't exists raise FireboltError """ database = rm.databases.get_by_name(name=database_name) bindings = rm.bindings.get_many(database_id=databa...
44,436
def _execute_onestep(seq, order=2, verbose=False): """ This function runs one full step of the non-sequential recursive window- substitution algorithm. (For pairs or order=2, called NSRPS). For internal use only, as this function does not carry out sanity checks. For general/external usage, refer t...
44,437
def getModulePower(): """Returns the current power consumption of the entire module in mW.""" return float(readValue(i2cAddr='0041', channel='0', valType='power'))
44,438
def roots(repo, subset, x): """``roots(set)`` Changesets in set with no parent changeset in set. """ s = set(getset(repo, repo.changelog, x)) subset = [r for r in subset if r in s] cs = _children(repo, subset, s) return [r for r in subset if r not in cs]
44,439
def title_case_action_groups(parser): """Capitalize the first character of all words in the title of each action group of the passed parser. This is useful for consistency when using the sphinx argparse extension, which title-cases default action groups only. """ for action_group in parser._action_groups:...
44,440
def _as_path_test(ctx): """Unit tests for maprule_testing.as_path.""" env = unittest.begin(ctx) asserts.equals( env, "Foo\\Bar\\Baz\\Qux", maprule_testing.cmd_strategy.as_path("Foo/Bar/Baz\\Qux"), msg = "assertion #1", ) asserts.equals( env, "Foo/Bar/B...
44,441
def alpha_optimisation (problem, alpha_range=np.arange(0.0, 1.1, 0.1)): """ This method is used to optimise the alpha parameter. Alpha parameter is used in the calculation of edges savings: saving = distance_saving * (1 - alpha) + revenue * alpha The higher is alpha the bigger is the importanc...
44,442
def _codify_quantitative_input_by_abs_val( df: pd.DataFrame, threshold: float, p_value: float, ) -> Dict[str, int]: """Codify nodes with | logFC | if they pass threshold, otherwise score is 0.""" # Codify nodes with | logFC | if they pass threshold df.loc[(df[LOG_FC]).abs() >= threshold, SCORE] ...
44,443
def labor_day(date: dt.date) -> Optional[str]: """First Monday in September""" if not is_nth_day(date, 0, 0, 9): return None return "Happy Memorial Day. You can wear white again"
44,444
def test_absolute(): """Check that absolute paths are returned unchanged.""" assert '/tmp/foo' == expand_path('/tmp/foo')
44,445
def PyUnicode_InternInPlace(space, string): """Intern the argument *string in place. The argument must be the address of a pointer variable pointing to a Python unicode string object. If there is an existing interned string that is the same as *string, it sets *string to it (decrementing the reference...
44,446
def vgg16(reparametrized=False, **kwargs): """VGG 16-layer model (configuration "D") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = VGG(make_layers(cfg['D'], reparametrized=reparametrized), **kwargs) return model
44,447
def logout(request): """ :param request: :return: """ auth_logout(request) return redirect('/')
44,448
async def main(): """ Place your code here. """ pass
44,449
def vec3d_rand_corners(corner1, corner2): """ Sample one R3 point from the AABB defined by 'corner1' and 'corner2' """ span = np.subtract(corner2, corner1) sample = vec_random(3) return [corner1[0]+span[0]*sample[0], corner1[1]+span[1]*sample[1], corner1[2]+span[2]*sample...
44,450
def app(): """Yield an application for the tests.""" _app = create_app(TestingConfig) with _app.app_context(): _db.create_all() minimum_legal_age = GlobalSetting( name='Minimum legal age', key='MINIMUM_LEGAL_AGE', value=18 ) max_daily_alc...
44,451
def exception_in_stack(): """Return true if we are currently in the process of handling an exception, ie one has been caught in a try block. https://docs.python.org/3/library/sys.html#sys.exc_info """ return sys.exc_info()[0] is not None
44,452
def validate_terminology(table, gecko_labels): """Validate an IHCC mapping table.""" basename = os.path.splitext(os.path.basename(table))[0].capitalize() problems = [] problem_count = 0 # label -> locs labels = {} # loc -> parent_term parent_terms = {} lines = [] with open(table...
44,453
def meta_body(): """Ugoira page data.""" return '{"error":false,"message":"","body":{"src":"https:\/\/i.pximg.net\/img-zip-ugoira\/img\/2019\/04\/29\/16\/09\/38\/74442143_ugoira600x600.zip","originalSrc":"https:\/\/i.pximg.net\/img-zip-ugoira\/img\/2019\/04\/29\/16\/09\/38\/74442143_ugoira1920x1080.zip","mime_...
44,454
def anatomical_traverse_bids(bids_layout, modalities='anat', subjects=None, sessions=None, extension=('nii', 'nii.gz', 'json'), param_files_required=False, ...
44,455
def get_email_subscriptions(email): """Verifies which email subsciptions exist for the provided email Parameters ---------- email : str The email to the check subscriptions for Returns ------- list(tuple(str, str, query_hash)) """ user_queries = db.get_subscribed_queries(em...
44,456
def save_content_to_csv(fname, fcontent, mode='w', delimiter=',', encoding='utf8'): """ Save fcontent in a csv file with the specifications provided in arguments. """ with open(fname, mode, encoding='utf8') as csvfile: writer = csv.writer(csvfile, delimiter=delimiter,...
44,457
def format_comments(text="default", line_size=90): """ Takes a string of text and formats it based on rule 1 (see docs). """ # rules to detect fancy comments, if not text regex1 = r"^ *?####*$" # rules to detect fancy comments, if text regex2 = r"^ *?####*([^#\n\r]+)#*" # if detected pat...
44,458
def get_test_composer_result(self,result_file=u'composer.log'): """ Get the result of test composer script """ cli = self._clients[self._cur_name] ix = cli['connection'] BuiltIn().log("Get test composer result") composer_runner = None quicktest_list = ix.getList(ix.getRoot() + 'quickT...
44,459
def get_kernel_versions_async(loop=None): """ Execute dpkg commands asynchronously. Args: loop: asyncio event loop (optional) Returns: [DpkgCommandResult]: stats from the executed dpkg commands """ return subprocess_workflow.exec_and_parse_subprocesses_async( [DpkgComma...
44,460
def new(name): """ create new desktop (short: /n). Number is stored in pipeline.""" command([EXE, f'-New']) rename(name, count()-1)
44,461
def plot_roc_curve(list_of_fpr, list_of_tpr, area_under_curve, plot_title="title", line_color = "dodgerblue", return_plot=False, save_plot = False, output_name = "output.png"): ...
44,462
def autoencoder( input_shape, encoding_dim=512, n_base_filters=16, batchnorm=True, batch_size=None, name="autoencoder", ): """Instantiate Autoencoder Architecture. Parameters ---------- input_shape: list or tuple of four ints, the shape of the input data. Should be scale...
44,463
def par_s1_slc_single(safe_dir, pol='vv', orbit_file=None): """Pre-process S1 SLC imagery into GAMMA format SLCs Args: safe_dir: Sentinel-1 SAFE directory location pol: polarization (e.g., 'vv') orbit_file: Orbit file to use (will download a matching orbit file if None) """ wrk ...
44,464
def run(url, cmd, log_path, log_level, log_session, force_discovery, print_info): """Main function.""" log_level = log_levels[log_level] conn = condoor.Connection("host", list(url), log_session=log_session, log_level=log_level, log_dir=log_path) try: conn.connect(force_discovery=force_discovery)...
44,465
def entities_generator(doc, params: dict): """Return entities in doc as a generator""" engine = params["engine"] for ent in engine.document_entities(doc): yield Entity( start=engine.entity_span_start(ent), end=engine.entity_span_end(ent), type=engine.entity_type(e...
44,466
def SHAPER(B, D, LA): """ """ LB = B.size LD = D.size A = numpy.zeros(LA) LC = LB + LA - 1 LCD = LC + LD - 1 C = numpy.zeros(LCD) INDEX = 0 ERRORS = numpy.zeros(LCD) SPACE = numpy.zeros(3 * LA) (A, LC, C, INDEX, ERRORS, S) = ER.SHAPER(LB, B, LD, D, LA, A, LC, C, INDEX, E...
44,467
def _get_efron_values_single( X: pd.DataFrame, T: pd.Series, E: pd.Series, weights: pd.Series, entries: None, beta: np.ndarray ) -> Tuple[np.ndarray, np.ndarray, float]: """ Calculates the first and second order vector differentials, with respect to beta. Note that X, T, E are assume...
44,468
def Interp_photometry_nosum(grid, wteff, wlogg, wmu, jteff, jlogg, jmu, area, val_mu): """ Simple interpolation of an atmosphere grid having axes (logtemp, logg, mu). Note: As opposed to Interp_photometry, this function does not sum the surface elements. Parameters ---------- The interpola...
44,469
def get_and_save_data(_=None): """Download data from John Hopkins, do some processing, and save as pickles Args: _: Empty variable. Was needed for the Google Cloud Function to work """ tot_deaths_df = load_raw_covid_file(DEATHS_FILE) tot_cases_df = load_raw_covid_file(CASES_FILE) uid_p...
44,470
def main(): """Main function""" # Requests headers headers={ "Authorization": f"token {args.token}", "Accept": "application/vnd.github.ant-man-preview+json" } # Get the URL formatting function url = url_formatter(*args.url) # Get all deployments response = requests.get(url()...
44,471
def get_battery_information(): """Return device's battery level.""" output = adb.run_adb_shell_command(['dumpsys', 'battery']) # Get battery level. m_battery_level = re.match(r'.*level: (\d+).*', output, re.DOTALL) if not m_battery_level: logs.log_error('Error occurred while getting battery status.') ...
44,472
def kolakoski(): """ Kolakoski Sequence: the nth term the length of the nth run of values """ yield 1 yield 2 L = [2] for digit in cycle([1,2]): run = L.pop(0) L += [digit]*run yield run
44,473
def _tensor_setitem_by_tuple_with_tuple(data, tuple_index, value): """ Tensor assignment. Note: Syntax support: A[B, C, D] = U. Restraint condition: 1) A is a Tensor, and B, C, D are index Tensors. 2) A B and C could be broadcast. 3)...
44,474
def openscad_stl_export(scad_file: Path, part: str, out_dir: Path): """ Export stl components from an openscad model. """ out_dir.mkdir(parents=True, exist_ok=True) out_filename = out_dir/"{}.stl".format(part) openscad_cmd = "openscad -o {} -Dpart=\"{}\" {}".format(out_filename, part, scad_file)...
44,475
def templates_global_context(request): """ Return context for use in all templates. """ global_context = { 'constant_ddd': constants.DDD, 'constant_estado': constants.ESTADO, 'constant_municipio': constants.MUNICIPIO, 'constant_cep': constants.CEP, 'constant_pais': constants.PAIS, 'constant_current_year...
44,476
def doubleunet(num_classes, input_shape=(224, 224, 3), model_weights=None, num_blocks=5, encoder_one_type='Default', encoder_one_weights=None, encoder_one_freeze=False, encoder_one_filters=[32, 64, 128, 256, 512], ...
44,477
def get_calendar_name(request): """ # Checks if the user has a saved calendar name and returns it """ # TODO: Try-except should be replaced try: if request.user.options.calendar_name: # Saved in options return request.user.options.calendar_name except AttributeErr...
44,478
def get_lldp_neighbors(dut, interface=None): """ Get LLDP Neighbours Info Author: Prudvi Mangadu (prudvi.mangadu@broadcom.com) :param dut: :param interface: localport :return: """ command = "show lldp neighbors" if interface: command = "show lldp neighbors {}".format(interfac...
44,479
def encode_onehot(batch_inputs, max_len=None): """One-hot encode a string input.""" if max_len is None: max_len = get_max_input_len() def encode_str(s): tokens = CTABLE.encode(s) unpadded_len = len(tokens) if unpadded_len > max_len: raise ValueError(f'Sequence too long ({len(tokens)}>{max_...
44,480
def test_spending_by_award_foreign_filter(client, test_data): """ Verify that foreign country filter is returning the correct results """ resp = client.post( "/api/v2/search/spending_by_award/", content_type="application/json", data=json.dumps( { "filters": {...
44,481
def plot_confusion_matrix(cm, normalize=True, title=None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. plt.show() must be run to view th...
44,482
def statsd_metric(name, count, elapsed): """Metric that records to statsd & graphite""" with statsd.pipeline() as pipe: pipe.incr(name, count) pipe.timing(name, int(round(1000 * elapsed)))
44,483
def test_get_action_from_num(dronem_env): """ Function to test the get action number function """ metadata = dronem_env.get_env_metadata() max_memory = metadata['max_memory'] pair_mapping = [(0, 1), (0, 2), (1, 2)] interpreted_actions = [ (Exchange(pair_mapping[0][0], pair_mapping[0...
44,484
def get_capped_cluster(atoms, folder_path, file_name, save_traj, EF_O_index): """ #TODO: check whether capping is necessary Inconsistent capping (remove all caps for now, does not need this cluster to be physical) Possible fix: change mult in neighbor list Extract smaller cluster containing the extra-f...
44,485
def get_min_and_max() -> None: """This function finds minimum and maximum values in input list of 3 elements.""" COUNT = 3 values = [] for i in range(COUNT): values.insert(i, get_integer_from_input()) print('provided values is', values) print('min = {}, max {}'.format(min(values), max...
44,486
def speed(input_file, coefficient=1.25): """ Speed or shrink a wave. Args: - infile (str) : Input filename. - coefficient (float) : coefficient caracterising the speeding degree. """ # set-up variables for paths and file names name_attribute = "_augmented_speeded.wav" ...
44,487
def detect_id_type(sid): """Method that tries to infer the type of abstract ID. Parameters ---------- sid : str The ID of an abstract on Scopus. Raises ------ ValueError If the ID type cannot be inferred. Notes ----- PII usually has 17 chars, but in Scopus ther...
44,488
def config_to_dict(plato_config): """ Convert the plato config (can be nested one) instance to the dict. """ # convert the whole to dict - OrderedDict plato_config_dict = plato_config._asdict() def to_dict(elem): for key, value in elem.items(): try: value = value._a...
44,489
async def epub_fix_enable_callback(event: events.CallbackQuery.Event): """Epub Fix callback handler""" message: Message = await event.get_message() lang = get_lang(event.chat_id) epub_button_row: List[MessageButton] = message.buttons.pop(-1) if event.data == event.data == b"epub_keep": epub_...
44,490
def analyze_single_user_info(result=load_data()): """ :param result: :return: examp: {user_id: 1, meal_info: {breakfast:{food_name:菜名,times:次数}}, {early_dinner:{...}}, {supper:{...}}} """ result = pd.DataFrame(result, columns=['user_id', 'user_name', 'food_code', 'food_name', 'meal_type', '...
44,491
def mergeSort(data): """ Implementation of the merge sort algorithm in ascending order """ n = len(data) if n == 1: return data else: midIndex = (int)(n/2) leftHalf = mergeSort(data[0:midIndex]) rightHalf = mergeSort(data[midIndex:n]) return mergeHalves(leftHalf,...
44,492
def compute_gradient_logistic(y, tx, w): """Function to compute gradient of loss of logistic regression for given w. Args: y (numpy array): Matrix output of size N x 1. tx (numpy array): Matrix input of size N x D. w (numpy array): Matrix weight (parameters of the model) of size D x 1....
44,493
def parse_py(fname): """Look for links in a .py file.""" with open(fname) as f: lines = f.readlines() urls = set() for i, line in enumerate(lines): for url in find_urls(line): # comment block if line.lstrip().startswith('# '): subidx = i + 1 ...
44,494
def lwp_cookie_str(cookie): """Return string representation of Cookie in an the LWP cookie file format. Actually, the format is extended a bit -- see module docstring. """ h = [(cookie.name, cookie.value), ("path", cookie.path), ("domain", cookie.domain)] if cookie.port is not No...
44,495
def test_error_code(conn_cnx): """Error code is included in the exception.""" with conn_cnx() as ctx: try: ctx.cursor().execute("SELECT * FROOOM TEST") raise Exception('Failed to detect Syntax error') except errors.ProgrammingError as e: assert e.errno == 1003...
44,496
def reg_signal(loop, hassio): """Register SIGTERM, SIGKILL to stop system.""" try: loop.add_signal_handler( signal.SIGTERM, lambda: loop.create_task(hassio.stop())) except (ValueError, RuntimeError): _LOGGER.warning("Could not bind to SIGTERM") try: loop.add_signal_h...
44,497
def process_eyes(roi_gray_image, roi_color, roi_color_out, create_mask): """ Image detection function to detect and return segmented mask of blue pixels in roi_color_out :param roi_gray_image: grayscale version cv2 image used for detection. :param roi_color: color version of cv2 image used for detectio...
44,498
def fiscalyear(): """Retrieve Fiscal Years and display for selection by user.""" cascs = db.session.query(casc).order_by(casc.name).all() cascs_and_fys = {} class F(FyForm): pass list_fy = [] for curr_casc in cascs: cascs_and_fys[curr_casc.name] = {} cascs_and_fys[curr_...
44,499