content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def expected_win(theirs, mine):
"""Compute the expected win rate of my strategy given theirs"""
assert abs(theirs.r + theirs.p + theirs.s - 1) < 0.001
assert abs(mine.r + mine.p + mine.s - 1) < 0.001
wins = theirs.r * mine.p + theirs.p * mine.s + theirs.s * mine.r
losses = theirs.r * mine.s + theirs.p * mine.r + theirs.s * mine.p
return wins - losses | 92de2010287e0c027cb18c3dd01d95353e4653c4 | 2,144 |
def SizeArray(input_matrix):
"""
Return the size of an array
"""
nrows=input_matrix.shape[0]
ncolumns=input_matrix.shape[1]
return nrows,ncolumns | 3ac45e126c1fea5a70d9d7b35e967896c5d3be0b | 2,148 |
def preimage_func(f, x):
"""Pre-image a funcation at a set of input points.
Parameters
----------
f : typing.Callable
The function we would like to pre-image. The output type must be hashable.
x : typing.Iterable
Input points we would like to evaluate `f`. `x` must be of a type acceptable by `f`.
Returns
-------
D : dict(object, list(object))
This dictionary maps the output of `f` to the list of `x` values that produce it.
"""
D = {}
for xx in x:
D.setdefault(f(xx), []).append(xx)
return D | 6ca0496aff52cff1ce07e327f845df4735e3266a | 2,152 |
from typing import Dict
def load_extract(context, extract: Dict) -> str:
"""
Upload extract to Google Cloud Storage.
Return GCS file path of uploaded file.
"""
return context.resources.data_lake.upload_df(
folder_name="nwea_map",
file_name=extract["filename"],
df=extract["value"]
) | c9d5fedf6f2adcb871abf4d9cead057b0627267a | 2,153 |
def reverse_index(alist, value):
"""Finding the index of last occurence of an element"""
return len(alist) - alist[-1::-1].index(value) -1 | 21fc4e17a91000085123ea4be42c72cb27a3482c | 2,158 |
def shingles(tokens, n):
"""
Return n-sized shingles from a list of tokens.
>>> assert list(shingles([1, 2, 3, 4], 2)) == [(1, 2), (2, 3), (3, 4)]
"""
return zip(*[tokens[i:-n + i + 1 or None] for i in range(n)]) | 93e8f3828bf4b49397e09cb46565199dcd7a68be | 2,162 |
def prefix_attrs(source, keys, prefix):
"""Rename some of the keys of a dictionary by adding a prefix.
Parameters
----------
source : dict
Source dictionary, for example data attributes.
keys : sequence
Names of keys to prefix.
prefix : str
Prefix to prepend to keys.
Returns
-------
dict
Dictionary of attributes with some keys prefixed.
"""
out = {}
for key, val in source.items():
if key in keys:
out[f"{prefix}{key}"] = val
else:
out[key] = val
return out | e1c8102fddf51cd7af620f9158419bff4b3f0c57 | 2,165 |
def _grep_first_pair_of_parentheses(s):
"""
Return the first matching pair of parentheses in a code string.
INPUT:
A string
OUTPUT:
A substring of the input, namely the part between the first
(outmost) matching pair of parentheses (including the
parentheses).
Parentheses between single or double quotation marks do not
count. If no matching pair of parentheses can be found, a
``SyntaxError`` is raised.
EXAMPLES::
sage: from sage.misc.sageinspect import _grep_first_pair_of_parentheses
sage: code = 'def foo(a="\'):", b=4):\n return'
sage: _grep_first_pair_of_parentheses(code)
'(a="\'):", b=4)'
sage: code = 'def foo(a="%s):", \'b=4):\n return'%("'")
sage: _grep_first_pair_of_parentheses(code)
Traceback (most recent call last):
...
SyntaxError: The given string does not contain balanced parentheses
"""
out = []
single_quote = False
double_quote = False
escaped = False
level = 0
for c in s:
if level>0:
out.append(c)
if c=='(' and not single_quote and not double_quote and not escaped:
level += 1
elif c=='"' and not single_quote and not escaped:
double_quote = not double_quote
elif c=="'" and not double_quote and not escaped:
single_quote = not single_quote
elif c==')' and not single_quote and not double_quote and not escaped:
if level == 1:
return '('+''.join(out)
level -= 1
elif c=="\\" and (single_quote or double_quote):
escaped = not escaped
else:
escaped = False
raise SyntaxError("The given string does not contain balanced parentheses") | 7441c1b8734c211b9b320e195155719452cf7407 | 2,166 |
def find_start_end(grid):
"""
Finds the source and destination block indexes from the list.
Args
grid: <list> the world grid blocks represented as a list of blocks (see Tutorial.pdf)
Returns
start: <int> source block index in the list
end: <int> destination block index in the list
"""
#------------------------------------
#
# Fill and submit this code
#
# return (None, None)
#-------------------------------------
counter = 0
eb_index = None
rb_index = None
air_block=[]
diamond_block=[]
state=[]
for i in grid:
if i =='diamond_block':
diamond_block.append(counter)
if i =='air':
air_block.append(counter)
if i == 'emerald_block':
eb_index = counter
if i == 'redstone_block':
rb_index = counter
state.append(counter)
counter+=1
return (eb_index, rb_index,air_block,diamond_block) | d617af3d6ebf9a2c9f42250214e3fe52d2017170 | 2,169 |
from typing import Optional
import inspect
def find_method_signature(klass, method: str) -> Optional[inspect.Signature]:
"""Look through a class' ancestors and fill out the methods signature.
A class method has a signature. But it might now always be complete. When a parameter is not
annotated, we might want to look through the ancestors and determine the annotation. This is
very useful when you have a base class that has annotations, and child classes that are not.
Examples
--------
>>> class Parent:
...
... def foo(self, x: int) -> int:
... ...
>>> find_method_signature(Parent, 'foo')
<Signature (self, x: int) -> int>
>>> class Child(Parent):
...
... def foo(self, x, y: float) -> str:
... ...
>>> find_method_signature(Child, 'foo')
<Signature (self, x: int, y: float) -> str>
"""
m = getattr(klass, method)
sig = inspect.signature(m)
params = []
for param in sig.parameters.values():
if param.name == "self" or param.annotation is not param.empty:
params.append(param)
continue
for ancestor in inspect.getmro(klass):
try:
ancestor_meth = inspect.signature(getattr(ancestor, m.__name__))
except AttributeError:
break
try:
ancestor_param = ancestor_meth.parameters[param.name]
except KeyError:
break
if ancestor_param.annotation is not param.empty:
param = param.replace(annotation=ancestor_param.annotation)
break
params.append(param)
return_annotation = sig.return_annotation
if return_annotation is inspect._empty:
for ancestor in inspect.getmro(klass):
try:
ancestor_meth = inspect.signature(getattr(ancestor, m.__name__))
except AttributeError:
break
if ancestor_meth.return_annotation is not inspect._empty:
return_annotation = ancestor_meth.return_annotation
break
return sig.replace(parameters=params, return_annotation=return_annotation) | 17d3e7d554720766ca62cb4ad7a66c42f947fc1c | 2,170 |
def split_bits(word : int, amounts : list):
"""
takes in a word and a list of bit amounts and returns
the bits in the word split up. See the doctests for concrete examples
>>> [bin(x) for x in split_bits(0b1001111010000001, [16])]
['0b1001111010000001']
>>> [bin(x) for x in split_bits(0b1001111010000001, [8,8])]
['0b10011110', '0b10000001']
not the whole 16 bits!
>>> [bin(x) for x in split_bits(0b1001111010000001, [8])]
Traceback (most recent call last):
AssertionError: expected to split exactly one word
This is a test splitting MOVE.B (A1),D4
>>> [bin(x) for x in split_bits(0b0001001010000100, [2,2,3,3,3,3])]
['0b0', '0b1', '0b1', '0b10', '0b0', '0b100']
"""
nums = []
pos = 0
for amount in amounts:
# get a group of "amount" 1's
mask = 2**amount - 1
# shift mask to the left so it aligns where the last
# iteration ended off
shift = 16 - amount - pos
mask = mask << shift
# update location in the word
pos += amount
# extract the relavent bits
bits = word & mask
# shift back and insert the list to be returned
nums.append(bits >> shift)
assert pos == 16, 'expected to split exactly one word'
return nums | 556a389bb673af12a8b11d8381914bf56f7e0599 | 2,173 |
def save_network_to_path(interactions, path):
"""Save dataframe to a tab-separated file at path."""
return interactions.to_csv(path, sep='\t', index=False, na_rep=str(None)) | f189c6e8f7791f1f97c32847f03e0cc2e167ae90 | 2,177 |
import re
def is_branch_or_version(string):
"""Tries to figure out if passed argument is branch or version.
Returns 'branch', 'version', or False if deduction failed.
Branch is either 'master' or something like 3.12.x;
version is something like 3.12.5,
optionally followed by letter (3.12.5b) for aplha/beta/gamma...zeta,
optionally followed by release (3.12.5-2).
"""
if string == "master" or re.match("3\.\\d+\.x$", string):
return "branch"
if re.match("3\\.\\d+\\.\\d+[a-z]?(-\\d+)?$", string):
return "version"
return None | 6a5ad7cb7af29b6ce0e39ff86171f0f230929fb3 | 2,180 |
def CONTAINS_INTS_FILTER(arg_value):
"""Only keeps int sequences or int tensors."""
return arg_value.elem_type is int or arg_value.has_int_dtypes() | c4452c5e6bbd9ead32359d8638a6bf1e49b600ba | 2,185 |
def sort_2metals(metals):
"""
Handles iterable or string of 2 metals and returns them
in alphabetical order
Args:
metals (str || iterable): two metal element names
Returns:
(tuple): element names in alphabetical order
"""
# return None's if metals is None
if metals is None:
return None, None
if isinstance(metals, str):
if len(metals) != 4:
raise ValueError('str can only have two elements.')
metal1, metal2 = sorted([metals[:2], metals[2:]])
else:
metal1, metal2 = sorted(metals)
return metal1.title(), metal2.title() | dab922797a6c7b94d6489d8fc4d9c1d99f3ee35c | 2,188 |
from datetime import datetime
def datetime_without_seconds(date: datetime) -> datetime:
"""
Returns given datetime with seconds and microseconds set to 0
"""
return date.replace(second=0, microsecond=0) | de30c7770d84751b555c78e045f37783030d8970 | 2,189 |
import six
def format_ratio(in_str, separator='/'):
""" Convert a string representing a rational value to a decimal value.
Args:
in_str (str): Input string.
separator (str): Separator character used to extract numerator and
denominator, if not found in ``in_str`` whitespace is used.
Returns:
An integer or float value with 2 digits precision or ``in_str`` if
formating has failed.
>>> format_ratio('48000/1')
48000
>>> format_ratio('24000 1000')
24
>>> format_ratio('24000 1001')
23.98
>>> format_ratio('1,77')
'1,77'
>>> format_ratio(1.77)
1.77
"""
if not isinstance(in_str, six.string_types):
return in_str
try:
sep = separator if separator in in_str else ' '
ratio = in_str.split(sep)
if len(ratio) == 2:
ratio = round(float(ratio[0]) / float(ratio[1]), 2)
else:
ratio = float(ratio[0])
if ratio.is_integer():
ratio = int(ratio)
return ratio
except ValueError:
return in_str | 308ec972df6e57e87e24c26e769311d652118aee | 2,190 |
from typing import Any
def get_artist_names(res: dict[str, Any]) -> str:
"""
Retrieves all artist names for a given input to the "album" key of a response.
"""
artists = []
for artist in res["artists"]:
artists.append(artist["name"])
artists_str = ", ".join(artists)
return artists_str | 2913c813e7e6097cb2cb3d3dfb84f831bbc0a6e7 | 2,195 |
from typing import Iterator
from typing import Tuple
from typing import Any
import itertools
def _nonnull_powerset(iterable) -> Iterator[Tuple[Any]]:
"""Returns powerset of iterable, minus the empty set."""
s = list(iterable)
return itertools.chain.from_iterable(
itertools.combinations(s, r) for r in range(1, len(s) + 1)) | ad02ab8ac02004adb54310bc639c6e2d84f19b02 | 2,196 |
def printable_cmd(c):
"""Converts a `list` of `str`s representing a shell command to a printable
`str`."""
return " ".join(map(lambda e: '"' + str(e) + '"', c)) | b5e8a68fc535c186fdbadc8a669ed3dec0da3aee | 2,198 |
def is_compiled_release(data):
"""
Returns whether the data is a compiled release (embedded or linked).
"""
return 'tag' in data and isinstance(data['tag'], list) and 'compiled' in data['tag'] | ea8c8ae4f1ccdedbcc145bd57bde3b6040e5cab5 | 2,202 |
def divisor(baudrate):
"""Calculate the divisor for generating a given baudrate"""
CLOCK_HZ = 50e6
return round(CLOCK_HZ / baudrate) | a09eee716889ee6950f8c5bba0f31cdd2b311ada | 2,204 |
def send(socket, obj, flags=0, protocol=-1):
"""stringify an object, and then send it"""
s = str(obj)
return socket.send_string(s) | a89165565837ad4a984905d5b5fdd73e398b35fd | 2,206 |
def strip_extension(name: str) -> str:
"""
Remove a single extension from a file name, if present.
"""
last_dot = name.rfind(".")
if last_dot > -1:
return name[:last_dot]
else:
return name | 9dc1e3a3c9ad3251aba8a1b61f73de9f79f9a8be | 2,209 |
def remove_arm(frame):
"""
Removes the human arm portion from the image.
"""
##print("Removing arm...")
# Cropping 15 pixels from the bottom.
height, width = frame.shape[:2]
frame = frame[:height - 15, :]
##print("Done!")
return frame | 99b998da87f1aa2eca0a02b67fc5adc411603ee4 | 2,216 |
import re
def valid_account_id(log, account_id):
"""Validate account Id is a 12 digit string"""
if not isinstance(account_id, str):
log.error("supplied account id {} is not a string".format(account_id))
return False
id_re = re.compile(r'^\d{12}$')
if not id_re.match(account_id):
log.error("supplied account id '{}' must be a 12 digit number".format(account_id))
return False
return True | 30f3aa9547f83c4bea53041a4c79ba1242ae4754 | 2,218 |
def is_color_rgb(color):
"""Is a color in a valid RGB format.
Parameters
----------
color : obj
The color object.
Returns
-------
bool
True, if the color object is in RGB format.
False, otherwise.
Examples
--------
>>> color = (255, 0, 0)
>>> is_color_rgb(color)
True
>>> color = (1.0, 0.0, 0.0)
>>> is_color_rgb(color)
True
>>> color = (1.0, 0, 0)
>>> is_color_rgb(color)
False
>>> color = (255, 0.0, 0.0)
>>> is_color_rgb(color)
False
>>> color = (256, 0, 0)
>>> is_color_rgb(color)
False
"""
if isinstance(color, (tuple, list)):
if len(color) == 3:
if all(isinstance(c, float) for c in color):
if all(c >= 0.0 and c <= 1.0 for c in color):
return True
elif all(isinstance(c, int) for c in color):
if all(c >= 0 and c <= 255 for c in color):
return True
return False | 46b8241d26fa19e4372587ffebda3690972c3395 | 2,220 |
import ipaddress
import logging
def _get_ip_block(ip_block_str):
""" Convert string into ipaddress.ip_network. Support both IPv4 or IPv6
addresses.
Args:
ip_block_str(string): network address, e.g. "192.168.0.0/24".
Returns:
ip_block(ipaddress.ip_network)
"""
try:
ip_block = ipaddress.ip_network(ip_block_str)
except ValueError:
logging.error("Invalid IP block format: %s", ip_block_str)
return None
return ip_block | b887c615091926ed7ebbbef8870e247348e2aa27 | 2,229 |
def mul_ntt(f_ntt, g_ntt, q):
"""Multiplication of two polynomials (coefficient representation)."""
assert len(f_ntt) == len(g_ntt)
deg = len(f_ntt)
return [(f_ntt[i] * g_ntt[i]) % q for i in range(deg)] | 504838bb812792b6bb83b1d485e4fb3221dec36e | 2,230 |
from datetime import datetime
def parse_date(datestr):
""" Given a date in xport format, return Python date. """
return datetime.strptime(datestr, "%d%b%y:%H:%M:%S") | b802a528418a24300aeba3e33e9df8a268f0a27b | 2,235 |
def get_num_forces(cgmodel):
"""
Given a CGModel() class object, this function determines how many forces we are including when evaluating the energy.
:param cgmodel: CGModel() class object
:type cgmodel: class
:returns:
- total_forces (int) - Number of forces in the coarse grained model
:Example:
>>> from foldamers.cg_model.cgmodel import CGModel
>>> cgmodel = CGModel()
>>> total_number_forces = get_num_forces(cgmodel)
"""
total_forces = 0
if cgmodel.include_bond_forces:
total_forces = total_forces + 1
if cgmodel.include_nonbonded_forces:
total_forces = total_forces + 1
if cgmodel.include_bond_angle_forces:
total_forces = total_forces + 1
if cgmodel.include_torsion_forces:
total_forces = total_forces + 1
return total_forces | 5f5b897f1b0def0b858ca82319f9eebfcf75454a | 2,236 |
def _passthrough_zotero_data(zotero_data):
"""
Address known issues with Zotero metadata.
Assumes zotero data should contain a single bibliographic record.
"""
if not isinstance(zotero_data, list):
raise ValueError('_passthrough_zotero_data: zotero_data should be a list')
if len(zotero_data) > 1:
# Sometimes translation-server creates multiple data items for a single record.
# If so, keep only the parent item, and remove child items (such as notes).
# https://github.com/zotero/translation-server/issues/67
zotero_data = zotero_data[:1]
return zotero_data | cec2271a7a966b77e2d380686ecccc0307f78116 | 2,240 |
def ignore_ip_addresses_rule_generator(ignore_ip_addresses):
"""
generate tshark rule to ignore ip addresses
Args:
ignore_ip_addresses: list of ip addresses
Returns:
rule string
"""
rules = []
for ip_address in ignore_ip_addresses:
rules.append("-Y ip.dst != {0}".format(ip_address))
return rules | 3ac43f28a4c8610d4350d0698d93675572d6ba44 | 2,242 |
from typing import Optional
from typing import Tuple
import crypt
def get_password_hash(password: str, salt: Optional[str] = None) -> Tuple[str, str]:
"""Get user password hash."""
salt = salt or crypt.mksalt(crypt.METHOD_SHA256)
return salt, crypt.crypt(password, salt) | ea3d7e0d8c65e23e40660b8921aa872dc9e2f53c | 2,251 |
def _summary(function):
"""
Derive summary information from a function's docstring or name. The summary is the first
sentence of the docstring, ending in a period, or if no dostring is present, the
function's name capitalized.
"""
if not function.__doc__:
return f"{function.__name__.capitalize()}."
result = []
for word in function.__doc__.split():
result.append(word)
if word.endswith("."):
break
return " ".join(result) | a3e3e45c3004e135c2810a5ec009aa78ef7e7a04 | 2,261 |
def remove_namespace(tag, ns):
"""Remove namespace from xml tag."""
for n in ns.values():
tag = tag.replace('{' + n + '}', '')
return tag | d4837a3d906baf8e439806ccfea76284e8fd9b87 | 2,266 |
def is_unique(x):
# A set cannot contain any duplicate, so we just check that the length of the list is the same as the length of the corresponding set
"""Check that the given list x has no duplicate
Returns:
boolean: tells if there are only unique values or not
Args:
x (list): elements to be compared
"""
return len(x) == len(set(x)) | 12b4513a71fc1b423366de3f48dd9e21db79e73a | 2,268 |
def number_field_choices(field):
"""
Given a field, returns the number of choices.
"""
try:
return len(field.get_flat_choices())
except AttributeError:
return 0 | b8776e813e9eb7471a480df9d6e49bfeb48a0eb6 | 2,276 |
def resize_image(image, size):
"""
Resize the image to fit in the specified size.
:param image: Original image.
:param size: Tuple of (width, height).
:return: Resized image.
:rtype: :py:class: `~PIL.Image.Image`
"""
image.thumbnail(size)
return image | 67db04eac8a92d27ebd3ec46c4946b7662f9c03f | 2,277 |
def price_sensitivity(results):
"""
Calculate the price sensitivity of a strategy
results
results dataframe or any dataframe with the columns
open, high, low, close, profit
returns
the percentage of returns sensitive to open price
Note
-----
Price sensitivity is calculated by
1) Calculating the profit in cases where open=high and open=low
2) Dividing these profits by the total profits
A high percentage indicates that most of your orders may not get
executed at the LIMIT price since the stock tends have a sharp
movement when open=low or open=high. A value of 1 indicates that
all returns are sensitive to prices
This is somewhat a rough measure and it doesn't take into account
whether you BUY or SELL
"""
profit = results["profit"].sum()
sen1 = results.query("open==low")["profit"].sum()
sen2 = results.query("open==high")["profit"].sum()
return (sen1 + sen2) / profit | 02ab811bf689e760e011db6d091dcb7c3079f0d1 | 2,282 |
import torch
def biband_mask(n: int, kernel_size: int, device: torch.device, v=-1e9):
"""compute mask for local attention with kernel size.
Args:
n (torch.Tensor): the input length.
kernel_size (int): The local attention kernel size.
device (torch.device): transformer mask to the device.
Returns: torch.Tensor. shape: [n,n]. The masked locations are -1e9
and unmasked locations are 0.
"""
if kernel_size is None:
return None
half = kernel_size // 2
mask1 = torch.ones(n, n).triu(diagonal=-half)
mask2 = torch.ones(n, n).tril(diagonal=half)
mask = mask1 * mask2
mask = (1 - mask) * v
return mask.to(device) | ab3a5f25f9fe0f83579d0492caa2913a13daa2d7 | 2,285 |
def str_cell(cell):
"""Get a nice string of given Cell statistics."""
result = f"-----Cell ({cell.x}, {cell.y})-----\n"
result += f"sugar: {cell.sugar}\n"
result += f"max sugar: {cell.capacity}\n"
result += f"height/level: {cell.level}\n"
result += f"Occupied by Agent {cell.agent.id if cell.agent else None}\n"
return result | d62801290321d5d2b8404dbe6243f2f0ae03ecef | 2,290 |
def get_reachable_nodes(node):
"""
returns a list with all the nodes from the tree with root *node*
"""
ret = []
stack = [node]
while len(stack) > 0:
cur = stack.pop()
ret.append(cur)
for c in cur.get_children():
stack.append(c)
return ret | c9ffaca113a5f85484433f214015bf93eea602d1 | 2,291 |
def f(i):
"""Add 2 to a value
Args:
i ([int]): integer value
Returns:
[int]: integer value
"""
return i + 2 | 72b5d99f3b2132054805ab56872cf2199b425b20 | 2,293 |
def estimate_label_width(labels):
"""
Given a list of labels, estimate the width in pixels
and return in a format accepted by CSS.
Necessarily an approximation, since the font is unknown
and is usually proportionally spaced.
"""
max_length = max([len(l) for l in labels])
return "{0}px".format(max(60,int(max_length*7.5))) | 1e22ad939973373a669841dd5cc318d6927249ca | 2,299 |
def count_num_peps(filename):
"""
Count the number of peptide sequences in FASTA file.
"""
with open(filename) as f:
counter = 0
for line in f:
if line.startswith(">"):
counter += 1
return counter | c062a22cd925f29d8793ab364a74cf05cbae2a66 | 2,300 |
def _stored_data_paths(wf, name, serializer):
"""Return list of paths created when storing data"""
metadata = wf.datafile(".{}.alfred-workflow".format(name))
datapath = wf.datafile(name + "." + serializer)
return [metadata, datapath] | 5f01d804db9f1848cc13e701a56e51c06dccdb31 | 2,302 |
import re
def get_number_location(
input : str,
):
# endregion get_number_location header
# region get_number_location docs
"""
get the string indices of all numbers that occur on the string
format example: [ ( 0, 1 ), ( 4, 6 ), ( 9, 9 ) ]
both begin and end are inclusive, in contrast with the way the std_lib does it
which is begin(inclusive), end(exclusive)
"""
# endregion get_number_location docs
# region get_number_location implementation
locations = []
for match in re.finditer("\d+", input):
# match start is inclusive
position_start = match.start()
# match end is exclusive
position_end = match.end() - 1
locations.append((position_start, position_end))
...
return locations | de035f640dd33dc96b4072bdc925efc649285121 | 2,304 |
import re
def is_valid_slug(slug):
"""Returns true iff slug is valid."""
VALID_SLUG_RE = re.compile(r"^[a-z0-9\-]+$")
return VALID_SLUG_RE.match(slug) | 439349f0689cd53fb2f7e89b2b48b90aa79dae80 | 2,305 |
def note_favorite(note):
"""
get the status of the note as a favorite
returns True if the note is marked as a favorite
False otherwise
"""
if 'favorite' in note:
return note['favorite']
return False | 503f4e3abaab9d759070c725cdf783d62d7c05d2 | 2,310 |
def get_source_fields(client, source_table):
"""
Gets column names of a table in bigquery
:param client: BigQuery client
:param source_table: fully qualified table name.
returns as a list of column names.
"""
return [f'{field.name}' for field in client.get_table(source_table).schema] | abc161f252c03647a99a6d2151c00288b176a4e7 | 2,312 |
def select_id_from_scores_dic(id1, id2, sc_dic,
get_worse=False,
rev_filter=False):
"""
Based on ID to score mapping, return better (or worse) scoring ID.
>>> id1 = "id1"
>>> id2 = "id2"
>>> id3 = "id3"
>>> sc_dic = {'id1' : 5, 'id2': 3, 'id3': 3}
>>> select_id_from_scores_dic(id1, id2, sc_dic)
'id1'
>>> select_id_from_scores_dic(id1, id2, sc_dic, get_worse=True)
'id2'
>>> select_id_from_scores_dic(id1, id2, sc_dic, rev_filter=True, get_worse=True)
'id1'
>>> select_id_from_scores_dic(id1, id2, sc_dic, rev_filter=True)
'id2'
>>> select_id_from_scores_dic(id2, id3, sc_dic)
False
"""
sc_id1 = sc_dic[id1]
sc_id2 = sc_dic[id2]
if sc_id1 > sc_id2:
if rev_filter:
if get_worse:
return id1
else:
return id2
else:
if get_worse:
return id2
else:
return id1
elif sc_id1 < sc_id2:
if rev_filter:
if get_worse:
return id2
else:
return id1
else:
if get_worse:
return id1
else:
return id2
else:
return False | f2fa5f33eead47288c92715ce358581a72f18361 | 2,317 |
def add_args(parser):
"""Add arguments to the argparse.ArgumentParser
Args:
parser: argparse.ArgumentParser
Returns:
parser: a parser added with args
"""
# Training settings
parser.add_argument(
"--task",
type=str,
default="train",
metavar="T",
help="the type of task: train or denoise",
)
parser.add_argument(
"--datadir",
type=str,
metavar="DD",
help="data directory for training",
)
parser.add_argument(
"--noisy_wav",
type=str,
metavar="NW",
help="path to noisy wav",
)
parser.add_argument(
"--denoised_wav",
type=str,
default="denoised_sample.wav",
metavar="DW",
help="path to denoised wav",
)
parser.add_argument(
"--pretrained",
type=str,
default=None,
metavar="PT",
help="path to pre-trainedmodel",
)
parser.add_argument(
"--saved_model_path",
type=str,
default="model.pth",
metavar="SMP",
help="path to trained model",
)
parser.add_argument(
"--partition_ratio",
type=float,
default=1 / 3,
metavar="PR",
help="partition ratio for trainig (default: 1/3)",
)
parser.add_argument(
"--batch_size",
type=int,
default=5,
metavar="BS",
help="input batch size for training (default: 5)",
)
parser.add_argument(
"--lr",
type=float,
default=0.001,
metavar="LR",
help="learning rate (default: 0.3)",
)
parser.add_argument(
"--momentum",
type=float,
default=0.9,
metavar="M",
help="momentum (default: 0.9)",
)
parser.add_argument(
"--noise_amp",
type=float,
default=0.01,
metavar="NA",
help="amplitude of added noise for trainign (default: 0.01)",
)
parser.add_argument(
"--split_sec",
type=float,
default=1.0,
metavar="SS",
help="interval for splitting [sec]",
)
parser.add_argument(
"--epochs",
type=int,
default=5,
metavar="EP",
help="how many epochs will be trained",
)
parser.add_argument(
"--sampling_rate",
type=int,
default=16000,
metavar="SR",
help="sampling rate",
)
parser.add_argument(
"--log_interval",
type=int,
default=2,
metavar="LI",
help="log interval",
)
parser.add_argument(
"--path_to_loss",
type=str,
default=None,
metavar="PL",
help="path to png filw which shows the transtion of loss",
)
return parser | cfebbfb6e9821290efdc96aaf0f7a7470e927c70 | 2,318 |
from typing import List
from typing import Dict
from typing import Any
def assert_typing(
input_text_word_predictions: List[Dict[str, Any]]
) -> List[Dict[str, str]]:
"""
this is only to ensure correct typing, it does not actually change anything
Args:
input_text_word_predictions: e.g. [
{"char_start": 0, "char_end": 7, "token": "example", "tag": "O"},
..
]
Returns:
input_text_word_predictions_str: e.g. [
{"char_start": "0", "char_end": "7", "token": "example", "tag": "O"},
..
]
"""
return [
{k: str(v) for k, v in input_text_word_prediction.items()}
for input_text_word_prediction in input_text_word_predictions
] | 0835bad510241eeb2ee1f69ac8abeca711ebbf53 | 2,323 |
import re
def expand_parameters(host, params):
"""Expand parameters in hostname.
Examples:
* "target{N}" => "target1"
* "{host}.{domain} => "host01.example.com"
"""
pattern = r"\{(.*?)\}"
def repl(match):
param_name = match.group(1)
return params[param_name]
return re.sub(pattern, repl, host) | 04f62924fdc77b02f3a393e5cc0c5382d1d4279a | 2,332 |
import re
def _skip_comments_and_whitespace(lines, idx):
###############################################################################
"""
Starting at idx, return next valid idx of lines that contains real data
"""
if (idx == len(lines)):
return idx
comment_re = re.compile(r'^[#!]')
lines_slice = lines[idx:]
for line in lines_slice:
line = line.strip()
if (comment_re.match(line) is not None or line == ""):
idx += 1
else:
return idx
return idx | b2b794681859eaa22dfc1807211bf050423cd107 | 2,333 |
def named_payload(name, parser_fn):
"""Wraps a parser result in a dictionary under given name."""
return lambda obj: {name: parser_fn(obj)} | 259525b93d056e045b0f8d5355d4028d67bfac45 | 2,334 |
def _4_graphlet_contains_3star(adj_mat):
"""Check if a given graphlet of size 4 contains a 3-star"""
return (4 in [a.sum() for a in adj_mat]) | 307f03707d1a7032df0ccb4f7951eec0c75832fe | 2,339 |
def get_sentence_content(sentence_token):
"""Extrac sentence string from list of token in present in sentence
Args:
sentence_token (tuple): contains length of sentence and list of all the token in sentence
Returns:
str: setence string
"""
sentence_content = ''
for word in sentence_token[1]:
sentence_content += word.text
return sentence_content | 4f6f1bb557bb508e823704fc645c2901e5f8f03f | 2,340 |
def option_not_exist_msg(option_name, existing_options):
""" Someone is referencing an option that is not available in the current package
options
"""
result = ["'options.%s' doesn't exist" % option_name]
result.append("Possible options are %s" % existing_options or "none")
return "\n".join(result) | 7ffa0afa81483d78a1ed0d40d68831e09710b7e1 | 2,343 |
def string_unquote(value: str):
"""
Method to unquote a string
Args:
value: the value to unquote
Returns:
unquoted string
"""
if not isinstance(value, str):
return value
return value.replace('"', "").replace("'", "") | e062c012fc43f9b41a224f168de31732d885b21f | 2,347 |
import configparser
def read_section(section, fname):
"""Read the specified section of an .ini file."""
conf = configparser.ConfigParser()
conf.read(fname)
val = {}
try:
val = dict((v, k) for v, k in conf.items(section))
return val
except configparser.NoSectionError:
return None | 65d6b81b45fc7b75505dd6ee4dda19d13ebf7095 | 2,351 |
def _helper_fit_partition(self, pnum, endog, exog, fit_kwds,
init_kwds_e={}):
"""handles the model fitting for each machine. NOTE: this
is primarily handled outside of DistributedModel because
joblib cannot handle class methods.
Parameters
----------
self : DistributedModel class instance
An instance of DistributedModel.
pnum : scalar
index of current partition.
endog : array_like
endogenous data for current partition.
exog : array_like
exogenous data for current partition.
fit_kwds : dict-like
Keywords needed for the model fitting.
init_kwds_e : dict-like
Additional init_kwds to add for each partition.
Returns
-------
estimation_method result. For the default,
_est_regularized_debiased, a tuple.
"""
temp_init_kwds = self.init_kwds.copy()
temp_init_kwds.update(init_kwds_e)
model = self.model_class(endog, exog, **temp_init_kwds)
results = self.estimation_method(model, pnum, self.partitions,
fit_kwds=fit_kwds,
**self.estimation_kwds)
return results | 30b7e6d48c2f0fa3eb2d2486fee9a87dad609886 | 2,352 |
def get_users(metadata):
"""
Pull users, handles hidden user errors
Parameters:
metadata: sheet of metadata from mwclient
Returns:
the list of users
"""
users = []
for rev in metadata:
try:
users.append(rev["user"])
except (KeyError):
users.append(None)
return users | 48dbae6a63019b0e4c2236a97e147102fe4d8758 | 2,354 |
def str_to_size(size_str):
"""
Receives a human size (i.e. 10GB) and converts to an integer size in
mebibytes.
Args:
size_str (str): human size to be converted to integer
Returns:
int: formatted size in mebibytes
Raises:
ValueError: in case size provided in invalid
"""
if size_str is None:
return None
# no unit: assume mebibytes as default and convert directly
if size_str.isnumeric():
return int(size_str)
size_str = size_str.upper()
# check if size is non-negative number
if size_str.startswith('-'):
raise ValueError(
'Invalid size format: {}'.format(size_str)) from None
# decimal units are converted to bytes and then to mebibytes
dec_units = ('KB', 'MB', 'GB', 'TB')
for index, unit in enumerate(dec_units):
# unit used is different: try next
if not size_str.endswith(unit):
continue
try:
size_int = int(size_str[:-2]) * pow(1000, index+1)
except ValueError:
raise ValueError(
'Invalid size format: {}'.format(size_str)) from None
# result is returned in mebibytes
return int(size_int / pow(1024, 2))
# binary units are just divided/multipled by powers of 2
bin_units = ('KIB', 'MIB', 'GIB', 'TIB')
for index, unit in enumerate(bin_units):
# unit used is different: try next
if not size_str.endswith(unit):
continue
try:
size_int = int(int(size_str[:-3]) * pow(1024, index-1))
except ValueError:
raise ValueError(
'Invalid size format: {}'.format(size_str)) from None
return size_int
raise ValueError(
'Invalid size format: {}'.format(size_str)) from None | 0051b7cf55d295a4fffcc41ed5b0d900243ef2da | 2,362 |
def decay_value(base_value, decay_rate, decay_steps, step):
""" decay base_value by decay_rate every decay_steps
:param base_value:
:param decay_rate:
:param decay_steps:
:param step:
:return: decayed value
"""
return base_value*decay_rate**(step/decay_steps) | c593f5e46d7687fbdf9760eb10be06dca3fb6f7b | 2,366 |
def crc16(data):
"""CRC-16-CCITT computation with LSB-first and inversion."""
crc = 0xffff
for byte in data:
crc ^= byte
for bits in range(8):
if crc & 1:
crc = (crc >> 1) ^ 0x8408
else:
crc >>= 1
return crc ^ 0xffff | 2560f53c1f2b597d556a0b63462ef56f0c972db2 | 2,371 |
def _read_dino_waterlvl_metadata(f, line):
"""read dino waterlevel metadata
Parameters
----------
f : text wrapper
line : str
line with meta dictionary keys
meta_dic : dict (optional)
dictionary with metadata
Returns
-------
meta : dict
dictionary with metadata
"""
meta_keys = line.strip().split(",")
meta_values = f.readline().strip().split(",")
meta = {}
for key, value in zip(meta_keys, meta_values):
key = key.strip()
if key in ["X-coordinaat", "Y-coordinaat"]:
if key == "X-coordinaat":
meta["x"] = float(value)
elif key == "Y-coordinaat":
meta["y"] = float(value)
elif key == "Locatie":
meta["locatie"] = value
meta["name"] = value
return meta | 949535f4fc677a7d0afc70a76e377ccefcc8943f | 2,372 |
def reverse(array):
"""Return `array` in reverse order.
Args:
array (list|string): Object to process.
Returns:
list|string: Reverse of object.
Example:
>>> reverse([1, 2, 3, 4])
[4, 3, 2, 1]
.. versionadded:: 2.2.0
"""
# NOTE: Using this method to reverse object since it works for both lists
# and strings.
return array[::-1] | 5eb096d043d051d4456e08fae91fb52048686992 | 2,375 |
def help_text_metadata(label=None, description=None, example=None):
"""
Standard interface to help specify the required metadata fields for helptext to
work correctly for a model.
:param str label: Alternative name for the model.
:param str description: Long description of the model.
:param example: A concrete example usage of the model.
:return dict: Dictionary of the help text metadata
"""
return {
'label': label,
'description': description,
'example': example
} | a1fb9c9a9419fe7ce60ed77bc6fadc97ed4523f8 | 2,376 |
def _maven_artifact(
group,
artifact,
version,
ownership_tag = None,
packaging = None,
classifier = None,
exclusions = None,
neverlink = None,
testonly = None,
tags = None,
flatten_transitive_deps = None,
aliases = None):
"""Defines maven artifact by coordinates.
Args:
group: The Maven artifact coordinate group name (ex: "com.google.guava").
artifact: The Maven artifact coordinate artifact name (ex: "guava").
version: The Maven artifact coordinate version name (ex: "1.20.1").
ownership_tag: 3rd party dependency owner responsible for its maintenance.
packaging:The Maven artifact coordinate packaging name (ex: "jar").
classifier: The Maven artifact coordinate classifier name (ex: "jdk11").
exclusions: Artifact dependencies to be excluded from resolution closure.
neverlink: neverlink value to set,
testonly: testonly value to set.
tags: Target tags.
flatten_transitive_deps: Define all transitive deps as direct deps.
aliases: aliases that will point to this dep.
"""
maven_artifact = {}
maven_artifact["group"] = group
maven_artifact["artifact"] = artifact
maven_artifact["version"] = version
maven_artifact["aliases"] = aliases
maven_artifact["tags"] = tags
maven_artifact["flatten_transitive_deps"] = flatten_transitive_deps
if packaging != None:
maven_artifact["packaging"] = packaging
if classifier != None:
maven_artifact["classifier"] = classifier
if exclusions != None:
maven_artifact["exclusions"] = exclusions
if neverlink != None:
maven_artifact["neverlink"] = neverlink
if testonly != None:
maven_artifact["testonly"] = testonly
if ownership_tag != None:
maven_artifact["ownership_tag"] = ownership_tag
return maven_artifact | 9f97cd8cadfc3ad1365cb6d291634a9362fea4e8 | 2,378 |
from typing import List
def get_povm_object_names() -> List[str]:
"""Return the list of valid povm-related object names.
Returns
-------
List[str]
the list of valid povm-related object names.
"""
names = ["pure_state_vectors", "matrices", "vectors", "povm"]
return names | cb80899b9b3a4aca4bfa1388c6ec9c61c59978a4 | 2,383 |
def get_dotted_field(input_dict: dict, accessor_string: str) -> dict:
"""Gets data from a dictionary using a dotted accessor-string.
Parameters
----------
input_dict : dict
A nested dictionary.
accessor_string : str
The value in the nested dict.
Returns
-------
dict
Data from the dictionary.
"""
current_data = input_dict
for chunk in accessor_string.split("."):
current_data = current_data.get(chunk, {})
return current_data | 2c82c0512384810e77a5fb53c73f67d2055dc98e | 2,384 |
def _format_param(name, optimizer, param):
"""Return correctly formatted lr/momentum for each param group."""
if isinstance(param, (list, tuple)):
if len(param) != len(optimizer.param_groups):
raise ValueError("expected {} values for {}, got {}".format(
len(optimizer.param_groups), name, len(param)))
return param
else:
return [param] * len(optimizer.param_groups) | 52904bdfb1cba7fe3175606bf77f5e46b3c7df80 | 2,387 |
def operating_cf(cf_df):
"""Checks if the latest reported OCF (Cashflow) is positive.
Explanation of OCF: https://www.investopedia.com/terms/o/operatingcashflow.asp
cf_df = Cashflow Statement of the specified company
"""
cf = cf_df.iloc[cf_df.index.get_loc("Total Cash From Operating Activities"),0]
if (cf > 0):
return True
else:
return False | ed6a849fa504b79cd65c656d9a1318aaaeed52bf | 2,390 |
def _is_json_mimetype(mimetype):
"""Returns 'True' if a given mimetype implies JSON data."""
return any(
[
mimetype == "application/json",
mimetype.startswith("application/") and mimetype.endswith("+json"),
]
) | 9c2580ff4a783d9f79d6f6cac41befb516c52e9f | 2,396 |
from datetime import datetime
def make_request(action, data, token):
"""Make request based on passed arguments and timestamp."""
return {
'action': action,
'time': datetime.now().timestamp(),
'data': data,
'token': token
} | 60e511f7b067595bd698421adaafe37bbf8e59e1 | 2,397 |
def get_unique_chemical_names(reagents):
"""Get the unique chemical species names in a list of reagents.
The concentrations of these species define the vector space in which we sample possible experiments
:param reagents: a list of perovskitereagent objects
:return: a list of the unique chemical names in all of the reagent
"""
chemical_species = set()
if isinstance(reagents, dict):
reagents = [v for v in reagents.values()]
for reagent in reagents:
chemical_species.update(reagent.chemicals)
return sorted(list(chemical_species)) | ae5d6b3bdd8e03c47b9c19c900760c8c2b83d0a0 | 2,399 |
def max_votes(x):
"""
Return the maximum occurrence of predicted class.
Notes
-----
If number of class 0 prediction is equal to number of class 1 predictions, NO_VOTE will be returned.
E.g.
Num_preds_0 = 25,
Num_preds_1 = 25,
Num_preds_NO_VOTE = 0,
returned vote : "NO_VOTE".
"""
if x['Num_preds_0'] > x['Num_preds_1'] and x['Num_preds_0'] > x['Num_preds_NO_VOTE']:
return 0
elif x['Num_preds_1'] > x['Num_preds_0'] and x['Num_preds_1'] > x['Num_preds_NO_VOTE']:
return 1
else:
return 'NO_VOTE' | 2eadafdaf9e9b4584cd81685a5c1b77a090e4f1c | 2,401 |
def _get_log_time_scale(units):
"""Retrieves the ``log10()`` of the scale factor for a given time unit.
Args:
units (str): String specifying the units
(one of ``'fs'``, ``'ps'``, ``'ns'``, ``'us'``, ``'ms'``, ``'sec'``).
Returns:
The ``log10()`` of the scale factor for the time unit.
"""
scale = {"fs": -15, "ps": -12, "ns": -9, "us": -6, "ms": -3, "sec": 0}
units_lwr = units.lower()
if units_lwr not in scale:
raise ValueError(f"Invalid unit ({units}) provided")
else:
return scale[units_lwr] | 2371aab923aacce9159bce6ea1470ed49ef2c72f | 2,404 |
from typing import Dict
from typing import Any
from typing import Tuple
def verify_block_arguments(
net_part: str,
block: Dict[str, Any],
num_block: int,
) -> Tuple[int, int]:
"""Verify block arguments are valid.
Args:
net_part: Network part, either 'encoder' or 'decoder'.
block: Block parameters.
num_block: Block ID.
Return:
block_io: Input and output dimension of the block.
"""
block_type = block.get("type")
if block_type is None:
raise ValueError(
"Block %d in %s doesn't a type assigned.", (num_block, net_part)
)
if block_type == "transformer":
arguments = {"d_hidden", "d_ff", "heads"}
elif block_type == "conformer":
arguments = {
"d_hidden",
"d_ff",
"heads",
"macaron_style",
"use_conv_mod",
}
if block.get("use_conv_mod", None) is True and "conv_mod_kernel" not in block:
raise ValueError(
"Block %d: 'use_conv_mod' is True but "
" 'conv_mod_kernel' is not specified" % num_block
)
elif block_type == "causal-conv1d":
arguments = {"idim", "odim", "kernel_size"}
if net_part == "encoder":
raise ValueError("Encoder does not support 'causal-conv1d.'")
elif block_type == "conv1d":
arguments = {"idim", "odim", "kernel_size"}
if net_part == "decoder":
raise ValueError("Decoder does not support 'conv1d.'")
else:
raise NotImplementedError(
"Wrong type. Currently supported: "
"causal-conv1d, conformer, conv-nd or transformer."
)
if not arguments.issubset(block):
raise ValueError(
"%s in %s in position %d: Expected block arguments : %s."
" See tutorial page for more information."
% (block_type, net_part, num_block, arguments)
)
if block_type in ("transformer", "conformer"):
block_io = (block["d_hidden"], block["d_hidden"])
else:
block_io = (block["idim"], block["odim"])
return block_io | cead023afcd72d1104e02b2d67406b9c47102589 | 2,405 |
def filesystem_entry(filesystem):
"""
Filesystem tag {% filesystem_entry filesystem %} is used to display a single
filesystem.
Arguments
---------
filesystem: filesystem object
Returns
-------
A context which maps the filesystem object to filesystem.
"""
return {'filesystem': filesystem} | 3afbd0b8ee9e72ab8841ca5c5517396650d2a898 | 2,409 |
def gather_squares_triangles(p1,p2,depth):
""" Draw Square and Right Triangle given 2 points,
Recurse on new points
args:
p1,p2 (float,float) : absolute position on base vertices
depth (int) : decrementing counter that terminates recursion
return:
squares [(float,float,float,float)...] : absolute positions of
vertices of squares
triangles [(float,float,float)...] : absolute positions of
vertices of right triangles
"""
# Break Recursion if depth is met
if depth == 0:
return [],[]
# Generate Points
pd = (p2[0] - p1[0]),(p1[1] - p2[1])
p3 = (p2[0] - pd[1]),(p2[1] - pd[0])
p4 = (p1[0] - pd[1]),(p1[1] - pd[0])
p5 = (p4[0] + (pd[0] - pd[1])/2),(p4[1] - (pd[0] + pd[1])/2)
# Gather Points further down the tree
squares_left,triangles_left = gather_squares_triangles(p4,p5,depth-1)
squares_right,triangles_right = gather_squares_triangles(p5,p3,depth-1)
# Merge and Return
squares = [[p1,p2,p3,p4]]+squares_left+squares_right
triangles = [[p3,p4,p5]]+triangles_left+triangles_right
return squares,triangles | de4e720eb10cb378f00086a6e8e45886746055c0 | 2,411 |
def decorate(rvecs):
"""Output range vectors into some desired string format"""
return ', '.join(['{%s}' % ','.join([str(x) for x in rvec]) for rvec in rvecs]) | 31a3d4414b0b88ffd92a5ddd8eb09aaf90ef3742 | 2,413 |
def get_color(card):
"""Returns the card's color
Args:
card (webelement): a visible card
Returns:
str: card's color
"""
color = card.find_element_by_xpath(".//div/*[name()='svg']/*[name()='use'][2]").get_attribute("stroke")
# both light and dark theme
if (color == "#ff0101" or color == "#ffb047"):
color = "red"
elif (color == "#800080" or color == "#ff47ff"):
color = "purple"
else:
color = "green"
return color | 452266b81d70973149fed4ab2e6cbc9c93591180 | 2,414 |
def add_chr_prefix(band):
"""
Return the band string with chr prefixed
"""
return ''.join(['chr', band]) | 08a99220023f10d79bdacdb062a27efcb51086ce | 2,415 |
def disable_text_recog_aug_test(cfg, set_types=None):
"""Remove aug_test from test pipeline of text recognition.
Args:
cfg (mmcv.Config): Input config.
set_types (list[str]): Type of dataset source. Should be
None or sublist of ['test', 'val']
Returns:
cfg (mmcv.Config): Output config removing
`MultiRotateAugOCR` in test pipeline.
"""
assert set_types is None or isinstance(set_types, list)
if set_types is None:
set_types = ['val', 'test']
for set_type in set_types:
if cfg.data[set_type].pipeline[1].type == 'MultiRotateAugOCR':
cfg.data[set_type].pipeline = [
cfg.data[set_type].pipeline[0],
*cfg.data[set_type].pipeline[1].transforms
]
return cfg | bda3a5420d32d55062b23a6af27cee3e203b878c | 2,416 |
def delta_in_ms(delta):
"""
Convert a timedelta object to milliseconds.
"""
return delta.seconds*1000.0+delta.microseconds/1000.0 | 4ed048155daf4a4891488e28c674e905e1bbe947 | 2,418 |
def selection_sort(data):
"""Sort a list of unique numbers in ascending order using selection sort. O(n^2).
The process includes repeatedly iterating through a list, finding the smallest element, and sorting that element.
Args:
data: data to sort (list of int)
Returns:
sorted list
"""
sorted_data = data[:]
for i, value in enumerate(sorted_data):
# find smallest value in unsorted subset
min_value = min(sorted_data[i:])
index_min = sorted_data.index(min_value)
# place smallest value at start of unsorted subset
sorted_data[i], sorted_data[index_min] = min_value, value
return sorted_data | 8b745be41c857669aedecb25b3006bbdc1ef04eb | 2,419 |
def player_count(conn, team_id):
"""Returns the number of players associated with a particular team"""
c = conn.cursor()
c.execute("SELECT id FROM players WHERE team_id=?", (team_id,))
return len(c.fetchall()) | cfced6da6c8927db2ccf331dca7d23bba0ce67e5 | 2,420 |
def find_process_in_list( proclist, pid ):
"""
Searches for the given 'pid' in 'proclist' (which should be the output
from get_process_list(). If not found, None is returned. Otherwise a
list
[ user, pid, ppid ]
"""
for L in proclist:
if pid == L[1]:
return L
return None | 19eab54b4d04b40a54a39a44e50ae28fbff9457c | 2,428 |
def get_dp_logs(logs):
"""Get only the list of data point logs, filter out the rest."""
filtered = []
compute_bias_for_types = [
"mouseout",
"add_to_list_via_card_click",
"add_to_list_via_scatterplot_click",
"select_from_list",
"remove_from_list",
]
for log in logs:
if log["type"] in compute_bias_for_types:
filtered.append(log)
return filtered | e0a7c579fa9218edbf942afdbdb8e6cf940d1a0c | 2,430 |
import random
def attack(health, power, percent_to_hit):
"""Calculates health from percent to hit and power of hit
Parameters:
health - integer defining health of attackee
power - integer defining damage of attacker
percent to hit - float defining percent chance to hit of attacker
Returns: new health
"""
random_number = random.random() # number between 0.0 and 1.0
# if our random number falls between 0 and percent to hit
if random_number <= percent_to_hit:
# then a hit occurred so we reduce health by power
health = health - power
# return the new health value
return health | 83a74908f76f389c798b28c5d3f9035d2d8aff6a | 2,436 |
import json
def load_data(path):
"""Load JSON data."""
with open(path) as inf:
return json.load(inf) | 531fc2b27a6ab9588b1f047e25758f359dc21b6d | 2,437 |
import random
def seed_story(text_dict):
"""Generate random seed for story."""
story_seed = random.choice(list(text_dict.keys()))
return story_seed | 0c0f41186f6eaab84a1d197e9335b4c28fd83785 | 2,444 |
def round_int(n, d):
"""Round a number (float/int) to the closest multiple of a divisor (int)."""
return round(n / float(d)) * d | 372c0f8845994aaa03f99ebb2f65243e6490b341 | 2,447 |
def check_hostgroup(zapi, region_name, cluster_id):
"""check hostgroup from region name if exists
:region_name: region name of hostgroup
:returns: true or false
"""
return zapi.hostgroup.exists(name="Region [%s %s]" % (region_name, cluster_id)) | b237b544ac59331ce94dd1ac471187a60d527a1b | 2,448 |
def refresh_wrapper(trynum, maxtries, *args, **kwargs):
"""A @retry argmod_func to refresh a Wrapper, which must be the first arg.
When using @retry to decorate a method which modifies a Wrapper, a common
cause of retry is etag mismatch. In this case, the retry should refresh
the wrapper before attempting the modifications again. This method may be
passed to @retry's argmod_func argument to effect such a refresh.
Note that the decorated method must be defined such that the wrapper is its
first argument.
"""
arglist = list(args)
# If we get here, we *usually* have an etag mismatch, so specifying
# use_etag=False *should* be redundant. However, for scenarios where we're
# retrying for some other reason, we want to guarantee a fresh fetch to
# obliterate any local changes we made to the wrapper (because the retry
# should be making those changes again).
arglist[0] = arglist[0].refresh(use_etag=False)
return arglist, kwargs | 089b859964e89d54def0058abc9cc7536f5d8877 | 2,453 |
def get_event_details(event):
"""Extract event image and timestamp - image with no tag will be tagged as latest.
:param dict event: start container event dictionary.
:return tuple: (container image, last use timestamp).
"""
image = str(event['from'] if ":" in event['from'] else event['from'] + ":latest")
timestamp = event['time']
return image, timestamp | c9b4ded7f343f0d9486c298b9a6f2d96dde58b8c | 2,468 |
import json
def copyJSONable(obj):
"""
Creates a copy of obj and ensures it is JSONable.
:return: copy of obj.
:raises:
TypeError: if the obj is not JSONable.
"""
return json.loads(json.dumps(obj)) | 1cc3c63893c7716a4c3a8333e725bb518b925923 | 2,469 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.