content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _aggregate_pop_simplified_comix( pop: pd.Series, target: pd.DataFrame ) -> pd.DataFrame: """ Aggregates the population matrix based on the CoMix table. :param pop: 1-year based population :param target: target dataframe we will want to multiply or divide with :return: Retuns a dataframe tha...
11ddfb103c95416b1a93577f90e12aa6159123eb
21,900
def authenticate(): """ Uses HTTP basic authentication to generate an authentication token. Any resource that requires authentication can use either basic auth or this token. """ token = serialize_token(basic_auth.current_user()) response = {'token': token.decode('ascii')} return jsonify(response)
adfd4d80bb08c6a0c3175495b4b2ab1aa0b898c6
21,901
import torch def split_image(image, N): """ image: (B, C, W, H) """ batches = [] for i in list(torch.split(image, N, dim=2)): batches.extend(list(torch.split(i, N, dim=3))) return batches
da51c3520dfee740a36d5e0241f3fd46a07f2752
21,902
def _upsample_add(x, y): """Upsample and add two feature maps. Args: x: (Variable) top feature map to be upsampled. y: (Variable) lateral feature map. Returns: (Variable) added feature map. Note in PyTorch, when input size is odd, the upsampled feature map with `F.upsample(..., sca...
facac22b50906509138a479074a7744b737d554d
21,903
def get_eta_and_mu(alpha): """Get the value of eta and mu. See (4.46) of the PhD thesis of J.-M. Battini. Parameters ---------- alpha: float the angle of the rotation. Returns ------- The first coefficient eta: float. The second coefficient mu: float. """ if alpha == 0...
4f1a215a52deda250827d4ad3d06f8731c69dc9d
21,904
def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to fi...
3d1c1ab7b2f346dab0fe3f01a262983c880eda34
21,905
def write_error_row(rowNum, errInfo): """Google Sheets API Code. Writes all team news link data from RSS feed to the NFL Team Articles speadsheet. https://docs.google.com/spreadsheets/d/1XiOZWw3S__3l20Fo0LzpMmnro9NYDulJtMko09KsZJQ/edit#gid=0 """ credentials = get_credentials() http = credential...
5a3d071d78656f6991103cac72c7ce46f025d689
21,906
import json def get_last_transaction(): """ return last transaction form blockchain """ try: transaction = w3.eth.get_transaction_by_block(w3.eth.blockNumber, 0) tx_dict = dict(transaction) tx_json = json.dumps(tx_dict, cls=HexJsonEncoder) return tx_json except Exception as...
89a70c474670b6e691fde8424ffc78b739ee415e
21,907
def get_tp_model() -> TargetPlatformModel: """ A method that generates a default target platform model, with base 8-bit quantization configuration and 8, 4, 2 bits configuration list for mixed-precision quantization. NOTE: in order to generate a target platform model with different configurations but wi...
5a501f18a090927f7aeba9883f3676ede595944c
21,908
import os def IsARepoRoot(directory): """Returns True if directory is the root of a repo checkout.""" return os.path.exists( os.path.join(os.path.realpath(os.path.expanduser(directory)), '.repo'))
b7b5fd57907c98835f4962ab095ed11cdd4975a4
21,909
from typing import Optional def check_sparv_version() -> Optional[bool]: """Check if the Sparv data dir is outdated. Returns: True if up to date, False if outdated, None if version file is missing. """ data_dir = paths.get_data_path() version_file = (data_dir / VERSION_FILE) if versio...
2c2ebeee0ad0c8a08c841b594ca45676a22407d7
21,910
def grav_n(expt_name, num_samples, num_particles, T_max, dt, srate, noise_std, seed): """2-body gravitational problem""" ##### ENERGY ##### def potential_energy(state): '''U=sum_i,j>i G m_i m_j / r_ij''' tot_energy = np.zeros((1, 1, state.shape[2])) for i in range(state.shape[0]): ...
05f8aa5f6b864440a8a69be35f23d3938114e133
21,911
def fit_spline_linear_extrapolation(cumul_observations, smoothing_fun=simple_mirroring, smoothed_dat=[], plotf=False, smoothep=True, smooth=0.5, ns=3, H=7): """ Linear extrapolation by splines on log daily cases Input: cumul_observations: cumulative observations, ...
62c0feacf87096a3889e63a2193bc93092b9dc02
21,912
def compute_dl_target(location): """ When the location is empty, set the location path to /usr/sys/inst.images return: return code : 0 - OK 1 - if error dl_target value or msg in case of error """ if not location or not location.strip(): loc = "...
419b9fcad59ca12b54ad981a9f3b265620a22ab1
21,913
def hz_to_angstrom(frequency): """Convert a frequency in Hz to a wavelength in Angstroms. Parameters ---------- frequency: float The frequency in Hz. Returns ------- The wavelength in Angstroms. """ return C / frequency / ANGSTROM
9fed63f7933c6d957a35de7244464d0303abf3ce
21,914
from re import T def is_literal(token): """ リテラル判定(文字列・数値) """ return token.ttype in T.Literal
46527a24660f8544951b999ec556a4cf12204087
21,915
def PutObject(*, session, bucket, key, content, type_="application/octet-stream"): """Saves data to S3 under specified filename and bucketname :param session: The session to use for AWS connection :type session: boto3.session.Session :param bucket: Name of bucket :type bucket: str :param key: Name of file ...
908581b7d61c3cce9a976b03a0bf7d3ed8c691ca
21,916
from io import StringIO def insert_sequences_into_tree(aln, moltype, params={}, write_log=True): """Returns a tree from Alignment object aln. aln: an xxx.Alignment object, or data that can be used to build one. moltype: cogent.core.moltype.MolType object p...
d81167b49f2e375f17a227d708d5115af5d18549
21,917
from azure.cli.core.azclierror import CLIInternalError def billing_invoice_download(client, account_name=None, invoice_name=None, download_token=None, download_urls=None): """ Get URL to downloa...
a75326953188e0aaf0145ceeaa791460ec0c0823
21,918
import re def find_classes(text): """ find line that contains a top-level open brace then look for class { in that line """ nest_level = 0 brace_re = re.compile("[\{\}]") classname_re = "[\w\<\>\:]+" class_re = re.compile( "(?:class|struct)\s*(\w+)\s*(?:\:\s*public\s*" ...
126bc091a809e152c3d447ffdd103c764bc6c9ac
21,919
def kineticEnergyCOM(robot : object, symbolic = False): """This function calculates the total kinetic energy, with respect to each center of mass, given linear and angular velocities Args: robot (object): serial robot (this won't work with other type of robots) symbolic (bool, optional): used t...
5f0559e55a389741ad0591b5ac3f220ffdb76a2c
21,920
def get_input(request) -> str: """Get the input song from the request form.""" return request.form.get('input')
de237dc0ad3ce2fa6312dc6ba0ea9fe1c2bdbeb3
21,921
from typing import Hashable import math def _unit_circle_positions(item_counts: dict[Hashable, tuple[int, int]], radius=0.45, center_x=0.5, center_y=0.5) -> dict[Hashable, tuple[float, float]]: """ computes equally spaced points on a circle based on the radius and center positions ...
66f60f5b90f7825f2abfdd2484375c9558786250
21,922
import re def rate_table_download(request, table_id): """ Download a calcification rate table as CSV. """ def render_permission_error(request, message): return render(request, 'permission_denied.html', dict(error=message)) table_permission_error_message = \ f"You don't have permis...
d62eb09d11c0e91cca3eb36388f1165e2a4433ee
21,923
from os.path import normpath, sep def normalize_path(path): """ Normalize a pathname by collapsing redundant separators and up-level references """ result = normpath(path) result = result.replace("/",sep) result = result.replace("\\",sep) return adapt_path(result)
e422a76e1fe19401db34dfe80ff1d8ce2f411af2
21,924
def rgb_to_RGB255(rgb: RGBTuple) -> RGB255Tuple: """ Convert from Color.rgb's 0-1 range to ANSI RGB (0-255) range. >>> rgb_to_RGB255((1, 0.5, 0)) (255, 128, 0) """ return tuple([int(round(map_interval(0, 1, 0, 255, c))) for c in rgb])
1fe460a4716244efbbacbc6d44f10a3fc6ba8d3f
21,925
import requests import re def check_rest_version(host="http://www.compbio.dundee.ac.uk/jpred4/cgi-bin/rest", suffix="version", silent=False): """Check version of JPred REST interface. :param str host: JPred host address. :param str suffix: Host address suffix. :param silent: Should the work be done s...
f9c5e858e4a4681d8b5045e8ed08738f1c32016a
21,926
def analyzer_options(*args): """ analyzer_options() Allow the user to set analyzer options. (show a dialog box) ( 'ui_analyzer_options' ) """ return _ida_kernwin.analyzer_options(*args)
e0b78523d32cce303fe8048012ae1e57c7c422bd
21,927
import torch def vector_vector_feature(v_a, v_b, weight, p_idx, frames, symmetric): """ Taking outer product, create matrix feature per pair, average, express in SO2 feature. :param v_a: [E, 3] :param v_b: [E, 3] :param weight: [E] :param p_idx: [E] index [0, V) :param frames: [V, 3, 3] ...
6b583cc834d79d463fc5e6b68b98cd027c4969ec
21,928
def parse_steps(filename): """ Read each line of FILENAME and return a dict where the key is the step and the value is a list of prerequisite steps. """ steps = defaultdict(lambda: list()) all_steps = set() with open(filename) as f: for line in f: words = line.split(' ') ...
450d93cb72cf92c186cbcecc1992c6e4391ca428
21,929
import glob import json def sitestructure(config, path, extra): """Read all markdown files and make a site structure file""" # no error handling here, because compile_page has it entire_site = list() for page in glob.iglob(path + '**/*.md', recursive=True): merged = compile_page(None, config, page, extra) if...
6c7d21bce30ebb418a8146f302ce62bbe0386bbf
21,930
import uuid def _create_component(tag_name, allow_children=True, callbacks=[]): """ Create a component for an HTML Tag Examples: >>> marquee = _create_component('marquee') >>> marquee('woohoo') <marquee>woohoo</marquee> """ def _component(*children, **kwargs): if 'c...
a11572de6d079b35ffe0492154939cceb953b199
21,931
def typeof(val, purpose=Purpose.argument): """ Get the Numba type of a Python value for the given purpose. """ # Note the behaviour for Purpose.argument must match _typeof.c. c = _TypeofContext(purpose) ty = typeof_impl(val, c) if ty is None: msg = _termcolor.errmsg( "can...
83d8e84fca58ce78b15e9106a14ff95c86ccac68
21,932
import logging def scale_site_by_jobslots(df, target_score, jobslot_col=Metric.JOBSLOT_COUNT.value, count_col=Metric.NODE_COUNT.value): """ Scale a resource environment (data frame with node type information) to the supplied share. This method uses the number of jobslots in each node as a target metric. ...
c46129ebf4761fbcb7c3e40165c83259d0eb24e0
21,933
def primesfrom2to(n): """Input n>=6, Returns a array of primes, 2 <= p < n""" sieve = np.ones(n / 3 + (n % 6 == 2), dtype=np.bool) sieve[0] = False for i in xrange(int(n ** 0.5) / 3 + 1): if sieve[i]: k = 3 * i + 1 | 1 sieve[((k * k) / 3)::2 * k] = False sieve[(k * k + 4 * k - 2 * k * (i &...
e66a8dd1bb23f1aab8786d4832e382d07e5973e0
21,934
import subprocess def file_types_diff(cwd, old_ver, new_ver): """ NB: Uses Git and the magic/ directory Select only files that are Copied (C), Modified (M), Renamed (R), have their type (i.e. regular file, symlink, submodule, ...) changed (T) Returns a list of changed file types! """ # diff only...
47ddee3bd7bfe0cbeb1af642016f3836900cd0a9
21,935
import time def TimeFromTicks(ticks): """construct an object holding a time value from the given ticks value.""" return Time(*time.localtime(ticks)[3:6])
96651ff5e0da5e88988640b5e3f544ad82dd90b2
21,936
def check_key_exists(file_location, section, key): """ Searches an INI Configuration file for the existance of a section & key :param file_location: The file to get a key value from :param section: The section to find the key value :param key: The key that can contain a value to retrieve :retur...
afdc8bad295cd2b0ed0576eab0ff633fb1f854b3
21,937
def replace_na(str_value: str, ch: str = "0") -> str: """replaces \"0\" with na, specifically designed for category list, may not work for others need Args: str_value (str): category list ch (str, optional): Replacemet char. Defaults to "0". Returns: str: clean cotegory name ""...
d8e6dfe6806c7a008163ba92c62e7b2b18633538
21,938
def intent_requires(): """ This view encapsulates the method get_intent_requirement It requires an Intent. :return: A dict containing the different entities required for an Intent """ data = request.get_json() if "intent" in data: return kg.get_intent_requirements(data["intent"]) ...
75901abc3d0833eba39c229cc35249c8cb3e6162
21,939
def standardize_df_off_tr(df_tr:pd.DataFrame, df_te:pd.DataFrame): """Standardize dataframes from a training and testing frame, where the means and standard deviations that are calculated from the training dataset. """ for key in df_tr.keys(): if key != 'target': ...
04438b7f31efbe80129ef1cda488ea3c93bcf55e
21,940
def filter_clusters(aoi_clusters, min_ratio, max_deviation, message, run=None): """ min_ratio: Has to have more than x % of all dots in the corner within the cluster max_deviation: Should not deviate more than x % of the screen size from the respective AO...
2767afd05093e364cf6be22b98b4821c6811165e
21,941
def set_to_true(): """matches v1, which assign True to v1""" key = yield symbol res = Assign(key, True) return res
e1a8eb62be409252475ad39d9d72a087b0344f9f
21,942
def fit_spectrum(spectrum, lineshapes, params, amps, bounds, ampbounds, centers, rIDs, box_width, error_flag, verb=True, **kw): """ Fit a NMR spectrum by regions which contain one or more peaks. Parameters ---------- spectrum : array_like NMR data. ndarray or emulated type...
e13959eb2fbca2146172d9c1f345c2715d28471b
21,943
def d1_to_q1(A, b, mapper, cnt, M): """ Constraints for d1 to q1 """ for key in mapper['ck'].keys(): for i in range(M): for j in range(i, M): # hermetian constraints if i != j: A[cnt, mapper['ck'][key](i, j)] += 0.5 ...
1ee9ec17f4464ef280aa22780d6034309941954e
21,944
import argparse import logging def handle_args(): """ Gathers commmand line options and sets up logging according to the verbose param. Returns the parsed args """ parser = argparse.ArgumentParser(description='Checks the queue for new messages and caclulates the calendar as needed') parser.add_argument('...
cb01af59300841c96fda7b1a78a7d4f671a127e3
21,945
import os def relative_of(base_path: str, relative_path: str) -> str: """Given a base file and path relative to it, get full path of it""" return os.path.normpath(os.path.join(os.path.dirname(base_path), relative_path))
b35e580ff2afc4cf196f6e53eedd5f4383579c6e
21,946
from typing import OrderedDict def _get_dict_roi(directory=None): """Get all available images with ROI bounding box. Returns ------- dict : {<image_id>: <ROI file path>} """ d = OrderedDict() for f in listdir(directory or IJ_ROI_DIR): d[splitext(f)[0]] = join(directory or...
56c2b6a8cb3cb296489050a5465e19e6829ee383
21,947
from operator import index def geol_units(img, lon_w, lat, legend=None): """Get geological units based on (lon, lat) coordinates. Parameters ---------- img: 2d-array 2D geol map image centered at 180°. lon_w: float or array Point west longitude(s). lat: float or array ...
d564ee29139d6a8c5d2235da10acb11b24866d80
21,948
def Water_Mask(shape_lsc,Reflect): """ Calculates the water and cloud mask """ mask = np.zeros((shape_lsc[1], shape_lsc[0])) mask[np.logical_and(Reflect[:, :, 3] < Reflect[:, :, 2], Reflect[:, :, 4] < Reflect[:, :, 1])] = 1.0 water_mask_temp = np.copy(mask) retur...
6bcf7b4a96c4de9938c1520253d81460dd7a8025
21,949
from typing import Iterable from typing import Tuple from typing import Any from functools import reduce def unzip(sequence: Iterable) -> Tuple[Any]: """Opposite of zip. Unzip is shallow. >>> unzip([[1,'a'], [2,'b'], [3,'c']]) ((1, 2, 3), ('a', 'b', 'c')) >>> unzip([ [1,'a','A'], [2, 'b','B'], [3,'c'...
8f1b71b2dfc4d6e67729e0aac012031579956d81
21,950
def get_gs_distortion(dict_energies: dict): """Calculates energy difference between Unperturbed structure and most favourable distortion. Returns energy drop of the ground-state relative to Unperturbed (in eV) and the BDM distortion that lead to ground-state. Args: dict_energies (dict): ...
2f23103ccac8e801cb6c2c4aff1fb4fc08341e78
21,951
def parse_accept_language(data: str = None): """Parse HTTP header `Accept-Language` Returns a tuple like below: ``` ((1.0, Locale('zh_Hant_TW')), (0.9, Locale('en')), (0.0, _fallback_ns)) ``` """ langs = {(0.0, _fallback_ns)} if data is None: return tuple(langs) for s in d...
fd2d9aef4825dc0d7fd7a84b69391c69353e9f86
21,952
def stop_service(): """ Stopping the service """ global __service_thread dbg("Trying to stop service thread") shutdown_service() __service_thread.join() __service_thread = None info("Server stopped") return True
97f7b9fb60a7a271f3c234be43b2b513c42ce77e
21,953
def get_constants_name_from_value(constant_dict, value) : """ @param constant_dict : constant dictionary to consider @param value : value's constant name to retrieve @rtype : a string """ try: return constant_dict[value] except KeyError: log.error("The c...
3848e3e83946196250f3987a976b5a74da016a34
21,954
def rotxyz(x_ang,y_ang,z_ang): """Creates a 3x3 numpy rotation matrix from three rotations done in the order of x, y, and z in the local coordinate frame as it rotates. The three columns represent the new basis vectors in the global coordinate system of a coordinate system rotated by this matrix. ...
779c4ca37d5636ad7cff38d9200a9b50b3b0fffe
21,955
def hpdi(proba, array): """ Give the highest posterior density interval. For example, the 95% HPDI is a lower bound and upper bound such that: 1. they contain 95% probability, and 2. in total, have higher peaks than any other bound. Parameters: proba: float A value b...
a417b6adba19ef6206326791250c880e3b2a28a1
21,956
import matplotlib.pyplot as plt import numpy as np from scipy.signal import find_peaks def PAMI_for_delay(ts, n = 5, plotting = False): """This function calculates the mutual information between permutations with tau = 1 and tau = delay Args: ts (array): Time series (1d). Kwargs: pl...
fd681ba0e3121be8ac709c2dc1f4d3a36358f84a
21,957
import urllib def _capabilities(repo, proto): """return a list of capabilities for a repo This function exists to allow extensions to easily wrap capabilities computation - returns a lists: easy to alter - change done here will be propagated to both `capabilities` and `hello` command witho...
764c59bbbe525b8d825dfded871643bb88a1588f
21,958
import types from typing import Dict import collections def dep(doclike: types.DocLike) -> Dict[str, int]: """ Count the number of times each syntactic dependency relation appears as a token annotation in ``doclike``. Args: doclike Returns: Mapping of dependency relation to count...
e4fcb5a54578b2b001eda4255cd3a22b89a6d195
21,959
def fix_phonology_table(engine, phonology_table, phonologybackup_table, user_table): """Give each phonology UUID and modifier_id values; also give the phonology backups of existing phonologies UUID values. """ print_('Fixing the phonology table ... ') msgs = [] #engine.execute('set names latin1...
746ca4a479b450f3320b4c04a3ce6013beb88ed4
21,960
def D(field, dynkin): """A derivative. Returns a new field with additional dotted and undotted indices. Example: >>> D(L, "01") DL(01001)(-1/2) >>> D(L, "21") DL(21001)(-1/2) """ undotted_delta = int(dynkin[0]) - field.dynkin_ints[0] dotted_delta = int(dynkin[1]) ...
1ee408a8cc2923b141c5ffe1c41d919a501111ae
21,961
def _det(m, n): """Recursive calculation of matrix determinant""" """utilizing cofactors""" sgn = 1 Det = 0 if n == 1: return m[0][0] cofact = [n*[0] for i in range(n)] for i in range(n): _get_cofact(m, cofact,0,i,n); Det += sgn*m[0][i]*_det(cofact, n - 1); ...
9019dd9dc1054fc4c36e72a6e3c9a3c478afa4ad
21,962
from typing import List def get_vcps() -> List[LinuxVCP]: """ Interrogates I2C buses to determine if they are DDC-CI capable. Returns: List of all VCPs detected. """ vcps = [] # iterate I2C devices for device in pyudev.Context().list_devices(subsystem="i2c"): vcp = LinuxV...
ce3766c695fe9ffb0a6ebcced4ac04808987f340
21,963
def toGoatLatin(S): """ :type S: str :rtype: str """ l_words = [] for i, word in enumerate(S.split()): if not is_vowel(word[0]): word = word[1:] + word[0] aa = "a" * (i + 1) l_words.append(word + "ma" + aa) return " ".join(l_words)
5ed41084a0d35d69e65b2821b43c2373cf289d26
21,964
def list_startswith(_list, lstart): """ Check if a list (_list) starts with all the items from another list (lstart) :param _list: list :param lstart: list :return: bool, True if _list starts with all the items of lstart. """ if _list is None: return False lenlist = len(_list) ...
6f8952a80da81381464521fec55abaaee4a04881
21,965
import os import warnings def _get_default_scheduler(): """Determine which scheduler system is being used. It tries to determine it by running both PBS and SLURM commands. If both are available then one needs to set an environment variable called 'SCHEDULER_SYSTEM' which is either 'PBS' or 'SLURM'. ...
6a8d6518d7e9b561f763a9268fc3557e09db3fb5
21,966
def get_subscribers(subreddit_, *args): """Gets current sub count for one or more subreddits. Inputs ------- str: Desired subreddit name(s) Returns ------- int: sub count or dict:{subreddit: int(sub count)} """ if len(args) > 0: subreddit = reddit.subreddit(subreddit_) ...
2648eb7db5fe0ebc9940f714fab8770947960463
21,967
def pattern_match(value, pattern, env=None): """ Pattern match a value and a pattern. Args: value: the value to pattern-match on pattern: a pattern, consisting of literals and/or locally bound variables env: a dictionary of local variables bound while matching ...
145ef26283f4e21f7ab763317174c5e6da043d84
21,968
import sys import heapq def dijkstra(adjacency_list, source_vertex, cull_distance = sys.maxsize): """ Implementation of Dijkstra's Algorithm for finding shortest path to all vertices in a graph. Parameters ---------- adjacency_list (dict of int : (dict of int : int)) Maps vertices to ...
067ecb9a0dd94631fb252ad98c1aae59d33e592f
21,969
import os def process_existing_fiber(country): """ Load and process existing fiber data. Parameters ---------- country : dict Contains all country specfic information. """ iso3 = country['iso3'] iso2 = country['iso2'].lower() folder = os.path.join(DATA_INTERMEDIATE, iso3...
77d6c034a48f1ca54e17227d55287ed308f53579
21,970
import functools import six def wraps(wrapped): """A functools.wraps helper that handles partial objects on Python 2.""" # https://github.com/google/pytype/issues/322 if isinstance(wrapped, functools.partial): # pytype: disable=wrong-arg-types return six.wraps(wrapped, assigned=_PARTIAL_VALID_ASS...
8e3762c9d7f50c8e26df0f0de545de7991d59e92
21,971
def byte_to_bits(byte): """Convert a byte to an tuple of 8 bits for use in Merkle-Hellman. The first element of the returned tuple is the most significant bit. Usage:: byte_to_bits(65) # => [0, 1, 0, 0, 0, 0, 0, 1] byte_to_bits(b'ABC'[0]) # => [0, 1, 0, 0, 0, 0, 0, 1] byte_to_bit...
231272c60a3d06de0a914b38fee4f50a0209bcd4
21,972
def KK_RC48_fit(params, w, t_values): """ Kramers-Kronig Function: -RC- Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ Rs = params["Rs"] R1 = params["R1"] R2 = params["R2"] R3 = params["R3"] R4 = params["R4"] R5 = params["R5"] R6 = params["R6"] ...
1395f182880db7f42d43eba05605673eab83770b
21,973
def race(deer, seconds): """ Use the reindeer's speed and rest times to find the timed distance """ distance = 0 stats = reindeer[deer] resting = False while True: if resting: if seconds <= stats[2]: break seconds -= stats[2] else: ...
ea7cb0577cdfa4aab558ca8ad6f4ddde2d79e996
21,974
def AsdlEqual(left, right): """Check if generated ASDL instances are equal. We don't use equality in the actual code, so this is relegated to test_lib. """ if left is None and right is None: return True if isinstance(left, (int, str, bool, pybase.SimpleObj)): return left == right if isinstance(le...
ac5752cd30ff31488ecc000426b6f2430acb1718
21,975
def FindPriority(bug_entry): """Finds and returns the priority of a provided bug entry. Args: bug_entry: The provided bug, a IssueEntry instance. Returns: A string containg the priority of the bug ("1", "2", etc...) """ priority = '' for label in bug_entry.label: if label.text.lower().startswi...
a56838fd90b0e46048e5e39c66e5bcb429270c21
21,976
import torch def attention_padding_mask(q, k, padding_index=0): """Generate mask tensor for padding value Args: q (Tensor): (B, T_q) k (Tensor): (B, T_k) padding_index (int): padding index. Default: 0 Returns: (torch.BoolTensor): Mask with shape (B, T_q, T_k). True element ...
49d1dc8dd4e59284eb090711545cf70c9ba5fad4
21,977
import sys def get_pcap_bytes(pcap_file): """Get the raw bytes of a pcap file or stdin.""" if pcap_file == "-": pcap_bytes = sys.stdin.buffer.read() else: with open(pcap_file, "rb") as f: pcap_bytes = f.read() return pcap_bytes
51abbefeb918016edef6f8f40c7c40cb973e2fc0
21,978
import subprocess def run(s, output_cmd=True, stdout=False): """Runs a subprocess.""" if output_cmd: print(f"Running: {s}") p_out = subprocess.run( s, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, check=False ) if stdout: return p_out.stdout.decode("utf-8")...
efcfe30a536789a69662642d2b2da1afc04ebe57
21,979
import itertools def process_params(request, standard_params=STANDARD_QUERY_PARAMS, filter_fields=None, defaults=None): """Parse query params. Parses, validates, and converts query into a consistent format. :keyword request: the bottle request :keyword standard_params: query param...
06de4c5df0bdcfcc091aefa12cc8aa7fd4c06597
21,980
import inspect def all_attributes(cls): """ Each object will have the attributes declared directly on the object in the attrs dictionary. In addition there may be attributes declared by a particular object's parent classes. This function walks the class hierarchy to collect the attrs in the object's p...
3d1a1013fe36cef776b6a9842f774f5394aaeff5
21,981
def _reshape_model_inputs(model_inputs: np.ndarray, num_trajectories: int, trajectory_size: int) -> np.ndarray: """Reshapes the model inputs' matrix. Parameters ---------- model_inputs: np.ndarray Matrix of model inputs num_trajectories: int Number of traje...
2562d143c5dbf7b6c1c018afe2f87df6297752da
21,982
from types import ModuleType import sys def _create_module(module_name): """ex. mod = _create_module('tenjin.util')""" mod = ModuleType(module_name.split('.')[-1]) sys.modules[module_name] = mod return mod
bfc1092bce61f7716a42ceeccc0604ced3696cdd
21,983
def VIS(img, **normalization): """Unmixes according to the Vegetation-Impervious-Soil (VIS) approach. Args: img: the ee.Image to unmix. **normalization: keyword arguments to pass to fractionalCover(), like shade_normalize=True. Returns: unmixed: a 3-band image file in o...
2c85aa894f6ccfae3da8650cb9c32cc125a19a45
21,984
def create_labels(mapfile, Nodes=None): """ Mapping from the protein identifier to the group Format : ##protein start_position end_position orthologous_group protein_annotation :param Nodes: set -- create mapping only for these set of nodes :param mapfile: file that contains the...
634eefc5a837e484059278939ba34fd2482846bf
21,985
import os import json def provide(annotation_path=None, images_dir=None): """Return image_paths and class labels. Args: annotation_path: Path to an anotation's .json file. images_dir: Path to images directory. Returns: image_files: A list containing the paths of i...
02fd2584568bdaedbb1a605b30092ceb462948f4
21,986
def sortKSUID(ksuidList): """ sorts a list of ksuids by their date (recent in the front) """ return sorted(ksuidList, key=lambda x: x.getTimestamp(), reverse=False)
0476bc0ef19f8730488041ac33598ba7471f96e7
21,987
import os def is_installable_dir(path): # type: (str) -> bool """Return True if `path` is a directory containing a setup.py file.""" if not os.path.isdir(path): return False setup_py = os.path.join(path, "setup.py") if os.path.isfile(setup_py): return True return False
b80929ac5ea558064bbcb3e47754c24cc548e478
21,988
from typing import Counter def get_vocabulary(list_): """ Computes the vocabulary for the provided list of sentences :param list_: a list of sentences (strings) :return: a dictionary with key, val = word, count and a sorted list, by count, of all the words """ all_the_words = [] for tex...
d6c357a5768c2c784c7dfe97743d34795b2695c0
21,989
import logging def lod_build_config(slurm_nodes, mds_list, oss_list, fsname, mdtdevs, ostdevs, inet, mountpoint, index): """ Build lod configuration for LOD instance """ # pylint: disable=too-many-arguments,too-many-locals,too-many-branches # take slurm nodes directly if found...
dc17de21a64409425192d8e660124b396f7a743f
21,990
def check_field(rule: tuple, field: int) -> bool: """check if a field is valid given a rule""" for min_range, max_range in rule: if min_range <= field <= max_range: return True return False
32e34da10fff12e765dd6d48472acf0ac5ad72af
21,991
import math def split(value, precision=1): """ Split `value` into value and "exponent-of-10", where "exponent-of-10" is a multiple of 3. This corresponds to SI prefixes. Returns tuple, where the second value is the "exponent-of-10" and the first value is `value` divided by the "exponent-of-10". ...
776ded073807773b755dcd7ab20c47d1f33ca1e1
21,992
import os import json def load_settings(): """Load JSON data from settings file :return: dictionary with settings details :rtype: dict """ if os.path.exists(config.SETTINGS_FILE): with open(config.SETTINGS_FILE, 'r') as sfile: settings = json.loads(sfile.read()) else: ...
2b13eb5f671f88cd0883a20f99d4d80aa346cd29
21,993
import requests def test_cert(host, port=443, timeout=5, **kwargs): """Test that a cert is valid on a site. Args: host (:obj:`str`): hostname to connect to. can be any of: "scheme://host:port", "scheme://host", or "host". port (:obj:`str`, optional): port t...
3d0e0098b5f654305c187f2a566c25f8c87a5ce3
21,994
def get_predicates(): # noqa: E501 """get_predicates Get a list of predicates used in statements issued by the knowledge source # noqa: E501 :rtype: List[BeaconPredicate] """ return controller_impl.get_predicates()
7f3f89b300a0e43449a1860cff8200af6d33a3b1
21,995
def noisy_job_stage3(aht, ht, zz, exact=False): """Adds noise to decoding circuit. Args: ===== aht, ht, zz : numeric Circuit parameters for decoding circuit exact : bool If True, works with wavefunction Returns: ======== noisy_circuit : cirq.Circuit Noisy versio...
a5f1bcb8cced41b2b6179d2eeb68e8b8939aca96
21,996
import math def buy_and_hold_manager_factory(mgr, j:int, y, s:dict, e=1000): """ Ignores manager preference except every j data points For this to make any sense, 'y' must be changes in log prices. For this to be efficient, the manager must respect the "e" convention. That is, the ...
2225b6f41979e1781a778f397b699751456dc2a4
21,997
def explicit_wait_visibility_of_element_located(browser, xpath, timeout=35): """Explicitly wait until visibility on element.""" locator = (By.XPATH, xpath) condition = expected_conditions.visibility_of_element_located(locator) try: wait = WebDriverWait(browser, timeout) result = wait.un...
2fd6fe951d1d55121909e2a326b72af4524f577b
21,998
def list_all_resources(): """Return a list of all known resources. :param start_timestamp: Limits resources by last update time >= this value. (optional) :type start_timestamp: ISO date in UTC :param end_timestamp: Limits resources by last update time < this value. (optional) :type ...
c2b42abd7c03d2f2b6541a45b7b45b2cb420ebc4
21,999