content stringlengths 42 6.51k |
|---|
def uniquify(seq):
"""
Returns the unique elements of a sequence ``seq``.
"""
#from http://stackoverflow.com/a/480227/1205799
seen = set()
seen_add = seen.add
return [ x for x in seq if x not in seen and not seen_add(x)] |
def preprocess(data_dict):
"""
Preprocess data to use in json file, for instance change strings to floats
or integers for calculations.
Keyword arguments:
data_dict -- a dictionar containing the raw data from the input file.
Outputs a dictionary which is preprocessed and ready to be written to... |
def basis_function_one(degree, knot_vector, span, knot):
""" Computes the value of a basis function for a single parameter.
Implementation of Algorithm 2.4 from The NURBS Book by Piegl & Tiller.
:param degree: degree, :math:`p`
:type degree: int
:param knot_vector: knot vector
:type knot_vecto... |
def read_line(line, key=' '):
"""Split line according to key
Return list of strings"""
str_list = []
str_line = line.split(key)
for el in str_line:
if "\n" in el:
el = el.split('\n')[0]
if not el == '':
str_list.append(el)
return str_list |
def reverse_inputs_if_required(inputs, condition):
"""
Very simple function to reverse a list if requested, but used so frequently during spreadsheet writing that worth
having.
Args:
inputs: A list of the inputs
condition: Boolean for whether to reverse or not
Returns:
The l... |
def total_value(metric):
"""Given a time series of values, sum the values"""
total = 0
for i in metric:
total += i
return total |
def getSound(t, sound, sr=44100, fps=24):
"""
Get part of the sound.
:param t: float - time of the part
:param sound: 1D array - sound data source
:param sr: int - sample rate (total sample per second)
:param fps: int - long of the sound part result is 1/fps
"""
end = t * sr
start = end - (sr / fps)
... |
def be_to_str(data: bytes) -> str:
"""Convert bencoded data from bytes to string"""
result = []
for num in data:
if num < 32 or num in [34, 91, 92, 93] or num > 126:
result.append("[%0.2x]" % num)
else:
result.append(chr(num))
return "".join(result) |
def rejoin_all_final_data(final_data, final_filtered_data):
"""
Takes two dictionaries of final data, one clean and the other filtered, and rejoins them, but with a boolean flag
to denote those that have been flagged.
:param dict final_data: final data as {'comp': (dates, mrs), 'comp2': (dates, mrs)}
... |
def find_markdown_path(line: str):
"""Parse the given string for the path in a markdown image tag"""
path = ''
open_paren_count = 0
for char in line:
if char == '(':
open_paren_count += 1
if char == ')':
open_paren_count -= 1
if open_paren_count > 0:
... |
def make_team(li, n):
"""takes in list of participants length 2-5, outputs formatted match(es)"""
match = {"team_1": [li[0]], "team_2": [li[1]]}
output = {f'match_{n}': match}
if len(li) == 2:
return output
match["team_1"].append(li[2])
if len(li) == 3:
return output
if len(l... |
def list_reverse2(list_in):
"""
:param list_in list:
:return list_out list :
Takes a list a returns a new list that is the reverse of the input
"""
list_out = []
length = len(list_in)
for part in range(length):
list_out.append(list_in[length - 1 - part])
return list_out |
def format_dict(dict_to_format):
"""
Function that formats the passed dictionary
and returns a string
:param dict_to_format: A dict you want to format
:return: String of the keys and values in the dict formatted
:rtype: str
"""
str_to_rtn = "\n-----------------\n"
if not dict_to_f... |
def find_by_key(target: str, data: dict) -> str:
"""
Returns the value of the target key from a nested Python dictionary.
"""
for key, value in data.items():
if isinstance(value, dict):
return find_by_key(target, value)
elif key == target:
return value
return ... |
def hasEmpty(listofElems):
"""
Check if given list contains any empty
"""
for i in listofElems:
if i == "":
return True
return False |
def build_everything_else_cell(cell_num, surface_num, comment):
"""Create a cell which encompasses everything outside an assembly/core."""
cell_card = "{} 0 {} imp:n=0 {}".format(cell_num, surface_num, comment)
assert (len(cell_card) - len(comment)) < 80
return cell_card |
def globs(test):
"""
Return the globals for *test*, which can be a `doctest`
or a regular `unittest.TestCase`.
"""
try:
return test.globs
except AttributeError:
return test.__dict__ |
def rev_comp(s):
"""A simple reverse complement implementation working on strings
Args:
s (string): a DNA sequence (IUPAC, can be ambiguous)
Returns:
list: reverse complement of the input sequence
"""
bases = {
"a": "t", "c": "g", "g": "c", "t": "a", "y": "r", "r": "y", "w"... |
def is_unique2(s):
"""
Use a list and the int of the character will tell if that character has
already appeared once
"""
d = []
for t in s:
if d[int(t)]:
return False
d[int(t)] = True
return True |
def prefer_end_of_sorted_list(mb):
"""When all eles fails, prefer the end of the sorted list."""
for aa in mb:
aa.sort()
mb.sort()
return [mb[-1]] |
def get_data_field(thing_description, data_field_list):
"""Get the field specified by 'data_field_list' from each thing description
Args:
data_field_list(list): list of str that specified the hierarchical field names
For example, if the parameter value is ['foo', 'bar', 'foobar'], then this... |
def _construct_key(previous_key, separator, new_key):
"""
Returns the new_key if no previous key exists, otherwise concatenates
previous key, separator, and new_key
:param previous_key:
:param separator:
:param new_key:
:return: a string if previous_key exists and simply passes through the
... |
def GenerateNextInRange(range, prev=None):
"""Generates next value in range.
Args:
range: dict, A range descriptor:
{start: Value, stop: Value, opt step: Value}
prev: int or float or None, A previous value or None.
Returns:
int or float, Random value.
"""
start = range['start']
if prev is... |
def factors(n):
"""
"""
da_factors = []
for f in [f for f in range(1, int(n**0.5) + 1) if n % f == 0]:
da_factors.extend([f, n//f])
return set(da_factors) |
def conv_c2f(c):
"""
Convert Celsius to Fahrenheit
:param c: Temperature in Celsius
:type c: float
:return: Temperature in Fahrenheit
:rtype: float
:Example:
>>> import hygrometry
>>> hygrometry.conv_c2f(21.111128)
70.0000304
"""
return c*1.8+32.0 |
def _to_yaml_tags(wrapped, instance, args, kwargs):
"""
New in v17
public decorator for yaml generator
"""
return wrapped(*args, **kwargs) |
def eformat(f, prec, exp_digits):
"""
reformats wavelength into scientific notation in meters
:param f: wavelength float
:param prec: precision
:param exp_digits: number of digits in the exponent
:return:
"""
s = "%.*e" % (prec, f)
mantissa, exp = s.split('e')
# add 1 to digits ... |
def path_downward(start, end, path=None):
"""
Returns a list of paths (if they exist) from an ancestor (start)
to a descentdant (end).
:param start: The individual at the start of the path
:param end: The individual to be found
:path: a path to append to
:returns: A list of individuals... |
def _join_and_groups(items):
"""
"-OR-" items separate the items that have to be grouped with an "AND" clause
This function groups items from a same "AND group" with commas
"""
indexes = [k for k, v in enumerate(items) if v == '-OR-']
next_group = 0
groups = []
for i in indexes:
... |
def next(some_list, current_index):
"""
Returns the next element of the list using the current index if it exists.
Otherwise returns an empty string.
"""
try:
return some_list[int(current_index) + 1] # access the next element
except Exception:
return '' |
def temperature_converter(f_temp):
"""
>>> temperature_converter(32)
0.0
"""
celsius_temp = (f_temp-32)*5/9
return celsius_temp |
def vertical_move(t, v_speed=2/320):
"""Probe moves vertically at v_speed [cm/s]"""
return 0.*t, 0*t, v_speed*t |
def get_component_name(obj):
"""
Return the human-readable name of the class of `obj`.
Document the type of a config field and can be used as a Union value
in a json config.
"""
if obj is type(None):
return None
if not hasattr(obj, "__module__"): # builtins
retur... |
def anagram_iter(s1, s2):
"""Anagram by iteration.
Time complexity: O(n^2).
Space complexity: O(n).
"""
if len(s1) != len(s2):
return False
# Make list of s2 for search memoization.
l2 = list(s2)
for c1 in s1:
is_found = False
for i2, c2 in enumerate(s2):
... |
def get_inverse_annotation(regions):
"""
Get a data structure similar to `regions`, however with the inverse regions defined.
Assume that counting starts on 1.
"""
regions_inverse = {}
for id, region in regions.items():
regions_inverse[id] = []
start = 1
for i in region:
... |
def build_url_parameters_for_change_list_filtering(queryset, field_key_pairs):
"""
Builds a URL query of key-value pairs for each field of the form:
.. code-block:: xml
<field>=<value>,...,<value> (i.e. 'UserID=1,2,3')
"""
query = '?'
for f in field_key_pairs:
values = [str(v) ... |
def SceneMatch(comp):
"""
Summary : This functions compares a list to scene with
typo handling
Parameters : comparison list
Return : Boolean
"""
for item in comp:
try:
item = item.lower()
except:
continue
if item == 'scen... |
def zero(m, n):
"""
Create zero matrix of dimension m,n
:param m: integer
:param n: integer
>>> zero(5, 3)
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
"""
new_matrix = [[0 for row in range(n)] for col in range(m)] # @UnusedVariable
return new_matrix |
def first_missing_positive(nums):
"""
:type nums: List[int]
:rtype: int
Basic idea:
1. for any array whose length is l, the first missing positive must be in range [1,...,l+1],
so we only have to care about those elements in this range and remove the rest.
2. we can use the array index ... |
def merge_tupls(tupl1, tupl2):
"""
Takes two tuples and returns a new tuple of
their min and max, assumes range (low,high)
Parameters:
tupl1, tupl2 - a tuple range
"""
return (min(tupl1[0],tupl2[0]),max(tupl1[1],tupl2[1])) |
def is_int(s):
"""return True or False if input string is integer or not."""
try:
int(s)
return True
except (ValueError, TypeError):
return False |
def channel_name(channel):
"""Get IRC channel name.
:channel: channel name without #
:returns: channel name with #
"""
return "#%s" % channel if not channel.startswith('#') else channel |
def string_to_number(x):
"""Suppose you want to determine whether an arbitrary text string can be
converted to a number. Write a function that uses a try/except clause to solve
this problem. Can you think of another way to solve this problem?"""
try:
return int(x)
except ValueError as e:
... |
def cpufy(tensor_iter):
""" Takes a list of tensors and safely pushes them back onto the cpu"""
return [_.cpu() for _ in tensor_iter] |
def merge_dicts(*dict_args):
"""Merge given dicts into a new dict.
Examples::
>>> merge_dicts({"a": 1, "b": 2}, {"c": 3, "b": 20}, {"d": 4})
{'a': 1, 'b': 20, 'c': 3, 'd': 4}
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result |
def gcd(x, y):
"""
Question 22.1: Find the greatest common divisor
of two numbers without using multiplication,
division, or the modulus operator
:return:
"""
if x == y:
return x
elif not (x & 1) and not (y & 1):
# x even, y even
return gcd(x >> 1, y >> 1) << 1
... |
def _get_graph_act_qubits(graph):
"""Get all acted qubits."""
nodes = set()
for node in graph:
nodes |= set(node)
nodes = list(nodes)
return sorted(nodes) |
def binary_to_decimal(binarybits):
""" Convert binary bits to decimal"""
# helps during list access
decimal = int(binarybits, 2)
return decimal |
def minimal_community(community_owner):
"""Minimal community data as dict coming from the external world."""
return {
"id": "comm_id",
"access": {
"visibility": "public",
},
"metadata": {
"title": "Title",
"type": "topic"
}
} |
def in_tcltk_website(text):
"""Receives the tcltk website text string and returns the range where the colors are written."""
start = text.find('<PRE>') + len('<PRE>')
end = text.find('</PRE>')
colors = text[start:end]
return colors |
def get_bits_from_int(val_int, val_size=16):
"""Get the list of bits of val_int integer (default size is 16 bits)
Return bits list, least significant bit first. Use list.reverse() if
need.
:param val_int: integer value
:type val_int: int
:param val_size: bit size of integer... |
def recursive_tuple(data):
"""Convert nested lists/dicts into tuples for structural comparing"""
if isinstance(data, (list, tuple)):
return tuple(recursive_tuple(x) for x in data)
elif isinstance(data, dict):
# We cannot use plain tuple(sorted(...)) here, because while it works giving us sta... |
def _str(value):
"""Returns the value formatted as a string"""
if value == 0:
return '-'
else:
return r'{}\%'.format(value) |
def pyfuncstring_to_tex(pyfuncstr):
"""
Placeholder - we'd like to fill this out later. This should be a function that takes a short string representing a
python funciton and translates it to latex. e.g.
pyfuncstring_to_text 'x**1.5/4' -> x^{1.5}/4
:param pyfuncstr: A string representing a p... |
def ccw(a, b, c):
"""Tests whether the turn formed by A, B, and C is ccw"""
return (b[0] - a[0]) * (c[1] - a[1]) > (b[1] - a[1]) * (c[0] - a[0]) |
def monomial_divides(A, B):
"""
Does there exist a monomial X such that XA == B?
>>> from sympy.polys.monomialtools import monomial_divides
>>> monomial_divides((1, 2), (3, 4))
True
>>> monomial_divides((1, 2), (0, 2))
False
"""
return all(a <= b for a, b in zip(A, B)) |
def transform_bbox_square(bbox, slack=1):
"""
Transforms a bounding box anchored at top left corner of shape () to a square with
edge length being the larger of the bounding box's height or width.
Only supports square aspect ratios currently.
## Parameters
bbox : {tuple or... |
def uint_to_string(uint, both=False):
""" Prints uint in readable form
"""
if both:
return hex(uint) + ' (' + repr(uint) + ')'
return hex(uint) |
def underscore_to_uppercase(dict_to_edit):
"""
This function convert underscore convention to uppercase convention
input: dictionary
output: dictionary with uppercase convention
"""
if not isinstance(dict_to_edit, (dict, list)):
return dict_to_edit
if isinstance(dict_to_edit, list):
... |
def iss(text: str) -> bool:
"""
:param text: string to test
:return: true if text is at lease one non-whitespace character
"""
if text is None:
return False
if (len(text) == 0) or (text.strip() == ""):
return False
return True |
def es_subcadena(adn1, adn2):
"""
(str, str) -> bool
Funcion que retorna la subcadena de una cadena
>>> es_subcadena('ATCTTA', 'ATC')
True
>>> es_subcadena('TCGA', 'AAT')
False
:param adn1: str Primer Cadena
:param adn2: str Segunda Cadena
:return: Retorna la subcadena de la pri... |
def str2bool(v):
"""From https://github.com/amdegroot/ssd.pytorch"""
return v.lower() in ("yes", "true", "t", "1") |
def remap(x, in_min, in_max, out_min, out_max):
"""
Scale x from range [in_min, in_max] to [out_min, out_max]
Based on this StackOverflow answer: https://stackoverflow.com/a/43567380/2260
"""
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min |
def is_filename_char(x):
"""Return True if x is an acceptable filename character."""
if x.isalnum():
return True
if x in ['-', '_']:
return True
return False |
def condition_1(x):
"""
>>> condition_1('b')
False
"""
if 'be' not in x and 'ba' not in x and 'bu' not in x:
return True
else:
return False |
def filter_by_tag(tests,tag):
"""Return a list of tests filtered by a tag
Keyword arguments:
tests -- list of tests
tag -- the considered tag
"""
return [x for x in tests if tag in x.get("tags",[])] |
def findDuplicate(nums):
"""
:type nums: List[int]
:rtype: int
"""
set_array = list(set(nums))
if set_array == nums:
return None
else:
sorted_nums = sorted(nums)
for x in range(0, len(sorted_nums)):
if x <= len(... |
def human_size(bytes, units=[' bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB']):
""" Returns a human readable string reprentation of bytes"""
return str(bytes) + units[0] if bytes < 1024 else human_size(bytes >> 10, units[1:]) |
def check_enter(user_input):
"""Accepts no input (= Enter) and skip"""
if user_input in ['', 'skip']:
return True
return False |
def get_datetime_string(datetime):
"""
Given a datetime object, return a human readable string (e.g 05/21/2014 11:12 AM)
"""
try:
if datetime is not None:
return datetime.strftime("%m/%d/%Y %I:%M %p")
return None
except:
return None |
def division(x,y):
"""Return result of division"""
try:
return x/y
except ZeroDivisionError:
print("Division by zero") |
def dict_filter(indict, key_list):
"""Filter dictionary according to specified keys."""
return dict((key, value) for key, value in list(indict.items()) if key in key_list) |
def encode_cookies(string_to_encode: str) -> str:
"""
Decode the utf-8 string, and encode it to latin-1.
Args:
string_to_encode: string to encode
Returns:
str: encoded string
"""
return string_to_encode.encode('utf-8').decode('latin-1') |
def _get_displayed_page_numbers(current, final):
"""
This utility function determines a list of page numbers to display.
This gives us a nice contextually relevant set of page numbers.
For example:
current=14, final=16 -> [1, None, 13, 14, 15, 16]
This implementation gives one page to each side ... |
def rot_char(character, n):
"""Rot-n for a single character"""
if character.islower():
return chr(((ord(character)-97+n)%26)+97)
elif character.isupper():
return chr(((ord(character)-65+n)%26)+65)
else:
return character |
def normalizeXRI(xri):
"""Normalize an XRI, stripping its scheme if present"""
if xri.startswith("xri://"):
xri = xri[6:]
return xri |
def convert_weight(val, old_scale="kg", new_scale="pound"):
"""
Convert from a weight scale to another one among kg, gram, and pound.
Parameters
----------
val: float or int
Value of the weight to be converted expressed in the original scale.
old_scale: str
Original scale from ... |
def j_to_paths(path_list):
""" A helper function to retrieve a candidate paths dictionary from JSON.
Parameters
----------
path_list : list
a list of dictionaries, each representing a JSON path candidate
object with from, to, and paths keywords.
Returns
... |
def get_border(border, size):
"""
Get border
"""
i = 1
while size - border // i <= border // i: # size > 2 * (border // i)
i *= 2
return border // i |
def merge_tuples(*tuples):
"""
Utility method to merge a number of tuples into a list.
To aid output, this also converts numbers into strings for easy output
:param tuples:
:return: List[String]
"""
return [str(j) for i in tuples for j in (i if isinstance(i, tuple) else (i,))] |
def func1(a):
"""
This should fail mutation testing (we don't test edge cases of a=5, a=6)
>>> func1(4)
False
>>> func1(8)
True
"""
if a > 5:
return True
return False |
def normalize_value(val):
"""
Normalize strings with booleans into Python types.
"""
if val is not None:
if val.lower() == 'false':
val = False
elif val.lower() == 'true':
val = True
return val |
def skip_n_lines_in_file(file_path, num_lines):
"""
Remove the initial num_lines of text from a file.
:param file_path: The path to the file that needs initial lines removed.
:param num_lines: The number of initial text lines to remove from the file
at file_path.
:return: The ... |
def normalize_weekly(data):
"""
Normalization for dining menu data
"""
if "tblMenu" not in data["result_data"]["Document"]:
data["result_data"]["Document"]["tblMenu"] = []
if isinstance(data["result_data"]["Document"]["tblMenu"], dict):
data["result_data"]["Document"]["tblMenu"] = [... |
def echo(string, newline=True, interpret=False):
"""
write output given to this command.
backslash escapes: these can be given, and will be evaluated.
if you want to include a backslash escapped character, escape it with
another backslash. (only applies in backslash interpretation mode (-e))"""
... |
def factorial(n):
"""recursive factorial"""
if n == 0:
return 1
else:
return n * factorial(n-1) |
def logic(tup, time):
"""
determines whether an onoff tuple is true by checking with time. v2.00
corrected v2.025
"""
st=False
if tup==(None, None): return None # v2.034
if tup: # empty tuple means False
ontime=tup[0]
offtime=tup[1]... |
def reverse_cut_n_cards(nb_cards, n, position):
"""Same as single_cut_n_cards with reversed argument."""
return (position + n) % nb_cards |
def beta_word(beta: float) -> str:
"""Describe a beta
Parameters
----------
beta : float
The beta for a portfolio
Returns
----------
str
The description of the beta
"""
if abs(1 - beta) > 3:
part = "extremely "
elif abs(1 - beta) > 2:
part = "ver... |
def get_dynamic_element_keys(data, keys=[], key=None, result=[]):
""" get_dynamic_element_keys """
keys_cp = keys.copy()
if key is None:
result = list()
if key is not None and (
isinstance(data, dict) or isinstance(data, list) or isinstance(data, tuple)):
keys_cp.append(key... |
def kfun(x, s, ksat=7.5):
""" Increasing conductivity to the right of the domain """
return ksat + 0.0065*x |
def class_repr(value):
"""Returns a representation of the value class.
Arguments
---------
value
A class or a class instance
Returns
-------
str
The "module.name" representation of the value class.
Example
-------
>>> from datetime import date
>>> class_rep... |
def get_greppable(string):
"""Simply produces a string that -- when grepped -- will omit listing the grep process in a grep listing.
"""
return string.replace(string[0], '[%s]' % string[0], 1) |
def _get_duration_in_seconds(selected_duration):
"""
Converts hours/minutes to seconds
Args:
selected_duration (string): String with number followed by unit
(e.g. 3 hours, 2 minutes)
Returns:
int: duration in seconds
"""
num_time, num_unit = selected_duration.split(' ')... |
def startofyear_cps(changepoints, thresh=5):
"""
Determine whether the person has change points in a given model at the start of a new year,
specifically in the first thresh (optional argument) days of the year.
"""
num_soy_cps = 0
for cp in changepoints:
if (cp.month == 1) and (cp.day... |
def predict_url(*args):
"""
Function to make prediction on a URL
"""
message = 'Not implemented in the model (predict_url)'
message = {"Error": message}
return message |
def staircase(size: int = 0) -> str:
"""Generates a staircase of '#', ascending to the right
Args:
size: Width and height of staircase.
Returns:
A string composed of '#' and ' ', separated by '\n'. When printed to
console, renders the following (given 'size' of 5).
#
... |
def gf_int(a, p):
"""Coerce `a mod p` to an integer in `[-p/2, p/2]` range. """
if a <= p // 2:
return a
else:
return a - p |
def wep_check_all_params_against_set(valid_params: set, request: dict) -> set:
"""
Check an entire request against a set of valid parameters.
:param valid_params: a set of valid parameters
:param request: the request object containing zero or more parameters
:return: The missing parameters, as a se... |
def iob2(tags):
"""Check that tags have a valid IOB format.
Tags in IOB1 format are converted to IOB2.
"""
for i, tag in enumerate(tags):
if tag == "O":
continue
split = tag.split("-")
if len(split) != 2 or split[0] not in ["I", "B"]:
return False
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.