content stringlengths 42 6.51k |
|---|
def runner_protocol_encode(reps_type, reps_data):
"""
encode for runner protocol
:param reps_type:
:param reps_data:
:return:
"""
reps_len = len(reps_data)
reps_header = reps_len.to_bytes(4, byteorder="big")
reps_header = bytearray(reps_header)
reps_header[0] = reps_type
reps... |
def create_default_query(relative):
"""Get the given paper."""
query = """
select p.id as from_id, p.title as from_title, p.abstract as from_abstract, p.year as from_year, false as from_is_influential, p.citations as from_citations, a.name as from_author
from paper p, write w, author a
... |
def _match_hash(x, y, no_match=None):
"""Returns an array of the positions of (first) matches of y in x
This is similar to R's `match` or Matlab's `[Lia, Locb] = ismember`
As in R's `match`, a hash (i.e. dictionary) is built to do the
mapping.
"""
x_val2ind = {v: i for i, v in enumera... |
def convert_to_tuple_of_two_int(value, name):
"""Transforms iterable of 2 integers into an tuple of 2 integers.
Args:
value: A iterable of 2 ints.
name: The name of the argument being validated, e.g., sparsity_m_by_n.
Returns:
A tuple of 2 integers.
Raises:
ValueError: If something else than ... |
def load_options(device="cpu:0"):
"""Format options for pytorch."""
if device == "cuda":
device = "cuda:0"
if device == "cpu":
device = "cpu:0"
return {"device": device} |
def startswith(value, arg):
"""
Test whether a string starts with the given argument
"""
return str(value).startswith(arg) |
def _format_number_list(*args, **kwargs):
"""
Format a list of numbers into a nice string.
"""
fmt = kwargs.pop('fmt', '{:.3g}')
sep = kwargs.pop('sep', ' ')
return sep.join(fmt.format(i) for i in args) |
def oauth_config(application_id, application_name = '',
client_string = '', consumer_key = '',
consumer_secret = ''):
"""Creates a new OAuth configuration.
:param application_id: The unique identifier of the client application.
:type application_id: str
:param ... |
def convert_str_to_bool(item):
"""Converts a boolean string to a boolean value"""
if isinstance(item, str):
return item.lower() == "true"
return False |
def _has_system_frames(frames):
"""
Determines whether there are any frames in the stacktrace with in_app=false.
"""
system_frames = 0
for frame in frames:
if not frame.get("in_app"):
system_frames += 1
return bool(system_frames) and len(frames) != system_frames |
def NumVisTerms(doc):
"""Number of visible terms on the page"""
_, terms = doc
return len(terms) |
def combine_loss_components(critic_loss_val, actor_loss_val, entropy_val,
actor_loss_weight, entropy_bonus):
"""Combine the components in the combined AWR loss."""
return critic_loss_val + (actor_loss_val * actor_loss_weight) - (
entropy_val * entropy_bonus) |
def normalize_scalar(value):
"""
5.1.1.4 - c.1:
Scalar values shall be rendered using their hexadecimal representation.
"""
return "%x" % value |
def HexDump(val, numBits=32):
"""
1. do not print 'L'
2. Handle negatives and large numbers by mod (2^numBits)
3. print fixed length, prepend with zeros.
Length is exactly 2+(numBits/4)
4. Do print 0x Why?
so that they can be easily distinguished using sed/rx
"""
val = val & ((... |
def flatten(nested):
"""Flatten a nested list."""
return [item for li in nested for item in li] |
def doprefix(site_url):
"""
Returns protocol prefix for url if needed.
"""
if site_url.startswith("http://") or site_url.startswith("https://"):
return ""
return "http://" |
def multiply(data, params=None):
"""
Multiply function aggregation.
Example config:
.. code-block:: python
config = {
...
'fields': ['timestamp', 'x'],
'aggregations': [
{
'func': 'multiply',
'field': ... |
def get_bollinger_bands(rm, rstd):
"""Return upper and lower Bollinger Bands."""
upper_band = rm + rstd*2
lower_band = rm - rstd*2
return upper_band, lower_band |
def remove_duplicates(lst):
"""
Utility function to remove duplicates from a list while preserving the
order of the elements
"""
seen = set()
seen_add = seen.add
return [item for item in lst if item not in seen and not seen_add(item)] |
def calculate_predictive_value(TP, TN, FP, FN):
"""
Calculates the Positive and Negative Predictive value of the supplied reference and test data
For PPV and NPV, if the denominator is 0, the result is defined as 1, as there were no false positive/negatives
Input:
ref: Numpy boolean ar... |
def sign(number):
"""
Sign of a number
:param number:
INPUT parameter:
number : number that's sign is to be calculated (numeric)
OUTPUT:
value of sign(number) (-1, 0, 1)
"""
if number > 0.0:
return 1
elif number < 0.0:
return -1
else:
return 0 |
def set_plot_properties(filename):
"""
Get "standard" plot properties based on the filename.
:param filename:
:return plot_properties:
"""
plot_properties = {}
if 'OGLE' in filename:
plot_properties['color'] = 'black'
plot_properties['zorder'] = 10
elif 'MOA' in filenam... |
def _rle_decode_segment(data):
"""Return a single segment of decoded RLE data as bytearray.
Parameters
----------
data : bytes
The segment data to be decoded.
Returns
-------
bytearray
The decoded segment.
"""
data = bytearray(data)
result = bytearray()
pos... |
def world2pixel(x, y, w, h, bbox):
"""Converts world coordinates
to image pixel coordinates"""
# Bounding box of the map
minx, miny, maxx, maxy = bbox
# world x distance
xdist = maxx - minx
# world y distance
ydist = maxy - miny
# scaling factors for x, y
xratio = w/xdist
yra... |
def _is_leaf_node(merge_node):
"""
Returns True for dicts like {'a': {}}.
"""
return len(merge_node) == 1 and not next(iter(merge_node.values())) |
def classes(*args, **kwargs):
"""Helper function for dynamically assembling a list of CSS class names
in templates.
Any positional arguments are added to the list of class names. All
positional arguments must be strings:
>>> classes('foo', 'bar')
u'foo bar'
In addition, the names of any s... |
def merge(a1, a2):
"""
Merges two arrays of numbers (both of which are expected to be pre-sorted into ascending order),
into a new array, sorted in ascending order.
"""
nTotalLength = len(a1) + len(a2)
aMerged = []
i = 0
j = 0
while len(aMerged) < nTotalLength:
if i == len(... |
def get_position_list(target, obs):
"""
Get the list of positions of obs in target
"""
pos_of_obs_in_target = [0]
if len(obs) != 0:
pos_of_obs_in_target =\
[j for j, w in enumerate(obs, start=1) if w in target]
if len(pos_of_obs_in_target) == 0:
pos_of_obs... |
def dumps_utf8string(obj):
"""
Convert the specified L{dbus.types.UTF8String} to bpickle's
representation for C{unicode} data.
"""
return "u%s:%s" % (len(obj), obj) |
def unique_append(old_list, new_list):
"""
Add items from new_list to end of old_list if those items are not
already in old list -- returned list will have unique entries.
Preserve order (which is why we can't do this quicker with dicts).
"""
combined = old_list
for item in new_list:
... |
def flipBits ( binVal ):
"""
This function will convert the given binary string to a binary string with the
bits flipped.
Parameters
----------
binVal:
An binary string without the leading '0b'
Returns
-------
flippedBinVal:
A binary string of flipped bits without the leading '0b'
"""
... |
def intersect(l0, l1):
"""Given two lists return the intersection."""
return [e for e in l0 if e in l1] |
def __filter_overlap(index):
"""Filters indexes in list if they overlap."""
if len(index) == 2:
return index
index_f = []
i = 0
j = i + 1
while j < len(index):
if index[i][1] > index[j][0]:
index[i] = (min(index[i][0], index[j][1]),
max(index[i... |
def uppercase_first_letter(string):
"""Return a copy of the given string with the first letter in uppercase"""
return string[0].upper() + string[1:] |
def prepare_fetch_incidents_query(fetch_timestamp: str,
fetch_severity: list,
fetch_table: str,
fetch_subtype: list,
fetch_fields: str,
fetch_limit: s... |
def apply_m_chg(line, mol):
"""
Parses a CHG line from the property block.
This will 0-out the charge on any atom that is not listed.
0123456789
M CHGnn8 aaa vvv ...
aaa An atom number to alter the charge for
vvv The ammount of charge on the target atom
"""
if len(line) == 0:
... |
def clamp(x, low=None, high=None):
"""Clamps a value 'x' between the values 'low' and 'high'
If low == None, then there is no lower bound
If high == None, then there is no upper bound
"""
if high is not None and x > high:
return high
elif low is not None and x < low:
return... |
def leastDifference(a, b, c):
""" Return the smallest difference between 2 numbers
among a b and c.
>>> least_Difference(1,5,-5)
4
"""
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(c - a)
return min(diff1, diff2, diff3) |
def bisect_search1(L, e):
"""where L is list and e is element
>>> bisect_search1([], 1)
False
>>> bisect_search1([2], 1)
False
>>> bisect_search1([1], 1)
True
"""
if L == []:
return False
elif len(L) == 1:
return L[0] == e
else:
half = len(L) // 2
if L(half) > e:
return bisect... |
def max_sort(nums):
"""
Evaluate the space complexity of this sorting algorithm.
"""
result = []
while len(nums) > 1:
index_max = max(range(len(nums)), key=nums.__getitem__)
result.insert(0, nums[index_max])
nums = list(nums[:index_max]) + list(nums[index_max + 1:])
retur... |
def subscribe_data(dest, headers_data):
"""
Generate subscription payload for market data subscription
:param dest: destination path
:param headers: id
:return:string of given data
"""
return "SUBSCRIBE\nid:%s\ndestination:%s\n\n\x00\n" % (
headers_data.get('id')... |
def gene_panel_choices(institute_obj, case_obj):
"""Populates the multiselect containing all the gene panels to be used in variants filtering
Args:
institute_obj(dict): an institute dictionary
case_obj(dict): a case dictionary
Returns:
panel_list(list): a list of tuples containing t... |
def extract_end(char_seq):
"""all sequences longer than 1014 are ignored"""
if len(char_seq) > 1014:
char_seq = char_seq[-1014:]
return char_seq |
def get_index_difference(idcs1, idcs2):
"""
Assume that the index tuples differ by exactly one index. Find out which dimension-index that is and the difference
(i.e. direction: 0 or 1)
:param idcs1:
:param idcs2:
:return: dim, dir
"""
assert len(idcs1) == len(idcs2)
for dim, (i1,... |
def utf8_lead_byte(b):
""" a utf-8 intermediate byte starts with the bits 10xxxxxx """
return (ord(b) & 0xC0) != 0x80 |
def are_there_enough_tickets(availability):
"""'Enough' meaning there should be more than 2 tickets"""
result = False
for dt in availability:
if sum(map(lambda x: x[1], availability[dt])) >= 3:
result = True
return result |
def frequencies(word_list):
"""
Takes a list of words and returns a dictionary associating
words with frequencies of occurrence
"""
word_freqs = {}
for w in word_list:
if w in word_freqs:
word_freqs[w] += 1
else:
word_freqs[w] = 1
return word_freqs |
def right(index: int) -> int:
"""Gets right descendant's index.
"""
return 2 * index + 1 |
def _build_event_from_results_reader(reader):
"""
Creates an event as a dict from an event in the SDK.
"""
event = {}
for field in list(reader.keys()):
event[field] = reader[field]
return event |
def core_code_str(user_kwargs: dict, disdat_kwargs: dict) -> str:
"""
Replace caching check, caching push, gathar data with this core_code_str.
The sole functionality of this function is to verify it the generator does it work (correctly passing all input params)
:param user_kwargs: dict, parameters fro... |
def num_e(s):
"""
Returns: number of 'e's in s
Parameter: s the string to count
Precondition s is a string
"""
assert type(s) == str, repr(s) + ' is not a string' # get in the habit
# Work on small data (BASE CASE)
if s == '':
return 0
elif len(s) == 1:
if ... |
def import_cls(cls_name):
"""Import class by its fully qualified name.
In terms of current example it is just a small helper function. Please,
don't use it in production approaches.
"""
path_components = cls_name.split('.')
module = __import__('.'.join(path_components[:-1]),
... |
def sext_3(value):
"""Sign-extended 3 bit number.
"""
if value & 0x4:
return 0xfffffff8 | value
return value |
def left_to_right_check(input_line: str):
"""
Check row-wise visibility from left to right.
Return True if number of building from the
left-most hint is visible looking to the right,
False otherwise.
input_line - representing board row.
"""
if input_line[0] == "*":
return True
... |
def newline(text, number=1):
"""returns text with exactly number newlines at the end"""
return text.strip() + ("\n" * number) |
def relay_microdescriptors_query_path(microdescriptor_hashes):
"""
Generates a query path to request microdescriptors by their hashes
from a directory server. For example:
>>> microdescriptor_hashes = ["Z62HG1C9PLIVs8jLi1guO48rzPdcq6tFTLi5s27Zy4U",
... "FkiLuQJe/Gqp4xsHfh... |
def find_event_by_backtracking(initial_event, events, condition_fn):
"""Backtracks to the first event that matches a specific condition and returns that event"""
event = initial_event
visited_events = []
for _ in range(len(events)):
if condition_fn(event, visited_events):
return even... |
def indices_to_list(indices):
"""
Return an abbreviated string representing indices.
e.g. indices = [1, 2, 3, 5, 6, 8, 9, 10, 11, 12, 13, 15, 20]
index_string = '1-3, 5-6, 8-13, 15, 20'
Args:
indices (list):
Returns:
index_string (string): condensed string representation o... |
def matrix_get_minor(m, i, j):
"""
Get minor of a matrix.
:param m:
:param i:
:param j:
:return:
"""
return [row[:j] + row[j + 1:] for row in (m[:i] + m[i + 1:])] |
def _decode_text(value):
"""
Decode a text-like value for display.
Unicode values are returned unchanged. Byte strings will be decoded
with a text-safe replacement for unrecognized characters.
"""
if isinstance(value, bytes):
return value.decode('ascii', 'replace')
else:... |
def get_argument_name(*name_or_flags) -> str:
"""Gets the name of the argument.
:param name_or_flags: Either a name or a list of option strings, e.g. foo or -f, --foo.
:return: The name of the argument (extracted from name_or_flags).
"""
if '-h' in name_or_flags or '--help' in name_or_flags:
... |
def get_managers_from_users(users):
"""get_managers_from_users(users)"""
managers=[]
manager_emails=[]
for user in users:
user_manager_email=user["manager"]
if (user_manager_email not in manager_emails):
user_manager = { "email": user_manager_email }
# add emai... |
def _place_place_rels(place_list, rel_type, rel_direction):
"""Processor for Place-Place relationship."""
return [relation for relation in place_list if relation['direction'] == rel_direction and relation['type-id'] == rel_type] |
def trim_suffix(s, suffix):
"""Removes a suffix from a string if it exists"""
return s[:-len(suffix)] if s.endswith(suffix) else s |
def get_dist(dist_str):
"""
Objective: Calculate how far away an object is from the main car
Returns: Int of distance away in pixels
Parameters:
bit_str: 12-bit lengthed trace
"""
# Define distance scale
dist_scale = 1 # 500 / 1023
int_dist = int(dist_str) # in units out of 1023
... |
def is_number(x):
"""Checks if a string can be converted to int"""
try:
num = int(x)
except ValueError:
return False
return True |
def distance(a,b):
"""Pure python version to compute the levenshtein distance between a and b.
The Levenshtein distance includes insertions, deletions, substitutions;
unlike the Hamming distance, which is substitutions only.
ORIGINALLY FROM: http://hetland.org/coding/python/levenshtein.py
"""
... |
def _spvec2pow(specvec):
"""Convert a spectrum envelope into a power
Parameters
----------
specvec : vector, shape (`fftlen / 2 + 1`)
Vector of specturm envelope |H(w)|^2
Return
------
power : scala,
Power of a frame
"""
# set FFT length
fftl2 = len(specvec) -... |
def transform_str(val, fmt=None, mode=None):
"""
Transform to string with optional str format notation
<dotted>|str str(val)
<dotted>|str:<fmt> <fmt> % val
<dotted>|str:<fmt>:force <fmt> % val or raises
"""
try:
if not fmt:
return st... |
def is_indexable_but_not_string(obj):
"""Return True if ``obj`` is indexable but isn't a string."""
return not hasattr(obj, "strip") and hasattr(obj, "__getitem__") |
def get_overhead(index, cmp_index):
"""Get the overhead between two ffindex files.
Args:
index (list): List of line in the ffindex
cmp_index (list): List of line in the ffindex
Returns:
list: List of overheads
"""
overhead = set()
index_set = set()
for entry in... |
def make_name_valid(name):
"""Make a string into a valid Python variable name."""
if not name:
return None
import string
valid_chars = "_%s%s" % (string.ascii_letters, string.digits)
name = str().join([c for c in name if c in valid_chars])
if not name[0].isalpha():
name = 'a' + n... |
def find_Pythagorean(n):
""" find_Pythagorean() takes an integer n and returns the all the triples from 1 to n """
# set all to 1 because triangle cannot have a side of length 1
a = 1 # side a
b = 1 # side b
c = 1 # side c
# list used to store the triples, in tuple form. initialized to empty... |
def lowerbound(sorted_arr, val):
"""Finds the SMALLEST index to insert the value `val` so that the elements in `sorted_arr` remain sorted."""
# Get the length of the array
n = len(sorted_arr)
# Perform binary search
left = 0
right = n - 1
while left < right:
middle = (left + right)... |
def vector_index(row_idx, col_idx, matrix_size):
"""
Convert from matrix indices to vector index.
Args:
row_idx (int): Row index for matrix.
col_idx (int): Column index for matrix.
matrix_size (int): Size along one axis of the square matrix that input indices are for.
Returns:
... |
def startOfChunk(prevTag, tag, prevType, type_):
"""
checks if a chunk started between the previous and current word;
arguments: previous and current chunk tags, previous and current types
"""
chunkStart = ((prevTag == "B" and tag == "B") or
(prevTag == "B" and tag == "B") or
(prevT... |
def n_angles(theta1_min: float, theta1_max: float, theta1_step=1) -> int:
"""
Computes number of traces for given angles on incidence.
:param theta1_min: minimum incidence angle
:param theta1_max: maximum incidence angle
:param theta1_step: angle of incidence steps, default is 1
:return:
... |
def is_valid_bbox(rect):
"""Left/top must be >= 0, W/H must be > 0"""
return rect[0] >= 0 and rect[1] >= 0 and rect[2] > 0 and rect[3] > 0 |
def get_file_extension(filename):
"""Helper to get the extension of a file. Returns None if the file has no
extension.
"""
try:
return filename.rsplit('.', 1)[1]
except IndexError:
return None |
def check_box(
iou, difficult, crowd, order, matched_ind, iou_threshold, mpolicy="greedy"
):
"""Check box for tp/fp/ignore.
Arguments:
iou (np.array): iou between predicted box and gt boxes.
difficult (np.array): difficult of gt boxes.
order (np.array): sorted order of iou's.
... |
def is_subset(l1, l2):
"""
returns true of l1 is a subset of l2 and 0 otherwise
"""
if len(l2) < len(l1):
return False
for c in l1:
if c not in l2:
return False
return True |
def get_dft_size(window_size):
"""
Returns the smallest power of two that is at least the specified
window size.
"""
dft_size = 1
while dft_size < window_size:
dft_size <<= 1
return dft_size |
def add_dicts(dicts):
"""Combine a list of dictionaries and return the results.
Args:
dicts: List of dicts
Returns:
d: Combined dict
"""
n = {}
for d in dicts:
n.update(d)
return n |
def awgGate(gate, station):
""" Return True if the specified gate can be controlled by the AWG """
awg = getattr(station, 'awg', None)
if awg is None:
return False
return awg.awg_gate(gate) |
def _strip_extensions(s, extensions):
"""Remove all the specified extensions from the supplied string.
Args:
s: string, generally a filename.
extensions: list of strings, extensions to remove. Each extension
is removed in order. For example, To remove .tar.gz, you can
either specify ["... |
def normalized_digest(digest, digest_type='sha512'):
"""Normalize the digest to return version that enables string comparison.
All forms (except the spec example forms) are case insensitive. We
use lowercase as the normalized form.
"""
if digest_type in ('sha512-spec-ex', 'sha256-spec-ex'):
... |
def unique_preserved_list(original_list):
"""
Return the unique items of a list in their original order.
:param original_list:
A list of items that may have duplicate entries.
:type original_list:
list
:returns:
A list with unique entries with the original order preserved.... |
def wbar(ni, agents, compcost):
""" Average computation cost """
return sum(compcost(ni, agent) for agent in agents) / len(agents) |
def keyname(name, i, okey):
"""
>>> keyname('x', 3, [None, None, 0, 2])
('x', 3, 0, 2)
"""
return (name, i) + tuple(k for k in okey if k is not None) |
def bubble_sort(arr: list) -> list:
# sourcery skip: remove-zero-from-range, use-itertools-product
"""Sort a list using bubble sort
Args:
arr (list): the list to be sorted
Returns:
list: the sorted list
"""
size = len(arr)
# Loop over the entire list
for _ in range(1, ... |
def to_page_count(n_entries, entries_per_page):
"""
Calculate the number of pages given a page count.
"""
if n_entries == 0:
return 0
# How this works:
# Say the number of entries per page was 10. Thus we'd want entries 1-10
# to appear on page 1, 11-20 to appear on page 2, and so on... |
def isEven(i):
"""assumes i a positive int
returns True if i is even, otherwise False"""
return i % 2 == 0 |
def urlsafe_address(address):
"""Make an address safe to use in a URL.
Args:
address: A tuple of address information.
Returns:
A 2-tuple of url-safe (address, port)
"""
addr, port, *rest = address
if rest:
# An IPv6 address needs to be surrounded by square brackets
... |
def discoverable(item):
""" used in templates for discovery to avoid non-indicative results. """
if item is None or item == 'Unknown':
return ""
return item |
def avg(arr: list):
"""
Returns the average of the array.
Uses floating-point division.
"""
return sum(arr) / float(len(arr)) |
def wrap_data(data, width=50):
"""list of atoms -> list of lists, chunked at width"""
chunks = []
curr, remain = None, data
while len(remain) > width:
curr, remain = remain[:width], remain[width:]
chunks.append(curr)
chunks.append(remain)
return chunks |
def schedule_timing(bus_stop_code):
"""
Message that will be sent after user types in bus stop code when scheduling message
:param bus_stop_code: Bus Stop Code of what users type in when scheduling message
"""
return 'Bus Stop Code <b>{}</b>\nPlease type in the time you want your message to ' \
... |
def get_bonus(config: dict, reward_rate_discount: float = 0.9) -> float:
"""
Ensures that the tasks have a bonus and estimated time in
accordance with the configuration.
Args:
config: The task configuration (task.yaml)
reward_rate_discount: A discount applied to the reward_rate. Set to 1.... |
def fix_optionparser_whitespace(input):
"""Hacks around whitespace Nazi-ism in OptionParser"""
newline = ' ' * 80
doublespace = '\033[8m.\033[0m' * 2
return input.replace(' ', doublespace).replace('\n', newline) |
def centroid(cluster_list: list) -> list:
"""
Description: This function will calculate the centroid of each cluster
and the number of points in each cluster. Then it returns centroids in centroid_list.
The longitude of centroid is the average longitude for each cluster.
The same is true... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.