content stringlengths 42 6.51k |
|---|
def create_vreddit_url(submission, reddit):
"""Read video url from reddit submission"""
try:
return str(submission.media['reddit_video']['fallback_url'])
except Exception as e:
# Submission is a crosspost
try:
crosspost_id = submission.crosspost_parent.split('_')[1]
... |
def humantime(seconds, ndigits=2, one_hour_digit=False):
"""Format a duration as a human readable string.
The duration in seconds (a nonnegative float) is formatted as
``HH:MM:SS.frac``, where the number of fractional digits is
controlled by `ndigits`; if `ndigits` is 0, the decimal point is not
pr... |
def get_all_files_of_same_type(experiments, filtered_csvs):
"""
Returns
-------
dict_holding_files_and_run_types: dict
A dictionary of different experiment types as keys
along with the paths to experimental results for that
key across different seeds.
"""
dict_holding... |
def _get_cores_and_type(config, fc_dir, run_info_yaml,
numcores=None, paralleltype=None):
"""Return core and parallelization approach from commandline.
Prefers passed commandline parameters over pre-configured, defaulting
to a local run on a single core.
"""
config_cores = c... |
def max_digits(x):
"""
Return the maximum integer that has at most ``x`` digits:
>>> max_digits(4)
9999
>>> max_digits(0)
0
"""
return (10 ** x) - 1 |
def remote_bazel_options(crosstool_top):
"""Returns bazel options for the "remote" execution strategy."""
k8 = [
"--cpu=k8",
"--host_cpu=k8",
"--crosstool_top=" + crosstool_top,
"--define=EXECUTOR=remote",
]
return k8 + [
"--spawn_strategy=remote",
"--genrule_strategy=remote"... |
def truedicts(all):
"""
Generates a pair of dictionairies containg all true tail and head completions.
:param all: A list of 3-tuples containing all known true triples
:return:
"""
heads, tails = {(p, o) : [] for _, p, o in all}, {(s, p) : [] for s, p, _ in all}
for s, p, o in all:
... |
def get_obs_projects():
"""
Return a list of strings with the names of observations projects.
Please keep this list up to date, or replace it with something more
sensible.
Returns
---------
list
Returns a list of strings of the various types of observational data.
"""
obs_p... |
def demo_app_name(name):
""" Returns a capitalized title for the app, with "Dash"
in front."""
return 'Dash ' + name.replace('app_', '').replace('_', ' ').title() |
def _sort_string_value(sort_type: int) -> str:
"""
Returns the string corresponding to the sort type integer
:param sort_type:
:return:
"""
if sort_type not in {0, 1, 2, 3}:
raise ValueError(f"Sort Number '{sort_type}' Is Invalid -> Must Be 0, 1, 2 or 3")
else:
sort_dict = {0... |
def lfnToPFN( path, tfcProt = 'rfio'):
"""Converts an LFN to a PFN. For example:
/store/cmst3/user/cbern/CMG/TauPlusX/Run2011A-03Oct2011-v1/AOD/V2/PAT_CMG_V2_4_0/H2TAUTAU_Nov21
->
root://eoscms//eos/cms/store/cmst3/user/cbern/CMG/TauPlusX/Run2011A-03Oct2011-v1/AOD/V2/PAT_CMG_V2_4_0/H2TAUTAU_Nov21?svcCla... |
def sublist_indices(sub, full):
"""
Returns a list of indices of the full list that contain the sub list
:param sub: list
:param full: list
:return: list
>>> sublist_indices(['Felix'], ['De', 'kat', 'genaamd', 'Felix', 'eet', 'geen', 'Felix'])
[[3], [6]]
>>> sublist_indices(
... |
def add_zero(number):
"""
Add a zero if the value doesn't have
2 digits behind it's decimal point
"""
if number == '':
return ''
else:
list_number = list(str(number))
if len(list_number[list_number.index('.') + 1:]) < 2:
list_number.append('0')
return ... |
def time_to_frame(time_s, fs=250):
"""Convert time in second to frame"""
return int(round(time_s * fs)) |
def fit_text(width, text, center=False):
"""Fits text to screen size
Helper function to fit text within a given width. Used to fix issue with status/title bar text
being too long
Parameters
----------
width : int
width of window in characters
text : str
input text
cente... |
def repr_args(args, dlim=", ", start=None):
"""
Represent arguments.
Parameters
----------
args : Iterable[Any]
Arguments.
dlim : str, optional
Delimiter. The default is ", ".
start : str, optional
Start of return value. Defaults to delimiter value.
Examples
... |
def is_dict_like(obj, attr=('keys', 'items')):
"""test if object is dict like"""
for a in attr:
if not hasattr(obj, a):
return False
return True |
def flatten(array):
"""Flattens a list of lists.
e.g. [[1, 2, 3], [4, 5, 6]] --> [1, 2, 3, 4, 5, 6]
"""
flat = []
for element in array:
flat.extend(element)
return flat |
def normalize_upload(upload):
"""
For Recipe System v2.0, upload shall now be a list of things to send
to fitsstore.
E.g.,
$ reduce --upload metrics <file.fits> <file2.fits>
$ reduce --upload metrics, calibs <file.fits> <file2.fits>
$ reduce --upload metrics, calibs, science <file.fits> <fil... |
def FormatSeconds(secs):
"""Formats seconds for easier reading.
@type secs: number
@param secs: Number of seconds
@rtype: string
@return: Formatted seconds (e.g. "2d 9h 19m 49s")
"""
parts = []
secs = round(secs, 0)
if secs > 0:
# Negative values would be a bit tricky
for unit, one in [("d... |
def search(f):
"""Return the smallest non-negative integer x for which f(x) is a true value."""
x = 0
while True:
if f(x):
return x
x += 1 |
def next_player(player_id):
"""
Determine who should play next based on current player.
"""
if player_id == 1:
return 2
return 1 |
def subdivise(tiles, zoom_current, zoom_target):
"""
Subdivise a list of tiles at level zoom_current into tiles at level zoom_target.
"""
coords = list()
ratio = 2 ** (zoom_target - zoom_current)
for x, y in tiles:
for X in range(ratio):
for Y in range(ratio):
... |
def is_serial_increased(old, new):
""" Return true if serial number was increased using RFC 1982 logic. """
old, new = (int(n) for n in [old, new])
diff = (new - old) % 2**32
return 0 < diff < (2**31 - 1) |
def reverse(s):
"""Return the sequence string in reverse order."""
letters = list(s)
letters.reverse()
return ''.join(letters) |
def is_url(word):
"""
Lazy check if a word is an url. True if word contains all of {':' '/' '.'}.
"""
return bool(set('./:').issubset(word)) |
def merge_dicts(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result |
def interpret_line(line, splitter=','):
"""
Split text into arguments and parse each of them to an appropriate format (int, float or string)
Args:
line: text line
splitter: value to split by
Returns: list of arguments
"""
parsed = []
elms = line.split(splitter)
for elm i... |
def histogram_flat ( flatness, q_min, q_max, h ):
"""Returns a signal that the histogram is sufficiently flat."""
# We only look at the histogram in the range of q visited during the run
# The flatness parameter should be in (0,1), higher values corresponding to flatter histograms
import numpy as np
... |
def _compress_condition_keys_only(data: dict) -> dict:
"""
a function that merges a condition key node with its only child (a token that has an int value)
"""
# this has been found heuristically. There's no way to explain it, just follow the test cases.
# there's probably a much easier way, f.e. by ... |
def build_s3_url(filenames, bucket):
"""
convert filenames to AWS S3 URLs
params:
bucket: string, AWS S3 bucket name
filenames: list of strings, AWS S3 filenames
"""
s3_urls = []
for f in filenames:
s3_urls.append('https://{}.s3.amazonaws.com/{}'.format(bucket, f))
retur... |
def truncate_to_significant_bits(input_x: int, num_significant_bits: int) -> int:
"""
Truncates the number such that only the top num_significant_bits contain 1s.
and the rest of the number is 0s (in binary). Ignores decimals and leading
zeroes. For example, -0b011110101 and 2, returns -0b11000000.
... |
def array_to_string(s):
"""gets a printable string for a string array."""
return ", ".join(s) |
def sanitize_webscrape_name(name):
""" Sanitizes webscrape powerplant names by removing unwanted
strings (listed in blacklist), applying lower case, and deleting
trailing whitespace.
Parameters
----------
name: str
webscrape plant name
Returns
-------
name: str
sani... |
def problem1(individual):
"""
Implements the first test problem ("bi-objetive Sphere Model").
Variables = 2
Objetives = 2
f(x) = (x'x, (x - a)'(x - a))' with a = (0, 1)' and a, x element of R^2.
Bounds [0, 1]
@author Cesar Revelo
"""
a = [0,1]
f1 = (individual[0] ** 2) + (... |
def normalized_value(xs):
""" normalizes a list of numbers
:param xs: a list of numbers
:return: a normalized list
"""
minval = min(xs)
maxval = max(xs)
minmax = (maxval-minval) * 1.0
return [(x - minval) / minmax for x in xs] |
def hexcolor_to_rgbcc(hexcolor):
""" Converts an Hex color to its equivalent Red, Green, Blue
Converse = hexcolor = (r << 16) + (g << 8) + b
"""
r = (hexcolor >> 16) & 0x7F
g = (hexcolor >> 8) & 0x7F
b = hexcolor & 0x7F
return r, g, b |
def is_randomized(key):
"""
Helper to determine if the key in the state_dict() is a set of parameters that is randomly initialized.
Some weights are not randomly initalized and won't be afffected by seed, particularly layer norm
weights and biases, and bias terms in general.
"""
# regexes for co... |
def normalize_TD_data(data, data_zero, data_one):
"""
Normalizes measured data to refernce signals for zero and one
"""
return (data - data_zero) / (data_one - data_zero) |
def batch_eval(k_function, batch_iterable):
"""
eval a keras function across a list, hiding the fact that keras requires
you to pass a list to everything for some reason.
"""
return [k_function([bx]) for bx in batch_iterable] |
def ascii_lower(string):
"""Lower-case, but only in the ASCII range."""
return string.encode('utf8').lower().decode('utf8') |
def L90_indicator(row):
"""
Determine the indicator of L90 as one of five indicators
"""
if row < 32:
return "Excellent"
elif row < 42:
return "Good"
elif row < 53:
return "Fair"
elif row <= 79:
return "Poor"
else:
return "Hazard" |
def find_max_occupancy_node(dir_list):
"""
Find node with maximum occupancy.
:param list_dir: list of directories for each node.
:return number: number node in list_dir
"""
count = 0
number = 0
length = 0
for dirs in dir_list:
if length < len(dirs):
length = len(... |
def build_response_params(params, ens_params):
"""Combine member strings with the parameter list"""
out = []
for param in params:
for ens in ens_params:
if ens == 'm0':
out.append(param)
else:
out.append('{}-{}'.format(param, ens))
return o... |
def unlink(text):
"""Find a link in a text string, and replaces it with RST-equiv."""
A_HREF = '<a href="'
A_HREF_CLOSE = '">'
A_HREF_TAG_CLOSE = '</a>'
find_a_href = text.find(A_HREF)
if find_a_href == -1:
return text
find_a_href_close = text.find(A_HREF_CLOSE)
if find_a_href_... |
def speech_response_with_card(title, output, cardcontent, endsession):
""" create a simple json response with card """
return {
'card': {
'type': 'Simple',
'title': title,
'content': cardcontent
},
'outputSpeech': {
'type': 'PlainText',
... |
def ffs(num):
"""Find the lowest order bit that is set
Args:
num: the number to search
Returns:
The 0-based index of the lowest order bit that is set, or None if no bits are set
"""
if num == 0:
return None
i = 0
while (num % 2) == 0:
i += 1
num = nu... |
def rotate_letter(letter, n):
"""Rotates a letter by n places. Does not change other chars.
letter: single-letter string
n: int
Returns: single-letter string
"""
if letter.isupper():
start = ord('A')
elif letter.islower():
start = ord('a')
else:
return... |
def filter_separate(pred, seq):
"""Generic filter function that produces two lists, one for which the
predicate is true, and the other elements."""
inlist = []
outlist = []
for e in seq:
if pred(e):
inlist.append(e)
else:
outlist.append(e)
return inlist, o... |
def check_not_finished_board(board: list):
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5', \
'*?????*', '*?????*', '*2*1***'])
False
>>> c... |
def _try_pydatetime(x):
"""Opportunistically try to convert to pandas time indexes
since plotly doesn't know how to handle them.
"""
try:
x = x.to_pydatetime()
except AttributeError:
pass
return x |
def set_intersection(list1, list2):
"""
Using the built-in 'intersection()' method form a 'set()' element.
'intersection()' can have as parameters more than two sets.
:param list1:
:param list2:
:return:
"""
set1 = set(list1)
set2 = set(list2)
return list(set1.intersection(set2)) |
def calculate_manhattan_dist(idx, value, n):
"""calculate the manhattan distance of a tile"""
### STUDENT CODE GOES HERE ###
if not value:
return 0
cur_row_idx = idx // n + 1
cur_col_idx = idx % n + 1
goal_row_idx = value // n + 1
goal_col_idx = value % n + 1
return abs(cur_... |
def merge_dicts(x, y, z=None):
"""Given two dicts, merge them into a new dict as a shallow copy."""
# https://stackoverflow.com/a/26853961
a = x.copy()
a.update(y)
if z is not None:
a.update(z)
return a |
def IsMultiPanel(hcuts, vcuts) -> bool:
"""
Check if the image is multi-panel or not.
Could have more logic.
"""
return bool(hcuts or vcuts) |
def bad_argument(*args, **kwargs) -> dict:
"""
Bad Option exception response
:return: OpenC2 response message - dict
"""
return dict(
status=501,
status_text="Option not supported"
) |
def negate(signal):
"""
negate the signal
"""
negated_signal = signal * (-1)
return negated_signal |
def _check_can_broadcast_to(shape, target_shape):
"""Determines if shape can be broadcast to target_shape."""
ndim = len(shape)
ndim_target = len(target_shape)
if ndim > ndim_target:
return False
for i, j in zip(reversed(shape), reversed(target_shape)):
if i not in (1, j):
... |
def calculate_fitness(info):
"""Calculates a fitness score based on Gym information"""
return info['distance'] |
def escape(s):
"""Taken from python's html library in 3.x escapes the html for python
Replace special characters "&", "<" and ">" to HTML-safe sequences.
Also translates the double quote and single quote chars, as well as
performs a simple nl2br operation.
"""
escapeMap = {ord('&'): '&', or... |
def s_to_hms(seconds):
""" Get tuple (hours, minutes, seconds) from total seconds """
h, r = divmod(seconds, 3600)
m, s = divmod(r, 60)
return h, m, s |
def get_name(name, list_of_name, size=1):
"""
:param name: (string) the param name
:param list_of_name: (string) the list of param name
:param size: (int) the size of the name used
:return: (string) the param name selected
"""
if name[0:size] not in list_of_name:
return name[0:size]... |
def get_config_params(subject_id, table):
"""Inserts subject_id to the top of the table
Parameters
----------
subject_id : String
Subject_id
table : List
2d table that will go into QA report
Outputs
-------
table : List
"""
table.insert(0,['subject_id',subject_id])
return tabl... |
def f1(a1):
"""
@type a1: str
@precondition: len(a1) > 2
@rtype: basestring
@postcondition: len(result) == len(a1) + 3
"""
if a1 == "bad output":
return 17
elif a1 == "bad postcondition":
return "def"
else:
return "%sdef" % a1 |
def get_process_command(cmd_args):
"""Get command-line text for task process."""
# Join arguments into command string, escaping any with spaces.
cmd = ''
for arg_index, arg in enumerate(cmd_args):
if arg_index > 0:
cmd += ' '
if ' ' in arg:
cmd += '"' + arg + '"'
else:
cmd += arg
... |
def pad(source: str, pad_len: int, align: str) -> str:
"""Return a padded string.
:param source: The string to be padded.
:param pad_len: The total length of the string to be returned.
:param align: The alignment for the string.
:return: The padded string.
"""
return "{s:{a}{n}}".format(s=s... |
def array_dtype(a):
"""Element data type of an array or array-like object"""
if hasattr(a,"dtype"): return a.dtype
if not hasattr(a,"__len__"): return type(a)
if len(a) == 0: return float
# If 'a' is a list, it may contain element of different data type.
# Converting it to an array, make numpy s... |
def _bucket_boundaries(max_length, min_length=8, length_bucket_step=1.1):
"""A default set of length-bucket boundaries."""
assert length_bucket_step > 1.0
x = min_length
boundaries = []
while x < max_length:
boundaries.append(x)
x = max(x + 1, int(x * length_bucket_step))
return boundaries |
def get_tag_val(tag, xml_str, match=None):
""" quick access to tag values via string splitting
FIXME: use regex...
"""
def get_tag_content(stri):
# string starts within a tag def, like ab='23' c='2'>foo</tag>
# we return 'foo'
return stri.split('</', 1)[0].split('>', 1)[1]
... |
def get_muted_layers(layers):
"""Given a list of layers, return only those that are muted
:param layers: list of layers to filter
:type layers: list
:return: list of layers that are muted.
:rtype: list
"""
return [layer for layer in layers if layer.get_muted()] |
def time_str(uptime):
""" converts uptime in seconds to a time string """
if not isinstance(uptime, int):
return ""
mins = (uptime/60) % 60
hours = (uptime/60/60) % 24
days = (uptime/24/60/60) % 365
years = uptime/365/24/60/60
if years == 0:
if days == 0:
if hours == 0:... |
def parse_line(self, line):
""" Split line into command and argument.
:param line: line to parse
:return: (command, argument)
"""
command, _, arg = line.strip().partition(" ")
return command, arg.strip() |
def beautify(name):
""" make file name looks better """
return name.replace('_', ' ').replace('-', ' ').title() |
def even_evens(some_list):
"""
Give a list 'some_list', return a list of only the even numbers from the
even indices of 'some_list'.
"""
return [x for x in some_list[::2] if x % 2 == 0] |
def create_leaf_node(stats):
""" Creates a leaf node
:param stats: stats on the partition
:return: a leaf node in the form ['Leaves', ['yes', 4, 10, 40%],...]
"""
tree = ['Leaves']
for row in stats:
if (row[1] > 0):
tree.append(row)
return tree |
def like_list(field, values, case="", condition="OR"):
"""Make a `<field> LIKE '%value%'` string for list of values.
Args:
field (str): field to use in LIKE statement; may need to be quoted
values (iterable): values to convert to LIKE query
condition (str): 'AND' or 'OR' (default 'OR')
... |
def order_json_objects(obj):
"""
Recusively orders all elemts in a Json object.
Source:
https://stackoverflow.com/questions/25851183/how-to-compare-two-json-objects-with-the-same-elements-in-a-different-order-equa
"""
if isinstance(obj, dict):
return sorted((k, order_json_objects(v)) for... |
def metaclass_instance_name_for_class(classname):
"""Return the name of the C++ metaclass instance for the given class."""
if '::' in classname:
return None
return classname + '::gMetaClass' |
def split_list_into_n_lists(l, n):
"""Split a list into n lists.
Args:
l: List of stuff.
n: Number of new lists to generate.
Returns:
list: List of n lists.
"""
return [l[i::n] for i in range(n)] |
def get_positive_axis(axis, ndims, axis_name="axis", ndims_name="ndims"):
"""Validate an `axis` parameter, and normalize it to be positive.
If `ndims` is known (i.e., not `None`), then check that `axis` is in the
range `-ndims <= axis < ndims`, and return `axis` (if `axis >= 0`) or
`axis + ndims` (otherwise).
If `... |
def get_users(metadata):
"""
Pull users, handles hidden user errors
Parameters:
metadata: sheet of metadata from mwclient
Returns:
the list of users
"""
users = []
for rev in metadata:
try:
users.append(rev["user"])
except (KeyError):
u... |
def cell_cube_coord(c):
""" Returns a tuple with the cube coordinates corresponding to the
given axial coordinates.
"""
x = c[0]
z = c[1]
return (x, -x-z, z) |
def get_times(ts_full, ts_system, len_state, sys_position, sys_length):
"""
This is a function specifically designed for TEDOPA systems. It calculates
the proper 'ts' and 'subsystems' input lists for :func:`tmps.evolve` from a
list of times where the full state shall be returned and a list of times
... |
def get_table_display_properties(request, default_items=25, default_sort_column = "id",
default_sort_descending = True, default_filters = {}):
"""Extract some display properties from a request object. The following
parameters (with default values) are extracted. Andy of t... |
def find_base_match(char, matrix):
"""Return list of coordinates wherein char matched inside matrix.
Args:
char (str): A single-length string
matrix (list): A list containing lines of string.
row_length (int): An integer which represents the height of the matrix.
column_length (... |
def check_draw(board):
""" Checks for a draw """
return ' ' not in board |
def build_resilient_url(host, port):
"""
build basic url to resilient instance
:param host: host name
:param port: port
:return: base url
"""
return "https://{0}:{1}".format(host, port) |
def signed_mod(a: int, b: int) -> int:
"""
Signed modulo operation for level top10 encryption/decryption.
"""
a = a & 0xFFFF
r = a % b
if a > 0x7FFF:
return -b + (r - 0x10000) % b
return r |
def hashpjw(s):
"""A simple and reasonable string hash function due to Peter Weinberger"""
val = 0
for c in s:
val = (val << 4) + ord(c)
tmp = val & 0xf0000000
if tmp != 0:
val = val ^ (tmp >> 24)
val = val ^ tmp
return val |
def translate(numpoints, refcoords, center_, mode):
"""Translate a molecule using equally weighted points.
:param numpoints: number of points
:type numpoints: int
:param refcoords:
list of reference coordinates, with each set a list of form [x,y,z]
:type: list
:param center: center ... |
def binary_search(list_obj, value, low, high):
"""
Recursive Binary Search Algoirthm:
Using Divide and Conquer design paradigm to reduce the complexity and increase the efficiency
Arguments:
list_obj: represent list object
value: an object where it's value that we are looking for in the list
low: an int... |
def get_ucr_class_name(id):
"""
This returns the module and class name for a ucr from its id as used in report permissions.
It takes an id and returns the string that needed for `user.can_view_report(string)`.
The class name comes from corehq.reports._make_report_class, if something breaks, look there f... |
def format_path(plot_root: str, variant: str) -> str:
"""
Format path.
Convert representation of variant to
a path.
:param plot_root: root path can be url
:param variant: variant
:return: path of variant resource
"""
return f"{plot_root}{variant}.png" |
def round_up(n: int, div: int):
"""Round up to the nearest multiplier of div."""
return ((n + div - 1) // div) * div |
def _is_bonded(item):
"""Determine if the item refers to a bonded port."""
for attribute in item['attributes']:
if attribute['attributeTypeKeyName'] == 'NON_LACP':
return False
return True |
def json_facts_filtered(returned_json, filter_fields=['manufacturer', 'boardassettag', 'memorysize', 'memoryfree']):
"""Create a nested dict, nodes-to-facts, indexed by certname(node_name), sub-index fact_name.
Creates the dict from the returned_json, Use filter_fields to only included the listed facts on the ... |
def get_geom(lines, geom_type='xyz', units='angstrom'):
"""
Takes the lines of an orca output file and returns its last geometry in the
specified format
"""
start = ''
end = '\n'
if geom_type == 'xyz' and units == 'angstrom':
start = 'CARTESIAN COORDINATES (ANGSTROEM)\n'
elif geo... |
def calc_median(nums):
"""Calculate the median of a number list."""
N = len(nums)
nums.sort()
if N % 2 == 0:
m1 = N / 2
m2 = (N / 2) + 1
m1 = int(m1) - 1
m2 = int(m2) - 1
median = (nums[m1] + nums[m2]) / 2
else:
m = N / 2
m = int(m) - 1
... |
def _GetShardKeyName(name, index):
"""Gets a key name for a partition on a given shard.
Args:
name: Str name of the shard.
index: Int partitin number.
Returns:
Str key name for the given partition.
"""
return 'CounterShard_%s_%d' % (name, index) |
def compute_shape(coords, reshape_len=None, py_name=""):
"""
Computes the 'shape' of a coords dictionary.
Function used to rearange data in xarrays and
to compute the number of rows/columns to be read in a file.
Parameters
----------
coords: dict
Ordered dictionary of the dimension na... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.