content
stringlengths
22
815k
id
int64
0
4.91M
def parse_regex(re): """Parse binary form for regular expression into canonical string. The input binary format is the one stored in the sandbox profile file. The out format is a canonical regular expression string using standard ASCII characters and metacharacters such as ^, $, +, *, etc. """ ...
43,900
def _validate_time_mode(mode, **kwargs): """Validate time mode.""" return mode
43,901
def flatten() -> GraphBuilder: """ dl.flatten layer builder """ def graph_builder(prev_layer: Metadata) -> Metadata: metadata = {} init_regularized_nodes(metadata, prev_layer) graph = prev_layer['graph'] metadata['units'] = (np.prod(prev_layer['units']),) metadata...
43,902
def _important() -> str: """Returns a query term matching messages that are important.""" return 'is:important'
43,903
async def root(): """ Dependency is "static". Value of Depends doesn't get passed into function we still get redirected half the time though """ return {"message": "Hello World"}
43,904
def test_install_over_existing(runner, foo_package, foo_updated_release): """Must ask for prompt before installing over existing package.""" assert not os.path.exists(os.path.join('bin', 'foo-1.0')) result = runner.invoke(steeve.cli, ['install', 'foo', '1.0', 'releases/foo-1.0'],...
43,905
def line_width(et: pd.DataFrame, lw_by: Hashable): """Default edge line width function.""" if lw_by is not None: return encodings.data_linewidth(et[lw_by], et[lw_by]) return pd.Series([1] * len(et), name="lw")
43,906
def run_state_machine(ctx, callback): """Run the libmongocrypt state machine until completion. :Parameters: - `ctx`: A :class:`MongoCryptContext`. - `callback`: A :class:`MongoCryptCallback`. :Returns: The completed libmongocrypt operation. """ while True: state = ctx.sta...
43,907
def buildGeneTSSInterval(infile, outfile): """build a :term:`bed` file with intervals that cover all transcription start sites within a gene. This method outputs for each gene the smallest genomic region that covers all the transcription start sites within that gene. The name column of the :term:`...
43,908
def remove_na_arraylike(arr): """ Return array-like containing only true/non-NaN values, possibly empty. """ if is_extension_array_dtype(arr): return arr[notna(arr)] else: return arr[notna(lib.values_from_object(arr))]
43,909
async def test_clean_up_in_use_booking_conversion(delete_in_use_mock: mock.AsyncMock): """ Check if the _clean_up_in_use_booking actually converts the data type and calls the _delete_if_in_use_booking. """ used_licenses = [ {"booked": 19, "lead_host": "host1", "user_name": "user1"}, ...
43,910
def conv_nested(image, kernel): """A naive implementation of convolution filter. This is a naive implementation of convolution using 4 nested for-loops. This function computes convolution of an image with a kernel and outputs the result that has the same shape as the input image. Args: ima...
43,911
def draw_polygon_filled(point_list: PointList, color: Color): """ Draw a polygon that is filled in. Args: :point_list: List of points making up the lines. Each point is in a list. So it is a list of lists. :color: color, specified in a list of 3 or 4 bytes i...
43,912
def getLatest(df): """ This get the data of the last day from the dataframe and append it to the details """ df_info = df.iloc[:,0:5] df_last = df.iloc[:,-1] df_info['latest'] = df_last return df_info
43,913
def cli(): """Create csv file for gantt chart generation.""" pass
43,914
def setup_camera(is_fullscreen = True): """ Setup the PiCam to default PSVD settings, and return the camera as an object. Keyword Arguments: is_fullscreen -- Boolean value. True for fullscreen, false for window. """ # ensure that camera is correctly installed and set...
43,915
def CalculateGearyAutoMutability(ProteinSequence): """ #################################################################################### Calculte the GearyAuto Autocorrelation descriptors based on Mutability. Usage: result=CalculateGearyAutoMutability(protein) Input: protein is a pure pro...
43,916
def get_mask_from_lengths_window_and_time_step(lengths, attention_window_size, time_step): """ One for mask and 0 for not mask Args: lengths: attention_window_size: time_step: zero-indexed Returns: """ # Mask all initially....
43,917
def hamming_distance(a, b): """ Returns the hamming distance between sequence a and b. Sequences must be 1D and have the same length. """ return np.count_nonzero(a != b)
43,918
def optimizer_to_map(vertices, optimizer: g2o.SparseOptimizer, is_sparse_bundle_adjustment=False) -> \ Dict[str, Union[List, np.ndarray]]: """Convert a :class: g2o.SparseOptimizer to a dictionary containing locations of the phone, tags, and waypoints. Args: vertices: A dictionary of vertices. T...
43,919
def test_others_not_dict(df): """Raise Error if `others` is not a dictionary.""" with pytest.raises(TypeError): df.expand_grid("frame", others=[2, 3])
43,920
def generate_url(mbid, level): """Generates AcousticBrainz end point url for given MBID. """ return ACOUSTIC_BASE + mbid + level
43,921
def __validate1 (property): """ Exit with error if property is not valid. """ msg = None f = get_grist (property) if f: value = get_value (property) if not feature.valid (f): f = ungrist (get_grist (property)) # Ungrist for better error messages msg ...
43,922
def averaged_knots_unconstrained(n: int, p: int, t: Sequence[float]) -> List[ float]: """ Returns an averaged knot vector from parametrization vector `t` for an unconstrained B-spline. Args: n: count of control points - 1 p: degree t: parametrization vector, normalized [0..1] ...
43,923
def render_glyph(face, char, filename): """Render a glyph to an image on disk.""" face.set_char_size(256 * 256) face.load_char( char, freetype.FT_LOAD_RENDER | freetype.FT_LOAD_TARGET_NORMAL) _do_render(face.glyph.bitmap, filename)
43,924
def converge_launch_stack(desired_state, stacks): """ Create steps that indicate how to transition from the state provided by the given parameters to the :obj:`DesiredStackGroupState` described by ``desired_state``. See note [Converging stacks] for more information. :param DesiredStackGroupSta...
43,925
def dir_content(path): """ returns the content of given path, excluding unreadable files and dotfiles (unless SHOW_ALL is True) """ ret = [] for item in listdir(path): full_path = join_dirs(path, item) if os.access(full_path, os.R_OK) and (SHOW_ALL or item[0] != '.'): ...
43,926
def export_standin(self, *args, **kwargs): """ Exports Standin file with given attributes """ raise NotImplementedError('export_standin function is not implemented!')
43,927
def strip_long_text(text, max_len, append=u'…'): """Returns text which len is less or equal max_len. If text is stripped, then `append` is added, but resulting text will have `max_len` length anyway. """ if len(text) < max_len - 1: return text return text[:max_len - len(append)] + append
43,928
async def test_Inverter_power_on_ZeversolarError(): """Power off inverter.""" url = "test" my_inverter = Inverter(url) with pytest.raises(ZeversolarError): my_inverter = Inverter(url) await my_inverter.power_on()
43,929
def function_rescale(data_and_metadata_in: _DataAndMetadataLike, data_range: typing.Optional[DataRangeType] = None, in_range: typing.Optional[DataRangeType] = None) -> DataAndMetadata.DataAndMetadata: """Rescale data and update intensity calibration. rescale(a, (0.0, 1...
43,930
def svn_diff_parse_next_patch(*args): """ svn_diff_parse_next_patch(svn_patch_file_t patch_file, svn_boolean_t reverse, svn_boolean_t ignore_whitespace, apr_pool_t result_pool, apr_pool_t scratch_pool) -> svn_error_t """ return _diff.svn_diff_parse_next_patch(*args)
43,931
def Sub(inputs, **kwargs): """Calculate A - B. Parameters ---------- inputs : list of Tensor The inputs, represent A and B respectively. Returns ------- Tensor The output tensor. """ CheckInputs(inputs, 2) arguments = ParseArguments(locals()) output = Tens...
43,932
def psf_1d(x, *p): """[summary] Arguments: x {[type]} -- [description] Returns: [type] -- [description] """ A, x0, alpha, C = p r = (x - x0) * alpha y = np.zeros(r.shape) y[r!=0] = A * (2 * special.j1(r[r!=0]) / r[r!=0])**2 y[r==0] = A return y + ...
43,933
def with_retries(func): """Wrapper for _http_request adding support for retries.""" @functools.wraps(func) def wrapper(self, url, method, **kwargs): if self.conflict_max_retries is None: self.conflict_max_retries = DEFAULT_MAX_RETRIES if self.conflict_retry_interval is None: ...
43,934
def load_json(path): """Load JSON file into Python object.""" with open(os.path.expanduser(path), "r") as file_data: data = json.load(file_data) return data
43,935
def arrow_format(jinja_ctx, context, *args, **kw): """Format datetime using Arrow formatter string. Context must be a time/datetime object. :term:`Arrow` is a Python helper library for parsing and formatting datetimes. Example: .. code-block:: html+jinja <li> Offer created at ...
43,936
def jsonify_query_result(conn, query): """deprecated""" res = query.all() #res = conn.execute(query) #return [dict(r) for r in res] return [r._asdict() for r in res]
43,937
def _postfix_queue(token_expr): """ Form postfix queue from tokenized expression using shunting-yard algorithm. If expression have function, then presence of arguments for that function added before function token. If function have few arguments then RPN algorithm will pop them from stack until...
43,938
def test_dead_pixels_absolute_rate(): """Make sure dead pixels defined using a normalized rate image and an absolute flux threshold value are found correctly""" test = np.ones((10, 10)) test[2, 2] = 0.04 test[3, 3] = 0.02 test[4, 4] = 0. dead = bpm.dead_pixels_absolute_rate(test, max_dead_s...
43,939
def test_none_grid_object_properties(): """Basic stupid tests for none grid object""" none = NoneGridObject() assert none.color == Color.NONE assert none.state_index == 0 assert none.can_be_represented_in_state() assert none.num_states() == 1
43,940
def get_from_list_to_examples(task_proc): """ Return a function that converts 2d list (from csv) into example list This can be different between DataProcessors """ if isinstance(task_proc, DefaultProcessor): return lambda l: task_proc._create_examples(l, "test") else: raise NotIm...
43,941
def read_rules(rule_file=None): """Read rule from rule yaml file. Args: rule_file (str, optional): The path of rule yaml file. Defaults to None. Returns: dict: dict object read from yaml file """ default_rule_file = Path(__file__).parent / 'rule/default_rule.yaml' p = Path(rule...
43,942
def localized_rattle( structure: Structure, defect_coords: np.array, stdev: float = 0.25, ): """ Given a pymnatgen structure, it applies a random distortion to the coordinates of the atoms in a radius 5 A from defect atom. Random distortion chosen from a gaussian with a sta...
43,943
def assert_valid_script( script_runner, tmpdir_factory, representation, dataset, dbpath, property, split=[10, 5], derivative=None, contributions=None, negative_dr=False, output_module=None, max_epochs=2, checkpoint_interval=1, keep_n_checkpoints=4, ): """ ...
43,944
def calculate_jaccard(set_1, set_2) -> float: """Calculate the jaccard similarity between two sets. :param set set_1: set 1 :param set set_2: set 2 """ intersection = len(set_1.intersection(set_2)) smaller_set = min(len(set_1), len(set_2)) return intersection / smaller_set
43,945
def bad_request(e) -> 'template': """Displays a custom 400 error handler page.""" return render_template('error_handler.html', code = 400, message = "Bad request", url = url_for('main.profile_page'), back_to = 'Profile Page'), 400
43,946
def quarter_of_year(datetimes): """Return the quarter of the year of given dates.""" return ((_month_of_year(datetimes) - 1) // 3 + 1).astype(int)
43,947
def downgrade(): """Downgrade database.""" # ### commands auto generated by Alembic - please adjust! ### op.execute('ALTER TABLE oarepo_communities ALTER COLUMN "type" TYPE char(16) USING "type"::varchar') # ### end Alembic commands ###
43,948
def position_cursor_right(message, row): """Calculates first position of a string that needs to be right-aligned based on the display being 16 characters wide. """ if not message: # If the message is empty just set the cursor to the last column cursor_position = COL_RIGHT_INDEX e...
43,949
def runner_entrypoint(args): """ Run bonobo using the python command entrypoint directly (bonobo.commands.entrypoint). """ return entrypoint(args)
43,950
def interface_details(): """Get interface details, CLI view""" if success_login_form is None: return redirect(url_for('base_blueprint.login')) else: return render_template('more_int_detials.html', details=GetDetails.more_int_details(device, username, password,...
43,951
def complement_sequence(sequence: str, reverse: bool = False) -> str: """Complement the given sequence, with optional reversing. Args: sequence: Input sequence reverse: Whether or not to perform reverse complementation Returns: Complemented (and optionally reversed) string """ ...
43,952
def run_real_data(): """ 测试GDA算法和逻辑回归算法 这里采用的数据集是breast_cancer数据 从实验结果来看,GDA算法的结果要稍微高于逻辑回归算法 :return: """ # 导入乳腺癌数据 breast_cancer = load_breast_cancer() data = np.array(breast_cancer.data) label = np.array(breast_cancer.target) data = MinMaxScaler().fit_transform(d...
43,953
def calc_llr(tree_dict: StrDict) -> int: """ Calculate the longest linear route for a synthetic route :param tree_dict: the route """ return calc_depth(tree_dict) // 2
43,954
def _GetArmVersion(arch): """Returns arm_version for the GN build with the given architecture.""" if arch == 'armeabi': return 6 elif arch == 'armeabi-v7a': return 7 elif arch in ['arm64-v8a', 'x86', 'x86_64']: return None else: raise Exception('Unknown arch: ' + arch...
43,955
def test__load_params_type(): """ Test that "VolumeType" is added to params """ kwargs = {"zone": "us-west-2", "type": "gp2"} expected = { "Action": "CreateVolume", "AvailabilityZone": "us-west-2", "VolumeType": "gp2", } result = ec2._load_params(kwargs=kwargs) as...
43,956
def logs(c, tail=10, follow=True, container=None): """Obtain last logs of current environment.""" cmd = "docker-compose logs" if follow: cmd += " -f" if tail: cmd += f" --tail {tail}" if container: cmd += f" {container.replace(',', ' ')}" with c.cd(str(PROJECT_ROOT)): ...
43,957
def package_copy(r, id, type, revision_number=None, version_name=None): """ Copy package - create a duplicate of the Package, set author as current user """ revision = get_package_revision(id, type, revision_number, version_name) """ it may be useful to copy your own package ... if r.user.pk == revision.author.pk...
43,958
def contract(equation, *operands, **kwargs): """ Wrapper around :func:`opt_einsum.contract` that caches contraction paths. :param bool cache_path: whether to cache the contraction path. Defaults to True. """ backend = kwargs.pop('backend', 'numpy') cache_path = kwargs.pop('cache_path', ...
43,959
def _compute_jn_pcoa_avg_ranges(jn_flipped_matrices, method): """Computes PCoA average and ranges for jackknife plotting returns 1) an array of jn_averages 2) an array of upper values of the ranges 3) an array of lower values for the ranges method: the method by which to calculate...
43,960
def get_readmission_label_keys(time_windows: List[int]) -> List[str]: """Get label keys for readmission. Args: time_windows: list<int> of the considered time windows (in days) for readmission. Returns: list<str> of labels for readmission within X days """ return [f"{READMISSION_LAB...
43,961
def runTool (toolFileName): """ Call an external application called toolFileName. Note that .exe extension may be omitted for windows applications. Include any arguments in arguments parameter. Example: returnString = te.runTool (['myplugin', 'arg1', 'arg2']) If the ...
43,962
def check_arguments(): """ Check the arguments """ global domain global file global skip_ip global logs_file parser = ArgumentParser(description='Script to scan subdomains of a domain') parser.add_argument("-d", help="Domain", required=True, action="store", dest="domain") ...
43,963
def multiplication(image1, image2): """ Multiply (pixel-wise) the two input images and return the result. <gui> <item name="image1" type="Image" label="Image 1"/> <item name="image2" type="Image" label="Image 2"/> <item name="result" type="Image" role="return" ...
43,964
def ioat_scan_accel_engine(client, pci_whitelist): """Scan and enable IOAT accel engine. Args: pci_whitelist: Python list of PCI addresses in domain:bus:device.function format or domain.bus.device.function format """ params = {} if pci_whitelist...
43,965
def load_test(tstfile): """Load a test from file. This reads a test from a csv file. Parameters ---------- tstfile : :class:`str` Path to the file """ # default version string version_string = "1.0.0" try: with zipfile.ZipFile(tstfile, "r") as zfile: inf...
43,966
def reorder_instruments(curr_instruments): """ Dialog to remove and add instruments at certain indexes. :param curr_instruments: initial list of instruments :return: The list of instruments in the new order """ while True: instruments_with_indexes(curr_instruments) tmp_instrument...
43,967
def fill_with_sample_data(rc_object): """Put dummy data into all four files of this RenewableCert.""" for kind in ALL_FOUR: with open(getattr(rc_object, kind), "w") as f: f.write(kind)
43,968
def compute_propeller_with_normal_position(arg_class, cabin_arr): """ compute propeller array and connected arm array :param cabin_arr: numpy array of cabin :param arg_class: argument class :return: propeller_arr, arm_arr """ l1 = arg_class.l1 l2 = arg_class.l2 l3 = arg_class.l3 ...
43,969
def get_dims_linear(weight_mat_layers, weight_dict): """ Returns a list of dimensions of layers of an mlp in decreasing order. """ dims = [] for ix, layer in enumerate(weight_mat_layers): dim_out, dim_in = weight_dict[layer].shape if ix == 0: dims.extend([dim_in, dim_out...
43,970
def yices_distinct(n, arg): """Returns (distinct arg[0] ... arg[n-1]).""" return libyices.yices_distinct(n, arg)
43,971
def is_cog_contributor(): """Check if whoever used the command is in the bots contributors.""" async def predicate(ctx): if str(ctx.author.id) in ctx.bot.contributors: return True else: raise NotAContributorError(f"Command {ctx.command.name} raised an error: {str(ctx.aut...
43,972
def tuplify2d(x): """Convert ``x`` to a tuple of length two. It performs the following conversion: .. code-block:: python x => x if isinstance(x, tuple) and len(x) == 2 x => (x, x) if not isinstance(x, tuple) Args: x (any): the object to be converted Returns: tupl...
43,973
def get_scene_info(path): """Extract information about the landsat scene from the file name""" fname = os.path.basename(path) parts = fname.split('_') output = {} output['sensor'] = parts[0] output['lpath' ] = parts[2][0:3] output['lrow' ] = parts[2][3:6] output['date' ] = parts[3] ...
43,974
def init_mako(app, **kw): """ Initializes the Mako TemplateLookup based on the application configuration and updates the _request_ctx_stack before each request """ def get_first(dicts, keys, default=None): # look in one or more dictionaries returning the first found value for d ...
43,975
def experiment(model_dir='.', # pylint: disable=dangerous-default-value imagenet_subset_dir=None, dataset='cifar10', batch_size=256, eval_batch_size=1024, num_epochs=200, learning_rate=0.1, aug_imagenet_apply_colou...
43,976
def erase_devices(): """Erase all the drives on this server. This method performs sanitize erase on all the supported physical drives in this server. This erase cannot be performed on logical drives. :returns: a dictionary of controllers with drives and the erase status. :raises exception.HPSSAExc...
43,977
def write_binary(filename, data, compressed=None, backup=True, makedirs=True): """Writes data (bytes) into a binary file. If compressed is None, autodetects if data should be compressed by filename suffix.""" with open_for_writing_binary(filename, compressed=compressed, backup=backup, makedirs=makedirs) as ...
43,978
def earlyon(time,duration,*args): """ Some lights have a slight delay before they turn on (capacitors that need to be charged up?). This takes the current time and subtracts that delay so the code looks like they turn on at the right time, but we really send the command a little bit early to give th...
43,979
def downsample_seg_to_mip(seg, mip_start, mip_end): """ Downsample a segmentation to the desired mip level. Args: seg (3darray): A volume segmentation. mip_start (int): The MIP level of seg. mip_end (int): The desired MIP level. Returns: 3darray: seg downsampled to :par...
43,980
def stop_workers(): """ Send all workers the command to exit the program. """ for worker in range(1, num_procs): pypar.send(SystemExit(), worker)
43,981
def example(name): """Renders a sample page with the name specified in the URL.""" return template('<b>Hello {{name}}</b>!', name=name)
43,982
def tri(N, M=None, k=0, dtype=float): """Creates an array with ones at and below the given diagonal. Args: N (int): Number of rows. M (int): Number of columns. ``M == N`` by default. k (int): The sub-diagonal at and below which the array is filled. Zero is the main diagonal,...
43,983
def UpdateGClientBranch(webkit_rev, magic_gclient_branch): """Update the magic gclient branch to point at |webkit_rev|. Returns: true if the branch didn't need changes.""" target = FindSVNRev(webkit_rev) if not target: print "r%s not available; fetching." % webkit_rev subprocess.check_call(['git', 'fet...
43,984
def get_process_name(): """Return the main binary we are attached to.""" # The return from gdb.objfiles() could include the file extension of the debug symbols. main_binary_name = gdb.objfiles()[0].filename return os.path.splitext(os.path.basename(main_binary_name))[0]
43,985
def calculate_trajectories(particles, daughters, alpha=1.): """Calculates the trajectories of the particles. Args: particles: a dataframe with the particle information. daughters: a dataframe where each line represents a daughter for the particles. alpha: for how long should stable trac...
43,986
def register_directive(name: str, directive: "Type[Directive]") -> None: """Register a directive to docutils. This modifies global state of docutils. So it is better to use this inside ``docutils_namespace()`` to prevent side-effects. """ directives.register_directive(name, directive)
43,987
def site_title(request, registry, settings): """Expose website name from ``tm.site_title`` config variable to templates. This is the default ``<title>`` tag. Example: .. code-block:: html+jinja <meta> <title>My page - {{ site_title }}</title> </meta> """ # Use .g...
43,988
def linkcode_resolve(repo_link: str, domain: str, info: dict[str, str]) -> typing.Optional[str]: """ Function called by linkcode to get the URL for a given resource. See for more details: https://www.sphinx-doc.org/en/master/usage/extensions/linkcode.html#confval-linkcode_resolve """ if domain ...
43,989
def scite( genotype_file, alpha, beta, n_iters, n_restarts, experiment, time_limit, smooth_rate, iters_rate, ): """SCITE. Tree inference for single-cell data :cite:`SCITE`. scphylo scite input.SC 0.0001 0.1 -l 1000000 -r 3 -e -t 86400 -s 2 """ outfile = os.path....
43,990
def checkForBamExtension(bamFile): """ make sure the specified file ends with either ".bam" or ".cram" """ extList = (".bam", ".cram") for ext in extList: if bamFile.endswith(ext): return raise OptParseException("Input alignment files should be in BAM/CRAM format and with extension .bam...
43,991
def deterministic_hash(items): """ Intermediary hashing function that allows deterministic hashing of a list of items. :param items: List of items to hash :return: Numeric, deterministic hash, returns 0 if item is none """ h = 0 for item in items: if not item: pass ...
43,992
def get_unique_licenses(codebase, good_only=True): """ Return a tuple of two sets of license keys found in the codebase: - the set license found in key files - the set license found in non-key files This is only for files in the core facet. """ key_license_keys = set() other_license_key...
43,993
def execute_sql_insert(cursor, sql_query): """ Executes SQL INSERT queries. :param cursor: Database cursor :param sql_query: SQl query to execute :return: Database cursor and last inserted row id """ if cursor is None: raise AttributeError("Provide cursor as parameter") if sql_...
43,994
def fetch_known_transcripts_with_gene_label(cursor, datasets): """ Fetch known transcripts along with the gene they belong to """ datasets = format_for_IN(datasets) query = """SELECT DISTINCT gene_ID,transcript_ID FROM observed LEFT JOIN transcript_annotations AS ta ON ta.ID = observed.t...
43,995
def change_data(): """Редактирование профиля пользователя.""" form = ChangeDataForm() if form.validate_on_submit(): current_user.age = form.age.data current_user.country = form.country.data current_user.city = form.city.data current_user.telegram = form.telegram.data ...
43,996
def simulate_single_image( simulation: Simulation, idx: int, zarr_filename: Optional[str] = None ) -> np.ndarray: """Generate a single image from a single-particle simulation. Optionally saves image into zarr store """ # get info required for simulation image_parameters = simulation.per_ima...
43,997
def run_checks(root, parent, cmds, scmds, paths='', opts={}): """Run the checks given in 'cmds', expected to have well-known signatures, and report results for any which fail. Return failure if any of them did. NB: the function name of the commands passed in is used to name the NOT file which exce...
43,998
def restore(path: Union["os.PathLike[str]", str], clean: bool): """ Restore command for mass apk installer :param path: :param clean:bool delete folder or files used by restore command before function returns :return: None :raises MassApkFileNotFoundError """ try: os.path.exist...
43,999