content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def kinetic_local(omega_par, disp_vector, passive_el, ind_passive, coord, connect, E, v, rho, const_func): """ Calculates the local kinetic energy function. Args: omega_par (:obj:`float`): 2 * pi * frequency. disp_vector (:obj:`numpy.array`): Displacement. passive_el (:obj:`numpy.array`...
d62f8ae304e82086cfd17136304e4844154ec337
71,200
def is_new_dbinit_notification(init_id, echoed_init_id): """Returns True if we have a received a new db initialisation notification from a peer unit and we have not previously echoed it to indicate that we have already performed the necessary actions as result. Initialisation notification is expected t...
3ff60ca786dd9e23e278d2e34d4e20f3e7b20985
71,201
def handle_NameError(exc, source): """Handles situation where a NameError is raise.""" _ = gettext_lang.lang msg = exc.args[0] var_name = msg.split("'")[1] exc_name = exc.__class__.__name__ python_display = "{exc_name}: {msg}".format(exc_name=exc_name, msg=msg) filename, linenumber = extrac...
88a8026c206cebe6837f8aee7f345d1dc640e4e1
71,202
def logout(): """Clear the current session, including the stored user id.""" logout_user() return redirect(url_for("index"))
0236e48025bf74eec9c56ee064d6dac985d9db59
71,203
import json def get_dataframe(): """Retrieve the dataframe from Redis This dataframe is periodically updated through the redis task """ jsonified_df = redis_instance.hget( tasks.REDIS_HASH_NAME, tasks.REDIS_KEYS["DATASETUP"] ).decode("utf-8") # df = pd.DataFrame(json.loads(jsonified_df...
465fcc3ece46428efa9e79b56dbd7a2fdd9f7bdd
71,204
def pokemon_media_path(pokemon_species, prefix, ext, form=None): """Returns a path to a Pokémon media file. form is not None if the form should be in the filename; it should be False if the form should be ignored, e.g. for footprints. """ # Leave it as None if it's null; pass it by filename_from_n...
7dd88cddaa0a6c158bf99dcfff9e82d26d7d2769
71,205
import requests import sys def search_solr_parse_json(): """ """ solr_url = 'http://localhost:8983/solr/nounphrases_wikipedia/select' # Exact search only url_params = {'q': '*', 'rows': 8000000, 'fl': 'wikipedia_url,num_occurrences'} solr_response = requests.get(solr_url, params=url_params) if...
8f1eebf68f0852106fe3892a7816bb96fc9f010d
71,206
def option_select(prompt="", choices=None): """ Bullet option select utility. """ return ScrollBar( prompt=prompt, choices=choices, margin=2, pointer="→" ).launch()
bceb101afdcc6332fd96911b4810feaf9093ae1b
71,207
def dist_12x24(var_series, aggregation_method='mean', var_name_label=None, return_data=False): """ Accepts a variable series and returns a plot of 12x24 (12 months x 24 hours) for the 'mean' of the variable with the table of data as an optional return. The aggregation_method 'mean' can be can be changed as ...
d4e7a79fe84ea9beb0139a8aabc0eecbc55b8b60
71,208
def mixer_l32_224(pretrained=False, **kwargs): """ Mixer-L/32 224x224. Paper: 'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601 """ model_args = dict(patch_size=32, num_blocks=24, embed_dim=1024, **kwargs) model = _create_mixer('mixer_l32_224', pretrained=pretrained...
009fdca7e1c1ddf743b42cdeb26866cec4a68b5e
71,209
def projector(data, cube, mask=None, obstacle=None, nthread=0): """ Project a cubic map into a data cube using the Siddon algorithm. The data cube is updated in-place, so you should make a copy before calling projector. Arguments --------- data : 3d InfoArray Contains a concatenation ...
b2a14ad97688451b53771296a0fcbec9194b5cf3
71,210
def parser_add_args_from_para(parser, para, usage): """Take the next Para as Lines of Args, if tagged as Positional Arguments""" if para[0].startswith("positional arguments"): for line in textwrap_para_unbreakdent_lines(para=para[1:]): parser_add_arg_line(parser, usage=usage, line=line) ...
d6b4f1ac20b2e8f24daab069b4071e952c694ad0
71,211
import os def default_node_sublabels(node): """function mapping nodes to a sublabel (e.g. specifying some attribute values) :param node: the node to map :type node: aiida.orm.nodes.node.Node :rtype: str """ # pylint: disable=too-many-branches class_node_type = node.class_node_type ...
9d0356e58f3493f378018295192f49891217801b
71,212
def getDERIP(tracker,ID="deRIPseq",deGAP=True): """Write tracker object to sequence string. Requires that all base values are strings.""" deRIPstr = ''.join([y.base for y in sorted(tracker.values(), key = lambda x: (x[0]))]) if deGAP: deRIPstr = deRIPstr.replace("-", "") deRIPseq = SeqRecord(Seq(deRIPstr, Gap...
714ba32c38e363289d38f587285d22d1ede8a862
71,213
def part_b(data, **_) -> int: """ Solution for part b Parameters ---------- data: str Returns ------- answer: int """ memory = {} mask = None for row in data.split('\n'): if row.startswith('mask'): mask = row.split(' = ')[1] else: ...
f662862c001b9fc7c882b014915a4efc47d510a1
71,214
from typing import List def get_worker_files(paths: List[str], env: CylonEnv, ext: str = None) -> List[str]: """ calculate the list of files that this worker will read """ all_files = get_files(paths=paths, ext=ext) start, end = indices_per_worker(len(all_files), env.rank, env.world_size) retu...
b6670ad3930826708254747ae1f10b97b77d4da5
71,215
import requests import json def modify_snmp_template(auth, url, snmp_template, template_name= None, template_id = None): """ Function takes input of a dictionry containing the required key/value pair for the modification of a snmp template. :param auth: :param url: :param ssh_template: Human ...
d4061820b588d8d1f2a6d77aa815022f21329b05
71,216
import inspect import os def get_setup_file(): """Returns the absolute path to the setup file for this package. Apache Beam requires this setup file to build this package on remote workers. """ this_file = inspect.getfile(inspect.currentframe()) this_dir = os.path.dirname(this_file) relative_path = os.pa...
da2f8d0528bb84189526ced3f21421859325601f
71,217
from typing import Sequence from typing import Optional def nodes_to_attach_risk_to( nodes: Sequence[NodeView], risky_node_keys: Optional[Sequence[str]], ) -> Sequence[NodeView]: """ a None risky_node_keys means 'mark all as risky' a [] risky_node_keys means 'mark none as risky'. """ if risky_...
9677a6f4fe212614090e247c1f8171bd713f393c
71,218
def configlet_factinfo(configlet_name, facts, debug=False): """ Get dictionary of configlet info from CVP. Parameters ---------- configlet_name : string Name of the container to look for on CVP side. module : AnsibleModule Ansible module to get access to cvp cient. debug : b...
9aba41363059c41e5c905043f862e3acf26a4ff2
71,219
def _calculate_overlap(seq1, seq2) -> float: """ Calculate overlap between two time series sequence :param seq1: Time series sequence :param seq2: Time series sequence :return: overlap value between two sequences """ if seq2.end > seq1.end and seq2.start >= seq1.start: return (seq1...
cbc8b2694742cbc0d47e0599a2ad158db76f8c2b
71,220
def foeppl_np_inkl_null(var_x, grenze_a, potenz_n): """Numpy Funktion für die Föppl Klammer mit ((var_x-a)==0) = 0""" return np.where((var_x - grenze_a) <= 0, 0, (var_x - grenze_a) ** potenz_n)
8f751529451ad19fa5a6b0bccfb322f8c75c28f8
71,221
def getDeploymentSections(deploymentInfos, nodesInformation): """ Combine deployments to the same nodes into lists in order to save on connect/disconnect time :param deploymentInfos: deployment infos :type: :class:`~storm.thunder.configuration.DeploymentInfos` :param nodesInformation: nodes informa...
3630f5ca0d7237fd2bdc0ce80026922eae20718f
71,222
def sorted_eigenvector_matrix(M, numpy=False, increase=False, eps=1e-14, **kwargs): """ returns a matrix whose columns are the normalized eigenvectors of M :M: square matrix (entries are assumed to be numbers) :numpy: use numyp instead of sympy :increase: sort in increasing order (defa...
ab895873d91cf114e6eecb5fd484528790faaec3
71,223
def _get_query_seqs(count_start, ref, ref_complement, srna_length): """ Get to correct length fwd and rvs query seq from the ref :param count_start: :param ref: :param ref_complement: :param srna_length: :return: """ query_seq_fwd = DNA(ref[count_start:(count_start + srna_length)]) ...
27ec71b3ad0735ac792b77cb59f7b6a0b16ca436
71,224
import collections def convert_examples_to_features(examples, tokenizer, max_seq_length, doc_stride, max_query_length, is_training): """Loads a data file into a list of `InputBatch`s.""" unique_id = 1000000000 features = [] for (example_index, example) in enumerate(e...
9cd255efd8daa611c9cccb6f33c39fe77c27f829
71,225
def find_val_percent(minval, maxval, x): """Find the percentage of a value, x, between a min and max number. minval -- The low number of the range. maxval -- The high number of the range. x -- A value between the min and max value.""" if not minval < x < maxval: print("\n" + " ERROR: X mu...
13661bb2b6b230fa212ddd3ceb96c5b362d52f19
71,226
def class_delete(): """ 删除班级信息 :return: """ res = ResMsg() obj = request.json n_class = db.session.query(Class).filter(Class.id == obj["id"]).first() n_stu_cls = db.session.query(StuCls).filter(StuCls.class_id == obj["id"]).all() try: db.session.delete(n_class) db.ses...
fd247e9c2dd162b915ea9dab24ce942c1042af7d
71,227
import json def specific_area(region): """ Shows the total number of COVID-19 positive test cases in specific \"region\"""" string = region.lower() datas = json.loads(date_function.regional_data) return datas.get(string,'The region name doesn\'t exist')
bef2a0dbf31cd82619fb36aa65a905244bd2e9f1
71,228
def ver_datos_basicos(request, extension_aulica_id): """ Visualización de los datos básicos de un extension_aulica. """ extension_aulica = __get_extension_aulica(request, extension_aulica_id) try: codigo = Establecimiento.get_parts_from_cue(extension_aulica.cue)['codigo_tipo_unidad_ed...
303bf80b1a08102aad3a702ab4ec556885bf96f3
71,229
def name(who): """Return the name of player WHO, for player numbered 0 or 1.""" if who == 0: return 'Player 0' elif who == 1: return 'Player 1' else: return 'An unknown player'
a553b64c7a03760e974b5ddeac170105dd5b8edd
71,230
from sys import path def get_scarff_version(): """ Find the value assigned to __version__ in __init__.py. This function assumes that there is a line of the form __version__ = "version-string" in scarff/__init__.py. It returns the string version-string, or None if such a line is not fou...
d56478e126f19d9b95c24d0304daaa24b947a1a7
71,231
import requests def jyfm_data_soybean_oil(indicator="豆油年度产能", headers=""): """ 交易法门-数据-农产品-豆油 :param indicator: ["豆油年度产能", "压榨装置开工率", "油厂周度产量", "豆油现货成交", "豆油商业库存", "豆油毛利润", "豆油月度产量", "豆油月度进口", "豆油月度消费", "豆油月度出口", "豆油月度库存"] :type indicator: str :param headers: headers with cookies :type hea...
b321569aa34351c7f94dfe9d697e67c221278663
71,232
def segment(*args, **kwargs): """ Segment the map """ if len(args) > 0 and type(args[0]) == "str" or "input_map_filename" in kwargs: func = mapfile_segment else: func = array_segment return func(*args, **kwargs)
0f1e3eca39a335031dcd6920f5c691086a1528db
71,233
def normalize_time_window(time_window, values_per_time_point): """ Bring all values in time window to -1, 1 range and center them around 0. :param time_window: vector of values for set of time points :param values_per_time_point: number of numeric values describing one time ...
4ee9fb63dfe30736f4c33ab1d97bd49d1f4aa944
71,234
def mean(nums): """ Gets mean value of a list of numbers :param nums: contains numbers to be averaged :type nums: list :return: average of nums :rtype: float or int """ counter = 0 for i in nums: counter += i return counter / len(nums)
d3ea7af8792f4fdd503d5762b5c0e54765ce2d99
71,235
def process_data(dr): # 统一输入单词的长度,不足补0,此方法会增加训练时间 """ :param dr: class data reader :return: process X, Y """ return dr.XTrain, dr.XTest, dr.YTrain, dr.YTest # 这是为了统一一个表达方式,和之前的章节一样
cc05605d77e25ed7363da3de9407d1f51b7dbf4b
71,236
def conv_block(x, growth_rate, name, activation, momentum, epsilon): """Convolutional block defined in Densenet architecture, It is its base layers Args: x: input tensor form the precedent layer growth_rate : float number, growth rate or number of filters (ref. paper) ...
125597246999c38630c8c9392e0ef874dbe863df
71,237
def question_2(data): """ Plots 2 graphs: Temperature change as a function of 'DayOfYear', and STD of daily temperatures as a function of 'Month'. Parameters ---------- data: preprocessed of city temperature dataset Returns ------- A tuple of: 1. A design matrix...
610067d77957ef36170e97d7152e2e1bc1b84e11
71,238
def map_id_to_value(nodes, value): """Maps Node id to another value""" return remove_colons(nodes).set_index('id')[value].to_dict()
b1f20a25df51cd93d13e16de197affbb768908e9
71,239
def PlotAA(df, eom=9, show_plot=True): """ Summary ------- Plot of annual average bar chart. No documentation as of 2018-10-31. Future Development ------------------ 1. Add comma separator to y-axis. 2. Add option to view by Sacramento Index Water Year Types. """ # Obtain ...
b258b0ecee7676a994558d9b2f89583b89a425b3
71,240
from .parser import read def df_from_sas(target, meta_df, skiprows=None, nrows=None, chunksize=None): """Deprecated. Use pyhcup.parser.read()""" print "WARNING: pyhcup.sas.df_from_sas() is deprecated and is scheduled for removal in pyhcup 0.1.6; use pyhcup.parser.read()" result = read(target, meta_df...
4afd2fd61dcd6af489cb63977ff8ad1dc222749d
71,241
def all(functions): """Returns function that returns True when all components return True.""" def apply_to(*args, **kwargs): return conjoin(functions, *args, **kwargs) return apply_to
6279be8d9e1977454e24d35d3cc94228f64dda35
71,242
def CombineProvenanceConst_get_decorator_type_name(): """CombineProvenanceConst_get_decorator_type_name() -> std::string""" return _RMF.CombineProvenanceConst_get_decorator_type_name()
6542246ac76545da6f98ada6f15653850b6ccc5e
71,243
def BuildVRTInternalObjects(*args): """ BuildVRTInternalObjects(char const * dest, int object_list_count, GDALBuildVRTOptions options, GDALProgressFunc callback=0, void * callback_data=None) -> Dataset """ return _gdal.BuildVRTInternalObjects(*args)
e5eb1aef230c79e6ff68a8f57fed0ef106c2e181
71,244
from typing import Tuple def _has_line_of_sight(matrix: np.ndarray, start: Tuple[int, int], end: Tuple[int, int]) -> bool: """ Return True if two points on a grid have line of sight. Return True if start == end. """ if start == end: return True start_y, start_x ...
fa9ecdb54fba90c43586f710b58bc51f37992048
71,245
def threshold1(x, col, thresh): """ 1-dimensional classification using a threshold function. """ return x[:, col] <= thresh
5814ab93fe41e2e92f4648bfee1f8033ff0864b6
71,246
import os import click def ask_overwrite(file_path): """ asks if you want to overwrite the given file, if it exists :param file_path: :return: """ if os.path.isfile(file_path): click.echo( chalk.red( "A configuration file already exists. Are you sure you wan...
1c8998fdfe85186dc8456b8a01949701f4b79ab2
71,247
from typing import Union from typing import List import sys def main(argv: Union[List[str], None] = None) -> int: """Delegate processing to functional module.""" argv = sys.argv[1:] if argv is None else argv return ky.main(argv)
4cca2c0b79dd0eff2d62476c4f5c8deabf55f30d
71,248
import torch def compute_rank(predictions, targets): """Compute the rank (between 1 and n) of of the true target in ordered predictions Example: >>> import torch >>> compute_rank(torch.tensor([[.1, .7, 0., 0., .2, 0., 0.], ... [.1, .7, 0., 0., .2, 0., 0.], ...
0aed5b14ef9b0f318239e98aa02d0ee5ed9aa758
71,249
def load_dataset(dataset_path, sequence_length, src_vocab_file, tgt_vocab_file, batch_size, buffer_size): """Create a tf.data Dataset. Args: dataset_path: Path to the files to load text from sequence_length: Maximun Length of the Sequence vocab_file: Location of vocab file batch...
b831403cbdf3ee2351aab72099031cf3dd780af7
71,250
def LazyLoadModule(name, contents): """ :param name: name of the module :param contents: dictionary of initial module globals This function returns a special module type with one method `_addattr`. The signature of this method is: _addattr(name, creator, *creatorArgs, **creatorKwargs) ...
5bb4cae8fc7209ba03bb74ac03e701ba74caf29a
71,251
def _debug(): """ returns True if debugging turned on (via _set_debug), otherwise, false """ return _DEBUG
5a4116f7ad462f8c0f1262577499dde1d1684296
71,252
def udfize_lambda_string(code: str): """Return a string with the code as a function""" return "lambda input: ({})".format(code) # return "lambda input: (%s)" % code
c519c8ec408b00f033878b6083d4a922f32d2ac9
71,253
import json def load_scalabel_frames( scalabel_frames_path ): """ Loads Scalabel frames from a file. Handles both raw sequences of Scalabel frames as well as labels exported from Scalabel.ai's application. Raises ValueError if the data read isn't of a known type. Takes 1 argument: scalab...
7e5467d0f184dba1e3efc724391931ed4053a683
71,254
def ovs_version_str(host): """ Retrieve OVS version and return it as a string """ mask_cmd = None ovs_ver_cmd = "ovs-vsctl get Open_vSwitch . ovs_version" with host.sudo(): if not host.exists("ovs-vsctl"): raise Exception("Unable to find ovs-vsctl in PATH") mask_cmd = host.r...
607ffbb2ab1099e86254a90d7ce36d4a9ae260ed
71,255
def maximum_displacement(initial_velocity): """Derived from s = 0.5 u + u t + 0.5 a t^2 at t = u and a = -1. The (0.5 u) term comes from the order of rules of the motion of the probe, the displacement changes before the velocities are updated.""" return int(0.5 * initial_velocity * (1 + initial_vel...
c4b71ad83d787cae9ad9abe7d044b0e2d66b9cc0
71,256
from typing import List def csv_rows(s: str) -> List[List[str]]: """Returns a list of list of strings from comma-separated rows""" return [row.split(',') for row in s.split('\n')]
7a6ea8c0f69801cfb1c0369c238e050502813b63
71,257
import math def getRotationMatrix(a, b, c): """ Compute Rotation Matrix given RPY euler angles. """ # Roll R_x = np.array([[1, 0, 0], [0, math.cos(a), -math.sin(a)], [0, math.sin(a), math.cos(a)] ]) # pitch R_y = np.array([[math.cos(b),...
5b68425a0b3244579528fd601b52c43add5de03e
71,258
import re import os def generate_us_state_all(): """Combine all US State datasets into a single file""" # setup country dataframe df_info = get_config()["files"]["us_state_all"] target_df = pd.DataFrame() # setup dataframe df_names = [] df_dtypes = {} col_index = 0 for key, value i...
f01c9d0586321471c0c9961c965acfdda3f4a71e
71,259
def GetMatchURL(soup): """Gets the ongoing match URL""" live_match_url = soup.find("a", attrs={"class": "match-status-3"})["href"] return live_match_url
bae3658c46976c7d43234e063d78eeea027d3095
71,260
def get_flattened_axes(x): """ Ordered list of axis visible to MKLDNN """ return Axes.as_flattened_list(x)
aa4ec87d1a2bbe254eb88f9356f1a76aaaf71f43
71,261
def get_service(service_name): """ Gets the service VerificationService, checks if there is already one in the memory, if so return that one. :param service_name: e.g. phone, email """ # Check if service_name in USER_VERIFICATIOn if not settings.USER_VERIFICATION.get(service_name, None): ...
38eeece00518fd638df8246878a597cee825bd5e
71,262
def wait_to_fetch(ctx, interval): """Check if an unscored solution exists in a database by calling query every "interval" seconds. :param ctx: Click context :param interval: int: Interval to access a database (second) :return solution_id: ID of a solution that has not been scored. """ w...
372da8b7e4c19b6d2d0f728753a1584a3ccd40cb
71,263
def ctab2inchiKey(): """ Converts CTAB to InChi Keys. CTAB is either single molfile or SDF file. cURL examples: curl -X POST --data-binary @aspirin.mol ${BEAKER_ROOT_URL}ctab2inchiKey curl -X POST -F "file=@aspirin.mol" ${BEAKER_ROOT_URL}ctab2inchiKey """ data = list(request.files.values())[0].fil...
8cadc1683e4f644f673751e95f560a45822593a4
71,264
import os def which(program): """Locate an executable on the system path. """ def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in ...
0a44d4dbb2332cbb69d89c0040b2ea6b5118d800
71,265
def matmul(a: ndarray, b: ndarray) \ -> ndarray: """ Matrix product of two arrays. """ return ndarray(af.matmul(a._af_array, b._af_array))
afdf18f72fcaf915e32b829d696eb605887254d1
71,266
def flam2epp(lam, flam, ddisp): """ Convert flux density [erg/s/cm2/A] to photons per pixel [photons/s/cm2/pixel] Args: lam (array-like): wavelength array associated to the spectrum flam (array-like): spectrum in units of erg/s/cm2/A ddisp (float): ...
4018c7346bf842b93f25a72b4249269ad245f31b
71,267
def demo_delete(id, **kwargs): """ swagger_from_file: Swagger/demo/del.yml """ return quickly_del(Demo, id)
499045763cecd62e67334045b031929de61c5070
71,268
import logging def get_foot(tags, highway, level, country_iso3): """ Returns a tuple (foot TRUE|FALSE, safety 0->3) safety -1 - not allowed 0 - no sidewalk and/or level 4-6 1 - sidewalk and/or level 3 2 - designated but shared 3 - designated """ foot = False safety = 0 ...
fc960fbba178530e3380dfecfc9b6d2b0be6d62e
71,269
from numpy import sum def load_LSRK(file,lstype='2S',has_emb=False): """ Load low storage methods of the types 2S/2S*/3S*/2S_pair/3S_pair from a file containing the low-storage coefficient arrays. If has_emb=True, the method has an embedded method that requires an extra register. ...
c8bef2e6973f73720c10e757cd01e536d027c67c
71,270
import calendar def create_disjunctive_constraints(solver, flat_vars): """ Create constrains that forbids multiple events from taking place at the same time. Returns a list of `SequenceVar`s, one for each day. These are then used in the first phase of the solver. """ events_for_day = [[] for _...
f7f8592ac00c8cac9808bb80d425ff1c1cf10b9e
71,271
def interp_quad(x, y, d, rLCFS, r): """Function 'interp' used for kinetic profiles. """ f = interp1d(x, np.log(y), kind="quadratic", assume_sorted=True, copy=False) idx = np.searchsorted(r, rLCFS) core = np.exp(f(np.clip(r[:idx] / rLCFS, 0, x[-1]))) edge = core[..., [idx - 1]] * np.exp( ...
d877c4521cc29046ca827f7235e2401d808b8257
71,272
def generateWalkJumpSample(adjacency_list, p, jump_probability): """ Generate random walk sample from real graph """ sample_network = dict() nodes = set() edges = set() number_of_edges = sum([len(adjacency_list[u]) for u in adjacency_list.keys()]) / 2 desired_num_edges = int(p * number_o...
fa3c1ea0df20c97e2587c2f55e954a6680856d9b
71,273
def pick_cluster(session,picks,pickwindow,pickaveraging_norm,counter): """ Cluster picks from different components on the same station. """ # | | /\ # | | / \ /\ # | | /\ /\ / ...
00ad6ca61efbd7093c827b0d57271c41ece1bc22
71,274
def echo(): """ Method used to test how Python is handling PowerBuilder requests. Will decode data sent from PB and return it to the requester. :return: Decoded data sent from the requester. """ try: return request.data.decode("utf-8"), 200 except UnicodeDecodeError as why_ude: ...
9b077c0603baef42dac91f7dd47020af110f2866
71,275
from typing import List import re import traceback def cdt(text: str) -> List: """将中文的日期转化为标准时间日期符串 支持年, 季, 月, 周, 日,以及他们的合理组合, 返回的粒度都为`日` 支持日期合理的往前推算, 如`去年第一季度`, `前20天`等 支持两位数和三位数年份的自动补全. 如`18年`, '95年'等 Args: text (str): 输入文本 Returns: List: 转化过后的时间, `和`表示的长度为2, 正...
b4ea360f4a59dfeafa7138f2e9adb95a229d2322
71,276
import os import ntpath def get_file_info(file_path : str) -> dict: """it takes a file path and returns information about the file like: 'directory': the directory path where the file resides 'base_file_name': the file name without extentation example.zip -> example 'flag_name' : 'base_file_name' + .f...
e46992217ee3869fae117a530fd020d644d9b1c4
71,277
def minhash_xor_192(features_32, masks=PERMS_192_NP): """Numpy & Numba supported implementation""" hashes = np.full(192, np.uint32(MAX_UINT32)) for f in features_32: hashes = np.minimum(hashes, np.bitwise_xor(masks, f)) return hashes
67d1c913bb6cc8596b04c19fb28deccfd76ba198
71,278
def fit_nelson_siegel_yield(tau, y, theta_0=None): """For details, see here. Parameters ---------- tau : array, shape (n_,) y : array, shape (n_,) theta_0: array, shape (4,) Returns ------- theta : array, shape (4,) """ n_ = len(tau) def minimization_...
feeeeef81cab003d006bf3d64076cf119c6f6c6f
71,279
def magic_string(string: str, filename: str = None): """ Returns tuple of (num_of_matches, array_of_matches) arranged highest confidence match first If filename is provided it will be used in the computation. :param string: string representation to check :param filename: original filename :retu...
8ce083418921a9a3da675a8ddbb144df29e096d2
71,280
import torch def correct_resize_label(tensor, size): """ Resize torch.Tensor label Parameters ---------- tensor : torch.Tensor size : Tuple[int] Returns ------- resized_tensor : torch.Tensor """ device = tensor.device tensor = tensor.detach().cpu() resized = [] ...
e2c6601e6c17fa894c0b6f83f61087d9f75e32b6
71,281
def read_data1(filename): """ This function reads the data from .txt file. :param filename: reading directory :return: lists of word_ids, words, emphasis probabilities, POS tags """ lines = read_lines(filename) + [''] word_id_lst, word_id_lsts = [], [] post_lst, post_lsts = [], [] se...
c31de2ff853c799078468d675d7a7adf4bb2fa12
71,282
def workflow_add_tags(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /workflow-xxxx/addTags API method. For more info, see: https://documentation.dnanexus.com/developer/api/introduction-to-data-object-metadata/tags#api-method-class-xxxx-addtags """ return DXHTTPRequest('/...
440d39e622f1dc6336118ce9704a187842e2ca06
71,283
def login(var=random.randint(0, 1000), error=None): """ The function can get a POST or GET requests. if the request is GET: returns the html login_page template if the request is POST: checks the data(email and password) in the users database. """ global clients_connecting if request.method ...
1e397ec4dc571f2c21893b70993c7b5a296293cb
71,284
def get_body(request): """ Return the body of a concrete publication. """ context = request['context'] entities = request['entities'] feed = context['feed'] ordinal = entities['ordinal'][0]['value'] body = feed[ordinal]['summary_detail']['value'] context['body'] = body return con...
53080b1727f0230a30b9fc4435d455a06e927be3
71,285
def get_default_snapshot_id(project): """ Generate a snapshot id from data on the given project. :param project: project object :return: snapshot id """ def snapshot_id_from_branch_name(name): return "{}:HEAD".format(name.replace('/', ':')) default_branch = project.git.get_default_branc...
2c542678036541372fa675e61b4f5a969cd5ab0f
71,286
import random def filter_shuffle(seq): """ Basic shuffle filter :param seq: list to be shuffled :return: shuffled list """ try: result = list(seq) random.shuffle(result) return result except: return seq
3f2dce2133ba32d8c24d038afaecfa14d37cbd4e
71,287
def read_vcf_file(vcf_file_address): """ Reading the vcf file input: vcf file outputs: lines_list: list of string. each string is a line of phased vcf file. var_pos_het_list: genomic position of phased hetrozygous variants in the vcf file. line_number_het_list: list...
f4e9718d8fc21f5c1dc37aa570f6bf1615b82452
71,288
def ipd_download_new_or_modified(organizer: Organizer, info: IpdDownloadInfo) -> bool: """ Accepts new files or files with a more recent modification date. """ resolved_file = organizer.resolve(info.path) if not resolved_file.exists(): return True if not info.modification_date: P...
36cbf48347b6bc4e7557cb06f316dbd912ae6e44
71,289
def sushi_report_all(request): """Report from SUSHI, shared common data.""" return parse_sushi_file(request.param)
9ae44e8ea80c74d1580662e9ce1bbd530214356a
71,290
def get_package_list_from_file(path): """ Create a list of packages to install from a provided .txt file Parameters __________ path: Filepath to the text file (.txt) containing the list of packages to install. Returns ______ List of filepaths to packages to install. Notes ...
91ef3e634e98afd116d2be9c803620f672acd950
71,291
def property_view(request, slug, property_id): """ """ return render(request, 'property/property.html', {'slug': slug, 'id': property_id})
05b28046274cfb1f09bfbe9c352888202b4fb485
71,292
def read_comment_line(line, verbose=0): """ Use pyleri to parse an extxyz comment line """ result = grammar.parse(line) parsed_part = result.tree.children[0].string if not result.is_valid: raise SyntaxError(f"Failed to parse entire input line, only '{parsed_part}'. " ...
dfdbea582dcfa14f5e3aefec89eb3959cde67685
71,293
def escaped_commands(line): """Transform escaped commands - %magic, !system, ?help + various autocalls. """ if not line or line.isspace(): return line lineinf = LineInfo(line) if lineinf.esc not in tr: return line return tr[lineinf.esc](lineinf)
84dea2fba22c7a7da6d75e8257b597c68aab67ef
71,294
def has_postgres() -> bool: """ Whether to use postgres """ return find_spec("asyncpg") is not None
0d6348f52fb01114bc57cc539d3874815da16ec8
71,295
def passthru(func): """Return value of function by same name in proxied object. Proxied object is located as an attribute named `_wrapped` in proxy object. """ @wraps(func) def _wrapper(self, *args, **kwargs): name = func.__name__ return getattr(self._wrapped, func.__name__)(*args,...
bc33e482b9b0c46f4e48f9dbe1367e60d47f5d04
71,296
def _sources_from_virtual_sink_port(sink_port, _traversed=None): """ Resolve the source port that is connected to the given virtual sink port. Use the get source from virtual source to recursively resolve subsequent ports. """ source_ports_per_virtual_connection = ( # there can be multiple p...
3a378632702afe62166f5ee75b43ba930b712a75
71,297
def parse_jcamp_line(line,f): """ Parse a single JCAMP-DX line Extract the Bruker parameter name and value from a line from a JCAMP-DX file. This may entail reading additional lines from the fileobj f if the parameter value extends over multiple lines. """ # extract key= text f...
84061c3f4bc42a62e308d5f93877e5c55d85efc1
71,298
def get_grounded_agent(gene_name): """Return a grounded Agent based on an HGNC symbol.""" db_refs = {'TEXT': gene_name} if gene_name in hgnc_map: gene_name = hgnc_map[gene_name] hgnc_id = hgnc_client.get_hgnc_id(gene_name) if not hgnc_id: hgnc_id = hgnc_client.get_current_hgnc_id(gen...
e4501fefe4d1617bd9d32679fd966b101708297d
71,299