content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def fold_dict(data, nb_level=10**5):
"""Fold dict `data`.
Turns dictionary keys, e.g. 'level1/level2/level3', into sub-dicts, e.g.
data['level1']['level2']['level3'].
Parameters
----------
data: dict
dict to be folded.
nb_level: int
Maximum recursion depth.
Returns
... | 793e319abae6472c3b22f19bc15d15173c069eb7 | 598,563 |
from typing import Sequence
from typing import List
def rotate_sequence(
sequence: Sequence,
new_first_element_index: int,
) -> List:
"""Rotates any sequence, making it start on the new given index
"""
sequence_copy_list = [element for element in sequence]
return sequence_copy_list[new_first... | bc7005bb7bca15f74b1b1100a7ee546fe50c2f64 | 598,566 |
def binary_search_recursive(arr, val, start, end):
"""searches arr for val between and including the indices start and end.
Parameters:
arr (array): array to search.
val (type used in array): value to search for in arr.
start (int): start index to search for val in arr.
end (int... | de48f0a81af50077fe1ca0e31ab11982eb8cbe51 | 598,569 |
def check_enter(user_input):
"""Accepts no input (= Enter) and skip"""
if user_input in ['', 'skip']:
return True
return False | 34cbd7b01795bd3d1e6548e6b8f779b845f60d79 | 598,574 |
def extract_issues_html(html):
"""
Extracts the part of the HTML page, which contains the list of issues
Testing the relevant part avoids getting false positives/negatives
due to certain texts being present also in other parts of the page.
"""
return html.split('id="issues"')[1] | 56304effc096bb5007d7f3c04bc87860a602c10d | 598,578 |
import functools
def retry(exceptions=Exception, tries=-1):
"""
A retry decorator which retried a function if one of the given exceptions
were raised.
:param exceptions: An exception or a tuple of exceptions to catch.
:param tries: The maximum number of attempts, -1 for infinite.
:return... | 8aeac5fc071e56acce17f464d43d214689f6b792 | 598,583 |
import re
def get_num(string):
"""
Takes a string and returns the numbers in that string, decimals included
Args:
string(str): The string containing a number
Returns:
A list of all the numbers contained in that string, as floats
"""
digits = r"-?[0-9]*\.?[0-9]+"
parameter =... | 11559b461229a295a8dc5ec652fa47251b942a82 | 598,585 |
def single_surveyation(m):
"""Return motivation if only one provided."""
if len(m.split('|')) == 1:
return m
return None | 398289fa09c34f5d7987fa92eae6ad9a58172c70 | 598,590 |
def _get_attentions(tokens_a, tokens_b, attn):
"""Compute representation of the attention to pass to the d3 visualization
Args:
tokens_a: tokens in sentence A
tokens_b: tokens in sentence B
attn: numpy array, attention
[num_layers, batch_size, num_heads, seq_len, seq_len]
Retur... | 59fc20890af3ff737736aec837b8d799c36f2079 | 598,593 |
import re
def is_valid_hostname(hostname):
"""Determine whether a hostname is valid as per RFC 1123."""
# Maximum length of 255
if not hostname or len(hostname) > 255:
return False
# Allow a single dot on the right hand side
if hostname[-1] == ".":
hostname = hostname[:-1]
# C... | a6ffb7713b81e51fc149d25e91f924f629c5e471 | 598,594 |
import math
def cosineSimilarity(a, b):
"""
Compute the similarity between two vectors using the cosine similarity metric
"""
dotProduct = 0
aMagnitude = 0
bMagnitude = 0
for i in range(len(a)):
dotProduct += (a[i] * b[i])
aMagnitude += math.pow(a[i], 2)
bMagnitude ... | 6e59f1afe846ae4ab80e8860d588b8d1395865df | 598,598 |
def parse_line16(string):
"""
Parse string containing exponental numbers of length 16 chars.
Note: Numbers may not have a space in between.
"""
assert len(string) % 16 == 0, 'Given string should have 16n chararacters'
# Replace the exponent D with E
string2 = string.replace('D', 'E')
... | fe4fe6fed44d37b4c0102df406c7b9395906efbc | 598,599 |
import time
def nersc_format_datetime(timetup=None):
"""
Given a time tuple from the time module, this will return a string in the proper format to be properly interpreted
by the NERSC Slurm queue scheduler.
Args:
timetup: tuple. A time.time() tuple object representing the time you want to tr... | 2e8b3b6a4ef1b9e41bcb2552032b1b8362b2ccc3 | 598,601 |
def subset_dataframe(df,feature_cols, remove_cols):
""" Create and return a copy of the desired dataframe without the listed columns.
Parameters
----------
df : pandas Dataframe
Dataframe from which subset will occur
feature_cols: list of strings
Column labels of features to be use... | 7dc9a5e75f15fe7fd6f3773b630648bddad6651e | 598,604 |
from typing import List
def merge(A: List[int], B: List[int]) -> List[int]:
"""merge two sorted lists"""
combined: List[int] = []
while A and B:
# merge backward, from big to small
a = A.pop()
b = B.pop()
if a >= b:
combined.append(a)
B.append(b)
... | 060f123b7a5551b2a52a63f75149a2c0ea0158d8 | 598,605 |
def findMiddle(input_list):
"""
Finds the middle element in a list. if list is even, returns two middle elements
"""
middle = float(len(input_list))/2
l = []
if middle % 2 != 0:
l.append(input_list[int(middle - .5)])
return l
else:
l.append(input_list[int(middle)])
... | b7de195172123e0382789b505110f5c5d4eb5b38 | 598,610 |
def user_login(r):
"""
Because dict nesting, this is a special function to return the user_login out of a dict
"""
if "user" in r:
if "login" in r["user"]:
return r["user"]["login"]
return None | 389cccf45d9467c43e1c5901eb1fbca1b88bace5 | 598,613 |
def get_rows_and_header(items):
"""
Return rows and header to print using tabulate.
:param items: list of dicts
:return: rows are all values in items. header is keys of dict
Example:
If items is a list of vpc dicts:
[
{"id":vpc-id1, "name":name1, "number_of_subnets": 6},
... | 094ef013e36591b720c2df16254532af4b7e8d19 | 598,617 |
def scrap_comments(sub, limit=10):
"""
Function to scrap the top-10 comments(as it was done in data collection for training data)
Params
sub: submission instance
Returns: top-10(if num_comments > 10 or top x) comments combined into single string with space
"""
# agg into ... | e78186136b4b4f796578ecf074354b4302cfe8c8 | 598,627 |
def is_float(data):
"""Checks if data is a float value."""
return isinstance(data, float) | a382851289479f18832f5d3f4ba3bd0ee742d809 | 598,631 |
def render_doc(jinja_env, stig_rule, deployer_notes):
"""Generate documentation RST for each STIG configuration."""
template = jinja_env.get_template('template_doc.j2')
return template.render(
rule=stig_rule,
notes=deployer_notes
) | 7eb3fda371e5a59ef7d58ceb6b6d1b3f754b8a79 | 598,632 |
from typing import AnyStr
from typing import Tuple
from typing import Optional
def split_chunk(part: AnyStr, char: AnyStr) -> Tuple[AnyStr, Optional[AnyStr]]:
"""Split chunk into two parts, based on given delimiter character.
It will return tuple of those two chunks. If no such delim exists,
the first el... | 02f27fe59b0cb021abd8f5a4bf25a51eaece0c8b | 598,633 |
def general_poly (L):
""" L, a list of numbers (n0, n1, n2, ... nk)
Returns a function, which when applied to a value x, returns the value
n0 * x^k + n1 * x^(k-1) + ... nk * x^0
"""
def func(num):
poly = 0
for i in range(len(L)):
poly += L[i] * num ** (len(L) - 1 - i)
... | 3e3d68772b12d6e6ca9d682c0de89e7e9df3146e | 598,634 |
def get_kpts_line_explicit(kpts_line, ndiv):
"""
Explicitly lists all points along a given high-symmetry k-path
Parameters
----------
kpts_line: Kpoint object describing the high-symmetry k-path
ndiv : (int) number of divisions along high-symmetry lines
Returns
-------
abs_pat... | 33646a534916f3d6b1b0a5222a21b7bc1ebed991 | 598,636 |
def _generate_bitfill(p):
"""
pe_A helper function for yield_bits_on to generate the primitive-root lookup table is
:param p: prime number which is also a primitive root of 2
Generates a lookup list for powers of two (called here a bitfill). To generate a valid bitfill,
p must be prime and 2 must ... | 90405367b46babcabd7c6269830f25231d5177ed | 598,637 |
def get_Id_Iq(self):
"""Return Id and Iq
Parameters
----------
self : OPdq
An OPdq object
Returns
-------
I_dict : dict
Dict with key "Id", "Iq"
"""
return {"Id": self.Id_ref, "Iq": self.Iq_ref} | cba09701c3cd1fb9dda0a560c14819560a38b48e | 598,639 |
def _validate_coverage_threshold(coverage_threshold):
"""
Validate that coverage_threshold is between 0 and 1 and if it is None set to zero.
:param coverage_threshold: Should be number between or equal to 0 and 1.
:type coverage_threshold: float or int
:return: coverage_threshold
... | 96f3e6fc1ff7288c73ec3e80decbd84e3c9f3ced | 598,640 |
def _ExplicitEuler_step(f, xi, ti, h):
"""Internal function implementing one step of the Explicit Euler method.
The ODE to be solved is of the form: x' = f(t,x), x being a vector in n-dimensions
- **parameters**, **types**, **return** and **return types**::
:param f: function in x' = f(t,x)
:param xi: current ... | faa8fe5c38cfff579c8ce2878a10f864ab97d827 | 598,643 |
def _descendants(node):
"""
Returns the list of all nodes which are descended from the given
tree node in some way.
"""
try:
treepos = node.treepositions()
except AttributeError:
return []
return [node[x] for x in treepos[1:]] | 677030ec819082a7124c2e9d85747ad92293876e | 598,646 |
def arcseconds_to_seconds(arcseconds):
"""
Convert Arc Seconds to Seconds.
:param arcseconds:
:return: converts arcseconds into seconds.
"""
return arcseconds / 3600 | 6d7c2212f7c615a03e030cec91fd8470e4d7119c | 598,647 |
def grad_method_validation(method, tape):
"""Validates if the gradient method requested is supported by the trainable
parameters of a tape, and returns the allowed parameter gradient methods.
This method will generate parameter gradient information for the given tape if it
has not already been generate... | 336aea91713a704ff41c140a8e37225a4ffbc36c | 598,649 |
def _formatOptions(kargs):
"""Returns a string: "key1=val1,key2=val2,..."
(where keyx and valx are string representations)
"""
arglist = ["%s=%s" % keyVal for keyVal in kargs.items()]
return "%s" % (",".join(arglist)) | a8dd5f62eafe995471641ca577430bc60f1ffea0 | 598,652 |
def closest_power(base, num):
"""
base: base of the exponential, integer > 1
num: number you want to be closest to, integer > 0
Find the integer exponent such that base**exponent is closest to num.
Note that the base**exponent may be either greater or smaller than num.
In case of a tie, return t... | b568854aae322c660a364e6165350781526c496b | 598,653 |
import re
def remove_ansi_escapes(s):
"""
Removes 7-bit C1 ANSI sequences (e.g. used to colorize command line
outputs) from the given string.
"""
ansi_escape = re.compile(r'''
\x1B # ESC
(?: # 7-bit C1 Fe (except CSI)
[@-Z\\-_]
| # or [ for CSI, followed ... | 9b866a6ab4d9f15fc9a301d7a5973de15bd22e23 | 598,658 |
def _configure_context_for_negotiation(context, inner_protocols):
"""
Given a PEP 543 list of protocols to negotiate, configures the SSLContext
to negotiate those protocols.
"""
if inner_protocols:
protocols = []
for np in inner_protocols:
proto_string = np if isinstance(... | dfd8addcaa29678d5006b2202fc1c02d1f54d9ba | 598,660 |
def adata_to_color_dict(adata, cluster_use):
"""
Extract color information from adata and returns as dictionary.
Args:
adata (anndata): anndata
cluster_use (str): column name in anndata.obs
Returns:
dictionary: python dictionary, key is cluster name, value is clor name
"""... | b4e20d7e6ae8c1824ba1350dacb7b266a9e7f96d | 598,661 |
import pickle
def load(filename):
"""
Reads a saved instance of the genetic algorithm:
-filename: Name of the file to read the instance. No extension is needed.
Returns the genetic algorithm instance.
"""
try:
with open(filename + ".pkl", 'rb') as file:
ga_in = pickle... | c4c6775beed616de150c19d57aebf91372af6347 | 598,666 |
import tempfile
def make_temp_filename(suffix=''):
"""Return a temporary name for a file."""
if len(suffix) > 0 and suffix[0] != '-':
suffix = '-' + suffix
return (tempfile.mkstemp(suffix, prefix='cs-test-'))[1] | 75326442e9349dd27ca21631b1f267baa47e7563 | 598,667 |
def query4(transaction, **params):
"""
Which 3 countries in the network have the most people within a specified age range?
"""
query = f'''
match $person isa person,
has age > {params['age_lower']}, has age < {params['age_upper']};
$country isa country, has name $country-name;
... | 44f82b869616a4061e0a7723cb6f8192d1475849 | 598,674 |
import re
def _get_resource_repr(resource):
"""Return a nice name for the `resource` based on its str representation"""
name = str(resource)
name = re.sub(r'<class.*?> ', '', name).strip() # Remove type()
name = re.sub(r'of Org.*\)$', '', name).strip() # Remove Org
name = re.sub(r'\s\([a-z0-9]{3... | 41cde51bf117a96dc062149f99b78b558bf7989d | 598,676 |
import requests
def recurse(subreddit, hot_list=[], after="", count=0):
"""Returns a list of titles of all hot posts on a given subreddit."""
url = "https://www.reddit.com/r/{}/hot/.json".format(subreddit)
headers = {
"User-Agent": "linux:0x16.api.advanced:v1.0.0 (by /u/bdov_)"
}
params = ... | 95a7a650c78c904d311adee63bc30848bb37a19e | 598,677 |
def kinematic_sensible_heat_flux(sensible_heat_flux_W_m2, air_density_kg_m3):
"""
Calculate kinematic sensible heat flux <w' theta'> from the raw sensible heat flux.
Args:
sensible_heat_flux_W_m2: Sensible heat flux in W m-2 units
air_density_kg_m3: Density of air derived from near surface ... | 876cce0fafa61202ba1a8c2add6392422652e62b | 598,678 |
def retrieve_posts(piazza_class):
"""Retrieve posts of the class.
Args:
piazza_class: Piazza class instance.
Returns:
Dict of every post in the class.
"""
feed = piazza_class.iter_all_posts()
posts = {}
for index, post in enumerate(feed):
posts[index] = post
ret... | d6032cc08d261f20549b3d1d22eff2189b42024b | 598,680 |
import math
def get_distance(start, end):
"""Distance between two points."""
coord_factor = 10000000.0
lat_1 = start.latitude / coord_factor
lat_2 = end.latitude / coord_factor
lon_1 = start.longitude / coord_factor
lon_2 = end.longitude / coord_factor
lat_rad_1 = math.radians(lat_1)
l... | bb6507cf017043659b4fc96e411405d41dd1a877 | 598,682 |
def _compare_term(minterm, term):
"""
Return True if a binary term is satisfied by the given term. Used
for recognizing prime implicants.
"""
for i, x in enumerate(term):
if x not in (3, minterm[i]):
return False
return True | b2df6985d2aa669e98d906ac76c4fe9c5836702f | 598,683 |
def genStringOptData(iter_data_dict: dict, key: str) -> str:
"""Generates a string that is compatible and used in the GAMS model to overwrite parameters for time series iteration.
Args:
iter_data_dict (dict): dictioary that holds the time series iteration information.
key (str): identifier that... | 1b5e5844700252479d6f231b44bd15eb315c9a25 | 598,690 |
def list_representatives(GCF_dict):
"""retrieves the represenatives
----------
GCF_dict
dictionary, {Representative: family members}
returns
----------
outlist: list, list of filenames
"""
outlist = []
# with open(json_file, "r") as jfile:
# GCF_dict = json.load(jfile)... | 69ba8dd8dd17e130914458d1ddb8dac61402f1a5 | 598,691 |
def pv_make(name:str, plane:str, flag:bool=False) -> str:
"""
Generate PV name for given BPM name and data plane.
Note, use harmonica PV prefix if flag is True
Parameters
----------
name: str
BPM name
plane: str
selected plane (x, y or i)
flag: bool
flag to use ... | f9ccffa3a0eacba7e6f67d6519d50d94a267d10e | 598,692 |
def process_list(string):
""" Create list from string with items separated by commas
Helper for get_sorted_emails.
"""
# Remove all spaces
no_spaces = "".join(string.split())
# Split at commas
split_lst = no_spaces.split(",")
# Remove empty strings and return
return list(filte... | 4191c63cfb3ef87a08102235152c2d2a56696749 | 598,694 |
def get_log_ax_lims(vals, base=10):
"""Get good limits for log-scale axis.
Since several plotting functions have trouble automatically doing this.
Parameters
----------
vals : array_like
The values plotted on the axis.
base : float, optional
The base of the axis
Returns
... | be976166d6d52e2570d0f82f7a344360dcb6d700 | 598,696 |
from datetime import datetime
def _parse_timestamp(ts):
"""
Convert the provided timestamp format to a Python datetime+TZ
"""
# remove the unhelpful colon in the TZ specification
ts = ts[0:-3]+ts[-2:]
return datetime.strptime(ts, '%Y-%m-%dT%H:%M:%S %z') | de4439200452262ea6356f690e006bac10e33910 | 598,701 |
import copy
def stringify_values(dictionary):
"""
Given a dictionary convert all values into the string representation of
the value. useful for dicts that only allow string values (like os.environ)
:param dictionary: the dictionary to convert
:return: a copy of the dictionary where all values a... | c7a231c1bb127f673ab58a8ea63146ea7568add0 | 598,703 |
def extendedGCD(a, b):
"""Returns gcd, x and y so that a*x+b*y = gcd(x,y)"""
# Base case (when a = 0)
if a == 0:
return (b,0,1)
# Recursive case
else:
gcd, x, y = extendedGCD(b%a,a)
return (gcd, y-(b/a)*x, x) | 15006524a6ec8269491f71fb04183bb3ab38ed77 | 598,714 |
def _GenerateFilter(params):
"""Generate a filter object using dot separated object paths.
A list of dot separated paths (foo, foo.bar, foo.baz) is merged into a
dict which can be used as a filter on a received object. Objects are parsed
until a falsy value (such as {}) is reached which includes everything in... | e26f01a2b1f8f11cc0983ccb50989331c00ff9c7 | 598,716 |
def get_email_domain(email):
"""Generates email domain from given email address."""
return "www."+email.split("@")[-1] | c44526f98f2e2b7afc3efecbdc57016fc104bfb9 | 598,718 |
def decode_message(encoded, key=4):
"""Decoding the message.
Parameters
----------
encoded : string
Code point string to be converted back to original string.
key : int or float
Code point number needed for user to decrypt the encrypted message.
Retu... | f6837110462e8cef448a25f29adcb3814220d290 | 598,719 |
def set_search_csrf(session):
"""Extract the required CSRF token.
LinkedIn's search function requires a CSRF token equal to the JSESSIONID.
"""
csrf_token = session.cookies['JSESSIONID'].replace('"', '')
session.headers.update({'Csrf-Token': csrf_token})
return session | 1c506f6c7039b4908cadd772c2e7a289b7d18ae3 | 598,727 |
import torch
def prepare_confusion_matrix(all_preds, all_targets, class_map):
"""Prepare Confusion matrix
Args:
all_preds (list): List of all predictions
all_targets (list): List of all actule labels
class_map (dict): Class names
Returns:
tensor: confusion matrix for size... | 498f4c54c726128f769cf6ef6fe28ad2f8dad013 | 598,735 |
def flatten_int(l):
"""
Flatten a multi-dimensional list to a one-dimensional and convert all values to integers.
:param l: list of lists with values that can be cast to int
:return: flattened int list
"""
return [int(item) for sublist in l for item in sublist] | 0cc6ec0a73a7e90ad8ba925e1c4d522f6a421f67 | 598,736 |
def ynprompt(default=None, message=""):
"""
Ask a yes/no question.
Returns True for yes, False for no.
message is any text to show at the prompt.
"""
#handle defaults
if default in ("y", "yes"):
default=True
prompt="[y]/n"
elif default in ("n", "no"):
default=False
prompt="y/[n]"
else:
default=None
... | 73aa088e5fa38ec49f63c9b54e4844d8a67856e1 | 598,737 |
import string
def header_link(title):
"""Return a github-style link target for a title.
>>> header_link('Hello there!')
'hello-there'
"""
# This doesn't handle multiple titles with the same text in the
# same file, but usually that's not a problem. GitHub makes
# links like the-title, the... | 8bdbd18cf5e842edddf07c0c653a5a613c000537 | 598,738 |
def get_elife_doi(article_id):
"""
Given an article_id, return a DOI for the eLife journal
"""
doi = "10.7554/eLife." + str(int(article_id)).zfill(5)
return doi | ac7b110ddd03a03a38e7cf013743e05a2b0054f1 | 598,739 |
def pseudo_gem(start_loc, frag_lengths, f2f_dist):
"""
Create a pseudo-GEM on a random start location.
Args:
start_loc (int): random start location on the genome (ex: 390)
frag_lengths (list): lengths of each fragments (ex: [100, 200, 150])
f2f_dist (list): fragment to fragment distance... | 66768ff97801dbc77e9525c08ec9fac736ddea6a | 598,745 |
def _unescape_xml(xml):
""" Replace escaped xml symbols with real ones. """
return xml.replace('<', '<').replace('>', '>').replace('"', '"') | b90fef782db6397535b1d9a5208a607176c8d0e3 | 598,749 |
def assign_labels(sentences):
"""
Assigns the majority class label to each sentence for each task.
Returns two lists: predicted AC and predicted SP
"""
predictions_category = []
predictions_sentiment = []
for sentence in sentences:
prediction_cat = 'NA'
predictions_catego... | 67bdc73a21ee51c9397f0faf907ec00c8d19c237 | 598,755 |
import math
def rotationMatrixAboutAxis(rotAxis, theta):
"""
Generate the rotation matrix for rotation about an axis.
:param rotAxis: axis of rotation
:param theta: angle of rotation
:return: rotation matrix
"""
cosTheta = math.cos(theta)
sinTheta = math.sin(theta)
C = 1 - cosTheta... | 92173518134bd768925caf38f57fd21b042e22f3 | 598,758 |
def precision(recommends, test):
"""计算准确率
:param recommends: 给用户的推荐结果{用户 : 该用户的推荐列表}
:param test: 测试集{用户 : 该用户感兴趣的物品列表}
:return: 准确率
"""
hit = 0
total = 0
for user, items in recommends.items():
rec = set(items)
tes = set(test[user])
hit += len(rec & tes)
total += len(tes)
return hit / (total * 1.0) | 1e478a4415904b829ef3487143f34fd2663c66dc | 598,759 |
from pathlib import Path
import zipfile
import gzip
import shutil
def unzip_file(element_path):
"""Checking if the path points to an existing folder or to its .zip format; if only the .zip format exists,
it unzips the folder.
Parameters
----------
element_path: PosixPath
Absolute path of ... | 646133d74f84fb496c3eae51b5516d2d50535b48 | 598,762 |
def current(t):
"""Current waveform."""
return -100e-6 | df484a41a0daf00d8093c51f21440058ba56e133 | 598,763 |
def flatten(collection):
"""Flatten a nested collection by concatenating sub-collections.
Examples
--------
.. doctest::
>>> a = [[1, 2], [2, 3]]
>>> hl.eval_expr(hl.flatten(a))
[1, 2, 2, 3]
Parameters
----------
collection : :class:`.ArrayExpression` or :class:`.... | 00bd34c29607645d0194d058d876f3b2199b45d3 | 598,769 |
import typing
import re
def _get_mypy_errors(stdout) -> typing.Dict[int, typing.Dict[str, str]]:
"""Parse line number and error message."""
errors: typing.Dict[int, typing.Dict[str, typing.Any]] = {}
# last line is summary of errors
for error in [x for x in stdout.split("\n") if x != ""][:-1]:
... | 7bc5b0c9cdbd9ce81a28c65885c36d5697c4900e | 598,770 |
def get_resultant(X,Y,Z):
"""This function gets the resultant magnitudes of three arrays of vector quantities: X, Y, and Z."""
resultant = []
for i in range(len(X)):
resultant.append((X[i]**2 + Y[i]**2 + Z[i] **2)**0.5)
return resultant | 494f819008a86a1a60e52f2f1bb9b5ac011b0508 | 598,773 |
def _filter_undesired_bots(bot_to_status_mapping, desired_bot_names):
"""Returns the desired bots for the builds status from the dictionary.
Args:
bot_to_status_mapping: Dictionary mapping bot name with revision to status.
desired_bot_names: List of bot names that will be the only bots returned in
th... | 17dd15ecbb2dd4fe5aa8d4654bc468b6ce229065 | 598,776 |
def around(number):
"""
Truncate a float to the third decimal
"""
if number is not None:
return int(number * 1000) / 1000.
else:
return None | 9f011cf7f7a0b0886aa4bd3a98674e9bb1326200 | 598,778 |
import codecs
def try_encoding(encoding, data):
""" Return decoded data, or None if decoding failed or the codec isn't
usable on this machine. """
try:
return codecs.decode(data, encoding, "strict")
except (UnicodeDecodeError, LookupError):
return None | 4c46d761d3bdb55a6df9e950761102cf71066395 | 598,779 |
def get_cmd_args(input):
"""Retuns cmd and its args from the input string.
Args:
input: the input string captured from the command line.
Returns:
(command, args[])
"""
arr = input.split(' ', 1)
if arr.__len__() == 1:
cmd, args = arr[0], []
elif arr.__len__() == ... | ec5b40733b8c6427392f86aa5172dbeae3fc08cb | 598,783 |
import re
def conv_estimate_number(s):
"""Convert a string representing a number with error to a float number.
Literally, string like '3.87(6)' will be converted to 3.876.
For now, estimate error in the parenthese is reserved.
Args:
s (str): number string
Retuns:
float
"""
... | 3cbc5fb105a8f6b5235543dfddb56891533be85b | 598,785 |
import re
def process_args(args: "list[str]") -> "dict":
"""Identify optional arguments from staged file names.
Args:
args (list[str]): A list of all command-line arguments.
Returns:
dict: A dictionary with three keys:
"files": The staged files to process.
"ignore... | 24339e94c7cfd249b507190d6b8b281fe24a79c4 | 598,786 |
def cumsum(list1):
"""Return the cumulative sum of the elements at each position of list1."""
return [sum(list1[:i+1]) for i in range(len(list1))] | 8a8148aea20d49d23c18091f60d51ffc29e3f8aa | 598,788 |
import torch
def batch_shape(model_name, x):
"""
Return a batch x with a relevant shape for a given model. For example,
# MLP
x = torch.ones(5, 360) # batch, features
# Conv1d
x = torch.ones(5, 1, 360) # batch, channel, features
# GNN
x = torch.ones(5, 360) # batch, features
graph ... | 81ecf813a1a8ad0b7007c4b440acd3a1daaabca9 | 598,790 |
def ds2array(ds, band=1):
"""
Given a datasource and optionally a band number,
return the array of values
"""
num_pix_wide, num_pix_high = ds.RasterXSize, ds.RasterYSize
if band > ds.RasterCount:
raise Exception('Band %s requested but raster only has %s bands' % (
band, ds.R... | ea198f040f6a68c608c450d79d6a09c7e7c2b056 | 598,792 |
import inspect
def is_subclass_by_name(child, parent_name):
"""
return True if child has a parent whose name is "parent_name"
issubclass does not work if the parent is loaded via import module
"""
if inspect.isclass(child):
if parent_name in [ancestor.__name__ for ancestor in inspect.getm... | 032966a43d7fb02f454e39626f8bc792683b39d6 | 598,795 |
import re
import six
def is_hex_string(string):
"""Check if the string is only composed of hex characters."""
pattern = re.compile(r'[A-Fa-f0-9]+')
if isinstance(string, six.binary_type):
string = str(string)
return pattern.match(string) is not None | 45eff67aa55104df1d69c0f51e74917765636d60 | 598,798 |
def fahrenheit_to_celsius(temp):
"""
Convert degrees Fahrenheit to degrees Celsius
:param float temp: The temperature in Fahrenheit
:return: The temperature in Celsius
:rtype: float
"""
return (temp - 32.0) / 1.8 | 5c090d34595db69bf98d60ce0dee91a7f867c27a | 598,800 |
from typing import List
def permutations(s: str) -> List[str]:
"""Compute a bunch of different forms of the same string."""
s = " ".join(w.capitalize() for w in s.split())
hyphens = s.replace(" ", "-")
underscores = s.replace(" ", "_")
compressed = s.replace(" ", "")
combined = [s, hyphens, un... | 0928f2e4789ffa1f301be2b6b493fd86a42243de | 598,806 |
def readdata(name):
"""
Read the data from a file and count it.
Arguments:
name: String containing the filename to open.
Returns:
A tuple (counts list, length of data).
"""
f = open(name, "rb")
data = f.read()
f.close()
ba = bytearray(data)
del data
counts =... | 3eeb05538b6bb93774fda234c880a2ac258650f4 | 598,809 |
import random
def create_simon(level):
"""Returns a number between 1 through 4"""
return random.randint(1, 4) | dc7452bab9a4a8d090451e1c4086df998f637728 | 598,810 |
def theta_(v, k, idx):
"""Estimate theta.
Parameters
----------
v: np.ndarray or list
A vector
k: int
An integer
idx: int
An integer
Returns
-------
res: float
"""
return (v[idx + 2 * k - 1] - v[idx + k])**2 | e741951aee2de8c64f782f11645651f841283897 | 598,811 |
def chunk_list(l, n):
"""
Chunks list into N sized chunks as list of list.
"""
if n <= 0:
raise ValueError('Chunk size of %s specified, which is invalid, must be positive int.' % n)
results = []
for i in range(0, len(l), n):
results.append(l[i:i + n])
return(results) | 4f243e50341fffa6a2ad035591b0b7b74c9578dc | 598,814 |
def is_larger_better(metric_name):
"""
Helper method to check whether high or low is better for a metric
:param metric_name:
:return:
"""
if metric_name in ['r2']:
return True
else:
return False | 32edce19aa639e006f1c3f0244dd56a7641db6a3 | 598,816 |
import math
def is_joystick_near_center(x, y, center_x_pos, center_y_pos):
"""
Compare the current joystick position to resting position and decide if it's close enough to be considered "center"
:param x: integer, between 0-1023 indicating position on x-axis
:param y: integer, between 0-1023 indicatin... | 5ac626afeba58332fb3f9f74181f3aedfdd424a6 | 598,817 |
def match_ot(gold_ote_sequence, pred_ote_sequence):
"""
calculate the number of correctly predicted opinion target
:param gold_ote_sequence: gold standard opinion target sequence
:param pred_ote_sequence: predicted opinion target sequence
:return: matched number
"""
n_hit = 0
for t in pr... | 7af349a13348b0110fb2d288dd3128c0f4e8632d | 598,818 |
def dawes_lim(D_o):
"""Calulates the Reosultion of the telescope according to the Dawes Limit
Args:
D_o (float): Diameter of Objective/Aperture (mm)
Returns:
float: Resolving power of the telescope arroding to Dawes Limit (arc-sec)
Note:
This function is generally use... | 8b1570aa678527ea968724facc8c27c8a1be6ae9 | 598,819 |
def _get_ids(file):
""" Read the content of a file
:param file: The file to read the data
:return: Data splitted in separated lines.
"""
with open(file, 'r') as f:
data = f.read()
f.closed
lines = data.splitlines()
return lines | 9cefc0f583ff62c6ed9b10be61e66628d3ffcd34 | 598,821 |
import re
def get_tokens_to_string(s):
""" divides a (potentially) multi-word string into tokens - splitting on whitespace or hyphens
(important for hyphenated names) and lower casing
returns a single joined string of tokens
"""
tokens = [t.lower() for t in re.split(r'[\s-]', s) if t]
re... | 07c7faa06bfdf7aca299689cd4bcaf7e44398dd2 | 598,828 |
def _is_symlink(file_info):
"""
Check the upper 4 bits of the external attribute for a symlink.
See: https://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute
Parameters
----------
file_info : zipfile.ZipInfo
The ZipInfo for a ZipFile
Returns
------... | 2d4fb9bb8cf68f2d671750dd57e65c98a338a073 | 598,831 |
def or_subscription(money):
"""
Display Abo in conferencier sale's table when amount == 0.
"""
if money.amount == 0:
return "Abo*"
else:
return money.amount | 9ba1f3595ee9febbac3f8554c8176014f45c32ea | 598,840 |
def refresh_possibs(
coins_possib: list[float], events_possib: list[float], gen_prob: float
) -> list[float]:
"""List of possibilities to get the current coin next time
Args:
coins_possib (list[float]): list of coins possibilities
events_possib (list[float]): list of getting current side
... | 18ae5a43a2d6f817b79397f46a371affd9c5d482 | 598,841 |
def get_backend_service_outputs(res_name, backend_name, region):
""" Creates outputs for the backend service. """
outputs = [
{
'name': 'name',
'value': backend_name
},
{
'name': 'selfLink',
'value': '$(ref.{}.selfLink)'.format(res_name)
... | 2d9cc49c637489439edfa7d90e8ddb8c49f2193b | 598,844 |
def _get_qualifiers(edge):
""" Retrieve the qualifiers from an edge (empty list if nonexistent or None) """
if "qualifiers" in edge.attributes():
qualifiers = edge["qualifiers"]
if qualifiers is None:
return []
return qualifiers
else:
return [] | 8c28f0f2633436256e3fe8d7246f1a7e8d4d466d | 598,847 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.