content stringlengths 42 6.51k |
|---|
def omega2rot(omega,twotheta,ccwrot):
"""
sign dependent determination of omega from rot and twotheta
"""
if ccwrot:
return(omega+twotheta/2.0)
else:
return(-omega-twotheta/2.0) |
def secretFunction(x):
"""
A nonsense function that swaps pixels around
x is a 2x2 array
"""
return [[x[1][1], x[0][0]], [x[0][1], x[1][0]]] |
def _instance_name_from_url(instance_url):
"""Extract instance name from url."""
return instance_url.split('/')[-1] |
def gql_labels(fragment):
"""
Return the GraphQL labels query
"""
return f'''
query ($where: LabelWhere!, $first: PageSize!, $skip: Int!) {{
data: labels(where: $where, first: $first, skip: $skip) {{
{fragment}
}}
}}
''' |
def gpsfix2str(fix: int) -> str:
"""
Convert GPS fix integer to descriptive string.
:param int fix: GPS fix type (0-5)
:return: GPS fix type as string
:rtype: str
"""
if fix == 5:
fixs = "TIME ONLY"
elif fix == 4:
fixs = "GPS + DR"
elif fix == 3:
... |
def aster( greenchan, redchan, nirchan, swirchan1, swirchan2, swirchan3, swirchan4, swirchan5, swirchan6 ):
"""
Broadband albedo Aster (Careful the DN multiplier! Here it is 1000.0, output range should be [0.0-1.0])
albedo_aster( greenchan, redchan, nirchan, swirchan1, swirchan2, swirchan3, swirchan4, swirchan5, swi... |
def irc_join(parv):
"""
Join already-encoded tokens into a protocol line.
"""
i, n = 0, len(parv)
if i < n and parv[i].startswith(b"@"):
if b" " in parv[i]:
raise ValueError("Parameter %d contains spaces: %r" % (i, parv[i]))
i += 1
if i < n and b" " in parv[i]:
... |
def _calc___package__(globals):
"""Calculate what __package__ should be.
__package__ is not guaranteed to be defined or could be set to None
to represent that its proper value is unknown.
"""
package = globals.get('__package__')
if package is None:
package = globals['__name__'... |
def flatten(lst, depth=0, level=0):
""" Utility to flatten lists with the option to constrain by depth """
if depth and depth == level:
return lst
flatlist = []
for item in lst:
if isinstance(item, list):
flatlist.extend(flatten(item, depth, level + 1))
else:
... |
def square_of_sum(nn):
"""
return the square of the sum of the integers [1,nn]
"""
return ((nn / 2) * (nn + 1)) ** 2 |
def _coerceToByteArrayIfString(aBytes):
"""If aBytes is a string, change it into a bytearray."""
if isinstance(aBytes, str):
aBytes = bytearray(aBytes, 'ascii')
return aBytes |
def make_slist(l,t_sizes):
"""
Create a list of tuples of given sizes from a list
Parameters:
* l List/array to pack into shaped list.
* t_sizes List of tuple sizes.
"""
out = [] # output
start = 0
for s in t_sizes:
out.append(l[start:start+s])
start = s... |
def string_extractor(text, url):
"""
Extracts RDF segments from a block of text using simple string
methods; for fallback only.
"""
START_TAG = '<rdf:rdf'
END_TAG = '</rdf:rdf>'
lower_text = text.lower()
matches = []
startpos = 0
startpos = lower_text.find(START_TAG, startpos... |
def verif_checksum(data, checksum):
"""Check data checksum."""
data_unicode = 0
for caractere in data:
data_unicode += ord(caractere)
sum_unicode = (data_unicode & 63) + 32
sum_chain = chr(sum_unicode)
return bool(checksum == sum_chain) |
def num_in_base(val, base, min_digits=1, complement=False,
digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
"""Convert number to string in specified base
If minimum number of digits is specified, pads result to at least
that length.
If complement is True, prints negative num... |
def isPalindrome(x):
"""Takes an integer and determines if it is a palindrome (reads the same forward and backward)
Args:
x (int): integer being analyzed
Returns:
boolean: true if integer is a palindrome, otherwise false
"""
for i in range(len(str(x))):
if str(x)[i] != str(x)[len(str(x)) - ... |
def human_readable(size: int) -> str:
"""Build a nice human readable string from a size given in
bytes
"""
if size < 1024 ** 2:
hreadable = float(size) / 1024.0
return "%.0fK" % hreadable
elif size < (1024 ** 3):
hreadable = float(size) / (1024 ** 2)
return "%.1fM" %... |
def last_name(s):
"""
Returns the last name in s
Examples:
last_name_first('Walker White') returns 'White'
last_name_first('Walker White') returns 'White'
Parameter s: a name 'first-name last-name'
Precondition: s is a string 'first-name last-name' with one or more bla... |
def mers(length):
"""Generates multimers for sorting through list of 10mers based on user
specification. Multimers generated act as the keys for generating a
hashtable to eliminate undesired sequence patterns from those 10mers not
found in the genome.
Usage: mers(N) = 4^(N) unique Nmers
... |
def triangular(n):
"""
The triangular numbers are the numbers 1, 3, 6, 10, 15, 21, ...
They are calculated as follows.
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
Returns nth triangular number.
"""
return sum([i for i in range(n+1)]) |
def _patch_fmt_config(conf, ctx):
"""Return config with formatted string."""
if isinstance(conf, str):
return conf.format(**ctx)
if isinstance(conf, dict):
conf.update({k: _patch_fmt_config(v, ctx) for k, v in conf.items()})
return conf
if isinstance(conf, list):
return [... |
def binary_search_recursive(iterable, item):
"""Returns the index of the item in the sorted iterable.
Binary search works on sorted, iterable collections. Binary search begins by
comparing the middle item in the collection with the target item. If the
target item is equal to the middle item, its position in th... |
def similar_outcome(str1, str2):
"""
Returns True if the strings are off by a single character, and that
character is not a 'd' at the end. That 'd' at the end of a word is highly
indicative of whether something is actually an outcome.
This is used in the get_outcome() method.
"""
i... |
def is_sequence_of_float(items):
"""Verify that the sequence contains only floats.
Parameters
----------
items : sequence
The sequence of items.
Returns
-------
bool
"""
return all(isinstance(item, float) for item in items) |
def greet_by_name(name):
"""Returns a greeting to the given person."""
greeting = "Hello, " + name + "!"
return greeting |
def DeleteTypeAbbr(suffix, type_abbr='B'):
"""Returns suffix with trailing type abbreviation deleted."""
if not suffix:
return suffix
s = suffix.upper()
i = len(s)
for c in reversed(type_abbr.upper()):
if not i:
break
if s[i - 1] == c:
i -= 1
return suffix[:i] |
def epi_file_selector(which_file, in_files):
"""Selects which EPI file will be the standard EPI space.
Choices are: 'middle', 'last', 'first', or any integer in the list
"""
import math
import os
if which_file == 'middle': # middle from the list
return in_files[int(math.floor(len(in_fi... |
def _clean_version(version):
"""
Convert version to string and append decimal if appropriate and missing
:param version: NPPES API version
:type version: int/str
:return: The cleaned version
:rtype: str
"""
version = str(version)
if version in ("1", "2"):
version += ".0"
... |
def method_header(method_name=None, *args):
"""
Get the formatted method header with arguments included
"""
hdr = "%s(" % method_name
if (len(args) > 0):
hdr += args[0]
for arg in args[1:]:
hdr += ", %s" % arg
hdr += ')'
return hdr |
def get_dict_depth(d=None, level=0):
"""Returns maximum depth of the hierarchy"""
if not isinstance(d, dict) or not d:
return level
return max(get_dict_depth(d[k], level=level + 1) for k in d) |
def split_cdl(cdl_string):
"""
Accepts a comma delimited list of values as a string,
and returns a list of the string elements.
"""
return [x.strip() for x in cdl_string.split(',')] |
def cena_biletu(wartosc, miejsc):
"""cena biletu dla liczby miejsc"""
return round(wartosc/miejsc, 2) |
def add_keys(destdict, srclist, value=None):
"""
Nests keys from srclist into destdict, with optional value set on the final key.
:param dict destdict: the dict to update with values from srclist
:param list srclist: list of keys to add to destdict
:param value: final value to set
:return: dest... |
def hashInt(bytebuffer):
"""
Map a long hash string to an int smaller than power(2, 31)-1
"""
import binascii
hex_dig = binascii.hexlify(bytebuffer)
return int(hex_dig, 16) % 2147483647 |
def fibonacci(n: int) -> int:
"""
1 0 LOAD_CONST 1 (1)
2 LOAD_FAST 0 (n)
4 LOAD_METHOD 0 (bit_length)
6 CALL_METHOD 0
8 LOAD_CONST 1 (1)
10 BINARY_SUBTRACT
... |
def binary_search(array, value):
"""Search for value in sorted array, using binary search
Continually divide (sub-) array in half until value is found, or entire
array has been searched. Iterative approach.
Parameters
array : list
List to search. Must be sorted.
value : any
Val... |
def bytes_to_gb(bytes_val):
""" Convert bytes to GB, rounded to 2 decimal places """
BYTES_IN_GB = 1024 * 1024 * 1024
gbytes = bytes_val / BYTES_IN_GB
return round(gbytes, 2) |
def is_gray(hex: str) -> bool:
"""Check if hex is a grayscale.
Arguments:
- hex: str - color code in the 16-digit number system, format:
#HHHHHH, where H is the digit of the 16-digit number system
Returns True or False depending on the result.
"""
if hex[0] != '#':
rai... |
def _IBeamProperties(h_web, t_web, w_flange, t_flange, w_base, t_base):
"""Computes uneven I-cross section area, CG
See: http://www.amesweb.info/SectionalPropertiesTabs/SectionalPropertiesTbeam.aspx
INPUTS:
----------
h_web : float (scalar/vector), web (I-stem) height
t_web : float (scal... |
def shrink_string(_str, strip_chars=None, nullable=True):
"""
:param _str:
:param nullable:
:param strip_chars:
:return:
"""
if isinstance(_str, str):
if strip_chars is None:
return _str.strip()
else:
return _str.strip(strip_chars)
if nullable:
... |
def getNformula(r, n):
""" generate string representation of fromNSperical formula """
rr = "" if r==1 else "r*"
if n <= 1:
return (rr+"cos(p0)", rr+"sin(p0)")
return (rr+"cos(p%d)" % (n-1), ) + tuple(rr+"sin(p%d)*%s" % (n-1, x) for x in getNformula(1.0, n-1)) |
def get_shortest(coin_change, target):
"""
Given a coin combination, find the combination with smallest number of coins.
:param coin_change list - List of tuples cointaining coin denominations, count and remainder.
:param target int - Amount the combination of coins should add up to.
:return list -... |
def average(x,weights=None):
"""
x is array of integers
w is array of weights corresponding to the integers
returns weighted average if weights are provided. else returns simple average
"""
if weights:
return sum(i*j for i,j in zip(x,weights)) / sum(weights)
return sum(x) / l... |
def linear(x, param):
"""Linear model used in dpfit"""
a = param['a']
b = param['b']
y = a*x + b
return y |
def _format_nics(nics):
""" Create a networks data structure for python-novaclient.
**Note** "auto" is the safest default to pass to novaclient
:param nics: either None, one of strings "auto" or "none"or string with a
comma-separated list of nic IDs from OpenStack.
:return: A data structure that ... |
def coast(state):
"""
Ignore the state, go straight.
"""
action = {"hvacON": 1}
return action |
def parse_input(input_data):
"""
Returns an array of unique cities and a dictionary of the distances between them
Each line of the input data must be in the format: City1 to City2 = 123
"""
lines = input_data.splitlines()
cities_arr = []
cities_dict = {}
distances = {}
for line in li... |
def get_domain(url: str) -> str:
""" get domain from url by given
Args: str type
Return: str type, return domain if can get
"""
from urllib.parse import urlparse
parsed_uri = urlparse(url)
domain = '{uri.netloc}'.format(uri=parsed_uri)
return domain |
def reset_slider(modal_open, selected_confidence):
"""
Reset the confidence slider range value to [0, 60] after closing the
modal component.
Parameters
----------
modal_open : bool
A boolean that describes if the modal component is open or not
selected_confidence : list of float
... |
def _Unquote(s):
"""Removes any trailing/leading single/double quotes from a string.
No-ops if the given object is not a string or otherwise does not have a
.strip() method.
Args:
s: The string to remove quotes from.
Returns:
|s| with trailing/leading quotes removed.
"""
if not hasattr(s, 'stri... |
def indentation(string, indent, count=1):
"""Indents a string.
Keyword arguments:
string -- The string you want to indent.
indent -- The string to use for the indent.
count -- How many times you want indent repeated.
"""
# Type check for string and indent
if type(string) is not str or t... |
def is_number(value):
"""
Return true if string is a number.
based on
https://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float
:param string value: input to check
:return bool: True if value is a number, otherwise False.
"""
try:
float(value)
... |
def pgquote(string):
"""single-quotes a string if not None, else returns null"""
return '\'{}\''.format(string) if string else 'null' |
def split_str(string, sep=[',']):
"""
Splits a string based on the list of separators, keeping the seprators.
Parameters
----------
string : str
The string to split
sep : list(str)
The list of separators. Defaults to [','].
Returns
-------
list_ : list(str)
... |
def normalize_basename(s, force_lowercase=True, maxlen=255):
"""Replaces some characters from s with a translation table:
trans_table = {" ": "_",
"/": "_slash_",
"\\": "_backslash_",
"?": "_question_",
"%": "_percent_",
... |
def _extact_field(object, name):
"""
Recursively search through a simple python object to find an element
with the given name and return it.
"""
if object[0] == name:
return object
for child in object[2]:
extracted = _extact_field(child, name)
if extracted:
re... |
def InvertRelativePath(path):
"""Given a relative path like foo/bar, return the inverse relative path:
the path from the relative path back to the origin dir.
E.g. os.path.normpath(os.path.join(path, InvertRelativePath(path)))
should always produce the empty string."""
if not path:
return path
# Only ... |
def is_listlike(item):
"""Determine if a scalar is listlike"""
if hasattr(item, "keys"):
listlike = False
else:
listlike = {"append", "next", "__reversed__"}.intersection(dir(item))
return listlike |
def record_to_numeric(num):
"""
Check if the field has a value other then zero.
:param str_field_to_check:
:return:
"""
if num is None:
return 0
else:
return num |
def split_field_action(s):
"""Takes a string and splits it into field and action
Example::
>>> split_field_action('foo__bar')
'foo', 'bar'
>>> split_field_action('foo')
'foo', None
"""
if '__' in s:
return s.rsplit('__', 1)
return s, None |
def fake_gauss_1(num_list):
"""Fake Gauss v1"""
a = num_list[0]
b = num_list[-1]
n = b - a + 1
return int(n * (n + 1)/2) |
def _parse_bool_str(attr, key, default='False'):
"""Parse bool string to boolean."""
return attr.get(key, default).strip().lower() in ['true', '1', 't', 'y', 'yes'] |
def dbl_colour(days):
"""
Return a colour corresponding to the number of days to double
:param days: int
:return: str
"""
if days >= 28:
return "orange"
elif 0 < days < 28:
return "red"
elif days < -28:
return "green"
else:
return "yellow" |
def lsum (inlist):
"""
Returns the sum of the items in the passed list.
Usage: lsum(inlist)
"""
s = 0
for item in inlist:
s = s + item
return s |
def multiple_selection(population, selection_size, selection_function):
"""
Perform selection on population of distinct group, can be used in the form parent selection or survival selection
:param population: parent selection in population
:param selection_size: amount of indivuals to select
:param ... |
def myfun(a, b):
"""This is function which will calculate average of two number
Function Doesent work for 3 Number""" # This is Doc String // firt line after fun creation
average = (a + b) / 2
print(average)
return average |
def square_sum(numbers):
""" This function returns the square sum. """
return sum([i ** 2 for i in numbers]) if len(numbers) > 0 else 0 |
def bitmask(input_array):
"""
| takes an array or string and converts to integer bitmask.
| reads from left to right e.g. 0100 = 2 not 4.
"""
total = 0
for i in range(len(input_array)):
if int(input_array[i]) != 0 and int(input_array[i])!=1:
raise Exception('nonbinary value i... |
def _make_divisible(v, divisor=8, min_value=None):
"""
Reference:
https://github.com/keras-team/keras/blob/v2.8.0/keras/applications/mobilenet_v2.py#L505
"""
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure th... |
def lucas(n):
"""Function that provides the nth term of lucas series."""
x, y = 2, 1
for i in range(n - 1):
x, y = y, x + y
return x |
def filter_sentence_length(sentence_pairs, max_length):
"""Filters sentence pairs by max length.
Args:
sentence_pairs (list): list of pairs of sentences.
max_length (int): max words num in each sentence.
Returns:
filter_result (list): filtered sentence pairs.
"""
filter_resul... |
def _toIPv6AddrInteger(strIPv6Addr):
"""Convert the IPv6 address string to the IPv6 address integer.
:param str strIPv6Addr: IPv6 address string that adopted the full
represented.
:return: IPv6 address integer.
:rtype: int
Example::
strIPv6Addr Ret... |
def bin(s):
"""
Convert an integer into a binary string.
Included for portability, Python 3 has this function built-in.
"""
return str(s) if s<=1 else bin(s>>1) + str(s&1) |
def _extend_unique(l1, l2):
"""
Extend a list with no duplicates
:param list l1: original list
:param list l2: list with items to add
:return list: an extended list
"""
return l1 + list(set(l2) - set(l1)) |
def is_exhausted(opts_mat):
""" is this options matrix exhausted?
the matrix is exhausted if any of its rows are
"""
return any(not opts_row for opts_row in opts_mat) |
def flush_log_bkp(args_array, server):
"""Function: flush_log_bkp
Description: flush_log_bkp function.
Arguments:
(input) args_array
(input) server
"""
status = True
if args_array and server:
status = True
return status |
def get_user_id_from_email(email, users):
"""
given an email address and a list of Respond users, find the user id of the user with the provided email,
and raise an exception if no user is found
:param email: valid email for a user
:param users: list of Respond Users
:return: user id (string) of... |
def hash_string(s):
"""
This does what Java hashCode does
:param str s:
:returns: Hash code
:rtype: int
"""
h = 0
for c in s:
o = ord(c) if isinstance(c, str) else c
h = (31 * h + o) & 0xFFFFFFFF
return ((h + 0x80000000) & 0xFFFFFFFF) - 0x80000000 |
def compare_records(azara_record, rui_record):
"""
:param azara_record: tuple - a (treasure, coordinate) pair.
:param rui_record: tuple - a (location, coordinate, quadrant) trio.
:return: bool - True if coordinates match, False otherwise.
"""
azra_coords = azara_record[1]
rui_x_coord = rui_... |
def poly(coeffs, n):
"""Compute value of polynomial given coefficients"""
total = 0
for i, c in enumerate(coeffs):
total += c * n**i
return total |
def quote_etag(etag, weak=False):
"""Quote an etag.
:param etag: the etag to quote.
:param weak: set to `True` to tag it "weak".
"""
if '"' in etag:
raise ValueError('invalid etag')
etag = '"%s"' % etag
if weak:
etag = 'w/' + etag
return etag |
def calc_line_x(y, slope, intercept):
"""Calculate x value given y, slope, intercept"""
return int((y - intercept)/slope) |
def _flatten_vertex(vertex_json):
"""Flatten the nested json structure returned by the Explorer."""
vertex = {'id': vertex_json['id'], 'properties': {}}
for prop in vertex_json['properties']:
if prop['cardinality'] == 'single':
vals = prop['values'][0]['value']
elif prop['cardina... |
def _list_bits(vrs, table):
"""Return `list` of bits for `vrs`."""
bits = list()
for var in vrs:
attr = table[var]
typ = attr['type']
if typ == 'bool':
bits.append(var)
else:
bits.extend(attr['bitnames'])
return bits |
def uniformat(value):
"""Convert a unicode char."""
# Escape #^-\]
# We include # in case we are using (?x)
if value in (0x23, 0x55, 0x5c, 0x5d):
c = "\\u%04x\\u%04x" % (0x5c, value)
elif value <= 0xFFFF:
c = "\\u%04x" % value
else:
c = "\\U%08x" % value
return c |
def ordered_uniks(iterable):
"""Unique values of iterable in the order they are encountered in arr
>>> iterable = [4, 2, 6, 1, 2, 2, 7]
>>> ordered_uniks(iterable)
[4, 2, 6, 1, 7]
"""
found = set()
# Note: (found.add(x) is None) is a trick so that it the expression is always evaluated.
r... |
def transform_pools(values):
"""Transform the output of pools to something more manageable.
:param list values: The list of values from `SHOW POOLS`
:rtype: dict
"""
output = {}
for row in values:
if row['database'] not in output:
output[row['database']] = {}
if row... |
def _flatten_multi_geoms(geoms, colors):
"""
Returns Series like geoms and colors, except that any Multi geometries
are split into their components and colors are repeated for all component
in the same Multi geometry. Maintains 1:1 matching of geometry to color.
"Colors" are treated opaquely and s... |
def convert_to_bool(value):
""" Convert a few common variations of "true" and "false" to boolean
:param Any value: string to test
:rtype: boolean
:raises: ValueError
"""
value = str(value).strip()
if value:
value = value.lower()[0]
if value in ("1", "y", "t"):
re... |
def convert(df_column):
"""
Converts a DataFrame column to list
"""
data_list = []
for element in df_column:
data_list.append(element)
return data_list |
def underscore(s: str) -> str:
"""Appends an underscore (_) to s."""
return f'{s}_' |
def _get_description(var, parameters):
"""Get the description for the variable from the parameters"""
if hasattr(parameters, 'viewer_descr') and var in parameters.viewer_descr:
return parameters.viewer_descr[var]
return var |
def to_bytes(strng):
"""Convert a python str or unicode to bytes."""
return strng.encode('utf-8', 'replace') |
def letter_score(letter):
"""Gets the value of a letter
E.g. A = 1, B = 2, C = 3, ..., Z = 26
"""
letter = letter.upper()
score = ord(letter) - ord('A') + 1
return score |
def comp2dict(composition):
"""Takes composition: Si20 O10, returns dict of atoms {'Si':20,'O':10}"""
import re
composition = "".join(composition)
pat = re.compile('([A-z]+|[0-9]+)')
m = re.findall(pat, composition)
return dict(zip(m[::2], map(int,m[1::2]))) |
def mouse2grain_coords(mpos, resolution):
"""Get mouse coords and convert to field coords based on given resolution"""
mx, my = mpos
return mx//resolution, my//resolution |
def bisect_right(a, x, lo=0, hi=None):
"""Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e <= x, and all e in
a[i:] have e > x. So if x already appears in the list, a.insert(x) will
insert just after the rightmost x already ... |
def merge_ranges(range_a, range_b):
"""
Checks whether two ranges are mergeable, and if yes, returns the merged range
:param range_a: first range
:param range_b: second range
:return: If ranges are mergeable, returns the merged range;
if not, returns None.
"""
(start_a, end_a) = range_a
... |
def pulse(time, start, duration):
"""
Implements vensim's PULSE function.
Parameters
----------
time: function
Function that returns the current time.
start: float
Starting time of the pulse.
duration: float
Duration of the pulse.
Returns
-------
float:
... |
def itemize(items: list):
"""
Given a list as argument, itemize each item and return a string
Example:
my_items = itemize(['hello', 'world'])
print(my_items)
output:
- hello
- world
"""
result = ''
for item in items:
result += f'- {item}\n'
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.