content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def read_path(path): """ Fetch the contents of a filesystem `path` as bytes. """ return open(path, 'rb').read()
3ea784bf47cd87deb245608ccce8aca03f76e4ac
595,756
def _parse_creation_options(input_str): """ Helper callback function to parse additional dataset creation options. """ return input_str.split("=")
462d62205ef7a9934173f5ce5ab684df14f15406
595,761
def distance_to_miles(distance): """ Distance in meters to miles """ return str(round(distance / 1609.3, 1)) + ' mi'
a9ecc9a55736f154594605c6eb43e4995417d1e7
595,762
def bone_distance(obj, bone1, bone2): """ Returns the distance between two bones. """ vec = obj.data.bones[bone1].head - obj.data.bones[bone2].head return vec.length
a8ce5382f49b911108d1252ee590579a8ab39dba
595,763
def parse_team_links(response): """Parse the links to individual teams from a franchise page to get injury reports.""" years = response.css('th[data-stat=year_id] a::text').getall() links = response.css('th[data-stat=year_id] a::attr(href)').getall() # Injury reports are only available from 2009 on...
a12b90e69330c977c6f4ab2e0313c80238ab1967
595,765
from math import pi, tan def polysum(n, s): """ n: number of sides s: side length Returns: The sum of area and perimeter**2 of the regular polygon defined by n and s, rounded to 4 decimal places. """ # Import pi and tan from math module # Calculate the area area = (0.25 ...
cc9ef08931848a164ee63994e52574388c086eed
595,767
def _remove_dupes(ls: list) -> list: """Remove duplicate values from a list.""" try: # Try the more efficient method first return list(set(ls)) except TypeError: # Fall back to a slower method ret = [] for v in ls: if v not in ret: ret.appe...
ceabf915565736f72b748c8ad8ebaf06ea667a33
595,768
import re def get_feat_shape(visual_archi, compress_type=None): """ Get feat shape depending on the training archi and compress type """ if visual_archi == "fasterrcnn": # the RCNN model should be trained with min_size=224 feat_shape = (-1, 2048, 7, 7) elif visual_archi == "maskrcn...
14a968924a1ee6be7f10de08578c19b8daadddd9
595,769
from typing import List def anydup(lst: List) -> bool: """Check if are there any duplicate value in the input list Parameters ---------- lst : list list of values Returns ------- bool """ seen = set() for e in lst: if e in seen: return True seen....
44ec835dd61d2ed7489a2924cbeb4a529442bdf2
595,772
def quote(path): """Return a path with quotes added if it contains spaces.""" if " " in path: path = '"%s"' % path return path
c5abdd4d59e51c93238c59bb0d723a8e1305c119
595,773
def product_sum(lags, Vx, Vt, k1, k2, k3, Cx, Ct): """Product-Sum space-time model Separable space-time variogram model, based on a combination of 'sum' and 'product' models. Both base models are based on separated marginal variograms for the space and time axis. Parameters ---------- lags...
d74ea61ea3287597755bebc2794538f7589fe870
595,779
import string import random def generate_uuid(length=4, characters=string.ascii_letters + string.digits): """Generate a string of random characters. Args: length (int, optional): The length of the UUID to generate. characters (string, optional): The character set used to build the UUID. ...
396cf1d979b2bf4edbba0bd690ebc628a56abe77
595,782
def range2d(n, m): """ Returns a list of values in a 2d range Arguments: n: The number of rows in the 2d range m: The number of columns in the 2d range Returns: A list of values in a 2d range """ return [(i, j) for i in range(n) for j in range(m)]
62df44df50403d3cc9e1ea1aa761bc0044b85676
595,783
def addSeqTokensArgs(parser): """ Add arguments defining DNN processing sequences of tokens Parameters: - parser -- argument parser as an object of ArgumentParser to add arguments Returns: constructed argument parser """ parser.add_argument('--seq_len', default=None, type=i...
15bb822b8f96f58c7e8f30af1789a36bc2471f15
595,786
def tree_size(tree) -> int: """ Recursively counts the number of nodes in the tree including the root node. """ return sum(tree_size(child) for child in tree.children) + 1
de8fe4e25cdc85a466e0faeb146012913c82dcc1
595,788
def get_ffmpeg_concact(file_names): """Returns the file names in a formatted string for the 'ffmpeg concat' command""" lines = ["file '{}'".format(f) for f in file_names] return '\n'.join(lines)
6c13d27821f212c253c9a44d276b8e9cdc48657a
595,789
def get_counting_line(line_orientation, frame_width, frame_height, line_position): """ This function return the cordd of the counting line by the line position and the frame width and height. :param line_orientation: string of the orientation of the line.need to be top, bottom, left, right. example- if righ...
d0f53ebc2dacc3fd4f76eca32be974fec4fb7e07
595,795
def get_drop_connect_rate(init_rate, block_num, total_blocks): """Get drop connect rate for the ith block.""" if init_rate is not None: return init_rate * float(block_num) / total_blocks else: return None
d541925de42daaf9c424053b9673c963cc904341
595,796
def tobytes(size_str): """Convert human filesizes to bytes. https://stackoverflow.com/questions/44307480/convert-size-notation-with-units-100kb-32mb-to-number-of-bytes-in-python Special cases: - singular units, e.g., "1 byte" - byte vs b - yottabytes, zetabytes, etc. - with & without spa...
db8c36bb35c757462ea3b6f338ef17bf451e5a47
595,797
def trim_prefix(text, nchr): """Trim characters off of the beginnings of text lines. Parameters ---------- text : str The text to be trimmed, with newlines (\n) separating lines nchr: int The number of spaces to trim off the beginning of a line if it starts with that many s...
de4d7e1ed7146359f75fdfad91ddadfbef80dd67
595,799
def is_foam_var(key): """Test if the variable is an OpenFOAM variable""" return key.startswith("WM_") or key.startswith("FOAM_")
61b60f0386dac6ead436b7c512aa14a76c568475
595,800
def checkavailrawpc (context, am): """Returns a list of node objects representing available raw PCs at the given aggregate.""" avail = [] ad = am.listresources(context) for node in ad.nodes: if node.exclusive and node.available: if "raw-pc" in node.sliver_types: avail.append(node) return av...
66a1c9b8c929002b76f90416bc97792446b4a98e
595,801
def get_color_from_cmap(val, val_min, val_max, cmap): """Return color. Args: val (float): value to get color for from colormap (mV) val_min (int): minimum value of voltage for colormap (mV) val_max (int): minimum value of voltage for colormap (mV) cmap (matplotlib.colors.Colorma...
da538abe4ecc3dd24ff445e3e75774e3e938f568
595,803
import functools def optional_argument_decorator(_decorator): """Decorate your decorator with this to allow it to always receive *args and **kwargs, making @deco equivalent to @deco()""" @functools.wraps(_decorator) def inner_decorator_make(*args, **kwargs): if len(args) == 1 and len(kwargs) ...
664efefc80ce5c3ea50dd5d5fbb2ae4291db69ac
595,804
def crop_rescale_img(im, crop_reading=0.3, pix_thres=230): """ Auxiliary function that performs simple modification to an image: 1) makes it greyscale,2) crops it around landmarks (group='PTS'), 3) rescales it """ try: im = im.crop_to_landmarks_proportion(crop_reading) except ValueError:...
4f0368c818d912e5b1760cd2552e076f64b86fb5
595,805
def get_namespaces_with_prefixes(namespaces): """ Get a dictionary of namespaces less namespaces that have no prefix Args: namespaces (:obj:`dict`): dictionary that maps prefixes of namespaces their URIs Returns: :obj:`dict`: dictionary that maps prefixes of namespaces their URIs """ ...
10ccfac66fa34eed2b588bf9da1601b2f64198cf
595,808
import click def command_line_timelines_options(f): """ Decorator for common timelines command line options """ f = click.option( "--exclude-replies", is_flag=True, default=False, help="Exclude replies from timeline", )(f) f = click.option( "--exclude-re...
a42a95b6bc34a35419929eba546121e8c6c5ccb5
595,809
from typing import OrderedDict def _remove_duplicates(input_list): """Remove duplicate entries from a list. This operation preserves the order of the list's elements. Args: input_list (list[Hashable]): The list whose duplicate entries shall be removed Returns: list[Hashable]: The in...
9613674ceb137eb1a46a394efda1617593203888
595,810
def _TopRegressions(recent_anomalies, num_to_show): """Fills in the given template dictionary with top regressions. Args: recent_anomalies: A list of Anomaly entities sorted from large to small. num_to_show: The number of regressions to return. Returns: A list of top regression Anomaly entities, in ...
7672099349adc2e8684c75890fd88fa6d171a4c2
595,813
import re def _is_overlay(source): """ Check if the identified source is an overlay (partially transparent) layer. Parameters ---------- source : dict The tile source: web tile provider. Must be preprocessed as into a dictionary, not just a string. Returns ------- bo...
eeb499a6195872dcc7554845c918c9c80ec32a77
595,814
import pathlib def resolve(path): """ Resolves the supplied path :param path: Path to be resolved :return: The resolved path """ p = pathlib.Path(path) return str(p.resolve())
f0bb3882c1304b7bbbbd893d5b23ad4fd310d401
595,816
import json def load_labels(key_path: str) -> dict: """Loads labels, filling missing values with empty string. """ required_keys = ['company', 'date', 'address', 'total'] defaults = dict((k, '') for k in required_keys) text_data = json.load(open(f'{key_path}.txt', 'r')) # text_data = default...
84f8e6a4b5d5aff8104f2c5c81afcc0a959199a8
595,818
import six def _get_selections_from_property_and_vertex_fields(property_fields_map, vertex_fields): """Combine property fields and vertex fields into a list of selections. Args: property_fields_map: OrderedDict[str, Field], mapping name of field to their representation. I...
2560dae51abfd2dd3c40bfab853706c33419d73c
595,820
import math def num_haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float: """ Vectorized haversine distance calculation :param lat1: Initial latitude in degrees :param lon1: Initial longitude in degrees :param lat2: Destinatio...
77618d4c70a202e8e7a21865e569f96333864fd0
595,821
def issnswrapped(logitem): """ Checks if the message is in an SNS wrapper """ return 'Type' in logitem and logitem['Type'] == 'Notification' and 'Message' in logitem and 'MessageId' in logitem
16c4a896a324f2c79c7f2a312d6d9a2ae2dae887
595,822
def scale(kernel): """ Scales a 2D array to [0, 255] """ minimum = min(min(k) for k in kernel) maximum = max(max(k) for k in kernel) return [[int(255 * (k - minimum) / (maximum - minimum)) for k in row] for row in kernel]
bb9f6aa1603547fef1629724d3366c5b05487edf
595,826
def geom_as_list(geometry): """Return the list of sub-polygon a polygon is made up of""" if geometry.geom_type == "Polygon": return [geometry] elif geometry.geom_type == "MultiPolygon": return geometry.geoms
6e6546dcd81d29ccfdf98dc5d6e9f3d8623e3dc6
595,827
import six def python_portable_string(string, encoding='utf-8'): """Converts bytes into a string type. Valid string types are retuned without modification. So in Python 2, type str and unicode are not converted. In Python 3, type bytes is converted to type str (unicode) """ if isinstance(string, six.str...
22e76654548859270783e1edaeacad52b3fc724f
595,831
import json def _decode_metadata(metadata_str): """Decode a UTF-8 encoded JSON string to dict Parameters ---------- metadata_str : string (UTF-8 encoded) Returns ------- dict """ if metadata_str is None: return None return json.loads(metadata_str.decode("utf-8"))
e11ca4da2e30c909a546458e2e5303b4653386e9
595,834
def isInt( obj ): """ Returns a boolean whether or not 'obj' is of type 'int'. """ return isinstance( obj, int )
9cbf03c1dc1bed1680c3d7c0ad59fa65848f5d2c
595,835
def get_class_name(object): """Returns the class name of a given object.""" return object.__class__.__name__
d06c1b7b985c06506f21c91effa512b54b31d113
595,840
def next_power_of_2(n): """Return the smallest power of 2 greater than or equal to n""" n -= 1 n |= n >> 1 n |= n >> 2 n |= n >> 4 n |= n >> 8 n |= n >> 16 n += 1 return n
4abd3e72af0ac8be82a7115584bcf481c959d573
595,847
import sqlite3 def create_entry(conn, tweet): """ Store new tweet in db :param conn: DB connection :param story: Tweet data :return: Row id of new tweet """ sql = ''' INSERT INTO tweets(created_at,full_text,tweet_id,source,retweets,favorites,geo,coordinates,place,reply_to,deeplink) ...
efec199115008b6906a722928925c3bee4f03b34
595,848
def find_first_nonzero(response): """ Parameters ---------- response : iterable Every item is a dictionary which must contain at least keys: 'open','close', 'high', 'low'. Returns ------- int First index where the entry is not zero. If none found,...
0a95c71508536090cad6809af7ea08e33ff4db32
595,850
def get_form(trans, form_id): """Get a FormDefinition from the database by id.""" form = trans.sa_session.query(trans.app.model.FormDefinitionCurrent).get(trans.security.decode_id(form_id)) if not form: return trans.show_error_message("Form not found for id (%s)" % str(form_id)) return form
bf041340fd2fd40076ac9519349ab57dd2ea76a5
595,851
def _filename_info(name): """ Compose the filename for an info-file given its name. :param name: String with name of the info-file. :return: String with filename for the info-file. """ return name + '.json'
c9c47545a511a6f86c0820df9520b0c3584d6105
595,855
def read_parent_node(dismod_file): """Get ``node_id`` for parent location.""" return int(dismod_file.option.query("option_name == 'parent_node_id'").option_value)
4c720d20c67c850bc34794b270d7531e8646381b
595,858
def type_to_string(type_obj): """Given a python type, return its JSON schema string counterpart.""" type_str = type_obj.__name__ if type_str == "str": return "string" if type_str == "float": return "number" if type_str == "int": return "integer" if type_str == "bool": ...
395caea8a89e5c6921837e954bf46d613ea258d2
595,859
import random import string def random_alphanumeric(length: int) -> str: """ Returns random str with the combination of alphabetic and numeric :param length: char length :return: [0-9a-zA-Z] """ letters = string.ascii_letters + string.digits random_str = ''.join(random.choice(letters) fo...
766a6ed24da7ddd7b581825c2e0d27654448795f
595,860
import re def chapters(text: str, num_chapters: int = 100, include_title: bool = False) -> list[str]: """ Splits text into an array of individual chapters. This function expects chapter formatting to be something like: "Very probably, I'm afraid," she said. Chapter 14 The ...
4cfdb530bf7afa14726e324eab02ac57f44245ae
595,862
def get_index_by_header( render_table, header_value, obj_cls=None, item_type=None ): """ Return the column index based on field header value. :param render_table: Study/assay render table :param header_value: Header value :param obj_cls: Class of Dango model object for searched header (optional...
7bef17a7d500675d869010b684f3de696ce384fd
595,865
def _cv_delta(x, eps=1.): """Returns the result of a regularised dirac function of the input value(s). """ return eps / (eps**2 + x**2)
8dcfc19acd0f311ea7ffa12c2a1d7b806d69c59b
595,866
def set_filenames(base_models, training_name, chosen_model): """Set filename values needed for object detection training. Args: base_models (dict) - possible pre-trained models training_name (str) - user-selected name for model chosen_model (str) - the user-selected pre-trained model ...
895338446574f7f626ef08bb0770e8e573d73ec7
595,871
def _swap_first_args(op): """ Given a binary operator function, return a function that applies it but with argument order swapped for the first two arguments. """ def op_swapped(a, b, *args, **kwargs): return op(b, a, *args, **kwargs) return op_swapped
de070bcf22dc11fdd34f8507be14729dd5c0ceb2
595,878
import base64 def base64decode(data): """ Return decoded data where data is base64 encoded binary data. :param str data: Base64 encoded binary data. :return: Decoded data :rtype: bytes """ return base64.b64decode(data)
505cd496d6544c33111845d6c38abb8407106904
595,879
def engine_and_raw(request): """engine and raw keyword arguments for rolling.apply""" return request.param
03fa1b9fe97c85cdfc2c4b736e8c7ad3dee56f0b
595,883
def _merge_batch_class(existing, other): """ Sets or unions two sets, for building batch class restrictions. If existing is None, the other set is returned directly Parameters: existing: iterable object of the current batch classes other: iterable object of batch classes to add Ret...
4f7993315a8086a1fe453a32871adbbce844655e
595,885
def recursive_fibonacci(n): """ Find the Fibonacci number of order n by recursion """ if n < 2: return n else: return recursive_fibonacci(n-1) + recursive_fibonacci(n-2)
45bbeda890d9137647f26903bc911319498d2226
595,887
def one(iterable): """Return the first entry of *iterable*. Assert that *iterable* has only that one entry. """ it = iter(iterable) try: v = next(it) except StopIteration: raise ValueError("empty iterable passed to 'one()'") def no_more(): try: next(it) ...
f78ddb3fb72cbf4d664f83bf097e45d89066f5bf
595,893
def email_project_info(project): """ Header for the email. e.g. Project ID, Project title, Submitting Author. """ header = ("Project title: {}\n" "Submission ID: {}\n" "Submitting author: {}" ).format(project.title, project.slug, project.submitting_author()) return header
b7525245f8af8300802030330f2f7741c2299088
595,899
def juxt(*fns): """ Takes a set of functions and returns a fn that is the juxtaposition of those fns. The returned fn takes a variable number of args, and returns a vector containing the result of applying each fn to the args (left-to-right) >>> juxt(first, second, last)(list(range(10))) [0, 1, 9]""" ...
7337d4fc7f9b726ae220be665c57d092e0cc4aa4
595,902
import random def shuffle_data(corpus, seed): """ Shuffle the data. corpus is list of lists (sentences) to be shuffled. Note: I will use the convention that seed 0 means no shuffle. If seed is None that also means no shuffle will occur. """ if seed not in {None, 0}: random.seed(seed) ...
a852fa754c9322861add1d159c97508baddcdf54
595,903
def split_file_path(full_file_path: str, dir_separator: str = '/') -> list: """ Splits the filepath at the last `dir_separator` to extract the filepath and the filename. Example: Input: '/path/to/file.ext' Output: ['/path/to/', 'file.ext'] Arguments: full_file_path: A full fil...
a84db14a3dd1876d52d5e7595ac91f2498ceed73
595,907
def minEdge(graph, i, vertices): """ Returns the minimum edge weight in the graph, ending at vertex i. """ min = float('inf') for j in range(vertices): x = graph[i][j] if(x < min and i != j): min = x return min
7ea260abb623782333e58a9706f7d68c6e072420
595,913
import time def showExecTime(startPoint, initialString = "", verbose=True): """ Compute the execution time from an initial starting point. You can also pass me a string to print out at the end of computation. Parameters ---------- startPoint : float, timestamp of the starting point in...
7756557e6b88962f4df18538eb5622bdb0378199
595,914
import math def round_sig(x, sig=2, method='round'): """Round float x to sig significant figures. method = string: 'round': round by standard rounding rules (default) 'ceil': always round up 'floor': always round down See http://stackoverflow.com/questions/3410976/how-to-round-a-n...
63bdbf78ace508d0fcc0ad703e364e7641b47d6f
595,921
def is_in(mfrlist, key): """Return True if key is in mfrlist, False otherwise""" return (mfrlist .map(lambda e: e == key) .reduce(lambda a, b: a or b, False))
5afde8b8b1d360b5b680ecde3a49cdcd8a06ce85
595,923
def Pretty(path): """Removes 'end_snippet.' prefix if present. Args: path: the path to remove prepended 'end_snippet' from. Returns: The path de-cluttered with informationless 'end_snippet' prefix. """ if path.startswith("end_snippet."): path = path[len("end_snippet."):] return path
da7045321a03bb1c1345db41ca2f9807c13f8287
595,924
def terminate_criterion_y(verts, f_difference, x_tolerance, y_tolerance): """Return True if f_difference < y_tolerance, else false. Args: verts: The verticies of a simplex f_difference: The absolute difference of the last and secondlast function_value x_tolerance: a real v...
4a08ec91c0b0268441f6eb62cc04e928a448d8c6
595,925
import hashlib def calcFileSha256(filname): """calculate file sha256""" with open(filname, "rb") as f: sha256obj = hashlib.sha256() sha256obj.update(f.read()) hash_value = sha256obj.hexdigest() return hash_value
7b9ac5d36e89b8708733b0acf6be4f002b90f659
595,926
def clean_capillary_refill_rate(v): """Clean the capillary refill rate (CRR) variable Args: v (pd.Series): Series containing all CRR values Returns: v (pd.Series): Series containing all cleaned CRR values """ crr_map = {'Brisk': 0, 'Delayed': 1, 'Normal <3 secs': 0, 'Ab...
0ac8e84e336b32bc792175c23b8bb4b701b41329
595,930
def _normalize_percent_rgb(value: str) -> str: """ Internal normalization function for clipping percent values into the permitted range (0%-100%, inclusive). """ value = value.split("%")[0] percent = float(value) if "." in value else int(value) return "0%" if percent < 0 else "100%" if per...
9cbe028bc86d8c02fd03d7f22ac8ce899cf47ba7
595,931
def pad_array(x, max_len=None): """ pad input 2d array (list of list), if max_len is given, may truncate inner 1d array: e.g. x = [[3, 46, 73, 43, 46], [19, 65, 64], [2, 82, 55, 4], [18, 82, 76, 18, 82, 28, 82, 27, 2, 82, 36], [2, 46, 82], [25, 65, 39], ...
cd893d000a1befa6cf9b7544bc46d7d115ee638d
595,934
def GetIdentifier(default): """Return the identifier for the keychain.""" return default
62eda10986da424d39235051917d53715cdccb38
595,935
import six def get_allowed_params(params, whitelist): """Extract from ``params`` all entries listed in ``whitelist``. The returning dict will contain an entry for a key if, and only if, there's an entry in ``whitelist`` for that key and at least one entry in ``params``. If ``params`` contains multipl...
591d2d68011eb0e310d8eeccea67be22221d21f2
595,939
def nice_size(size, number_only=False): """ Returns a readably formatted string with the size If ``number_only`` is set, return the number as a string; otherwise, add the unit (e.g., KB, MB). If the ``size`` cannot be parsed, return ``N/A``. >>> nice_size(100) '100 bytes' >>> nice_size(1000...
ce52a9e775bf5d09dd38b66cab311771a15152cf
595,941
def rotate_word(word, shift): """ Take a string and rotates the words around, tape-style. word: a string to be rotated shift: an integer, how much to rotate the string 'abc' +1 is 'cba' """ shifted = "" overflow = word[-shift:] # Takes the last n = shift chars secondpart = word[0:-shift]#sli...
9505b34decbaf71ae868929ca7fd8365488739b4
595,942
def edit_modified_distance_dp(pattern,text): """ This function takes 'pattern' and 'text' nucleotide sequences and compares them forming the DP matrix, which contains the path of the optimal alignment. It uses a modified version of the edit distance approach, which contemplates the presence of transposi...
45b428f1c4e4a377b8a0f90934c23c48280e7a4e
595,949
import torch def _get_triplet_mask(labels): """Return a 3D mask where mask[a, p, n] is True iff the triplet (a, p, n) is valid. A triplet (i, j, k) is valid if: - i, j, k are distinct - labels[i] == labels[j] and labels[i] != labels[k] """ device = torch.device("cuda:0" if torch.cuda.i...
d4cfc40a354af2d5063e4f7af46328f50c443144
595,952
def _server_run_on_save() -> bool: """Automatically rerun script when the file is modified on disk. Default: false """ return False
7360c0f4649cb299749730d55a840075f7a4fb5c
595,953
from typing import OrderedDict def orderify(obj): """Convert dicts (recursively) to ordered dicts with sorted keys""" if isinstance(obj, dict): for key, value in obj.items(): if isinstance(value, dict): obj[key] = orderify(value) continue if isi...
bd0cc8d36fd666fa6dc27425c9a613032d726d59
595,956
def get_status_code_value(status_code): """function to return appropriate status code value from the dictionary""" status_code_dict = { "100": "Continue", "101": "Switching Protocols", "200": "OK", "201": "Created", "202": "Accepted", "203": "Non-authoritative Information", "204": "No Content", ...
162e5f9b5f7ce151435661345ab2333eccef0cfb
595,959
def sanity_check_args(args): """ Check that command-line arguments are self-consistent. """ if args.weeks_ahead and (args.gw_start or args.gw_end): raise RuntimeError("Please only specify weeks_ahead OR gw_start/end") elif (args.gw_start and not args.gw_end) or (args.gw_end and not args.gw_s...
da4d9333f79eb923dcadd2023a4756f562e35f7a
595,962
def rotate_left(node): """Perform left rotation around given node.""" new_root = node.right grandson = new_root.left node.right = grandson new_root.left = node node.compute_height() return new_root
08128b90bd36c303025b5656077b79a24ca561ab
595,966
def escaped_str(s: str): """Escape all special characters in the string. Some special characters can have surprising effect, such as the newline character. For example it is common that the vocabulary file have one line per token, but if the token contain a newline character, it will be counted as two tokens...
1b8d2827ae65036d8b684e155401511d2c0f183f
595,967
import six def encode(obj, ascii=False): """ Encode the object arg as ascii (unicode-escaped) if `ascii` true or utf8. """ if isinstance(obj, six.text_type): obj = obj.encode("unicode-escape" if ascii else "utf8") return obj
afeda7cab98745b3c62f2961093f2a9dd8b18c0b
595,973
def get_db_login(path='../data/db_details.txt'): """Get login details for database from file.""" with open(path, 'r') as f: lines = [line.strip() for line in f] login_dict = {i.split(":")[0].strip(): i.split(":")[1].strip() for i in lines} return login_dict
01f2e25a351af6d19d3c93989c00cba7cf3161a8
595,982
from typing import List from typing import Any from typing import Dict import torch def my_data_collator(features: List[Any]) -> Dict[str, torch.Tensor]: """ A nearly identical version of the default_data_collator from the HuggingFace transformers library. """ first = features[0] batch = {} ...
80e8e92fee033716ee1e5b22231e6127d2c6349e
595,991
def parse_bsrate_report(report): """Parse bsrate report file.""" bsrate_dict = {} with open(report, "r") as r: first_line = r.readline() if not first_line.startswith("Bisulfite conversion rate process skipped."): bsrate_dict["Overall conversion rate"] = first_line.split()[-1] ...
9ee30ec5a715e2cdad195fe5de1db9991db87e68
595,994
import gzip import pickle def load_gzipped_pickle(filename: str) -> dict: """ The function loads gzipped and pickled items / sessions object. Parameters ---------- filename : str Returns ------- pickled_object : dict """ with gzip.open(filename, 'rb') as fstream: pick...
4601083db8484904e91abf6c636cace981f5a713
595,996
def name_generator(nn_name, nn_name2id): """ 生成paddle.nn类op的名字。 Args: nn_name (str): 名字。 nn_name2id (dict): key为名字,value为名字出现的次数-1。 """ if nn_name in nn_name2id: nn_name2id[nn_name] += 1 else: nn_name2id[nn_name] = 0 real_nn_name = nn_name + str(nn_name2id[nn...
a1788af5a9df1618d161ce725ab7839405faef66
595,997
def _get_tensor_name(node_name, output_slot): """Get tensor name given node name and output slot index. Parameters ---------- node_name : str Name of the node that outputs the tensor, as a string. output_slot : str Output slot index of the tensor, as an integer. Returns --...
07ba4dc1fd9452ddf9b48c07462d140a938f9351
595,999
def breakArgs(string): """turns name(arg1,arg2) into ('name','arg1,arg2')""" split = string.split('(') split[1]=split[1][:-1] return tuple(split)
38e532df812b080512a3c665cc86e27b61f43b6c
596,001
import math def vToA( x, y, a ): """calculate angle from a 2D vector and default value""" if y == 0: # dangerous special case (avoids div by 0 in dx/dy) if x > 0: return math.pi * 0.5 elif x < 0: return -math.pi * 0.5 else: # don't change ang...
4dd52355b2d1ee8191a35d263d372e4e9101ff3e
596,003
import requests def getSTCNBooks(ENDPOINT: str = "http://data.bibliotheken.nl/sparql"): """ Get all books (Manifestations) from the STCN collection that have "Rijksmuseum" as holding archive. Args: ENDPOINT (str, optional): SPARQL endpoint """ q = """ PREFIX rdf: <http://www.w3....
99bc777a95af5f461ee8fd942e3c3053a5408db5
596,005
import time def time_to_unix(str_time): """ convert str time tp unix timestamp :param str_time: yyyy-mm-dd :return: timestamp """ return time.mktime(time.strptime(str_time, "%Y-%m-%d"))
f786924d5a2324fba4cf0cdbb5b0b8b238242de4
596,009
def read_prefs_file(day): """ Reads the prefs file for 'day' and returns the line-by-line text. """ fname = "prefs/" + day + ".txt" with open(fname) as f: return f.read().splitlines()
107a7ac795828749f823cdbc29c81f17d3f1a259
596,010
def guess_correct_module(example): """ Given some form of the example name guess and return a reasonable module. Examples -------- >>> guess_correct_module('example1') 'peripy.examples.example1.example' >>> guess_correct_module('peripy.examples.example1') 'peripy.examples.example1.examp...
58e22a347eaa55ba079f9b67051d996070bdd350
596,011
def product_of_3( numbers ): """ From the given list of numbers, find the group of 3 numbers that sum up to 2020. This function returns the product of those 3 numbers. """ numbers = [ int( item ) for item in numbers ] for i in range( len(numbers) ): for j in range( i+1, len(numbers) ): ...
a11073dacf11c35ace150013da2055c5092f85d4
596,012
def addTFAsSteps(tf,RGBa,bin_edges): """adds a general RGBa array to transfer function as step functions. Parameters ---------- tf : yt ColorTransferFunction the transfer function, already initialized RGBa : ndarray, shape (4,N) The RGBa values for each step, values between 0,1 ...
50dbab1041240c02ed26cf127a91c884c8d1f5ce
596,014