content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
async def get_health(): """ Check health of service. """ return {"status": "OK"}
17a8c5f7f96bff26a7044fcd0c785c438272e2b4
642,649
def titleType(dataFrame): """ Count how many series and movies exists in the dataFrame. Used for mostWatchedType visualization Parameters: dataFrame: string The name of the dataFrame the user wants to work with. Returns: a dataFrame """ dataFrameTypeCount = da...
865c4d1654592bad9f01ce67f3e9d23559d322f7
642,650
def to_bytes(string): """Converts a string with a human-readable byte size to a number of bytes. Takes strings like '7536 kB', in the format of proc.""" num, units = string.split() num = int(num) powers = {'kb': 10, 'mb': 20, 'gb': 30} if units and units.lower() in powers: num <<= power...
adfdb4dbdb175f012714390a48b04aec9bfcc705
642,651
def format_as(format_string): """format_as(form)(obj) = form % obj Useful to format many objects with the same format string. >>> list(map(format_as("0x%x"), [0, 1, 10, 11, 15])) ['0x0', '0x1', '0xa', '0xb', '0xf'] """ return lambda obj : format_string % obj
ad2e02106b32b2157c6c026f8031120f3d16fe1e
642,652
from typing import List from typing import Any import random def generate_random_batches(values: List[Any], min_batch_size: int, max_batch_size: int) -> List[List[Any]]: """ Generate random batches of elements in values without replacement and return the list of all batches. Batch sizes can be anything be...
ab122041de32fb731251dacc5cfac77888e8ae03
642,653
import os def _fo_apex(fpath, _): """Opens a regular file in append mode, raises an error if it doesn't exists""" return os.open(fpath, os.O_WRONLY | os.O_APPEND)
b7379d61aa1929d286356efad3afec2f7a7a7f73
642,654
def group_by(l, column, comp_margin=None): """ Groups list entities by column values. """ sorted_values = [] result_list = [] current_value = None for i in range(0, len(l)): x = l[i] if x[column][0:comp_margin] in sorted_values or x[column][0:comp_margin] == current_value: ...
9807985fcca0dc8f690fdacfa747ca5c84c524ae
642,655
import os def gather_images(root, imtype="jpg"): """ Recursively find all the images within a root directory. Returns a list of strings. :root: string; path to root directory """ imfiles = [] for root, directories, filenames in os.walk("DCIM/"): for filename in filenames: ...
629303b01c845a12956bad90463cbc7b088ddffb
642,656
from typing import Optional import typing import sys def line_buffer_from_input(input_stream: Optional[typing.IO] = None) -> bool: """ Return whether line buffering should be enabled for a given input stream. When data is being read from an input stream, processed somehow, and then written to an auto...
4699a38fbef703c814244bf6ddde4d041bc4cc1e
642,657
def calculate_nps_int(pos: int, neg: int, neu: int) -> float: """Считаем Net Promoter Score Args: pos (list): Сумма позитивных оценок neg (list): Сумма негативных оценок neu (list): Сумма нейтральных оценок Returns: float: NPS """ total = pos + neg + neu + 1e-8 ...
d699cf861d1abad1573ccdc130f2bbddf48b7e6a
642,658
import os def is_multipart_controller(path): """ Check if the specified directory follows the pattern of a single controller split into multiple files. For example, a regular controller would have the directory structure js/user/LoginController.js A multipart controller split into multiple fil...
0bd2dbcb1b83cd76fa6fb610d580e68718ed4b85
642,659
def pig_actions_d(state): """The legal actions from a state. Usually, ["roll", "hold"]. Exceptions: If double is "double", can only "accept" or "decline". Can't "hold" if pending is 0. If double is 1, can "double" (in addition to other moves). (If double > 1, cannot "double"). """ # state is...
59088cc91d8033a88e997627f6b50a37b8b68b3b
642,660
def ion_parallel_heat_conduction(ion_temp, ion_temp_parallel_gradient, norm): """ Ion parallel heat conduction to the boundaries Equivalent to 3.9 * density * ion_temp / (nu_ee * ion_mass) * parallel_grad(Ti) with nu_ee the ion-ion collision rate """ value = -norm.chipar_i * ion_temp ** 2.5...
190ae80346ea91de015b0ee6ebb66a088c4290fe
642,661
def run(dfs: dict, settings: dict) -> dict: """len(df)""" print() print(len(dfs[settings['df']])) print() return dfs
ce25fbde06fdcd6c577a1adf595d3635234b2815
642,662
def tail_stream(stream, nlines=10): """Returns last N lines from the io object (file or io.string).""" # Seek to eof, backtrack 1024 or to the beginning, return last # N lines. stream.seek(0, 2) fsize = stream.tell() stream.seek(max(fsize - 1024, 0), 0) lines = stream.readlines() return ...
44c4a0291cba6590981308216f0aecc64d8f5001
642,663
def timedelta2seconds(delta): """ Convert a datetime.timedelta() objet to a number of second (floatting point number). >>> timedelta2seconds(timedelta(seconds=2, microseconds=40000)) 2.04 >>> timedelta2seconds(timedelta(minutes=1, milliseconds=250)) 60.25 """ return delta.microsecon...
9133e812a73366e961e68c4868ed589e959f93af
642,664
def answer_is_type(answer, target_answer_type): """ :param answer: :param target_answer_type: :return: true if the answer type matches given input 'RepeatingAnswer' question type return 'answers' as an object, and dict for all other question types. """ answer_type = answer['type'] if isinsta...
cb62355fd213d309304526e479e348745fff6c26
642,665
def create_include(workflow_stat): """ Generates the html script include content. @param workflow_stat the WorkflowInfo object reference """ include_str = "\n\ <script type='text/javascript' src='hc_action.js'></script>\n\ <script type='text/javascript' src='hc_" + workflow_stat.wf_uuid +"_data.js'></script>\n" ...
0b4a98ec1bb16bf437e79d270612c068d7efbf7e
642,666
def get_assumed_creds(sts, arn): """Retrieves the AWS assume role credentials. Args: sts: boto3 sts object arn: Arn of the role we want to assume Returns: AWS credentials """ if arn: credentials = sts.assume_role( RoleArn=arn, RoleSessionName...
d293a553ca1087318108a571e9fe4920e78abcd9
642,667
from datetime import datetime def parse_date(date_str): """Return parsed datetime tuple""" date_format_str = '%Y-%m-%d %H:%M:%S' d = datetime.strptime(date_str, date_format_str) return {'year': d.year, 'month': d.month, 'day': d.day, 'hour': d.hour, 'weekday': d.weekday()}
75bdaabbd38fc988cefed68b90698e88b07e23a3
642,668
def get_full_verbs(tokens): """Identify, color and count full verbs """ full_verbs = [k for k in tokens if k.full_pos.startswith('VV')] for t in full_verbs: t.pos_color.append('Full verbs') return len(full_verbs)
f68b22058c50e44ba25aef498225082504358dfe
642,669
import os def flatten_path_lists(env_dict, env_root=None): """Join paths in environment dict down to strings.""" for (key, val) in env_dict.items(): # Lists are presumed to be path components and will be turned back # to strings if isinstance(val, list): env_dict[key] = os....
e9b386fff4b23dd0a7095b7f633b35500ff1a17e
642,670
import math def length_of_degree(lat): """Calcualte the length of a degree in meters.""" m1 = 111132.92 m2 = -559.82 m3 = 1.175 m4 = -0.0023 p1 = 111412.84 p2 = -93.5 p3 = 0.118 lat_rad = lat * math.pi / 180 latlen = ( m1 + m2 * math.cos(2 * lat_rad) + m3 * math.cos(4 *...
c9e46bc04b8476ba6f14993fa21c651bf1da3a8f
642,671
def vector_to_rotate(quadrant_point, axis_combination): """Gives full 3D vector using quadrant_point and axis_combination.""" axis_from_index, axis_to_index, zero_axis_index = axis_combination full_vector = quadrant_point.copy() full_vector.insert(zero_axis_index, 0) return full_vector
f79ba7976ea09333f9007d597cfba55f116cc7ef
642,673
def hexstr(s): """Compact inline hexdump""" return ' '.join(['%02x' % ord(b) for b in s])
4539c9866752206e4f4fe1c2b8026f7abdf540ed
642,674
def _prefixed_flag_vals(prefixes, flag_vals): """Returns a dict of prefixed flag values. Prefixes are stripped from matching flag names. The value for the first matching prefix from prefixes is used. """ prefixed = {} for prefix in prefixes: for full_name in flag_vals: if f...
ab6f865dce34f21966466f72db424cced3bfe998
642,675
def pWMRead(fileHandle, alphabetSize=4): """reads in standard position weight matrix format, rows are different types of base, columns are individual residues """ lines = fileHandle.readlines() assert len(lines) == alphabetSize l = [ [ float(i) ] for i in lines[0].split() ] for line in lines...
045d3bb576d37c0d5b4d055ef8c1291d7e6b52f6
642,677
def navigation_key_expected_key_pair(request): """ Fixture to generate pairs of navigation keys with their respective expected key. The expected key is the one which is passed to the super `keypress` calls. """ return request.param
5292a535714fdf46f0e0555be627b89e0a01c63f
642,678
import subprocess def is_itunes_running(): """ Checks if iTunes is running. :return: whether iTunes is running (bool) """ status = subprocess.check_output(['osascript', '-e', 'application "iTunes" is running']) is_running = b'true' == status.strip() # Strip newline return is_running
27d883c42a84ada997078dcbb745f5b7e5956d1f
642,679
def parabola_through_three_points(p1, p2, p3): """ Calculates the parabola a*(x-b)+c through three points. The points should be given as (y, x) tuples. Returns a tuple (a, b, c) """ # formula taken from http://stackoverflow.com/questions/4039039/fastest-way-to-fit-a-parabola-to-set-of-points # A...
477c3a4190dc04c26edd4eedf7232e1f64003834
642,682
import string def contains_all_letters(text): """ Checks if a string contains all of the letters of the alphabet. Args: text: the string to be evaluated Returns: True if the string contains all of the letters of the alphabet. False otherwise Raises: None """ # use a flag to hold our re...
0024099ad24dc76ff3200ab7b676f617c56c435c
642,683
def grab_pairs_keys_to_compare(descriptors_list_to_diff): """Grab all pair of keys to compare. Knowing that we already have an array containing the keys to be compared, we iterate on its indexes twice in order to just grab pairs of them. We doesn't want equal pairs indexes to be compared, and also (1,2) is the ...
a6b865256bd966440f12951ac88203e749df0710
642,684
def user_playlist_custom_cover(playlist_id, encodedImage): """ Replace the image used to represent a specific playlist. @param playlist_id: The Spotify ID for the playlist. @param encodedImage: base64 encoded Image to use as new playlist cover. @retun: None """ additional_headers = {'Conten...
5c8c748bacc44310aebf9adaefb2215d345eb51a
642,685
def parse_wfo_location_group(form): """Parse wfoLimiter""" limiter = '' if 'wfo[]' in form: wfos = form.getlist('wfo[]') wfos.append('XXX') # Hack to make next section work if 'ALL' not in wfos: limiter = " and w.wfo in %s " % (str(tuple(wfos)),) if 'wfos[]' in form...
bdb156876d9c6029f0099b0da9797e2504ad007c
642,686
import requests def get_access_token(username, password, client_id, client_secret): """ Get the Netatmo access token :param username: Netamo username :param password: Netamo password :param client_id: Netamo Client ID :param client_secret: Netamo Client Secret :return: access token """...
5f4513bf65df8ba255c3479c48ac9ad73d9a7f4e
642,687
def is_configurable(cls) -> bool: """check if a class or an object is configurable. Returns: bool Example: >>> import ice >>> import torch.nn as nn >>> ice.make_configurable(nn.Conv2d, nn.Linear) >>> assert ice.is_configurable(nn.Conv2d) """ return getattr(cls, "configura...
5f5c5bc9b481aaf41bfa5dcab2c65864bb334e77
642,688
def not_bits(number): """Takes a number in string format and performs a not bitwise operation on all bits from its binary representation. Arguments: number (str) -- the number to be modified Returns: str type """ notBit = lambda c: '1' if c == '0' else '0' return ''.join(li...
f5d5969ebb815a666848772e00e3238644448583
642,689
from typing import List from typing import Any def read_keyword_list(keywords: List[Any], list_length: int) -> List[Any]: """Reads a number of tokens from a keyword list and returns as separate list""" newlist = [] #Uses a loop like this to ensure the original list is modified when removing keywords, rath...
d9250fc3960cce0491a7b3d1861d0d116ec31ceb
642,690
def clamp(p, v, d_min=0, d_max=100, rule="slip", bounce_factor=-0.5): """Prevent particles escaping grid.""" if rule == "slip": # Clamp positions if p[0] < d_min + 1: p[0] = d_min + 1 elif p[0] > d_max - 2: p[0] = d_max - 2 if p[1] < d_min + 1: p[1] ...
078eef41b61b63a6f34b8e8d290fee1a799ef6d6
642,691
def split_tag(chunk_tag): """ split chunk tag into IOBES prefix and chunk_type e.g. B-PER -> (B, PER) O -> (O, None) """ if chunk_tag == 'O': return ('O', None) return chunk_tag.split('-', maxsplit=1)
edf51eb54d68be4b606be99c3166776ceb157345
642,692
def apply_image_filter(image, image_filter=None): """ unpacking / pseudo-dispatch function `image_filter` is a dict() that contains 'params' and 'function' keys. The optional 'params' value is a parameters dict() and the 'function' value is the corresponding function to run on `image`. """ ...
360c428fede9d5280aaa4c271facd705c8a120b8
642,693
import math def angleBetweenPoints( firstPoint, secondPoint ): """ Returns the angle (in degrees) of the straight line between firstPoint and secondPoint, 0 degrees being the second point to the right of first point. firstPoint, secondPoint: must be NSPoint or GSNode """ xDiff = secondPoint.x - firstPoint.x yD...
d3b633b105ae90382e0ae900cb26d97986f0bee5
642,694
def get_school_friends(conn, student_friends, school_id): """ Получение списка друзей пользователя по школе. :param conn: соединение с БД профилей пользователей :param student_friends: список идентификаторов друзей пользователя :param school_id: идентификатор школы пользователя :return: множест...
050a221016403e3efa6408e7ee8ed9784ffda284
642,695
def reverse(xs): """Returns the reverse of a list. """ output = [] for elem in xs: output = [elem] + output return output
ab0069f756045bbd6700a9024d314e511298e3b8
642,696
def removeFeedbackReport(report, noFeedback=False, isChecker=False): """Remove the feedback from an execution report, if the test has hidden results.""" if not noFeedback: return report report.update({ 'noFeedback': True, 'commandLine': '', 'files': [] }) re...
240b2dce1c39421adbfb11a40b0a48c55b3f570c
642,697
def normalize_gc(gc): """normalize gencode data""" gc['GC'] = int(gc['GC']) return gc
4266680331a25960206d7cada6b938025f0b9de1
642,698
import pkg_resources import csv def city_nums(): """ Get a dictionary of Backpage city names mapped to their 'legend' value. Returns: dictionary of Backpage city names mapped to their numeric value """ city_nums = {} first_row = 1 num = 0 fname = pkg_resources.resource_filename(__name__, 'resourc...
c0805b45c550bda41403600da33d410519d1ae33
642,699
def find_example3(sequence): """ Returns the FIRST STRING in the given sequence, or None if the sequence contains no strings. """ # Returns the item ( sequence[k] ) or None for k in range(len(sequence)): if type(sequence[k]) == str: return sequence[k] return None
8e9edd18b62e6ef121025f400cd386799404f679
642,700
def get_num_rows(puzzle: str) -> int: """Return the number of rows in puzzle. puzzle is a game board. >>> get_num_rows('abcd\nefgh\nijkl\n') 3 """ return puzzle.count('\n')
30985b6477a5ce8db82e289f157313f79fe1a39d
642,702
def loop_train(data_loader, model, criterion, optimizer, epochs): """ Training loop for Pytorch :param data_loader: :param model: :param criterion: :param optimizer: :param epochs: :return: """ losses = [] for epoch in range(epochs): for x, y in data_loader: ...
85e942fc5cd74a1e06af810a1a90b4ec13ee45a3
642,703
import torch def generate_anchors(anchor_shapes, grid_centers): """ Generate all anchors. @Params: ------- anchor_shapes (tensor): Tensor of shape [A, 2] giving the shapes of anchor boxes to consider at each point in the grid. anchor_shapes[a] = (w, h) indicate width and height ...
5248e7a6854e8e8bd6366c4352a6ee1fca8e8602
642,704
def clean_closed_channels(output): """Cleans up the list returned by command ":ROUTe:CLOSe?", such that each entry is an integer denoting the channel number. """ if isinstance(output, str): s = output.replace("(", "").replace(")", "").replace("@", "") if s == "": return [] ...
67a20d87ec2c04c2c81a75dc019418ff0e26c1f8
642,705
import os def filename(x): """ Extract the name of fastq file """ if x is None: xname = None else: if x.endswith('.gz'): xname = os.path.basename(x).replace('.gz', '') else: xname = os.path.basename(x) xname = os.path.splitext(xname)[0] ...
f367ed37a2dadc5e827901d2ce0670fb16f19253
642,706
def parse_string(parser, header, arg_name, arg_value): """ Parse an argument from the given parser. If the argument is not specified, return the default value :param parser: the parser to be used for parsing :param header: name of the header in the configuration file :param arg_name: name in the con...
cd987bfac49a4f14c411250df8362bb0cb95b547
642,707
def analyzeData(data, dict): """ 解析数据 :param data: 原数据 :param dict: 数据解析字典 :return: 解析过的数据 """ value=[] for i in data: d = '' for j in i: for k, v in dict.items(): if j.find(k) != -1: d = d + v if j.find(...
27b42748b166a7c0a82cacfe16f35ff801c50228
642,708
import math def sqroot(*args): """ .. function:: sqroot(int) -> int Returns the square root of a given argument. Examples: >>> table1(''' ... 25 ... ''') >>> sql("select sqroot(a) from table1") sqroot(a) --------- 5.0 """ try: ret=math.sqrt(args[0]) ...
af4ab45d112cfd28aa071680d0d42e907caaaeaf
642,709
import argparse def get_key_length_from_command_line(): """returns None on failure""" parser = argparse.ArgumentParser() parser.add_argument("length") args = parser.parse_args() length_str = args.length length = None try: length = int(length_str) print('{0} byte key'.format(length)) except Exception as...
78a6faeba0dd3814c6ee5b460c9cb970d18c3121
642,710
def is_crack(x, y): """Determine whether a pair of particles define the crack.""" output = 0 crack_length = 0.3 p1 = x p2 = y if x[0] > y[0]: p2 = x p1 = y # 1e-6 makes it fall one side of central line of particles if p1[0] < 0.5 + 1e-6 and p2[0] > 0.5 + 1e-6: # d...
8206526c0cc09561f0b31104f5962df6a5e2be50
642,711
def msg2typestr(msg): """ Introspects the message type from the passed in `msg` and encodes it as a string in the format required by rosbag2. Parameters ---------- msg : Message A ROS 2 message (deserialized) whose type we need to introspect Returns ------- A string encoding ...
2ad3ed44d6bb110290ad8a92fa95c11a639a7cc9
642,712
from typing import Tuple def _parse_url(url: str) -> Tuple[str, str, str, str]: """ :param url: a url under the format "<profile>#<share>.<schema>.<table>" :return: a tuple with parsed (profile, share, schema, table) """ shape_index = url.rfind("#") if shape_index < 0: raise ValueError...
e39ede543bbc79947abfa6160a5d9238db2ce306
642,713
import os def check_bool_env_var(env_var: str) -> bool: """Convert the value of an environment variable to a boolean. Add special check for "0" (falsy) and consider everything else truthy, except unset. env_var (str): The name of the environment variable to check. RETURNS (bool): Its boolean value. ...
aa2e78cb0332b68ad0978397ee248239d6b6e69e
642,714
import sys def checkLTL(f, t, trace, vocab, c = None, v = False): """ Checks satisfaction of a LTL formula on an execution trace NOTES: * This works by using the semantics of LTL and forward progression through recursion * Note that this does NOT require using any off-the-shelf planner ...
0821a8da46b0f8319e8450e0ed5404644dcc710d
642,715
def versiontuple(v): """utility for compare dot separate versions. Fills with zeros to proper number comparison package version will be something like 4.0.1.post11+gb3f024d.dirty-1. Where 4.0.1 is the git tag, postXX is the number of commits from this tag, and +XXXXXXX is the git commit short id. Total leng...
cadd766a21321aa4d605ed5d9697e64a103d9a67
642,716
def normalize_coefficients(n, D): """ :param n: integer dimension of the original space :param D: dictionary in the form returned by forward_no_normalization(v): :return: corresponding dictionary with the coefficients noramlized >>> expected = {(2, 0): -0.7071067811865476, (0, 0): 5.0, (1, 0): -2.0,...
b6414a771063de3207aee1ad79810466eeec5116
642,717
import torch def sent_batchwise_recall(lang_output, visn_output, lang_mask, recalls=(1,)): """ Calculate the accuracy of contextual word retrieval, average by batch. :param lang_output: [batch_size, max_len, hid_dim] :param lang_output: [batch_size, hid_dim] :param visn_output: [batch_size, hid_di...
c8f4584ce2fd505c27f604505e8c835a9fdd2574
642,718
import requests def escolha_da_palavra(): """ Escolhe a palavra e cria o arquivo palavra.txt na qual ela será armazenada :return: str randomizada pela API 'dicionário aberto' """ requisicao_palavra = requests.get('https://api.dicionario-aberto.net/random') resposta_palavra = requisicao_palavr...
a8517f19c0261a80f17d1ebf368264c405b4cacb
642,719
import glob def load_paths_if_same__person(): """ loads data from a part of set extracted from yt :return dict of form {person_id, [list of paths to videos]}: """ id = 0 data = {} for catalogue in glob.iglob('../dataset/*'): data[id] = [] for vid in glob.glob(catalogue + '/...
89e05007023d75a89927d50e6590b7db1a1ab792
642,720
def timedelta2duration(delta): """ Convert a datetime.timedelta to ISO 8601 duration format Parameters ---------- delta : datetime.timedelta Returns ------- str """ s = "P" if delta.days: s += f"{delta.days}D" if delta.seconds or delta.microseconds: sec ...
ffd550ce8852046d08c39388362e677741ad117c
642,721
def extract(a, t, x_shape): """ return a[t].view(x_shape[0], *[1]*(len(x_shape)-1)) """ b, *_ = t.shape out = a.gather(-1, t) return out.reshape(b, *((1,) * (len(x_shape) - 1)))
eea8d7e81e8dbaf1aba080ca77a520712918cd5c
642,722
def mean(mylist): """ Returns the mean value of a list """ total = 1.0 * sum(mylist) length = len(mylist) if length == 0.0: raise ArithmeticError( "Attempting to compute the mean of a zero-length list") return (total / length)
bbecfc1929d20c71a81c867dfc672f5dc4296ca0
642,723
def getRecurringLen(n): """ Returns the length of the recurring part of the fraction 1/n """ index = {} rem, curIndex = 1, 0 while rem > 0 and rem not in index: index[rem] = curIndex rem = rem * 10 ext = 0 while rem < n: rem = rem * 10 ext += 1 ...
184880f5fb730f7b1e495846dc4cd40073f8add4
642,724
import torch def _motion_smooth_helper(motion_map): """Calculates L1 (total variation) smoothness loss of a tensor. Args: motion_map: A tensor to be smoothed, of shape [B, C, H, W]. Returns: A scalar tensor, the total variation loss. """ motion_map_dx = motion_map - torch.roll(motion_m...
66672dfb011b8ccba26a68bcd0cd628e3e81ddd9
642,725
def format_font_name(value): """Formats a font name into the display version""" return value \ .replace('_', ' ') \ .title()
1707b1f86c37bd1aa68934b9ae857e6e89e90be8
642,726
from pathlib import Path def get_resource_type(pth: Path) -> str: """Get the resource type from the path - useful for finding the right resources.""" typ = Path(pth).parts[1].replace('_backfill', '') return typ
6aa5bb922fd60c5b32ac5081c4dcd12e7f9375ae
642,727
import os def find_wheels(path): """ find any Python wheel files in the directory provided by "path". We build wheels and they are distributed alongside this file, so this loads and installs any wheels it finds. :param path: :return: list of files in the provided path """ return [f for f in os.listdir(path)...
27c14a9dcce855db068e7d0b73d8e56a09685af4
642,728
import subprocess def _check_docker_image(args, raise_error=True): """Ensure docker image exists. """ a_tag = None a_image = args.image if ":" in a_image: (a_image,a_tag) = a_image.split(":") for image in subprocess.check_output(["docker", "images"]).decode(errors="ignore").split("\n")...
f5d55909d3180bd52318d409d875755803d6d4a0
642,729
import os def raw_saveconfig(filepath, config, sortlist=[], delimiter='=', quoter='"'): """Write config to file. """ if not os.path.exists(filepath): return False lines = [] # write the item in sortlist first if len(sortlist) > 0: for k in sortlist: if config.has_key(k): ...
7e2ad6c90bd804180ee722ee493697b6f6a925ef
642,731
import torch from typing import Optional def eigvals_batch(m: torch.Tensor, dim: int=2) -> Optional[torch.Tensor]: """Calculates the elementwise Eigenvalues of a batch of tensors of shape [1, 1] or [2, 2]. Works only for real symmetric tensors. Args: m (torch.Tensor): shape [bs, dim, dim] ...
a8968519a4363ba885b33b12041ce67b32d2cd26
642,733
import os from pathlib import Path def path_w_suffix(in_path: str, template_path: os.PathLike) -> Path: """If the input starts with a '.' assume it is a suffix and return the template with the suffix replaced, otherwise return the input.""" if in_path.startswith("."): return Path(template_path).wi...
15a823d72f134c0ca78527b9d656a55900403ae7
642,735
import numpy def rescale(curves, values): """ Multiply the losses in each curve of kind (losses, poes) by the corresponding value. """ n = len(curves) assert n == len(values), (n, len(values)) losses = [curves[i, 0] * values[i] for i in range(n)] poes = curves[:, 1] return numpy.ar...
8ffbef0e5a40c022be7be1c7d96e0b8173cdc410
642,736
def improve_policy(env, gamma, value_func, policy): """Given a policy and value function improve the policy. See page 87 (pg 105 pdf) of the Sutton and Barto Second Edition book. http://webdocs.cs.ualberta.ca/~sutton/book/bookdraft2016sep.pdf Parameters ---------- env: gym.core.Enviro...
4b3037616c100a06f661faef25f7a461eb0f0c9a
642,737
import requests import zipfile import io def get_files(code): """ A wrapper function to obtain .csv files from the world bank. Parameters: ----------- code: str The code of the indicator. Returns: -------- str downloaded .csv filename """ r = requests....
1a23e9760bde8f5f29701fbe0afcc0af4a2ee693
642,738
def parse_col_name(col_name): """ Standardize column name `col_name` """ return col_name.upper().strip()
9c96348651ec441a1957571d55c3b8afd8fee7e8
642,739
def _patch_ssl_transport(monkeypatch): """Make ssl transport substitution to prevent ssl handshake.""" def _make_ssl_transport_dummy(self, rawsock, protocol, sslcontext, waiter=None, **kwargs): return self._make_socket_transport(rawsock, protocol, waiter) monkeypat...
e838ed4ddc2c9482bee2b03a30dca02be017a382
642,740
def part_c(f, x, h): """Central difference""" return (f(x+h) - f(x-h)) / (2*h)
d77f4ff84408fd4b9d0589194523121c8dc7edf1
642,741
import subprocess def alignBlastDB(query, db, outfile): """ Aligns query to properly formatted blast db Outputs a temporary XML file """ subprocess.call(["blastn", "-db", db, "-query", query, "-out", outfile, "-outfmt", "5", '-max_target_seqs', '20']) return True
cb5731b7b3a10ef64a2a9367b2c563cd3c4c4bca
642,742
import os def followlink(path, max_follows=10): """ Dereference a symlink repeatedly to get a non-symlink (up to max_follows times, to avoid cycles). """ orig_path = path count = 0 if not os.path.exists(path): raise ValueError("Not found: %r" % path) while os.path.islink(path): # Note path.joi...
a77fd62417ca59591c707b412f51e0184d0e4cc8
642,743
def _update_globals(task_file_to_run, globals_dict): """Updates globals dictionary with default data path for provided task if Inputs/Outputs directories are equal to None. Args: task_file_to_run (str): path to the task that will be run. globals_dict (dict): contains global variables for f...
4ee348eec90f5886056994dd61d00d32dc244237
642,744
def post_query(path, p_limit, _1_property, _1_property_value): # noqa: E501 """post_query # noqa: E501 :param path: :type path: str :param p_limit: :type p_limit: :param _1_property: :type _1_property: str :param _1_property_value: :type _1_property_value: str :rtyp...
f2e9ca14523440079041a95ed684ce019b1601fa
642,745
def format_nvec(nvec): """Nice strings representing tuples of integers.""" if isinstance(nvec, int): return str(nvec) nvec_str = [f"{n}" if n < 0 else f" {n}" for n in nvec] return " ".join(nvec_str)
0a6522937a5ce9c5b3eac60155709a706b595c16
642,746
import json def create_error_response(error): """ Create error response from an error exception Parameters ---------- error : Exception An error exception Returns ------- string A JSON string of the error response """ error_response = json.dumps({ 'sta...
f1d8cee0db2ed83c9e7bb1ee7b058da2905bc5de
642,747
def mixture_loss_normalize(value, predictions): """.""" return (value - predictions['means'])*predictions['inverse_standard_deviations']
3080faf3775bf18ed3f380574a83b6f5079e6f3c
642,748
def gradient_x(image): """ AUTHORS: -------- :author: Alix Leroy DESCRIPTION: ------------ Compute the horizontal gradient of an image PARAMETERS: ----------- :param image (Tensor): The original image RETURN: ------- :return gx(Tensor): The horizontal gradient ...
9f42d4ce0be4cecea88d1810c2f1edd1018e3904
642,749
def _is_json(q): """Check if q is JSON. Parameters ---------- q : str Query string. Returns ------- bool True if q starts with "{" and ends with "}". """ return q.strip().startswith("{") and q.strip().endswith("}")
0146cc62d550bbcdbd4fc8ef5e9a81325c044cb6
642,751
from numpy import dot, floor, abs from numpy.linalg import inv def zero_centered(position, cell, inverse=None): """ Folds vector back to origin This may not be the vector with the smallest possible norm if the cell is very skewed :param position: Vector/position to fold back ...
d31c20cc8aa6c0b987bf563ca066637b83c34818
642,752
def ComputeR(edge_weights): """ Computes the value of R (sum of edge weights) given the edge weights of a graph. """ sume = 0 for (i, j) in edge_weights.keys(): sume += edge_weights[(i, j)] return sume
cd4607305d8422c15978641162b3e51331046496
642,753
import random def mutate_all_odds(odd_numbers): """ Mutates a string of odds numbers in an other string of odd numbers :param odd_numbers: String of odd numbers :return: string of other odd numbers """ new_numbers = "" for i in range(len(odd_numbers)): new_numbers += str(random.choice(...
6500a9c707d3da1675933dbb31df700c6aa83d40
642,754
from itertools import cycle def _create_color_generator(): """Create a generator which will cycle through a list of default matplotlib colors""" colors = [ "#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", ...
32953c27cca8505636bea8059d6595b6509d327a
642,755
def load_data(filename): """ function to load data with family codes from csv to dataframe :param filename: name of csv file with columns with accession numbers with header :type filename: str :return: list with data from the file :rtype: list """ file = open(filename) list = file.r...
ac56e0a75dc48d4c80f23530f3365a100a31d1e2
642,756
import random def random_jitter(value, jitter=1): """Jitter the value a random number of milliseconds. Copied from https://github.com/litl/backoff/blob/master/backoff.py (MIT License) This adds up to 1 second of additional time to the original value. Prior to backoff version 1.2 this was the default...
4aad5b214fc89284cd1ad2e6975cb1fe61816337
642,757