content stringlengths 42 6.51k |
|---|
def _translate_attachment_summary_view(_context, vol):
"""Maps keys for attachment summary view."""
d = {}
conductor_id = vol['id']
# NOTE(justinsb): We use the conductor id as the id of the attachment object
d['id'] = conductor_id
d['conductor_id'] = conductor_id
d['server_id'] = vol['in... |
def xyminmax_to_xywh(xmin, ymin, xmax, ymax):
"""convert box coordinates from (xmin, ymin, xmax, ymax) form to (x, y, w , h) form"""
return [xmin, ymin, xmax - xmin, ymax - ymin] |
def lowerleft_iou(box1, box2):
""" Compute the Intersection-Over-Union of two given boxes.
Args:
box1: array of 4 elements [cx, cy, width, height].
box2: same as above
Returns:
iou: a float number in range [0, 1]. iou of the two boxes.
"""
x0 = max(box1[0]... |
def adjust_shell_pattern_to_work_with_fnmatch( pattern ):
"""
slight modification to the ends of the pattern in order to use
fnmatch to simulate basic shell style matching
"""
if pattern.startswith('^'):
pattern = pattern[1:]
else:
pattern = '*'+pattern
if pattern.endswith('... |
def day_in_hour(dy):
""" Convertion d'un nombre de jours en heure
:param int dy: nombre de jours
:rtype: int
"""
nb = int(dy)
return nb * 24 |
def getobjectid(obj):
"""Try to get the id of an object or dict"""
try:
return obj.id
except AttributeError:
try:
return obj.get('id', obj.get('_id', None))
except AttributeError:
pass
return obj |
def reverse_it(lines: list) -> list:
"""
Reverses the line's content. Thus the first char will be the last and the last one the first etc.
:param lines:
:return: lines rearanged
"""
newlines = []
for line in lines:
newlines.append(''.join(reversed(line)))
return newlines |
def valid_num(val, rule):
"""Default True, check against rule if provided."""
return (rule(val) if callable(rule) else
val == rule if rule else
True) |
def make_timestamp_range(start, end,
start_timestamp_op=None, end_timestamp_op=None):
"""Given two possible datetimes and their operations, create the query
document to find timestamps within that range.
By default, using $gte for the lower bound and $lt for the
upper bound.
... |
def str2tokenstags(string, delimiter):
"""
Usage:
{% str2tokens 'a/b/c/d' '/' as token_list %}
"""
token_list = [token.strip() for token in string.split(delimiter)]
return token_list |
def merge_dicts(dict1: dict, dict2: dict) -> dict:
"""Merge 2 dictionaries
Arguments:
dict1 {dict} -- 1st Dictionary
dict2 {dict} -- 2nd Dictionary
Returns:
dict -- Concatenated Dictionary
"""
return {**dict1, **dict2} |
def filecontent(filename,default=''):
""" Return the file's content as a string, default in case
there's an error
"""
try:
f = open(filename,'rb')
except IOError:
return default
c = f.read()
f.close()
return c |
def recursiveMap(function, sequence):
"""
Iterate recursively over a structure using a function.
:param function: function to apply
:param sequence: iterator
:return:
"""
def helper(seq):
try:
return list(map(helper, seq))
except TypeError:
return fun... |
def karatsuba(x, y):
"""Karatsuba method for fast multiplication"""
if x < 10 and y < 10:
return x * y
num1_len = len(str(x))
num2_len = len(str(y))
n = max(num1_len, num2_len)
# round decides to be floor or ceil value
# by this we can reduce some function calls
# of ceil or f... |
def multipole_label(T,L):
"""Get multipole label.
T = 0 (electric), 1(magnetic)
L = 0,1,2... (order)
"""
first = ['e', 'm'][T]
if L <= 3:
last = ['D', 'Q', 'O', 'H'][L]
else:
last = " (L = {L})".format(L=L)
return first + last |
def object_list_check_any_has_attribute(object_list,attr_name):
"""
check if any object in the list has the attribute.
"""
unique = False
for obj in object_list:
if hasattr(obj,attr_name):
unique = True
break
else:
pass
return unique |
def absmax(i):
"""
Returns the largest absolute value present in an array in its raw form
(e.g. in [-2, 0, 1] it returns -2, in [-2,0,3] it returns 3.)
"""
# Use the absolute largest value in its raw form
if max(i) > abs(min(i)):
return max(i)
elif abs(min(i)) >= max(i):
ret... |
def max_spike_power(FWHM):
"""
max_spike_power(FWHM):
Return the (approx.) ratio of the highest power from a
triangular spike pulse profile to the power from a
perfect sinusoidal pulse profile. In other words, if a
sine gives you a power of 1, what power does a spike profile
... |
def ztf_seeing(bands=''):
"""
Sample from the ZTF seeing distribution
"""
dist = {'g': 2.1, 'r': 2.0, 'i': 2.1}
return [dist[b] for b in bands.split(',')] |
def get_consumption(
assets_this_period,
assets_next_period,
pension_benefit,
labor_input,
interest_rate,
wage_rate,
income_tax_rate,
productivity,
efficiency,
):
""" Calculate consumption level via household budget constraint.
Arguments:
assets_this_period: np.float... |
def positions2bits(positions):
"""Converts a list of numerical positions to an integer.
Args:
positions:
list(int). A list of distinct integers in the range 0 through 60 inclusive.
"""
return sum(1 << pos for pos in positions) |
def _check_equal(iterator):
"""Check if all the values in an iterator are equal.
:param iterator: iterator
:return: bool
"""
iterator = iter(iterator)
try:
first = next(iterator)
except StopIteration:
return True
return all(first == rest for rest in iterator) |
def _deep_merge_dict(dict_x, dict_y, path=None):
"""Recursively merges dict_y into dict_x.
"""
if path is None: path = []
for key in dict_y:
if key in dict_x:
if isinstance(dict_x[key], dict) and isinstance(dict_y[key], dict):
_deep_merge_dict(dict_x[key], dict_y[key], path + [str(key)])
... |
def _convert_digit_base(digit, alphabet):
"""
Parameters
----------
digit : int
number in base 10 to convert
alphabet : list
symbols of the conversion base
"""
baselen = len(alphabet)
x = digit
if x == 0:
return alphabet[0]
sign = 1 if x > 0 else -1
x... |
def GetHour(acq_time):
"""
Function which gets the hour number from the FIRMS aquired hour
"""
aqtime = str(acq_time)
size = len(aqtime)
hr = aqtime[:size - 2] #get the hours
#add the 0 if we need it to match the fire db
if len (hr) == 1:
hr = '0' + hr
return hr |
def safe_slice(list_, *args):
"""safe_slice(list_, [start], stop, [end], [step])
Slices list and truncates if out of bounds
"""
if len(args) == 3:
start = args[0]
stop = args[1]
step = args[2]
else:
step = 1
if len(args) == 2:
start = args[0]
... |
def rep_hill(x, n):
"""Dimensionless production rate for a gene repressed by x.
Parameters
----------
x : float or NumPy array
Concentration of repressor.
n : float
Hill coefficient.
Returns
-------
output : NumPy array or float
1 / (1 + x**n)
"""
return... |
def getHeaderResponse(station, type='FixedStation'):
""" Get header response
:param station: station name id
:param type: station type (FixedStation or MobileStation)
:return: header response
"""
response = {'id': station}
response['station_name'] = station
response['scientificName'] = 'CanAirIO Air qua... |
def as_words(string):
"""Split the string into words
>>> as_words('\tfred was here ') == ['fred', 'was', 'here']
True
"""
return string.strip().split() |
def iou (box1, box2, x1y1x2y2 = True):
""" Intersection Over Union """
if x1y1x2y2:
mx = min (box1 [0], box2 [0])
Mx = max (box1 [2], box2 [2])
my = min (box1 [1], box2 [1])
My = max (box1 [3], box2 [3])
w1 = box1 [2] - box1 [0]
h1 = box1 [3] - box1 [1]
... |
def get_identifier(term):
"""Convert identifier string to the corresponding identifier property schema
Args:
term: a string with the format "source:id_content"
Returns:
a tuple: (property_line,new_source_map). property_line is the identifier
property in schema, and new_source_map is ... |
def _list(v):
"""Convert a value (list, string or None) into a list."""
if v is None:
return []
elif hasattr(v,'lower'):
return [v]
assert(isinstance(v, list))
return v |
def get_argv(cmd: str) -> list:
""" Return a list of arguments from a fully-formed command line. """
return cmd.strip().split(' ') |
def convert_datepicker_to_isotime(date_picker_format):
"""the date_picker_format argument comes from the html forms and it should looks like this: MM/DD/YYYY.
We want to transform them into our standart ISO format like this :
YYYY-MM-DDThh:mm:ss.ms
"""
try:
year = date_picker_format.sp... |
def gauss_units(deriv=None):
"""
Return string of the magnetic field units given the derivative with time.
String is meant to be used in plot labels.
Parameters
----------
deriv : int, optional
Derivative (defaults to 0).
Returns
-------
units : str
Tex-style unit ... |
def predict_data(*args):
"""
Function to make prediction on an uploaded file
"""
message = 'Not implemented in the model (predict_data)'
return message |
def reflow_text(text, linewidth=80):
"""
Add line breaks to ensure text doesn't exceed a certain line width.
Parameters
----------
text : str
linewidth : int, optional
Returns
-------
reflowed_text : str
"""
""
lines = text.split("\n")
linebreak_chars = [" ", "$"]
... |
def formatSignificantDigits(q):
"""
Truncate a float to 2 significant figures, with exceptions for numbers below 1
Only works for numbers [-100;100]
Arguments:
q : a float
Returns:
Float with only n s.f. and trailing zeros, but with a possible small overflow.
"""
if abs(q) < 1... |
def group(lst, max_group_size):
""" partition `lst` into that the mininal number of groups that as evenly sized
as possible and are at most `max_group_size` in size """
if max_group_size is None:
return [lst]
n_groups = (len(lst) + max_group_size - 1) // max_group_size
per_group = len(lst) ... |
def get_blocks_headers_columns_indexes(headers_string, delimiter="\t", silent_fail=False):
"""
Seq_id Strand Start End Length
"""
headers_string = headers_string.strip()
data = headers_string.split(delimiter)
seq_id_columns = data.index("Seq_id")
strand_column = data.index("Strand")
... |
def depth(data):
"""
Get the depth of a dictionary
Args:
data: data in dictionary type
Returns: the depth of a dictionary
"""
if isinstance(data, dict):
return 1 + (max(map(depth, data.values())) if data else 0)
return 0 |
def pool_url(aws_region, aws_user_pool):
""" Create an Amazon cognito issuer URL from a region and pool id
Args:
aws_region (string): The region the pool was created in.
aws_user_pool (string): The Amazon region ID.
Returns:
string: a URL
"""
return (
"https://cogni... |
def sql_from_dtype(dtype):
"""Returns a sql datatype given a pandas datatype
Args:
dtype (str): The pandas datatype to convert
Returns:
str: the equivalent SQL datatype
Examples:
>>> sql_from_dtype('bool')
'boolean'
>>> sql_from_dtype('float64')
'numeri... |
def port_hash(name):
""" Given a string, returns a port number between 49152 and 65535
This range (of 2**14 posibilities) is the range for dynamic and/or
private ports (ephemeral ports) specified by iana.org. The algorithm
is deterministic.
"""
fac = 0xd2d84a61
val = 0
for c in name:
... |
def FindPhaseByID(phase_id, phases):
"""Find the specified phase, or return None"""
for phase in phases:
if phase.phase_id == phase_id:
return phase
return None |
def merge(a: list, b: list) -> list:
"""Merges two sorted lists into one sorted list"""
i = 0
j = 0
result = []
while i < len(a) and j < len(b):
if a[i] < b[j]:
result.append(a[i])
i += 1
else:
result.append(b[j])
j += 1
while i < ... |
def get_next_prior_import_or_install_required_dict_entry( prior_required_dict, processed_tsr_ids ):
"""
This method is used in the Tool Shed when exporting a repository and its dependencies, and in Galaxy
when a repository and its dependencies are being installed. The order in which the prior_required_dict... |
def saveusername(clicks, name):
"""
Save the username inserted by the user
:type clicks: int
:param clicks: number of times the user has selected the log in button
:type name: string
:param name: the username inserted by the user
"""
if clicks != 0 and name is not None:
re... |
def solve_approxDP_static_homo_basic(distance_g, k):
"""solve for `distance_0`, the per-query epsilon and delta
:param distance_g: global (epsilon, delta)
:param k: compose to `distance_g` in `k` folds
"""
epsilon_g, delta_g = distance_g
return epsilon_g / k, delta_g / k |
def check_required_fields(req_fields, input_list):
"""Check if the required fields are present inside the input list.
Keyword arguments:
req_fields -- The list of required fields
input_list -- The list to validate for required fields
Returns:
Boolean
"""
if all(field in req_fields... |
def _numbering(numbering):
"""
Numbering (for csv)
"""
if numbering == True:
return 'Yes'
else:
return 'No' |
def find_first_text(blocks, default=""):
"""
Find text of first text block in an iterable of blocks.
Returns that text, or default, if there are no text blocks.
"""
for block in blocks:
if block.type == "text":
return block.value
return default |
def quintic_easeout(pos):
"""
Easing function for animations: Quintic Ease Out
"""
fos = pos - 1
return fos * fos * fos * fos * fos + 1 |
def _get_max_name_len(instances):
"""get max length of Tag:Name"""
for i in instances:
return max([len(i['DBInstanceIdentifier']) for i in instances])
return 0 |
def deep_get(dikt, path):
"""Get a value located in `path` from a nested dictionary.
Use a string separated by periods as the path to access
values in a nested dictionary:
deep_get(data, "data.files.0") == data["data"]["files"][0]
Taken from jupyter/repo2docker
"""
value = dikt
for co... |
def _extension(file_name: str) -> str:
"""For 'name.ext' return 'ext'."""
return file_name[file_name.rindex(".") + 1:] |
def swap_keys_values(_dict: dict):
"""Swaps the Keys and Values in Dictionary.
Parameters
----------
_dict : dict
The dictionary that needs to be reversed.
Returns
-------
swapped_dict : dict
Returns the Swapped/Reversed Dictionary.
"""
swapped_dict = {... |
def boolean_flag(name, configurable, set_help='', unset_help=''):
"""Helper for building basic --trait, --no-trait flags.
Parameters
----------
name : str
The name of the flag.
configurable : str
The 'Class.trait' string of the trait to be set/unset with the flag
set_help : uni... |
def fuzzy_match_threshold(category):
"""determine the threshold for fuzzy matching"""
if category == 'word_jumble':
return 60
if category == 'spelling_backwords':
return 90
if category == 'simple_math':
return 100
if category == 'memory_game':
return 60
if categor... |
def parse_bool(s: str) -> bool:
"""
Parses a 'true'/'false' string to a bool, ignoring case.
:raises: KaleValueError If neither true nor false
"""
if s.lower() == 'false':
return False
if s.lower() == 'true':
return True
raise ValueError("{} is not true/false".format(s)) |
def remove_duplicate_context(cmds):
""" Helper method to remove duplicate telemetry context commands """
if not cmds:
return cmds
feature_indices = [
i for i, x in enumerate(cmds) if x == "feature telemetry"
]
telemetry_indices = [i for i, x in enumerate(cmds) if x == "telemetry"]
... |
def total_time(boutlist):
"""Takes list of times of bouts in seconds, returns it's last item representing the total trial time."""
total_time = boutlist[-1]
return total_time |
def combination_of_two_lists(lst1, lst2):
"""
["f", "m"] and ["wb", "go", "re"] => ["f_wb", "f_go", "f_re", "m_wb", "m_go", "m_re"]
"""
return [e1 + "_" + e2 for e1 in lst1 for e2 in lst2] |
def dbs_has_min_columns(column_name_list):
"""
Function determines if DBS headers passed contain the required
columns.
"""
compulsory_header_cols = set([
'runtype',
'station',
'cast',
'niskin',
'depth',
'bottle',
'date',
'time',
... |
def int_from_bytes(bytes_) -> int:
"""Calculates
"""
output = 0
for i in range(0, len(bytes_)):
output += bytes_[i] * (2**(8*i))
return output |
def fibonacci_at_pos(n):
"""return fibonacci number for given position"""
curr_pos = 0
prev_num, curr_num = 0, 1
while curr_pos < n:
curr_pos += 1
prev_num, curr_num = curr_num, prev_num + curr_num
return prev_num |
def squares(s):
"""Returns a new list containing square roots of the elements of the
original list that are perfect squares.
>>> seq = [8, 49, 8, 9, 2, 1, 100, 102]
>>> squares(seq)
[7, 3, 1, 10]
>>> seq = [500, 30]
>>> squares(seq)
[]
"""
return [int(x ** 0.5) for x in s if int... |
def read_file(filename):
"""
Opens as file and returns it as a single string
Arguments:
filename (str): full path to the file
"""
try:
with open(filename, 'r') as df:
return df.readlines()
except Exception as e:
print("Error while accessing dependencies file"... |
def ipv6exp(ip6addr):
"""ipv6 address expanding function
replace :: in an IPv6address with zeros
return the list after split(':')
"""
ast2=ip6addr.count('::')
if(ast2==0): return ip6addr.split(':')
ast1=ip6addr.count(':')-2*ast2
num=7-ast1
i=1
pad=':'
while i<num:
pa... |
def invertKey(key):
"""
Inverts a substitution cipher key so that an encryption key becomes a decryption key and vice versa.
"""
invkey = {}
for (key, subst) in key.items():
if subst in invkey: raise Exception("Duplicate key " + subst)
invkey[subst] = key
return invkey |
def move_from_vertex(vertex, board_size):
"""Interpret a string representing a vertex, as specified by GTP.
Returns a pair of coordinates (row, col) in range(0, board_size)
Raises ValueError with an appropriate message if 'vertex' isn't a valid GTP
vertex specification for a board of size 'board_size'... |
def get_canonical_encoding_name(name):
# type: (str) -> str
"""Given an encoding name, get the canonical name from a codec lookup.
:param str name: The name of the codec to lookup
:return: The canonical version of the codec name
:rtype: str
"""
import codecs
try:
codec = codec... |
def remove_protocol_from_url(url):
""" Supplied URL may be null, if not ensure http:// or https://
etc... is stripped off.
"""
if url is None:
return url
# We have a URL
if url.find('://') > 0:
new_url = url.split('://')[1]
else:
new_url = url
return new_url.rstr... |
def _auth_items_to_dict(auth_items):
"""Takes a list of auth_items and returns a dictionary mapping the items
to their respective step names, i.e..:
[{"step_name": ..., "threshold": ..., "authorized_functionaries": ...}, ...]
-->
{<step name> : {"step_name": ..., "threshold": ..., "authorized_..."}, ...}
""... |
def f1x_p(x,p):
"""
General 1/x function: a + b/x
Parameters
----------
x : float or array_like of floats
independent variable
p : iterable of floats
parameters (`len(p)=2`)
`p[0]` a
`p[1]` b
Returns
-------
float
function value(s)
"""
... |
def set_optimizer_state_devices(state, device_id=None):
"""
set state in optimizer to a device. move to cpu if device_id==None
:param state: optimizer.state
:param device_id: None or a number
:return:
"""
for k, v in state.items():
for k2 in v.keys():
if hasattr(v[k2], "c... |
def find( s, target ):
"""version of find that returns len( s ) when target is not found"""
result = s.find( target )
if result == -1: result = len( s )
return result |
def uh(a): #'12345' -> 0x12345
"""Convert a decimal string representation of a number to an integer.
Example:
uh('12345') == 0x12345
"""
return int(a, 16) |
def is_url(config_file):
"""
Returns true if 'config_file` starts with `http` which indicates that it's
an url.
"""
return config_file.startswith('http') |
def is_valid_arp(pkt):
"""Check if a packet is arp."""
try:
return pkt[12:14] == b'\x08\x06'
except:
return False |
def pointDistance( x1, y1, x2, y2 ):
"""Calculates the distance between P1 and P2."""
dist = ( ( float(x2) - float(x1) ) ** 2 + ( float(y2) - float(y1) ) **2 ) ** 0.5
return dist |
def correct_cursors_pos(cursors, rows, columns):
"""
Correct cursors (pixels) so they do not become larger than datastructures shape
"""
if(cursors['x1'] < 0):
cursors['x1'] = 0
if(cursors['x1'] >= columns):
cursors['x1'] = columns
if(cursors['x2'] < 0):
cursors['x2'] =... |
def get_text_from_ocr(res):
"""
Simply extract the text from OCR
:param res: OCR result string
:return: The text only
"""
res_string = ''
for pages in res['analyzeResult']['readResults']: # Added page
for lines in pages['lines']:
for words in lines['words']:
... |
def extract_html_body(html: str) -> str:
"""Returns the content of the html <body> tag."""
body_start = html.index("<body>") + 6
body_end = html.index("</body>")
return html[body_start:body_end] |
def tabify(s):
""" Takes an array of strings and
outputs a single string separated
by tab characters
:type s: list
:param s: list of strings
:raises: N/A
:rtype: string
"""
s = '\t'.join(s)
return s |
def send_wsgi_response(status, headers, content, start_response,
cors_handler=None):
"""Dump reformatted response to CGI start_response.
This calls start_response and returns the response body.
Args:
status: A string containing the HTTP status code to send.
headers: A list of (hea... |
def neglect_none(*values):
"""Return a tuple of values, considering only elements that are not None.
If the tuple only has one element, just return that element.
"""
ret = tuple([v for v in values if v is not None])
if len(ret) == 1:
return ret[0]
return ret |
def graph_is_connected(edges, players):
"""
Test if the set of edges defines a graph in which each player is connected
to at least one other player. This function does not test if the graph is
fully connected in the sense that each node is reachable from every other
node.
Parameters:
------... |
def common_stock(trade):
"""Generate a message for stock transactions."""
trade_type = trade['type'].lower()
user = trade['User']['username']
symbol = trade['symbol'].upper()
price = "${:,.2f}".format(trade['price_filled'])
quantity = trade['quantity']
action = "bought" if "buy" in trade_ty... |
def f1_score(this_precision, this_recall):
""" Returns f1 score
>>> f1_score(test_rank_metrics.precision, test_rank_metrics.recall)
1.0
"""
if this_precision + this_recall > 0:
return 2 * this_precision * this_recall / (this_precision + this_recall)
else:
return None |
def process_resize_value(resize_spec):
"""Helper method to process input resize spec.
Args:
resize_spec: Either None, a python scalar, or a sequence with length <=2.
Each value in the sequence should be a python integer.
Returns:
None if input size is not valid, or 2-tuple of (height, width), deri... |
def transaction_update_spents(txs, address):
"""
Update spent information for list of transactions for a specific address. This method assumes the list of
transaction complete and up-to-date.
This methods loops through all the transaction and update all transaction outputs for given address, checks
... |
def bit_count(i):
"""Count the number of set bits in *i*."""
# nicked from http://wiki.python.org/moin/BitManipulation
count = 0
while i:
i &= i - 1
count += 1
return count |
def _foreign_keys(value):
"""_foreign_keys
key name is changed to foreign_key
"""
key = "foreign_key"
if value:
foreign_keys = []
for col in value:
foreign_keys.append(col.target_fullname)
if len(foreign_keys) > 1:
return {key: foreign_keys}
... |
def box_label(key, verbose=False):
"""Label boxes in graph by chunk index
>>> box_label(('x', 1, 2, 3))
'(1, 2, 3)'
>>> box_label(('x', 123))
'123'
>>> box_label('x')
''
"""
if isinstance(key, tuple):
key = key[1:]
if len(key) == 1:
[key] = key
re... |
def output_baseline(lines):
"""
Output a writable string of the lines
:param lines: The lines
:return: The string
"""
result = ""
for positions in lines:
first_time = True
positions = list(positions)
for i in range(0, len(positions) // 2):
if not first_t... |
def to_unsigned(x: int, width: int) -> int:
"""
Convert signed value into unsigned
:param x: original value
:param width in bits
"""
pow2w = 2**width
if x < 0:
x += pow2w
assert 0 <= x < pow2w
return x |
def count_median(lst):
"""Computes median of list"""
n = len(lst)
if n < 1:
return None
if n % 2 == 1:
return sorted(lst)[n//2]
else:
return sum(sorted(lst)[n//2-1:n//2+1])/2.0 |
def get_bool(flag: str) -> bool:
"""
Get boolean from a string.
"true" / "t" / "y" -> True
"false" / "f" / "n" -> False
:param flag: a string representing a boolean
:return: boolean
"""
flag = flag.lower()
if flag in {"true", "t", "y"}:
return True
if flag in {"false",... |
def write_file(file, text):
"""Writes text to file. Returns -1 on failure."""
try:
with open(file, "w") as f:
f.write(text)
f.close()
except:
return -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.