content stringlengths 42 6.51k |
|---|
def trim_description(desc: str, n_words: int) -> str:
"""Return the first `n_words` words of description `desc`/"""
return " ".join(str(desc).split(" ")[0:n_words]) |
def same_spot_check(moves):
"""validate that two cars are not going to the same spot"""
movesaccepted = True
for move in moves:
if move['movestatus']=='rejected':
continue
for other_move in moves:
if (other_move['movestatus']=='rejected') or (
other_mo... |
def obj_to_dict(obj):
"""Converts XML object to an easy to use dict."""
if obj is None:
return None
res = {}
res['type'] = obj.tag
res['id'] = int(obj.get('id'))
res['version'] = int(obj.get('version'))
res['deleted'] = obj.get('visible') == 'false'
if obj.tag == 'node' and 'lon'... |
def hue(p):
"""
Returns the saturation of a pixel.
Gray pixels have saturation 0.
:param p: A tuple of (R,G,B) values
:return: A saturation value between 0 and 360
"""
min_c = min(p)
max_c = max(p)
d = float(max_c - min_c)
if d == 0:
return 0
if max_c == p[0]:
... |
def _destupidize_dict(mylist):
"""The opposite of _stupidize_dict()"""
output = {}
for item in mylist:
output[item['key']] = item['value']
return output |
def cost_function(pos_neg, off_on):
"""
Cost function for a sequence of control messages, lower is better.
:param pos_neg: count of forward<->reverse transitions, cost=10
:param off_on: count of off->on transitions, cost=5
:return: cost
"""
return 10 * pos_neg + 5 * off_on |
def values(dictionaries, key):
"""
Go through the list of dictionaries and add all values of a certain key
to a list.
"""
value_list = []
for item in dictionaries:
if isinstance(item, dict) and key in item:
if item[key] not in value_list:
value_list.append(ite... |
def quote(s):
"""
Quotes a string if it needs it
"""
if " " in s:
return "\"" + s + "\""
else:
return s |
def url_path_join(*pieces):
"""Join components into a relative url.
Use to prevent double slash when joining subpath. This will leave the
initial and final / in place.
Code based on Jupyter notebook `url_path_join`.
"""
initial = pieces[0].startswith('/')
final = pieces[-1].endswit... |
def g(n):
"""Return the value of G(n), computed recursively.
>>> g(1)
1
>>> g(2)
2
>>> g(3)
3
>>> g(4)
10
>>> g(5)
22
"""
"*** YOUR CODE HERE ***"
if n <= 3:
return n
else:
return g(n - 1) + 2 * g(n - 2) + 3 * g(n - 3) |
def stateVec2stateIndex(sigma,N,typ = 1):
"""
Returns the index m that corresponds to the binary vector sigma_0, where m is a int between 0 and 2**N
typ determins if the neuron activation state is defined in {-1,1} or {0,1}
typ=1 --> {-1,1} typ=0 --> {0,1}
"""
k=int(0)
for i in range(0,... |
def description(d, i, r):
"""Get the description from the item.
:param d: Report definition
:type d: Dict
:param i: Item definition
:type i: Dict
:param r: Meter reading
:type r: usage.reading.Reading
:return: Description from item
:rtype: String
"""
return i.get('descriptio... |
def _GenericRetrieve(root, default, path):
"""Given a list of dictionary keys |path| and a tree of dicts |root|, find
value at path, or return |default| if any of the path doesn't exist."""
if not root:
return default
if not path:
return root
return _GenericRetrieve(root.get(path[0]), default, ... |
def areaTriangle(base: float, height: float) -> float:
"""Finds area of triangle"""
area: float = (height * base) / 2
return area |
def rx_band(freq):
"""
Associate a waveguide band with a frequency
"""
# Which front end channel is this for?
if freq < 2000.:
band = 'L'
elif freq < 5000.:
band = 'S'
elif freq < 10000.:
band = 'X'
elif freq < 40000.:
band = 'Ka'
else:
band = None
return band |
def name_from_canonical_parts(prefix, controller, action, args=None):
"""
Returns the route's name ('admin-users-edit') from the canonical
parts ('admin','users','edit')
"""
route_parts = [prefix, controller, action]
route_parts = [x for x in route_parts if x]
route_name = ':'.join(route_par... |
def get_inplace_score(arr):
"""Reward based on position of item"""
score = 0
for i, val in enumerate(arr):
score += 1 if i == val else 0
return score |
def format_field_display(fields):
"""format the display of missing fields"""
num_fields = len(fields)
if num_fields == 1:
return fields[0]
if num_fields == 2:
return "{} and {}".format(fields[-2], fields[-1])
# field length greater than 2
return "{} and {}".format(", ".join(field... |
def calc_luminance(cos_a, cos_b, cos_phi, cos_theta, sin_a, sin_b, sin_phi, sin_theta):
"""
Luminance should be equal to:
cosphi*costheta*sinB - cosA*costheta*sinphi -
sinA*sintheta + cosB*(cosA*sintheta - costheta*sinA*sinphi);
:param cos_a:
:param cos_b:
:param cos_phi:
:param cos_thet... |
def calculate_s_upper(len_of_auction: float,
quantity_auctioned: int,
l: float,
pa: float) -> float:
"""
Summary line.
Extended description of function.
Parameters
----------
len_of_auction: description
quantity_auctioned: d... |
def case_name_to_folder(name):
"""Convert name of case to case folder."""
return name.replace('/', '_') |
def singleline_diff_format(line1, line2, idx):
"""
Inputs:
line1 - first single line string
line2 - second single line string
idx - index of first difference between the lines
Output:
Returns a three line formatted string showing the location
of the first difference between l... |
def lookup_charset(in_charset_name):
""" Provides some additional aliases for text encoding names. """
out_charset_name = in_charset_name
if out_charset_name is not None:
out_charset_name = out_charset_name.lower()
out_charset_name = out_charset_name.replace("-", "_")
if out_charset_... |
def verbosityTranslator(marlinLogLevel):
"""Translate the verbosity level from Marlin to a Gaudi level.
Marlin log level can end with numbers, e.g., MESSAGE4
"""
logLevelDict = {'DEBUG': 'DEBUG',
'MESSAGE': 'INFO',
'WARNING': 'WARNING',
'ERROR': 'ERROR',
... |
def is_vcf_chrom_header(line):
"""
Returns ``True`` if ``line`` is a VCF chrom-definition header line, ``False`` otherwise.
:param line: line from VCF file
:return: ``bool``
"""
if line.startswith('##contig='):
return True
else:
return False |
def create_buckets(lower_bound, upper_bound, bins):
"""
Create a dictionary with bins
:param lower_bound: low range
:param upper_bound: high range
:param bins: number of buckets
:return:
"""
range_value = (upper_bound - lower_bound) / bins
low = lower_bound
buckets = []
if ... |
def generate_paths(source):
"""
Generate full paths for nested dictionary or alike object
:param source: Input object
:return: List of paths
"""
paths = []
if isinstance(source, dict):
for k, v in source.items():
paths.append([k])
paths += [[k] + x for x in ge... |
def count_construct_rec(target, word_bank):
"""Counts the number of ways that 'target' can be constructed.
Args:
target (str): The string to be constructed.
word_bank (Iterable[str]): Collection of string from which 'target'
can be constructed.
Returns:
int: The number ... |
def word(a):
"""
This function turns the_word into dashed-word.
:param a: str, a random word chose from the function random_word()
:return: str, the random word as a dashed word.
"""
ans = ''
for i in range(len(a)):
ans += '-'
return ans |
def convert_arg_to_int(cmd_args):
"""Convert str to int as much as possible
:param cmd_args: the sequence of args
:return the sequence of args
"""
args = []
for arg in cmd_args:
if isinstance(arg, str): # Int will cause TypeError
try:
arg = int(arg, 0)
... |
def get_file_name(suffix=""):
"""Return report file name with date appended."""
return "hwsurvey-weekly" + suffix + ".json" |
def _get_tensor_name(node_name, output_slot):
"""Get tensor name given node name and output slot index.
Args:
node_name: Name of the node that outputs the tensor, as a string.
output_slot: Output slot index of the tensor, as an integer.
Returns:
Name of the tensor, as a string.
"""
return "%s:%... |
def find_grey_code_bits(num_bits):
"""
Takes in the number of bits and returns a list of unique grey code combinations
"""
if type(num_bits) is not int:
return None
if num_bits <= 0:
return []
final_bits = []
initial_bit = "0" * num_bits
length = 2 if num_bits is 1 else ... |
def calculate_delays_between_slaves(load_chunks, delay_per_req):
""" Calculate amount of delay to insert between slave invocations"""
delays = []
for chunk in load_chunks:
num_reqs = len(chunk)
delay_for_this_slave = delay_per_req * num_reqs
delays.append(delay_for_this_slave)
re... |
def clamp(minimum: float, value: float, maximum: float) -> float:
"""Clamp value between given minimum and maximum."""
return max(minimum, min(value, maximum)) |
def sort_dict_keys_by_date(dict_in):
"""dict_in should have a structure dict_in[some_key]["datetime"]; this function
will return a list of some_key.s ordered by the content of the "datetime" entry
under it."""
list_key_datetime = []
for crrt_key in dict_in:
crrt_datetime = dict_in[crrt_key]... |
def calculate_theory_score(user_answers, actual_answers):
""" Takes 2 dictionaries and compares them for
differences. The result is a percentage and the incorrect answers
"""
total = len(actual_answers)
correct = 0
incorrect_answers = {}
for k in actual_answers.keys():
#If there is... |
def d_sig(f): # pragma: no cover
"""
Calculates the derivative of a sigmoid function
"""
return f * (1 - f) |
def merge_clause_merge_properties(merge_properties):
"""
{sid: properties.sid}
:param merge_properties: The merge properties
:return:
"""
merge_strings = []
for u in merge_properties:
merge_strings.append("{0}: properties.{0}".format(u))
merge_string = ', '.join(merge_strings)
... |
def validate_tag(string):
""" Extracts a single tag in key[=value] format """
result = {}
if string:
comps = string.split('=', 1)
result = {comps[0]: comps[1]} if len(comps) > 1 else {string: ''}
return result |
def average_error(decay_constant: float, num_qubits: int = 1) -> float:
"""Calculates the average error from the depolarization decay constant.
Args:
decay_constant: Depolarization decay constant.
num_qubits: Number of qubits.
Returns:
Calculated average error.
"""
N = 2 **... |
def compare_ri_param(registers, params):
"""Return from registers register/immediate parameters for compare."""
return registers[params[0]], params[1], params[2] |
def leap_year(year):
"""
checks year parameter to see if the given year is a leap year.
:param year: accepts INT between 0-9999
:return: BOOLEAN True or False
"""
if year % 400 == 0:
return True
elif year % 100 == 0:
return False
elif year % 4 == 0:
r... |
def check_for_sudoku_success(sudo_list):
"""Check for success of SUDOKU list of list"""
sudo_col_list = []
for row_lst in sudo_list:
if "".join(sorted(row_lst)) != "123456789":
return False
for col_index in range(0, 9):
col_lst = [item[col_index] for item in sudo_list]
... |
def ensure_scripts(linux_scripts):
"""Creates the proper script names required for each platform
(taken from 4Suite)
"""
from distutils import util
if util.get_platform()[:3] == 'win':
scripts_ = [script + '.bat' for script in linux_scripts]
else:
scripts_ = linux_scripts
ret... |
def staying_alive_reward(nobs, agent_id):
"""
Return a reward if the agent with the given id is alive.
:param nobs: The game state
:param agent_id: The agent to check
:return: The reward for staying alive
"""
#print(nobs[0]['position'][0])
if agent_id in nobs[0]['alive']:
retur... |
def distance(strand_a, strand_b):
"""Return the hamming distance of given strands of DNA"""
if len(strand_a) != len(strand_b):
raise ValueError("Strand length doesn't match")
return sum(1 for a,b in zip(strand_a, strand_b) if a != b) |
def _wsURL(url):
"""internal"""
return "/1.0/" + url |
def change_label2idx(train_meta, label2idx={}):
""" change label to index
Parameters
----------
train_meta
label2idx
Returns
-------
"""
for name, train in train_meta.items():
for i, vs in enumerate(train):
train_meta[name][i] = (vs[0], vs[1], vs[2], label2idx[... |
def decode_varint(buffer, pos=0):
""" Decode an integer from a varint presentation. See
https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints
on how those can be produced.
Arguments:
buffer (bytearry): buffer to read from.
pos (int): optional position to... |
def int_to_padded_hex_byte(integer):
"""
Convert an int to a 0-padded hex byte string
example: 65 == 41, 10 == 0A
Returns: The hex byte as string (ex: "0C")
"""
to_hex = hex(integer)
xpos = to_hex.find('x')
hex_byte = to_hex[xpos+1 : len(to_hex)].upper()
if len(hex_byte)... |
def center_move(possible_moves):
"""A player marks the center.
>>> center_move([2, 5, 8])
>>> 5
"""
if 5 in possible_moves:
return 5 |
def check_sofware_if_exists(package_name, package_names, packages):
""" A function to check if the package exists already in the json
:returns none if doesn't exist
:returns package already defined if exists
"""
# If we already have the package
if package_name in package_names:
for temp_... |
def make_new_get_user_response(row):
""" Returns an object containing only what needs to be sent back to the user. """
return {
'userName': row['userName'],
'categories': row['categories'],
'imageName': row['imageName'],
'refToImage': row['refToImage'],
... |
def find_replace(search_dict, field_value, replace=None):
"""
Takes a dict with nested lists and dicts,
and searches all dicts for a value of the field
provided, replacing if desired.
"""
fields_found = []
for key, value in search_dict.items():
if value == field_value:
... |
def in_green(s: str) -> str:
"""Return string formatted in red."""
return f"\033[92m{str(s)}\033[0m" |
def build_data_pipeline(chain, **kwargs):
"""
Chain of responsibility pattern
:param chain: array of callable
:param **kwargs: any kwargs you like
"""
kwargdict = kwargs
for call in chain:
kwargdict = call(**kwargdict)
return kwargdict |
def concatenate_payload_settings(settings):
"""Takes a list of dictionaries, removed duplicate entries and concatenates an array of settings for the same key
"""
settings_list = []
settings_dict = {}
for item in settings:
for key, value in item.items():
if isinstance(value, list)... |
def schema_to_json(schema: dict, indent: int = 2) -> str:
"""Convert the given JSON schema (dict) into a JSON string."""
import json
return json.dumps(schema, indent=indent) |
def dflt_label_weighter(test_label, gold_label):
"""
Return score corresponding to the weight to add for matching
test_label and gold_label in the default Smatch setting.
"""
if test_label.lower() == gold_label.lower():
return 1.0
else:
return 0.0 |
def func_namespace(func):
"""Generates a unique namespace for a function"""
kls = None
if hasattr(func, 'im_func'):
kls = func.im_class
func = func.im_func
if kls:
return '%s.%s' % (kls.__module__, kls.__name__)
else:
return func.__module__ |
def translate_severity(sev):
"""
Translates Prisma Cloud Compute alert severity into Demisto's severity score
"""
sev = sev.capitalize()
if sev == 'Critical':
return 4
elif sev == 'High':
return 3
elif sev == 'Important':
return 3
elif sev == 'Medium':
r... |
def len_float_or_list(var):
"""
Helper function for handling cases where only one epoch was run.
These abnormal cases result in a float instead of a list, hence len() would create an exception.
"""
if type(var) == list:
return len(var)
elif type(var) == float:
return 1
... |
def arange(a, b, inc=1):
"""
Generate an array of integers from (a, b) with increment of inc
@param a int start of range (inclusive)
@param b int end of range (inclusive)
@param inc float
"""
x = [a]
i = 0
while x[i]+inc <= b:
x.append(x[i]+inc)
i += 1
return x |
def get_bounds(points):
"""
return bounding box of a list of gpxpy points
"""
min_lat = None
max_lat = None
min_lon = None
max_lon = None
min_ele = None
max_ele = None
for point in points:
if min_lat is None or point.latitude < min_lat:
min_lat = point.latitu... |
def isnan(x):
"""Is x 'Not a Number'? fail-safe version"""
from numpy import isnan
try: return isnan(x)
except: return True |
def greedyAdvisor(subjects, maxWork, comparator):
"""
Returns a dictionary mapping subject name to (value, work) which includes
subjects selected by the algorithm, such that the total work of subjects in
the dictionary is not greater than maxWork. The subjects are chosen using
a greedy algorithm. ... |
def replace_spaces_list(s):
"""In-place replacement using a list."""
n = len(s)
if n == 0:
return s
s_list = list(s)
old = ' '
new = list('%20')
i = 0
while i < n:
if s_list[i] == old:
# Shift right two characters
s_list.extend(['', ''])
... |
def get_version_tag(api_major):
"""Args:
api_major: int DataONE API major version. Valid versions are currently 1 or 2.
Returns: str: DataONE API version tag. Valid version tags are currently ``v1`` or
``v2``.
"""
return "v{}".format(api_major) |
def is_status(byte):
"""Return True if the given byte is a MIDI status byte, False otherwise."""
return (byte & 0x80) == 0x80 |
def find_min(node):
"""Find min value node"""
while node and node.left:
node = node.left
return node |
def column2list(matrix: list, column_idx: int) -> list:
"""
Convert column from features 2D matrix to 1D list of
that feature.
:param matrix: 2D square array of number
:param column_idx: column index in the matrix
:return:
"""
if len(matrix) <= 1:
return matrix if matrix... |
def round_time(time_string, base=5):
"""
Round time to the nearest base so that minute hand on time will look nicer in db
Parameters
----------
time_string: str
minute hand you wish to round: 08 -> 05
base: int
round to the nearest base
"""
rounded = str(base * round(int(... |
def find(haystack, needle):
"""
>>> find("ll", "hello")
-1
>>> find("", "")
0
>>> find("hello", "ll")
2
>>> find("aaaaabba", "bba")
5
>>> find("bbaaaaaa", "bba")
0
>>> find("aaaaa", "bba")
-1
"""
m = len(haystack)
n = len(needle)
if m < n:
retu... |
def remove_es_keys(hit):
"""
Removes ES keys from a hit object in-place
Args:
hit (dict): Elasticsearch hit object
Returns:
dict: modified Elasticsearch hit object
"""
del hit['_id']
if '_type' in hit:
del hit['_type']
return hit |
def is_empty(content: str):
"""
:param content:
:return: is empty
"""
if content is None or len(content.strip()) == 0:
return True
return False |
def is_normal_triple(triples, is_relation_first=False):
"""
normal triples means triples are not over lap in entity.
example [e1,e2,r1, e3,e4,r2]
:param triples
:param is_relation_first
:return:
>>> is_normal_triple([1,2,3, 4,5,0])
True
>>> is_normal_triple([1,2,3, 4,5,3])
True
... |
def create_validator_config(name, options={}): # lint-amnesty, pylint: disable=dangerous-default-value
"""
This function is meant to be used for testing purposes to create validators
easily. It returns a validator config of the form:
{
"NAME": "common.djangoapps.util.password_policy_val... |
def ensure_sequence(obj):
"""If `obj` isn't a tuple or list, return a tuple containing `obj`."""
if isinstance(obj, (tuple, list)):
return obj
else:
return (obj,) |
def change_interface(step):
""" Changes the html.Div of whole page according to the step selected """
if step == 1:
return {'textAlign': 'center'}
else:
return {'display': 'none'} |
def is_self_eating(snake):
"""input must be list or tuple"""
head = snake[0]
for segment in snake[1:]:
if head == segment:
return True
return False |
def get_outer_boundaries(regions, cls, rest_cls):
"""
Assuming rest periods alternate with other classes, find the
outer boundaries of the rest regions enclosing all regions for cls
>>> l = [0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 2, 0, 3, 3, 0, 4]
>>> d = get_regions(l)
>>> get_outer_boundari... |
def make_modifier_resized(target_size):
"""Make a string designating a resize transformation.
Note that the final image size may differ slightly from this size as
it only reflects the size targeted.
Args:
target_size: Target size of rescaling in x,y,z.
Returns:
String... |
def clamp(value, low, high):
"""Returns a value that is no lower than 'low' and no higher than 'high'."""
return max(min(value, high), low) |
def getToken(tokenList, expected):
""" removes the expected token from the token list """
if tokenList[0] == expected:
del tokenList[0]
return True
else:
return False |
def _slider_range_to_slice(range_value_tuple, max):
"""Transform a tuple into a slice accounting for overlapping"""
if range_value_tuple[0] != range_value_tuple[1]:
return slice(*range_value_tuple)
if range_value_tuple[1] != max:
return slice(range_value_tuple[0], range_value_tuple[1]+1)
... |
def second_largest(numbers): #found online, link unavailable
""" return the second highest number of a list"""
count = 0
m1 = m2 = float('-inf')
for x in numbers:
count += 1
if x > m2:
if x >= m1:
m1, m2 = x, m1
else:
m2 = x
ret... |
def decode(data):
"""
Decode byte to string in utf-8
:param data: Byte or str
:return: Decoded string
:raises: TypeError
"""
if isinstance(data, str):
return data
elif isinstance(data, bytes):
return bytes.decode(data)
else:
return str(data) |
def _var_length_field(field: bytes) -> bytes:
"""Returns the message representation of a variable length field
(currently just length + field)"""
if len(field) > 255:
# Length has to be representable by one byte
raise ValueError("Var fields cannot exceed 255 bytes")
return bytes([len(... |
def name_to_id(s):
"""Generate block identifier from url string
Example input:
al/2013/100cm/rgb/30085/m_3008501_ne_16_1_20130928.tif
"""
# cell: 30085
# stem: m_3008501_ne_16_1_20130928.tif
cell, stem = s.split('/')[4:]
# Keep text before date
# m_3008501_ne_16_1_
stem = stem... |
def formatlink(value):
"""
>>> formatlink({'url': 'https://example.com'})
'https://example.com'
>>> formatlink({'url': 'https://example.com', 'title': 'Example'})
'[Example](https://example.com)'
"""
if value.get('title') is None:
return value['url']
return '[{title}]({url})'.f... |
def unique_count(value):
"""Count the number of unique characters in the string representation of a
scalar value.
Parameters
----------
value: scalar
Scalar value in a data stream.
Returns
-------
int
"""
unique = set()
for c in str(value):
unique.add(c)
... |
def transfer_mac(mac):
"""Transfer MAC address format from xxxx.xxxx.xxxx to xx:xx:xx:xx:xx:xx"""
mac = ''.join(mac.split('.'))
rslt = ':'.join([mac[e:e + 2] for e in range(0, 11, 2)])
return rslt |
def move_left(point):
"""Return a copy of `point`, moved left along the X-axis by 1.
This function returns a tuple, not a Vector2D instance, and should only be
used if performance is essential. Otherwise, the recommended alternative is
to write `point + LEFT`.
"""
x, y = point
return x - 1... |
def pythonize_path(path):
""" Replace argument to valid python dotted notation.
ex. foo/bar/baz -> foo.bar.baz
"""
return path.replace('/', '.') |
def f_missing(a, b):
"""Function f
Parameters
----------
a : int
Parameter a
Returns
-------
c : list
Parameter c
"""
c = a + b
return c |
def aa_and(x, y, nx, ny):
"""Dimensionless production rate for a gene regulated by two
activators with AND logic in the absence of leakage.
Parameters
----------
x : float or NumPy array
Concentration of first activator.
y : float or NumPy array
Concentration of second activator... |
def get_resource_id(fhir_instance):
"""
Get the resource id stored in the meta field of a fhir document
"""
try:
return fhir_instance["meta"]["tag"][1]["code"]
except (KeyError, IndexError):
return None |
def get_latest(results):
"""Select the latest results"""
if results:
latest = results[0]
for result in results[1:]:
current_version = result['version'][1:] if 'v' in result['version'] else result['version']
latest_version = latest['version'][1:] if 'v' in latest['version... |
def one_tone_up(freq, amount=1):
"""
Returns the key, one tone up
:param freq: the frequency in hz
:param amount: the amount of tones up
:return: the frequency one tone up in hz
"""
return freq * 2 ** (2 * amount / 12) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.