content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def normalize_md(txt):
"""Replace newlines *inside paragraphs* with spaces.
Consecutive lines of text are considered part of the same paragraph
in Markdown. So this function joins those into a single line to make the
test robust to changes in text wrapping.
NOTE: This function doesn't attempt to be 100% grammatically correct
Markdown! It's just supposed to be "correct enough" for tests to pass. For
example, when we guard "\n\n" from being converted, we really should be
guarding for RegEx("\n\n+") instead. But that doesn't matter for our tests.
"""
# Two newlines in a row should NOT be replaced with a space.
txt = txt.replace("\n\n", "OMG_NEWLINE")
# Lists should NOT be replaced with a space.
txt = txt.replace("\n*", "OMG_STAR")
txt = txt.replace("\n-", "OMG_HYPHEN")
# Links broken over two lines should not get an extra space.
txt = txt.replace("]\n(", "OMG_LINK")
# Convert all remaining newlines into spaces.
txt = txt.replace("\n", " ")
# Restore everything else.
txt = txt.replace("OMG_NEWLINE", "\n\n")
txt = txt.replace("OMG_STAR", "\n*")
txt = txt.replace("OMG_HYPHEN", "\n-")
txt = txt.replace("OMG_LINK", "](")
return txt.strip() | 3d3383607c7b5957ce75888266326f03f7dc7be2 | 20,417 |
import re
def tsv_string_to_list(s, func=lambda x : x, sep='|^|'):
"""Convert a TSV string from the sentences_input table to a list,
optionally applying a fn to each element"""
if s.strip() == "":
return []
# Auto-detect separator
if re.search(r'^\{|\}$', s):
split = re.split(r'\s*,\s*', re.sub(r'^\{\s*|\s*\}$', '', s))
else:
split = s.split(sep)
# split and apply function
return [func(x) for x in split] | 3bc223b7d685a0245d4dad98eeac81c39a315a77 | 20,422 |
def replicate_config(cfg, num_times=1):
"""Replicate a config dictionary some number of times
Args:
cfg (dict): Base config dictionary
num_times (int): Number of repeats
Returns:
(list): List of duplicated config dictionaries, with an added 'replicate' field.
"""
# Repeat configuration settings across replicates
configs = []
for replicate in range(num_times):
_config = cfg.copy()
_config.update({"replicate": replicate})
configs.append(_config)
return configs | 8b4d43002c22d20c6d2238c2309086a21d560c5c | 20,425 |
def create_table_sql(tablename, fields, geom_type, geom_srid):
"""
Create a SQL statement for creating a table. Based on a geoJSON
representation. For simplicity all fields are declared VARCHAR 255
(not good, I know, patches welcome)
"""
cols = []
for field in fields:
cols.append("%s VARCHAR(255)" % field)
statement = """CREATE TABLE %s (
id SERIAL,
%s,
geom GEOMETRY(%s, %s),
PRIMARY KEY (id)
)
""" %(tablename, ",\n".join(cols), geom_type, geom_srid)
return statement | 1df5ff0472a0333f6dcc872030e3f253e4aeb940 | 20,436 |
import click
def _validate_count(value):
"""
Validate that count is 4 or 5, because EFF lists
only work for these number of dice.
:param value: value to validate
:return: value after it's validated
"""
# Use `set` ({x, y, z}) here for quickest result
if value not in {4, 5}:
raise click.BadParameter(
'Words in word lists limit number of dice to 4 or 5.'
)
return value | 79f17c061af41e71f0f2f82d4a6a21fe2e09abfa | 20,443 |
import torch
def compute_content_loss(a_C, a_G):
"""
Compute the content cost
Arguments:
a_C -- tensor of dimension (1, n_C, n_H, n_W)
a_G -- tensor of dimension (1, n_C, n_H, n_W)
Returns:
J_content -- scalar that you compute using equation 1 above
"""
m, n_C, n_H, n_W = a_G.shape
# Reshape a_C and a_G to the (m * n_C, n_H * n_W)
a_C_unrolled = a_C.view(m * n_C, n_H * n_W)
a_G_unrolled = a_G.view(m * n_C, n_H * n_W)
# Compute the cost
J_content = 1.0 / (4 * m * n_C * n_H * n_W) * torch.sum((a_C_unrolled - a_G_unrolled) ** 2)
return J_content | 51894aedd2a7cfce5db3be3b43f8689ecdf78bf6 | 20,449 |
def filter_table_from_column(table,column,value):
"""
Return a view into the 'table' DataFrame, selecting only the rows where
'column' equals 'value'
"""
return table[table[column] == value] | 2b0642d8a2a7959614ef99f1fdc12148ddd294f7 | 20,451 |
def strip_specific_magics(source, magic):
"""
Given the source of a cell, filter out specific cell and line magics.
"""
filtered=[]
for line in source.splitlines():
if line.startswith(f'%{magic}'):
filtered.append(line.lstrip(f'%{magic}').strip(' '))
if line.startswith(f'%%{magic}'):
filtered.append(line.lstrip(f'%%{magic}').strip(' '))
else:
filtered.append(line)
return '\n'.join(filtered) | 3c2722b86b6fc8e40c8dd51edd06d7edb28e2945 | 20,452 |
def pagination_for(context, current_page, page_var="page", exclude_vars=""):
"""
Include the pagination template and data for persisting querystring
in pagination links. Can also contain a comma separated string of
var names in the current querystring to exclude from the pagination
links, via the ``exclude_vars`` arg.
"""
querystring = context["request"].GET.copy()
exclude_vars = [v for v in exclude_vars.split(",") if v] + [page_var]
for exclude_var in exclude_vars:
if exclude_var in querystring:
del querystring[exclude_var]
querystring = querystring.urlencode()
return {
"current_page": current_page,
"querystring": querystring,
"page_var": page_var,
} | 77996effe11d35cff3b7e279533f331e1b2d05e0 | 20,459 |
import hmac
def compute_signature(payload: bytes, secret: bytes, algo: str = 'sha256') -> str:
"""
Computes the HMAC signature of *payload* given the specified *secret* and the given hashing *algo*.
# Parmeters
payload: The payload for which the signature should be computed.
secret: The secret string that is used in conjunction to generate the signature.
algo: The hash algorithm to use, must be `sha1` or `sha256`.
"""
if algo not in ('sha1', 'sha256'):
raise ValueError(f'algo must be {{sha1, sha256}}, got {algo!r}')
return f'{algo}=' + hmac.new(secret, payload, algo).hexdigest() | 0f62326eaadddb569c661a59a60284062c348b2e | 20,467 |
from typing import Any
import jinja2
def _render_jinja2(filename: str, **kwargs: Any) -> str:
"""Returns a rendered template.
Args:
filename: Template filename.
**kwargs: Template environment.
"""
with open(filename, 'r') as fh:
template = jinja2.Template(fh.read(), autoescape=False)
return template.render(**kwargs) | 1a48edc8fb829e9a12bfd678756c995afaf5c9bd | 20,478 |
def min_value_node(node):
"""
Binary Search Tree min value node
Complexity: O(HEIGHT)
Find the node with the minimum value in a
binary search tree.
"""
while node.left is not None:
node = node.left
return node | 4d423183f0da3fd5d0bc66c84f26353543f8e406 | 20,479 |
def parse_option_list_string(option_list, delimiter=None):
"""Convert the given string to a dictionary of options.
Each pair must be of the form 'k=v', the delimiter seperates the
pairs from each other not the key from the value.
:param option_list: A string representation of key value pairs.
:type option_list: str
:param delimiter: Delimiter to use to seperate each pair.
:type delimiter: str
:returns: A dictionary of settings.
:rtype: Dict
"""
settings = {}
if delimiter is None:
delimiter = ';'
for setting in option_list.split(delimiter):
if not setting:
continue
key, value = setting.split('=')
settings[key.strip()] = value.strip()
return settings | fe6a440e004552b418d151ac6f3de9a08fe3e787 | 20,481 |
def _read_exact(read, size):
"""
Read exactly size bytes with `read`, except on EOF
:Parameters:
- `read`: The reading function
- `size`: expected number of bytes
:Types:
- `read`: ``callable``
- `size`: ``int``
:return: The read bytes
:rtype: ``str``
"""
if size < 0:
return read(size)
vlen, buf = 0, []
push = buf.append
while vlen < size:
val = read(size - vlen)
if not val:
break
vlen += len(val)
push(val)
return "".join(buf) | 4520c977812bd77365dd1b5a445697b3435d1d19 | 20,483 |
import re
def char_length(character, letter_spacing=0):
"""Return the max width of a character by looking at its longest line.
:param character: The character array from the font face
:param letter_spacing: The user defined letter spacing
:returns: The length of a longest line in a character
"""
stripped = [re.sub(r"(<([^>]+)>)", "", char) for char in character]
char_width = max(map(len, stripped))
if char_width == 0 and letter_spacing > 0:
# Adding space to letter spacing
char_width = 1
return char_width | 32650f0d21e597810225dad25513b0107d6551e1 | 20,488 |
from typing import List
from typing import Dict
def aggregate_action_stats(action_stats: List[Dict[str, int]]) -> Dict[str, int]:
"""Aggregate statistics by returning largest value observed for each of the tweet reactions (reply, retweet, favorite)."""
action_stat = {}
for key in action_stats[0].keys():
counts = [count[key] for count in action_stats]
action_stat[key] = max(counts)
return action_stat | 2e43e186c6f6ba58ce7ba0ff883bdb61783c896b | 20,490 |
import re
import logging
def append_to_csl_item_note(csl_item, text='', dictionary={}):
"""
Add information to the note field of a CSL Item.
In addition to accepting arbitrary text, the note field can be used to encode
additional values not defined by the CSL JSON schema, as per
https://github.com/Juris-M/citeproc-js-docs/blob/93d7991d42b4a96b74b7281f38e168e365847e40/csl-json/markup.rst#cheater-syntax-for-odd-fields
Use dictionary to specify variable-value pairs.
"""
if not isinstance(csl_item, dict):
raise ValueError(f'append_to_csl_item_note: csl_item must be a dict but was of type {type(csl_item)}')
if not isinstance(dictionary, dict):
raise ValueError(f'append_to_csl_item_note: dictionary must be a dict but was of type {type(dictionary)}')
if not isinstance(text, str):
raise ValueError(f'append_to_csl_item_note: text must be a str but was of type {type(text)}')
note = str(csl_item.get('note', ''))
if text:
if note and not note.endswith('\n'):
note += '\n'
note += text
for key, value in dictionary.items():
if not re.fullmatch(r'[A-Z]+|[-_a-z]+', key):
logging.warning(f'append_to_csl_item_note: skipping adding "{key}" because it does not conform to the variable_name syntax as per https://git.io/fjTzW.')
continue
if '\n' in value:
logging.warning(f'append_to_csl_item_note: skipping adding "{key}" because the value contains a newline: "{value}"')
continue
if note and not note.endswith('\n'):
note += '\n'
note += f'{key}: {value}'
if note:
csl_item['note'] = note
return csl_item | b3f43adacba1dca3749e048fe94b5cf0b2c15e3b | 20,491 |
def GetTitle( text ):
"""Given a bit of text which has a form like this:
'\n\n Film Title\n \n (OmU)\n '
return just the film title.
"""
pp = text.splitlines()
pp2 = [p.strip() for p in pp if len(p.strip()) >= 1]
return pp2[0] | d152282610072fa88c7a45a3aca2991b6fedb79c | 20,493 |
def get_time_in_seconds(timeval, unit):
"""
Convert a time from 'unit' to seconds
"""
if 'nyear' in unit:
dmult = 365 * 24 * 3600
elif 'nmonth' in unit:
dmult = 30 * 24 * 3600
elif 'nday' in unit:
dmult = 24 * 3600
elif 'nhour' in unit:
dmult = 3600
elif 'nminute' in unit:
dmult = 60
else:
dmult = 1
return dmult * timeval | 4fbcbf16e7a51e046e267a0cafad090049357cae | 20,494 |
def get_columns(document):
"""
Return a list of tuples, each tuple containing column name and type
"""
# tags = document.tags.to_dict()
tags = document.tags
names = list(tags.keys())
types = list(tags.values())
columns = []
for field, value in zip(names, types):
try:
value = int(value) # Handle year better
except:
pass
if isinstance(value, str):
value = "str"
elif isinstance(value, int):
value = "int"
col = (field, value)
columns.append(col)
return columns | c227815fcf1d2b3815b951c90397a7e89c43cc1c | 20,496 |
def drawPins(input_data, xpins, ypins, map):
"""
Draw pins on input_data
Inputs:
- input_data: np.array of size (C, H, W) (all zeros to start with)
- xpins & ypins: np.array of x-coordinates and y-coordinates for all pins
e.g., [x1, x2 ... xm] and [y1, y2, ... ym] for m pins
- map: layout layer map (dictionary from layer name to index)
Outputs:
- output_data: np.array of size (C, H, W) (with pixels corresponding to pins in layer 'pins' set to '1')
"""
output_data = input_data
for (x, y) in zip(xpins, ypins):
output_data[map['pin'], y, x] = 1
return output_data | 1d5796cc2a009e8e5993cbc374525c46b08a1a61 | 20,497 |
import re
def slugify(input: str) -> str:
"""Converts Foo Bar into foo-bar, for use wih anchor links."""
input = re.sub(r"([() ]+)", "-", input.lower())
return re.sub(r"-$", "", input) | c08acb689783e382ce58ca886f2971aa4f42c763 | 20,500 |
def check_input_stream_count(expected_number_of_streams):
"""
Decorator for Tool._execute that checks the number of input streams
:param expected_number_of_streams: The expected number of streams
:return: the decorator
"""
def stream_count_decorator(func):
def func_wrapper(*args, **kwargs):
self = args[0]
sources = kwargs['sources'] if 'sources' in kwargs else args[1]
if expected_number_of_streams == 0:
if sources:
raise ValueError("No input streams expected")
else:
given_number_of_streams = len(sources) if sources else 0
if given_number_of_streams != expected_number_of_streams:
raise ValueError("{} tool takes {} stream(s) as input ({} given)".format(
self.__class__.__name__, expected_number_of_streams, given_number_of_streams))
return func(*args, **kwargs)
return func_wrapper
return stream_count_decorator | 96dfdc8f85d70dee1ac44f01f95dd07eb3725261 | 20,508 |
import math
def calculate_base_day_duration(game):
"""Calculate the base day length."""
base_day_length = math.sqrt(2 * game.nb_alive_players)
base_day_length = math.ceil(base_day_length) + 1
base_day_length = base_day_length * 60
return base_day_length | 00f49a75f7b9772bed5358fe05f7ddf9b35d2f93 | 20,510 |
def contains_tokens(pattern):
"""Test if pattern is a list of subpatterns."""
return type(pattern) is list and len(pattern) > 0 | 10436114b1eb1b9e3f5c85bf30ec0813d999d101 | 20,513 |
def solve(equation, answer):
""" Solve equation and check if user is correct or incorrect """
splitted = equation.split('=')
left = splitted[0].strip().replace('?', str(answer)).replace('x', '*')
right = splitted[1].strip().replace('?', str(answer)).replace('x', '*')
try:
if right.isdigit():
return eval(left) == int(right)
else:
return int(left) == eval(right)
except ValueError:
return False | 78f0eced818e681ed8d8c5e0e4667a101a7ffd4e | 20,522 |
def load_model_configurations(model):
"""
Arguments:
model: A SSD model with PriorBox layers that indicate the
parameters of the prior boxes to be created.
Returns:
model_configurations: A dictionary of the model parameters.
"""
model_configurations = []
for layer in model.layers:
layer_type = layer.__class__.__name__
if layer_type == 'PriorBox':
layer_data = {}
layer_data['layer_width'] = layer.input_shape[1]
layer_data['layer_height'] = layer.input_shape[2]
layer_data['min_size'] = layer.min_size
layer_data['max_size'] = layer.max_size
layer_data['aspect_ratios'] = layer.aspect_ratios
layer_data['num_prior'] = len(layer.aspect_ratios)
model_configurations.append(layer_data)
return model_configurations | 34c6efbca820bd5461b2e5aeb2c7b30184afa250 | 20,540 |
def user_case(mocker, user, case, org):
"""Fake UserCase instance."""
instance = mocker.Mock()
instance.user = user
instance.case = case
instance.organisation = org
return instance | 5d6de334a8ac690156204e81a6c2db53a71ea1d6 | 20,543 |
import re
def camel_to_snake(text):
"""
Will convert CamelCaseStrings to snake_case_strings. Examples:
>>> camel_to_snake('CamelCase')
'camel_case'
>>> camel_to_snake('CamelCamelCase')
'camel_camel_case'
>>> camel_to_snake('Camel2Camel2Case')
'camel2_camel2_case'
>>> camel_to_snake('getHTTPResponseCode')
'get_http_response_code'
>>> camel_to_snake('get2HTTPResponseCode')
'get2_http_response_code'
>>> camel_to_snake('HTTPResponseCode')
'http_response_code'
>>> camel_to_snake('HTTPResponseCodeXYZ')
'http_response_code_xyz'
>>> camel_to_snake('Double_Case')
'double_case'
>>> camel_to_snake('SW_Merch')
'sw_merch'
>>> camel_to_snake('Odd/Characters')
'odd_characters'
>>> camel_to_snake('With Spaces')
'with_spaces'
"""
# Load #
result = text
# Eliminate trailing spaces #
result = result.strip(' ')
# First step #
try:
result = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', result)
except TypeError:
print("The text received was '%s'" % result)
raise
# Second step #
result = re.sub('([a-z0-9])([A-Z])', r'\1_\2', result)
# Lower case the rest #
result = result.lower()
# Eliminate remaining spaces #
result = result.replace(' ', '_')
# Eliminate quote characters #
result = result.replace('"', '')
result = result.replace("'", '')
# Eliminate parenthesis #
result = result.replace("(", '')
result = result.replace(")", '')
# Eliminate special characters #
result = result.replace('/', '_')
# Eliminate double underscore #
while '__' in result: result = result.replace('__', '_')
# Return #
return result | d7216ab1a35c189abf67bfb475486ce05dcba560 | 20,544 |
def get_hex(binary_str):
"""
Returns the hexadecimal string literal for the given binary string
literal input
:param str binary_str: Binary string to be converted to hex
"""
return "{0:#0{1}x}".format(int(binary_str, base=2), 4) | fe2784e58d61e577bcc66ed1bd3d2c02c1e7fda0 | 20,545 |
import glob
def is_file_exists(file_name: str) -> bool:
"""
Checks if a file exists.
:param file_name: file name to check
:return: True, if the file exists, False otherwise
"""
return len(glob.glob(file_name)) == 1 | 7e8da1f544d40d53f9329e4453e198022330f01c | 20,551 |
def fix_lon(lon):
"""
Fixes negative longitude values.
Parameters
----------
lon: ndarray like or value
Input longitude array or single value
"""
if lon < 0:
lon += 360.
return lon | ab11dca9279399179242537c86cf0af85eedb60e | 20,552 |
def is_unique_chars_v3(str):
"""
If not allowed to use additional data structures, we can compare every character of the string to every other
character of the string.
This will take 0(n ** 2) time and 0(1) space
"""
for char1 in str:
occurrence = 0
for char2 in str:
if char1 == char2:
occurrence += 1
if occurrence > 1:
return False
return True | 5c524ffa29b7cdc9d43619da7b299ae0f90d443c | 20,554 |
def split_canonical(canonical):
"""
Split a canonical into prefix and suffix based on value sign #
:param canonical: the canonical to split
:return: prefix and suffix
"""
if '#' not in canonical:
return canonical, ''
if canonical.startswith('#'):
return '', canonical[1:].strip()
return list(map(lambda x: x.strip(), canonical.split('#'))) | 1a3f7e17cfcc9fa88d63d72fced5435c92f2ea10 | 20,555 |
def _format_yaml_load(data):
"""
Reinsert '\n's that have been removed fom comments to make file more readable
:param data: string to format
:return: formatted string
"""
# ptr = 0
# cptr = data[ptr:].find('comment: ')
data = data.replace("\n", "\n\n")
return data | 499cd37a75d9badb4ba3bc853a6152036bc2e66b | 20,564 |
def TransformName(r, undefined=''):
"""Returns a resorce name from an URI.
Args:
r: JSON-serializable object.
undefined: Returns this value if the resource cannot be formatted.
Returns:
A project name for selfLink from r.
"""
if r:
try:
return r.split('/')[-1]
except AttributeError:
pass
return undefined | 6dafaa2b3f0e187fc9bc9238e3a7a06a895675fd | 20,565 |
def get_username(request):
"""Returns the username from request."""
# Retrieve the username either from a cookie (when logging out) or
# the authenticated user.
username = "not-login"
if hasattr(request, "user"):
username = request.user.username
if request.session.get('staff', False):
username = "%s(*)" % username
return username | cdd19d9715c20a4bc7f20be9b53926b87be671da | 20,566 |
def west_valley(parcels):
"""
Dummy for presence in West Valley.
"""
in_wv = parcels['mpa'].isin([
'AV', 'BU', 'EL', 'GB', 'GL', 'GO', 'LP', 'PE', 'SU', 'TO', 'WI', 'YO'
])
return (parcels['is_MC'] & in_wv).astype(int) | fec326f82b21acb0cab670904b76096f84445e4d | 20,569 |
from typing import Dict
def _run_compatibility_patches(json_data: Dict) -> Dict:
"""Patch the incoming JSON to make it compatible.
Over time the structure of the JSON information used to dump a workflow
has changed. These patches are to guarantee that an old workflow is
compliant with the new structure. The patches applied are:
1. Change action.target_url from None to ''
:param json_data: Json object to process
:return: Modified json_data
"""
# Target_url field in actions should be present an empty by default
for action_obj in json_data['actions']:
if action_obj.get('target_url') is None:
action_obj['target_url'] = ''
return json_data | e00776cfb89499fbac71cf867830fc00631ac600 | 20,575 |
def unsplit_to_tensors(tuples):
"""Get original tensor list from list of tensor tuples.
Args:
tuples: list of tensor tuples.
Returns:
original tensor list.
"""
return [t for tup in tuples for t in tup] | b5df94421ade286ef5ff9bb4c422c5201babe36f | 20,577 |
def getLivenessPoints(liveness):
"""
histogram points for the liveness plot. It will be used for a plot like:
^
| *
| * * *
| ** ***
| *********
+-------------->
schedule index.
For example, if the livenesses are [3,5], the points will be,
[[0,3],[1,3],[1,5],[2,5]]
The points are connected alternatively with horizontal and vertical lines.
"""
xs = []
ys = []
for op in range(len(liveness)):
if op == 0:
xs.append(0)
else:
xs.append(xs[-1])
xs.append(xs[-1] + 1)
ys.append(liveness[op])
ys.append(liveness[op])
assert len(xs) == len(ys)
assert len(xs) == 2 * len(liveness)
return xs, ys | 84dac2f0b29c957727354dd06863820c2e56a866 | 20,578 |
from urllib.parse import urlencode
def oauth_url(client_id, permissions=None, server=None, redirect_uri=None):
"""A helper function that returns the OAuth2 URL for inviting the bot
into servers.
Parameters
-----------
client_id : str
The client ID for your bot.
permissions : :class:`Permissions`
The permissions you're requesting. If not given then you won't be requesting any
permissions.
server : :class:`Server`
The server to pre-select in the authorization screen, if available.
redirect_uri : str
An optional valid redirect URI.
"""
url = 'https://discordapp.com/oauth2/authorize?client_id={}&scope=bot'.format(client_id)
if permissions is not None:
url = url + '&permissions=' + str(permissions.value)
if server is not None:
url = url + "&guild_id=" + server.id
if redirect_uri is not None:
url = url + "&response_type=code&" + urlencode({'redirect_uri': redirect_uri})
return url | bf7ca1957153ff938334927744804891010c0c26 | 20,579 |
def get_menu_item(menu):
"""
Asks user to choose a menu item from one of the menu
dictionaries defined above
Args:
(dictionary) menu - dict of menu items
Returns:
(str) selection - key of menu item chosen
"""
while True:
print('------------')
print('Menu Options')
print('------------')
options = list(menu.keys())
options.sort()
for entry in options:
print( entry, menu[entry] )
selection = input("Please Select: ")
# in case X entered for exit
if selection.isupper():
selection = selection.lower()
if selection in options:
# print(menu[selection])
break
else:
print( "Unknown Option Selected!" )
return selection | 603ed07bdd7b51d9539cb0251f42e0affc1001cf | 20,584 |
def _sharded_checkpoint_pattern(process_index, process_count):
"""Returns the sharded checkpoint prefix."""
return f"shard-{process_index:05d}-of-{process_count:05d}_checkpoint_" | 67e0b91b8b3ac9d5c69ec662f6c7931c90a79225 | 20,587 |
def parse_arg(arg):
"""
Parses arguments for convenience. Argument can be a
csv list ('a,b,c'), a string, a list, a tuple.
Returns a list.
"""
# handle string input
if type(arg) == str:
arg = arg.strip()
# parse csv as tickers and create children
if ',' in arg:
arg = arg.split(',')
arg = [x.strip() for x in arg]
# assume single string - create single item list
else:
arg = [arg]
return arg | 45154fbdd9b6ecfafebbee0ec47a6185799a773a | 20,589 |
from typing import Dict
def tags_string(tags: Dict[str, str]) -> str:
"""
tags_string generates datadog format tags from dict.
"""
s = ''
for k in tags:
s += f'{k}:{tags[k]},'
return s.rstrip(',') | 203243c2960bb4fb75a832bc014484aa5b9dec9c | 20,590 |
def if_elif_else(value, condition_function_pair):
"""
Apply logic if condition is True.
Parameters
----------
value : anything
The initial value
condition_function_pair : tuple
First element is the assertion function, second element is the
logic function to execute if assertion is true.
Returns
-------
The result of the first function for which assertion is true.
"""
for condition, func in condition_function_pair:
if condition(value):
return func(value) | ff2e5315e3bf7ad3e8fa23941e17d7052d6e3ebc | 20,593 |
from typing import List
def nest_list(inp: list, col_cnt: int) -> List[list]:
"""Make a list of list give the column count."""
nested = []
if len(inp) % col_cnt != 0:
raise ValueError("Missing value in matrix data")
for i in range(0, len(inp), col_cnt):
sub_list = []
for n in range(col_cnt):
try:
sub_list.append(inp[i+n])
except IndexError:
break
nested.append(sub_list)
return nested | 6d3ca2e2d4cb61d68279ffad773831a7ba203eae | 20,595 |
def get_koji_build_info(build_id, session, config):
"""
Returns build information from koji based on build id.
:param dict build_id: build id of a build in koji.
:param koji.ClientSession session: koji connection session object
:return: build information.
:rtype: dict
"""
print("Retriewing build metadata from: ", config.koji_host)
build = session.getBuild(build_id)
if not build:
raise Exception("Build with id '{id}' has not been found.".format(id=build_id))
print("Build with the ID", build_id, "found.")
return build | 4ffc925ca3ec6ede46d55f7a98f129683d2b4980 | 20,599 |
def dict_from_list(keyfunc, l):
""" Generate a dictionary from a list where the keys for each element are generated based off of keyfunc. """
result = dict()
for item in l:
result[keyfunc(item)] = item
return result | a676eb6cefaf99cbb6dd8d0aa61f05c31f2a2382 | 20,604 |
import re
def add_item_offset(token, sentence):
"""Get the start and end offset of a token in a sentence"""
s_pattern = re.compile(re.escape(token), re.I)
token_offset_list = []
for m in s_pattern.finditer(sentence):
token_offset_list.append((m.group(), m.start(), m.end()))
return token_offset_list | 45c387674c84cb6ba7559acc98b69e6789040f50 | 20,606 |
import torch
def get_lastlayers_model_weights(mdl, is_mask_class_specific = False, is_fc_lastlayer = False):
"""
Returns the weights at the head of the ROI predictor -> classification and bounding box regressor weights + bias
:returns cls_weights, bbox_pred_weights, bbox_pred_bias
:rtype: tuple
"""
if isinstance(mdl, str):
mdl = torch.load(mdl)['model']
elif isinstance(mdl, dict):
if 'model' in mdl:
mdl = mdl['model']
else:
raise TypeError('Expected dict or str')
cls_weights = mdl['roi_heads.box_predictor.cls_score.weight']
bbox_pred_weights = mdl['roi_heads.box_predictor.bbox_pred.weight']
bbox_pred_bias = mdl['roi_heads.box_predictor.bbox_pred.bias']
return cls_weights, bbox_pred_weights, bbox_pred_bias | fe662b448dc514113a8692cfb06417c99ab77244 | 20,607 |
def custom_rounder(input_number, p):
"""
Return round of the input number respected to the digit.
:param input_number: number that should be round
:type input_number: float
:param p: 10 powered by number of digits that wanted to be rounded to
:type p: int
:return: rounded number in float
"""
return int(input_number * p + 0.5) / p | 01cc63849c180024f83bb530aa0dfd69cbfc1495 | 20,610 |
def get_type(string_: str):
"""
Find type into which provided string should be casted.
:param string_: str -- single string to reformat
:return: float, int, bool or str
"""
if "." in string_ and string_.replace(".", "").isdigit():
return float
elif string_.replace("-", "").isdigit():
return int
elif string_ in ("True", "False"):
return bool
else:
return str | 1ca3de231a973488a77489b938eeaddb9531de1e | 20,612 |
import torch
import math
def elastic_deformation(img: torch.Tensor, sample_mode: str = "bilinear", alpha: int = 50,
sigma: int = 12) -> torch.Tensor:
"""
Performs random elastic deformation to the given Tensor image
:param img: (torch.Tensor) Input image
:param sample_mode: (str) Resmapling mode
:param alpha: (int) Scale factor of the deformation
:param sigma: (int) Standard deviation of the gaussian kernel to be applied
"""
# Get image shape
height, width = img.shape[-2:]
# Get kernel size
kernel_size = (sigma * 4) + 1
# Get mean of gaussian kernel
mean = (kernel_size - 1) / 2.
# Make gaussian kernel
# https://discuss.pytorch.org/t/is-there-anyway-to-do-gaussian-filtering-for-an-image-2d-3d-in-pytorch/12351/7
x_cord = torch.arange(kernel_size, device=img.device)
x_grid = x_cord.repeat(kernel_size).view(kernel_size, kernel_size)
y_grid = x_grid.t()
xy_grid = torch.stack([x_grid, y_grid], dim=-1)
gaussian_kernel = (1. / (2. * math.pi * sigma ** 2)) \
* torch.exp(-torch.sum((xy_grid - mean) ** 2., dim=-1) / (2. * sigma ** 2))
gaussian_kernel = gaussian_kernel.view(1, 1, kernel_size, kernel_size)
gaussian_kernel = gaussian_kernel.repeat(1, 1, 1, 1)
gaussian_kernel.requires_grad = False
# Make random deformations in the range of [-1, 1]
dx = (torch.rand((height, width), dtype=torch.float, device=img.device) * 2. - 1.).view(1, 1, height, width)
dy = (torch.rand((height, width), dtype=torch.float, device=img.device) * 2. - 1.).view(1, 1, height, width)
# Apply gaussian filter to deformations
dx, dy = torch.nn.functional.conv2d(input=torch.cat([dx, dy], dim=0), weight=gaussian_kernel, stride=1,
padding=kernel_size // 2).squeeze(dim=0) * alpha
# Add deformations to coordinate grid
grid = torch.stack(torch.meshgrid([torch.arange(height, dtype=torch.float, device=img.device),
torch.arange(width, dtype=torch.float, device=img.device)]),
dim=-1).unsqueeze(dim=0).flip(dims=(-1,))
grid[..., 0] += dx
grid[..., 1] += dy
# Convert grid to relative sampling location in the range of [-1, 1]
grid[..., 0] = 2 * (grid[..., 0] - (height // 2)) / height
grid[..., 1] = 2 * (grid[..., 1] - (width // 2)) / width
# Resample image
img_deformed = torch.nn.functional.grid_sample(input=img[None] if img.ndimension() == 3 else img,
grid=grid, mode=sample_mode, padding_mode='border',
align_corners=False)[0]
return img_deformed | ce8e884780a8dd54851d375f058fb836dfca0a0a | 20,617 |
def as_list(value):
"""\
Cast anything to a list (just copy a list or a tuple,
or put an atomic item to as a single element to a list).
"""
if isinstance(value, (list, tuple)):
return list(value)
return [value] | 02f8aa7194a594e0fd4bbddde77995382e011ac2 | 20,618 |
def user_register(request):
"""
用户注册页面路由函数
:param request: 请求对象
:return: 用户注册页面
"""
return {
'__template__': 'user_register.html'
} | 72813591d14a63a5788c2c9056d1482e8d07a31b | 20,620 |
from pathlib import Path
def dbt_artifacts_directory() -> Path:
"""
Get the path to the dbt artifacts directory.
Returns
-------
out : Path
The dbt artifacts directory
"""
artifactis_directory = Path(__file__).parent / "dbt/data/"
return artifactis_directory | 94b44a3418c4d307f2bed977325015ca2e78ed00 | 20,624 |
from datetime import datetime
def get_data_for_daily_statistics_table(df):
"""
Return data which is ready to be inserted to the daily_statistics table in
the database.
Parameters
----------
df : pandas.core.frame.DataFrame
Pandas Dataframe containing data received from the API.
Returns
-------
df_daily_statistics_data : pandas.core.frame.DataFrame
Pandas Dataframe containing data to be inserted to the daily_statistics
table in the database.
"""
df_daily_statistics_data = (
df.groupby(["district_name", "min_age_limit", "vaccine"])["available_capacity"]
.sum()
.reset_index()
)
df_daily_statistics_data["vaccine"] = df_daily_statistics_data[
"vaccine"
].str.upper()
df_daily_statistics_data["timestamp"] = datetime.utcnow().strftime(
"%Y-%m-%d %H:%M:%S"
)
return df_daily_statistics_data | faf7cfb76e88838d049e79bcabfbeef2238dc304 | 20,625 |
def number_of_authors(publications: list[dict]) -> int:
"""Computes the number of different authors.
Authors are differentiated by their ID.
:param: a list of publications.
:return: the number of authors.
"""
authors = set()
for publication in publications:
authors.update(x['id'] for x in publication['authors'])
return len(authors) | 7d4c610bb2f9a8003ae440e1408998ee28733bbc | 20,629 |
def get_slope(r, sy, sx):
"""
Get the slope for a regression line having given parameters.
Parameters
----------
> `r`: regrwssion coefficient of the line
> `sy` sample standard deviation of y distribution
> `sx`: sample standard deviation of x distribution
Returns
-------
The slope of the given regression line with the above parameters.
"""
return r * (sy / sx) | ada3f2b105634635a41d973a629aa32b64f8bbaf | 20,632 |
def clean_translation(translation):
"""Clean the translation string from unwanted substrings."""
illegal_substrings = ['; french.languagedaily.com',
';\u00a0french.languagedaily.com',
' french.languagedaily.co']
for iss in illegal_substrings:
translation = translation.replace(iss, '')
return translation | 9e20b739ebb47900555309d3a91f58f9ef0e8f7c | 20,634 |
def get_ids_from_nodes(node_prefix, nodes):
"""
Take a list of nodes from G and returns a list of the ids of only the nodes with the given prefix.
param node_prefix: prefix for the nodes to keep.
type node_prefix: str.
param nodes: list of nodes from G.
type nodes: [(str, int)].
"""
return map(lambda pair: pair[1], filter(lambda pair: pair[0] == node_prefix, nodes)) | 08c53235c0164dee66b63f7d672550763bb7e26d | 20,636 |
def parse_cachecontrol(header):
"""Parse Cache-Control header
https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
>>> parse_cachecontrol(b'public, max-age=3600') == {b'public': None,
... b'max-age': b'3600'}
True
>>> parse_cachecontrol(b'') == {}
True
"""
directives = {}
for directive in header.split(b','):
key, sep, val = directive.strip().partition(b'=')
if key:
directives[key.lower()] = val if sep else None
return directives | 8ebcd161f1361c59b82dd6eda42d429dc3bf1e4b | 20,637 |
def get_prefix0_format_string(item_num):
"""Get the prefix 0 format string from item_num.
For example, 3 items would result in {:01d}
"""
max_digit_num = len(str(item_num))
output_pattern = '{:0' + str(max_digit_num) + 'd}'
return output_pattern | 9b5e5597763d16577aacc2f884cc391edea4dcd4 | 20,639 |
from typing import Iterable
def join_comma_or(items: Iterable[str]) -> str:
"""Join strings with commas and 'or'."""
if not items:
raise ValueError("No items to join")
*rest, last = items
if not rest:
return last
return f"{', '.join(rest)} or {last}" | 08126eb0db002943c7613f140ad8ee279a1a8515 | 20,642 |
def generate_cursor(collection, parameters):
"""Query collection and return a cursor to be used for data retrieval."""
# We set no_cursor_timeout so that long retrievals do not cause generated
# cursors to expire on the MongoDB server. This allows us to generate all cursors
# up front and then pull results without worrying about a generated cursor
# timing out on the server.
return collection.find(
parameters["query"], parameters["projection"], no_cursor_timeout=True
) | 7b50cff3bad2cc0907f262008ff4e2c91b794d35 | 20,644 |
def is_prod_of_two_3_digit_num(n):
"""Determine whether n is the product of 3-digit numbers."""
result = False
for i in range(100, 1000):
if n % i == 0 and n // i in range(100, 1000):
result = True
break
return result | db0cb1b3ae1ecb8b15d01582f8c0599ce00ce766 | 20,647 |
def split_authority(authority):
"""
Basic authority parser that splits authority into component parts
>>> split_authority("user:password@host:port")
('user', 'password', 'host', 'port')
"""
if '@' in authority:
userinfo, hostport = authority.split('@', 1)
else:
userinfo, hostport = None, authority
if userinfo and ':' in userinfo:
user, passwd = userinfo.split(':', 1)
else:
user, passwd = userinfo, None
if hostport and ':' in hostport:
host, port = hostport.split(':', 1)
else:
host, port = hostport, None
if not host:
host = None
return (user, passwd, host, port) | bb6663646cec725ecb809cccfd75e7ee48a1684e | 20,648 |
def finite_fault_factor(magnitude, model="BT15"):
"""
Finite fault factor for converting Rrup to an equivalent point source
distance.
Args:
magnitude (float):
Earthquake moment magnitude.
model (str):
Which model to use; currently only suppport "BT15".
Returns:
float: Adjusted distance.
"""
if model == "BT15":
Mt1 = 5.744
Mt2 = 7.744
if magnitude < Mt1:
c0 = 0.7497
c1 = 0.4300
c2 = 0.0
Mt = Mt1
elif magnitude < Mt2:
c0 = 0.7497
c1 = 0.4300
c2 = -0.04875
Mt = Mt1
else:
c0 = 1.4147
c1 = 0.2350
c2 = 0
Mt = Mt2
logH = c0 + c1 * (magnitude - Mt) + c2 * (magnitude - Mt)**2
h = 10**(logH)
else:
raise ValueError("Unsupported finite fault adjustment model.")
return h | 55d74563cdfd367e7866ebc5285d6abed9c649df | 20,650 |
def addattr(**kwargs):
"""
Decorator to add attributes to a function
The shortcut is most useful for admin representations
of methods or attributes.
Example:
Instead of writing
>>> def is_valid(self):
>>> return self.name != "foo"
>>> is_valid.short_description = "The name for the function"
>>> is_valid.boolean = True
You write
>>> @addattr(short_description="The name for the function", boolean=True)
>>> def is_valid(self):
>>> return self.name != "foo"
:param kwargs: the properties to add to a function
"""
def decorator(func):
for key in kwargs:
setattr(func, key, kwargs[key])
return func
return decorator | bbf9ed404cc90413e6e186967621ed5d8ef858ad | 20,652 |
def outputCoords(x:int,y:int) -> str:
"""
Converts 2D list indexes into Human-Readable chess-board coordinates
x and y correspond to the indexes such that it looks like this: `dataList[x][y]`
"""
columnCheck = ["A","B","C"]
column = columnCheck[y]
row = str(x+1)
return column+row | 37412d503f792822f2264ac59eb22aee334182e8 | 20,653 |
def replace_ch(string: str, characters: list, replacement: str) -> str:
"""Replaces all intances of characters in a given string with a given
replacement character.
"""
n_string = string
for ch in characters:
n_string = n_string.replace(ch, replacement)
return n_string | 30939885554638d4b1cf844211e687a1447cd72b | 20,654 |
def isfloat(element):
"""
This function check if a string is convertable to float
"""
try:
float(element)
return True
except ValueError:
return False | 0a2c209b998a8aeea696a35f2cb3b587373739a5 | 20,657 |
def extract_topic_data(msg, t):
""" Reads all data in a message
This is a recursive function. Given a message, extract all of the data in the message to a dictionary. The keys
of the dictionary are the field names within the message, and the values are the values of the fields in the
message. Recursively call this function on a message to build up a dictionary of dictionaries representing the
ROS message.
Args:
msg: A ROS message
t: Time the message was recorded in the bag file
Returns:
A dictionary containing all information found in the message.
"""
# Initialize the information found for this message
data = {}
# If the message has slots, we have a non-primitive type, and need to extract all of the information from this
# message by recursively calling this function on the data in that slot. For example, we may have a message with a
# geometry_msgs/Vector3 as a field. Call this function on that field to get the x, y, and z components
if hasattr(msg, '__slots__'):
# Extract all information on a non-primitive type
for slot in msg.__slots__:
data[slot] = extract_topic_data(getattr(msg, slot), t)
else:
# We encountered a primitive type, like a double. Just return it so it gets put into the output dictionary
return msg
# Return the dictionary representing all of the fields and their information in this message
return data | 2a80771b70aa012bd626da7fbe8d5509c444481b | 20,658 |
def atm2Btu_ft3(x):
"""atm -> Btu/ft^3"""
return 2.719*x | e9717d6990e18a50c644bd5c942b965fabff861b | 20,661 |
def calc_angle(per, line):
"""
Calculate angle between two vector.
Take into consideration a quarter circle
:param per: first vector
:type per: DB.XYZ
:param line: second vector
:type line: DB.XYZ
:return: Angle between [-pi, pi]
:rtype: float
"""
return (1 if per.Y >= 0 else -1) * per.AngleTo(line) | 81290fd40dfd4d714f56478a2c41b33156ca8157 | 20,665 |
from pathlib import Path
def check_dir(dir, mkdir=False):
"""check directory
ディレクトリの存在を確認する。
Args:
dir (str): 対象ディレクトリのパス(文字列)
mkdir (bool, optional): 存在しない場合にディレクトリを作成するかを指定するフラグ.
Defaults to False.
Raises:
FileNotFoundError: mkdir=Falseの場合に、ディレクトリが存在しない場合に例外をraise
Returns:
dir_path : ディレクトリのPathオブジェクト
"""
dir_path = Path(dir)
if not dir_path.exists():
print(f"directory not found : {dir}")
if mkdir:
print(f"make directory : {dir}")
dir_path.mkdir(parents=True)
else:
raise FileNotFoundError(f"{dir}")
return dir_path | 1ada67ae07bdfe05c25474f3028cf4b5808d541b | 20,667 |
def extract_column_from_array(array, col_number):
"""
Extracts a specific column from an array and copies it to a list
:param array: The NumPy array with the data
:param col_number: The number of the column that should be extracted
:return: The list with the extracted values
"""
extracted_column = []
for row in array:
for number, column in enumerate(row):
if number == col_number:
extracted_column.append(column)
return extracted_column | b390ee58aab8802302996488925855de4d428f1a | 20,671 |
def spreadsheet_col_num_to_name(num):
"""Convert a column index to spreadsheet letters.
Adapted from http://asyoulook.com/computers%20&%20internet/python-convert-spreadsheet-number-to-column-letter/659618
"""
letters = ''
num += 1
while num:
mod = num % 26
letters += chr(mod + 64)
num = num // 26
return ''.join(reversed(letters)) | c39a96ed5794f582ce790a025ddecfe2cff39bf0 | 20,673 |
def _get_states(rev, act):
"""Determines the initial state and the final state based on boolean inputs
Parameters
----------
rev : bool
True if the reaction is in the reverse direction.
act : bool
True if the transition state is the final state.
Returns
-------
initial_state : str
Initial state of the reaction. Either 'reactants', 'products' or
'transition state'
final_state : str
Final state of the reaction. Either 'reactants', 'products' or
'transition state'
"""
if rev:
initial_state = 'products'
final_state = 'reactants'
else:
initial_state = 'reactants'
final_state = 'products'
# Overwrites the final state if necessary
if act:
final_state = 'transition state'
return initial_state, final_state | 4303b193a40515b4b7c52c4e2b5286dc6a9f4cd1 | 20,679 |
from typing import Any
def compare_any_with_str(other: Any, str_value: str) -> bool:
"""Compare any value with a string value in its str() form.
:param other: the other value to be compared with a string.
:param str_value: the string value to be compared.
:return: True if the str() of the other value is equal to str_value.
"""
return str(other) == str_value | be88d4e15a609468d3d65eb99417a4e76582ac9a | 20,682 |
def get_temp_column_name(df) -> str:
"""Small helper to get a new column name that does not already exist"""
temp_column_name = '__tmp__'
while temp_column_name in df.columns:
temp_column_name += '_'
return temp_column_name | a4dba2fb09166b2797f8c4c6dd93f46aaebb408e | 20,683 |
def enable() -> dict:
"""Enables tracking security state changes."""
return {"method": "Security.enable", "params": {}} | a9c341edf37ec5ebbc0b372b4e56a81e98aff903 | 20,685 |
def _sanitize_for_filename(text):
"""
Sanitize the given text for use in a filename.
(particularly log and lock files under Unix. So we lowercase them.)
:type text: str
:rtype: str
>>> _sanitize_for_filename('some one')
'some-one'
>>> _sanitize_for_filename('s@me One')
's-me-one'
>>> _sanitize_for_filename('LS8 BPF')
'ls8-bpf'
"""
return "".join([x if x.isalnum() else "-" for x in text.lower()]) | 7edda0859a6527c9a4cb0a464afb82c16d6df6dc | 20,691 |
def estimate_parms(W, X, Y, n):
"""Compute estimates of q_mod and q_con parameters."""
q_mod_hat = 1 - X / Y
q_con_hat = W / (n - 1)
return (q_mod_hat, q_con_hat) | b1f47de984482dee9d99f8ffa33ccb570079ba93 | 20,702 |
def _is_empty(value):
"""Returns true if value is none or empty string"""
return value is None or value is "" | 8afbcbc71ab47097520c7a7e646406967d1086f6 | 20,704 |
from html.entities import name2codepoint
import re
def extract_text(html, start, end, decode_entities=True, strip_tags=True):
"""Given *html*, a string of HTML content, and two substrings (*start* and *end*) present in this string, return all text between the substrings, optionally decoding any HTML entities and removing HTML tags.
>>> extract_text("<body><div><b>Hello</b> <i>World</i>™</div></body>",
... "<div>", "</div>") == 'Hello World™'
True
>>> extract_text("<body><div><b>Hello</b> <i>World</i>™</div></body>",
... "<div>", "</div>", decode_entities=False) == 'Hello World™'
True
>>> extract_text("<body><div><b>Hello</b> <i>World</i>™</div></body>",
... "<div>", "</div>", strip_tags=False) == '<b>Hello</b> <i>World</i>™'
True
"""
startidx = html.index(start)
endidx = html.rindex(end)
text = html[startidx + len(start):endidx]
if decode_entities:
entities = re.compile("&(\w+?);")
text = entities.sub(
lambda m: chr(
name2codepoint[
m.group(1)]),
text)
if strip_tags:
# http://stackoverflow.com/a/1732454
tags = re.compile("</?\w+>")
text = tags.sub('', text)
return text | 1770ad49ec992df949725c9595f48e93188dc0e8 | 20,705 |
def serializer_is_dirty(preference_serializer):
"""
Return True if saving the supplied (Raw)UserPreferenceSerializer would change the database.
"""
return (
preference_serializer.instance is None or
preference_serializer.instance.value != preference_serializer.validated_data['value']
) | 19ce15215a13e96020e0503c28930525d6243330 | 20,711 |
import json
import requests
def adjust_led(state_irgb):
"""
Sends a request to the arduino to adjust the leds.
"""
state = state_irgb.split()[0]
irgb = state_irgb.split()[1].upper()
url = f"http://192.168.1.188/led?state={state};irgb={irgb};"
return json.loads(requests.get(url).text) | 8330842295b0bb3dcfb99085fb9d27e18b12c8a0 | 20,713 |
import re
def isfloat(word):
"""Matches ANY number; it can be a decimal, scientific notation, integer, or what have you"""
return re.match('^[-+]?[0-9]*\.?[0-9]*([eEdD][-+]?[0-9]+)?$',word) | 8df3be23d1e39590c88fb0e8de275571b0ec4c57 | 20,715 |
def safestart(text: str, piece: str, lc: bool = False) -> bool:
"""
Checks if text starts with another, safely
:param text: the string to check
:param piece: the start string
:return: true if text starts with piece
"""
check = text if lc else text.lower()
return len(text) >= len(piece) and check.startswith(piece) | 9bdefe01f97be4660b11ed4ce36b08da410680e3 | 20,723 |
def onecase(case):
"""Check if the binary string is all ones"""
if case == "1" * len(case):
return True
else:
return False | d21bbf34960abcf3eafe6f0b4271ea9054d3e77f | 20,725 |
def get_chosen_df(processed_cycler_run, diag_pos):
"""
This function narrows your data down to a dataframe that contains only the diagnostic cycle number you
are interested in.
Args:
processed_cycler_run (beep.structure.ProcessedCyclerRun)
diag_pos (int): diagnostic cycle occurence for a specific <diagnostic_cycle_type>. e.g.
if rpt_0.2C, occurs at cycle_index = [2, 37, 142, 244 ...], <diag_pos>=0 would correspond to cycle_index 2.
Returns:
a datarame that only has the diagnostic cycle you are interested in, and there is a column called
'diagnostic_time[h]' starting from 0 for this dataframe.
"""
data = processed_cycler_run.diagnostic_interpolated
hppc_cycle = data.loc[data.cycle_type == "hppc"]
hppc_cycle = hppc_cycle.loc[hppc_cycle.current.notna()]
cycles = hppc_cycle.cycle_index.unique()
diag_num = cycles[diag_pos]
selected_diag_df = hppc_cycle.loc[hppc_cycle.cycle_index == diag_num]
selected_diag_df = selected_diag_df.sort_values(by="test_time")
selected_diag_df["diagnostic_time"] = (selected_diag_df.test_time - selected_diag_df.test_time.min()) / 3600
return selected_diag_df | b09abfdc3a9b1fa7836f548d6c40ca7845321418 | 20,729 |
def hms_to_sec(hms):
"""
Converts a given half-min-sec iterable to a unique second value.
Parameters
----------
hms : Iterable (tuple, list, array, ...)
A pack of half-min-sec values. This may be a tuple (10, 5, 2), list
[10, 5, 2], ndarray, and so on
Returns
-------
out : scalar (int, float, ...) depending on the input values.
Unique second value.
"""
h, m, s = hms
return 3000 * h + 60 * m + s | 9da83a9487bfe855890d5ffd4429914439f4b28b | 20,733 |
def easeInOutQuad(t, b, c, d):
"""Robert Penner easing function examples at: http://gizma.com/easing/
t = current time in frames or whatever unit
b = beginning/start value
c = change in value
d = duration
"""
t /= d/2
if t < 1:
return c/2*t*t + b
t-=1
return -c/2 * (t*(t-2) - 1) + b | a4ae2cc0b2c03a499bee456a08bdada023570361 | 20,736 |
def higlight_row(string):
"""
When hovering hover label, highlight corresponding row in table,
using label column.
"""
index = string["points"][0]["customdata"]
return [
{
"if": {"filter_query": "{label} eq %d" % index},
"backgroundColor": "#3D9970",
"color": "white",
}
] | c4473cf2d41b4ef7df6d08048dd6f9fe8f5d4099 | 20,742 |
def get_dict_value(key, data):
"""Return data[key] with improved KeyError."""
try:
return data[key]
except (KeyError, TypeError):
raise KeyError("No key [%s] in [%s]" % (key, data)) | 166656c226bb7a846c7c63f6d8d07ab7ee1a81f9 | 20,744 |
def list_to_string(s, separator='-'):
"""
Convert a list of numeric types to a string with the same information.
Arguments
---------
s : list of integers
separator : a placeholder between strings
Returns
-------
string
Example
-------
>>> list_to_string( [0,1], "-" )
"""
str1 = ""
for ele in s:
str1 += (separator+str(ele))
return str1 | bf926cbc87895fe820d5de8c206f499f9558eefd | 20,746 |
import functools
def cached_method(cache_size=100):
"""
Decorator to cache the output of class method by its positional arguments
Up tp 'cache_size' values are cached per method and entries are remvoed in a FIFO order
"""
def decorator(fn):
@functools.wraps(fn)
def wrapper(self, *args, **kwargs):
_dict = self._cached_methods[fn.__name__]
if args in _dict:
return _dict[args]
res = fn(self, *args, **kwargs)
if len(_dict) >= cache_size:
_dict.popitem(False)
_dict[args] = res
return res
return wrapper
return decorator | 3e580dc984373d3a19fd37a7c195ee3c4842d8b3 | 20,748 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.