content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from datetime import datetime def _event_last_observed(event: EventsV1Event) -> datetime.datetime: """ Returns the last time an event was observed """ if event.series: series_data: EventsV1EventSeries = event.series return series_data.last_observed_time if event.event_time: ...
c8a26c067df0375923b3aa57afaa48f5c5fc0cf8
29,900
import numpy def bytes(length): """Returns random bytes. .. seealso:: :func:`numpy.random.bytes` """ return numpy.bytes(length)
44055f168dbd9e6b2e2481f8d57b9edef0110430
29,901
def init_json(): """ This function init the JSON dict. Return : Dictionnary """ data_json = {} data_json['login'] = "" data_json['hash'] = "" data_json['duration'] = 0 data_json['nbFiles'] = 0 data_json['nbVirus'] = 0 data_json['nbErrors'] = 0 data_json['uuidUsb'] = "" ...
9411f3a525df9e68f53fba94da679bd8d5b34013
29,902
def django_popup_view_field_javascript(): """ Return HTML for django_popup_view_field JavaScript. Adjust url in settings. **Tag name**:: django_popup_view_field_javascript **Usage**:: {% django_popup_view_field_javascript %} """ temp = loader.get_template('django_popup_view...
f2cf0631139ade2044aa577f906b4b8568b33713
29,903
import re import os def get_version(verbose=0): """ Extract version information from source code """ matcher = re.compile('[\t ]*#define[\t ]+OPENQL_VERSION_STRING[\t ]+"(.*)"') version = None with open(os.path.join(inc_dir, 'ql', 'version.h'), 'r') as f: for ln in f: m = matcher....
c80ee3543973879e11f47a178394b7c23dea501f
29,904
def apply_filters(row): """Applies filters to the input data and returns transformed row.""" return {k: COLUMN_FILTERS.get(k, lambda x: x)(v) for k,v in row.items()}
2f31dda70bedc35f8b1b66e5906c38c5d3202e2b
29,905
def save_convergence_statistics( inputs, results, dmf=None, display=True, json_path=None, report_path=None ): """ """ s = Stats(inputs, results) if display: s.report() if report_path: with open(report_path, "w") as f: s.report(f) if json_path is not None: with...
e06891c917abc3678e8fbcf0ff81cae46ac2e04a
29,906
import pkgutil import platform import sklearn from importlib import import_module from operator import itemgetter from sklearn.utils.testing import ignore_warnings from sklearn.base import ( BaseEstimator, ClassifierMixin, RegressorMixin, TransformerMixin, ClusterMixin, ) d...
b0171c3e820fc4e686882f3f0d2a10f5b8ccf4c6
29,907
def max_size(resize_info): """ リサイズ情報から結合先として必要な画像サイズを計算して返す :param resize_info: リサイズ情報 :return: width, height """ max_w, max_h = 0, 0 for name, info in resize_info.items(): pos = info['pos'] size = info['size'] max_w = max(max_w, pos[0] + size[0]) max_h = max...
1e28f993b3b0fac077f234b6388a2d9042396f6b
29,908
def get_thru(path, specs=range(10), cameras='brz'): """Calculate the throughput in each camera for a single exposure. See https://github.com/desihub/desispec/blob/master/bin/desi_average_flux_calibration and DESI-6043. The result includes the instrument throughput as well as the fiber acceptance los...
ec123a4f8843fcd5eb4aef87bf77b936687c544d
29,909
def quicksort(lyst): """This is a quicksort """ def partition_helper(lyst, first, last): pivot = lyst[first] left = (first + 1) right = last done = False while not done: while left <= right and lyst[left] <= pivot: left += 1 whi...
33385c01b877a86a2970f33dc4d0bd9d456dc983
29,910
def status_parameter_error(): """Returns the value returned by the function calls to the library in case of parameter error. """ r = call_c_function(petlink32_c.status_parameter_error, [{'name': 'return_value', 'type': 'int', 'value': None}]) return r.return_value
fbbdcd85fde27f200c1c749e03234baa8d725f1d
29,911
def df_to_dict(df: DataFrame) -> list[dict]: """DataFrame 转 dict""" # 拿到表头,转换为字典结构 head_list = list(df.columns) list_dic = [] for i in df.values: a_line = dict(zip(head_list, i)) list_dic.append(a_line) return list_dic
c52e628a78e2bd863a4a9926e739bff53195910a
29,912
def parse_describeprocess(html_response): """Parse WPS DescribeProcess response. Parameters ---------- html_response : string xml document from a DescribeProcess WPS request. Returns ------- out : list of dict 'identifier' : ProcessDescription -> ows:Identifier 'inp...
80f7e866424ffa8cbdae2a94d31f6044722648c6
29,913
def variational_implicit_step(system, dt, p, x, z, t): """ For Lagrangian functions of the form L(j) = 1/(2h^2) (x_{j+1} - x_j)^2 - 1/2 (V(x_j) + V(x_{j+1})) - 1/2 (F(z_j) + F(z_{j+1})) """ tnew = t + dt xnew = ( x + (dt - 0.5 * dt ** 2 * system.Fz(z, t)) * p - 0.5 * dt ** 2 * system.Vq...
c32e13ae37873983a3a88b91e7f0bfdf7ba9d043
29,914
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. """ ...
595ff793e4e5b4f1eeaf0c60d0db631565fea078
29,915
def _validate_time_mode(mode, **kwargs): """Validate time mode.""" return mode
e30fd9071bde102b4986fe9ef846a812f7c08ff7
29,916
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...
bf00faa00f5059c33887acafb0665ae37dc970e8
29,917
def _important() -> str: """Returns a query term matching messages that are important.""" return 'is:important'
dced06645f5311b321d42cd3892627df5b30faec
29,918
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"}
6d3b634444240275f56d30aa0c1fe3b3bb84ce24
29,919
from typing import Hashable import encodings 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")
064f90d4974f64d9be99090c77cf24d30a34a9f0
29,920
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...
37da937db46bea8e7952e72753ab27543215f8fe
29,921
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))]
e89d3218d053852ddbc553223d035c71615f7c21
29,922
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...
acfa5f275bc15a39357390ac356f7ee681dbf31a
29,923
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
f42cae0552a4ac791d3499fa2ca1417a80a970ac
29,924
import time 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...
301d046541c0463e8e3ab58fe429a3c47cbd960e
29,925
def CalculateGearyAutoMutability(ProteinSequence): """ #################################################################################### Calculte the GearyAuto Autocorrelation descriptors based on Mutability. Usage: result=CalculateGearyAutoMutability(protein) Input: protein is a pure protein sequenc...
a9a7f92d742736f7a66c8bdc06980f393922ea4a
29,926
import torch 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...
a0c1fc6c273bd4fb10871c7fbf130e0113a65a71
29,927
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)
fe895c87867999159c57f23f96eab9d7b41edb8e
29,928
from typing import Dict from typing import Union from typing import List 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, ta...
6931a115fab8bb65834936b972d9fa51229458c9
29,929
def generate_url(mbid, level): """Generates AcousticBrainz end point url for given MBID. """ return ACOUSTIC_BASE + mbid + level
96fe05dc3274730196dbc764c3e8f58f32b81a5f
29,930
from typing import Sequence from typing import List 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 ...
6da79c699a3420270efc938a6f0de659d4886060
29,931
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...
3f615b38d3e303a63873f3dc8ed2d3699460f3b8
29,932
import os 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] != '.'):...
e8c56e64c08dced954e0e0a92cc16939f883e942
29,933
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
02ce128f1de1dbeb2a2dcef5bc2b6eb8745322d3
29,934
import typing import numpy 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 calibra...
e312ee866c142b6d2166c450831ce5308d263aaa
29,935
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)
49c2797c2798a0870cbc68e6ffe917d353cf41bb
29,936
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...
9da04c8898bb58db0db49eb46bb69b3591f6c99d
29,937
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 + ...
06b5d6a56db19ebc7d43b1d4a95805559e549273
29,938
import functools import time 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.confli...
bb5b225f2eccf75d71d3cfb67cb1d5517e66e086
29,939
import os import json 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
e71c3dbc040a5425dd16ed35267dc9fa681b3322
29,940
from datetime import datetime import time 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+jin...
739a1b97499a614dfabe9321ccd18126d1ebcad9
29,941
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]
ca11226c6f6fc731089f1d257db02a6cb83bd145
29,942
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...
777c87bf1c4ac123f65e4061c1e5e72f5abe90d9
29,943
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...
e42d050074b9f83127cca95261d5b1300a5b453a
29,944
from pathlib import Path import yaml 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 / 'ru...
24def1cb09f1ecc464d38b866397d9821ac24293
29,945
from pymatgen.core.structure import Structure 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. Ran...
35be05f136c5f1050394a0ac335ad281c0e855c3
29,946
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
eddb25b2fdc0dd5b5d2505fc52cb1353ce74f89d
29,947
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
e9f302cea41e6a3b51044be28850b948153170e7
29,948
def quarter_of_year(datetimes): """Return the quarter of the year of given dates.""" return ((_month_of_year(datetimes) - 1) // 3 + 1).astype(int)
49f3d8d63f9cc5c73b2c0c6cf9859c8be53e567e
29,949
def runner_entrypoint(args): """ Run bonobo using the python command entrypoint directly (bonobo.commands.entrypoint). """ return entrypoint(args)
f1eda845fa442d831f12b501a45dff3c91297f2a
29,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,...
f5643644583babb92a188d04c77a59582db69b52
29,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 """ ...
74c85857f3abf669cfaa43d05d1f0190a448bb54
29,952
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
18c4cf62e434ee1e7c5902871feb323c1b72a96d
29,953
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...
fbad0d1066fe4a7e81d2341291b436f5dd98fff0
29,954
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...
8f244a6e8b1309b8b129f316698047b6c78f0186
29,955
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', ...
c7ac17fcee8eef036181e0ee2a96d0b0d4a38593
29,956
import array 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 whi...
bba0003df771b60a55b11b67a7df7cb36039d69f
29,957
from typing import List 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 """ ...
1ba53ef818aadb719832d23afb250fb817b1e087
29,958
import subprocess import os import sys 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'...
0526ae67d8a9778fe97336b71508679c7bf08791
29,959
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" ...
2813758eba743155960d617eb03aafa937a4cfc0
29,960
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...
714e40288b2ba141d113c0951bf2c171ebcc76d3
29,961
import zipfile import csv 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...
c8b4e7f2dfc7e627afd1ae58a64723a4deed8248
29,962
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...
03c042e086d99c9e5ab52c37a2272af82411c777
29,963
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 ...
c58aa5939f1b4fef05c9bfa09781310a9b64ab52
29,964
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...
eba82695a5c3bd1f850703b172e1f0a7b84fa010
29,965
def yices_distinct(n, arg): """Returns (distinct arg[0] ... arg[n-1]).""" return libyices.yices_distinct(n, arg)
7d37cf6a2193cb4bb0d1d46f4f9986afbe35ad50
29,966
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...
d0a7d8096f03ce1bbeed2e6c6265c46d0ae1022a
29,967
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...
64170b14dbe7eb8885d21f45acff6b43979f1219
29,968
import os 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' ] ...
4a1bbad4d8b9b2b1ad21ca78ca7a046d92232699
29,969
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 ...
60713b06cde3be9eca72207aea69a30d9061cffc
29,970
import time 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 exce...
5f9a7a2328b24cb0fb45ea560f570b596c0326d7
29,971
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...
5671d46ffe42bd456689cffc3ce3e1f6731101c8
29,972
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...
9245c6f1b0602f284a7d565758e322af083e6242
29,973
def example(name): """Renders a sample page with the name specified in the URL.""" return template('<b>Hello {{name}}</b>!', name=name)
df52c3ed0708698d7049223b5ea1b7d98f8c3eb7
29,974
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,...
e7de7d0bc41563450d7e98071a14ca3b85f250c5
29,975
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...
52de6ec5139052de914d29d44b926938227894db
29,976
import os 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]
eb74c4b325668888a0c4f2d1ed25aa025f7c0577
29,977
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...
fb9422ac315dc1c2b6e6781cfef93e8235dd7f2d
29,978
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...
fcc61acecabb163ef6e55ed2fde7d4d025a8082a
29,979
import typing from pathlib import Path import importlib import inspect import ast 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/m...
1fd4571b81f98c82c57dae43a2be957380dca91f
29,980
import os 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 """ outfil...
524127b14edf0777c2dae039d652aa6271595825
29,981
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 ...
da3950039762e2b499f522cbd891a87d98633bd9
29,982
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...
ee9e1ea67809edcedc5f300c5321d9ebc60001d6
29,983
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_...
ece8362efff364558e9deb480db3ec690e638eca
29,984
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...
92dbd97ee79672ff0986c2caecf90ab95f05fa70
29,985
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 ...
6dc8299a07733fe7291d1c8b646848f6e1b60c60
29,986
from typing import Optional from pathlib import Path import os import subprocess 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 "...
105e1e7cdd85f22a6d1e31a98128d37441da92bb
29,987
from io import StringIO 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 t...
bde53f0f0fca0b6d12f6cf58b631cc841a0d567f
29,988
def numpy_to_rdkit(adj, nf, ef, sanitize=False): """ Converts a molecule from numpy to RDKit format. :param adj: binary numpy array of shape (N, N) :param nf: numpy array of shape (N, F) :param ef: numpy array of shape (N, N, S) :param sanitize: whether to sanitize the molecule after conversion...
93295c556037ffa3e84373b73ca1308a9a1d53b7
29,989
from typing import Dict from typing import Any from pathlib import Path def get_path(key: str, **kwargs: Dict[str, Any]) -> Path: """Get a file path string system variable as a pathlib.Path instance. See signature of get() for parameter details.""" return Path(get(key, **kwargs))
9fe34573ced90c266ef7b73a430cc95ba4d09bc5
29,990
import time def run_competition(builders=[], task=BalanceTask(), Optimizer=HillClimber, rounds=3, max_eval=20, N_hidden=3, verbosity=0): """ pybrain buildNetwork builds a subtly different network structhan build_ann... so compete them! Arguments: task (Task): task to compete at Optimizer (cla...
8f826e4dbf7bbcc111a30bf4a08597629efb4f63
29,991
def get_reduced_tree(tree, reduce_by): """ Given a tree decomposition in tree and a required size of reduction, produces a new tree decomposition with treewidth reduced by the requested size and a list of eliminated nodes. We use a greedy algorithm to find nodes to eliminate. This algorithm ...
a644ae326ef86e9b53bb3c3c510e46740038c8d3
29,992
from pathlib import Path def temp_path(suffix=""): """Return the path of a temporary directory.""" directory = mkdtemp(suffix=suffix) return Path(directory)
2cd196a2a1974816d49d75fd10a0d43b03c12612
29,993
def maybe_utf8(value): """Encode to utf-8, only if the value is Unicode.""" if isinstance(value, unicode): return value.encode("utf-8") return value
82e15ef35527e064a2b5bf3934c135985d60e1fe
29,994
def parse_id_as_interval(id_string, regex): """ The fasta ids contain the locus information. """ match = regex.match(id_string) genome = match.group("genome") seqid = match.group("seqid") start_tmp = int(match.group("start")) end_tmp = int(match.group("end")) start = min([start_tmp, end_tm...
7d35bdd7b4418d1edcd433cd39b9defc9050c6f6
29,995
def map_sentences_to_indices_of_vectors(sentences, word_to_index_glove, unknown_token): """ map senteces to integers that represent the index of each word in the glove vocabulary """ # the list to be returned mapped_sentences = [] # get the index of the unknown token unknown_token_index = word_to_...
04a27bd4ccd5ac9d0366218107ee36b61d4a7655
29,996
import subprocess def ruler(inputdict_unchecked): """ This program calculates reduced transition probabilities. (RULER readme) Parameters ---------- inputdict_unchecked : dictionary dictionary that must have the following key-pair values: input_file : string, input ensdf file ...
7cbc88b9c2bf561d483d12609ff14decf19df7e7
29,997
import numpy def jordan_wigner_dual_basis_jellium(grid, spinless=False, include_constant=False): """Return the jellium Hamiltonian as QubitOperator in the dual basis. Args: grid (Grid): The discretization to use. spinless (bool): Whether to use the spinles...
d52a5a102297213de830f58c8190337589d0d9ca
29,998
def boxcar_decay(tbins, t0, area_box, height_box, area_decay): """ Compute the lightcurve from one or more boxcar-decay functions. Parameters ---------- tbins : array edges of the time bins used for the lightcurve t0 : float or array start times of the boxcar-decays area_box...
31beb8d6cab940bd75a814121833535819c17e69
29,999