content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def CleanLine(line):
"""Converts a line from coolrunning results to a tuple of values."""
t = line.split()
if len(t) < 6:
return None
place, divtot, div, gun, net, pace = t[0:6]
if not '/' in divtot:
return None
for time in [gun, net, pace]:
if ':' not in time:
... | c59550c846e474ab5eadcc0e082feda4c04cc819 | 643,654 |
def pattern_molecular_weight(mzs: list, intensities: list, charge: int = 1):
"""
Calculates the molecular weight given by an isotope pattern.
:param mzs: m/z (x) values for pattern
:param intensities: intensity (y) values for the pattern
:param charge: charge for the molecule
:return: molecular... | ffc94ee9cc506919862f62d25a828ebf64511504 | 643,656 |
import operator
def filtered_join (sep, strings, pred = None) :
"""Return a string which is the concatenation of the items in the
iterable `strings` for which `pred` is true, separated by `sep`.
>>> filtered_join ("-", ["", "abc", "ced"])
'abc-ced'
>>> filtered_join ("-", [" ", "abc",... | f2062339413c5572646284112df7856039f7c35e | 643,658 |
def from_bits(bin_str: str):
"""
This function will convert a binary string (with or without prefix) into a integer;
:param bin_str: A binary string to convert into integer
:return: A integer representing the given binary string
"""
return int(bin_str, 2) | ee4a50f18f0c8ee7c0d0087444e1aebadf3a8ad4 | 643,662 |
def swap_order(value):
"""
Common crawl optimizes search by working back to front ("org.example.www")
This is a utility function for swapping the order back to the expected value ("www.example.org")
"""
parts = value.split(".")
new_value = ""
for part in parts:
new_value = part + ".... | 7cf789e9b97dbb55125d2928479f020bbdd75769 | 643,663 |
def dtype_to_json_type(dtype) -> str:
"""Convert Pandas Dataframe types to Airbyte Types.
:param dtype: Pandas Dataframe type
:return: Corresponding Airbyte Type
"""
if dtype == object:
return "string"
elif dtype in ("int64", "float64"):
return "number"
elif dtype == "bool":
... | c97bf036cce3356bec63dc84efaa8b20b3e45872 | 643,665 |
def get_string_trace_attribute_rep(trace, trace_attribute):
"""
Get a representation of the feature name associated to a string trace attribute value
Parameters
------------
trace
Trace of the log
trace_attribute
Attribute of the trace to consider
Returns
------------
... | 1e8c49e81379392b8c062c3058dc59eff2787f9d | 643,670 |
def _get_qualifiers(graph, source_node: int, target_node: int):
""" Retrieve the qualifiers list (empty list if nonexistent) """
if "qualifiers" in graph.es[0].attributes():
qualifiers_list = graph.es.select(_source=source_node, _target=target_node)["qualifiers"]
qualifiers_list = [x if x is not... | a64c2fa74048d27aa1f0e3acc2e985ef0b245389 | 643,671 |
def question_is_nonarray(questions, question_id):
"""
Return whether the question exists and has no subquestions.
"""
if question_id not in questions:
return False
question = questions[question_id]
if question[1] is not None or question[2] is not None:
return False
return Tru... | 15a602366a8c14bbeb272594b36c01ca48261075 | 643,673 |
import random
def extract_text(para):
"""Returns a sufficiently-large random text from a tokenized paragraph,
if such text exists. Otherwise, returns None."""
for _ in range(10):
text = random.choice(para)
if text and 60 < len(text) < 210:
return text
return None | 2a8f736ce87a94ea9c02d8037e9ce44e21f86674 | 643,678 |
def get_missing_frameworks(descriptor, environment, yml_file):
"""
Returns a list of missing frameworks from a given environment based on the
list of dependencies returned by a bundle descriptor.
:param descriptor: The bundle for which missing dependencies will be searched.
:param environment: The ... | 93cf391cb08dc402bbfd22a43abcaa52862f5c65 | 643,681 |
def inject_none_for_missing_fields(cls, values):
"""Given a BaseModel class and a dictionary to populate its fields, inject None for missing fields."""
for field_name, field_info in cls.__fields__.items():
if field_name not in values and field_info.alias not in values:
values[field_name] = N... | 809895e9df296d8765f9c5df0640b9c8df77c136 | 643,684 |
def find_constant_features(data):
"""
Get a list of the constant features in a dataframe.
"""
const_features = []
for column in list(data.columns):
if data[column].unique().size < 2:
const_features.append(column)
return const_features | 58fb8f98e6da9026b26437fb93230258312714d6 | 643,692 |
def remove_unspecified_items(attrs):
"""Remove the items that don't have any values."""
for key, value in list(attrs.items()):
if value is None:
del attrs[key]
return attrs | 10a495d8189cde6ba345dfc4bcb5bcb483769ea0 | 643,695 |
import tempfile
def tmpfile(prefix, direc):
"""Returns the path to a newly created temporary file."""
return tempfile.mktemp(prefix=prefix, suffix='.pdb', dir=direc) | 3c9a1f88804dc9626b6c8f03846eb6323cff848b | 643,696 |
def group_degree_centrality(G, S):
"""Compute the group degree centrality for a group of nodes.
Group degree centrality of a group of nodes $S$ is the fraction
of non-group members connected to group members.
Parameters
----------
G : graph
A NetworkX graph.
S : list or set
... | 6a63218d39790d6c8ddb76a39bc585df73822211 | 643,698 |
import bisect
def clip_around_detections(detections, time_interval):
"""Return the narrowest sublist of detections (a list of Detections)
containing time_interval.
"""
times = [d.timestamp for d in detections]
lo = bisect.bisect(times, time_interval[0]) - 1
hi = bisect.bisect_left(times, time... | bd20c5caa3f1c9737980febb584d0f131c185c33 | 643,701 |
import requests
def pr_info(branch: str):
"""Get PR title and link from github api"""
_, _, pr_nr = branch.partition("-")
try:
response = requests.get(
f"https://api.github.com/repos/glotaran/pyglotaran/pulls/{pr_nr}",
).json()
return response["title"], response["html_u... | 053074b695f323b312755a8d34a1f763c29e1943 | 643,706 |
def token_depth(token):
"""
determines the "depth" of a regex
prefix tree. Used for guaranteeing
unique node labels.
"""
if token[0] == 'singleton':
return 1
else:
depth = 0
for operand in token[1][1:]:
if token_depth(operand) > depth:
dep... | 26e000633e76160afb1c01c427bbe4b16fa8c06b | 643,707 |
def is_string_arg(parameter):
"""Whether the parameter's type is string or bytes."""
return parameter["grpc_type"] in ["string", "bytes"] | d0f7a3016bdf20edae9dc8bbcf2736da38b259ce | 643,710 |
def _is_leap(y):
"""True if y is a leap year."""
return (y % 400 == 0 or (y % 4 == 0 and y % 100 != 0)) | d5c93930280419b07094c0256b5ac90759b453ff | 643,712 |
import random
def random_case(message: str) -> str:
"""Convert the string to RanDoM CasE.
Parameters
----------
message : str
The string to be converted
Returns
-------
str
The string in RandOm caSe
"""
characters = []
for character in message:
conver... | 2ac0f0b5cf0dad052754cfe319994e64d15bf858 | 643,714 |
def center_of_effect(cloud, duration):
"""
The center of effect condenses musical information
in the spiral array by a single point.
Parameters
----------
cloud : 3D array
Array containing the coordinates in the spiral array
of the notes in the cloud.
duration : array
... | bd3037a3c9521b02db2bd9313e476daa56b426b7 | 643,716 |
def limpiar_1(texto:str):
"""
Se hace una primera limpieza de los datos. Eliminando saltos de línea,
y espacios innecesarios.
"""
texto = texto.replace('\n', '')
return texto | 4c58f03db2a5b7e8d60623aa56c75db1e7dede2f | 643,717 |
def hex_to_rgb(hexstring):
"""
Converts a hexadecimal string to RGB tuple
Parameters
----------
hexstring : str
Hexadecimal string such as '#FFFFFF'
Returns
-------
tuple
RGB tuple such as (256,256,256)
"""
#From http://stackoverflow.com/a/214657
hexstri... | 598e33aa0d14fee0aaf5ba84f2b6fd4c253d991a | 643,719 |
def is_valid_minimizer(object):
"""
Checks if the minimzer object has the following attributes/methods:
* minimize
"""
has_minimize = hasattr(object, "minimize")
return has_minimize | b822b9ba41f68a877c345ac676b7b0186cab49eb | 643,722 |
def C2F(C):
"""Convert Celcius to Fahrenheit"""
return 1.8 * C + 32 | e09f7415a2c509d8cb2d07d4c0d8e667f94e3c7d | 643,725 |
def _GetDataFilesForTestSuite(test_suite_basename):
"""Returns a list of data files/dirs needed by the test suite.
Args:
test_suite_basename: The test suite basename for which to return file paths.
Returns:
A list of test file and directory paths.
"""
test_files = []
if test_suite_basename in ['Ch... | 0f4ff42ef0ed050cf6a48ea35ac77fda8b249f75 | 643,730 |
def estimarPGC(h, a, n, sexo):
"""Estimación del PGC utilizando la fórmula del item M.
Args:
h (float): Altura en centímetros
a (float): Circunferencia abdominal en centímetros
n (float): Circunferencia del cuello en centímetros
sexo (string): 'M': Masculino ; 'F': Femenino
... | 1bbba867b27e55d65726877e7b59c21e5ebd108d | 643,731 |
def loop(self, n=None, duracion=None):
"""
Returns a clip that plays the current clip in an infinite loop.
Ideal for clips coming from gifs.
Parameters
------------
n
Number of times the clip should be played. If `None` the
the clip will loop indefinitely (i.e. with no set durac... | e3fafd8046b291563b6c77143148726c8a2b7b03 | 643,732 |
def normalized_in_degree(in_degree_dict):
""" dict -> dict
Takes a dictionary of nodes with their indegree value, and returns a
normalized dictionary whose values sum up to 1.
"""
normalized = {}
for key in in_degree_dict:
normalized[key] = float(in_degree_dict[key]) / len(in_degree_dic... | 30462b2f730239ae1f9ae3cba29961a597053449 | 643,734 |
import requests
from bs4 import BeautifulSoup
def _root(url):
"""Get root BeautifulSoup element from ``url``."""
page = requests.get(url)
return BeautifulSoup(page.content, "html.parser") | 25e2d99c61bee51c1f93cf7ce4ef7aee79c5ff0c | 643,735 |
def countMotHitCmp(motDistr1, motDistr2):
"""Helper function for comparing two motif distributions. Compares based
on number of central hits."""
return motDistr2.getNcentralHits() - motDistr1.getNcentralHits() | 81a7cfc5268eb6cf124e555fa1bc1fbeaf4c2d96 | 643,741 |
def _is_list_like(x):
"""Helper which returns `True` if input is `list`-like."""
return isinstance(x, (tuple, list)) | 1af7652bac0189bd1629c4d8064b63c96c6964b2 | 643,742 |
import re
import string
def replace_numbers(text):
"""Transform every number of the string into space."""
return re.sub('[%s]' % string.digits, ' ', text) | 70272349a0ebfca3a1d52e02f98674dbad5d3f69 | 643,743 |
def convert(color):
"""Get (0-1, 0-1, 0-1) color code and converts it to (0-255, 0-255, 0-255).
Parameters
----------
color : tuple
RGB code in format (0-1, 0-1, 0-1)
Returns
-------
list
a list representing RBG color code in format (0-255, 0-255, 0-255)
"""
return ... | 4e57b4c575ad9a8c6fe9cda077d07dc67e41df3b | 643,746 |
def set_accuracy_95(num: float) -> float:
"""Reduce floating point accuracy to 9.5 (xxxx.xxxxx).
Used by Hedron and Dihedron classes writing PIC and SCAD files.
:param float num: input number
:returns: float with specified accuracy
"""
# return round(num, 5) # much slower
return float(f"{n... | 2f4c942b66972cfcf47121a9d7d674a854161df5 | 643,749 |
def ClusterKey(cluster, key_type):
"""Return a cluster-generated public encryption key if there is one.
Args:
cluster: Cluster to check for an encryption key.
key_type: Dataproc clusters publishes both RSA and ECIES public keys.
Returns:
The public key for the cluster if there is one, otherwise None... | 073ce9fb790b8fcdaabded2c8f9a4ec649f10850 | 643,752 |
def _GetProcJiffies(timer_list):
"""Parse '/proc/timer_list' output and returns the first jiffies attribute.
Multi-CPU machines will have multiple 'jiffies:' lines, all of which will be
essentially the same. Return the first one."""
if isinstance(timer_list, str):
timer_list = timer_list.splitlines()
fo... | 63ece49d4950a1654afcbe704cf19fdfe911ed2e | 643,758 |
def figure_asthetics(ax):
"""Change the asthetics of the given figure (operators in place).
Parameters
----------
ax : matplotlib ax object
"""
ax.yaxis.grid()
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.yaxis.set_ticks_position('left')
ax.xaxi... | b5a2c1b5a1274ba738117564292237e1abf42d76 | 643,760 |
def pairs_quality(cand_rec_id_pair_list, true_match_set):
"""Pairs quality measures the efficiency of a blocking technique.
Pairs quality is calculated as the number of true matches included in the
candidate record pairs divided by the number of candidate record pairs
generated by blocking.
Para... | d40f088e3ad2ae68ba32274f87ad1f188ccfbc67 | 643,761 |
def is_power_of_two(n):
"""Check whether `n` is an exponent of two
>>> is_power_of_two(0)
False
>>> is_power_of_two(1)
True
>>> is_power_of_two(2)
True
>>> is_power_of_two(3)
False
>>> if_power_of_two(16)
True
"""
return n != 0 and ((n & (n - 1)) == 0) | b5fdbabb959f224018b57c2244bbfe93780ece1c | 643,762 |
def WaitForOpMaybe(operations_client, op, asyncronous=False, message=None):
"""Waits for an operation if asyncronous flag is on.
Args:
operations_client: api_lib.ml_engine.operations.OperationsClient, the client
via which to poll
op: Cloud ML Engine operation, the operation to poll
asyncronous: b... | 98221aaa1115c49c256824df072ef6f11b40e183 | 643,764 |
def is_func_bound(method, instance=None):
""" check function is bound in class instance.
>>> is_func_bound(lambda :None)
False
>>> is_func_bound(dict().get)
True
>>> x = dict(a=1)
>>> is_func_bound(x.get, x)
True
>>> y = dict(a=1)
>>> is_func_bound(x.get, y)
False
:param... | 20f3fb11b4f90cfab526a0221e490598e7c7834c | 643,765 |
def toBin3(v):
"""Return a string (little-endian) from a numeric value."""
return '%s%s%s' % (chr(v & 255), chr((v >> 8) & 255), chr((v >> 16) & 255)) | 93f2ca4c39419ece5ea41dd07608cce8287c1366 | 643,767 |
def is_present(value: str) -> str:
"""
Ensure that a string is present
:param value: the string to validate
:return: a valid string
"""
if value == "":
raise ValueError("must be present")
return value | 9ca041c7e344e56a7572f82b68e5c6e0cfa0af82 | 643,769 |
import re
def replace_emoticons_with_tags(tweet):
"""
Replaces emoticons in a tweet with tags.
INPUT:
tweet: original tweet as a string
OUTPU:
tweet with emoticons replaced
"""
hearts = set(['<3', '❤'])
happy_faces = set([
':)', ":')", '=)', ':-)', ':]', ":']", '=]... | bec8829ce963da7759db87e1bbb320227bc6ad7a | 643,783 |
def message_filter(msg):
"""Return True if the message cannot be considered as a repeat."""
if msg == '' or '--' in msg or 'List:\n' in msg:
return True
return False | d194bad3971abe733666a6546f07f0fc6cb5359a | 643,784 |
import re
def split_hname(hname):
"""split a hierarchical name (hname) into parts.
double '/' is used to escape the '/'.
and is transformed into a into single '/'
e.g.
hname = "network/network-fd02:://64"
=> ["network", "network-fd02::/64"]
:param str hname: hierarchical name
... | bb88dd2164a37c42a109332f6d62a85d2d009198 | 643,787 |
def _get_dependencies_in_namespace(msg_desc, namespace):
"""Return all message dependencies in the given namespace."""
dependencies = []
for key in msg_desc.message_dependencies:
if key.startswith(namespace):
dependencies.append(key)
return dependencies | 1d1369c068fcc3c71c7081532030f9503a4755b9 | 643,789 |
import re
def validar_cpf(cpf):
"""Rotina para validação do CPF - Cadastro Nacional
de Pessoa Física.
:Return: True or False
:Parameters:
- 'cpf': CPF to be validate.
"""
# Limpando o cpf
if not cpf.isdigit():
cpf = re.sub('[^0-9]', '', cpf)
if len(cpf) != 11 or cpf == c... | db9852d534c9894c50dcdb1ee709ef6ff27f7699 | 643,792 |
import re
def process_string_and_remove_tags(raw_string: str):
"""Removes tags and converts newlines to match ace offsets alignment"""
raw_string = raw_string.replace('\r\n', '\n')
return re.sub(r'<[\s\S]*?>', '', raw_string) | a4e82ad0728519b5646be767e60f8dfa7be760ef | 643,793 |
from typing import Any
def get_client_region(client: Any) -> str:
"""Get the region from a boto3 client.
Args:
client: The client to get the region from.
Returns:
AWS region string.
"""
return client._client_config.region_name | 1b6d0810d7376bd5ef8ea59d7ae700c39a89e610 | 643,799 |
def _compute_depth_recursively(event):
"""Return the depth of the current event. The depth is the largest number
of possible successive descend into the children field.
Args:
event (json): Json representing the current event.
Returns:
The depth of the current event.
"""
if event['c... | e36fde83e787406892f686fc4278e8e25ef68fe4 | 643,800 |
import random
import string
def random_pass(length=20):
"""Generate a random string of letters and digits """
return "".join(random.choice(string.ascii_letters + string.digits) for _ in range(length)) | e23d82e8c4328e07bb57c7aab4be8817f73f25d5 | 643,801 |
import re
def read_urls(filename):
"""Returns a list of the puzzle urls from the given log file,
extracting the hostname from the filename itself.
Screens out duplicate urls and returns the urls sorted into
increasing order."""
# NOTE: Hostname not longer exists
hostName = 'http://'+ filename... | 56226030bc9a0ec33d416a8cb62d20cd79c75196 | 643,802 |
def namedtuple_to_dict(data):
"""
Converts a namedtuple to a dictionary with the top-level key being the class name.
"""
return {type(data).__name__.lower(): dict(data._asdict())} | fcbc01c822932636f30a41e1f2870528e14865ea | 643,804 |
import math
def prime_sieve(num: int) -> list[int]:
"""
Returns a list with all prime numbers up to n.
>>> prime_sieve(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>>> prime_sieve(25)
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> prime_sieve(10)
[2, 3, 5, 7]
>>> prime_sieve... | 5ff2708fb92387ac671b54829ff4710fcf7ac2a8 | 643,805 |
def shipDown(self):
""" Returns True if alien bolt collides with ship and removes bolt from _bolts"""
for bolt in self._bolts:
if self._ship is not None and self._animator is None:
if self._ship.collides(bolt):
# Sound(self._soundList[0]).play()
self._bolts.re... | 1de376d7d4343068ffb6ea8b65d8382291d1c895 | 643,807 |
import wave
def read_audio(path):
"""
Read the audio from path into a wave_read object.
Parameters
----------
path : string
Specifies path of the audio file.
Returns
-------
wave_reader : class : 'wave.Wave_read'
wave_params : class : 'wave._wave_params'
"""
wave... | 0b91aac08e2e0520c90ffa1360cc32aa82665900 | 643,809 |
def ask_question(question, not_done):
"""Method to ask the user a simple yes or no question"""
while not_done:
answer = input("\n[?] {} ['yes' or 'no']: ".format(question))
if answer[0].lower() == "y":
break
if answer[0].lower() == "n":
not_done = False
... | bc8a661fa2c301b652d98d6eae01c7ff03cce6c5 | 643,811 |
def locus_generator(start, stop, length, n, f):
"""Generate index positions
Parameters
----------
start : int
A starting or minimum index
stop : int
The largest possible index
length : int
The length of a substring to extract
n : int
The number of indices to ... | ade11318c4f05a20e780087177ad69c7f9aed8f9 | 643,816 |
def get_gRNAs(db):
"""get gRNAs
:param db: ultra or g_ultra list
:return: set object with sequences as elements
"""
hold = []
for j in range(len(db)):
hold.append(db[j].split(',')[0])
hold_set = set(hold)
return hold_set | 3f99e6a8af52e678dd77a72634e314968c5bd46c | 643,818 |
import math
def floor(value):
"""Rounds a number down to the nearest whole number."""
return math.floor(value) | ae79c659bbdb157c2d79e7bb7ba1747ef19ada1c | 643,823 |
def build_feature_dict(opt):
"""Make mapping of feature option to feature index."""
feature_dict = {}
if opt['use_in_question']:
feature_dict['in_question'] = len(feature_dict)
feature_dict['in_question_uncased'] = len(feature_dict)
if opt['use_tf']:
feature_dict['tf'] = len(feat... | 2b2d4c34637a3709766cf8f8cfc3df5b6910d8b3 | 643,828 |
import math
def to_degree7(r):
"""
Convert radians to 'degrees' with a 0-7 scale.
:param r:
:return: direction in 7-value degrees
"""
return round(r * 4 / math.pi) | 832a5bac58114f2b121cf0bd5dc92bc124ad3381 | 643,830 |
import operator
def ParseIpRanges(messages, ip_ranges):
"""Parse a dict of IP ranges into AdvertisedPrefix objects.
Args:
messages: API messages holder.
ip_ranges: A dict of IP ranges of the form ip_range=description, where
ip_range is a CIDR-formatted IP and description is an optional
... | 67421829f0451859e940de282b84230e4252d58c | 643,831 |
def iscellular(kit_name):
"""
Determine if a kit is a cellular kit or a WiFi kit based on kit name.
:param kit_name: Name of the kit
the LTE-M name is only used in prototype kits
"""
return "CELLULAR" in kit_name.upper() or "LTE-M" in kit_name | 151430128f348866e58fc4d3c41ecbf6a4d69a2f | 643,832 |
def rb_epc(fit, rb_pattern):
"""Take the rb fit data and convert it into EPC (error per Clifford)
Args:
fit (dict): dictionary of the fit quantities (A, alpha, B) with the
keys 'qn' where n is the qubit and subkeys 'fit', e.g.
{'q0':{'fit': [1, 0, 0.9], 'fiterr': [0, 0, 0]}}}
... | 74bcf29747cfe5522ff5f6085fc0a8b71c48569f | 643,837 |
import ntpath
import posixpath
def MakeZipPath(os_path, isdir, iswindows):
"""Changes a path into zipfile format.
# doctest doesn't seem to honor r'' strings, so the backslashes need to be
# escaped.
>>> MakeZipPath(r'C:\\users\\foobar\\blah', False, True)
'users/foobar/blah'
>>> MakeZipPath('/tmp/tmpfoo... | 175070384239c751a6662a4f46133f0dad69d84f | 643,839 |
def bytes_from_str( size_str ):
"""
Given a string description of directory size, return float bytes.
Supports B, K, M, G, T suffixes. B can be ommitted.
"""
unit_conversions = { char: 1024**power for ( power, char ) in enumerate( [ "B", "K", "M", "G", "T" ] ) }
try:
coeff = unit_convers... | 43c0abdf513ebb60ed486f1a8c9a8143d4dbcf0e | 643,840 |
import functools
def _str_table_result(cols, rows):
"""Turn a Civis Query result into a readable table."""
str_rows = [['' if _v is None else _v for _v in row] for row in rows]
# Determine the maximum width of each column.
# First find the width of each element in each row, then find the max
# wid... | 397c71590d630d61a7204c1098191de5ff433f56 | 643,842 |
def get_recipients(connection, search_term, search_pattern="CONTAINS_ANY_WORD", offset=0, limit=-1,
enabled_status='ALL'):
"""Get information for a set of recipients.
Args:
connection(object): MicroStrategy connection object returned by
`connection.Connection()`.
... | cfc1bf8e62395ef63aa36c97d4ab280d9851584b | 643,845 |
def bin_centers(bins):
"""
Centers of histogram bins to plothistograms as lines
:param bins:
Bins limits.
:return:
Centers of bins.
"""
return bins[:-1] + (bins[1:] - bins[:-1]) / 2.0 | e30c67efcb8e2249d23aebe73f1bff4894ed9b4d | 643,846 |
def get_max_row_column(train, val, test):
"""Returns the total number of rows, columns from train, validation and test arrays in COO form."""
r = max(max(train[:, 0]), max(val[:, 0]), max(test[:, 0])).astype(int) + 1
c = max(max(train[:, 1]), max(val[:, 1]), max(test[:, 1])).astype(int) + 1
return r, c | 43f07cc68f5b4dcee2503ffb0d704ad599407efd | 643,847 |
def residualSumOfSquares(xs,ys,func):
"""Return the residual sum of squares."""
return sum([(func(xs[i])-ys[i])**2 for i in range(len(xs))]) | c513c0100a4076ccf8a2de580a6af5caeb9cd373 | 643,850 |
from typing import Iterable
def _get_common_letters(box_id1: str, box_id2: str) -> str:
"""Returns common letters in the box ids
Arguments:
box_id1 {String}
box_id2 {String}
Returns:
[String]
"""
# I can iterate through both the string and find out the diff in one iteration... | 8e20830b951d1876d523c51448ec7a3f9c55d250 | 643,854 |
def _reGroupDict(d, newgr):
"""Regroup keys in the d dictionary in subdictionaries, based on
the scheme in the newgr dictionary.
E.g.: in the newgr, an entry 'LD label': ('laserdisc', 'label')
tells the _reGroupDict() function to take the entry with
label 'LD label' (as received from the sql databas... | eed4344c415dbb12cdceb8edb54ef2a1fbc369d2 | 643,855 |
import time
def date_to_TS(date, form='%Y-%m-%d %H:%M:%S'):
""" Use your local time-zone to convert date in specific format to
timestamp.
Parameters
----------
date : str
A date to convert.
form : str (default '%Y-%m-%d %H:%M:%S')
Time format.
Returns
-------
TS :... | de1e5223cce8a55566f4e0657482f1ee08e6b30d | 643,858 |
def sqlite_list_text(elements):
"""Return text to create a repr of a python list."""
return "'[' || %s || ']'" % "|| ', ' ||".join(elements) | f50766d680269d61814d679e635143f799a14294 | 643,859 |
import re
def extract_url(input_string):
"""Extracts a URL from a blob of text.
Params:
- input_string: (type: string) string to parse.
Returns:
- result: (type: string) extracted URL.
"""
if input_string:
url_search = re.search(
r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&... | 0e7b7ee68ed7e5b40777c613e109db226eee58d3 | 643,860 |
def get_unmatched_part(abbr: str, text: str):
"""
Returns a part of `abbr` that wasn’t directly matched against `str`.
For example, if abbreviation `poas` is matched against `position`,
the unmatched part will be `as` since `a` wasn’t found in string stream
"""
last_pos = 0
for i, ch in enum... | 042273ca8ac9c50eebeed2e519b78406ff70b26b | 643,865 |
def create_output_header(data_type, species_list, biomet_var_list=[]):
"""
A helper function to create the header for output data frame.
Parameters
----------
data_type : str
The type of output dataframe
* 'flux' - flux data
* 'diag' - curve fitting diagnostics
species_l... | 7ae280b59433a39ac2244ee9ee5306e1676818cd | 643,866 |
def split_sections(diff):
"""
takes a git diff and breaks it up into sections
:param diff: a diff piped from git
:return: a list of sections
"""
sections = []
section = ''
for line in diff.splitlines():
line = line.strip()
if line.startswith('@@'):
if section... | 26a79be87a1695135be267012f0ad1552a9c2680 | 643,868 |
def calculate_fpl(household_size, annual_income):
"""Calculate income as a percentage of the Federal Poverty Level."""
fpl = 4160 * int(household_size) + 7610
return float(annual_income) / fpl * 100 | 6928c6c8ac6dd6fe0a94efa75ec838237213831e | 643,871 |
def zero_module(module):
"""
Zero out the parameters of a module and return it.
"""
for p in module.parameters():
p.detach().zero_()
return module | 005ff5799a2ddcf5b93e9e12e1dce9372c1c5e9b | 643,876 |
def factorial(
*,
number: int,
) -> int:
"""Recursive Factorial Function
Args:
number (int): number
Returns:
int: factorial of the number
"""
if number <= 1:
return 1
return number * factorial(number=number - 1) | 0ab7323ebd6bd9df7a72a3b26abeddc46e8a5a37 | 643,881 |
from typing import Iterable
def norm1(x: Iterable[int]) -> int:
""" Returns the manhattan distance (1-norm) of x """
return sum(map(abs, x)) | 04dea3fb08401ca6d9bf4cc759410c5e370248d7 | 643,885 |
def getlink(tag):
"""
Get the hyperlink and title from a tag.
Return None tuple if there isn't a link.
"""
if not tag or isinstance(tag, str):
return None, None
if "href" not in tag.attrs:
return None, None
return tag["href"], tag["title"] | 85af70a2b219b0c90f91f9dce2eaf9dc69cba2ee | 643,891 |
from typing import Tuple
def __parse_gav(full_artifact_path: str, root="/") -> Tuple[str, str, str]:
"""Parse maven groupId, artifactId and version from a standard path in a local maven repo.
e.g: org/apache/maven/plugin/maven-plugin-plugin/1.0.0/maven-plugin-plugin-1.0.0.pom
-> (org.apache.maven.plugin, ... | bb8a30f77a2e0fd9dff2b67cce85ede601b36a6d | 643,892 |
def getTimestamps(data):
"""
Get the time stamps for each position
:param data: JSON Object
:return: Array of timestamps
"""
timestamps = data['time']
return timestamps | 7ecfc32b80cfd1967b80090d02fb5db1da03ccaf | 643,893 |
import math
def update_alg_squarert(score):
"""Change the score by taking the square root."""
return math.sqrt(score) | aa1a91ddbff1537244275bb170c6cc97b190a8f9 | 643,894 |
def lifetime_init(rule='1/e'):
"""Initialize a lifetime object.
Parameters
----------
rule : str {'1/e', 'trapz', 'simpson'}, optional
Name of the method to integrate the correlation curve. \n
'1/e' uses the 1/e rule and assumes an exponential decay. It linearly
interpolates the... | 246bf31672fcd98a7ccd272ec7967c8a5e51817b | 643,897 |
import string
import random
def random_string(lenght: int = 10) -> str:
"""Generate a random string composed of lower cased ascii characters
Args:
lenght (int, optional): lenght of the string to generate. Defaults to 10.
Returns:
str: random string of lenght `lenght` composed of lower ca... | e44f1f44234f9a47eec854c7c351aa26fd68d0bf | 643,899 |
def generatetfmatrix(matrix, idf):
"""
Generate a new term weight matrix when supplied with the current `matrix` and
the weighing factors `idf`. Returns a new matrix using lists.
"""
docamount = len(matrix[0]) # get the amount of documents
wordcount = len(matrix)
updatedmatrix = list() # c... | b62fdc6ec77a923e74dcaa529124ba19dabe1fd7 | 643,900 |
def parse_column_names(df):
"""
Method used to parse the column names
:param df: Original data frame
:type df: pd.DataFrame
:return: pd.DataFrame -- Formatted data frame
"""
cols = set(df.columns.tolist())
if "StreamID" in cols:
df.rename(columns={"StreamID": "stream_id"}, inpl... | 2dba3d0d185a0111e93763f74f303dc4bd46f418 | 643,905 |
def find_containerName_by_containerId(containers_list, container_id):
"""
Function to get containername based on container ID.
Parameters
----------
containers_list : list
Containers list extracted from CVP.
container_id : string
ID of the container to search
Returns
--... | c3660ab437765a8681def3c2c2b0f4f974629949 | 643,907 |
def distance_from_speed_and_time(movement_speed, movement_time):
"""Returns distance from speed and time"""
return movement_time * movement_speed * 1000 / 3600 | 8cc1a9745c4f03ffe47e6e872a04435beb82a15f | 643,908 |
from pathlib import Path
def get_image_paths(image_folder: Path) -> list:
"""
Get all images in image folder ending in .jpg or .png
"""
suffix_set = {'.jpg', '.png'}
return [
image for image in image_folder.iterdir() if image.suffix in suffix_set
] | edbeacbe899f2e19a1d8a460d2b30215e28c2a46 | 643,909 |
def personal_top_three(scores):
"""
Return top three score from the list. if there are less than 3
scores then return in a decending order the all elements
"""
# sorted the list in a decending order
sorted_scores = sorted(scores, reverse=True)
# check if there are at least 3 elements... | 7937d881fd370e6a710511c51ae5772441f66825 | 643,910 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.