content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_user_emails(users):
"""Extracts email addresses from user objects
pre: a list of user object -- users
post: a list of email addressess
"""
emails = []
for user in users:
emails.append(user.email)
return emails | 0731b173119d38453393d64b0fbd45478be99460 | 573,478 |
def AddClusterAutoscalingFlags(parser, update_group=None, hidden=False):
"""Adds autoscaling related flags to parser.
Autoscaling related flags are: --enable-autoscaling
--min-nodes --max-nodes flags.
Args:
parser: A given parser.
update_group: An optional group of mutually exclusive flag options to w... | d4febeef565321f34a974c506ea176785ebe355a | 573,481 |
def get_parent_id(org_client, account_id):
"""
Query deployed AWS organanization for 'account_id. Return the 'Id' of
the parent OrganizationalUnit or 'None'.
"""
parents = org_client.list_parents(ChildId=account_id)['Parents']
try:
len(parents) == 1
return parents[0]['Id']
ex... | 69b42af5989f4672fdbce2c15da5b7290a1465c1 | 573,482 |
def n_eff(n):
"""Return the effective principal quantum number
Args:
n : (int)
Principal quantum number
.. note::
The values are taken from J. A. Pople, D. L. Beveridge,
"Approximate Molecular Orbital Theory", McGraw-Hill, 1970
"""
values = {1: 1.0, 2: 2.0, 3: 3.... | af68cce4a4cf364bab50737d86f9c0814e25b568 | 573,483 |
def remove_newline(s):
"""
Remove a trailing newline from the string, if one exists.
"""
if s.endswith("\n"):
return s[:-1]
return s | 6c7633e7a5d7b591f208fc19c2e1454b72407a7e | 573,484 |
from typing import Tuple
def parse_version(version_string: str) -> Tuple[str, str, str]:
"""
Parse version string into release, major, minor version.
:param version_string: Version string.
:return: Tuple of strings.
"""
release, major, minor = version_string.split(".", 2)
return release, ... | 7f9a0d22b6287a21c7f84d3ec52af7e5e448c1a3 | 573,490 |
def score_substitute(a_c1, a_c2):
"""Score substitution of two characters.
Args:
a_c1 (str): first word to compare
a_c2 (str): second word to compare
Returns:
int: 2 if the last characters of both words are equal, -3 otherwise
"""
return 2 if a_c1[-1] == a_c2[-1] else -3 | 6c329daf5cdc9cfda54523d7322e6e2b92e4d4f7 | 573,495 |
def eff_to_hr(eff):
"""
Convert electric efficiency into heat rate
:param eff: Efficiency value, only 0 to 1
:return: Heat rate as KJ heat/ KWh electricity
"""
assert 0 <= eff <= 1, "Efficiency out of range"
return 3600 / eff | 15db08a56c20bbef4a3262afc1938198014ae8f9 | 573,502 |
import six
def dots_from(braille):
"""Get set dots from given
See https://en.wikipedia.org/wiki/Braille_Patterns#Identifying.2C_naming_and_ordering
for braille to dot decoding.
Parameters:
braille: unicode Braille character in \u2800 - \u28ff
Returns:
List[int]: dots that are s... | 297242519508aaf80de14f3f7baa2006e7663939 | 573,508 |
def find_bounds(f, y):
"""
given a function f,
return lv & hv such that lv <= t(y) <= hv
"""
x = 1
while f(x) < y:
x = x * 2
lv = 0 if x == 1 else x / 2
return lv, x | efb7d1f853f4cb975c4bbed85df6f08795efee7f | 573,512 |
def unique_column_values(rows, column_name):
"""
Given a list of rows and the name of a column (a string), returns a set
containing all values in that column.
"""
column = []
for row in rows:
column.append(row.get(column_name)) #Store the column data for each row and store in the list
... | e4fc3cfaf5401ea381690acf2f479b9b3fb09540 | 573,516 |
def get_lr(optimizer):
"""Returns the optimizer's learning rate, or 0 if not found."""
if optimizer is not None:
for param_group in optimizer.param_groups:
if "lr" in param_group:
return param_group["lr"]
return 0 | 75c73fe5a45ca0504e6686443c88ebde933969d5 | 573,519 |
import ast
def to_attribute(value, attr, ctx=None):
""" Create an Attribute AST node.
"""
return ast.Attribute(value, attr, ctx or ast.Load()) | f4a60f3643938c33a315e6c274ee173e0b303112 | 573,525 |
def operational_commands(fw_conn, cmd):
"""Operational Command
Args:
fw_conn (PanDevice): A panos object for device
cmd (str): [description]
Returns:
xml_output (Element): XML results from firewall
"""
xml_output = fw_conn.op(cmd=cmd, xml=True, cmd_xml=True)
return xml_... | 1b32d5100bc45f7e2edc54557580b8cf702c78e9 | 573,528 |
import re
def remove_argument_quotes(text: str) -> str:
"""Remove single and double outer quotes from text.
"""
if re.match(r'^(\'.*\')|(".*")$', text or ''):
return text[1:-1]
return text | f99d82ba3b4528072db614a6f8409c1d2768744c | 573,530 |
from bs4 import BeautifulSoup
def get_plaintext(html):
"""Scrub out tags and extract plaintext"""
soup = BeautifulSoup(html)
for script in soup(["script", "style"]):
script.extract()
return soup.get_text() | 3e7b13b7f57886bee20816375d53c86f38e3c655 | 573,532 |
def list_check(lista):
"""
If a list has only one element, return that element. Otherwise return the whole list.
"""
try:
e2 = lista[1]
return lista
except IndexError:
return lista[0]
#______________________________________#
# ... | 702c990e4d2af2401ce7ff17c9a30218324d89b9 | 573,536 |
def add_fold_column(fold_test_out, fold_num):
"""Add a column to each df in <fold_test_out> specifying which fold the
prediction was made in"""
epochs_to_consider = list(fold_test_out.keys())
for epochstr in epochs_to_consider:
fold_test_out[epochstr]['FoldNum'] = 'fold_'+str(fold_num)
retur... | 9fb1cda982385884b19e17475caf7d43c9ce8a93 | 573,537 |
from pathlib import Path
def detect_filetype(file):
"""
Detect FoldX filetype from the filenames
"""
file = Path(file).stem
filetype = file.split('_')[0].lower()
if filetype not in ('interface', 'interaction', 'indiv', 'summary'):
raise ValueError('Unknown type detected')
return fi... | 3220a955ccabbb7f7f626efb6bf28891d028dcda | 573,538 |
def disambiguating_filter_from_query_params(query_params: dict[str, str]):
"""
Sometimes wordforms may have the same text (a.k.a., be homographs/homophones),
thus need to be disambiguate further before displaying a paradigm.
This computes the intersection between the provided query parameters and the v... | 7b00242a3624fe3a444779566ae6341033317e9d | 573,539 |
from datetime import datetime
import pytz
def date_string_to_datetime(date_string, fmt='%Y-%m-%d', timezone=None):
"""Return a date object for a string of a given format."""
if isinstance(date_string, datetime):
return date_string
try:
dt = datetime.strptime(date_string, fmt)
except Va... | 0401d611f4ada9dcde632276e40d367b77c17bbb | 573,541 |
def find_coord_vars(ncds):
"""
Finds all coordinate variables in a dataset.
A variable with the same name as a dimension is called a coordinate variable.
"""
coord_vars = []
for d in ncds.dimensions:
if d in ncds.variables and ncds.variables[d].dimensions == (d,):
coord_var... | fd4d33c2785a3cee894ba7420d0d94a0de852c09 | 573,542 |
def synchronized_order(img, target_img,
axes=True,
reference=True):
""" Reorder reference and axes of `img` to match target_img.
Parameters
----------
img : Image
target_img : Image
axes : bool, optional
If True, synchronize the order of the... | a4e1ba72bf06ad56cf394c8459d3e09710ae61ee | 573,543 |
def audio_acquisition(r, mic):
"""Return an input audio from a microphone.
Args:
r: Recognizer instance.
mic: Microphone instance.
Returns:
audio: Audio clip in the SpeechRecognition format.
"""
print("Say something!")
with mic as source:
audio = r.listen(sour... | 58e11c0578c05e377f01e705eb0083efc8030b90 | 573,545 |
def get_provenance_record(ancestor_file):
"""Create a provenance record."""
record = {
'caption': "Forcings for the PCR-GLOBWB hydrological model.",
'domains': ['global'],
'authors': [
'aerts_jerom',
'andela_bouwe',
'alidoost_sarah',
],
... | 0ed9cc5b38150e437d8c1cb589e6e2534686ec85 | 573,547 |
def ping(bot, event, *args):
"""reply to a ping"""
yield from bot.coro_send_message(event.conv, 'pong')
return { "api.response": "pong" } | 9c9c25458e6ccb4e32889defaafc14e03571707d | 573,550 |
import math
def gam_srgb(rgb):
"""
Convert an array of linear-light sRGB values in the range 0.0-1.0 to gamma corrected form.
https://en.wikipedia.org/wiki/SRGB
"""
result = []
for i in rgb:
# Mirror linear nature of algorithm on the negative axis
abs_i = abs(i)
if ab... | d82a88a1c73d3e1fc53e80a4dcf3c809330dd487 | 573,551 |
import io
def load_image_bytes(fname='example.jpg'):
""" Returns a bytes stream representing the image.
Parameters
----------
fname : str
The file name of the image.
Returns
-------
image : bytes
The example image in bytes.
"""
with io.open(fname, 'rb') as image_fil... | 4fd677234bb6a6285bf288267614b6b13bb4c548 | 573,553 |
def pval_to_num_(pval: str) -> float:
"""P-values are reported as strings; convert to numbers for easier processing."""
parts = pval.split(" x 10-")
return float(parts[0]) * pow(10, -float(parts[1])) | d508fc40b491f81e8e133d92a99f246a4d82ddab | 573,554 |
def endswith(s, suffix):
""" True if the string ends with the specified suffix. """
return s.endswith(suffix) | bb24552d5756ed1239b8a0abe06aa5479bed535f | 573,556 |
def cubic_ease_in(p):
"""Modeled after the cubic y = x^3"""
return p * p * p | 386e00834c2f93615593a02264d780724d986ead | 573,558 |
def split_train_test(train, test, target):
"""
(train,test) -> (X_train, X_test, y_train, y_test)
:param target: target column
:param train: training set with features and target
:param test: test set with features and target
"""
return train.drop(target, axis=1), test.drop(target, axis=1), ... | 3c23899efd7c5f0bcb690b6595f8b1eeb6bf8c84 | 573,563 |
def get_hand_value(cards):
"""Returns the value of the cards. Face cards are worth l0, aces are worth 11 or 1
(this function picks the most suitable ace value)."""
value = 0
number_of_aces = 0
# Add the value for the non-ace cards:
for card in cards:
rank = card[0] # card is a tuple li... | 2cd3d6156dff3f5069ad23f66051f90056845117 | 573,564 |
def test_string_content(string):
"""
Detects if string is integer, float or string.
Parameters
----------
string : string
An input string to be tested.
Returns
-------
string
A string with value 'int' if input is an integer,
'float' if the input is a float and '... | 26c21f50b2e09f3f31d6bddb889fd85823986ac2 | 573,565 |
def _encode_plain(uname, pwd):
"""
Encode a username/password pair with the SASL PLAIN mechanism.
"""
# See https://tools.ietf.org/html/rfc4616
return "\0{}\0{}".format(uname, pwd) | 1af9fa0839b9ee2f578558935f57fc027b71af68 | 573,566 |
import textwrap
def dedent(str):
"""Dedent a block of non code."""
str = textwrap.dedent(str)
lines = str.splitlines(True)
for i, line in enumerate(lines):
if line.strip():
lines[i] = textwrap.dedent(line)
break
return "".join(lines) | e7bb5aaa438951aeca7395ed5361f4635b7523cd | 573,567 |
def calc_obs_efficiency(t_exp, t_duration):
"""Calculates the observation efficiency.
Parameters
----------
t_exp : float
Exposure time (in seconds).
t_duration : float
Duration time (in seconds).
Returns
-------
obs_eff : float
Observation efficiency.
"... | b2f378ee212ff8bbb20026a598c7646ab655c6bc | 573,568 |
import socket
def getHostIp(host=None):
"""Return host ip address. If no host is passed, returns the ip address of current host."""
try:
if host is None:
host = socket.gethostname()
return socket.gethostbyname(host)
except Exception as e:
print(("Got exception resolvin... | dc1aaa26b15fa9701453ab6585fae82095a27ce2 | 573,572 |
def choose_colour(wtr: int) -> int:
"""
Choose a colour to represent the wtr
:param wtr: the wtr
:return: a hex integer of the colour
"""
if not wtr or wtr < 300:
return 0x930D0D
elif wtr < 700:
return 0xCD3333
elif wtr < 900:
return 0xCC7A00
elif wtr < 1000:
... | 6eef3b69e4ff8dc653fcf24381cc7bacdaf6f768 | 573,574 |
def IsArgsSpecified(args):
"""Returns true if at least one of the flags for secrets is specified.
Args:
args: Argparse namespace.
Returns:
True if at least one of the flags for secrets is specified.
"""
secrets_flags = {
'--set-secrets', '--update-secrets', '--remove-secrets', '--clear-secrets... | fed7f4fa0a2830eebda1b62423e06c726348c3ac | 573,576 |
def overloaded_lines(net, max_load=100):
"""
Returns the results for all lines with loading_percent > max_load or None, if
there are none.
"""
if net.converged:
return net["res_line"].index[net["res_line"]["loading_percent"] > max_load]
else:
raise UserWarning("The last loadflow ... | 2cc0979a1eac95bcf487b9eb1e60d269f49c3813 | 573,577 |
def count_model_params(model):
""" Counting the number of learnable parameters in a nn.Module """
num_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
return num_params | 3078e066cc381432d84123879b05f6ae26c5643f | 573,578 |
def _get_conv_center(conv_x, conv_y, stride):
"""
Finds the center of this convolution position in the image's original coordinate space.
:param conv_x: non-negative integer, x coordinate of the convolution position.
:param conv_y: non-negative integer, y coordinate of the convolution position.
:par... | ea44d2f67c83dc16139e95e0330541a4f27a67ab | 573,581 |
def parser_network_name_Descriptor(data,i,length,end):
"""\
parser_network_name_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
Parses a descriptor containing the name of the 'network' of which the
multiplex is a part. In the United Kingdom for the Freeview Terrestrial
Servic... | 0c2acc714795e66704085e95ba4ca8123a5a9b88 | 573,583 |
def mk_closest(D, n):
"""Compute a sorted list of the distances for each of the nodes.
For each node, the entry is in the form [(d1,i1), (d2,i2), ...]
where each tuple is a pair (distance,node).
"""
C = []
for i in range(n):
dlist = [(D[i,j], j) for j in range(n) if j != i]
dlis... | fb327dc5eb93d4db8b19eb06c369d5bea7c3b275 | 573,584 |
def split_summation(bucket, value):
"""
Add value into the contents of the bucket.
:param bucket: Summation of all splits that have been stored in this bucket.
:param value: Split object to add to bucket
:return: new bucket value as a decimal.
"""
bucket += value.value
return bucket | cd7b6a21f44423b8dcf99d1c2304d9715e03d457 | 573,586 |
from typing import Callable
from typing import Set
from typing import Optional
import inspect
def _make_extras_import_error(
get_extras_modules: Callable[[], Set[str]],
missing_module_name: str,
) -> Optional[str]:
"""This function implements the most common implementation of a custom error
message wh... | 779a151d0ad89f6898a5ce7853ea59901c79b085 | 573,590 |
def analysis_max(x, y):
"""Maximum of two integers."""
result = max(x, y)
return result | dc01b84bf124f38983fa4cd4d0c9e4b6e8c31e82 | 573,591 |
def is_bicycling_speed(speed):
"""
From http://journals.sagepub.com/doi/pdf/10.1177/1687814015616918,
non motorized bike max speed is 30 km/h = 8.333 m/s
"""
return not speed > 8.5 | 7a23aa84170e4144a85df773f3ec7acb222deb84 | 573,592 |
def partial_map(method, object_seq):
"""
Like map, but filters out all objects with an non-true result, and
returns them in a separate items list. I.e. any item for which the map
resulted in a non-true value is provided in a "reject" list.
:param func method:
The method to perform on each i... | e8d1deffcd75bf01bb00bfdf088bc9500c0407d0 | 573,593 |
from typing import Union
from typing import List
def ref_constructor(loader, node) -> Union[str, List[str]]:
"""
A constructor for !ref yaml tags. These tags describe yaml values that
reference other namespaces within the document, using colons to separate
namespaces. For example:
!ref 'environmen... | 45c8bbe46d1e0eccec73f252f0a653e844afb071 | 573,594 |
def get_n_atoms(traj_file_lines):
"""From the trajectory file lines extract the number of atoms, which should be the first item in the first line"""
try:
return int(traj_file_lines[0].split()[0])
except ValueError:
exit('It looks like the trajectory is malformatted') | fdec1ce51b0983ee13e6b2d9e5cd04b54c116ca2 | 573,596 |
from typing import Dict
def flatten_dict_to_nested_dict(flatten_dict: Dict, sep='.') -> Dict:
"""
Return nested dict from flatten dict.
Parameters
----------
flatten_dict: Dict
sep: str
flatten key separator
Returns
-------
Dict
Nested dict
"""
assert all(... | 76b4718fafb8bd13bc8b54584159887bc0b5ddfb | 573,597 |
def get_prior_unit_cube(cube, priors):
"""
Returns the transformed unit cube for MultiNest.
Parameters
----------
cube : list or numpy.array
Unit cube [0,1]
priors : list of instantiated Prior objects
:class:`Prior` vector
Returns
-------
cube : list or numpy.array
... | 3b66aa8a934d9a7dc846292afd0ea8cf0f4d204e | 573,600 |
def to_address(ptr: int):
"""Convert a ROM pointer to an address."""
if ptr < 0x8000000 or ptr > 0x9FFFFFF:
return -1
return ptr - 0x8000000 | 68b7473893385ba641ec467f7b478409959eca76 | 573,602 |
def arr2text(arr):
""" format a numpy array into a text string """
text = ''
if len(arr.shape) == 1: # vector
text = " ".join(arr.astype(str))
elif len(arr.shape) == 2: # matrix
mat = [arr2text(line) for line in arr]
text = "\n" + "\n".join(mat) + "\n"
else:
raise RuntimeError('arr2text can... | 680162ca71b8fab5591c4fccff8e253e636bffa3 | 573,603 |
import math
def distance(p1, p2):
"""
Simple fonction pour calculer la distance entre deux points
params :
- p1 = Le point 1
- p2 = Le point 2
return -> float = La distance euclidienne entre les deux points
"""
return math.sqrt((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2) | 0aa4345a022a15eaf21b3140c90c3807ca5f1c09 | 573,607 |
def store_decorators(decorators):
"""Sets a list of decorators as the attribute `_decorators` on a
function.
This is for the purpose of applying decorators to a higher-level
wrapping function.
"""
def outer(fn):
fn._decorators = decorators
return fn
return outer | a63df3dfec1cff24ee9e4fd7651284f86459bc1d | 573,609 |
def point_inside_rect(pos, x, y, w, h):
"""
Verifies if a line crosses a rectangle.
:param pos:
:param x:
:param y:
:param w:
:param h:
:return: true if a point is inside a rectangular, false otherwise
"""
if x <= pos.x <= x + w and y <= pos.y <= y + h:
return True
re... | 40c0a29a92d97bccae90e82cc175d55233ba88a4 | 573,614 |
import secrets
def generate_code_verifier(length: int = 128) -> str:
"""Return a random PKCE-compliant code verifier.
Parameters
----------
length : int
Code verifier length. Must verify `43 <= length <= 128`.
Returns
-------
code_verifier : str
Code verifier.
Raises... | 349afa4564f647c127b6f24b20e06597e466b85d | 573,615 |
import yaml
def get_parameter_from_yaml(parameter, yfile):
"""
Returns the value of a given parameter in file.yaml
parameter must be given in string format with dots
Example: general.openstack.image_name
"""
with open(yfile, encoding='utf-8') as yfd:
file_yaml = yaml.safe_load(yfd)
... | 122cc4beaa3d55ce6267fafc402940d4a53061a7 | 573,620 |
def capitalize(s):
"""
Capitalize a string - only first letter
Args:
s (string): The input string to be capitalized.
Returns:
(string): The capitalized string.
"""
return s[0:1].upper() + s[1:] | 937ee3a60a9e7505c5bd999cfb4c78c38205e3c1 | 573,621 |
def dof(params, y):
""" Calculate the number of degrees of freedom """
n = len(y)
k = len(params)
dof = n - k
return dof | c5b05201efd9b5ca91c71e9ec5bbe08ade3f93eb | 573,622 |
import re
def clean_whitespace(text):
"""
Map all ASCII control characters (0x00-0x1F) to spaces, and
remove unnecessary spaces.
"""
text = re.sub("[\000-\040]+", " ", text)
return text.strip() | 0169e8f90e388183aab67c46af3035c1df17de79 | 573,623 |
def symmetric_difference(M: set, N: set) -> set:
"""Find the symmetric difference between sets M and N."""
return M ^ N | e62731141cedc1c9b46e75e9d23301a146c9b327 | 573,625 |
def flatten_delete(replication_record):
"""Creates a flat record for delete, None otherwise."""
if replication_record.action == 'delete':
return {
'node_id': replication_record.key,
'is_delete': True,
'label': replication_record.clazz.label
}
return None | 41b29beb73611c70893e65c02ff631561dfd09f6 | 573,627 |
def add(X, value):
"""Add `value` to all elements of `X`"""
return [[a + value for a in row] for row in X] | ec88f7c88484663f1f38ae8cd658e2ac7c0134e7 | 573,628 |
def parse_contaminants(file):
"""
Parse contamination file.
example:
==============================
Pirisoci Alveolata Higher Taxonomy
DiplDSTH GoniavonGEN Unique ID
Fucucera Ochrophyta Lower Taxonomy
==============================
input: tab separated file with contaminants
resu... | 3133d1a6bc4285044cdb7a52067beca7129b17e5 | 573,629 |
import re
def path_property(path: str):
"""
Extract the property name from a materialized path.
As we traverse the catalog tree, we build a materialized path
to keep track of the parent nodes.
Examples:
stream[0].properties.list_items.properties.account → list_items.account
stream[0... | 3c30917fbe9b7f9121ad1c76a57e46363ffaeedd | 573,630 |
import six
def utf8(string):
"""Convert a Unicode or utf-8 encoded string to a native Python str.
This function's name is misleading: while on Python 2 it really
returns a utf-8-encoded string, on Python 3 it return a native
Unicode Python str.
This function is robust to incorrectly-enco... | aa696782d03fc8e96046e47e8595c007ba446bfe | 573,635 |
import re
def add_or_replace_setting(old_buf, variable, new_value, quote_value=True):
"""
If there is a line setting 'variable' in 'old_buf' (in a "var=value" format),
change it to set variable to new_value. If there is no such line, add a line
to the end of buf setting variable to new_value. Return t... | d1535fe10904b43a5f76f0cf27384e3a37d56073 | 573,636 |
def _get_search_fields(model):
"""
Get search fields from a model
:param model: Model object
:return: Return list of fields otherwise return None
"""
search_fields = []
field_types = ['Slugfield', 'Foreignkey']
fields_names = ['object_id', 'content_object', 'time_created', 'last_update',... | a70d07a0c29413f2848b6e633373367543d5e12f | 573,639 |
def mapkey(client, script, delay=0):
"""Run a Mapkey script in Creo.
Make sure to remove any `mapkey(continued)` clauses from the script
argument. The tilde at the start of a line should occur immediately
after the semicolon at the end of the previous line.
Args:
client (obj):
... | 65ca551acf864935689f6298dc0593ffa5375fbb | 573,653 |
import re
def check_filteraction(option, opt, value): # pylint: disable=W0613
"""Custom parser for filter rule actions.
Takes a string, returns an action as a Python object (list or string).
The string "RATE_LIMIT n" becomes `["RATE_LIMIT", n]`.
All other strings stay as they are.
"""
match = re.match(... | 082b846a976efd26a3662d1e8ddd0d43d4fcdbf7 | 573,654 |
def chain(checks):
""" Chain multiple checks. First error fails, result from last check is returned as data """
def _validate(data):
parsed = data
for check in checks:
parsed, error = check(parsed)
if error != None:
return None, error
return parsed... | 7500675ae543426bfc9c0e8cc4439c97c85a2727 | 573,660 |
def binomial_coeff_recursive(n, k): #This is the author's original version
"""Uses recursion to compute the binomial coefficient "n choose k"
n: number of trials
k: number of successes
returns: int
"""
if k == 0:
return 1
if n == 0:
return 0
res = binomial_coeff_recursive... | 500fadbb5916e7002a194df0cd95320aabe30be4 | 573,663 |
def value_to_message(value, num_bytes):
"""
Converts a integer configuration value to a message compatible byte
(character) format to be appended to set configuration request.
Inputs:
value - Integer value.
num_bytes - The number of bytes to package the integer into.
Outputs:
... | ba9cc1a95f71304d4a1208cc1956a1838a2e313f | 573,665 |
def get_min_hit_end_distance(l1, l2):
"""
Given two lists of kmer hit ends on a sequence (from get_kmer_hit_ends()),
return the minimum distance between two hit ends in the two lists.
In other words, the closest positions in both lists.
>>> l1 = [2,10,20]
>>> l2 = [12,15,30]
>>> get_min_hit... | e8640173d17c432ff59dc0914ee287e95ed0db91 | 573,666 |
def clean_row_author_info(row_author_info):
"""Returns a string of author info stripped of parentheses or numericals"""
clean_row_author_info = ""
for i in range(len(row_author_info)):
undesirable_characters = "()-"
if row_author_info[i].isnumeric() or row_author_info[i] in undesirable_characters:
continue
... | 1b3e930d016bd872ddc9099f6f0a9604d0c58d29 | 573,667 |
def binomial_coef_v3(n, k):
"""Computes the k-th coefficient of n-th degree binomial.
Args:
n (int): The degree of binomial.
k (int): The order of binomial coefficient.
Returns:
(int): The k-th coefficient of n-th degree binomial.
"""
k = min(k, n - k)
table = [1] + [0... | 5a7445471713cddbb5f14881f4242106a70d9789 | 573,670 |
def APMMonthly(data):
"""Requires the open, high, and low values to exist in the provided dataframe >>>'data'.
For plotting, fill functions can be used inbetween the adrlow10+adrlow5 and the adrhigh10+adrhigh5.
Parameters
----------
data : dataframe
A dataframe with the requirement bei... | e7089e7c53a9f52dc5e00c563d205f6ec208a18b | 573,671 |
from typing import List
def map_spatial_axes(
img_ndim: int,
spatial_axes=None,
channel_first=True,
) -> List[int]:
"""
Utility to map the spatial axes to real axes in channel first/last shape.
For example:
If `channel_first` is True, and `img` has 3 spatial dims, map spatial axes to real ... | 295add8fdd9397a2cfc91e9bfc6b8ce07c9cbe52 | 573,674 |
def differentiated_payment(p: float, n: float, i: float, m: int) -> float:
"""
Calculate the differentiated payment for the m-th period
:param p: loan principal value
:param n: number of payments
:param i: monthly nominal interest rate
:param m: current repayment period
:return: amount of th... | 2c8f0b0679943995da6abc7b90ca1a0b45123579 | 573,675 |
def preprocess(resized_inputs):
"""Faster R-CNN Resnet V1 preprocessing.
VGG style channel mean subtraction as described here:
https://gist.github.com/ksimonyan/211839e770f7b538e2d8#file-readme-md
Args:
resized_inputs: A [batch, height_in, width_in, channels] float32 tensor
representing ... | d520a3e777c7bfc46a8e092ca3cf631e0aff738d | 573,676 |
def deleteSpace1(s1):
"""
delete space in String
sample: " abc x y z " => "abc x y z"
"""
sa = (s1.strip()).rsplit()
sres = ""
for i in range(len(sa)):
if i>0:
sres +=' '
sres += sa[i]
return sres | 82e60f2aee7c6a0f2bc12eb8e2e356bbff126da0 | 573,680 |
def is_valid(var, var_type, list_type=None):
"""
Check that the var is of a certain type.
If type is list and list_type is specified,
checks that the list contains list_type.
Parameters
----------
var: any type
Variable to be checked.
var_type: type
Type the variable is... | c343ec3687472c9853fd95d3a116c7b2afff658a | 573,685 |
def _md5_to_filename(md5):
"""
Converts base64 encoded md5 to filename safe base64 encoding. Uneeded
padding is removed and '+' and '/' are replaced with safe alternatives.
"""
return md5[:22].replace('+', '-').replace('/', '_') | 1b6267f37b28bddf718323d7162e2c2f9d64c94b | 573,694 |
def is_valid_w3e(file_path):
"""Checks if a given file is a valid w3e file."""
with open(file_path, "rb") as f:
main_tileset_sig = f.read(4)
main_tileset_sig = str(main_tileset_sig.decode('utf-8'))
if main_tileset_sig == "W3E!":
return True
else:
return False | 0ad58c8a6d7c9b5d16385736e67b9f761d78512f | 573,695 |
def strip_enclosing_quotes(string: str) -> str:
"""Strip leading/trailing whitespace and remove any enclosing quotes"""
stripped = string.strip()
# Need to check double quotes again in case they're nested inside
# single quotes
for quote in ['"', "'", '"']:
if stripped.startswith(quote) and... | 712211d4a2044fd3c610ef7769ef73016c8569b9 | 573,696 |
def arePermsEqualParity(perm0, perm1):
"""Check if 2 permutations are of equal parity.
Assume that both permutation lists are of equal length
and have the same elements. No need to check for these
conditions.
:param perm0: A list.
:param perm1: Another list with same elements.
:return: Tr... | 40e5bb65afaad68c5c188f3ff2b8551b2be4cacb | 573,702 |
def hypind(i, j):
""" Returns a tuple identifier for a hyperplane of ith and jth observation,
regardless of ordering.
"""
if i > j:
return (j, i)
else:
return (i, j) | a9aea9e770430432de1ce86f002e20b865dc7f2b | 573,703 |
from typing import List
def read_hypothesis_file(fname: str) -> List[str]:
"""Reads lines from a text file and returns it as a list of strings."""
lines = []
with open(fname) as f:
for line in f:
lines.append(line.strip())
return lines | 0c1b968d43e58abece4209b4805b2ba6093c7616 | 573,704 |
def _find_install_subgraphs(graph):
"""In the install graph, find subgraphs that install a node instance.
Make a dict of {instance id: subgraph}, based on the subgraph name.
"""
install_subgraphs = {}
for task in graph.tasks:
if task.is_subgraph and task.name.startswith('install_'):
... | b15f2e6ac411817481cf3391dc609b9ec776da73 | 573,706 |
import time
from datetime import datetime
def to_timestampe(x: str, format_string: str):
""" str -> timestamp
Args:
x: ex) 2022010101
format_string: ex) '%Y%m%d%H'
Returns: timestamp
"""
return int(time.mktime(datetime.strptime(x, format_string).timetuple())) | d91b7da1acb25d17097263ececf547d34271cebd | 573,713 |
def safe_get_first(l):
"""Get the first element. Returns None if len == 0
"""
if len(l) > 0:
return l[0]
else:
return None | 79fb0aa06fee49222e405226ec0fd456f112f8ba | 573,717 |
def read_all_words_from_file(source_file):
"""
Function for read all words from source file.
:param source_file: str
File with words.
:return:
List of words.
"""
if not isinstance(source_file, str):
raise TypeError
with open(source_file, 'rb') as f_in:
word... | 8ad8e679f1c1d1efe7797d3a0374a706f2d5327c | 573,721 |
def Get_Better_Correlations(busqueda,df_distance,number_elements=10 ):
""" Return a df with the correlation between a title and the others"""
a=0
df = df_distance.loc[busqueda].to_frame()
df.reset_index(inplace=True)
df.insert(0, 'title1', busqueda)
df.rename(columns={'index': 'title2', }, inpla... | 5f53a16c20c962b79c4f06b345163c07981fd32a | 573,722 |
def max2(x, y):
"""
>>> max2(1, 2)
2
>>> max2(1, -2)
1
>>> max2(10, 10.25)
10.25
>>> max2(10, 9.9)
10.0
>>> max2(0.1, 0.25)
0.25
>>> max2(1, 'a')
Traceback (most recent call last):
...
UnpromotableTypeError: Cannot promote types int and string
"""
... | 3d12353bca7cf73bdd97ca3a9fe79b9b927a716f | 573,724 |
def my_sqrt(x: int) -> int:
"""
:param x: integer
:return: integer - the square root of the input x
"""
return int(x**0.5) | 7b6b743e8cf4f1e8886e0e67f3232858d864c3b9 | 573,728 |
def split(binaryArray):
"""Split binary digits into separate digits"""
return [int(char) for char in binaryArray]; | d2a263f24a5c7cd461d1445b4b2f5914ef12d16a | 573,729 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.