content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os import configparser def load_config(config_file_path): """ Load the config ini, parse settings to WORC Args: config_file_path (String): path of the .ini config file Returns: settings_dict (dict): dict with the loaded settings """ if not os.path.exists(config_file_pa...
d46e7e3ef92b5cb3a61a9ec2339b407adb506a68
3,651,900
from typing import Dict def get_last_confirmed() -> Dict: """ This function get the last day saved on mongodb and show us the confirmed cases and the accumulated. - The country is the only needed path parameter. """ date = db.find({}, {"date": 1, "_id": 0}).sort("date", -1).limit(1) date =...
af2cf9ea3da1d361bf1347c389c2c9a6f095629e
3,651,901
def _newNode( cls, named ): """Construct new instance of cls, set proper color, and add to objects""" if not scene.visible: scene.visible = 1 if not [k for k in ('color','red','green','blue') if k in named]: named['color'] = scene.foreground if 'display' in named: target = named[...
7b81b4ec5c1a540f7159dd532c87cc2ebd3c7150
3,651,902
def MplJs(): """ Serves the generated matplotlib javascript file. The content is dynamically generated based on which toolbar functions the user has defined. Call `FigureManagerWebAgg` to get its content. """ js_content = FigureManagerWebAgg.get_javascript() resp = make_response(js_con...
d7b34b86d75f1375f6788a40245e7d04cb3ce6d9
3,651,903
def VVSS2021_fig4_plot(data, model, sizes=fig_sizes, cmaps=colormaps): """ Create and save a plot of the results from the linear regression reaction time model :param data: the data frame :param model: the fitted reaction time model :param cmaps: a dictionary of colormaps :param sizes: a diction...
47e63763073c454f1c44cf6e4c590b8b7a985f43
3,651,904
def stat(noten): """ Berechne Mittelwert, Median, min, max, oberes und unteres Quantil """ minimum = round(min(noten), 2) maximum = round(max(noten), 2) _median = median(noten) _mittelwert = mittelwert(noten) [unteres_quartil, oberes_quartil] = quartile(noten) return [minimum, unteres_quarti...
89d00c9b91b142366a4ca927298931a2f22bc715
3,651,905
def translation_activate_block(function=None, language=None): """ Activate language only for one method or function """ def _translation_activate_block(function): def _decorator(*args, **kwargs): tmp_language = translation.get_language() try: translation....
8615b02e4e3aa0560be0734f8e6564755f5e5e9b
3,651,906
def _loaded_schema_collections(schema_file_relative_dir) -> SchemaCollectionManager: """A loaded ``SchemaCollectionManager`` object, but this should never be modified. This object manages ``Schema`` objects corresponding to ``tests/{datasets,formats,licenses}.yaml``. Note that these are not necessarily the same...
ba5d03c8ad1c622391247ef505ccad21476c17d2
3,651,907
import uuid def dag(name=None, child_tasks=None, edges=None, target=None): """ Create a DAG task Args: name (str): Name for the task child_tasks (list [Task]): Child tasks within this dag edges (list [tuple (Ref, Ref)]): List of tuples of ref(Task). ...
ce12e46141ab030297303b4d55585475eb74f2cf
3,651,908
async def async_validate_pdf_signature( embedded_sig: EmbeddedPdfSignature, signer_validation_context: ValidationContext = None, ts_validation_context: ValidationContext = None, ac_validation_context: ValidationC...
fb4a8ae244d80c672ddc35c94d75953ab2d7d119
3,651,909
import inspect def get_one_to_many_foreign_key_column_name(model, name): """ Returns the constituent column names for the foreign key on the remote table of the one-to-many relationship specified by name. Args: model (class or object): The given model class or model instance. name (st...
f829de2cbb29034f033f3c124837ac888f7526eb
3,651,910
import argparse def parse_args(): """ parse the args from the cli """ logger.debug("parse_args()") parser = argparse.ArgumentParser(description='Check the status of dnsmasq') parser.add_argument('-v', '--verbose', action='store_true', default=None, help='Verbose?') parser.add_argument('--url', de...
de22e0b754d204c5c59fcfc2cb452fea844d387d
3,651,911
import argparse def parse_args(args): """Parse command line parameters Args: args ([str]): command line parameters as list of strings Returns: :obj:`argparse.Namespace`: command line parameters namespace """ parser = argparse.ArgumentParser( description="Just a Fibonacci demo...
96a7a5825ef0ba990e6bfac4e4a4d49e29bfb662
3,651,912
from typing import List def formula(formula: str, formula_param: str, cols: List[str]) -> Aggregation: """ Create a user defined formula aggregation. Args: formula (str): the user defined formula to apply to each group formula_param (str): the parameter name within the formula cols (L...
86247179aa3252bf24500c53b2cf7c20eb9afe62
3,651,913
def num_false_positives(df): """Total number of false positives (false-alarms).""" return df.noraw.Type.isin(['FP']).sum()
6aa339b86d15072c6a6910a43e70281575da5d36
3,651,914
import ctypes def repmot(instr, marker, value, repcase, lenout=None): """ Replace a marker with the text representation of an ordinal number. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmot_c.html :param instr: Input string. :type instr: str :param marker: Marker to be replace...
1be758f8c594805ae08c4b2e62014809e62039ad
3,651,915
from typing import Optional def check_for_pending_actions( user: IdPUser, ticket: SSOLoginData, sso_session: SSOSession ) -> Optional[WerkzeugResponse]: """ Check whether there are any pending actions for the current user, and if there are, redirect to the actions app. :param user: the authentica...
372b232d24003f6f8cbaefd8293fec233376a743
3,651,916
def emulatte_RESOLVE( thicks, resistivity, freqs, nfreq, spans, height, vca_index=None, add_noise=False, noise_ave=None, noise_std=None ): """ return : ndarray [ Re(HCP1), Re(HCP2), Re(HCP3), (Re(VCX)), Re(HCP4), Re(HCP5), Im(HCP1), I...
0cdd44d9d3d53c1813ed25f230e29adec36fca5e
3,651,917
import csv from pathlib import Path def metadata_dict_chex_mimic(metadata_location): """Reads whole csv to find image_name, creates dict with nonempty bboxes Output: Bboxes dictionary with key the img_name and values the bboxes themselves.""" bboxes = {} with open(metadata_location) as f_obj...
716358d1eb5a77c177a41076bb630108d7ffc934
3,651,918
def create_feature_df(cnv_dict, feature_type, labels, csv=False): """Creates a pandas Dataframe containing cnvs as rows and features as columns""" # get features for each CNV cnv_features = [] if csv: for chrom in cnv_dict: for cnv in cnv_dict[chrom]: if cnv.tads: ...
76af71f73ee09a7cbfbafed3ad447b20a98e0da5
3,651,919
import xml def simulationcell_from_axes(axes, bconds='p p p', rckc=15.): """ construct the <simulationcell> xml element from axes Args: axes (np.array): lattice vectors bconds (str, optional): boundary conditions in x,y,z directions. p for periodic, n for non-periodic, default to 'p p p' rc...
c3cdc77f9cce7ef09418459832c60b6570d7e11c
3,651,920
def diff_seq(seq1, seq0): """Returns the difference of two sequences: seq1 - seq0. Args: seq1: The left operand. seq0: The right operand. Returns: The difference of the two sequences. """ return (seq1 - seq0) % MAX_SEQ
cd1632357d6ff61fcd2a32ba71a6a6be2454521d
3,651,921
def method_menu(): """Method menu items 1. Add a new method 2. Duplicate selected method 3. Remove selected method ------------------------------ 4. Clear methods """ message_method = "You are about to delete all methods. Do you want to continue?" method_items = [ menu_item(i...
d22a820a249728650b49f75ccfcdc254f3a84e76
3,651,922
def shapeanalysis_OuterWire(*args): """ * Returns the outer wire on the face <Face>. This is replacement of the method BRepTools::OuterWire until it works badly. Returns the first wire oriented as outer according to FClass2d_Classifier. If none, last wire is returned. :param face: :type face: TopoDS_Face...
7fa38d16cdfe40f802dea7d93666870e82d5cf26
3,651,923
def is_numeric(val: str) -> bool: """Check whether an unparsed string is a numeric value""" if val in MISSING_VALUES: return True try: float(val) except Exception: return False else: return True
72d6095c32f3bd89c0ae8bda22dc4b9a6461468b
3,651,924
import tempfile import os def safeRun( commandArgs ): """ Runs the given command and reads the output """ errTmp = tempfile.mkstemp() errStream = os.fdopen( errTmp[0] ) process = Popen( commandArgs, stdin = PIPE, stdout = PIPE, stderr = errStream ) process.stdin.close...
217ddceaaaab339e80adaab6c7884c751474e53f
3,651,925
def expand_options(sent, as_strings=True): """ ['1', '(', '2', '|', '3, ')'] -> [['1', '2'], ['1', '3']] For example: Will it (rain|pour) (today|tomorrow|)? ----> Will it rain today? Will it rain tomorrow? Will it rain? Will it pour today? Will it pour tomorrow? Will it pour?...
2b07ac0cfee7339b11016f68792500bf855df019
3,651,926
def gcd_recursive_by_divrem(m, n): """ Computes the greatest common divisor of two numbers by recursively getting remainder from division. :param int m: First number. :param int n: Second number. :returns: GCD as a number. """ if n == 0: return m return gcd_recursive_by_div...
bd25d9cea4813e523ea6bb9bd85c24bf43dd2744
3,651,927
def repeat(atoms, coord): """ Repeat atoms (:class:`AtomArray` or :class:`AtomArrayStack`) multiple times in the same model with different coordinates. Parameters ---------- atoms : AtomArray, shape=(n,) or AtomArrayStack, shape=(m,n) The atoms to be repeated. coord : ndarray, dtype...
b4f86bad25061807370d0f1eacdb0637eb8a19cc
3,651,928
def get_mzi_delta_length(m, neff=2.4, wavelength=1.55): """ m*wavelength = neff * delta_length """ return m * wavelength / neff
5bcd4b9b217c79a06b48856f7801060787f12e52
3,651,929
def yagzag2radec(yag, zag, q): """ Given ACA Y-ang, Z-ang and pointing quaternion determine RA, Dec. The input ``yag`` and ``zag`` values can be 1-d arrays in which case the output ``ra`` and ``dec`` will be corresponding arrays of the same length. :param yag: ACA Y angle (degrees) :param zag: ...
e7266f5c0dd0763238c3f12fafebea19c080022d
3,651,930
from tensorflow.keras.preprocessing.image import load_img from typing import Union def load_image( path: str, color_mode="rgb", target_size: Union[None, ImageSize] = None, normalize=False, ) -> np.ndarray: """Load an RGB image from the given path, optionally resizing it. :param path: Path to ...
9b80d39561e3ccdae778675e011ab5c52c04db4f
3,651,931
def deit_base_patch16_384(): """ DeiT base model @ 384x384 from paper (https://arxiv.org/abs/2012.12877). ImageNet-1k weights from https://github.com/facebookresearch/deit. """ cfg = ViTConfig( name="deit_base_patch16_384", url="", input_size=(384, 384), patch_size=16...
720968c8a95de30c836631fd5505c8029eaf46c0
3,651,932
def update_output( event_id, event_dividers, light_dividers, filename, geometry, do_plot_tracks, do_plot_opids, figure, ): """Update 3D event display end event id""" fig = go.Figure(figure) if event_dividers is None: return no_update, no_update, no_update, no_update,...
370f7a165ddaf870d4806564d8b86f4d5c4e90b5
3,651,933
import requests def get_containerports(marathon_url, app_id): """ Get containerports if we have portmapping. marathon_url : [string] the URL of the marathon service app_id : [string] ID of the running marathon app Method : GET Return : list of ports """ api_endpoint = '/v2/apps/' ...
eb22656e58b2b7156015b84c63755cb4f4348502
3,651,934
def backward_algorithm(O, HMM_model): """HMM Backward Algorithm. Args: O: (o1, o2, ..., oT), observations HMM_model: (pi, A, B), (init state prob, transition prob, emitting prob) Return: prob: the probability of HMM_model generating O. """ pi, A, B = HMM_model T = len(O) ...
da958ddd8d8943546030ba4306b7f632061d96bc
3,651,935
def scan_codes(code_type, image): """Get *code_type* codes from a PIL Image *code_type* can be any of zbar supported code type [#zbar_symbologies]_: - **EAN/UPC**: EAN-13 (`ean13`), UPC-A (`upca`), EAN-8 (`ean8`) and UPC-E (`upce`) - **Linear barcode**: Code 128 (`code128`), Code 93 (`code93`), Code 3...
02c70551138ffc5dc386e753d7532c28466de97e
3,651,936
def get_summoner_masteries(summoner_ids): """ https://developer.riotgames.com/api/methods#!/1017/3450 Args: summoner_ids (int | list<int>): the summoner ID(s) to get mastery pages for Returns: dict<str, MasteryPages>: the requested summoners' mastery pages """ # Can only have 4...
55b9395cd452e444f049d05af0718ca847f346d0
3,651,937
def make_pod_spec( name, image_spec, image_pull_policy, image_pull_secret, port, cmd, node_selector, run_as_uid, fs_gid, env, working_dir, volumes, volume_mounts, labels, cpu_limit, cpu_guarantee, mem_limit, mem_guarantee, lifecycle_hooks, ...
0be1782f91ab4de7a0baf0291eb3fcf9c1fc57a4
3,651,938
def preprocess(text, remove_punct=False, remove_num=True): """ preprocess text into clean text for tokenization """ # 1. normalize text = normalize_unicode(text) # 2. to lower text = text.lower() # 3. space text = spacing_punctuation(text) text = spacing_number(text) # (optio...
289ed6c3032840191ea792b01cb4b3a17535ddf2
3,651,939
def verify_ptp_calibration_states( device, states, domain, max_time=15, check_interval=5 ): """ Verify ptp parent values in show ptp parent command Args: device (`obj`): Device object states ('str): PTP calibration state domain ('str): PTP domain max_time...
648e9753b418365d8469ce17bc709ad67d814bf6
3,651,940
def get_auth_use_case(): """Get use case instance.""" return auth_use_case
a01595d40d2693ff2b4023a8d7938b4af7734ca3
3,651,941
import glob import os import re def convert_file_link(file): """Reads the content of all files matching the file specification (removing YAML metadata blocks is required) for insertion into the calling file. Optionally add a separator between each file and/or add a prefix to each line of the included ...
f1af225482e558fe8ef60c98b3f0f5692ae70133
3,651,942
def pagerank(G, alpha=0.85, personalization=None, max_iter=100, tol=1.0e-6, nstart=None, weight='weight', dangling=None): """Returns the PageRank of the nodes in the graph. PageRank computes a ranking of the nodes in the graph G based on the structure of the incoming links. It was...
1d6e758275a3caf33049e5c042b7bde8f4cff17d
3,651,943
from pathlib import Path import zlib import tqdm def fetch_file(name, chunksize=16 * 1024): """ Fetch a datafile from a compressed/gzipped URL source. Parameters ---------- name : :class:`str` Name of the file to fetch. chunksize : :class:`int` Number of bytes to read in a chu...
f22eb09220135b542bb3b0e599abe896664dffa3
3,651,944
def create_include(workflow_stat): """ Generates the html script include content. @param workflow_stat the WorkflowInfo object reference """ include_str = """ <script type='text/javascript' src='bc_action.js'> </script> <script type='text/javascript' src='bc_""" + workflow_stat.wf_uuid +"""_data.js'> </script> "...
24151952c9dd5bc4034916dae90a3760fc06ca44
3,651,945
import random def choose_sample_from_group( group: general.ParameterListType, ) -> general.ParameterValuesType: """ Choose single sample from group DataFrame. """ # Make continous index from 0 indexes = [idx for idx in range(len(group))] assert len(indexes) > 0 # Choose from indexes ...
27f1c8a9ca4640b881f5bdd3faca0db4b1b882da
3,651,946
def path_available(filepath): # type: (str) -> bool """Return true if filepath is available""" parent_directory = dirname(filepath) if not exists(parent_directory): raise ParentDirectoryDoesNotExist(parent_directory, filepath) return not exists(filepath)
efd506d2028f2c55e88dfc618395620571205773
3,651,947
from typing import Dict from typing import Any from typing import Callable def memory_item_to_resource(urn: URN, items: Dict[str, Any] = None, loader: Callable = None) -> CloudWandererResource: """Convert a resource and its attributes to a CloudWandererResource. Arguments: urn (URN): The URN of the r...
0bf680574f2ef3038d9d29c656a657e4e7a172ec
3,651,948
def sample_user(email='[email protected]', password='testpass'): """Create a sample user""" return get_user_model().objects.create_user(email, password)
deb5c45287a8ff546e2631c4409d10015b550e5c
3,651,949
import PIL import random def ShearX(img: Image, magnitude: float) -> Image: """Shear the image on x-axis.""" return img.transform( img.size, PIL.Image.AFFINE, (1, magnitude * random.choice([-1, 1]), 0, 0, 1, 0), PIL.Image.BICUBIC, fillcolor=FILLCOLOR, )
9d534cfc8f7cc5497356b8e07115d42f666aac5d
3,651,950
import subprocess def run_command_unchecked(command, cwd, env=None): """Runs a command in the given dir, returning its exit code and stdio.""" p = subprocess.Popen( command, cwd=cwd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, ) std...
89c6fd0acf7e8bb81c837f78252bdaa30fe39ad1
3,651,951
import numpy def read_onsets(onsets_path: PathLike) -> numpy.array: """ Read a text file containing onsets. Return it as a list of floats. """ with open(onsets_path, "r") as io: lines = io.readlines() onsets = numpy.array([float(line) for line in lines]) return onsets
cbfa38ce0a5e2ea4d6c465251ee8c3e6ec47d04f
3,651,952
def format_specific_efficacy(method, type_1: str, type_2: str = None): """ Format the efficacy string specifically for defense or attack. """ effective, ineffective, useless = format_damage(method, type_1, type_2) type_name = format_type(type_1, type_2) s = "**{}** \N{EN DASH} **{}**\n".format(type_name...
095f943cda0dfdf1803ae38b16c6b9d7f8fd3e1f
3,651,953
import sys def postfix(itemString): """transform infixExpre into postfixExpre Algorithm: step1: if operator, stack in; step2: if "(", stack in. step3: if variable, pop out the all continued unary operator until other operator or "(" step4: if ")", pop out all operators until "(...
1c3bee30f450c1dfab6ca7d0dd057465d8b6e8e5
3,651,954
def getSuffixes(algorithm, seqType) : """ Get the suffixes for the right algorithm with the right sequence type """ suffixes = {} suffixes['LAST'] = {} suffixes['BLAST'] = {} suffixes['BLAST']['nucl'] = ['nhr', 'nsq', 'nin'] suffixes['BLAST']['prot'] = ['phr', 'psq', 'pin'] s...
9ab699a71be73381c4dff555f0ef19201589e82f
3,651,955
import tempfile from robocorp_code.path_operations import get_user from robocorp_code.path_operations import make_numbered_dir_with_cleanup from robocorp_code.path_operations import LOCK_TIMEOUT from typing import Optional from pathlib import Path def make_numbered_in_temp( keep: int = 10, lock_timeout: float...
9ba3d08d933d961099d5169afc25c152177857b3
3,651,956
def handle_server_api(output, kwargs): """ Special handler for API-call 'set_config' [servers] """ name = kwargs.get('keyword') if not name: name = kwargs.get('name') if name: server = config.get_config('servers', name) if server: server.set_dict(kwargs) ...
0c4396619c1aee1151642de3edeb4b28d76acb9c
3,651,957
def compare_names(namepartsA, namepartsB): """Takes two name-parts lists (as lists of words) and returns a score.""" complement = set(namepartsA) ^ set(namepartsB) intersection = set(namepartsA) & set(namepartsB) score = float(len(intersection))/(len(intersection)+len(complement)) return score
87cbceaaa0acce0b83b5faf66cbe909ad52382eb
3,651,958
def Normal_VaR(return_matrix, theta,Horizon): #500 datas needed """ Compute the Value-at-Risk and Conditional Value-at-Risk Parameters ---------- risk_returns : np.ndarray theta : np.float64 Horizon : np.int16 Returns ---------- np.ndarra...
a2b911d647c942724dc30480bb90db7c83e200bb
3,651,959
def oscillator_amplitude(state, ders, period, floquet, zero_phase_lc, phase_warmup_periods=5, thr=0.0, dt=0.005): """calculates the isostable amplitude of the oscillator from dynamical equations :param state: state of the system :param ders: a list of state variable derivatives :param period: oscillator period :...
b6a55d9965eea712be2f49dbbc1f186d268f82bf
3,651,960
def commonprefix(a, b): """Find longest common prefix of `a` and `b`.""" pos = 0 length = min(len(a), len(b)) while pos < length and a[pos] == b[pos]: pos += 1 return pos, b
75e2f9ac6c3d0c38986cba5f8409ddc87fe8edbe
3,651,961
def parse_datetime(strtime): """ Parse a string date, time & tz into a datetime object: 2003-03-20 05:00:00-07 """ offset = int(strtime[-3:]) date_time = dt.strptime(strtime[:-4], '%Y-%m-%d %H:%M:%S') offset = timedelta(hours=offset) return (date_time + offset).replace(tzinfo=utc)
c7537ed913a4d0b20a71b7253725231c32c9f60b
3,651,962
from typing import List from typing import cast from typing import Iterable def traverse_depth_first(base: AnyDependency) -> List[AnyDependency]: """Performs a depth first traversal of the dependency tree. """ def _traverse_tree_2(base: AnyDependency) -> List[AnyDependency]: queue: List[AnyDepende...
1172f3b97110cc41c68631d3e6a91a0ea8d20627
3,651,963
def update_config( client, key, *, value=None, remove=False, global_only=False, commit_message=None ): """Add, update, or remove configuration values.""" section, section_key = _split_section_and_key(key) if remove: value = client.remove_value( section, sectio...
59f71b2608ddcfb38cdf1845720d782b7858607f
3,651,964
from datetime import datetime def parse_time(t): """ parse a date time string, or a negative number as the number of seconds ago. returns unix timestamp in MS """ try: tint = int(t) if tint <= 0: return int(nowms() + (tint * 1000)) except ValueError: pass ...
68189b1d0aa2f73152a77a1a790fc6a291e5ff25
3,651,965
def _get_duration(tmin: np.datetime64, tmax: np.datetime64) -> str: """ Determine the duration of the given datetimes. See also: `ISO 8601 Durations <https://en.wikipedia.org/wiki/ISO_8601#Durations>`_ :param tmin: Time minimum :param tmax: Time maximum :return: Temporal resolution formatted a...
e56c399402a1325bc519443ea4caea57be2806e7
3,651,966
import math def get_polyend_circle_angles(a, b, isLeft): """ theta0 = pi/2 + betta, theta1 = 2 * pi + betta; betta = pi/2 - alpha; alpha = atan(a) """ if a is None and b is None: return None, None alpha = math.pi / 2.0 if a is None else math.atan(a) betta = math.pi / 2.0 - a...
9547ba4ea9f74cba3d52d90bb24dc8c4b246fbff
3,651,967
import argparse import pathlib def main(): """Main entrypoint.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("file", nargs="+", type=pathlib.Path) args = parser.parse_args() hooks.utils.check_executable("packer") return hooks.utils.bulk_check( packer_fix,...
025acb7a6ed7b5e5dff9b0fe0ad743616945e2ee
3,651,968
import re def get_search_cache_key(prefix, *args): """ Generate suitable key to cache twitter tag context """ key = '%s_%s' % (prefix, '_'.join([str(arg) for arg in args if arg])) not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)])) key = not_allowed.sub('', key) retur...
f3ff5baa13e4e84deb5c13cd8d5b618ba75c8699
3,651,969
def main(argv=None): """Run pragma-no-mutate filter with specified command line arguments. """ return PragmaNoMutateFilter().main(argv)
f268a010b454fe28307e8e304dca3d57fe1e635a
3,651,970
import math def independence_single_value(values, sigma=0.70): """ This calculates the independence of the models for a given metric where the metric is single valued, e.g. the slope of a gradient. ------Input------ values (list) : The single values for each model. sigma (float) : The value of...
0802966fed4d9cb5b9e2d525d10593534c5c51a0
3,651,971
def extract_fingerprints(atoms, i_jbond_dict, radius): """Extract the r-radius subgraphs (i.e., fingerprints) from a molecular graph using Weisfeiler-Lehman algorithm.""" if (len(atoms) == 1) or (radius == 0): fingerprints = [fingerprint_dict[a] for a in atoms] else: nodes = atoms ...
beaa457e0eb514ca7fbfaca846378a0d23c2b94c
3,651,972
import inspect def GetUniqueClassMembers(Class, Ignore = [], AllowedOverrides = []): """ Args: - Class {object}: reference to the class - Ignore {List[str]}: - AlwaysAllow {List[str]}: Always allowed members named x, even if they exists in the parent class Returns: tuple("Name",...
bdd22e6ce7eaa12d2285f7ca7747a0210d3b98c9
3,651,973
def get_condition_keys_available_to_raw_arn(db_session, raw_arn): """ Get a list of condition keys available to a RAW ARN :param db_session: SQLAlchemy database session object :param raw_arn: The value in the database, like arn:${Partition}:s3:::${BucketName}/${ObjectName} """ rows = db_session...
8f8025ffe1fd6f6fa750f826b0a3c5b8a4f655eb
3,651,974
def get_reviewer(form): """ Gets reviewer info, or adds if necessary """ reviewer = Reviewer.query.filter_by(email=form.get("reviewer-email")).first() if reviewer: reviewer_id = reviewer.reviewer_id else: reviewer_id = add_reviewer(form) return reviewer_id
641bb81e73bad7f0eeac8a5cbd5efde499535b77
3,651,975
def read_xyz(using): """Reads coordinates of an xyz file and return a list of |Atom| objects, one for each atom""" coords = [] with open(using, "r") as f: for coord in f.readlines()[2:]: line = coord.split() for val in PT.ptable.values(): if line[0] == val[0]:...
9ed1b0de9fe4bd7bbabe63a2d808b08e44315113
3,651,976
def initialize_classification(model_name: str, num_classes: int, use_pretrained: bool =True ) -> (Module, int): """ Initialize these variables which will be set in this if statement. Each of these variables is mo...
23958e7970022b2c0ed77353fa8b927510873bb7
3,651,977
def get_csc(): """get Configuration Client""" config_host = enstore_functions2.default_host() config_port = enstore_functions2.default_port() return configuration_client.ConfigurationClient((config_host,config_port))
49c2740ac9a654e700079d15f32421e32f8568c3
3,651,978
def findx(mu, lnum): """Obtains the Hill sphere and x-coordinate for a mu-value and lnum.""" hill = (mu/3)**(1.0/3.0) if lnum == 1: #lnum is used to request one of the collinear Lagrange points. guess = 1 - mu - hill * (1 - (1.0/3.0) * hill - (1.0/9.0) * hill ** 2) elif lnum == 2: ...
260f9dda3b5a494df15d3c0bbe7ce0ebd0351c9b
3,651,979
def _f1_div_ ( self , other ) : """Operator for ``1D-function / other''""" return _f1_op_ ( self , other , Ostap.MoreRooFit.Division , "Divide_" )
5278ec2036724f0bb263487b8880c16b161d8145
3,651,980
def test_interrupted_late_wait(): """Test we can interrupt the wait during the timeout period. """ called = 0 def cond(): nonlocal called called += 1 if called == 3: return True job = InstrJob(cond, 0) assert not job.wait_for_completion(lambda: True, refresh...
737df84c71efdaf0e52be5f42c0ae856f9fb1018
3,651,981
def set_prior_6(para): """ set prior before the first data came in doc details to be added """ n_shape = para['n_shape'] log_prob = [ [] for i_shape in range(n_shape) ] delta_mean = [ [] for i_shape in range(n_shape) ] delta_var = [ [] for i_shape in range(n_shape) ] time_since_last...
e97944e1c48ca6def16308584dfe04eaebae6259
3,651,982
def inf_set_af2(*args): """ inf_set_af2(_v) -> bool """ return _ida_ida.inf_set_af2(*args)
c9fa149ca8595d053db4eb4d4113e2493b8665de
3,651,983
import matplotlib.pyplot as plt import matplotlib def showOverlapTable(modes_x, modes_y, **kwargs): """Show overlap table using :func:`~matplotlib.pyplot.pcolor`. *modes_x* and *modes_y* are sets of normal modes, and correspond to x and y axes of the plot. Note that mode indices are incremented by **1**...
86a0853b8caf6ade88185cef17277d01be38ecc7
3,651,984
import pandas as pd def json_find_matches_dataframe(df, filter_path, reverse_selectivity=False): """Iteratively filters a pandas.DataFrame df using the same sort of filter_path used by json_extract. Because of the tabular nature of pandas DataFrames, filters are treated as being either 'down' ...
33f3de47ffbe774d22e2dc9fb7c07f132272452f
3,651,985
def contrast(arr, amount=0.2, split=0.5, normalize=True): """ General contrast booster or diffuser of normalized array-like data. Parameters ---------- arr : ndarray Input array (of floats on range [0, 1] if ``normalize=False``). If values exist outside this range, with ``normalize=...
94542fd4df7c65c98f818b652c733ad5a319f449
3,651,986
def get_group(items, total_groups, group_id): """ Get the items from the passed in group based on group size. """ if not 0 < group_id <= total_groups: raise ValueError("Invalid test-group argument") start, size = get_group_size_and_start(len(items), total_groups, group_id) selected = it...
f236c9f26adfa5da5507e7ae91feb8858ac13c6c
3,651,987
def read_nq_entry(entry, is_training): """ Converts a NQ entry into a list of NqExamples. :param entry: dict :param is_training: bool :return: list[NqExample] """ def is_whitespace(c): return c in " \t\r\n" or ord(c) == 0x202F examples = [] contexts_id = entry["id"] con...
a712ff6a2714798ee49fd90741f387d8cb3b4695
3,651,988
def calc_atoms(psi, vol_elem=1.0): """Calculate the total number of atoms. Parameters ---------- psi : :obj:`list` of 2D NumPy :obj:`array` or PyTorch :obj:`Tensor` The input spinor wavefunction. vol_elem : :obj:`float` 2D volume element of the space. Returns ------- at...
9e9d87c9445a6a03fe245b66c2ce1c104a276e7a
3,651,989
def get_tcp_packet_payload_len(pkt: dpkt.ethernet.Ethernet) -> int: """ Return the length of only payload without options :param pkt: dpkt.ethernet.Ethernet packet containing TCP header :return: int """ if isinstance(pkt, dpkt.ethernet.Ethernet): ip = pkt.data elif isinstance(pkt...
410ec3f76085647def33572cc35f951462dd9324
3,651,990
def overviewUsage(err=''): """ default overview information highlighting active scripts""" m = '%s\n' %err m += ' The following scripts allow you to manage Team Branches (TmB) on SalesForce.\n' m += ' Use one of the scripts below to meet your needs.\n' m += ' \n' m += ' 1. First link Task Br...
ba62773dd8be21d17c44e8e295c8228d568512a0
3,651,991
def min_distance(z_i, z_j, sc_size): """Calculates the minimum distance between the particle at ``z_i`` and all of the images of the particle at ``z_j``, including this. The minimum distance is always less than half of the size of the simulation supercell ``sc_size``. :param z_i: :param z_j: ...
b585eb8e813ca852c4538eea7a9a6f9028a969d7
3,651,992
import re def prf(gold: str, pred: str, dic) -> tuple: """ 计算P、R、F1 :param gold: 标准答案文件,比如“商品 和 服务” :param pred: 分词结果文件,比如“商品 和服 务” :param dic: 词典 :return: (P, R, F1, OOV_R, IV_R) """ A_size, B_size, A_cap_B_size, OOV, IV, OOV_R, IV_R = 0, 0, 0, 0, 0, 0, 0 with open(gold,encoding='...
a8767bbe4c60eea2433d2c8023a9d7a1af74a4bf
3,651,993
def lorem(): """Returns some sample latin text to use for prototyping.""" return """ Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nis...
6ddacdb23b7c62cf930e622a7fd801b514a419ae
3,651,994
def read_gene2species(* filenames): """ Reads a gene2species file Returns a function that will map gene names to species names. """ for filename in filenames: maps = [] for filename in filenames: maps.extend(util.read_delim(util.skip_comments( util.open_...
90e58b2089f2561642ac1ba6648256888b931080
3,651,995
from typing import Dict from typing import Any from typing import Optional from sys import path import requests def ingest( token: str, endpoint: str, method: str = "GET", time_zone: str = "Asia/Tokyo", params: Dict[Any, Any] = {}, data: Dict[Any, Any] = {}, ) -> Optional[Dict[Any, Any]]: ...
70bf1de3cb09743f421ae592214a8e058fdb8365
3,651,996
def make_list_table(headers, data, title='', columns=None): """Build a list-table directive. :param headers: List of header values. :param data: Iterable of row data, yielding lists or tuples with rows. :param title: Optional text to show as the table title. :param columns: Optional widths for the ...
569370b8359ad25bf255f940b5a89d93d896804d
3,651,997
def toss_unbaised(): """ toss 2 times: assign 0-1 = 0 assign 1-0 = 1 discard 0-0 and 1-1 """ while True: first, second = toss_biased(), toss_biased() if first == 0 and second == 1: return 0 if first == 1 and second == 0: return 1
971f3365fbc4f0de34cd51c8060aab5c5037c7b2
3,651,998
def split_val_condition(input_string): """ Split and return a {'value': v, 'condition': c} dict for the value and the condition. Condition is empty if no condition was found. @param input A string of the form XXX @ YYYY """ try: (value, condition) = [x.strip() for x in input_string.s...
97c5733a80b3348928b95e2430bf3630867b2050
3,651,999