content
stringlengths
22
815k
id
int64
0
4.91M
def get_msids_for_add_msids(opt, logger): """ Parse MSIDs spec file (opt.add_msids) and return corresponding list of MSIDs. This implements support for a MSID spec file like:: # MSIDs that match the name or pattern are included, where * matches # anything (0 or more characters) while ? mat...
5,359,000
def gaussian_similarity(stimulus_representation, i, j, w, c, r): """ Function that calculates and returns the gaussian similarity of stimuli i and j (equation 4b in [Noso86]_) Parameters ---------- stimulus_representation : np.array The stimuli are given to this function in the form of a n ...
5,359,001
def windShearVector(u, v, top, bottom, unit=None): """ calculate the u and v layer difference and return as vector """ udiff = layerDiff(u, top, bottom, unit) vdiff = layerDiff(v, top, bottom, unit) return makeVector(udiff, vdiff)
5,359,002
def test_escaping(): """test escaping Windows Resource files to Python strings""" assert rc.escape_to_python('''First line \ second line''') == "First line second line" assert rc.escape_to_python("A newline \\n in a string") == "A newline \n in a string" assert rc.escape_to_python("A tab \\t in a string...
5,359,003
def create_tables(cur, conn) -> None: """Create all tables base on create_table_queries commit results into the database immediately. Parameters ---------- cur: psyconpg2.connect cursor of connection conn: psyconpg2.connect.cursor connecition function """ for query in cre...
5,359,004
def test_validate_owner_inactive_subscription( api_rf, subscription_factory, user_factory ): """ If the user initiating the transfer has an inactive subscription, validation should fail. """ owner = user_factory() subscription_factory(is_active=False, user=owner) api_rf.user = owner ...
5,359,005
def withdraw_entry(contest): """Withdraws a submitted entry from the contest. After this step the submitted entry will be seen as a draft. """ return _update_sketch(contest, code=None, action="withdraw")
5,359,006
def test_invalid_properties(properties, error_message): """Check that ValueError is raised if invalid properties are passed. 1. Try to create an embedded representation with invalid properties. 2. Check that ValueError is raised. 3. Check the error message. """ with pytest.raises(ValueError) as...
5,359,007
def scan(): """Update the database of transactions (amount in each address). """ controller.scan_utxos()
5,359,008
def download_file(url, output_path): """Downloads a file given its URL and the output path to be saved. Args: url (str): URL to download the file. output_path (str): Path to save the downloaded file. """ file_exists = os.path.exists(output_path) if not file_exists: folder...
5,359,009
def _conditional_field(if_, condition, colon, comment, eol, indent, body, dedent): """Formats an `if` construct.""" del indent, dedent # Unused # The body of an 'if' should be columnized with the surrounding blocks, so # much like an inline 'bits', its body is treated as an inline list o...
5,359,010
def check_sum_cases(nation='England'): """check total data""" ck=LocalLatest() fail=False data=ck.data.get('data') latest={} data=clean_cases(data) #repair glitches #check latest data matches stored data for nation for i in data: _code=i['areaCode'] latest[_code...
5,359,011
def get_module_name() -> str: """Gets the name of the module that called a function Is meant to be used within a function. :returns: The name of the module that called your function """ return getmodulename(stack()[2][1])
5,359,012
def hand_points(work_hand): """returns the point value of a given hand""" debug_level = 1 work_points = 0 for card in work_hand: work_points += card_point_value(card) return work_points
5,359,013
def elements_counter(arr, count=0): """递归计算列表包含的元素数 Arguments: arr {[list]} -- [列表] Keyword Arguments: count {int} -- [列表包含的元素数] (default: {0}) Returns: [int] -- [列表包含的元素数] """ if len(arr): arr.pop(0) count += 1 return elements_counter(arr, coun...
5,359,014
def dataset_is_open_data(dataset: Dict) -> bool: """Check if dataset is tagged as open data.""" is_open_data = dataset.get("isOpenData") if is_open_data: return is_open_data["value"] == "true" return False
5,359,015
def destroy_shared_memory_region(shm_handle): """Unlink a shared memory region with the specified handle. Parameters ---------- shm_handle : c_void_p The handle for the shared memory region. Raises ------ SharedMemoryException If unable to unlink the shared memory region. ...
5,359,016
def _remove_suffix_apple(path): """ Strip off .so or .dylib. >>> _remove_suffix_apple("libpython.so") 'libpython' >>> _remove_suffix_apple("libpython.dylib") 'libpython' >>> _remove_suffix_apple("libpython3.7") 'libpython3.7' """ if path.endswith(".dylib"): return path[:...
5,359,017
def sparsenet201(**kwargs): """ SparseNet-201 model from 'Sparsely Aggregated Convolutional Networks,' https://arxiv.org/abs/1801.05895. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.torch/models' ...
5,359,018
async def process_token(message: types.Message, state: FSMContext): """ Process user token """ logger.info('Обрабатываем ввод токена ВК.') vk_token = message.text async with state.proxy() as data: data['vk_token'] = vk_token test_result, test_message = await vk.test_token(vk_token...
5,359,019
def _run_diagnostic_(diff, diff_var, rratio=None, rratio_var=None, oratio=None, oratio_var=None, color="gray"): """Background function to run all diagnostics Returns ------- Plot to console """ # Continuous outcomes have less plots to generate if rratio is None: # Point estimates ...
5,359,020
def alt_text_to_curly_bracket(text): """ Converts the text that appears in the alt attribute of image tags from gatherer to a curly-bracket mana notation. ex: 'Green'->{G}, 'Blue or Red'->{U/R} 'Variable Colorless' -> {XC} 'Colorless' -> {C} 'N colorless' -> {N}, where N is some ...
5,359,021
def massage_primary(repo_primary, src_cache, cdt): """ Massages the result of dictify() into a less cumbersome form. In particular: 1. There are many lists that can only be of length one that don't need to be lists at all. 2. The '_text' entries need to go away. 3. The real information st...
5,359,022
def ansi_color_name_to_escape_code(name, style="default", cmap=None): """Converts a color name to the inner part of an ANSI escape code""" cmap = _ensure_color_map(style=style, cmap=cmap) if name in cmap: return cmap[name] m = RE_XONSH_COLOR.match(name) if m is None: raise ValueError...
5,359,023
def twitter(bot, message): """#twitter [-p 天数] -p : 几天以前 """ try: cmd, *args = shlex.split(message.text) except ValueError: return False if not cmd[0] in config['trigger']: return False if not cmd[1:] == 'twitter': return False try: options, args...
5,359,024
def checkdir(*args: List[str]) -> bool: """ Guard for checking directories Returns: bool -- True if all arguments directories """ for a in args: if a and not os.path.isdir(a): return False if a and a[0] != '/': return False return True
5,359,025
def get_zones(request): """Returns preprocessed thermal data for a given request or None.""" logging.info("received zone request:", request.building) zones, err = _get_zones(request.building) if err is not None: return None, err grpc_zones = [] for zones in zones: grpc_zones.a...
5,359,026
def proper_classification(sp): """ Uses splat.classifyByStandard to classify spectra using spex standards """ #sp.slitpixelwidth=1 #sp.slitwidth=1 #sp.toInstrument('WFC3-G141') wsp= wisps.Spectrum(wave=sp.wave.value, flux=sp.flux.value, ...
5,359,027
def sum_last_4_layers(sequence_outputs: Tuple[torch.Tensor]) -> torch.Tensor: """Sums the last 4 hidden representations of a sequence output of BERT. Args: ----- sequence_output: Tuple of tensors of shape (batch, seq_length, hidden_size). For BERT base, the Tuple has length 13. Returns: ...
5,359,028
def TotalCust(): """(read-only) Total Number of customers served from this line section.""" return lib.Lines_Get_TotalCust()
5,359,029
def extra_normalize(text_orig: str): """ This function allows a simple normalization to the original text to make possible the aligning process. The replacement_patterns were obtained during experimentation with real text it is possible to add more or to get some errors without new rules. :Not...
5,359,030
def test_serial_bad_configA(): """Test if bad_configurationA causes a RuntimeError on trying to create the population.""" # Load configuration. local_dir = os.path.dirname(__file__) config_path = os.path.join(local_dir, 'bad_configurationA') config = neat.Config(neat.DefaultGenome, neat.DefaultRepro...
5,359,031
def _print_version(): """ Print the version of the currently running collector. Gets the collector name from inspecting `__main__`. Gets version information from environment variables set by an S2I build. """ import __main__ # name of dir above app.py exporter_name = pathlib.PurePath(__...
5,359,032
def test_vbm_installed(mock_path_exists): """Test installed.""" vbm = mech.vbm.VBoxManage(executable='/bin/VBoxManage') assert vbm.installed() mock_path_exists.assert_called() assert vbm.get_executable() == '/bin/VBoxManage'
5,359,033
def list2str(lst: list) -> str: """ 将 list 内的元素转化为字符串,使得打印时能够按行输出并在前面加上序号(从1开始) e.g. In: lst = [a,b,c] str = list2str(lst) print(str) Out: 1. a 2. b 3. c """ i = 1 res_list = [] for x in lst: res_list.append(str(i)+'. '+str(x)) i += 1 res...
5,359,034
def _prompt_save(): # pragma: no cover """Show a prompt asking the user whether he wants to save or not. Output is 'save', 'cancel', or 'close' """ b = prompt( "Do you want to save your changes before quitting?", buttons=['save', 'cancel', 'close'], title='Save') return show_box(b...
5,359,035
def plot_dataset_samples_1d( dataset, n_samples=10, title="Dataset", figsize=DFLT_FIGSIZE, ax=None, plot_config_kwargs={}, seed=123, ): """Plot `n_samples` samples of the a datset.""" np.random.seed(seed) with plot_config(plot_config_kwargs): if ax is None: f...
5,359,036
def test_str_conversion_of_command_object(): """ String conversion shows embedded command string, class of command object and id to allow for differentiating between multiple instances of same command """ class PingCmd(Command): def __init__(self, host='localhost', connection=None): ...
5,359,037
def list_versions(namespace, name, provider): """List version for mnodule. Args: namespace (str): namespace for the version name (str): Name of the module provider (str): Provider for the module Returns: response: JSON formatted respnse """ try: return make_...
5,359,038
def script_cbor(self, script_hash: str, **kwargs): """ CBOR representation of a plutus script https://docs.blockfrost.io/#tag/Cardano-Scripts/paths/~1scripts~1{script_hash}~1cbor/get :param script_hash: Hash of the script. :type script_hash: str :param return_type: Optional. "object", "json" o...
5,359,039
def ithOfNPointsOnCircleY(i,n,r): """ return x coordinate of ith value of n points on circle of radius r points are numbered from 0 through n-1, spread counterclockwise around circle point 0 is at angle 0, as of on a unit circle, i.e. at point (0,r) """ # Hints: similar to ithOfNPointsOnCircle...
5,359,040
def fieldset_experiment_results(objparent): """ :param objparent: """ objparent.id() objparent.created_at() objparent.occured_at() objparent.result() objparent.updated_at() objparent.object_class_id() fieldset_research_plan_metrics(objparent.research_plan_metric())
5,359,041
def get_tags(ec2id, ec2type, region): """ get tags return tags (json) """ mytags = [] ec2 = connect('ec2', region) if ec2type == 'volume': response = ec2.describe_volumes(VolumeIds=[ec2id]) if 'Tags' in response['Volumes'][0]: mytags = response['Volumes'][0]['Tags...
5,359,042
def parse(data, raw=False, quiet=False): """ Main text parsing function Parameters: data: (string) text data to parse raw: (boolean) unprocessed output if True quiet: (boolean) suppress warning messages if True Returns: Dictionary. Raw or process...
5,359,043
def download_pretrained_model(model: str, target_path: str = None) -> str: """Downloads pretrained model to given target path, if target path is None, it will use model cache path. If model already exists in the given target path than it will do notting. Args: model (str): pretrained model name...
5,359,044
def callNasaApi(date='empty'): """calls NASA APIS Args: date (str, optional): date for nasa APOD API. Defaults to 'empty'. Returns: Dict: custom API response """ print('calling nasa APOD API...') url = nasaInfo['nasa_apod_api_uri'] if date != 'empty': params = getA...
5,359,045
def train_reduced_model(x_values: np.ndarray, y_values: np.ndarray, n_components: int, seed: int, max_iter: int = 10000) -> sklearn.base.BaseEstimator: """ Train a reduced-quality model by putting a Gaussian random projection in front of the multinomial logistic regression stage of t...
5,359,046
def pv(array): """Return the PV value of the valid elements of an array. Parameters ---------- array : `numpy.ndarray` array of values Returns ------- `float` PV of the array """ non_nan = np.isfinite(array) return array[non_nan].max() - array[non_nan].min()
5,359,047
def test_main_nothing_to_do(capfd: Any) -> None: """Do nothing if nothing to do""" args = main.cli_parser([]) with patch.object(main, "cli_parser", MagicMock(return_value=args)): main.main() out, _ = capfd.readouterr() assert out == main.NOTHING_TO_DO + "\n"
5,359,048
def format_bad_frames(bad_frames): """Create an array of bad frame indices from string loaded from yml file.""" if bad_frames == "": bads = [] else: try: bads = [x.split("-") for x in bad_frames.split(",")] bads = [[int(x) for x in y] for y in bads] bads ...
5,359,049
def test_multivoxel(): """Test fitting with multivoxel data. We generate a multivoxel signal to test the fitting for multivoxel data. This is to ensure that the fitting routine takes care of signals packed as 1D, 2D or 3D arrays. """ ivim_fit_multi = ivim_model.fit(data_multi) est_signal =...
5,359,050