content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def temp(input_temp): """ Formats input temperature with "+" or "-" sign :param input_temp: :return: formated temperature """ decimal = 0 temp2 = float(input_temp) if temp2 < 0: temp_sign = '' elif temp2 > 0: temp_sign = '+' else: temp_sign = '' de...
9ce3be3ec362761c2a6aa43e4ae4191c7a471667
3,605,200
from os.path import basename def env_is_created(env_name): """ Assert an environment is created Args: env_name: the environment name Returns: True if created False otherwise """ for prefix in list_all_known_prefixes(): name = (ROOT_ENV_NAME if prefix == contex...
4b808e7f987da0f8bbded74533695b06dfdf266d
3,605,201
import time def listarNoticias(api_obj: object, portais: tuple or list, qntd: int) -> list: """ Chama a função raspar_noticias() para cada conta em portais Args: api_obj: Objeto criado pelo tweepy, necessário para realizar ações na API do twitter. portais: Lista contendo t...
b6edf7fae2d88de0c5cdf2314c7694421b64b536
3,605,202
from typing import Union def INCREASING(x: Union[float, np.ndarray]) -> Union[float, np.ndarray]: """ Linearly increasing function over interval [0, 1]. """ return 2 * x
99a960ce687d031ef60f3e76f528dd089ca50284
3,605,203
def deposit_preview(submission_id: int) -> Response: """Deposit a preview PDF for a submission.""" stream = request.stream data, code, head = controllers.deposit_preview(submission_id, get_body()) response: Response = make_response(jsonify(data), code, head) return response
634539d9e536c8a0c5f08fadad843a61e988e9c1
3,605,204
def parse_reads(reads, chromosome_name, fasta_handler): """ Given a set of pysam read objects, generate data for matches/mismatches/inserts/deletes and contig size/position for each read :param reads: pysam aligned segment objects :param chromosome_name: :param fasta_handler: fasta_handler objec...
e70a10ff4e03e13e5938bff2129100b790632a3e
3,605,205
from datetime import datetime def get_utc(): """Basic function to get Datetime in Zulu""" return "%sZ" % (datetime.datetime.utcnow().isoformat("T"))
600e00f5719ec6b2ac1c131bc1b5c2db8ff2bf0f
3,605,206
def send_ui(path = 'index.html'): """Send static content (HTML/CSS/JS/images/...).""" log_request(request) return flask.send_from_directory('html', path)
8a462e49250de143bd2a6e195f3ca7d1f13dc0ac
3,605,207
def extract_html(response): """Extracts an html page from the response. """ return htmlpage_from_response(response).body
eef1d5cce0e461d0b4f1f4de4e7bfc70459ddb81
3,605,208
import os def remove(name: str) -> bool: """ Remove corpus :param string name: corpus name :return: True or False """ db = TinyDB(corpus_db_path()) temp = Query() data = db.search(temp.name == name) if len(data) > 0: path = get_corpus_path(name) os.remove(path) ...
9b4810282d6d1a8827d0e991a9d14b06808c4b59
3,605,209
from tayph.vartests import typetest import time def end(start,id='',silent=False): """ Short-hand for ending a timing measurement and printing the elapsed time. Parameters ---------- start : float Generated by time.time() id : str Description or numeral to identify the clock ...
b692086cc85ce303adb8aa55bed2919607ef534b
3,605,210
def epsilon_greedy_sample(nested_dist, eps=0.1): """Generate greedy sample that maximizes the probability. Args: nested_dist (nested Distribution): distribution to sample from eps (float): a floating value in [0,1], representing the chance of action sampling instead of taking argmax....
913f7bea99e866c2b697f64951317857fa9dfe9e
3,605,211
import logging def parse(line, app_name, source, dyno): """ return: exit: boolean. If true, we can stop this parser thread """ # Validate if the line matches the source and dyno if source not in line or dyno not in line: return False root = app_name + settings.SEPERATOR + source + se...
62a9e663ef41f4e257a89c880893bdfb3250556a
3,605,212
def find_pattern(pattern, text): """ Find all the occurrences of the pattern in the text and return a list of all positions in the text where the pattern starts in the text. """ S = "".join([pattern, "$", text]) s = prefixFunction(S) result = [] for i in range(len(pattern)+1, len(S))...
6cb65af8bb1bb49d3db4ab214648982b27311a01
3,605,213
def exclude(*arg): """ excludes all HOSTLIST args from first HOSTLIST :param: nodelist: The hostlist string. :param: node: The node to be excluded. :return: The resulting hostlist string without the nodes specified. """ nodelist = arg[0] len_nodes = arg[1:] for node in len_nodes: ...
2fa61fad0f9743c70e6c42a39b7a81f7c60da34e
3,605,214
def generateOldLibraryEntry(data): """ Return a list of values used to save entries to the old-style RMG thermo database based on the thermodynamics object `data`. """ if isinstance(data, ThermoData): return '{0:9g} {1:9g} {2:9g} {3:9g} {4:9g} {5:9g} {6:9g} {7:9g} {8:9g} {9:9g} {10:9g} {11:9...
b6c8d3c4e3c5d3c2d2466ef9b95baf2285b093f5
3,605,215
def get_cell_values(queries, subjects, key=len, attr=None): """Generates the values of cells in the binary matrix. This function calls some specified key function (def. max) against all values of a specified attribute (def. None) from Hits inside Subjects which match each query. By default, this functi...
4725a4c9f9dc291ff0e8595bb25f51c4612f747d
3,605,216
def form_CheckboxRequired(request): """ Simple Boolean Checkbox with a required validator. Add an empty value if you want to force the user to add a tick """ schema = schemaish.Structure() schema.add('checkbox', schemaish.Boolean(validator=validatish.Required())) form = formish.Form(schema, 'fo...
f5a885826846e9effa4643777a094e73df45d746
3,605,217
def PointCloudObject(name,**kw): """ This function create a polygon representing the atom as point (vertex of the polygon). @type name: string @param name: name of the pointCloud @type kw: dictionary @param kw: dictionary of arg options, ie : 'vertices' array of coordinates ; ...
afdf1b716d6b57ae0a18c4b3cee81f9d0d47ab0c
3,605,218
import curses def scrolled_menu(window, datas: list, tag: str): """menu cursesを使って引数のリストを表示してユーザーに選択を促す。 Args: window: リストを表示/操作するcurses.Windowクラス datas: 列挙する内容1つづつをdictとして保持したリスト tag: datasのデータ1つの中で、表示する内容のkey Returns: int: ユーザーがリストの何番目を選択したのか値 """ window.era...
f7ce97dbafdf7736a42a0da1e640788662be27d9
3,605,219
from typing import Union import pathlib import scipy def read_matlab(input_file: Union[str, pathlib.Path]) -> dict: """ Read data from MATLAB file while performing some checks. **Parameters** - `input_file`: str or pathlib Path to the input file. **Returns** - `res`: dict ...
834fb52c4c8c6e93bd8f12d6b59e2dcba0ac525e
3,605,220
import io def load_poi_points(path: str) -> PoiPoints: """Load :py:obj:`PoiPoints` from a file. Args: path (str): The path to the file. Returns: :py:obj:`PoiPoints`: The data loaded. """ data = io._load(path) return PoiPoints(data)
a1ddae115582d8a9ddad62edb612e4ce2b9f707e
3,605,221
import requests def get_yield(): """A function that retrieves current Treasury Bond rates from the US Treasury website. :return: Dictionary containing all the T-Bond terms as keys (strings) and their rates as values (floats). """ # Formatting of XML to Python Dict curve = requests.get(GOV_YIELD_U...
a1eea5d1e022398cb099575b4b9f179b5c40b72c
3,605,222
def ParseDate(date, messages, fmt='%Y-%m-%d'): """Convert to Date Type.""" datetime_obj = times.ParseDateTime(date, fmt=fmt) return messages.GoogleTypeDate( year=datetime_obj.year, month=datetime_obj.month, day=datetime_obj.day)
941b707b6c9fd1e3cc4f114d0d1c4bb6db638840
3,605,223
import argparse def init(): """ script initialize. get arguments :return: """ parser = argparse.ArgumentParser(description='This script is parsing wsgi_lineprof result') parser.add_argument( "-V", "--version", action="version", version="wlreporter Version:{}".fo...
0b147cd0c26a05be6e261db22fa4631674c0509b
3,605,224
def and_(fst, snd): """Wraps the logical and function.""" return fst and snd
c03f2cb9178aa2863e2da58e4fe2741f4a98ea79
3,605,225
def AttenLogitsRPE(query, key, abs_pos_emb): """Attention logits from ... https://arxiv.org/pdf/1803.02155.pdf with trainable rel position emb. Notice padding is supposed to be masked by the caller of this function. B: batch size T: sequence length N: num of attention heads. H: per-head attention dimen...
404b6288fc4df90edcfc45aacababb23671a4427
3,605,226
def config_factory(base_config, attr_list): """ Create new config files from attribute dictionary. """ configs = [] for attr in attr_list: # create deep copy of nested dict config_cp = deepcopy(base_config) # change value and append change_nested_dict(config_cp, attr[0]...
2a3852d7147fee49e408bdfa475468936609a5c3
3,605,227
def triplet_counts_to_dataframe(counts): """Convert a dictionary of counts, as returned by colorful_triplet_count, into a dataframe""" colors, motif, index, count = [], [], [], [] for k in counts.keys(): k_counts = counts[k] colors += [k] * len(k_counts) count += list(k_counts) ...
daa97d5ef9e89ba7216a27024bcf2761f80780a9
3,605,228
def _partition(sequence, size, count): """Partition sequence into count subsequences of size length, and a remainder. Return (partitions, remainder), where partitions is a sequence of count subsequences of cardinality count, and apply(append, partitions) + remainder == sequence.""" par...
e33e7eaa35e3c57f0decda50e863686f529d5afa
3,605,229
def get_style_sheet( bg: str = "", bg_lighter: str = "", text: str = "", text_button: str = "" ) -> str: """ Returns a string representing the style sheet. Usage: get_style_sheet(True) for dark mode or get_style_sheet(False) for light mode """ return f"""QWidget {{ background: {bg}...
1f760e240de493a34e4148f69ad64dc307b6dc99
3,605,230
import re def parse_docket_number(docket_number): """ Parse a Common Pleas docket number into its components. A docket number has the form "CP-46-CR-1234567-2019" This method takes a docket number as a string and returns a dictionary with the different parts as keys """ patt = re.compile( ...
8f9af7709f881cc82bb7d22b420a5361e085de70
3,605,231
import random import functools def get_symbolic_alchemy_level( level_name, observe_used=True, end_trial_action=False, num_trials=10, num_stones_per_trial=3, num_potions_per_trial=12, seed=None, reward_weights=None, max_steps_per_trial=DEFAULT_MAX_STEPS_PER_TRIAL, see_chemistries=None, generate_events=...
7fe520d63b512d3779da4db49e090a988cf848e5
3,605,232
def make_div(unit: str, length: int = 24, start: str = '', end: str = '', literal_unit=False) -> str: """ Generates and returns a custom divider :param unit: str containing a repeating unit :param length: The maximum length that will not be exceeded (default: 24) :param start: optional starting str...
d628123e807231cab2b1a96e907aa9bd97537974
3,605,233
def thread(n_workers): """ Decorator to execute a function in multiple threads. Example: .. doctest:: >>> import lox >>> >>> @lox.thread(4) # Will operate with a maximum of 4 threads ... def foo(x,y): ... return x*y >>> foo(3,4) 12 >>> f...
e45a32a3191ea91f809b6ecfdd9bb6efe321eb2f
3,605,234
from queue import PriorityQueue from collections import defaultdict from typing import List def _assign( datapoints: List, annotators: List, max_per_annotator: int, max_per_dp: int, blacklist_fn=None, ): """ Args: datapoints: A list of data points to assign to each annotator. ...
4eeefc5cc9bf70e35b396ab718228faac00e64c0
3,605,235
def correct_image_illumination(im, illum, stretch_quantile=0, mask=None): """Divide input image pointwise by the illumination field. Parameters ---------- im : np.ndarray of float The input image. illum : np.ndarray of float, same shape as `im` The illumination field. stretch_qu...
40c5b165d6e63a4fa5ae872bb39b2ef1476de1d1
3,605,236
def suffixes(word): """Returns the list of propper suffixes of a word :param word: the word :type word: str :rtype: list .. versionadded: 0.9.8""" return [word[i:] for i in range(1, len(word))]
551ea4d612a6c9f0ffe432701e3bde2c80899d85
3,605,237
import re def ValidateAndParsePemChain(pem_chain): """Validates and parses a pem_chain string into a list of certs. Args: pem_chain: The string represting the pem_chain. Returns: A list of the certificates that make up the chain, in the same order as the input. Raises: exceptions.InvalidArg...
1a81be58a804280f080f890be49dfc59c3725cfe
3,605,238
def tensormol_acsf(xyzs, Zs, elements, element_pairs, radial_cutoff, angular_cutoff, radial_rs, angular_rs, theta_s, zeta, eta): """ This function uses the tensormol atom centred symmetry functions. :param xyzs: tensor of shape (n_samples, n_atoms, 3) :param Zs: tensor of sha...
89a32d49264b7e5fbfb151fc9c9a3cb83dd1679c
3,605,239
def delete_task(id): """Delete a task by its ID""" TaskPersistence.delete(id) return {'success': True, 'message': 'Task has been deleted'}
65788e2d822ef9d150cbcae870d1c147205ca509
3,605,240
def get_morphological_patch(dimension, shape): """ :param dimension: dimension of the image (NOT the shape). :param shape: circle or square. :return: morphological patch as ndimage """ if shape == 'circle': morpho_patch = ndimage.generate_binary_structure(dimension, 1) elif shape == ...
50d6c2c366190a4b3d3a808053080bcb72a7a6a7
3,605,241
def get_preflight_headers(*allowed_methods, **options): """ gets all headers to set in response for cors preflight requests. it returns None if cors is not enabled or request's origin is not valid. :param str allowed_methods: all allowed http methods. :keyword bool enabled: specifies that cors he...
576dad68d523e159d665219a072a222e387ef8fd
3,605,242
def build_url(param_dict): """ Builds the URL needed to query [University of Wyoming, College of Engineering, Department of Atmospheric Science's website](http://weather.uwyo.edu/upperair/sounding.html) to get the proper sounding data. Parameters ---------- param_dict : dict A dictionar...
77825ae917650d1b832333920b6363d4dac7c36b
3,605,243
def get_signer(salt="newsletter_subscription"): """ Returns the signer instance used to sign and unsign the registration link tokens """ return signing.Signer(salt=salt)
a8f16ceeb48a57b75c171881555dc85497c9f0ee
3,605,244
def _fast_rcnn_box_loss(box_outputs, box_targets, class_targets, normalizer=1.0, delta=1.): """Computes box regression loss.""" # delta is typically around the mean value of regression target. # for instances, the regression targets of 512x512 input with 6 anchors on # P2-P6 pyramid is about [0.1, 0.1, ...
97cb886e0aa248798c6fa45cda95f1b096cb690a
3,605,245
def do_mprofile(func): """Wrapper that logs memory before and after a wrapped function call.""" @wraps(func) def decorated_func(*args, **kwargs): name = func.__name__ if hasattr( func, '__name__') else func.__class__.__name__ mem_info_before = memory_info() memory_logger...
506aa8cfab7f203a1bd6dc4e937d8cbd24de739a
3,605,246
import os import yaml import logging import re def parse_config( filepath: str, force_log_debug: bool = False, ) -> Configuration: """Parse a config file Return a tuple of an AppConfig object and a Logger """ filepath = os.path.abspath(filepath) if not os.path.isfile(filepath): ra...
c694b907d57edb61168b6fcaaff1571d9a947a96
3,605,247
def smooth(values, factor): """smooth non zero values (by factor) towards 0th element.""" new_values = [0] * len(values) for i in reversed(range(len(values))): if values[i] != 0: smoothed_value = values[i] j = 0 while True: if i-j < 0: break new_values[i-j] += smoothed_value ...
055c4bbe5bd1e696c69ad1ff14beb72b4abbdd11
3,605,248
from typing import Optional from typing import List def get_metrics(ticker: str) -> Optional[List[_Metric]]: """Get core metrics for ticker""" data = sentipy.parsed(ticker) return _contextualise_metrics(data, ticker, core_metrics)
64398664dc04cb4c140ba6744af43efb50d4d110
3,605,249
def apis_index_doc_view(request): """ Show a list of available APIs """ # Create a voter_device_id and voter in the database if one doesn't exist yet results = voter_setup(request) voter_api_device_id = results['voter_api_device_id'] store_new_voter_api_device_id_in_cookie = results['store_n...
85d30e2dcf3efc0cd7392031879dd721b58b98f3
3,605,250
from typing import cast def ss_projects(subject: State, query: Query) -> State: """Split a list-like mob by release format (album/single)""" if not query: query = subject.mob api = subject.api query_mob = ss_open(subject, query).mob print(' NOTE: "projects" may take a while') tracks...
4b83bb578311c40bf122bc41343b830d7825402a
3,605,251
def in_month(ref_date): """ which month contains a reference date :param ref_date: mx.DateTime reference date :rtype: range_string e.g. 2007-M12 """ return "%4d-M%02d" % (ref_date.year, ref_date.mon)
fe8126529521565e35f2012e359d7a9c57b773d1
3,605,252
def _precipitable_water(ea, pair): """Precipitable water in the atmosphere (Eq. D.3) Parameters ---------- ea : ee.Image Vapor pressure [kPa]. pair : ee.Image or ee.Number Air pressure [kPa]. Returns ------- ee.Image or ee.Number Precipitable water [mm]. N...
a56b3948167fb22bb49b6f84bd3980a2666dd345
3,605,253
from rest_framework.generics import GenericAPIView def api_view_with_serializer(http_method_names=None, input_serializer=None, serializer=None, validation=True): """ Décorateur permettant de créer une APIView à partir d'une fonction suivant la structure d'un serializer Elle remplace le décorateur @api_vie...
7d26a68922643ebf1f07ddb07da329a3e23d52eb
3,605,254
def euler3122PRV(e): """ euler3122PRV(E) Q = euler3122PRV(E) translates the (3-1-2) euler angle vector E into the principal rotation vector Q. """ return EP2PRV(euler3122EP(e))
4b8b64cc73683512e9f4f0fe3194e0af28bc80b3
3,605,255
import numpy def smooth(data,N=10,step=1): """ Smooth sequence data using a moving window of width N. Returns a list of tuples, <i, mu, stderr>, where i is the index of the last element of in the moving window, mu is the average of the window, and stderr is the standard error of the values in the...
3afbf9652d729de945b983dea756188cc410dbb1
3,605,256
import unittest import sys def _MonkeyPatchTestResultForUnexpectedPasses(): """Workaround for <http://bugs.python.org/issue20165>.""" # pylint: disable=g-doc-return-or-yield,g-doc-args,g-wrong-blank-lines def wasSuccessful(self): """Tells whether or not this result was a success. Any unexpected pass ...
0ebef5be0a3afe4d117431d1685c0f6af4f40472
3,605,257
def get_files_to_check(): """ :return: files to be checked string """ files = current_app.config.get('PYLINT_SETTINGS').get('include') if not files: abort(400, 'MISSING PYLINT_SETTINGS.include value') try: return ' '.join(files) except TypeError: abort(400, 'PYLINT_SE...
6b0d502cc38752ad588e7d08ef0479f894c2ab1f
3,605,258
from datetime import datetime import requests import json def env_sensor(sample): """Query environmental sensor data""" global env_sensor_response global env_sensor_query_interval global env_sensor_last_request if env_sensor_response == '' or datetime.now() - env_sensor_last_request > env_sensor_...
f925f5c2c1b2844356e85bba7eb8e4332559097b
3,605,259
import logging import tqdm def parse_dbcan_output(overview_path, hotpep_file, fasta_file): """Parse the data in the 'overview.txt' files from dbCAN. The 'overview.txt' file contains the CAZyme predicion data from HMMER, Hotpep and DIAMOND. A dbCAN consensus result is retrieved by finding predictions that...
6113912c0810e6abf647bee1ffa21a0e30f91845
3,605,260
def get_supported_server_info(mail_address, protocol): """Use user address to get server address and port.""" provider = mail_address.split('@')[1] if provider in supported_server: server_info = supported_server[provider] if protocol in server_info: return server_info[protocol] ...
aa67535c5232ca980a8b386afa6244496f57d752
3,605,261
def str2tuple(string: str): """Construct the tuple data from string for SecondQuantizedOp.""" return (string, 1)
f9b8fe56bf54d27c9aee6c7a3ec3ab797b08fcd0
3,605,262
def interpolation(points, queries, feat, points_row_splits, queries_row_splits, k=3): """Interpolation of features with nearest neighbours. Args: points: Input pointcloud (m, 3). queries: Queries for Knn (...
bde1dc11369fc1111d846ec6aa32fc0b8a9fb9e1
3,605,263
def running_covariance_init(shape: 'IntTensor', dtype: 'DTypeNest') -> 'RunningCovarianceState': """Initializes the `RunningCovarianceState`. Args: shape: Shape of the computed mean. dtype: DType of the computed statistics. Returns: state: `RunningCovarianceState`. """ ...
fc3858a41e1dcd39c2bef27fc37e0a96b36e1e6a
3,605,264
def integrate_up_to_thr(state, ders, thr, dt=0.005): """integrates state with derivative for up to x = thr :param state: state of the variables :param ders: derivative functions :param thr: threshold :param dt: time step (default 0.005) :return: state at threshold crossing""" xh = state[0] while((state[0] > t...
3559b2168bfbb2a3818dbe87837a463822b80a09
3,605,265
def engin(parameters_ex,parameters_in,k,name_file,test1=False): """ run the fitting :param parameters_ex: :param parameters_in: :param k: :param name_file: :return: """ parameters_ex['b']=6 data = np.load(name_file, encoding = 'latin1',allow_pickle=True) shift_time = 0 ma...
f0565ddd5df9bb827b48dcbf8ca050a831b8a026
3,605,266
def _encode(values, *, uniques, check_unknown=True): """Helper function to encode values into [0, n_uniques - 1]. Uses pure python method for object dtype, and numpy method for all other dtypes. The numpy method has the limitation that the `uniques` need to be sorted. Importantly, this is not check...
1bba77ef713b9a07e543165cb1e9179c560ff225
3,605,267
def adjust_mye_age(mye): """ Makes mid-year estimate/snpp data conform with census age categories: - subtract 100 from age (so that "1" means under 1) - aggregate 86,87,88,89,90,91 into 86 (meaning 85+) """ # keep track of some totals pop = mye.OBS_VALUE.sum() pop_m = mye[mye.GENDER == 1].OBS_VA...
a500ee483fb94950d95e4874ce3a183db332ccf5
3,605,268
from typing import List def check_validation_config( default_params: List, local_params: List ) -> ValidationConfig: """ Compare the passed parameter values of a validation function to its default parameter values. """ custom = False for kw in default_params: if not (default_params...
eda66672b7d1d06d53e586e310f3ee24241af16a
3,605,269
def binning(features, n_bins, strategy, encode, feature_names): """ Returns binned features and the corresponding labels for each bin 'n_bins' can either be an integer or a list/numpy array of n integers (different number of bins for n features) 'strategy' and 'encode' are inputs for Scikit-learns KBins...
295ccfb20d53002b15360593ef6ff9653db30d78
3,605,270
def to_grid(videos, size): """ Convert videos to a size x size grid video :param np.ndarray video: video (dim=5, axis=(video_len, batchsize, channel, height, width)) :param int size: size of one side of the grid """ t, bs, c, h, w = videos.shape # make (size x size) grid if bs < s...
c8ea4146d56283c17d19f988bb5ea77f426407d9
3,605,271
from typing import List from typing import Tuple import re def dexpand_string(string: str, to_replace: List[Tuple[str, str]]) -> str: """ inverse operation of expand_string :param string: output of expand_string :param to_replace: the same variable passed to expand_string :return: """ # ...
6b753bf8c8526092f89185bf136f554968d3f312
3,605,272
def make_gradient_function(mixture_obj, gradient_type, unpacker, setter): """ chooses gradient among different approximations """ if gradient_type == "standard": mixture_obj_grad = grad(mixture_obj) elif gradient_type == "score_mean": print "Scoring the mean with the current variance!!!" ...
96650218f87ba12d069060796543d7a57c5a846f
3,605,273
def _reassemble(obs_settings, num_bricks, randomize_initial_order, randomize_desired_order): """Configure and instantiate a `Reassemble` task. Args: obs_settings: `observations.ObservationSettings` instance. num_bricks: The total number of bricks; must be between 2 and 6. randomize_init...
a007ce91f4816406bd8f1a8ee308db2506cf73d1
3,605,274
from typing import OrderedDict import sys def read_weights(weight_file,chrom,pos,ref,alt,coord,ea,weight,vcf_chrom): """ Read file with weights into dictionary and regions files for tabix. """ weight_dict=OrderedDict() command=open_zip(weight_file) counter=0 with command as f: for ...
cb0017dc0ddbb271d48fb1d8a9f4c07f3b5b7924
3,605,275
import argparse def set_args(): """设置训练模型所需参数""" parser = argparse.ArgumentParser() parser.add_argument('--device', default='0', type=str, help='设置训练或测试时使用的显卡') parser.add_argument('--config_path', default='./config/config.json', type=str, help='模型参数配置信息') parser.add_argument('--vocab_path', defau...
cea63034d513b8717236d68c1270147d6ed1cdff
3,605,276
def get_list_types(list_type=['organisation_type_id']): """Method to get all organisation types for js.""" try: org_units = SetupList.objects.filter(is_void=False) vals = [] orgs = {} orgs_dict = {} cnt = 0 for org_unit in org_units: field_name = org_u...
8b371bae35cd8f11d8e6b44d60ebaadc03a7475e
3,605,277
def YScaleFun(center): """ function that returns a scaling vector to scale y data to same range as x data """ # center gets ignored in this case return N.array((5e7, 1), N.float)
3314618c40db6b7954b246234aece384654a8539
3,605,278
def mesh_muvw_fz(quad_int, cryst_ptgrp, sig_type, *args): """ For given integer quadruples, the set belonging to the corresponding fundamental zone are separated out and retruned. Parameters ---------------- quad_int: numpy.array Integer quadruples cryst_ptgrp: str Proper po...
f59ed76aabe94330ca8c3662a37c34cd66d7549a
3,605,279
def atcab_aes_cmac_finish(ctx, cmac, size): """ Finish a CMAC operation returning the CMAC value. Args: ctx AES-128 CMAC context. cmac CMAC is returned here. cmac_size Size of CMAC requested in bytes (max 16 bytes). Returns: Stat...
cbc77488bc204e5b6c9b0cf35d35ae376edf4f74
3,605,280
def neg2pos(index, shape): """Make a negative index (that counts from then end) positive .. warning:: this function should be called only once -- always on user inputs -- otherwise we risk transforming back stuff that should be kept negative. Ex: neg2pos(-5, 3) = -2 ...
f863230e20af21cd6c69e8ac8d91757e692b6803
3,605,281
from typing import List from typing import Tuple from typing import Type def compare_detect_inference_frame( df: pd.DataFrame, typeset: VisionsTypeset ) -> List[Tuple[str, Type[VisionsBaseType], Type[VisionsBaseType]]]: """Compare the types given by inference on the base graph and the relational graph Ar...
d43c1e1747ec4be8136e87ebaf9edf9e2346b2e3
3,605,282
def setup_experiment(lbann): """Construct LBANN experiment. Args: lbann (module): Module for LBANN Python frontend """ # Setup the training algorithm SGD = lbann.BatchedIterativeOptimizer TSE = lbann.TruncationSelectionExchange metalearning = TSE( metric_strategies={'rando...
8a5581395f9851e6de6fa4a0477ef20214d5d3ea
3,605,283
def pointwiseFold(f,x,n,listOfLists): """This function is a generalization of the fold function to take more than one list. Keyword arguments: f -- the binary function used to accumulate some value x -- the initial value for all the values n -- the common length of the lists ...
e6c8cd5565b5554631aa55c5b42c9c50a11256e7
3,605,284
import calendar def update_pie(year, ser): """ Update the pie plot using dailyStats, as function of selected year in year-slider In case of None use Current year as default year """ year = year if year is not None else dyear dailyStats = pd.read_json(ser) min_month = dailyStats.index.m...
dcdd28754c6b77cbad266a578c4e71b92ba08bc7
3,605,285
import os def test_mindir_export_split(): """ Feature: MindIR Export model is exceed TOTAL_SAVE(1G but mocked as 0) Description: MindIR Export model is exceed TOTAL_SAVE should be split save as model file and data file Expectation: No exception. """ ms.train.serialization.TOTAL_SAVE = 0 c...
fcf29b35057d41efe4e924ab762ac6e3bbde97ec
3,605,286
import numpy def _n_gaussians(x, N, *params): """Sum of N Gaussian functions plus an offset from zero Parameters ---------- x : float values to calculate Gaussians function at N : int number of Gaussians params : floats 3*N + 1 parameters corresp...
afa3683316f60463a8320457754680e3da52714c
3,605,287
def posts_update(post_id): """Handle form submission for updating an existing post""" post = Post.query.get_or_404(post_id) post.title = request.form['title'] post.content = request.form['content'] db.session.add(post) db.session.commit() flash(f"Post '{post.title}' edited.") return r...
ef14c4712f1a1810bea4503358f0f93623cf0b14
3,605,288
def get_azimuth_value(label): """ Returns the angle in degrees represented by a azimuth label int. Parameters ---------- label: int Azimuth label. """ _check_is_integral('azimuth', label) if label == -1: return None else: if (label % 2) != 0 or label < 0 or la...
d33ff558b23b3dc0cc9ce411686403e4519ac59c
3,605,289
def _unpack_topk(topk, lp, hists, xok=None, sub_stts=None, attn=None): """unpack the decoder output""" beam, _ = topk.size() topks = [t for t in topk] lps = [l for l in lp] k_hists = [(hists[0][:, i, :], hists[1][:, i, :], hists[2][i, :]) for i in range(beam)] if xok is not None: ...
db9d93ef8b40390733034ce10ef7228bc4d23fbf
3,605,290
def pack_bits( longbits ): """Crunch a 64-bit int (8 bool bytes) into a bitfield.""" byte = longbits & (0x0101010101010101) byte = (byte | (byte>>7)) & (0x0003000300030003) byte = (byte | (byte>>14)) & (0x0000000f0000000f) byte = (byte | (byte>>28)) & (0x00000000000000ff) return byte
78fdf9828b4f98c9bc44233ef5f95244eefb24fc
3,605,291
from pathlib import Path def fullpath(path=""): """ Path: Expand relative paths and tildes. """ return Path.cwd() / Path(path).expanduser()
e7b7d1caa67a2a9988035713ec18347b5581406e
3,605,292
def get_engine_latest_version(request): """ Return a string with if new versions have been released. Return 'None' if the version is not available """ return HttpResponse(engine.check_obsolete_version())
4d4e1d864ec8e9a46867820959a98dbdcdb19a1a
3,605,293
import os from datetime import datetime def get_video_end_time(video_file): """Get video end time in seconds""" if not os.path.isfile(video_file): print(f"Error, video file {video_file} does not exist") return None try: time_string = FFProbe(video_file).video[0].creation_time ...
ad071a70a873df63d3fe4f983226ea5bda995fdd
3,605,294
def scaffold_split(data, test_size, balanced = True, random_state = 0): """ Splits a :class:`~chemprop.data.MoleculeDataset` by scaffold so that no molecules sharing a scaffold are in different splits. :param data :param test_size: the proportions...
26ec190d4ac251883be014fb4b7d71cbf071a5a3
3,605,295
import io def read_file(path): """Returns all the lines of a file at path as a List""" file_lines = [] with io.open(path, mode="rt", encoding="utf-8") as the_file: file_lines = the_file.readlines() return file_lines
8e220e0b90ded168a1d1d8d37b7451b7796b1ed5
3,605,296
def scale_by_std(df, demean=False): """ Align the columns of the df to the last value. """ df = df.copy() if demean: df -= df.dropna().mean() scale = np.abs(df.dropna().std()) return df / scale
ee6ab8359e0bf089d2f6ea40601299665024570c
3,605,297
def count_intersections(lines, *, with_diagonals): """ >>> lines = [(0,9,5,9), (8,0,0,8), (9,4,3,4), (2,2,2,1), (7,0,7,4), (6,4,2,0), (0,9,2,9), (3,4,1,4), (0,0,8,8), (5,5,8,2)] >>> count_intersections(lines, with_diagonals=False) 5 >>> count_intersections(lines, with_diagonals=True) 12 """ ...
c9a1d13e64cca408b76d5c1271be3afca0d87dcd
3,605,298
def edit_product(request, product_id): """ Edit a product in the store """ if not request.user.is_superuser: messages.error(request, 'Sorry, only store owners can do that.') return redirect(reverse('home')) product = get_object_or_404(Product, pk=product_id) if request.method == 'POST':...
17578c3210d9f84d1746d8a55cee1efcf8755fbb
3,605,299