content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import urllib import ast def find_path(start, finish, security=5, invert=0): """ Returns a list of system objects which represent the path. start: system_id of first system finish: system_id of last system security: sec level of system * 10 invert: if true (1), use security as highest seclevel...
1fee78f6899cf6d4f28141214ec50b1b5de656dd
68,600
from typing import Union from typing import Callable from typing import Any from typing import Dict import time def debounce(duration: Union[float, int] = 0.1) -> Callable[..., Any]: """Ensure a function called with the same arguments executes only once per `duration` (default: 100ms). """ def decora...
11d8d52fec00a6eb0535ef4f6a544b7b349749cc
68,601
def set_student_i_d(person_id: str = None, student_id: str = None): """ Sets a student's ID :param person_id: The numeric ID of the person whose student ID you'd like to change. :param student_id: The new student ID :returns: String containing xml or an lxml element. """ return get_anonymo...
61b51ba20b2d9a5845e6441344c251f55467e175
68,602
def signalumap(jsonfiles, **kwargs): """ Performs UMAP on signal matrices read from the given files; returns the coordinates of the elements in the reduced dimension space. Each JSON file should contain a matrix with the same number of elements, corresponding to the matrix rows. The vectors from each fi...
12719ff8bfce59af39b2e900e640e785c37294cf
68,603
from datetime import datetime def pls(X,Y,A,*,mcsX=True,mcsY=True,md_algorithm='nipals',force_nipals=False,shush=False,cross_val=0,cross_val_X=False): """ Projection to Latent Structures routine by Salvador Garcia-Munoz (sgarciam@ic.ac.uk ,salvadorgarciamunoz@gmail.com) Inputs: X,Y...
23dadf785068d06d3d2488748ffb84bad8baa00e
68,604
def GetLastCollectionPathInfos(client_paths, max_timestamp=None): """Returns PathInfos corresponding to last collection times. Args: client_paths: An iterable of ClientPath objects. max_timestamp: When specified, onlys PathInfo with a timestamp lower or equal to max_timestamp will be returned. Ret...
80cb02e7c707145e008166f21da40ee8b3bc0cfd
68,605
from typing import Tuple from typing import Callable def create_acoustic_bottleneck_block( *, # Convolution configs. dim_in: int, dim_inner: int, dim_out: int, conv_a_kernel_size: Tuple[int] = (3, 1, 1), conv_a_stride: Tuple[int] = (2, 1, 1), conv_a_padding: Tuple[int] = (1, 0, 0), ...
8ae884a0d3d62550440354ec5608b98dc80609df
68,606
from re import T def gen_updates_adadelta(loss, all_parameters, learning_rate=1.0, rho=0.95, epsilon=1e-6): """ in the paper, no learning rate is considered (so learning_rate=1.0). Probably best to keep it at this value. epsilon is important for the very first update (so the numerator does not become 0). ...
be2ef23a612ee4792a83d35ae864ea5db3389428
68,607
def read_user_header(head): """ The 'User-Id' header contains the current online user's id, which is an integer -1 if no user online :param head: the request's header :return: online user's id, abort type error if the header is not an integer. """ try: return int(head['User-Id']) ...
95586f32b698283f33c9271b5ffdf61a934dbb4a
68,608
def acceptance_probability(alpha, multiplier): """The probability of a user accepting a ride given the multiplier""" return np.exp(-alpha * (multiplier - 1))
bfbeff9b6b8410babadc22ffa224fd02ca8a4aff
68,609
import re def get_info(printer_address): """ Returns an object with basic printer information such as name etc.""" info_result = send_gcode(printer_address, GCode.GET_INFO) printer_info = {} info_fields = ['Type', 'Name', 'Firmware', 'SN', 'X', 'Tool Count'] for field in info_fields: rege...
50a2873a4b5df4b0d43085da731b78cd54d61968
68,610
import time from datetime import datetime def t_dt_utc_a(): """Time, format datetime, scale utc, array entry""" return time.Time( [datetime(2015, 6, 30) + timedelta(hours=23, minutes=59, seconds=i) for i in range(0, 2)], scale="utc", fmt="datetime", )
ade94944b928e36ba1b075451f26909a5e7ebcf8
68,611
def message_max(message, max): """ Returns a given message with a maximum length. Primarily used for additional logging :param message: a message intended to send to twitter :param max: the maximum length of the message :returns: the message truncated to a maximum length """ if len(message)...
a4146ca18eb17d5f766a09f1ef1c425a71c1d2bd
68,612
def register_shellcontext(app): """Register shell context objects.""" def shell_context(): """Shell context objects.""" return { 'db': db, 'Person': person, 'Movie': movie, 'Actors': actors, 'Writers': writers, 'Directors': ...
1bc82e99d840ff499715122e9ed0095822c9d12f
68,613
from typing import List from typing import Any def fermion_opstring_to_bitstring(ops) -> List[List[Any]]: """Convert an openfermion FermionOperator object into the corresponding bitstring representation with the appropriate coefficient. Args: ops (FermionOperator): A product of FermionOperators w...
09894f4b9d91d6c473651b25e2523df6b1ffae15
68,614
from typing import Tuple def apply_burn(o1_factors: Tuple[Mass, Mobile], o2_factors: Tuple[Heat],) -> SetFactor[Mass]: """Reduces the mass of something conditioned it is on something with heat. :param o1_factors: First set of factors. :param o2_factors: Second set of factors. :return: Change of mass ...
ebf3ca873e78fc3b58b0ec36477c7e245189ae10
68,615
import uuid def GenerateUID(): """This will generate a unique ID which will be assigned""" return str(uuid.uuid1()).lower()
2b93b6db1de6139419dd13084147efe3e39de5ee
68,616
import sys import traceback def require_login(func): """Simple decorator helper for requiring login on functions decorated with flask route: make sure that it's LAST in the decorator list so that the flask magic happens (see voice_testing for an example). Important: we are assuming the blueprint endp...
130a9feb1d32ff79746bda935da747e7e1ea8fc4
68,617
from typing import Iterable from re import T def all_meet_predicate(iterable: Iterable[T], predicate: Predicate[T]) -> bool: """ Version of all which checks values against a predicate. :param iterable: An iterable of values. :param predicate: A predicate which checks those values. :return: ...
48e0c1b2460313e371f4e843334de04d9aaee626
68,618
def markovKdV(u,M,alpha): """Computes nonlinear part of Markov term in KdV C_k(u,v) = -(alpha * 1i * k) / 2 * sum_{i+j = k} u_i v_j where the sum of i and j is over a "full" system with M positive modes (user specified) Computed in real space to avoid loops and then converted back to ...
27365d95bc03e888db5e060e8ee26ba24cc51450
68,619
def recursive_merge(a, b): """Recursively merge two dicts. Updates a.""" if not isinstance(b, dict): return b for k, v in b.items(): if k in a and isinstance(a[k], dict): a[k] = recursive_merge(a[k], v) else: a[k] = v return a
3d98b804e95acf12a147b298f2c2642b2b4f96cb
68,620
def _compute_node_to_inventory_dict(compute_node): """Given a supplied `objects.ComputeNode` object, return a dict, keyed by resource class, of various inventory information. :param compute_node: `objects.ComputeNode` object to translate """ result = {} # NOTE(jaypipes): Ironic virt driver wil...
7edaa446d299baa22fbff08a8a57002730d4ed0c
68,621
def list_objects(remote): """Return a list of object IDs for the current scene""" cmd1 = mmapi.StoredCommands() key1 = cmd1.AppendSceneCommand_ListObjects() remote.runCommand(cmd1) objects = mmapi.vectori() cmd1.GetSceneCommandResult_ListObjects(key1, objects) return vectori_to_list(objects)
bff6c73fad57af300add264f2314bcba5605b232
68,622
def site_details(site: dict) -> dict: """ Describe site details in a simple data structure designed to be used from SQL. """ return { "type": site.get("type"), }
12295cec8616fc9beb5d1d0e0b41e9ed5026a828
68,623
def cosmicray_lacosmic(ccd, error_image=None, thresh=5, fthresh=5, gthresh=1.5, b_factor=2, mbox=5, min_limit=0.01, gbox=0, rbox=0, f_conv=None): """ Identify cosmic rays through the lacosmic technique. The lacosmic technique identifies co...
67fdffa29c9c209ad62db167f3c88debcba26df4
68,624
import six def _check_dedup(data): """Check configuration for de-duplication. Defaults to no de-duplication for RNA-seq and small RNA, the back compatible default. Allow overwriting with explicit `mark_duplicates: true` setting. Also defaults to false for no alignment inputs. """ if dd.ge...
795ca9185c1ddb617609675af7143923369cd912
68,625
def y_intercept_line(slope, point): """ Calculate a y-intercept of a line for given values of slope and point. Parameters ---------- slope : float A value of slope line. point : tuple A tuple with xy coordinates. Returns ------- y-intercept : float A vaule o...
839cdaa4b4646ebbdc5a2b941e5e14b45587cd24
68,626
from operator import index def crawl(domain): """ Primary function for the process pool. Crawl websites for links to privacy policies. First check if the website can be reached at all, then find list of policy links on first page. Then loop through links to see if the links are valid polici...
ac55cc04c369a9a98d99d8813d0ab4856cdedc6b
68,627
import math import cmath def phasor_to_time(upha = 1+1j*0.0,uphb = -0.5-1j*0.867,uphc = -0.5+1j*0.867,w=2.0*math.pi*60.0,t=0.0): """Convert a,b,c quantities from phasor domain to time domain.""" ra,pha = cmath.polar(upha) rb,phb = cmath.polar(uphb) rc,phc = cmath.polar(uphc) #ua = (ra*np.exp(...
98b53a24c3ff22f25d8fe78b7dae3b6d426c01f9
68,628
def wepay_docs_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """ Process the WePay docs role. """ # get the application app = inliner.document.settings.env.app # parse the text entered in the role. # here, we simply split on space to define the two parts o...
3883f8b9437bd15c4aa3592ec23a6dcc56647f11
68,629
def error_pattern(target, actual, debug=False): """ Return the phonological error pattern from a target/actual pair of consonants or consonant sequences. Args: target : str of consonant or consonant sequence actual : str of consonant or consonant sequence Returns: ...
22b8b2328c5b509a12447caf675a73e06b39a9e9
68,630
def followerstopper_example(render=None): """Perform a simulation of vehicles on a ring road. In this simulation, one vehicle is automated, and switches from human-driving to begins to automated vehicles after the time specified in AUTOMATED_TIME. Parameters ---------- render : bool, optio...
0e7b39c01b27c3cceff591735801fab17a46ca6e
68,631
def get_plugin_dir(app_path: str) -> str: """Returns full path to application plugin directory.""" product_info = get_product_info(app_path) version = parse_version(product_info.version) if is_android_studio(product_info): return join(ANDROID_STUDIO_PLUGIN_PREFIX, product_info.data_dir) if...
ad37618a10170e92407bdac16bacf7797dc5c407
68,632
from typing import Dict import types def makeSegmentLocations(seg, segSize): """ Create a data structure to hold the locations of all pixels in all segments. """ d = Dict.empty(key_type=types.uint32, value_type=RowColArray_Type) numSeg = len(segSize) for segid in range(MINSEGID, numSeg): ...
d8dcd8eb3d388a6e29c96c20865db2df3c711cff
68,633
def get_fasta_size(fasta): """ given a fasta file output the number of seqs and the length of the longest seq """ longest = 0 seqlist = read_fasta_file(fasta) for s in seqlist: longest = max(longest,len(s.seq.replace("-",""))) return len(seqlist),longest
f2e20ee41b2c67880582c8101cc75b6b4082627c
68,634
def random_email(): """随机email""" return fake.email()
3aa9f4a9bd23e6b49fe098d9280dfe3464b018fc
68,635
from ...tracking.utils import gm_calculate import sys def plot2d_gmphd_track(model, grid, gm_s_list=None, gm_list_list=None, observation_list=None, prediction_list=None, truth=None, title=None, contours=4, log_plot=True): """ Animate GM-PHD Filter result on 2D plot wi...
38b206b361cb5c8697cc9a6fe1bf1ee1330f5fb4
68,636
import os def expand_path(path, abs=False): """Path expansion util to get the right slashes and variable expansions. Note expanduser is needed, ~ is not expanded by expandvars """ path = os.path.normpath(os.path.expandvars(os.path.expanduser(path))) if abs: return os.path.abspath(path) ...
06076dfc7ed8b270883bf371bdbbc83ec7e17c5e
68,637
def load_pipeline(artifact_dir): """load all saved artifacts from pipeline run Args: artifact_dir (str): directory location Returns: pipeline: loaded pipeline components """ pipeline = PersistPipeline() pipeline.load(artifact_dir) return pipeline
2b1c3a559232abf3ee42121b8b7026d467010c5f
68,638
import torch def build_multi_agt_summarizer(n_agents: int, embedding_dim: int, vocab_size: int, hidden_size: int, n_contextual_layers: int, embeddings: torch.Tensor): """Builds the Multi-Agents Summarizer.""" embedding_layer = nn.Embedding.from_pr...
61d1c31440126cc179e49172cb35fb2e509d7b43
68,639
import json def iter_manifests(): """Iterate over all available manifests.""" manifests = [ json.loads(fil.read_text()) for fil in component_dir.glob("*/manifest.json") ] return sorted(manifests, key=lambda man: man["domain"])
9cfd93b07d3797bfdfb2c131d4a3d549d627fd96
68,640
def create_parent_record_links_bp(app): """Create parent record links blueprint.""" ext = app.extensions["invenio-rdm-records"] return ext.parent_record_links_resource.as_blueprint()
f977054140da7075daeb5ef1bb96dafd8164f537
68,641
import argparse def create_args(): """ :return: ArgumentParser Parser that handles cmd arguments. """ parser = argparse.ArgumentParser(usage='-i <input folder> ' '-h for full usage') parser.add_argument('-i', dest='dir', h...
b3d36aac5a3a444f183bcb1679d5f5914c19ed6d
68,642
def safe_dict(data): """Clean a dictionary to make sure it contains only valid, non-null keys and values.""" if data is None: return safe = {} for key, value in data.items(): key = safe_string(key) value = safe_string(value) if key is not None and value is not None: ...
b5ec44dc29c26b36517c2207daeed488acef61d2
68,643
def tp_group(tp_group_df, k): """Function called to find the top k for each time group""" #take the top k from each group tp_group_df = tp_group_df.head(k) #return the total tp in each group return tp_group_df['y_true'].sum()
b6cb7da179d7b5ad54b2d503ee107a2b922e1d8c
68,644
def fixture_async_message() -> AsyncMock: """Fixture""" message = AsyncMock() message.content = "<#!111> + <!222#> + Oh yeah baby!" message.guild.name = "Testing Guild" message.guild.id = 111 message.guild.owner.id = 333 message.author.id = 222 message.author.display_name = "Tester" ...
daa76ac9829ec7d18386b94681a701692f428c9e
68,645
def do_if_app(parser, token): """ An if statement that validates to True if an app is loaded. Example (the else tag is optional): {% if_app "tagging" %} <p>tagging is installed</p> {% else %} <p>tagging is not installed</p> {% endif_app %} """ bits = ...
b1296b5068106b80d918cdf07dfdd5ef1f4fe5b3
68,646
def _table_outlier_overview(dset: "Dataset"): """Generate Dataframe table with overview over number of navigation messages Args: dset: A dataset containing the data. Returns: Dataframe with satellites as indices and following columns: | Name | Description ...
5372460ec8db63e2f5522a3308cd5b24e04b6dfb
68,647
def get_client_ip(rq): """Try to get client's real IP address.""" x_forwarded_for = rq.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',') ip = ip[-1] else: ip = rq.META.get('REMOTE_ADDR') return ip
adae8af8841dad91fb1af9df196b3d424f53d33d
68,648
import logging def get_logger(logger_name, file_name=None, log_level=None, format=FORMAT): """Return an opinionated basic logger named `name` that logs to stdout If you leave the log level argument as None and the logger was not previously instantiated, the level will be set to NOTSET. If the logger ...
eb3ce4970e6eaaa1083a75948d7cc37807593706
68,649
import click def get_plan(api_client, plan_id): """ Workaround for a bug in plans read which causes failure when looking up by plan id """ params = { 'id': plan_id } # Look up the plan res = api_client('plans', 'list', params=params) if res['count'] == 0: raise click.ClickExce...
e22d6dfaecf97fe134462fe06a9d7471cac8b4d9
68,650
def band_atom_orbitals( folder, atom_orbital_pairs, output='band_atom_orbitals.png', spin='up', scale_factor=6, color_list=None, legend=True, linewidth=0.75, band_color='black', figsize=(4, 3), erange=[-6, 6], hse=False, kpath=None, n=None, fontsize=7, sav...
bfc5b589167494cd9e2a1de019fafdfb30897c76
68,651
def sherlockPredict(X: Matrix, cW1: Matrix, cb1: Matrix, cW2: Matrix, cb2: Matrix, cW3: Matrix, cb3: Matrix, wW1: Matrix, wb1: Matrix, wW2: ...
a9ed0c10c07f560588671cd585999da46a756cc8
68,652
import array def calculate_geomean(json): """ Extract all real/cpu times from all the benchmarks as seconds, and calculate their geomean. """ times = [] for benchmark in json['benchmarks']: if 'run_type' in benchmark and benchmark['run_type'] == 'aggregate': continue ...
b402022a31f0296676a3f1a9dc127d5f51c0aa37
68,653
import itertools def _groupby_leading_idxs(shape): """Group the indices for `shape` by the leading indices of `shape`. All dimensions except for the rightmost dimension are used to create groups. A 3d shape will be grouped by the indices for the two leading dimensions. >>> for key, idxs...
cc71304b9da4df2c9a32e009e3159bc9777d3e70
68,654
def _recvall(sock, size): """ Read exactly the specified amount of data from a socket. If a ``recv()`` call returns less than the requested amount, the ``recv()`` is retried until it either returns EOF or all the requested data has been read. :param sock: A socket from which bytes may be read....
6a456ee4925b7faa25646e9bc6e702848d047783
68,655
import argparse def ParseArguments() -> argparse.Namespace: """Parses command line options.""" parser = argparse.ArgumentParser() parser.add_argument('--input') parser.add_argument('--output') parser.add_argument('--work_dir') return parser.parse_args()
6d7bb317f8dd5b98239b8bcbb998f67188c9368f
68,656
import os def load_data(messages_filepath, categories_filepath): """Load & merge messages & categories datasets inputs: messages_filepath: string. Filepath for csv file containing messages dataset. categories_filepath: string. Filepath for csv file containing categories dataset. outpu...
bac9bfec0059745d06459f1022f275d4aed01913
68,657
import torch def rotation_matrix_to_quaternion(rotation_matrix, eps=1e-6): """Convert 3x4 rotation matrix to 4d quaternion vector This algorithm is based on algorithm described in https://github.com/KieranWynn/pyquaternion/blob/master/pyquaternion/quaternion.py#L201 Args: rotation_matrix (Te...
994f1d728502c0298c02f3d74d7a7d39bceab891
68,658
import json import re def change_user_surname(request): """ Create response with prompting user to give his new surname :param request: POST request from "Change user surname" Dialogflow intent :return: JSON with response prompting user to give his new surname """ language = request.data['quer...
e37744262858b7ca197ee42e6f8acb34b40d6bc5
68,659
import re def split_authors(authors_list): """ :param authors_list A list of authors to further split :return A cleaner version of the authors list """ test_split = re.split(",", authors_list) # Remove 'and' or & symbol from the last author if it exists splits = [re.split("and |& | ", x) f...
57f8f8c52ab07baddf9f3410c5be58ef482536ab
68,660
from typing import Callable from typing import Tuple import asyncio def juxt(*funcs: Callable) -> Callable[..., Tuple]: """Create a function that applies each function in :funcs: to its arguments and returns a tuple of the results. >>> inc = lambda x: x + 1 >>> double = lambda x: x * 2 >>> juxt(inc, ...
fd75972b988fa0577ce3e4a9cea38207e10f35b9
68,661
def vectorized_result(j): """Return a 10-dimensional unit vector with a 1.0 in the jth position and zeroes elsewhere. This is used to convert a digit (0...9) into a corresponding desired output from the neural network.""" output_result = np.zeros((10, 1)) output_result[j] = 1.0 return outp...
0b35bb4f6d0172412757fce9d3d05a8eab39410f
68,662
def speed_convert(size): """ Hi human, you can't read bytes? """ power = 2**10 zero = 0 units = {0: "", 1: "Kb/s", 2: "Mb/s", 3: "Gb/s", 4: "Tb/s"} while size > power: size /= power zero += 1 return f"{round(size, 2)} {units[zero]}"
19f6b9dea0c0d151c7a44d7554f42132dedcb29e
68,663
import re def _parse_extract(extract_url: str): """ Parses information from extract. :param extract_url: extract url :type extract_url: str :return: capital base and insolvency """ bs = _open_url(extract_url) capital_base_row = bs.find('span', text=re.compile('(ákladní kapitál|Kmenov...
15a4ca189a16fde3a7fd0feb32bb785111bd21ab
68,664
import collections def sequence_example_batch(mode, batch_size, shuffle=True): """Generates a padded batch of (negated_conjecture, clause, label) examples. Each batch is organized into (positive, negative) pairs of examples from the same proof. Args: mode: Either 'train' or 'eval'. batch_size: Integ...
0fabc9bf42890bd5076dc6887ec6d07f8a353849
68,665
def validate_calculation(calculation): """ Validate that all of the symbols needed for a calculation are defined Args: expression (:obj:`Calculation`) Returns: :obj:`tuple`: * nested :obj:`list` of :obj:`str`: nested list of errors (e.g., required ids missing or ids not unique...
a7596a0ea4b65f30c93c58e3da3d2c4b295e45fc
68,666
def associate_detections_to_trackers_fusion(detections, trackers, iou_threshold): """ Assigns detections to tracked object (both represented as bounding boxes) detections: N x 8 x 3 trackers: M x 8 x 3 Returns 3 lists of matches, unmatched_detections and unmatched_trackers """ dets_8corner = [convert_3dbo...
b24c2e3956cc5bf9e355d13ed207a265e7f4e011
68,667
def get_expected_name(logfile): """get the name of the file with the expected json""" return logfile.with_name(logfile.stem + "-expected.json")
7bc886fdbc23a53610817391db3fccbe53fbab81
68,668
def get_derivative(top_field, bottom_field, ws): """ Return the W object corresponding to a particular derivative in the general covariance equations, with a flag for W- due to its different symmetry and a multiplier (+/- 1). """ # Extract field index and type top_field_idx, top_field_type = to...
434215401c24e8f23cb400825e6621690de67c47
68,669
def string_formulation(model, feature_names, number_words, number_topics, similar_words, levenshtein_distance, pub_year_one, pub_year_two, bert_model, bert_tokenizer, author): """Formulate the search string based on the input parameters. Args: model: Return of the lda_algorithm()...
67e3188cc5fe5b2792132c060945453b1d3af3ab
68,670
def temp_file_name(name=""): """Return string of a full path to a new temporary file name. Args: name: str of name to include in temporary file name. Returns: str of full path to new file name in TMP_DIR """ t = int(time.time()) x = random.randint(0, 1000000) filename = "tmp.%s.%d.%d" % (name, t,...
563d772abe85c964686f0a11e35ddd37371d0f58
68,671
import os import tempfile def _writable_sample_file(file, warn=True, wfun=None): """Check to see if file is writable, if not use temporary file""" if wfun is None: wfun = lambda x, y: '"{}" is not writable; use "{}" instead'.format(x, y) dir = os.path.dirname(file) dir = os.getcwd() if dir == ...
c0c2893c7ab45d979a92815d488e48c9eafe9ca9
68,672
def get_target(name): """Returns the module of the target going by the given name. Returns `None` if the target does not exist.""" return _TARGETS.get(name, None)
819c8417b820a762fbf5f2c1d9419b4584bd8b2a
68,673
def make_login(name: str): """ Makes a login route for an Oauth API. """ def login() -> Response: oauth = cube.make_oauth(name) authorization_url, state = oauth.authorization_url(cube.CONFIG[cube.make_key(name, "url")] + "oauth/authorize") # State is used to prevent CSRF, keep this for ...
356c8c755942367e03de4cb68e943cc1e34b556a
68,674
def figure_to_image(figure): """ @brief Convert a Matplotlib figure to a vtkImageData with RGBA unsigned char channels @param figure A matplotlib figure. @return a vtkImageData with the Matplotlib figure content """ buf = figure_to_data(figure) # Flip rows to be suitable for vtkImageData. buf = buf[::-...
502f61cfd1f9a553da71487aa81e062c57909c4f
68,675
import subprocess def run_local_cmd(cmd, cmd_input=None, log_input=True, log_output=True): """ Run local OS command :param cmd: str, Command to run :param cmd_input: stdin stream :param log_input: bool, True iff log command to debug log :param log_output: bool, True iff log results to debug l...
1d303846d9eefdd5effd308d0a36d1ff190298bb
68,676
def decode(obj): """ Decodes JSON / msgpack objects into the corresponding PhaseMap types. """ return obj
821d72ed0c1fe51441f3ac40e1389ee450241087
68,677
def byte_instruction(name, bytecode, offset): # """ """ slot = bytecode.code[offset + 1] print("{:16s} {:4d}".format(name, slot)) return offset + 2
5a1a95f2d2a7cb6bad05ed3941efdb15c0ec5969
68,678
def conv_with_pools(inputs, output_size, kernel_size, pool_sizes, pooling_type, **kwargs): """Convolution plus 1x1 convolution applied to specified pools. For example we might do a regular convolution with kernel size (3, 1), and pools of sizes [(9, 1), (27, 1)]. Args: inputs: a Tensor...
dd0a2affed21388096963d2029a094611281d206
68,679
def get_free_symbols(s, symbols, free_symbols=None): """ Returns free_symbols present in `s`. """ free_symbols = free_symbols or [] if not isinstance(s, list): if s in symbols: free_symbols.append(s) return free_symbols for i in s: free_symbols = get_free_sym...
873d0bac2fa24db3b4ded6d9d867ca703d0a2314
68,680
def dth_dp(theta_in, data_in): """ Calculate vertical derivative on even (theta) levels. Parameters ---------- theta_in : array_like, 1D Vertical coordinate (potential temperature) data_in : array_like, ND, where data_in.shape[1] == theta_in.shape[0] Data on theta levels Re...
1ad77261410b3f4c927ff6ba0987616effe2c495
68,681
import logging def heartbeat_batch(heartbeats): """Extends build leases in a batch. Args: heartbeats (list of dict): list of builds to update. Each dict is kwargs for heartbeat() method. Returns: List of (build_id, build, exception) tuples. """ build_ids = [h['build_id'] for h in heartbeats] ...
8d800521910ccc48c5e83089d2f3669d1dbfe623
68,682
import pathlib def _check_data(data): """Ensure that data is of appropriate type and return numpy array""" if isinstance(data, np.ndarray): return data.astype(float) elif isinstance(data, (str, pathlib.PosixPath)): data = nib.load(data) elif isinstance(data, (nib.Cifti2Image, nib.Gifti...
9644d4cf570b387049d5cda121ef5470757c35f2
68,683
import tqdm def global_alignment(train_frame, test_frame): """ Calculates the global alignment metric proposed in the paper Smolak et al. (2022) through the application of the Needleman-Wunsch algorithm on sequences for pairwise matching. Returns normalised values. :param train_frame: TrajectoriesFrame class obj...
04d37a3146969dfb6232687abdbbd883e726abf7
68,684
def resnet_v2_152_separable(input_shape, kernel_size=3, include_root=True, weight_decay=1e-4, kernel_initializer="he_normal", bn_epsilon=1e-3, bn_moment...
1bebdde79c66afef44c319de5df3b53caea5879f
68,685
import os def getFiles(dirpath): """ 获取文件 """ file = [] for root, dirs, files in os.walk(dirpath, topdown=False): for name in files: path = os.path.join(root, name) if name.split(".")[-1] in _suffix: file.append(path) return file
2fa561ca5b557c56cfc0fce854d8ba8d33ec084b
68,686
async def aio_wcheck(url: str, timeout: int = 5) -> bool: """If the http status is 200 return true.""" try: async with ClientSession() as session: async with session.get(url, allow_redirects=True, timeout=timeout) as res: return res.status == 200 except ClientError: ...
d375de749080e02a6625e79f4e86febdaa6a8996
68,687
def aggregateGeolevels(spark_session, spark_df, geolevels, verbose=True): """ Take a spark dataframe and aggregate blocks to get geounits at higher geolevels Parameters ========== spark_session : SparkSession Needed for accessing the crosswalk file that joins to the dataframe (if not alread...
748fe5158588579e5a377a5186c7b9e75ddae499
68,688
def new(params={}, lan=None, language=None): """ """ user_object = User(params=params, lan=lan, language=language) user_object.new() if user_object.success: data = { "success": True, "message": user_object.message, ...
b0d54380f5524f9df1268c67bb56c3b6ad86e82f
68,689
import torch def hflip(input): """ Horizontally flip a tensor image or a batch of tensor images. """ w = input.shape[-1] return input[..., torch.arange(w - 1, -1, -1, device=input.device)]
0d0606cc5c1858e574c6ba41130c1feba612aa37
68,690
import ast from typing import List def check_for_unstack(node: ast.Call) -> List: """ Check occurence of the `.unstack()` method on the pandas data frame. Error/warning message to recommend use of `.pivot_table()` method. """ if isinstance(node.func, ast.Attribute) and node.func.attr == "unstack"...
a2796059429486024faa68b930bf1f32ecc9db5c
68,691
def healpixMap(nside, lon, lat, fill_value=0., nest=False): """ Input (lon, lat) in degrees instead of (theta, phi) in radians. Returns HEALPix map at the desired resolution """ lon_median, lat_median = np.median(lon), np.median(lat) max_angsep = np.max(ugali.utils.projector.angsep(lon, lat, l...
c17ab5bce748309a24bc16838db24d2dca87cc9b
68,692
from presqt.targets.gitlab.functions.fetch import gitlab_fetch_resource import requests import base64 import json def gitlab_fetch_keywords(token, resource_id): """ Fetch the keywords of a given resource id. Parameters ---------- token: str User's GitLab token resource_id: str ...
019628d43a5be648b3af2a57fbce9b37f8e178cf
68,693
def add_sp2_hydrogen(site, neighbors, length: float = 1): """convert x-C=z to x-CH-z""" assert len(neighbors) == 2 vector0 = make_vec(neighbors[0].site.coords, site.coords) vector1 = make_vec(neighbors[1].site.coords, site.coords) summed = vector0 + vector1 summed = summed / np.linalg.norm(summ...
937fa93d780addc59524d0c4fe06ef35f744c509
68,694
from typing import Dict import json def replace_function(text:str) -> Dict: """Replaces given keyword with the corresponding value within the database Args: keyword (str): Text to be replaced. Returns: Dict: Replaced value in following format. {'result':'[Replacement]'} """ try: with ope...
a462d0e7a821aeb449e9223cbc3aebcf40cc93f3
68,695
import subprocess def get_container_names_per_pod(pod_namespace, pod_name, init_containers=True): """Return the list of container names in the given pod""" cmd = "kubectl get pods {} -n {} " \ "-o jsonpath='{} {}'".format( pod_name, pod_namespace, "{.spec.containers[*].name}", ...
633789b771c4e5e85d96abd99f3974d9afc84f10
68,696
def ok_resp(data, message=None): """Return a SuccessResponse with success=True and data""" return BasicResponse(True, message=message, data=data)
b1c9f2aff61df4a135c9531e467d297b9a252bbf
68,697
def compute_prediction_interval(model, data_eval, percentile=95): """ A function that compute the prediction interval based on the predictions of each trees of a random forest. Parameters ---------- model: a fitted RandomForestRegressor. data_eval: A panda or numpy matrix of da...
dc7aae7283847b64437d78e9b7d1649b9b32b3a1
68,698
def logistic(y): """ Function for calculating sigmoid activation. """ try: return 1. / (1. + cumath.exp(-y)) except RuntimeWarning: raise Exception("Overflow Encountered. Check your model!")
2eb7ba05fee8e2121b7863ad418a894fa4140a69
68,699