content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def single2float(x): """Convert a single x to a rounded floating point number that has the same number of decimals as the original""" dPlaces = len(str(x).split('.')[1]) y = round(float(x),dPlaces+2) # NOTE: Alternative method: #y = round(float(x),6) return y
4501bd8ebc17102ecbc82f4a26615adc3ef4639f
561,721
import hashlib def hash_object(*objects, hasher=None): """Hash the given object(s) and return the hashlib hasher instance If no hasher argument is provided, then automatically created a hashlib.md5() """ if hasher is None: hasher = hashlib.md5() for obj in objects: if...
7e072d27d625f47dde75f5119a5bb1f8e57202fb
640,991
def find_overlap(bta, btb, r=0.01): """ Overlaps two pbt.BedTool objects based on reciprocal overlap (r) Matches on CNV type (assumes the fifth column = CNV type) Returns: two lists of interval IDs of the overlapping set """ ibt = bta.cut(range(5)).intersect(btb.cut(range(5)), f=r, r=True, wa=T...
7e76f5a90266079f5f4c03d5106af810e8d9c19b
411,790
import ast def get_functions(_ast): """ Gets all function definitions immediately below an ast node @param _ast the ast node to search for functions in @return a tuple of function definition ast nodes """ return (node for node in _ast.body if isinstance(node, ast.FunctionDef))
8d9816b9ea6c20090e72e833644c69dbf982d436
646,166
def extract_doi(doi): """Ensure that 'doi' is a single string Occasionally, INSPIRE returns a list of identical DOIs. This just extracts the first element if it is such a list, or returns the input otherwise. """ if isinstance(doi, list) and len(doi)>0: return doi[0] return doi
cd799512101792c3506ab70b3d29b033e1f1429e
528,275
def format_line(line): """ Format a line of Matlab into either a markdown line or a code line. Parameters ---------- line : str The line of code to be formatted. Formatting occurs according to the following rules: - If the line starts with (at least) two %% signs, a new cel...
2ef8ea7d1c5aaff0a3fc11d7013c2a0722617f97
114,958
def DuplicateStyleDict(style_dict): """Duplicates the style dictionary to make a true copy of it, as simply assigning the dictionary to two different variables only copies a reference leaving both variables pointing to the same object. @param style_dict: dictionary of tags->StyleItems @return: a...
3d7a53c9b3490d21355daaaa88c0ae2221526887
434,604
def MockMethod(*_args, **_kwargs): """ Absorbs all arguments, does nothing, returns None. """ return None
366a14e6964c06e6125fd877c4fc61e95ef404d4
512,520
import uuid def is_convertible_to_UUID(value, version=4): """Returns True if value is convertible to UUIDs UUID v.4 General Format: - xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx - where x is a hex digit and y is one of (8, 9, A, B) Using python uuid.UUID and as so, Supporting these forms: ...
1a42ee06cdddeae977c0a6bdc4aa87a5c02f8b72
362,016
import re def strip_numeric(s): """ Remove digits from `s` using RE_NUMERIC. """ RE_NUMERIC = re.compile(r"[0-9]+", re.UNICODE) return RE_NUMERIC.sub("", s)
095f1adf9ad31f5500d4c2e1a79c31147eb879f4
475,570
def reformat_timezone_offset(in_date_string): """ Reformats the datetime string to get rid of the colon in the timezone offset :param in_date_string: The datetime string (str) :return: The reformatted string (str) """ out_data = in_date_string if ":" == in_date_string[-3:-2]...
279fbf00ff51f0926f3d284faee66a43327298e4
32,006
def timedur(x): """ Print consistent string format of seconds passed. Example: 300 = '5 mins' Example: 86400 = '1 day' Example: 86705 = '1 day, 5 mins, 5 sec' """ divs = [('days', 86400), ('hours', 3600), ('mins', 60)] x = float(x) res = [] for lbl, sec in divs: ...
33ba00c3354174a49b91addd4243f22859433b35
239,360
def adder(x: int | float, y: int | float) -> int | float: """ Simple function that adds two numbers (int or float) :param x: first number to add (int or float) :param y: second number to add (int or float) :return: result of addition (int or float) """ return x + y
5aa722eec8a71cfd8d62d81ded6aceb3662eb65d
329,397
import torch def get_spixel_prob(spixel_x, spixel_y): """ generate soft assignment matrix via probability vector in x and y direction Args: spixel_x: torch.tensor A trainable tensor indicating the probability that pixels belong to superpxiels in x direc...
214916083bc2bbdc153f082be648623e6609f238
141,974
def expand_unknown_vocab(line, vocab): """ Treat the words that are in the "line" but not in the "vocab" as unknows, and expand the characters in those words as individual words. For example, the word "Spoon" is in "line" but not in "vocab", it will be expanded as "<S> <p> <o> <o> <n>". """ ...
9c20267e7bf6a31f7f21411ec1db701e088268a1
636,625
def sources_list(sources, params): """ Adds defined list of sources to params Parameters ---------- sources : list Payment sources params : dict Default params Returns ------- dict params with sources """ if isinstance(sources, list): for sou...
7d056479fcc2144b1b886d60f5eca749c7c0303a
361,793
def docutils_node_to_jinja(list_item, only_pages=False, numbered=False): """Convert a docutils node to a structure that can be read by Jinja. Parameters ---------- list_item : docutils list_item node A parent item, potentially with children, corresponding to the level of a TocTree. ...
487ddc50fd69fb39a37d3bea48acf7221f81c0b8
407,246
def is_weekend_worked(x, wkend_type, i): """ Determine if i'th weekend is worked (full or half) for a given weekend pattern x and weekend type, :param x: list of 2-tuples representing weekend days worked. Each list element is one week. The tuple of binary values represent the fi...
e93069b0ebffdc32f1a5d415508e1f19c9f5a9db
353,351
from typing import List import string def format_int_alpha(value: int) -> str: """Format a number as lowercase letters a-z, aa-zz, etc.""" assert value > 0 result: List[str] = [] while value != 0: value, remainder = divmod(value - 1, len(string.ascii_lowercase)) result.append(string....
be83a2d76aa7f983a8603b4dfd46e46a5d05df5c
149,983
def LowerCamelCase(upperCamelCaseStr): """ Return the lowerCamelCase variant of an upper camel case string. """ return upperCamelCaseStr[0].lower() + upperCamelCaseStr[1:]
321e22b96984a241f5ad79ecd7297f58792bb384
61,648
def _GetDepsLine(path, js_source): """Get a deps.js file string for a source.""" provides = list(js_source.provides) provides.sort() requires = list(js_source.requires) requires.sort() return 'goog.addDependency(\'%s\', %s, %s);\n' % (path, provides, requires)
e4f5cec4d8e6e57bf0d825fc6eea9cb8cc7b940c
370,550
def rename_ending(file: str, condition: str, ending: str)-> str: """ conditional renaming of file name ending :param file: str file name :param condition: str file name ending to be compared with :param ending: str new ending :return: str """ file_name = file.rsplit(".", 1)[0] return...
ffdb1eb96b35ddcd1d40991bedbb53dcdb211f3a
285,487
def _prepare_params(params): """Convert lists to strings with ',' between items.""" for (key, value) in params.items(): if isinstance(value, list): params[key] = ','.join([item for item in value]) return params
ab012f730e4596618da14986184eee3f3085a27f
311,440
def get_vad_out_from_rttm_line(rttm_line): """ Extract VAD timestamp from the given RTTM lines. """ vad_out = rttm_line.strip().split() if len(vad_out) > 3: start, dur, _ = float(vad_out[3]), float(vad_out[4]), vad_out[7] else: start, dur, _ = float(vad_out[0]), float(vad_out[1])...
08cc36d23b916411878141824734143a604cf9af
451,212
def range_str(range_str, sort=True): """Generate range of ints from a formatted string, then convert range from int to str Example: >>> range_str('1-4,6,9-11') ['1','2','3','4','6','9','10','11'] Takes a range in form of "a-b" and returns a list of numbers between a and b inclusive...
7648683ec79ad93dcddd98378ab40f2dffb1f6e8
494,471
def isprimer(n: int) -> bool: """Is n prime? >>> isprimer(2) True >>> tuple( isprimer(x) for x in range(3,11) ) (True, False, True, False, True, False, False, False) """ def isprime(k: int, coprime: int) -> bool: """Is k relatively prime to the value coprime?""" if k < copri...
33fccf076604601bd40298f555180ee5388b00af
69,618
def gmres_params(n_krylov=40, max_restarts=20, tol_coef=0.01): """ Bundles parameters for the GMRES linear solver. These control the expense of finding the left and right environment Hamiltonians. PARAMETERS ---------- n_krylov (int): Size of the Krylov subspace. max_restarts (int): Maximum...
4eabe3f6595141b65e5097c449600089cad099b1
370,557
def gardner(vp, alpha=310, beta=0.25): """ Compute bulk density (in kg/m^3) from vp (in m/s). """ return alpha * vp ** beta
12c4ca35171b7091dac466a782b438e341fc3d71
623,875
def escape_sql_id(string): """Escape string into a valid SQL identifier.""" return '"' + string.replace('"', '""') + '"'
8764d87683da1a5f40a835227ab29cca756fa228
246,812
def is_overlapping(segment_time, previous_segments): """ Checks if the time of a segment overlaps with the times of existing segments. Arguments: segment_time -- a tuple of (segment_start, segment_end) for the new segment previous_segments -- a list of tuples of (segment_start, segment_end) for the...
27b817a76829eb7eba63d3fd22376e4164a7bf39
694,786
import csv def loadFlags(file): """Takes in a filename/path and reads the data stored in the file. If it is a single column of data returns a 1D list, if it is multiple columns of data returns a 2D list. Note the first line is skipped as it assumes these are column labels. """ with op...
cfd48269ed94b47dfd2c12e6a7f66f8106253f15
694,779
import logging def _check_api_error_message(json_data): """ Returns an error if one occurred and an empty string if the response was successful json_data -- the data returned from the UW API query """ #Ensure the response was received status_code = json_data['meta']['status'] logging...
3c0c274a599201683d35b48e04b2b27abcdc056f
532,236
def unflatten_like(vector, likeTensorList): """ Takes a flat torch.tensor and unflattens it to a list of torch.tensors shaped like likeTensorList Arguments: vector (torch.tensor): flat one dimensional tensor likeTensorList (list or iterable): list of tensors with same number of ele- ...
ae121ac963df5352d346fb59f8c9560b919e2bb4
573,280
def read_file(location, chomp=True): """ Read the specified file and return the contents. Optionally the file content could be subjected to a chomp operation before returning. Args: location Location of the file that needs to be read chomp True if the file content needs to be chomped ...
b736b8bf19ac30608a9f9105a1a2fe49a4a74c74
146,172
def send_onboarding_message(self, user_email: str) -> dict: """ Sends the onboarding message to a user. :param user_email: The email of the user to be on-boarded. :type user_email: str :return: The response from the message request as a dict. :rtype: dict """ user = self.get_user_by_ema...
a09790df550d68df209220746b48dc7d370f179f
305,163
def valid_att_in_field(arch): """A `name` attribute must be in a `field` node.""" return not arch.xpath('//field[not (@name)]')
e61d61bf4e6f38d256d50786bd74b7b772b2ca5d
211,143
def toklist_print(toklist): """ Helper function to print token lists with proper whitespace. """ out = [] for tok in toklist: if not tok: continue if tok.prev_white: out.append(" ") out.append(str(tok)) return ''.join(out)
24c859be10229da0bb0c39b03e79a86f63089072
419,118
def _convert_1hot_to_str(one_hot): """ Convert a one-hot class label vector, shape (1, num_classes), to a string. Returns: one_hot_string """ one_hot_string = one_hot.tostring() return one_hot_string
dc92d73caa79bd81a2ca14a640b3fe5e6a852da7
474,535
import ast def matches_attr(node, name): """Determines if the ``ast.Call`` node points to an ``ast.Attribute`` node with a matching name. Args: node (ast.Call): a node that represents a function call. For more, see https://docs.python.org/3/library/ast.html#abstract-grammar. name ...
fe76ee845fabc965ba15475c2a6c4098cbeae221
630,078
from typing import TextIO def read_until(f: TextIO, char: str) -> str: """ Returns the text from the current position in the file up to and including the given char. If we hit the end of the file before finding our character, a ValueError is raised. """ buf = "" cur = "" while cur != ...
9750131df37c936d35403fb6c984435d870182e9
610,820
from typing import Tuple def to_isometric(position: Tuple[int, int], tile_size: int = 64) -> Tuple[int, int]: """Take screen (X,Y) coordinates and translate them into Isometric space Args: position: (Tuple[int, int]) - position in top-down cartesian space tile_size: (int) - size (length & wid...
cf9b2b562ec29b42fd349c154df7cf5c790e16ce
517,757
def six_hump_camelback(x): """ Six-hump Camelback function (2-D). Global Optima: -1.031628453489877 at (-0.08983, 0.7126) and (0.08983, -0.7126). Parameters ---------- x : array 2 x-values. `len(x)=2`. `x[i]` bound to [-5, 5] for i=1 and 2. Returns ------- floa...
17e63651b686e9505e72774eea6beddb508d72f6
154,479
def valid_conversion(val, type_to_convert): """ Checking whether it is possible to convert val to the specified type :param val: value :param type_to_convert: type :return: boolean """ if isinstance(type_to_convert, type): try: type_to_convert(val) res = True...
6dddf95d633c55b63e1ed96a7efe3e8a7c108045
693,184
def get_number_of_verb(sentence_token): """Return number of verbs in sentence Args: sentence_token (tuple): contains length of sentence and list of all the token in sentence Returns: int: number of verb in sentence """ number_of_verb = 0 for word in sentence_token[1]: i...
7f9d404e204612ef8a5379566bde802997fc30ef
641,055
from typing import Any import importlib def dynamic_import_from(source_file: str, class_name: str) -> Any: """Do a from source_file import class_name dynamically Args: source_file (str): Where to import from class_name (str): What to import Returns: Any: The class to be imported ...
90c861f727c8e6f20f89b7af24c2163bc65bd516
697,319
def _dechunk(raw): """ Given a BLE advertisement in hex format, interpret the first byte as a length byte, return the data indicated by the length byte, and the remainder of the data in a tuple. The lenght byte itself is not included in the length. If the length indicated is longer than the da...
f04c8c91895a8c8b7b9a3b46461082531cf705c2
462,048
def add_sub_idx(i1: int, change: int): """ Adds or subtracts an index from another one and skips 0 if encountered. :param i1: The start index :param change: The change (+ or -) :return: The new index >>> add_sub_idx(-10, 10) 1 >>> add_sub_idx(10, -10) -1 >>> add_sub_idx(-5, 10) ...
942db377efb13da01e381ea76833b207e7ec5e0a
378,303
def unindent(text, skip1=False): """Remove leading spaces that are present in all lines of ``text``. Parameters ---------- test : str The text from which leading spaces should be removed. skip1 : bool Ignore the first line when determining number of spaces to unindent, and r...
c787f5176b7b38ab5e6caec5175c4de3bbf1bbf5
40,529
def count_from_0(index, collection): """Numbering function: consecutive integers starting at 0.""" return index
bc01bc8e46e913c325e4972b3bd71cd4d2543237
653,403
def get_cell_name(row): """Build cell name from FoV name and cell id.""" cell_name = "{0}_{1}".format(row["fov_name"], int(row["cell_id"])) return cell_name
be051ecf9e07c14227b696aceef2a7942f98bb38
335,748
import re def split_into_words(in_str:str) -> list: """ Helper function splitting the given string into a list of words. Hyphens are considered to separate words. :param in_str: The string to split into words :return: A list of words in the given string """ in_str = re.sub('[/ \-\t\n]+', ' ', ...
4248f79a7ccf398154cc8b8a0eda9517e2dd9255
344,240
import torch def channel_shuffle(x, groups): """Channel Shuffle operation from ShuffleNet [arxiv: 1707.01083] Arguments: x (Tensor): tensor to shuffle. groups (int): groups to be split """ batch, channels, height, width = x.size() channels_per_group = channels /...
0a89ee012784328294dedfc11975f06558eb45d2
388,871
def deep_update(cfg, other): """deep_update recursively mutates `cfg`, copying items from `other`, recursing when both values are dictionaries and overriding otherwise""" for key in other.keys(): if ( isinstance(other[key], dict) and key in cfg and isinstance(cfg[...
2665d0174a03d74b3933e15746c9b320f8c44243
578,175
def valueclass(*members): """ A classdecorator that makes a class into a standard value type. This decorator provides an __init__ method that takes in the supplied members and stores them in instance variables. This decorator also provides standard __eq__, __repr__ and __str__ functions that u...
2c02952f61da94c7b846fbd5d26849e0994b2d49
571,713
def choose_dimensions(valid_dims, overrides={}): """For each dimension, choose a single valid option (except for 'time', where we use the wildcard '*' to get the whole time-series.) If not specified, choose the first valid option for each dimension. Parameters ---------- valid_dims : dict ...
e5c732b88852e9a07116818935587f575ab290cf
289,318
def set_mock_response(requests_mock, response): """Register the given MockResponse with requests_mock""" requests_mock.register_uri(**response.as_dict()) return response
06adc17686602b621ebe8ef5417cafccda204e2d
152,390
def swap_to_title_case(word): """ Converts a word from any case to title case. E.g. 'mumbai' will become 'Mumbai' :param word: A string which is will converted to Title case. :return: A string in Title case """ return word.lower()[0].upper() + word.lower()[1:]
e78861e5c933684ed18d3e8aecaf7cdfe86260e7
213,361
def clean_dalton_label(original_label: str) -> str: """Operator/integral labels in DALTON are in uppercase and may have spaces in them; replace spaces with underscores and make all letters lowercase. >>> clean_dalton_label("PSO 002") 'pso_002' """ return original_label.lower().replace(" ", ...
e52f4aa75ee4ed0bc25e963b4616d0cd3e9fedc4
211,464
def toNearest(n, res): """ :param n: Number :param res: Resolution :return: Number rounded up to the closest multiplicate of res """ if n % res == 0: return n return (n // res + 1) * res
21033e60a4a5059acbe90fcd6f4782b242b55006
446,891
from datetime import datetime def get_utc_dt(event_time): """Takes a UTC time from API and returns a datetime object""" return datetime.strptime(event_time['data']['attributes']['starts_at'], '%Y-%m-%dT%H:%M:%SZ')
391a0722e40e6cf53e93662d43caa17e3a6c4560
374,872
def denormalize(img, mean, std): """Denormalize an array of images with mean and standard deviation. Parameters ---------- img: array An array of images. mean: float Mean of img array. std: float Standard deviation of img array. """ return (img * std) + mean
1a459a5dd76a69e862c404677eefaaaa3c5b54e2
609,423
def color_to_rgba(color): """Converts a color (tuple or string) to an RGBA tuple. This function does not validate the input, so if the input format does not match one of the formats listed below, the output format is not guaranteed. Args: color: The color to be converted. It can be: ...
cdec624a54e3a1ed3c5d8854dc93c82c453abf57
114,051
def get_incoming_connections(individual, node): """Given an individual and a node, returns the connections in individual that end at the node""" return list(filter(lambda x, n=node: x.to_node.id == n.id, individual.enabled_connections()))
df5a4acd99866e3b768d54a2d85256887f11091a
530,597
import re def remove_punct_tokens(mylist): """Takes a tokenized text and removes punctuation tokens""" returnlist = [] for elem in mylist: if not re.match(r'^[^\w\s]', elem): returnlist.append(elem) return returnlist
b430478b1c3da2c63cfad52d82037380a224dd28
262,044
import collections def plot_chromosome_dividers(axis, chrom_sizes, pad=None, along='x'): """Given chromosome sizes, plot divider lines and labels. Draws black lines between each chromosome, with padding. Labels each chromosome range with the chromosome name, centered in the region, under a tick. Sets the...
2698380cc827e25fe7b5f09ee7fdb683afa320c6
336,530
import logging def create_logger() -> logging.Logger: """Create logger. Returns: logging.Logger: General logger. """ logging.basicConfig(format="%(message)s", level=logging.INFO) logger = logging.getLogger('gyomei_detection') return logger
bfe6d0e06389f0bd8d2500cf09eef426bc755b0a
209,365
def _mat_vec_dot_fp(x, y): """Matrix (list of list) times vector (list).""" return [sum(a * b for a, b in zip(row_x, y)) for row_x in x]
9ab85561ee5eee056489324e5f5c594cb573c979
113,244
def encode(integer: int) -> bytes: """Encodes an integer as an uvarint. :param integer: the integer to encode :return: bytes containing the integer encoded as an uvarint """ def to_byte(integer: int) -> int: return integer & 0b1111_1111 buffer: bytearray = bytearray() while intege...
da3b6b320ddcc39ecf494fca564d6d3ae06faea9
695,434
import torch def log_binom(n, k): """ Returns of the log of n choose k. """ return torch.lgamma(n+1) - ( torch.lgamma(k+1) + torch.lgamma((n-k)+1))
b9275e8043533790cef92dcf9e65226a3e84dc6f
76,816
def get_partners(bam, bams): """ Returns the partner bam files having the same ID """ partners = [] for bam_iter in bams: if bam in bam_iter: partners.append(bam_iter) return partners
d691918b5f7ac8149c5afd0002b8ef245aed4f15
671,065
from hashlib import sha3_512 def sha512(obj: bytes) -> bytes: """ hash any bytes with sha3-512 :param obj: bytes object :return: the hash """ h = sha3_512() h.update(obj) return h.digest()
b6bd466589142c5a2dbe90fbd27d7a7c99d688f7
229,581
def dist_to_num(soup): """Extracts number from string e.g. '(0.4 miles)' -> 0.4""" return float(soup.text.strip().split('(')[-1].replace(')', '').split(' ')[0])
c71d3f4dbbe592805be7e1253dbe9dc1bd1a8b4f
375,304
def hangman(leftovertries): """Print out hangman ASCII graphic on incorrect guesses.""" allhangmans = [ """ ______ |/ | | o | ´|` | / \\ __|________""", """ ______ |/ | | o | ´|` | / __|________""", """ ______ |/ | | o | ´|` | __|________""", """ ______ |/ ...
46702936d9e9f3626458ffc9767735c91dbb11d0
322,814
def int_bounds(signed, bits): """ calculate the bounds on an integer type ex. int_bounds(8, True) -> (-128, 127) int_bounds(8, False) -> (0, 255) """ if signed: return -(2 ** (bits - 1)), (2 ** (bits - 1)) - 1 return 0, (2 ** bits) - 1
ea51d1932d743c00c0d90333efeefcabb5cc2f1b
437,548
import re def split_name(name): """Split the string name based on a specific regular expression.""" return re.split("_|-| |[0-9]|\(|\)", name)
f4343b8c5f2c73e29c19abbb662a9ec3aebb0c24
445,490
def processHoles(code, holes_decls): """Finds all hole symbols in the SMT-LIB code of the program and replaces them with appropriate references to their synthesis functions. Does nothing in case of verification. :param code: (str) Source code (in arbitrary language) of the program. :param holes_dec...
78daf2434e0638415fbde44f2d9fbeb97bcadab8
579,162
import random def random_indexes(a, b, feats_in_plot): """Support function for tSNE_vis Args: a: start index b: end index feats_in_plot: # of featuers to be plotted per class Returns: Random list of feats_in_plot indexes between a and b """ randomList = [] # Set...
2fad244becdc378dc3cc36ccc786634c7ec0d832
60,013
def widthHeightDividedBy(image, divisor): """Return an image's dimensions, divided by a value.""" h, w = image.shape[:2] return (int(w / divisor), int(h / divisor))
e7de8e4a80e9dcf7b1ca6000671a97de6c56a351
299,763
import torch def euler_angles_to_rotation_matrices(angles): """ Arguments: --------- angles: Tensor with size Kx3, where K is the number of Euler angles we want to transform to rotation matrices Returns: ------- rotation_matrices: Tensor with size Kx3x3, that conta...
a3fdad7a1496bc1f1a9170cc63c030451fd23812
243,632
import re def get_sofile_name(sofilename): """ get the .so file name ie: foo.so.0.0 -> foo.so """ return re.findall(r'.*.so', sofilename)[0]
a9a492c988e8cd78003616660ddf9a1535371451
160,538
import pathlib def last_two(path): """Return the last two parts of path.""" return pathlib.Path(*path.parts[-2:])
4cd1689b9cbae6b77583cc9fdd8dac60db32770a
225,840
def typeName(ty): """ Return the name of a type, e.g.: typeName(int) => 'int' typeName(Foo) => 'Foo' typeName((int,str)) => 'int or str' @param ty [type|tuple of type] @return [str] """ if isinstance(ty, tuple): return " or ".join(t.__name__ for t in ty) else: return ...
e1af991a1ae75847da8edee86eb688ccee525e4b
74,443
import six import warnings def string_to_text(value, deprecate_msg): """ Return input string coverted to text string. If input is text, it is returned as is. If input is binary, it is decoded using UTF-8 to text. """ assert isinstance(value, (six.text_type, six.binary_type)) if isinstance...
8facc8e1da3b63dce793e5f70c6226bacdf0b9c4
511,422
import yaml def get_tweet_templates(yaml_filename="../data/tweet_content.yaml"): """Read the tweet content yaml file and return a dictionary of template sentences to be formed into tweets""" with open(yaml_filename, 'r', encoding="utf8") as f: templates_dict = yaml.load(f, Loader=yaml.FullLoader) ...
7f783dac8bc102d53ca6b909753aeae332c1175f
536,965
def same_len_lists(A,B): """ Create lists of same size - A: list - B: list - returns: list (2 lists of same size) """ arrays = [A, B] max_length = 0 for array in arrays: max_length = max(max_length, len(array)) for array in arrays: array += ['------'] * (max_leng...
b4fba9223f0dc26c0071e6e7eff4d899e9755f23
155,357
def format_attributes(callable, *args): """ Format the results of *callable* in the format expected by Graphviz. """ value = callable(*args) if not value: return "" else: parts = [] for k in sorted(value): parts.append(f"{k}={value[k]}") return f"...
3443fff94441b26f446d007e7d3b25e8fe82b8b9
448,739
def unflatten_dict(dictionary, sep='.'): """ unflattens a dictionary into a nested dictionary according to sep Args: dictionary: flattened dictionary, i.e. there are not dictionaries as elements sep: separator to use when nesting. I.e. on what the keys are splot Returns: nested dictiona...
f6125051fde842c04e604e6dcb6e7da82160d1b5
290,582
def serialize_columns(columns): """ Return the headers and frames resulting from serializing a list of Column Parameters ---------- columns : list list of Columns to serialize Returns ------- headers : list list of header metadata for each Column frames : list ...
8906f8d2fbb94f4c0ffde147e5f04fddc2b2c515
291,576
def valid_sort(sort, allow_empty=False): """Returns validated sort name or throws Assert.""" assert isinstance(sort, str), 'sort must be a string' if not (allow_empty and sort == ''): valid_sorts = ['trending', 'promoted', 'hot', 'created'] assert sort in valid_sorts, 'invalid sort' retu...
cd2debc03b4dde717fd0e4a277b85410af03d508
379,444
def get_params(**override): """Returns default parameters dictionary for model.""" params = dict( # Model args num_channels=3, multiscale='Steerable', # 'Steerable', Laplacian', None nscales=3, steerable_filter_type=1, cnn='Conv', num_filters=[64, 64, 64, 3], paddi...
5dfb12f705ccda9c35103a125f20d8ac9d53e51f
621,089
def flat_vars(doc): """ Flat given nested dict, but keep the last layer of dict object unchanged. :param doc: nested dict object, consisted solely by dict objects. :return: flattened dict, with only last layer of dict un-flattened. """ me = {} has_next_layer = False for key, value in doc...
614eea5fe1cbfc1434780ab3fd87faeceb187b94
168,203
def error_max_retry(num_retries, err_string): """error_max_retry message""" return "Unable to retrieve artifact after {} retries: {}".format(num_retries, err_string)
16fd360db6e25fe5b4ce7c34b145c2325e52cd19
92,537
def send_message(key, channel_loc, message, get_info): """ Bot will send a message to Slack :param channel where the message wants to be send. :type str :param message that wants to be sent to Slack :type str :param see return :type boolean :return will return the action'...
d4c90ca3ac530ee6234da0e15dd44d9ab19e826e
448,690
def empty_path(tmp_path_factory): """Provides a temp directory with no files in it.""" return tmp_path_factory.mktemp('empty_dir')
2aeff1c813e4799725da4da7de1a5ec919bfb207
191,156
def timeframe_search(sensor_df_list): """Determines the timeframe for which data should be loaded. Locates the beginning and end date of each hourly averaged sensor dataframe and subsequently determines the eariest and latest date within all recorded sensor datasets Args: sensor_df_list (l...
86ea68acc38b1818e464d3e15ec59d19febf0f14
556,087
def _calculate_pa(row): """ Returns: The number of plate appearances by a player as an int based on the following formula: PA = AB + BB + SF + SH + HBP - IBB """ PA = (row['AB'] + row['BB'] + row['SF'] + row['SH'] + row['HBP'] \ - row['IBB']) ...
2ded4997d3b904616f6d5f6c74c90dd22d8fe334
187,342
import tempfile def tsv(df, **kwargs): """ Write ``pandas.DataFrame`` to a temporary tab-delimited file. Works in a ``with`` block (file is deleted at context teardown). >>> with tsv(df1) as f1, tsv(df2) as f2: ... # something that requires tsv file input (use f or f.name) """ fh = te...
e57750dc3c05f5b83b25885b700d101a8569797d
235,725
def createPlotMetaData( title, xLabel, yLabel, xMajorTicks=None, yMajorTicks=None, legendLabels=None ): """ Create plot metadata (title, labels, ticks) Parameters ---------- title : str Plot title xLabel : str x-axis label yLabel : str y-axis label xMajorT...
d0442babdba33613d218b7be037ff8322d8bbcd7
551,567
def getFoodNames(cursor): """Get dictionary from food id to food name.""" cursor.execute("SELECT id, name FROM Food") return dict([v.values() for v in cursor.fetchall()])
e3bbd6d655747cbb1350bc294e5ce86c0931b209
69,149
import re def StringToMakefileVariable(string): """Convert a string to a value that is acceptable as a make variable name.""" return re.sub('[^a-zA-Z0-9_]', '_', string)
15ae7faa71a625249cb17cf3804ab576fbe471a0
173,724