content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import numpy def stitch(input_array, project_dict, col_name): """ Given EIA performance, cost, and lifetime projections for a technology between a series of time periods (i.e. 2010-2014, 2014-2020, 2020-2040), reconstruct this information in a dict with annual keys across the modeling time horizon use...
15ae57bc648dde06ad9c1b52294154aace1e627a
658,038
def _LLF(job, t): """ Least-Laxity-First assigns higher priority to jobs with lesser laxity (slack). The laxity (slack) of a job of a job with deadline d at time t is equal to deadline - t - (time required to complete the remaining portion of the job) """ return job.deadline - t - job.remai...
8dd5025c5ee077352c7f0cf0e23fc76bc29950c3
658,039
def calc_ttr(df_ttr): """Calculates travel time reliability. Args: df_ttr, a pandas dataframe. Returns: df_ttr, a pandas dataframe with new ttr column. """ # Working vehicle occupancy assumptions: VOCt = 1 df_ttr['VOLt'] = df_ttr['pct_truck'] * df_ttr['dir_aadt'] * 365 df_ttr['ttr'] = df...
cee9b22dd1866458dfd7ec849c9dccc20da5c92b
658,040
def trunc(s,min_pos=0,max_pos=75,ellipsis=True): """Return a nicely shortened string if over a set upper limit (default 75 characters) What is nicely shortened? Consider this line from Orwell's 1984... 0---------1---------2---------3---------4---------5---------6---------7----> When we are omn...
4622d3332e9c22c0597633ab025c0f2998f8b773
658,041
from typing import Callable import math def fv_american(s0: float, i: int, n: int, t: float, r: float, u: float, pu: float, i_u: int, d: float, pd: float, i_d: int, f: dict, iv: Callable, k, **_) -> float: """One-Step update for a european option""" return max((math.exp(- r * t / n) * # disco...
3ae420e33dbc69b28f2c719d6370aa0a4544ba8b
658,042
def U32(i): """Return i as an unsigned integer, assuming it fits in 32 bits. If it's >= 2GB when viewed as a 32-bit unsigned int, return a long. """ if i < 0: i += 1 << 32 return i
212c3e62d34c1708b29eaa02b6fc96af57eb48e5
658,043
from typing import List def _check_is_list(obj): """Check whether obj is a list""" return isinstance(obj, (list, List))
2327f6641cae73e98e0820a14e05dfaf2c87dc6b
658,044
import time def string_to_datetime(str_time): """ #把字符串转成datetime :param str_time: :return: time.struct_time(tm_year=2018, tm_mon=10, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=1, tm_wday=0, tm_yday=274, tm_isdst=-1) """ return time.strptime(str_time, "%Y-%m-%d %H:%M:%S")
fbd23d5a6340e793cc5b6ea16be2ec0f31d66c67
658,045
import argparse import os def parse_command_line(): """ :return: """ parser = argparse.ArgumentParser() parser.add_argument( '--pipeline-work-dir', '-wd', type=str, dest='work_dir', default=os.getcwd(), help='Pipeline (Snkemake) working directory', ...
6d2b8cc683befa2c257e06f758365dc647e51488
658,046
def day_2_strategy(offset): """Return the new offset given the current value.""" return offset - 1 if offset >= 3 else offset + 1
35ea0dd3f226f61ee161ff27879fdf71acacf57f
658,047
def dict_pop(d, key): """ Template filter that looks removes a key-value pair from a dict. """ return d.pop(key)
e79839edd6c17ed32b6751f16f582c427234ca09
658,048
from typing import Tuple from typing import Sequence def get_involved_bits(instruction) -> Tuple[Sequence[int], Sequence[int]]: """Returns the bits involved in the instruction. :param instruction: The instruction of interest. :return: The quantum and classical bits used by the considered instruction. ...
896f1755b80e7d0e2bfd427e219eb0fb546307af
658,050
import socket import struct import random def gen_random_ip() -> str: """ Generate random ip From: https://stackoverflow.com/questions/21014618/python-randomly-generated-ip-address-of-the-string """ return socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
eda3b7494ffd36590b122ccc136f3c873feff281
658,051
def leaf_size(request): """ Fixture to specify IntervalTree leaf_size parameter; to be used with the tree fixture. """ return request.param
f28f607f631470e1541ebc9ee71735d9f66ae3f3
658,052
def run_to_inlines(textrange): """ Here, only focuses on the style of `string`. """ def _to_str(s): return {"t": "Str", "c": str(s)} text = textrange.text.rstrip("\r") tokens = text.split("\013") # vertical tag. result = [] for i, token in enumerate(tokens): result += [_to...
ef1d20cee9d5f645868c6a29de6b1ea7f6ee578b
658,053
def all_tags(feature): """All fields to tags translate.""" tags = {} for attr in [f.name() for f in feature.fields()]: tags[attr] = str(feature[attr]) return tags
c4d66cbccda38166da32a7b04adecad2d7019e46
658,054
import os def merger(input_dir_1, input_dir_2, output_file, verbose): """ Merges CoNLL files from two annotators. Parameters ---------- input_dir_1 : directory Input directory path from first annotator input_dir_2 : directory Input directory...
04dc3c61a860cb3242ab0981c41afed91451a4b5
658,055
from datetime import datetime def str_to_milisecond_timestamp(str_datetime): """:arg str_datetimea: '%Y-%m-%d %H:%M:%S.%f', e.g. 2019-06-06 00:00:00.0""" dt = datetime.strptime(str_datetime, '%Y-%m-%d %H:%M:%S.%f') dt_miliseconds = int(datetime.timestamp(dt)) * 1000 return dt_miliseconds
033e573426523aba65c2a72d4caf31f8a11638a2
658,056
import argparse def parse_arguments(): """ Set required input arguments and add functionality to parse them Returns: The arugments parsed from the command line """ parser = argparse.ArgumentParser(description="Freezes (or exports) a model from TensorFlow \ ...
82a2f310dbceddf95bd84d1e0636e942a00b6f7c
658,057
import os def get_partyA_input_range_file(folder_name): """ Get file object for output.inputs.partyA.txt :param folder_name: folder which contains output.* files for a circuit :return: file object for output.inputs.partyA.txt from specified folder """ script_dir = os.path.dirname(__file__) ...
76a6980fd226d1b4ac40f512d7812eeee2422754
658,058
import math def is_equal(aabb1, aabb2, rel_tol=1e-9, abs_tol=1e-7): """ Check if two AABBs aabb1 and aabb2 are approximately equal. The two AABBs are considered equal if the min and max points of the AABBs are componentwise approximately equal. For the componentwise equality check, the standard funct...
c1758b90bc139a983748feff0850145a374ca4f4
658,059
def solve(): """ """ range_a, range_b = range(2, 101), range(2, 101) return len(set([a ** b for a in range_a for b in range_b]))
817dc836a42ae36bc76c524a3e1451211c0aa19b
658,060
def CountName(name): """Returns the name of the auxiliary count member used for array typed.""" return '%s_bytes' % name
e6d0b0bc6f0209a2e29a4afa6b2052b9e924e7bb
658,061
def insertion_sort(numbers): """Will sort any given number iterable into a min first list.""" new = [] while len(new) < len(numbers): x = 0 for i in numbers: while True: try: if new[x] >= i: new.insert(x, i) ...
a2e67d550b07df8affbb6fafa64f81370cb359ae
658,062
def remove_top_words(text, remove_words): """ text: str of text to be filtered remove_words: set of most common strings """ new_contents = [word for word in text.split() if word not in remove_words] return ' '.join(new_contents)
09e122dbfe024008c254f904533affd0935eab66
658,063
def reg_token(request): """ reg_token param. """ return request.config.getoption("--reg_token")
20543fec1d6a60641fb82fb0b0bfb27948addddc
658,064
def adj_mom(df, i): """ Creates relative Form from all games (home + away) for the past i games relative Form -> sum of points from last i games divided by expected points from those games """ df1 = df.loc[:,["HomeTeam", "AwayTeam", "H_Pts", "A_Pts", "H_Pts_Exp", "A_Pts_Exp"]] df1.columns = ...
23404496beff3d206af351f5e2af6e7c1b255172
658,065
def get_max_trait_id(cxn): """Get taxa already in the database.""" return cxn.execute('SELECT MAX(trait_id) FROM traits;').fetchone()[0] or 0
8025dedb11e6ec37a2918566422ed64163ad67e3
658,066
def newdims(img = None, resize = 1, dims = None): """Returns new dimensions of an image array based on resize value""" if dims is None: if img is None: print("No img or dims provided..") return else: dims = (img.shape[1],img.shape[0]) width = int(dims[0...
c282f77944eb525d49d845a1d1a94af021827720
658,067
import json def _clean_test_user_fixture(fixture_content, test_users): """ Removes any test users in a fixture that aren't defined in the app's test users """ fixture_names = set([u['pk'] for u in json.loads(fixture_content)]) actual_names = set([u['name'] for u in test_users]) names_to_remove...
654eda4fde84fb68b1f2d585482c6c5fe9465841
658,068
def review_coa(): """ Creates a certificate of analysis. """ # Validate the user's pin. # Get the user's signature. # Insert the signature into the CoA template. # Create the PDF. # Upload the PDF to storage. # Save the reviewer data. return NotImplementedError
0382f6444309ae824b95f4084dbce6c3d9ab2398
658,069
import random def any_int(min_value=0, max_value=100, **kwargs): """ Return random integer from the selected range >>> result = any_int(min_value=0, max_value=100) >>> type(result) <type 'int'> >>> result in range(0,101) True """ return random.randint(min_value, max_value)
2253de803c8b577fc8318673805ac85304f20320
658,070
import json import math def get_record_data_json_bytes(data): # type: (dict) -> bytes """Get serialized and utf-8 encoded record data with padding""" data_str = json.dumps(data) padding = int(math.ceil(max(384, len(data_str)) / 16) * 16) if padding: data_str = data_str.ljust(padding) retur...
e908707b0d4ceca6be493d14c01eceac74765cfc
658,071
def _get_field_name(svl_axis): """ Extracts the name of the field for the SVL plot. Parameters ---------- svl_axis : dict The SVL axis specifier. Returns ------- str The name of the field in the axis, or the transform statement. """ if "transform" in svl_axis: ...
243eac630f2e8e892b41d8ac0bee5088d6ac7dc8
658,072
def copy_factory(src, dest): """Copy Dash I/O Factory When a Dash component has been wrapped in additional layout to make a composite it is necessary to copy the embedded component I/O definition to the outermost component. This will then allow the composite component to be referenced in Dash callb...
3e6fe3d644f81f9f884bdae3312ffcda0fc2d56e
658,073
def mitemgetter(*items): """Like :func:`operator.itemgetter` but returns ``None`` on missing items instead of raising :exc:`KeyError`.""" return lambda container: map(container.get, items)
a935d8dd422791c819211db7facacf7a0eb74d70
658,074
import bisect import random def weighted_sampler(seq, weights): """Return a random-sample function that picks from seq weighted by weights.""" totals = [] for w in weights: totals.append(w + totals[-1] if totals else w) return lambda: seq[bisect.bisect(totals, random.uniform(0, totals[-1]))]
46d70c659b1b6358728bb2a0f3bc7363735a3d25
658,075
def ReadOnlyPropertyWithFunctionAccess(func): """With normal property, you can not (easily) retrieve the function. This will return the value of the func if you do x.prop and the func itsealf if you do type(x).prop """ class Property: def __get__(self, inst, instcls): if inst is...
21e163bc44d0adedb2c9ead0d1f1d4b1cb3bc749
658,076
def bic_intra_extra_pairs(training_data): """bic_intra_extra_pairs(training_data) -> intra_pairs, extra_pairs Computes intra-class and extra-class pairs from given training data. The ``training_data`` should be aligned in a list of sub-lists, where each sub-list contains the data of one class. This function w...
d39c865458584dc536a3bc77f74e7065bf0b3198
658,077
def read_file(file_path, ignore_error=False): """Safely read file and return empty str in case ignore_error fla is set.""" try: with open(file_path, encoding="utf-8") as file: return file.read() except OSError as err: if ignore_error: return '' raise err
2f280de8c9b36ef98ff07bca3fb09564acc65808
658,078
def skew_array(genome): """[keeps track of total no of occurrences of C and G encountered so far in genome] Args: genome ([string]): [string to be parsed] Returns: [list]: [tracks how many times nucleotide bases C and G appear in genome] """ Skew = [0] for i in range(len(genome...
999eabf1ecb1b07cd9c8f121059eec8af8cd7a04
658,080
import torch def covariance(x: torch.Tensor, assume_centered: bool = False) -> torch.Tensor: """ Calculate empirical covariance matrix.. """ n_samples, n_features = x.shape if not assume_centered: x = x - torch.mean(x, 0).view(-1, n_features) cov = (1 / (n_samples - 1)) * torch.mm(x.t...
81d20e2bb924db3c864e41e591912d2e277e0f44
658,081
def read_input(input_path: str) -> list: """take input file path and return appropriate data structure""" with open(input_path, 'r') as input_file: lines = list() for line in input_file.readlines(): lines.append(line.strip()) return lines
3e239d9599e76ff19a865236ed0c127903c2d308
658,082
import json def get_sub_suite(database, sub_suite_id): """Sub suite gets a sub suite by suite_id from database. :param database: The database to get sub suites from. :type database: :obj:`etos_lib.lib.database.Database` :param sub_suite_id: The suite ID of the sub suite in database. :type sub_sui...
70b895211dfa8b7a1c240384fccdd66f0d1eaf9a
658,083
def cli(ctx, history_id, dataset_id, annotation=None, deleted=None, genome_build=None, name=None, visible=None): """Update history dataset metadata. Some of the attributes that can be modified are documented below. Output: details of the updated dataset (for Galaxy release_15.01 and earlier only ...
4a934d103586767ac1ec6079893ed4882006915a
658,084
from typing import Type import enum def is_enum(typ: Type) -> bool: """ Test if class is Enum class. """ try: return issubclass(typ, enum.Enum) except TypeError: return isinstance(typ, enum.Enum)
428dd504a570bbf1dcf616a970ff2ee37c25cc72
658,085
def eff_t(t_c, h): """ t: mean temparature of the air h: relative humidity """ t = t_c * 1.8 + 32 c1 = -42.379 c2 = 2.04901523 c3 = 10.14333127 c4 = -0.224755 c5 = -6.83783e-3 c6 = -5.481717e-2 c7 = 1.22874e-3 c8 = 8.5252e-4 c9 = -1.99e-6 if t > 80: et...
dc5a422962fec679456d0f9f8fb71a789bfbff6c
658,087
import ctypes def allocate_aligned(ty, align): """ Python does not do any aligned allocations by default. At least, not most of the time. The does not seem to be a good API to force an allocation to be aligned, so this function implements one. We allocate the type and wait until its address value...
1d49f68adede782156e03ccf816d20cdd1204a0b
658,088
def _make_json_response(json, status): """Creates a tuple representing the HTTP package to respond the requisition with the given JSON on its body and the given status code. :param json: object to be sent on HTTP body :param status: status code :return response: tuple representing the HTTP respo...
93e0f23f72fb0940d991186d1bb4c2ff44d514a1
658,089
def anno_parser(annos_str): """Annotation parser.""" annos = [] for anno_str in annos_str: anno = list(map(int, anno_str.strip().split(','))) annos.append(anno) return annos
a9f22e8e9485f0dd28738d25b985b5ab4d675611
658,091
def find_subtree(root, label_parts): """Given a nested tree and a label to look for, find the associated node in the tree. Note that, unlike regulations, preamble trees _always_ encode their exact position in the tree.""" cursor = root while cursor and cursor['label'] != label_parts: next_cu...
a5d2d6abbed7752c0691b37989a8a0ca733ab789
658,092
def comp_width(self): """Compute the average width of the Slot by dividing its surface by its height Parameters ---------- self : Slot A Slot object Returns ------- W2: float Average width of the slot [m] """ S = self.comp_surface() H = self.comp_height() ...
80e69a4cc380f9e0aadc3888c2dc192bd9dd767b
658,093
def combine(x,y): """ Combines Testclasses X and Y Returns (NewElement or None, Delete X from Worklist, Delete Y from Worklist) Any Class that replaces an essential class is itself essential. """ deleteX = True deleteY = True merge = False workout = [] for i in range(len(x)): ...
b0e350a6fafe8ed753c2acb21c55e534221cbb66
658,094
def get_iou(pred_box, gt_box): """ pred_box : the coordinate for predict bounding box (x, y, w, h) gt_box : the coordinate for ground truth bounding box (x, y, w, h) return : the iou score """ # 1.get the coordinate of inters ixmin = max(pred_box[0], gt_box[0]) ixmax = min(pred_box[0...
cc9008f243b736a2bac0a0656d29591bea9bba3e
658,096
def distance(coords): """Calculate the distance of a path between multiple points Arguments received: coords — list of coordinates representing a path Arguments returned: distance -- total distance as a float """ distance = 0 for p1, p2 in zip(coords[:-1], coords[1:]): distance...
c0d353f374aef11bda019077616cf2b4f57c3ba6
658,097
import os def prep_info(filepath, osver, device=None): """ Prepare file list for new-style info file. :param filepath: Path to folder to analyze. :type filepath: str :param osver: OS version, required for both types. :type osver: str :param device: Device type, required for Android. ...
a747fb09f9eb58f16e0506f60547c8683f03808e
658,098
import argparse def parse_args(): """ Parse command line options. """ parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument("--host", "-H", dest="host", default="localhost", help="Elasticsearch hostname") par...
49091a2651ef9e222e8f629a5582939cc365d240
658,099
def default_to(default, x): """Returns the second argument if it is not null, undefined or NaN; otherwise the first argument is returned""" return default if x is None else x
f13bb6be049ffbdf04b9e57591770dcbada2111d
658,100
def compute_indentation(props): """ Compute the indentation in inches from the properties of a paragraph style. """ res = 0 for k, v in props.items(): if k in ['margin-left', 'text-indent']: try: res += float(v.replace('in', '')) except: ...
d422421560de9d7eff6831773a23c6fb5a823cca
658,101
def part1(data): """ >>> part1(read_input()) 5929 """ registers = {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0, 'g': 0, 'h': 0} count = 0 index = 0 while 0 <= index < len(data): (ins, x, y) = data[index] if y.isalpha(): y = registers[y] else: ...
3871009543b1465d2eca1eb0aef66399b8946b21
658,102
from operator import xor def feistel_scheme(dl, dr, F, n): """ Applique un schéma de Feistel (n tours) aux blocs de données dl (gauche) et dr (droite), en utilisant la fonction F. """ l = dl r = dr for i in range(n): l = xor(l, F(r)) l, r = r, l return (r, l)
42d5c50bfacfdb1b4adbc7a4d877d5350a304689
658,103
import os def clean_flist(flist): """ remove files that don't exist from the flist :param flist: :return: """ exists = [] for f in flist: if os.path.exists(f): exists.append(f) else: print("Ingore missing file {0}".format(f)) return exists
1f7ddd38a5f66f3f763c9acf3273310ec1d15979
658,104
def unbalance(A, B, C, all=False): """ Voltage/Current Unbalance Function. Performs a voltage/current unbalance calculation to determine the maximum current/voltage unbalance. Returns result as a decimal percentage. Parameters ---------- A: float Phase-A value ...
4c5ba17ed1ce0e94e77ef02c9d8bc6e05ec64cf8
658,105
def valiant_license() -> str: """The expected app license.""" return "MIT"
33f24faa78da605b8c66aac5daa0b6ca73a71eed
658,106
import torch def create_threshold_mask(inp): """ Args: inp: [batch_size, input_window, column, row, input_dim] Returns: """ oup = torch.sum(inp, dim=-1) shape = oup.shape oup = torch.reshape(oup, [shape[0], shape[1], -1]) mask = (oup == 0).float() return mask
c0ee1ee989cdd0d1c72ff8482156cfd95a63068d
658,107
def min1(x): """ >>> min1([100]) 100 >>> min1([1,2,3.0]) 1 >>> min1([-1,-2.0,-3]) -3 >>> min1(1) Traceback (most recent call last): ... TypeError: 'int' object is not iterable """ return min(x)
f51cfc1fc3b5cabe1f405b37f62ae24d7b34f518
658,108
import re def replace_region(fn, region_start, region_end, callback, replace_start=True, write_back=True): """Replace a region in a file delimited by two lines matching regexes. A callback is called to write the new region. If `replace_start` is true, the start delimiter line is repla...
09ff6f7606daed2e274f73f94bf9c7724d0b663a
658,109
import re import functools def _translate(pat): """Translate a shell PATTERN to a regular expression. There is no way to quote meta-characters. """ i, n = 0, len(pat) res = '' while i < n: c = pat[i] i = i + 1 if c == '*': res = res + '.*' elif c == ...
191dca95e117b4033fdb10fe4c4ffedf65585946
658,110
import argparse def parse_arguments(): """Parse arguments""" parser = argparse.ArgumentParser() parser.add_argument( "-i", "--input", type=str, default="data/NL-gtfs", help="Input directory", ) parser.add_argument( "-o", "--output", t...
84154ab2246b5d6a95f22109dd4c58caffdabfbe
658,111
import uuid def nsuuid_to_uuid(nsuuid): """Convert Objective-C NSUUID type to native Python UUID type.""" return uuid.UUID(nsuuid.UUIDString())
304b7c7ff5299bfec6224e22e624dc47079589ac
658,112
import operator def size_maxed(inner, outer, exact=False): """Return True if the inner QSize meets or exceeds the outer QSize in at least one dimension. If exact is True, return False if inner is larger than outer in at least one dimension.""" oper = operator.eq if exact else operator.ge ret...
c0649f7f8da62fcac89a47fe7ad498390c0b1791
658,113
import json import base64 def json_safe(string, content_type='application/octet-stream'): """Returns JSON-safe version of `string`. If `string` is a Unicode string or a valid UTF-8, it is returned unmodified, as it can safely be encoded to JSON string. If `string` contains raw/binary data, it is Base6...
49014fde3b769cebfbebd66033c6d4762193179a
658,114
def has_many_siblings(img, x1, y1, width, height): """ check if a pixel has 3+ adjacent pixels of the same color. """ x0 = max(x1 - 1, 0) y0 = max(y1 - 1, 0) x2 = min(x1 + 1, width - 1) y2 = min(y1 + 1, height - 1) pos = (y1 * width + x1) * 4 zeroes = (x1 == x0 or x1 == x2 or y1 == y...
a47733ea12eb9404b15fa1bd7b341b3b6dde999e
658,115
def iter_func(root_name, root, set_traverse, list_funcs, G, strings, plot_nodes, cur_pos, xgrain, min_weight, max_weight): """ Recursive function to traverse over the phylogeny and generate positions of each node. """ set_traverse.append(root) nbs = G.neighbors(root) nbs = G[root] plot_nod...
abd79c67c5734e97b23d7fabfe408d721723722e
658,116
import os def get_top_dir(root, path): """ Return the directory in path that is a subdirectory of root. e.g. >>> print get_top_dir('/a/b/c', '/a/b/c/d/e/f') d >>> print get_top_dir('/a/b/c/', '/a/b/c/d/e/f') d >>> print get_top_dir('/a/b/c', '/g/e/f') None >>> print get_top_di...
9b763e41f649a2d5a62fd000bf94276bbdd9811e
658,117
def evm_stop(): """ STOP """ return "00"
d5a7933969849b0800730b6e2627253f63e6b69e
658,118
def get_multiplicative_cooling_schedule_function(cooling_ratio_multiplier): """ Returns a cooling schedule function of the form f(T) = a*T, "a" being the cooling ratio multiplier - a real number between 0 and 1 (As specified in the proforma) :param cooling_ratio_multiplier: real number a, 0 <= a <= 1 :...
6770781ebab8c570370d95d7bd21206f7e3534bb
658,119
def get_intersection_of_lists(list_1, list_2): """Takes in two singly-linked lists and returns the intersection of them""" longest_list = list_1 if list_1.length > list_2.length else list_2 shortest_list = list_2 if list_1.length > list_2.length else list_1 remaining_longest_nodes = longest_list.length...
7d14bbacce5cc1ed4976be8e7c491e58e8c8e5f8
658,120
import os def get_last_block(fn): """From existing db, e.g. 'raw_reads.db', return (bool, int) Related to 'openending'. Not currently used. """ last_block = 1 new_db = True if os.path.exists(fn): with open(fn) as f: for l in f: l = l.strip().split() ...
6dd889d34b6447a5f6fca9cdd6771e10787c627f
658,121
def prepare_id(id_): """ if id_ is string uuid, return as is, if list, format as comma separated list. """ if isinstance(id_, list): return ','.join(id_) elif isinstance(id_, str): return id_ else: raise ValueError(f'Incorrect ID type: {type(id_)}')
81e2ef42edb05d707f8378123709364408ba4690
658,122
def compute_attribution(conn, df, axioma_model = 'sh') : """ Do attribution analysis of portfolio returns against factor model returns from axioma. Parameters ---------- df : Time series data frame of portfolio position weights with data_date as index and 'sec_id' and 'weight' as columns axio...
161ed870f262ad1fb328af125b44522502655e66
658,123
def make_description(comment): """Construct a single comment string from a fancy object.""" ret = '\n\n'.join(text for text in [comment.get('shortText'), comment.get('text')] if text) return ret.strip()
27ba0272bda866732225b53d3ad28447432890b8
658,124
import calendar def _month_number(x): """Return the month number for the fullname of a month""" return list(calendar.month_name).index(x)
1756fe82f1ea82e879bddd1a262feaa319ffbae5
658,125
import os import sqlite3 def connect_to_db(config): """Connects to an SQL measurement database """ cwd = os.getcwd() msr_db_path = ( cwd + "/" + config["results"]["folder"] + "/" + config["results"]["measurements"] ) return sqlite3.connect(msr_db...
9eefe799acaa67b29730c83a9e444d09e7d4d260
658,126
import torch def tlbr2cthw(boxes): """ Convert top/left bottom/right format `boxes` to center/size corners." :param boxes: bounding boxes :return: bounding boxes """ center = (boxes[..., :2] + boxes[..., 2:])/2 sizes = boxes[..., 2:] - boxes[..., :2] return torch.cat([center, sizes], d...
15dff8e597e1386e88a8a0417cf5061e830c863f
658,127
from typing import Iterable def ensure_list(obj): """Accepts a thing, a list of things or None and turns it into a list.""" if isinstance(obj, Iterable): return list(obj) if obj is None: return [] return [obj]
6e28324d0c430f6481c748dccd3b6d38270ce898
658,128
def get_words(filename): """ Get the wordlist from the file. """ wordlist = [] with open(filename) as f: for line in f: line = line.rstrip() if (line != '') and (line[0] != '#'): wordlist.append(line) return wordlist
80a3a68ed0431cf12df607fdcbe5edf29df888c7
658,129
import glob def find_duo_taxcode(source_A, source_B): """This function searches two folders to find filenames with matching taxonomy codes. It disregards the suffixes after the taxonomy code in the filenames. Expected inputs are: source_A and source_B: str """ def get_filelist(source): ...
1f30dd5bc99145f7ca7a166c9359f9b801f4151c
658,130
import re def parse_results_with_regex(output, regex): """Find and returns the regex matching results in output Looks through the output line by line looking for a matching regex. The function assembles a list of lists where each parent list is the results for that position in the regex string and ea...
434fd7114001d2a250eca81b74050c52082b2993
658,131
import math import torch def spherical_meshgrid(shape, lon_limit=(-math.pi, math.pi), lat_limit=(-math.pi / 2, math.pi / 2)): """ Default limits are according to an equirectangular image """ H, W = shape lon = torch.linspace( lon_limit[0], lon_...
3ebed102f34e564276883d2d8313818511593027
658,132
def parse_none(data: bytes) -> bytes: """Return `data` as is.""" return data
ba1977dbc79503d5ae0d7a6c86d29e76f5628e33
658,133
from datetime import datetime def convert_to_date(s): """ Convert the date into a useful format. """ return datetime.strptime(s, '%m/%d/%Y')
e78409f75814e7505a0ddfcdfe3787659dc52c03
658,134
import functools def trycatchfinal(errors=(Exception, ), default=""): """ try catch with return value and Custom Exception Raises: Exception: somthing went wrong running the function Returns: (Any): return value of the function handle or value handle Examples: .. exampl...
d67320b14dba1af37efd0cbe5852d71d57657e2a
658,135
def linear_growth( start: float, end: float, start_time: int, end_time: int, trade_time: int ) -> float: """ Simple linear growth function. Grows from start to end after end_time minutes (starts after start_time minutes) """ time = max(0, trade_time - start_time) rate = (end - start) / (end_time...
a33c019fd6e6658dc6be4c8437772ce4dc9cd88a
658,136
def policy_compare(sen_a, sen_b, voting_dict): """ Input: last names of sen_a and sen_b, and a voting dictionary mapping senator names to lists representing their voting records. Output: the dot-product (as a number) representing the degree of similarity between two senators' voting p...
0fedbcc46c57a9ec6b57d6dd7566281b7557af1d
658,137
def has_prompt(): """Return True if communicator provides a direct prompt to users.""" return True
7fa2a4041641760b67c2f888b9b930beb325c25b
658,138
import os def current_kernel_revision() -> str: """ Goal: get the current kernel version """ return os.uname().release
1e7429daae4ac1ff6b9b70245514ebd85fcfde6e
658,140
def directory_size(directory): """ Total size of files in the given directory. :type file_paths: Path :rtype: int """ return sum(p.stat().st_size for p in directory.rglob('*') if p.is_file())
f6395065fc6e28504c7c268beb2767d63333283e
658,143
def get_leaves(nodes): """Return a list containing the leaves of the graph defined by nodes.""" leaves = [] for n in nodes: if not n.children: leaves.append(n) return leaves
891b06a2d4180e63682b5118128bbad70a24e1af
658,144
def euterpea_len (note): """ Returns the Euterpea length name for a music21 note. Args: note (music21.note.Note): The note to convert. Returns: str: The Euterpea length name. """ lookup = { 0.125: 'tn', 0.1875: 'dtn', 0.25: 'sn', 0.375: 'dsn', ...
a1c40a2e9e1316140e8552b72a150847f1842b28
658,145