content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from collections import Counter
def most_common(words, n=10):
"""
Returnes the most common words in a document
Args:
words (list): list of words in a document
n (int, optional): Top n common words. Defaults to 10.
Returns:
list: list of Top n common terms
"""
bow = Co... | c4f0adecdec09cb3b2a83e9edbd39eb1789ad592 | 688,948 |
def num_items() -> int:
"""The number of candidate items to rank"""
return 10000 | 437e39083a0abb5f1ce51edd36f7e5bb5e815162 | 688,950 |
import json
def json_dumps(json_obj, indent=2, sort_keys=True):
"""Unified (default indent and sort_keys) invocation of json.dumps
"""
return json.dumps(json_obj, indent=indent, sort_keys=sort_keys) | fdb81417c36c42ae23b72c88041a3be2ea42f0a3 | 688,953 |
def nonSynonCount(t):
""" count the number of nonsynon labels in the transcript annotations.
"""
count = 0
for a in t.annotations:
for l in a.labels:
if l == 'nonsynon':
count += 1
return count | 886c9ae564fabe434b2f30c9f31c78784a311741 | 688,956 |
def _make_socket_path(host: str, display: int, screen: int) -> str:
"""
Attempt to create a path to a bspwm socket.
No attempts are made to ensure its actual existence.
The parameters are intentionally identical to the layout of an XDisplay,
so you can just unpack one.
Parameters:
host --... | ea7e36b7058db9291f2ed4b1888bf5fca263ba8d | 688,960 |
def strip_unsupported_schema(base_data, schema):
""" Strip keys/columns if not in SCHEMA """
return [
{key: value for key, value in place.items() if key in schema}
for place in base_data
] | 6faebcbb5b7a7a611ed1befd3daa321d79c925a8 | 688,961 |
def comma_join(items, stringify=False):
"""
Joins an iterable of strings with commas.
"""
if stringify:
return ', '.join(str(item) for item in items)
else:
return ', '.join(items) | 78e823c70fa5896c9cb26140327b485200041369 | 688,962 |
import math
def polar_to_cartesian(r, theta, r_ref=0.0, theta_ref=0.0):
"""
Helper function to convert polar coordinates to Cartesian
coordinates (relative to a defined reference point).
:Parameters:
r: float
Radial distance of point from origin.
theta: float
Angular bearing... | a78cc513fc76dcb1a40f12c28310bbe74373c2ff | 688,966 |
from pathlib import Path
def make_paths_absolute(value: str, workdir: Path = Path.cwd()) -> str:
"""
Detect if value is a relative path and make it absolut if so.
:param value: Parameter value from arguments
:param workdir: Path to workdir. Default: CWD
:return:
"""
if "../" in value and (... | 00d6809197fc753419ee3abe1cef8d2eb0dd0219 | 688,969 |
from typing import Dict
import math
def position_distance(a: Dict[str, float], b: Dict[str, float]) -> float:
"""Compute the distance between two positions."""
return math.sqrt((a['x'] - b['x'])**2 + (a['y'] - b['y'])**2 + (a['z'] - b['z'])**2) | e945797844132c30bc5c707c2f31f28338c3896c | 688,970 |
def fix_strength(val, default):
""" Assigns given strength to a default value if needed. """
return val and int(val) or default | e9a2414feb1d3e84fb9a02aa83b085d3845d728d | 688,972 |
def get_refs_from_soup(soup):
"""get_refs_from_soup.
Returns a list of `<cite>` tags from the passed BeautifulSoup object.
:param soup: BeautifulSoup object (parsed HTML)
"""
return soup.find_all('cite', recursive=True) | 5bd7ec0e1884aceaf05800775cc304d59e59c458 | 688,974 |
def get_target_value(data_frame, target_type):
"""
Get the value of a specific target from the engineered features pandas data frame.
:param data_frame: The engineered features pandas data frame.
:param target_type: The name of the prediction target.
:return: The prediction target value.
"""
... | a31661b6feeadc2b8be3013edf57aa07ebac9f1b | 688,976 |
import string
def filename_from_string(text):
"""Produces a valid (space-free) filename from some text"""
text = text.lower()
valid_chars = "-_." + string.ascii_letters + string.digits
return ''.join(c for c in text if c in valid_chars) | d841923eb4e00f1debb186d7ac3811a5ecfe8f71 | 688,979 |
from pathlib import Path
from typing import List
def read_tabular_data(filename: Path) -> List[List[float]]:
"""Reads a tabular data file, skipping comment lines.
Args:
filename (Path): The full path of the file to be read
Returns:
List[List[float]]: The file contents, with comment lines... | ec2d237304d5748e58f6dfcc3282ce32f06ed414 | 688,981 |
def _tile_url(tile_format, x, y, zoom):
"""Build S3 URL prefix
The S3 bucket is organized {tile_format}/{z}/{x}/{y}.tif
Parameters
----------
tile_format : str
One of 'terrarium', 'normal', 'geotiff'
zoom : int
zoom level
x : int
x tilespace coordinate
y : int
... | 816512f68958c8b04e724e843ce975ededd118d7 | 688,983 |
def parse_opcode(token):
"""Extract the opcode and the mode of all params"""
opcode = token % 100
modes = [0, 0, 0, 0]
if token > 100:
for (i, mode) in enumerate(str(token)[-3::-1]):
modes[i] = int(mode)
return opcode, modes | 90f36fa1b69318739cc8d785639ca9381f8cdb2b | 688,986 |
def _desc_has_possible_number_data(desc):
"""Returns true if there is any possible number data set for a particular PhoneNumberDesc."""
# If this is empty, it means numbers of this type inherit from the "general desc" -> the value
# "-1" means that no numbers exist for this type.
if desc is None:
... | 393f16dee7040f044f26909e524b3e11dbf88c94 | 688,987 |
import pickle
def load_pickle(path):
"""
Load object from path
:param path: path to pickle file
:type path: str
:return: object
"""
with open(path, 'rb') as f:
obj = pickle.load(f)
return obj | d75d5bdae7dd84c569b450feb5f1349788a2997c | 688,991 |
def has_dtypes(df, items):
"""
Assert that a DataFrame has ``dtypes``
Parameters
==========
df: DataFrame
items: dict
mapping of columns to dtype.
Returns
=======
df : DataFrame
"""
dtypes = df.dtypes
for k, v in items.items():
if not dtypes[k] == v:
... | f542aca7b69116c1c49d09d9ec8a137856d8c4f1 | 688,992 |
def parse_filename(filename):
# time_tag=TIME_INFOLDER_TAG,
# time_fmt=TIME_INFILE_FMT,
# ):
"""Parse Hive and RPi number from filename.
Filename e.g.: raw_hive1_rpi1_190801-000002-utc.jpg
"""
prefix, hive_str, rpi_str, t_str = filename.split("_")
... | d4330e5b1123624288b3cb8d4747971e4cee795b | 688,996 |
def do_steps_help(cls_list):
"""Print out the help for the given steps classes."""
for cls in cls_list:
print(cls.help())
return 0 | 19ce1585f915183fcb38c2ea268a6f30780830bb | 689,001 |
def bbox_to_pptx(left, bottom, width, height):
""" Convert matplotlib bounding box format to pptx format
Parameters
----------
bottom : float
left : float
width : float
height : float
Returns
-------
left, top, width, height
"""
return left, bottom-height, width, heig... | b32018d50cb022fd65ee87fe258f0cdc9bc04d41 | 689,002 |
def get_ids(cls, inherit=None):
"""Function that returns all the IDs to use as primary key
For a given class, this function will check for the _ids parameter and
call itself recursively on the given class' base classes to append all
other required IDs, thus generating the list of parameters to use as
... | 242036494f91e5ee67a6f92a691ec2fde13c241a | 689,006 |
import itertools
def createListWord(n):
"""Creates the list of word with size n on the alphabet {1,2,3,4}."""
temp = [''.join(x) for x in itertools.product('1234', repeat=n)]
L = [int(y) for y in temp]
return L | 7103f269695a77a24c716501b524e1bfddfe2562 | 689,010 |
def build_group_id(ad, desc_list, prettify=(), force_list=(), additional=None):
"""
Builds a Group ID from information found in the descriptors. It takes a number
of descriptor names, invokes and then concatenates their result (converted to string)
to from a group ID. Additional parameters can be passe... | 186f56058ecc7dc12bec7e1936416207a09dcdb3 | 689,013 |
import random
def tirage_uniforme(min, max):
"""
Renvoie un nombre décimal (float) choisi de manière (pseudo)aléatoire et uniforme
de l'intervalle \[``min`` ; ``max``\[.
Arguments:
min (float): Un nombre réel.
max (float): Un nombre réel.
"""
return random.uniform(min, max) | 3ea65fd222e7579df207c22111a405f2fee839ab | 689,014 |
def greet(greeting, name):
"""Returns a greeting
Args:
greeting (string): A greet word
name (string): A persons name
Returns:
string -- A greeting with a name
"""
return f'{greeting} {name}' | e58041beabf77a247fb6b0edc0f5385d29934649 | 689,019 |
def _is_parameter_for(name, container, docmap):
"""
@rtype: C{boolean}
@return: True if C{name} is the name of a parameter for the
routine C{container}, given the DocMap C{docmap}.
"""
if docmap is None or not docmap.has_key(container): return 0
container_doc = docmap.get(container)
if c... | ae65511c006be2d26c6afa78444df7360319a46c | 689,026 |
def is_lvm(name):
"""
Check if device is marked as an lvm
"""
if "lvm" in name:
return True
return False | 8b29fc4b49580cb776529d573c47fdc7b47e7a71 | 689,031 |
def place_figures(figures):
"""Generate LaTeX code for figure placement.
Parameters
----------
figures : list
List holding LaTeX code of individual figures to be placed in document.
Returns
-------
latex : str
LaTeX code for figure alignment.
"""
latex = ''
num_... | b6653eed30edd5658bc09282ff8251be4a1338ba | 689,034 |
import random
def scramble_word(word: str) -> str:
"""Return a scrambled version of the word."""
return ''.join(random.sample(word, k=len(word))) | 36e6bb2a5e9c5978b490d8fffe52f3d03fbe4483 | 689,035 |
def _get_node_name_prefix(node_name):
"""
Returns the node name prefix, without phase character or trailing
whitespaces.
"""
wows_name = node_name.strip()
return wows_name[:-1] | aeef1629f098708a1d70317683f6c2b6dda5109b | 689,036 |
def file_requires_unicode(x):
"""
Return whether the given writable file-like object requires Unicode to be
written to it.
"""
try:
x.write(b'')
except TypeError:
return True
else:
return False | c4e287012f5c8fba594a568ac08adcf3f4ccf79a | 689,039 |
def get_type_name(value_type):
"""Returns the name of the given type."""
return value_type.__name__ | 0d510c0de910d90fabbb275a418eab18dca88965 | 689,041 |
def runge_kutta_fourth_xy(rhs, h, x, y):
"""
Solves one step using a fourth-order Runge-Kutta method. RHS expects both x and y variables.
Moin, P. 2010. Fundamentals of Engineering Numerical Analysis. 2nd ed.
Cambridge University Press. New York, New York.
:param rhs: "Right-hand Side" of the equa... | 22b8d042376501b6910ddb1511c61ed7d2282896 | 689,045 |
def ptbunescape(token):
"""Unescape brackets in a single token, including PTB notation."""
if token in ('', '#FRONTIER#', None):
return None
elif token == '-LCB-':
return '{'
elif token == '-RCB-':
return '}'
elif token == '-LSB-':
return '['
elif token == '-RSB-':
return ']'
return token.replace('-LRB... | b47e52812de83275b227d4483be733788a4a1fce | 689,048 |
def mean(list):
"""
Calcula a média de um vetor de números.
Args:
list (list): vetor de números
Returns:
(float) média dos números
"""
return sum(list) / len(list) | a95825083952e529888a8d932a1e2daf2a7aac62 | 689,049 |
def parse_config(configfile):
"""Parse the config file 'configfile' and return the parsed key-value pairs as dict"""
return {k:v for k,v in map(lambda x: x.strip().split('='), filter(lambda x: not x.strip().startswith('#'),
(line for line in open(configfile))))} | 022243368fb63588a4bffaa6dad799e1bc5c2e66 | 689,053 |
def parse_id(string):
"""Returns the UUID part of a string only."""
return string.split('/')[-1] | bc50d9ba09512ac9ead25822be5b0985557acbdf | 689,059 |
def formalize_bbox(_im_summary):
"""
Extract bboxes from all classes and return a list of bbox.
Each element of the list is in the form: [x1, y1, x2, y2, class_id, score].
The returned list is sorted descendingly according to score.
"""
boxes = [] # each element: x, y, w, h, class_id, score ... | d6a35972da005b89de3274a73637474986b2f0f1 | 689,060 |
def row_full(row, puzzle):
"""
Takes a row number, and a sudoku puzzle as parameter
Returns True if there is no empty space on the row
ReturnsFalse if otherwise
"""
for col in range(0, 9):
if puzzle[row][col] == -1:
return False
return True | 96828d1481dccce583b090a247542db87979e2ce | 689,061 |
def collect_families_from_instances(instances, only_active=False):
"""Collect all families for passed publish instances.
Args:
instances(list<pyblish.api.Instance>): List of publish instances from
which are families collected.
only_active(bool): Return families only for active insta... | d47d7a0fe70feb291d55bec068b023cedbb6d1c5 | 689,062 |
def isvlan(value):
"""Checks if the argument is a valid VLAN
A valid VLAN is an integer value in the range of 1 to 4094. This
function will test if the argument falls into the specified range and
is considered a valid VLAN
Args:
value: The value to check if is a valid VLAN
Returns:
... | 485f856330fb61fc009d6d84f4b8d71a7ee77198 | 689,065 |
def parse(utxo, offset=0):
""" Parses a given serialized UTXO to extract a base-128 varint.
:param utxo: Serialized UTXO from which the varint will be parsed.
:type utxo: hex str
:param offset: Offset where the beginning of the varint if located in the UTXO.
:type offset: int
:return: The extrac... | 6330898ae2113370b1f1ec5e2b8ba0ec326eb48d | 689,066 |
def _list_readline(x):
"""Given a list, returns a readline() function that returns the next element
with each call.
"""
x = iter(x)
def readline():
return next(x)
return readline | f1111906b29efa44adef3d4a838eb25ed1dd0801 | 689,071 |
import random
import string
def random_string(nlen):
"""Create random string which length is `nlen`."""
return "".join([random.choice(string.ascii_lowercase) for _ in range(nlen)]) | 49f63e3f8122dd886ce4cc5d3fe0b2c55c0679bb | 689,074 |
def match_word(encoded_word, words_list):
"""
Find first probably correct word
based on list of words and given encoded word.
"""
results = []
for word in words_list:
#skip all items with different first and last char
if word[0] != encoded_word[0] or word[-1] != encoded_word[-1]:... | ffea6f7042f3d8bc47e5f9335c7e944be692e9a3 | 689,076 |
def extract_meta_from_keys(keys, prefix):
"""Extract metadata contained in a key's name.
Parameters
----------
keys : list of strings
prefix : string
Returns
-------
meta : string
"""
return next(k[len(prefix):] for k in keys if k.startswith(prefix)) | 808101a8edf7cab38ac249959ac27f27b9020d08 | 689,078 |
def ChannelFirst(arr):
"""Convert a HWC array to CHW."""
ndim = arr.ndim
return arr.swapaxes(ndim - 1, ndim - 2).swapaxes(ndim - 2, ndim - 3) | 017b7fb8b0597c201cddd546bf47a21228f0bedd | 689,079 |
import torch
def exp(x):
"""
The exponential link function given by
$$ y = e^{x} $$
"""
return torch.exp(x) | 5daf001a96e3deafb8549ec73f9824d3a512fc58 | 689,081 |
def get_linef(fp, line_no):
"""'fp' should be (readable) file object.
Return the line content at line_no or an empty line
if there is less lines than line_no.
"""
fp.seek(0)
for line in fp:
line_no -= 1
if line_no == 0:
return line
return '' | 8c73e672ccf2eaea6b1e23d7ed5b7a66385440b6 | 689,083 |
def make_1024_list() :
"""
Generates a list of 1024 strings of numbers in the format "XXXX", filled with zeros before the number.
It is here to translate integers into the format used in the dataset (+1 because the list starts at "0001").
:return: returns a list of 1024 strings
"""
list = []
for x in ran... | 6a42dd4e0ff17a5fd84d584627338cf2975399ac | 689,085 |
import collections
def longest_path(current_state):
"""Find longest possible path from the current state to the final state
Args:
current_state: StateForGraphs
The state at the beginning of the search; the root of the tree.
Returns:
The maximum number of steps that can be use... | 8acca90179eaff3f8d06972aec0a63a8050fbcf9 | 689,086 |
def get_topic_key(project_name, topic):
"""
Get the topic key for a project name and a topic
:param project_name: project name
:param topic: topic
:return: topic key
"""
return f"{project_name}/{topic}" | fb1e036e75e43429dc3d5f3e44c64fb7fdc62486 | 689,087 |
def nvl(*args):
"""
SQL like coelesce / redshift NVL, returns first non Falsey arg
"""
for arg in args:
try:
if arg:
return arg
except ValueError:
if arg is not None:
return arg
return args[-1] | 3f49d4c855e8e7f8e0359301acf454f731489495 | 689,089 |
def parseFields(fields, output):
""" Take a string of fields encoded as
key1=value1,key2=value2,...
and add the keys and values to the output dict"""
for field in fields.split('|'):
key, value = field.split('=')
try:
value = int(value)
except:
pass
output[key] = value
return output | 7cbe131e0f4c8df85ccc7bca52aa80f0f0d17a59 | 689,092 |
def to_camel_case(snake_str):
"""
Transforms a snake_case string into camelCase.
Parameters
----------
snake_str : str
Returns
-------
str
"""
parts = snake_str.split("_")
# We capitalize the first letter of each component except the first one
# with the 'title' method ... | 02e28889da2a92fc5e085ad955b11519b5069dc4 | 689,093 |
def to_bytes(s, encoding="utf-8"):
"""Convert a text string (unicode) to bytestring, i.e. str on Py2 and bytes on Py3."""
if type(s) is not bytes:
s = bytes(s, encoding)
return s | d66b0620e1c71650db11e48fe6f961289f9fed5b | 689,094 |
from typing import List
from typing import Counter
def top_k_frequent_bucket_sort(nums: List[int], k: int) -> List[int]:
"""Given a list of numbers, return the the top k most frequent numbers.
Solved using buckets sort approach.
Example:
nums: [1, 1, 1, 2, 2, 3], k=2
output: [1, 2]
... | 94970d9c0c21a5288e52207e85f59d631e546600 | 689,098 |
import re
def increment(s):
""" look for the last sequence of number(s) in a string and increment """
lastNum = re.compile(r'(?:[^\d]*(\d+)[^\d]*)+')
m = lastNum.search(s)
if m:
next = str(int(m.group(1))+1)
start, end = m.span(1)
s = s[:max(end-len(next), start)] + next + s[en... | 918c72990f04fcc36884deeb1e1d5a846b86ea12 | 689,101 |
def _check_delimiter(output_filename, delim=None):
"""Detect delimiter by filename extension if not set"""
if output_filename and (delim is None):
delimiters = {"tsv": "\t", "csv": ","}
delim = delimiters[output_filename.rsplit(".", 1)[-1].lower()]
assert delim, "File output delimiter no... | db3cbea27c09f1ec67459cfec6e1f4fbbb1ed5c8 | 689,105 |
from typing import Counter
def precision_recall_f1(prediction, ground_truth):
"""
This function calculates and returns the precision, recall and f1-score
Args:
prediction: prediction string or list to be matched
ground_truth: golden string or list reference
Returns:
floats of (... | 363be5c9786226d0f95a21791bd4da65623ccd80 | 689,107 |
from bs4 import BeautifulSoup
import requests
def fetch_page(url, method, **kwargs) -> BeautifulSoup:
"""Execute request for page and return as soup"""
ret = requests.request(method, url, **kwargs)
if ret.status_code != 200:
raise Exception(f"Page {url} returned {ret.status_code}")
return Be... | 158c10bcdf2db4e60112f7b9a643661732ca2d29 | 689,110 |
def on_off(image, w, h, threshold=128):
"""
Black and white (no greyscale) with a simple threshold.
If the color is dark enough, the laser is on!
"""
result = []
for row in image:
result_row = []
for pixel in row:
# We draw black, so 255 is for dark pixels
... | c9e577bf851fa972c1bbe7f8a61afc09ffb37de5 | 689,111 |
def get_init(order):
"""Return initial guess for fit parameters."""
lambda_guess = [1.0]
coeff_guess = [0.0] * (2 * order)
return lambda_guess + coeff_guess | 6e1e7a2be2727a0f6c3fedb1ef88c45081643778 | 689,115 |
def get_caller_name(caller):
"""Find the name of a calling (i.e. observed) object.
Args:
caller: The observed object which is calling an observer.
Returns:
The name of the caller. If the caller is a function we return that
function's .__name__. If the caller is a bound method we re... | 2b5bf37a34b7b75684c5301159d461535d986f3f | 689,117 |
def wc(q,mc2,B):
"""
Calculate the electron gyrofrequency
q is the charge in multiples of the fundamental
mc2 is the particle rest mass in MeV
B is the magnetic field magnitude in nT
"""
cof = 89.8755311
res = cof*q*B/mc2
return res | 69e015a36384b9e9af07e303993cc74c2c8cae58 | 689,120 |
from typing import Union
from typing import List
from typing import Tuple
def deduplicate(x: Union[List, Tuple]):
"""Remove duplicates in a list or tuple; preserves original order."""
return type(x)(dict.fromkeys(x)) | ad47ec846f08feadb6c89be31205be536a469d8f | 689,126 |
def sizeof(bsObj):
""" Size of BotSense object in bytes. Size is contextual by object type. """
return bsObj.__sizeof__() | 70c55a9002e336d2d827ee21d04260dfc328d7fc | 689,127 |
def extract_variable_index_and_name(string):
"""Takes a string of the form variable_name[index] and
returns the variable_name, and index.
The method will return a `ValueError` if the string does not
contain a valid set of access brackets, or if the string contains
multiple bracket accessors.
P... | 0d31763f5ed96ec99b35e3ef94d030c1ddeb6268 | 689,129 |
async def start_entry() -> dict:
"""Create a mock start_entry object."""
return {
"id": "start_entry_1",
"race_id": "race_1",
"startlist_id": "startlist_1",
"bib": 1,
"name": "name names",
"club": "the club",
"scheduled_start_time": ("2021-08-31T12:00:00")... | 3faf34ebd8000e2aafb872a6abf929ed0d9c9543 | 689,134 |
def myfunc(_a, _b):
"""Add two numbers."""
return _a + _b | 7177568b60056ea28b6c880eaba8d05441b14c96 | 689,136 |
def is_one_to_one(table):
"""A staticmethod that takes a codon table as a dictionary and returns
True if it represents a One-To-One genetic code and False otherwise.
A one-to-one code is defined as a code in which every amino acid is
represented with exactly one codon. This defines an unamb... | d90f3cfc69a7ded4b93b8e15e2175234d96ca7a7 | 689,137 |
def mex(L):
"""Return the minimum excluded value of a list"""
L = set(L)
n = 0
while n in L:
n += 1
return n | c35205dd22ca47e28141ae56aba2827065abf164 | 689,141 |
def _get_magnitude(string):
"""
Get the magnitude of the smallest significant value in the string
:param str string: A representation of the value as a string
:returns: The magnitude of the value in the string. e.g. for 102, the magnitude is 0, and for 102.03 it is -2
:rtype: int
"""
split_... | 03a3abc46aca847489431ab86aceab1d59f9c626 | 689,146 |
def __get_pivots(diameter, x, y):
"""
Get the x-intercepts and y-intercepts of
the circle and return a list of pivots which
the coin lies on.
"""
pivots = []
radius = diameter / 2
sqval = radius**2 - y**2
if sqval > 0: # no imaginary numbers!
sqrt = sqval**(0.5)
piv... | a82c465d82e428797bf98d4ab005335005d44368 | 689,148 |
def create_filename(lecture_num, title):
"""
Create a filename from a title string.
Converts spaces to dashes and makes everything lowercase
Returns:
lecture filename
"""
return "lecture-{:02d}{}.md".format(int(lecture_num), "" if not title else '-' + title.lower().replace(" ", "-")) | 2370a63fb69b8cf0ddd431745d01201f2bafe6c0 | 689,150 |
def get_line(s3_autoimport):
"""Build a list of relevant data to be printed.
Args:
s3_autoimport (S3ProjectImport): instance of
S3 autoimport
Returns:
list(str): list of relevant data to be printed
"""
return "\t".join(
[
str(s3_autoimport.id),
... | 0624af6e6ce02f23baedda01fb30c4c62c01b7e4 | 689,153 |
def FindPhaseByID(phase_id, phases):
"""Find the specified phase, or return None"""
for phase in phases:
if phase.phase_id == phase_id:
return phase
return None | 5544d47139a00cb6e0e33486031ff49796092907 | 689,154 |
def dataToString(var, data):
"""Given a tuple of data, and a name to save it as
returns var <- c(data)
"""
#convert data to strings
d = [str(d) for d in data]
return "%s <- c(%s)" % (var, ",".join(d)) | dcfb8e443f0a8f8c783047190822c7194104fc44 | 689,155 |
def alt_ternary_handle(tokens):
"""Handle if ... then ... else ternary operator."""
cond, if_true, if_false = tokens
return "{if_true} if {cond} else {if_false}".format(cond=cond, if_true=if_true, if_false=if_false) | d41d4e67f66282648cc13f4e678c8e712c41e01c | 689,156 |
def extract_volume_number(value):
"""Extract the volume number from a string, returns None if not matched."""
return value.replace("v.", "").replace("v .", "").strip() | 50b25b9c33ae62f2e61165ca36648cbe09e39883 | 689,158 |
def get_full_exception_name(exception: Exception) -> str:
"""Get the full exception name
i.e. get sqlalchemy.exc.IntegrityError instead of just IntegrityError
"""
module = exception.__class__.__module__
if module is None or module == str.__class__.__module__:
return exception.__class__.__nam... | a188427bbf12d861990c784c65f4d524734ba787 | 689,159 |
def prettyTimeDelta (seconds):
"""
Pretty-print seconds to human readable string 1d 1h 1m 1s
"""
seconds = int(seconds)
days, seconds = divmod(seconds, 86400)
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
s = [(days, 'd'), (hours, 'h'), (minutes, 'm'), (se... | 9c52730208782c628ddc26ee7b3570b9f962eb7d | 689,161 |
def _convert_snake_to_pascal(snake_case_string: str) -> str:
"""
Convert a string provided in snake_case to PascalCase
"""
return ''.join(word.capitalize() for word in snake_case_string.split('_')) | 41fd25da7fa5b6f120fae63aafb5bed1438256bd | 689,162 |
def read_file_str(file_path: str) -> str:
"""
Read the target file string.
Parameters
----------
file_path : str
Path of target file.
Returns
-------
file_str : str
The target string read.
"""
with open(file_path, mode='r', encoding='utf-8') as f:
file_s... | 01ac8056896b7b40102c032e7a9b132cec0cbb6b | 689,163 |
def getHlAtt(app, n, highlights, isSlot):
"""Get the highlight attribute and style for a node for both pretty and plain modes.
Parameters
----------
app: obj
The high-level API object
n: int
The node to be highlighted
highlights: set|dict
The nodes to be highlighted.
... | 5e6119cd8fb5622589d84e8831e3e12a02d673c6 | 689,168 |
def dir_tree_find(tree, kind):
"""Find nodes of the given kind from a directory tree structure
Parameters
----------
tree : dict
Directory tree.
kind : int
Kind to find.
Returns
-------
nodes : list
List of matching nodes.
"""
nodes = []
if isinstan... | 935021a2daae3cc53f1e9a44961643171c5a5fc2 | 689,169 |
def solve_tridiag(a, b, c, d, overwrite_bd=False):
"""
Solve a tridiagonal equation system using the Thomas algorithm.
The equivalent using scipy.linalg.solve_banded would be:
ab = np.zeros((3, len(a)))
ab[0, 1:] = c[:-1]
ab[1, :] = b
ab[2, :-1] = a[1:]
x = scipy.li... | af25c811fa1b74b571995ddc531e31bda9efbf59 | 689,171 |
def intToDBaseTuple(x, dim, D):
"""
Transfer a integer to a base-D fixed-length tuple of digits.
Parameters
----------
x : int
A positive integer to be transformed into base-D.
dim : int
The length of digit tuple as the output.
D : int
The base of the digit tuple.
... | 7f5567aa92602743dfccae026d6c266049092e43 | 689,173 |
def list_product(num_list):
"""Multiplies all of the numbers in a list
"""
product = 1
for x in num_list:
product *= x
return product | 3d6d56f03817f9b4db0e7671f6c95c229a14a042 | 689,175 |
def lin_interp(x, x0, x1, y0, y1):
""" Simple helper function for linear interpolation. Estimates the value of y at x
by linearly interpolating between points (x0, y0) and (x1, y1), where x0 <= x < x1.
Args:
x: Float. x-value for which to esrimate y
x0: Float. x-value of point 0
... | 07efe42eda983bb9221c26df73bc260204830c53 | 689,179 |
def output_size(W, F, P, S):
"""
https://adventuresinmachinelearning.com/convolutional-neural-networks-tutorial-in-pytorch/
:param W: width in
:param F: filter diameter
:param P: padding
:param S: stride
:return:width out
"""
return (W-F+2*P)/S + 1 | 06bb0e4c6d8b6d46b7ddc4300dd925a8203e9b16 | 689,180 |
import torch
def out_degree(adjacency: torch.Tensor) -> torch.Tensor:
"""Compute out-degrees of nodes in a graph.
Parameters
----------
adjacency
Adjacency matrix.
Shape: :math:`(N_{nodes},N_{nodes})`
Returns
-------
torch.Tensor
Nodewise out-degree tensor.
... | 92eec222cf125135b6bcd711dcef6cb7144f2a59 | 689,182 |
def is_fasta_file_extension(file_name):
"""
Check if file has fasta extension
Parameters
----------
file_name : str
file name
Returns
-------
bool
True if file has fasta extension, False otherwise
"""
if file_name[-4:] == ".fna":
return True
elif file_name[-4:] == ".faa":
return True
elif file_nam... | 711267ab304ca188b03f3a7e816a0df70c3f4fa3 | 689,185 |
from typing import Union
def _get_remainder(code: Union[list, int]) -> int:
"""Calculate remainder of validation calculations.
:param Union[list, int] code: input code
:return: remainder of calculations
:rtype: int
:raises TypeError: if code is not a list or an integer
"""
# raise an exc... | c235512d66e1041ab30c376b1e7682a085d27dcc | 689,186 |
def _is_group(token):
"""
sqlparse 0.2.2 changed it from a callable to a bool property
"""
is_group = token.is_group
if isinstance(is_group, bool):
return is_group
else:
return is_group() | 91b8a9a18831c46a878fbbacf72a0ebe9f4f4fdf | 689,187 |
import warnings
def force_connect(client):
"""
Convenience to wait for a newly-constructed client to connect.
Taken from pymongo test.utils.connected.
"""
with warnings.catch_warnings():
# Ignore warning that "ismaster" is always routed to primary even
# if client's read preferenc... | a9a49ff79108f38a10215aaab3ee371b860f6270 | 689,190 |
def unescape(st):
"""
Unescape special chars and return the given string *st*.
**Examples**:
>>> unescape('\\\\t and \\\\n and \\\\r and \\\\" and \\\\\\\\')
'\\t and \\n and \\r and " and \\\\'
"""
st = st.replace(r'\"', '"')
st = st.replace(r'\n', '\n')
st = st.replace(r'\r', '\r... | bce4370ace1162b96a8c4d4e175903b2d8c2e929 | 689,198 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.