content
stringlengths
22
815k
id
int64
0
4.91M
def test_distribution_structures6(): """ A test for the distribution_structures strategy. """ dists = distribution_structures(size=3, alphabet=2, uniform=True) example = find(dists, predicate) assert coinformation(example) <= -1 / 2
5,307,700
def channels(N: int, radix: int) -> Iterator[Tuple[int, Iterator[int]]]: """Given a 1-d contiguous array of size N, and a FFT of given radix, this returns a map of iterators of the different memory channels.""" parity_r = partial(parity, radix) return groupby(sorted(range(N), key=parity_r), parity_r)
5,307,701
def SeleniumWebDriver(**kwargs): """ This context manager is designed to create Selenium's Web Driver. It assumes that BMPDaemon is already up. It returns web_driver. In the exit from the code block inside context-manager, it closes web_driver, see closeSeleniumWebDriver(). :param browsermobpr...
5,307,702
def positive_float(value): """An argparse type method for accepting only positive floats""" try: fvalue = float(value) except (ValueError, TypeError) as e: raise ArgumentTypeError( "Expected a positive float, error message: " "{}".format(e) ) if fvalue <= 0: r...
5,307,703
def readfile(space, fname, use_include_path=False, w_ctx=None): """ readfile - Outputs a file """ fname, read_filters, write_filters = _parse_wrapper(fname) if fname == "" or fname is None: space.ec.warn("readfile(): Filename cannot be empty") return space.w_False if not _valid_fname(fn...
5,307,704
def _match_tags_to_names(tag_names): """ INPUT: tag1,tag2,tag3 OUTPUT: <Tag: tag1>, ..., <Tag: tag3> NOTE: Tags NOT created BEFORE being added to new_machine_tags are ignored. """ matches = [Q(name__iexact=name.strip()) for name in tag_names.split(',')] filters = reduce(operator.or_, matches...
5,307,705
def eval_ws(in_data, ws_labels, n_map, label=None, re_all=False): """Evaluate and return the best watershed prediction result Parameters ---------- in_data : np.array or list data matrix ws_labels : np.array predicted cluster labels from watershed segmentation n_map : np.array ...
5,307,706
def close(*args): """Call plt.close() on any Figure objects or lists of Figure objects passed in. If nothing is passed, all Figure objects are closed with plt.close('all')""" if(args): for a in args: if(hasattr(a, '__len__')): for b in a: plt.close(b.numbe...
5,307,707
def main(): """ entry for console """ download_path = get_download_path() try: args = parse_argument(download_path) except SystemExit as e: if e.code == 1: download_status = "Failed" exit_status = 1 else: download_status = "Success" ...
5,307,708
def team_width(positions, points=False): """Returns the maximum string width of a team.""" width = 0 for position in positions: if points: player_names = [PICKS_FORMAT.format( player.name, player.gameweek_points, player.role) for player in position] ...
5,307,709
def pull(image_name_tag): """ Pull single image from bw dockerhub """ try: shell(f"docker pull {image_name_tag}") except: error(f"ERROR: Image {image_name_tag} not found", exit=False)
5,307,710
def construct_bbox(all_points): """ Construct the bounding box based on all points from the road and buildings that were discretised. """ maximum = list(map(max, zip(*all_points))) minimum = list(map(min, zip(*all_points))) bbox = [(minimum[0], minimum[1]), (minimum[0], maximum...
5,307,711
def OpenDocument(filePath) -> NexDoc: """Opens a data file with the specified path. Returns a reference to the opened document.""" return NexRun("OpenDocument", locals())
5,307,712
def test_div(x, y): """Compute complex z=x*y, and check that z/x==y and z/y==x.""" global nerrors z = x * y if x != 0: q = z / x if not check_close(q, y): nerrors += 1 print "%r / %r == %r but expected %r" % (z, x, q, y) if y != 0: q = z / y if...
5,307,713
async def test_proxy_resolver_failure(): """Test record checker got invalid dns ip""" dns_ip = '8.855.0.5' with pytest.raises(exceptions.InvalidDNSHost) as e: record_checker.RecordChecker(dns_ip) expected_msg = 'RecordChecker got invalid DNS server IP: 8.855.0.5.' assert e.match(expected_m...
5,307,714
def solver_rho_complete_nonorm(dp): """ Returns rho. dp is full param dict (with "k_Gp_rho" and "kGp_myo" """ dp["Gt"] = dp["Gt_res"] dp["k_Gp"] = dp["k_Gp_rho"] dp["Gpt"] = dp["Gpt_rho"] r = solver_dict_complete_nonorm(dp) return r[:,1]
5,307,715
def delete(args, config_name): """ delete a configuration. """ args.resource.delete(config_name)
5,307,716
async def refresh_permissions(app: web.Application, nocache: bool=False): """Refresh the permission information""" logger.info("Refreshing permissions") try: Mappings._permissions, Mappings._permission_name_to_id_map = await _load( app["access_control_api"].permission_list, app["redis"],...
5,307,717
def my_review(book_id): """ Check to see whether the user is logged in. Find a book by the supplied book_id. Find the review related to that book, written by the logged-in user. Render the view_book page with that information. """ # Check to see whether the user is logged in. if not ...
5,307,718
def unzip_files(file_list, force=False): """Given a list of file paths, unzip them in place. Attempts to skip it if the extracted folder exists. Parameters ---------- file_list : list of str Files to extract. force : bool, default=False Force the unzip if the file exists. ...
5,307,719
def base64encode(byte_arr): """ Encodes an array of binary values to a base64 string. Args: byte_arr - the array of bytes to encode Returns: A base64 encoding of the given binary data """ length = len(byte_arr) paddingAmount = length % 3 base64_string = "" # blocks o...
5,307,720
def dist(p1, p2): """ Determines the straight line distance between two points p1 and p2 in euclidean space. """ d = math.sqrt(math.pow(p1[0] - p2[0], 2) + math.pow(p1[1] - p2[1], 2)) return d
5,307,721
def resize(x, p=2): """Resize heatmaps.""" return x**p
5,307,722
def varifocal_loss(pred, target, alpha=0.75, gamma=2.0, iou_weighted=True, reduction='mean',): """`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_ Args: pred (torch.Tensor): The prediction with shape (N, ...
5,307,723
def pointIsInside(x,y): """pointIsInside Arguments: x,y -- x and y coordinates of the point. returns true if it is inside of the Circumference. """ return x**2 + y**2 <= 1.
5,307,724
def most_probable_words(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None): """ Order the words from `vocab` by marginal word probability from most to least probable. Optionally only return the `n` most probable words. .. seealso:: :func:`~tmtoolkit.topicmod.model_stats.marginal_word_di...
5,307,725
def subscribe_to_responsys(campaign, address, format='html', source_url='', lang='', country='', **kw): """ Subscribe a user to a list in responsys. There should be two fields within the Responsys system named by the "campaign" parameter: <campaign>_FLG and <campaign>_DATE. ...
5,307,726
def _check_flag(flag: str) -> None: """Check if flag is a supported value for the ask() function. Args: flag (str) Raises: ValueError: If the flag isn't AskFlag.YES_TO_ALL ("yes_to_all"), AskFlag.NO_TO_ALL ("no_to_all"), AskFlag.DEFAULT_TO_ALL("default_to_all") or None...
5,307,727
def _get_vt_api_key() -> Optional[str]: """Retrieve the VT key from settings.""" prov_settings = get_provider_settings("TIProviders") vt_settings = prov_settings.get("VirusTotal") if vt_settings: return vt_settings.args.get("AuthKey") return None
5,307,728
def test_qubefit_single(): """ This test will load a thin disk data set which includes gaussian noise and it will try to fit this data set using the qubefit procedure. """ # load the thin disk model Cube = create_thindiskmodel() # define the mask to use for the fitting Cube.create_maskarr...
5,307,729
def add_dose_time_to_mtz(hklin, hklout, doses, times=None): """Add doses and times from dictionaries doses, times (optional) to hklin to produce hklout. The dictionaries are indexed by the BATCH column in hklin. Will raise exception if no BATCH column.""" # instantiate the MTZ object representation ...
5,307,730
def search_tweet_query(): """ Searches for tweets using TwitterSearch API async. """ query_id = request.args[0] # Process TwitterSearch async s3task.async("msg_process_twitter_search", args=[query_id]) redirect(URL(f="twitter_search_query")) return
5,307,731
def download_unpack_zip(url,download_file_name,folder,software_name): """ Download the url to the file and decompress into the folder """ # Check for write permission to the target folder if not os.access(folder, os.W_OK): print("WARNING: The directory is not writeable: "+ f...
5,307,732
def prime_sets(): """Yield all sets of possible answers for problem #49. Will 'yield' three arguments: the first, second and third prime. These three prime numbers are separated by exactly LEAP, and are permutations of each other. The three primes have exactly 4 digits.""" # for each prime number ...
5,307,733
def test_menu__CalendarMasterDataManager__2(address_book, browser): """It prevents access for anonymous.""" browser.handleErrors = False # needed to catch exception with pytest.raises(Unauthorized): browser.open(browser.CALENDAR_MASTERDATA_URL)
5,307,734
def test_refund(failed_ico_ready_to_refund: Contract, web3: Web3, customer: str, customer_2: str): """Customers can claim their refunds.""" assert failed_ico_ready_to_refund.functions.loadedRefund().call() == to_wei(120, "ether") assert failed_ico_ready_to_refund.functions.getState().call() == CrowdsaleSta...
5,307,735
def stop_arkouda_server(): """ Shutdown the Arkouda server. :return: None """ _, _, server_process = get_server_info() try: run_client(os.path.join(util_dir, 'shutdown.py'), timeout=60) server_process.wait(5) except subprocess.TimeoutExpired as e: server_process....
5,307,736
def create_qso(con, qso): """ Function for actually writing qso entries, called by getqso()""" sql = ''' INSERT INTO qso(utcdate, utctime, band, mode, ocall, ocat, osec, tcall, tcat, tsec) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ''' cur.execute(sql, qso) con.commit() ret...
5,307,737
def softmax_score(cdata, data, trace): """ calculates and prints the softmax score """ yt = pd.Categorical(data[cdata.label_column]).codes data_pred = trace['mu'].mean(0) y_pred = [np.exp(point) / np.sum(np.exp(point), axis=0) for point in data_pred] cor = 0; err = 0 for i in range...
5,307,738
def smooth(mat, kernel): """ Function that produce a smoothed version of the 2D array :param mat: Array to smooth :param nPix: kernel array (output) from the function kernel_square() :return: smoothed array """ r = cv2.filter2D(mat, -1, kernel) print("Smoothing done ...") return r
5,307,739
def get_pcs(X, n_pcs, **kwargs): """ Assumes X has shape (...,n_features) """ shape = X.shape X = X.reshape((-1,shape[-1])) max_n_pcs = min(X.shape) # min(n_data_points, n_features) if n_pcs == -1: n_pcs = max_n_pcs assert n_pcs <= max_n_pcs # Can't have more than max_n_pcs p...
5,307,740
def parse_commandline(): """ returns (files, test_mode) created from the command line arguments passed to pytddmon. """ usage = "usage: %prog [options] [static file list]" version = "%prog " + '1.0.8' parser = optparse.OptionParser(usage=usage, version=version) parser.add_option( ...
5,307,741
def load_candidate(path_to_candidate): """Load candidate data from a file. Args:path_to_candidate (str): path to file to load. Returns:qid_to_ranked_candidate_passages (dict): dictionary mapping from query_id (int) to a list of 1000 passage ids(int) ranked by relevance and importance """ with open(...
5,307,742
def convert_4d_matrix_to_2d_block(K): """Convert a 4D matrix of shape ``M, M, V, V`` to a block matrix of shape ``M*V, M*V``""" M, _, V, __ = K.shape _K = np.zeros((M*V, M*V)) for i in range(M): for j in range(M): _K[i*V:(i+1)*V,j*V:(j+1)*V] = K[i,j,:,:] return _K
5,307,743
def ShowSeedingFromPools(PoolQualifiers, Nums = False): """Prints the seeds for the persons in PoolQualifiers, printing the numbers of the seeds if indicated. PoolQualifiers: A list of lists of qualifiers from pools, where the sublists are in order from strongest to weakest pool, and each sublist is ordered from to...
5,307,744
def test_contract_sscq_faucet_getOneSscq(conftest_args): """ run test_contract_sscq_faucet_deposit before this test case, to ensure the faucet contract has enough HTDF balance. """ with open('sol/sscq_faucet_sol_SscqFaucet.abi', 'r') as abifile: # abi = abifile.readlines() abijson =...
5,307,745
def get_l10n_files() -> List[str]: """取得所有翻譯相關檔案列表,包括.pot .po .mo。 Returns: List[str]: 翻譯相關檔案列表,包括.pot .po .mo。 """ po_parser = 'asaloader/locale/*/LC_MESSAGES/asaloader.po' pot_file = 'asaloader/locale/asaloader.pot' po_files = glob.glob(po_parser) mo_files = [po_file.replace('.po'...
5,307,746
def filter_standardize(data_in, low_frequency, high_factor, order, sampling_frequency, buffer_size, filename_dat, n_channels, output_directory): """Butterworth filter for a one dimensional time series Parameters ---------- ts: np.array T numpy arra...
5,307,747
def send_user_add_mail(request, email, password): """Send email when add new user.""" c = { 'user': request.user.username, 'org': request.user.org, 'email': email, 'password': password, } send_html_email(_('You are invited to join %s') % get_site_name(), '...
5,307,748
def eprint(*args, **kwargs): """Like print, but outputs to stderr.""" print(*args, file=sys.stderr, **kwargs)
5,307,749
def get_or_create_service_account( project_id, account_id, account_name, google_credentials ): """ Get a service account or create it if it does not exist. Args: project_id: The ID of the project the service account is contained in. account_id...
5,307,750
def create_excel_file(file_name="results", results_classes=None, results_parts=None, path="", num_classes=21, num_parts=108, color_map_path=""): """ :param file_name: name of the file :param results_classes: array with IoU for the num_classes classes :param results_parts: array wit...
5,307,751
def delivery_pricing_api_url(): """ Delivery Pricing API """ return get_parameter("/ecommerce/{Environment}/delivery-pricing/api/url")
5,307,752
def filter_value(entry, values=None): """ Returns True if it should be filtered. Only take calls with filter values in the list provided if None provided, assume that filter_value must be PASS or blank '.' """ if values is None: return len(entry.filter) != 0 and 'PASS' not in entry.filte...
5,307,753
def sample_nonlinear_icp_sim( dag, n_samples, nonlinearity="id", noise_df=2, combination="additive", intervention_targets=None, intervention="soft", intervention_shift=0, intervention_scale=1, intervention_pct=None, random_state=None, pre_intervention=False, lambda_no...
5,307,754
def process_data(expected_keys, data): """ Check for any expected but missing keyword arguments and raise a TypeError else return the keywords arguments repackaged in a dictionary i.e the payload. :param expected_keys: :param data: :return payload: """ payload = {} for key in exp...
5,307,755
def test_call_interpolation(posterior): """Interpolation is possible and returns a Normal RV.""" assert posterior.locations[0] < 9.88 < posterior.locations[-1] assert 9.88 not in posterior.locations out_rv = posterior(9.88) assert isinstance(out_rv, randvars.Normal)
5,307,756
def restore_scores(scores, shape, shift): """ Restores scores to original size using linear interpolation. Arguments: scores -- original 'compressed' scores shape -- shape of the restored scores shift -- sliding windows shift """ new_scores = np.zeros(shape) for i in range(1, scor...
5,307,757
def get_mtime_for_page(): """获取分时数据""" rps = {} rps["status"] = True if request.form.get("symbol") or request.form.get("timestamp"): symbol = request.form["symbol"] timestamp = request.form["timestamp"] data = get_stock_mtime(symbol, timestamp, tdx) if data: ...
5,307,758
def get_dist_mat(opts, bb_atoms): """ Takes a list of prody.Atoms and calls calc_dist_matrix """ ### Commenting this out, since I don't require <dist> arg in usage # Distance threshold for contact maps. # if opts["<dist>"]: # opts["<dist>"] = float(opts["<dist>"]) if opts["--mask-thresh"]: opts["--mask-t...
5,307,759
def make_song_title(artists: list, name: str, delim: str) -> str: """ Generates a song title by joining the song title and artist names. Artist names given in list format are split using the given delimiter. """ return f"{delim.join(artists)} - {name}"
5,307,760
def list_fastmodels(check_models=False): """! List all models and configs in fm_agent""" resource = FastmodelAgent() model_dict = resource.list_avaliable_models() columns = ['MODEL NAME', "MODEL Binary Full Path", 'CONFIG NAME' , 'CONFIG FILE', 'AVAILABILITY'] if check_models: columns....
5,307,761
def pytest_addoption(parser): """Pytest hook that adds command line parameters""" parser.addoption( "--simple", action="store_true", help="Run tests only (no cov, no pylint, warning output silenced)", )
5,307,762
def changeSamplingRateOfSignal( data, oldSamplingFrequency, newSamplingFrequency, tmpPath = None, tmpFileName = 'tmp.wav', sincWidth = 200, normalize = False ): """ change the sampling frequency of a given signal. similar to @ref changeSamplingRate(), but does not operate on a saved sound file, b...
5,307,763
def make_html_viz(prog, html_file, html_info): """'Make' the visualizations for html_file""" js_out, py_dict = html_info # all_traces is a string containing all the js trace datastructures # for all the supplied .py files for html_file try: all_traces = '\n'.join(run_command(prog, py) for ...
5,307,764
def get_mangled_dataframe(metal_currency_key): """ Parameter: The key in Redis. E.g. XAU-USD """ currency = metal_currency_key.split('-')[1] metal = metal_currency_key.split('-')[0] df = redis_to_dataframe(metal_currency_key) # convert usd pricing if currency == 'USD': ...
5,307,765
def value_to_idx(val_range, unique_values, run_idx): """Return the index that belongs to the value at run index. Parameters ---------- range unique_values run_idx Returns ------- """ return np.where(unique_values == val_range[run_idx])[0]
5,307,766
def run_pyspark_yarn_client(env_dir, env_name, env_archive, args): """ Initializes the requires spark command line options on order to start a python job with the given python environment. Parameters ---------- env_dir : str env_name : str env_archive : str args : list Returns ...
5,307,767
def struct_parse(struct, stream, stream_pos=None): """ Convenience function for using the given struct to parse a stream. If stream_pos is provided, the stream is seeked to this position before the parsing is done. Otherwise, the current position of the stream is used. Wraps the erro...
5,307,768
def DEFAULT_RENAMER(L, Names=None): """ Renames overlapping column names of numpy ndarrays with structured dtypes Rename the columns by using a simple convention: * If `L` is a list, it will append the number in the list to the key associated with the array. * If `L` is a dictionary,...
5,307,769
def authorizeView(user, identifier): """ Returns True if a request to view identifier metadata is authorized. 'user' is the requestor and should be an authenticated StoreUser object. 'identifier' is the identifier in question; it should be a StoreIdentifier object. """ # In EZID, essentially all iden...
5,307,770
def test_integer(value, fails, allow_empty, coerce_value, minimum, maximum, expects): """Test the numeric validator.""" if not fails: validated = validators.integer(value, allow_empty = allow_empty, coerce_value = coerce_value...
5,307,771
def create_absolute_installed_file_path(root_dir, file_path): """ Return an absolute path to `file_path` given the root directory path at `root_dir` """ file_path = remove_drive_letter(file_path) # Append the install location to the path string `root_dir` return str(Path(root_dir).joinpath(f...
5,307,772
def validate_mark(mark: Mark) -> None: """Validate each test's :py:func:`LISA` parameters.""" assert not mark.args, "LISA marker cannot have positional arguments!" mark.kwargs.update(lisa_schema.validate(mark.kwargs))
5,307,773
def test_doc_add_tag_function(flat_mode): """ Tests that the @add_tag example from doc (functions only) works """ if not flat_mode: @function_decorator def add_tag(tag='hi!'): """ Example decorator to add a 'tag' attribute to a function. :param tag: the 'tag'...
5,307,774
def sort(reader, buf_size, cmp=None, key=None, reverse=False): """ Creates a data reader whose data output is sorted. Output from the iterator that created by original reader will be buffered into sort buffer, and then sorted. The size of sort buffer is determined by argument buf_size. :param ...
5,307,775
def getSequenceNumbers(radar_dir, data_format): """ Get all the numbers from input file names """ assert isinstance(data_format, list) assert all(isinstance(x, str) for x in data_format) assert (len(data_format) == 2 or len(data_format) == 3) sequence_numbers = [] for this_file in glob(os.path.j...
5,307,776
def _release(ptr): """Send a release message to the given id cdata. The object cannot be used anymore afterwards. Do not call directly, ID retains and releases objects automatically.""" _objc_msgSend_release(ptr, libc.sel_registerName(b"release"))
5,307,777
def test_multiple_plugins(miradord, bitcoind): """Test we use the union of all plugins output to revault. That is, the stricter one will always rule.""" # Start with the max value plugin plugin_path = os.path.join( os.path.dirname(__file__), "plugins", "max_value_in_flight.py" ) datadir ...
5,307,778
def delete_completions(): """ 删除所有已完成的标注样本 :return: """ r = requests.delete(host + "completions", headers=headers) print(r.status_code) print(r.text)
5,307,779
def __get_editor_of_statement(uid): """ :param uid: :return: """ db_statement = DBDiscussionSession.query(TextVersion).filter_by(statement_uid=uid).order_by( TextVersion.uid.desc()).first() db_editor = DBDiscussionSession.query(User).get(db_statement.author_uid) gravatar = get_profi...
5,307,780
def get_strategy(tpu='', gpus=None): """Chooses a distribution strategy. AI Platform automatically sets TF_CONFIG environment variable based on provided config file. If training is run on multiple VMs different strategy needs to be chosen than when it is run on only one VM. This function determines ...
5,307,781
def clean_keyword(kw): """Given a keyword parsed from the header of one of the tutorials, return a 'cleaned' keyword that can be used by the filtering machinery. - Replaces spaces with capital letters - Removes . / and space """ return kw.strip().title().replace('.', '').replace('/', '').replac...
5,307,782
def delco_osm(): """Analyze Delco Trailheads w/ OSM network""" arguments = { "edge_table_name": "osm_edges_all_no_motorway", "node_table_name": "nodes_for_osm_all", "node_id_column": "node_id", "poi_table_name": "delco_trailheads", "poi_id_column": "original_gid", ...
5,307,783
def stop_guest(userid): """Shutdown a virtual machine. Input parameters: :userid: USERID of the guest, last 8 if length > 8 """ sdk_client.send_request('guest_start', userid)
5,307,784
def compute_md5(path: Union[str, Path], chunk_size: int): """Return the MD5 checksum of a file, calculated chunk by chunk. Parameters ---------- path : str or Path Path to the file to be read. chunk_size : int Chunk size used to calculate the MD5 checksum. """ md5 = hashlib...
5,307,785
def is_canonical_emoji_sequence(seq): """Return true if this is a canonical emoji sequence (has 'vs' where Unicode says it should), and is known.""" _load_emoji_sequence_data() return seq in _emoji_sequence_data
5,307,786
def align_coefs(coefs, lag, verbose=False): """ coefs: n* lag x n. the i * lagth row of col k is the auto-coefficient of k on k # align the coefs: # split into same lag return: lag x n x n. the """ assert len(coefs.shape) == 2 assert coefs.shape[0] / lag == coefs.shape[1] n = coef...
5,307,787
def calc_zq(qz, zp, zm, En, aa): """ function used in computing polar geodesic coordinates Parameters: qz (float) zp (float): polar root zm (float): polar root En (float): energy aa (float): spin Returns: zq (float) """ ktheta = (aa ** 2 * (1 - E...
5,307,788
def equation_dw18(dbconn, speccode, biomassassign, dbh, ht): """ Equation form: ((a + b * dbh + c * (dbh ^ d))-(e + f * dbh + g * (dbh ^ h))) """ qstr = "SELECT a, b, c, d, e, f, g, h FROM VolBioCoeffs WHERE SpecCode = '%s'" % (biomassassign) c = dbconn.cursor() c.execute(qstr) coeffs = c.fetchone()...
5,307,789
def denormalize(images, min_, max_): """scales image back to min_, max_ range""" return [((i + 1) / 2 * (max_ - min_)) + min_ for i in images]
5,307,790
def suppliers(state): """ CoST IDS element: Contract firm(s) """ copy_party_by_role(state, "supplier") for compiled_release, contracting_process in zip( state.compiled_releases, state.output["contractingProcesses"] ): parties = check_type(compiled_release.get("parties"), list) ...
5,307,791
def update_config(config, args): """Update config by ArgumentParser Args: args: ArgumentParser contains options Return: config: updated config """ if args.cfg: _update_config_from_file(config, args.cfg) config.defrost() if args.dataset: config.DATA.DATASET = a...
5,307,792
def update_or_create_variable(site, slug, date, value): """Update or create variable """ variable = None try: variable = Variable.objects.get(site=site, slug=slug) variable.update_value(date, value) variable.save() except Variable.DoesNotExist: LOGGER.info("Variable c...
5,307,793
def print_result(hash_in, passwd_out): """ Funtion userd to print result to console """ print("%s\n\t=> %s" % (hash_in, passwd_out))
5,307,794
def body_part(ent): """Enrich the match.""" data = {} parts = [] part = [] for token in ent: label = token._.cached_label lower = REPLACE.get(token.lower_, token.lower_) if label in PARTS: part.insert(0, lower) elif label == 'subpart': part.ap...
5,307,795
def download_sample_data_files(path=None): """Downloads sample data to be used with VCS. Default download directory is vcs.sample_data, but if __path__ is provided then data will be downloaded to that path. :Example: .. doctest:: utils_download_sample_data >>> import os # use this...
5,307,796
def version_is_locked(version): """ Determine if a version is locked """ return getattr(version, "versionlock", None)
5,307,797
def run_task( f: Callable, prepare_data: Union[RQTaskPrepareData, None] = None, args: tuple = (), kwargs: dict = {} ) -> None: """ Runs background task. NOTE: you should pass this function to task queue. :param f: Function that will be called from background task. :param pr...
5,307,798
def generate(request, recipient): """ Generate a test email. :param request: the current request :type request: pyramid.request.Request :param recipient: the recipient of the test email :type recipient: str :returns: a 4-element tuple containing: recipients, subject, text, html """ ...
5,307,799