content stringlengths 42 6.51k |
|---|
def strip_dev_suffix(dev):
"""Removes corporation suffix from developer names, if present."""
corp_suffixes = (
"incorporated",
"corporation",
"limited",
"oy/ltd",
"pty ltd",
"pty. ltd",
"pvt ltd",
"pvt. ltd",
"s.a r.l",
"sa rl",
... |
def decode(obj):
"""decode an object"""
if isinstance(obj, bytes):
obj = obj.decode()
return obj |
def _get_value(key, entry):
"""
:param key:
:param entry:
:return:
"""
if key in entry:
return entry[key]
return None |
def clean_string_value_from_dict_object(dict_object, dict_name, dict_key, post_errors, empty_string_allowed=False,
none_allowed=False, no_key_allowed=False):
"""
This function takes a target dictionary and returns the string value given by the given key.
Returns None ... |
def is_inst(module):
"""Returns an indication where a particular module should be instantiated
in the top level
"""
top_level_module = False
top_level_mem = False
if "attr" not in module:
top_level_module = True
elif module["attr"] in ["normal", "templated", "reggen_top"]:
... |
def get_name(path):
"""
Get a file name from its full path.
Args:
path (str): full path
Returns:
name (str): just the file name
"""
splits = path.split("/")
if splits[-1] == "":
name = splits[-2]
else:
name = splits[-1]
return name |
def reinterpret_latin1_as_windows1252(wrongtext):
"""
Maybe this was always meant to be in a single-byte encoding, and it
makes the most sense in Windows-1252.
"""
return wrongtext.encode('latin-1').decode('WINDOWS_1252', 'replace') |
def human_readable_time_from_seconds(seconds, depth=4):
"""
Convert seconds to a human-readable str.
The exact format may change, so this string should not be parsed.
seconds (int) - a time in seconds
depth (int) max larged units to report.
Examples:
In [2]: hrts(4)
Out[2]: ... |
def get_filename_in_second_line(cpp_txt):
"""
From the second line of cpp_txt, get the filename
Expected input argument:
// ```
// Begin file_name.cpp
// ...
Expected output argument in this case:
file_name.cpp
"""
result = ""
for line in cpp_txt.splitlines():
if ... |
def format_hotkey(s, default=None, hotkey='hotkey'):
"""
Given a caption *s*, returns an urwid markup list with the first underscore
prefixed character transformed into a (*hotkey*, char) tuple, and the rest
marked with the *default* attribute (or not marked if *default* is
``None``.
For exampl... |
def basename(p):
"""Returns the final component of a pathname"""
i = p.rfind('/') + 1
return p[i:] |
def iscamel(s: str) -> bool:
"""
Return true if the string is in camel case format, false otherwise.
"""
return s.isalnum() and s[0].isalpha() and s[0].islower() |
def elink_module(elink_intf, emesh_intf):
""" The Adapteva ELink off-chip communication channel.
Interfaces:
elink_intf: The external link signals
emesh_intf: The internal EMesh packet interface
"""
# keep track of all the myhdl generators
mod_inst = []
# clock and reset conf... |
def add_role_constraint_to_app_def(app_def, roles=['*']):
"""Roles are a comma-delimited list. Acceptable roles include:
'*'
'slave_public'
'*, slave_public'
"""
app_def['acceptedResourceRoles'] = roles
return app_def |
def _num_to_month(num):
"""Helper function to convert month number to short name
Args:
num (int): the month number to convert
Returns:
(str): The three letter short name of the corresponding month
"""
return {
1: "Jan",
2: "Feb",
3: "Mar",
4: "Apr"... |
def formatnumber(value, p=1):
"""return a formated number with thousands seperators"""
try:
return "{:,.{}f}".format(float(value), int(p))
except (ValueError, TypeError):
return None |
def _unescape(cmd: bytes) -> bytes:
"""Replace escaped characters with the unescaped version."""
charmap = {b" ": b" ", b"'": b"'", b"(": b"(", b")": b")"}
for escape, unescape in charmap.items():
cmd = cmd.replace(escape, unescape)
return cmd |
def check_available(all_p, other):
"""
(list, list) -> bool
Function checks if coordinates are available for ship placement
"""
return len(set(all_p).intersection(set(other))) == len(other) |
def pad_to(unpadded, target_len):
"""
Pad a string to the target length in characters, or return the original
string if it's longer than the target length.
"""
under = target_len - len(unpadded)
if under <= 0:
return unpadded
return unpadded + (' ' * under) |
def create_numeric_mapping(node_properties):
"""
Create node feature map.
:param node_properties: List of features sorted.
:return : Feature numeric map.
"""
return {value:i for i, value in enumerate(node_properties)} |
def split_args(args):
"""Split arguments string from input.
Parameters
----------
args : string
arguments string that typically splitted by spaces.
Parameters
----------
args_dict : list
the list of the splited arguments.
"""
return args.split(" ") |
def parse_obitools_fasta_entry(text, known_species=None):
"""Parse species from the OBITools extended FASTA header.
See https://pythonhosted.org/OBITools/attributes.html which explains that
OBITools splits the FASTA line into identifier, zero or more key=value;
entries, and a free text description.
... |
def matchTypes(accept_types, have_types):
"""Given the result of parsing an Accept: header, and the
available MIME types, return the acceptable types with their
quality markdowns.
For example:
>>> acceptable = parseAcceptHeader('text/html, text/plain; q=0.5')
>>> matchTypes(acceptable, ['text/... |
def patch(base, *overlays):
"""Recursive dictionary patching."""
for ovl in overlays:
for k, v in ovl.items():
if isinstance(v, dict) and isinstance(base.get(k), dict):
patch(base[k], v)
else:
base[k] = v
return base |
def getValIfDictInString(s0,dictC):
"""
example get connection code in FaultDescription
Bus Fault on: "6 NEVADA 132. kV 3LG" => "3LG"
"""
for key in dictC:
if key in s0:
return dictC[key]
return '' |
def ERR_NOSUCHSERVER(sender, receipient, message):
""" Error Code 402 """
return "ERROR from <" + sender + ">: " + message |
def greatest_common_superclass(*types):
"""
Finds the greatest common superclass of the given *types. Returns None if
the types are unrelated.
Args:
*types (type):
Returns:
type or None
"""
if len(types) == 1:
return types[0]
mros = [t.__mro__ for t in types]
... |
def scalar_eq(a, b, precision=0):
"""Check if two scalars are equal.
Input:
a : first scalar
b : second scalar
precision : precision to check equality
Output:
True if scalars are equal
"""
return abs(a - b) <= precision |
def numericalTimeSlot(day) -> int:
"""
Returns the numerical day of thr timeslot given
:param day: str
the day to turn into
:return: int
The corresponding numerical time slot
"""
switch = {
"Sunday_AM": 1,
"Monday_AM": 2,
"Monday_PM": 3,
"Tuesday_A... |
def _format_classifiers(_classifiers: str):
"""Format classifiers gotten from the API."""
classifier_dict = {}
output = ""
for classifier in _classifiers.splitlines():
topic, content = map(str.strip, classifier.split("::", 1))
try:
classifier_dict[topic].append(content)
... |
def _construct_resource_name(project_id, location, dataset_id, fhir_store_id,
resource_id):
"""Constructs a resource name."""
return '/'.join([
'projects', project_id, 'locations', location, 'datasets', dataset_id,
'fhirStores', fhir_store_id, 'fhir', resource_id
]) |
def _dist_calc(q_phoc, w_phoc):
""" """
s = 0
qsq = 10**-8
psq = 10**-8
for q, p in zip(q_phoc, w_phoc):
s += q*p
qsq += q**2
psq += p**2
q_norm = qsq**(0.5)
p_norm = psq**(0.5)
dist = 1 - s / (q_norm * p_norm)
return dist |
def occ_indexes(l, sub_l):
"""
used for finding the concordances
:param l: list
:param sub_l: sub-list
:return: indexes (x, y) for all occurrences of the sub-list in the list, an empty list if none found
"""
return [(i, i+len(sub_l)) for i in range(len(l)) if l[i:i+len(sub_l)] == sub_l] |
def Powerlaw(x, a, alpha):
"""Power-law function
Inputs:
-------
``x``: independent variable
``a``: scaling factor
``alpha``: exponent
Formula:
--------
``a*x^alpha``
"""
return a * x ** alpha |
def prod(factors):
"""
Computes the product of values in a list
:param factors: list of values to multiply
:return: product
"""
product = factors[0]
if len(factors) > 1:
for i in factors[1:]:
product *= i
return product |
def group_chains(chain_list):
"""
Group EPBC chains.
"""
chains = []
while len(chain_list):
chain = set(chain_list.pop(0))
## print ':', chain
ii = 0
while ii < len(chain_list):
c1 = sorted(chain_list[ii])
## print '--', ii, c1, chain
... |
def cuda_tpb_bpg_1d(x, TPB = 256):
"""
Get the needed blocks per grid for a 1D CUDA grid.
Parameters :
------------
x : int
Total number of threads
TPB : int
Threads per block
Returns :
---------
BPG : int
Number of blocks per grid
TPB : int
Th... |
def index_along_axis(index, ndim, axis):
"""
Create a slice tuple for indexing into a NumPy array along a
(single) given axis.
Parameters
----------
index : array_like or slice
The value you wish to index with along `axis`.
ndim : int
The number of dimensions in the array in... |
def _scaled_average(numbers, scalar):
"""Internal utility function to calculate scaled averages."""
average = sum(numbers) / len(numbers)
return scalar * average |
def strip_package_version(package_name):
"""Takes a component name with a version and strips the version"""
if not "/" in package_name:
return package_name
return package_name.split("/")[0] |
def repackage_hidden(h):
"""Wraps hidden states in new Variables, to detach them from their history."""
return [state.detach() for state in h] |
def disambiguate(lines, words, bytes_, chars, filename=None):
"""
When an option is specified, wc only reports the information requested by
that option. The order of output always takes the form of line, word,
byte, and file name. The default action is equivalent to specifying the
-c, -l and -w op... |
def translate_dna_sequence( sequence ):
"""Translates **DNA** to **protein**.
Assumes always that the codon starts in the first position
of the sequence.
:param str sequence: DNA sequence
:return: :class:`str` - protein sequence
.. seealso::
:func:`.translate_3frames`
.. rubric::... |
def score_word(word, score_dict):
""" Given a word, score it using the scoring dicitonary. """
return sum([score_dict[letter] for letter in word]) |
def is_int(some_str):
""" Return True, if the given string represents an integer value. """
try:
int(some_str)
return True
except ValueError:
return False |
def parse_description(description):
""" Parse description.
Args:
description: str.
Returns:
parsed: list. parsed description.
"""
parsed = description.split('\n')
return parsed |
def check_for_keys(key_list, dictionary):
"""Checks if all keys are present in dictionary"""
return True if all(k in dictionary for k in key_list) else False |
def match_score(s1, s2):
""" align two sequences and count matching score """
return sum(s1[i] == s2[i] for i in range(min(len(s1), len(s2)))) |
def FlagsForCpu(cpu, target_os, sysroot):
"""Returns the flags to build for the given CPU."""
FLAGS = {
'x64': '-m64',
'x86': '-m32',
'arm': '-arch armv7',
'arm64': '-arch arm64',
}
assert ' ' not in sysroot, "sysroot path can't contain spaces"
assert cpu in FLAGS, 'Unsupported CPU arc... |
def transform_sample_name(value):
"""Transform legacy name to new sample name."""
if '/' in value:
sample_name = ''.join(value.split('/'))
return sample_name
else:
return value |
def read_file(filename, mode='rU', content=None):
"""Read and return the contents of the given filename."""
f = open(filename, mode)
try:
content = f.read()
finally:
f.close()
return content |
def parse_gff_attributes(attr_str):
"""
Parses a GFF/GTF attribute string and returns a dictionary of name-value
pairs. The general format for a GFF3 attributes string is
name1=value1;name2=value2
The general format for a GTF attribute string is
name1 "value1" ; name2 "value2"
The ge... |
def maxSatisfied(customers, grumpy, X):
"""
:type customers: List[int]
:type grumpy: List[int]
:type X: int
:rtype: int
"""
sum_cust = 0
count = 0
start = 0
for i in range(len(customers)):
if grumpy[i] == 0:
sum_cust += customers[i]
win = sum_cust
if X... |
def glue_tokens(tokens):
"""The standard way in which we glue together tokens to
create keys in our hashmaps"""
return ' '.join(tokens) |
def x_gate_counts_deterministic(shots, hex_counts=True):
"""X-gate circuits reference counts."""
targets = []
if hex_counts:
# X
targets.append({'0x1': shots})
# XX = I
targets.append({'0x0': shots})
# HXH=Z
targets.append({'0x0': shots})
else:
# X... |
def evaluate_poly(poly, x):
"""
Objective: Computes the polynomial function for a given value x.
Returns that value.
Input Prams:
poly: tuple of numbers - value of cofficients
x: value for x in f(x)
Return: value of f(x)
>>> evaluate_poly((... |
def list_intersection(lst1, lst2):
"""List intersection."""
lst3 = [value for value in lst1 if value in lst2]
return lst3 |
def get_att(logical_name, attribute):
"""The intrinsic function Fn:GetAtt returns the value of an attribute from \
a resource in the template.
Args:
logical_name: The logical name of the resource that
contains the attribute you want.
attribute: The name of the resource-specific ... |
def merge_stations(all_stations, accessible_stations):
"""Merge two lists of stations."""
merged_stations = []
merged_count = 0
for station1 in all_stations:
found = False
for station2 in accessible_stations:
if len(station1.osm_ids.intersection(station2.osm_ids)):
... |
def bitInBitmap(bitmap, bit):
"""bit map decoding"""
flag = False
for i in range(10, -1,- 1):
if bitmap - 2**i >= 0:
bitmap = bitmap - 2**i
if 2**i == bit:
flag = True
else:
continue
return flag |
def schedule_lrn_rate(train_step):
"""train_step equals total number of min_batch updates"""
f = 1 # rl schedule factor
lr = 1e-3
if train_step < 1 * f:
lr = 1e-3 # 1e-1 blows up, sometimes 1e-2 blows up too.
elif train_step < 2 * f:
lr = 1e-4
elif train_step < 3 * f:
l... |
def concat_things( *args ):
""" Behave kinda like a print statement: convert all the things to strings.
Return the large concatinated string. """
result = ''
space = ''
for arg in args:
result += space + str(arg).strip()
space = ' '
return result |
def treat_input(data):
"""
Treats the input json to keep it in the same format as the coeficcients
"""
treated_data = dict()
for key, value in data.items():
if key[0] == 'Q':
treated_data[value] = 1
else:
treated_data[key] = 1
return treated_data |
def class_name(dataset, idx):
"""
Args
- dataset: (str) Dataset name
- idx: (int or string) Class index
"""
LINEMOD = ('ape', 'bvise', 'bowl', 'camera', 'can', 'cat', 'cup', 'driller',
'duck', 'eggbox', 'glue', 'holepuncher', 'iron', 'lamp', 'phone')
YCB = ('002_master... |
def lowercase(obj):
""" Make dictionary lowercase """
if isinstance(obj, dict):
return {k.lower(): lowercase(v) for k, v in obj.items()}
elif isinstance(obj, (list, set, tuple)):
t = type(obj)
return t(lowercase(o) for o in obj)
elif isinstance(obj, str):
return obj.lower... |
def find_on_grid(grid, wanted):
"""Find location of wanted on grid."""
for row_no, row in enumerate(grid):
for col_no, col in enumerate(row):
if col == wanted:
return (row_no, col_no)
return None |
def loss_inversely_correlated(X, y):
"""
Return
-1 * (concept_direction * prediction)
where
prediction = X[0]
concept_direction = y
"""
prediction, *_ = X
concept_direction = y
return -1 * (concept_direction * prediction) |
def calculate_mean(numbers):
"""Calculates the mean of a list of numbers
Parameters
----------
numbers: iterable[numbers]
Returns
-------
number
"""
return sum(numbers) / len(numbers) |
def median_val(vals):
"""
:param vals: an iterable such as list
:return: the median of the values from the iterable
"""
n = len(vals)
sorted_vals = sorted(vals)
if n % 2 == 0:
return (sorted_vals[n // 2] + sorted_vals[n // 2 - 1]) / 2
else:
return sorted_vals[n // 2] |
def _unpack_metric_map(names_to_tuples):
"""Unpacks {metric_name: (metric_value, update_op)} into separate dicts."""
metric_names = names_to_tuples.keys()
value_ops, update_ops = zip(*names_to_tuples.values())
return dict(zip(metric_names, value_ops)), dict(zip(metric_names, update_ops)) |
def dir_basename_from_pid(pid,j):
""" Mapping article id from metadata to its location in the arxiv S3 tarbals.
Returns dir/basename without extention and without full qualified path.
It also ignores version because there is no version in the tarbals.
I understand they have the updated version in the tarball... |
def recvall(sock, n):
"""
returns the data from a recieved bytestream, helper function
to receive n bytes or return None if EOF is hit
:param sock: socket
:param n: length in bytes (number of bytes)
:return: message
"""
#
data = b''
while len(data) < n:
packet = sock.recv... |
def dist_rgb_weighted(rgb1, rgb2):
"""
Determine the weighted distance between two rgb colors.
:arg tuple rgb1: RGB color definition
:arg tuple rgb2: RGB color definition
:returns: Square of the distance between provided colors
:rtype: float
Similar to a standard distance formula, the valu... |
def find_divisors(x):
"""
This is the "function to find divisors in order to find generators" module.
This DocTest verifies that the module is correctly calculating all divisors
of a number x.
>>> find_divisors(10)
[1, 2, 5, 10]
>>> find_divisors(112)
[1, 2, 4, 7, 8, 14, 16, 28, 56, 11... |
def _isiterable(obj):
"""
Copied from putil.misc module, not included to avoid recursive inclusion
of putil.pcontracts module
"""
try:
iter(obj)
except TypeError:
return False
else:
return True |
def check_argument(actual_argument_value, correct_argument_value):
"""
Checks whether the two given argument-values are equal.
If so, returns True.
If not, prints an appropriate message and returns False.
"""
if actual_argument_value == correct_argument_value:
return True
else:
... |
def RETURN_delete_negatives(numbers):
"""
Returns a NEW list that is the same as the given list of numbers,
but with each negative number in the list DELETED from the list.
For example, if the given list is [-30.2, 50, 12.5, -1, -5, 8, 0].
then the returned list is the NEW list [50, 12.5, 8, 0].
... |
def format_hostmaster(hostmaster):
"""
The DNS encodes the <local-part> as a single label, and encodes the
<mail-domain> as a domain name. The single label from the <local-part>
is prefaced to the domain name from <mail-domain> to form the domain
name corresponding to the mailbox. Thus the mailbox... |
def totalStudents (theDictionary):
"""Identifies the total number of students assigned a locker.
:param dict[str, str] theDictionary:
key: locker number / value: student name or "open"
:return:
The total number of students assigned to a locker
:rtype: int
"""
total = 0
for ... |
def add_two_numbers(first, second):
"""Add two numbers together
:first: first number
:second: second number
"""
result = first + second
return result |
def rc2p(row, col, N):
"""
row-col to (board) position
row and column go from 1 to N
Test OK
:param row:
:param col:
:param N:
:return:
"""
# print('row:{} col:{}'.format(row,col))
return row * (N + 1) + col |
def recursive(duration, J_prev, vol_prev, omega, alpha, beta):
"""
GARCH Recursive function to forecast the index process.
.. math::
\sigma^2_t = \omega + \alpha \epsilon^2_{t-1} + \beta \sigma^2_{t-1}
For the EWMA process, the parameters become:
omega = 0
alpha = 1-lambda... |
def find_item(tgt_dict, key):
"""Recursively search dictionary for key and return value"""
if key in tgt_dict: return tgt_dict[key]
for k, v in tgt_dict.items():
if isinstance(v, dict):
item = find_item(v, key)
if item is not None:
return item |
def dict_get(inp, *subfields):
"""Find the value of the provided sequence of keys in the dictionary,
if available.
Retrieve the value of the dictionary in a sequence of keys if it is
available. Otherwise it provides as default value the last item of the
sequence ``subfields``.
Args:
inp... |
def get_attribution(file_json):
"""give file response in embedded frame and extract attribution info"""
attributions = {
'project': file_json['project']['@id'],
'institution': file_json['institution']['@id']
}
return attributions |
def build_api_link(service_name, callback_url):
"""
Utility for building UDID.io API links
"""
api_link = 'https://get.udid.io/thirdparty/api/?callback=%(callback)s&service=%(service)s&schemeurl=0' % {
'callback': callback_url,
'service': service_name
}
return api_link |
def _get_identifiers(header, data, fields):
"""See get_identifiers
Returns
-------
rv : dict
map from field in <fields> to a set of identifiers
"""
rv = {}
for field in fields:
pipe_str = data[header[field]]
id_value_pairs = pipe_str.split("|")
for id_value_pair in id_value_pairs:
#... |
def odd_or_even(arr):
"""
Given a list of numbers, determine whether the sum of its elements is odd or even. Give your answer as a string
matching "odd" or "even". If the input array is empty consider it as: [0] (array with a zero).
:param arr: A list of numbers.
:return: 'even' if the sum of the nu... |
def pred(lis):
""" This function moves the list representing a relation (first element
of the list) AFTER relational term. """
# Remove all dummy semantic elements.
lis = [ele for ele in lis if ele != []]
# Put the relational predicate in front of the token
lis[0], lis[1] = lis[1], lis[0]
r... |
def calculate_intensity_group(hfi: float) -> int:
""" Returns a 1-5 integer value indicating Intensity Group based on HFI.
Intensity groupings are:
HFI IG
0-499 1
500-999 2
1000-1999 3
2000-3999 4
4000+ 5
"""
if hfi < 500:... |
def make_response(response):
"""
Make a byte string of the response dictionary
"""
response_string = response["status"] + "\r\n"
keys = [key for key in response if key not in ["status", "content"]]
for key in keys:
response_string += key + ": " + response[key] + "\r\n"
response_strin... |
def check_port_in_port_range(expected_port: str,
dest_port_range: str):
"""
Check if a port is within a port range
Port range maybe like *, 8080 or 8888-8889
"""
if dest_port_range == '*':
return True
dest_ports = dest_port_range.split('-')
if len(dest... |
def count_nice_hours(rows, threshold, time_interval):
"""
Calculate the amount of hours that have a solar temperature over a specific threshold
It is assumed that all rows correspond with a single day and each row is measured
in equal time differences specified by the time_interval parameter
... |
def get_mouse_pos(new_x_coord, new_y_coord):
""" Gets the updated mouse position
:param new_x_coord:
The new x coordinate as reported by the controller
:param new_y_coord:
The new y coordinate as reported by the controller
"""
x_change = 0
y_change = 0
... |
def div(func):
"""
Divergence of the input Function.
Parameters
----------
func : Function or TensorFunction
"""
try:
return func.div
except AttributeError:
return 0 |
def valid_provider(provider):
"""Determine if the provider provided is supported and valid.
Returns True if it is valid or False if it is not valid.
"""
if provider in ('vmware', 'virtualbox'):
return True
else:
return False |
def html_attrs(context):
"""
Adds a ``no-js`` class to the ``<html>`` tag
todo: Make this much more flexible
"""
request = context.get('request')
tags = [
('class', 'no-js')
]
return ' '.join(
['%s="%s"' % t for t in tags]
) |
def is_ascii_chars(text):
"""
check if the text contains "non-latin"
characters. If have non start char then
return true.
"""
is_ascii = True
try:
text.encode(encoding='utf-8').decode('ascii')
except UnicodeDecodeError:
is_ascii = False
return is_ascii |
def remove_null_values(data):
""" Removed null value
Arguments:
data {dict}: data
Returns:
data {dict}: update data
"""
return {k: v for k, v in data.items() if v is not None} |
def legacy_html_escape(s):
"""legacy HTML escape for non-unicode mode."""
s = s.replace("&", "&")
s = s.replace(">", ">")
s = s.replace("<", "<")
s = s.replace('"', """)
s = s.replace("'", "'")
return s |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.