content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def snakecase_to_kebab_case(key: str) -> str:
"""Convert snake_case to kebab-case."""
return f'--{key.lower().replace("_", "-")}'
|
5a6f32ac7457b7d88bb717fbc1539ddca82177ce
| 37,390 |
def formatCoreTime(core_time_ms):
"""
Format core time in millis to core hours.
"""
return "%0.2f" % (core_time_ms / 1000 / 3600.0)
|
948245393134e1b9069ed6caab67fb5b028c2212
| 37,391 |
def getEnergy(tl, t, tr, l, r, dl, d, dr):
"""helper for getEnergyMap that returns the energy of a single pixel given its neighbors"""
vertEnergy = tl + 2 * t + tr - dl - 2 * d - dr
horizEnergy = tl + 2 * l + dl - tr - 2 * r - dr
return (vertEnergy ** 2 + horizEnergy ** 2) ** 0.5
|
7f9fc3edb7c8987a2a7fac7a4145e0054fb6b8ee
| 37,399 |
def calc_line_x(y, slope, intercept):
"""Calculate x value given y, slope, intercept"""
return int((y - intercept)/slope)
|
6597394f49ca74f70ca110cd83b258751ba3262d
| 37,405 |
def read_bands(bands):
"""
Read energy bands list, each band per line.
"""
bands = map(str.split, open(bands).readlines())
bands = ["-".join(b) for b in bands]
return bands
|
b116e218df30c804142f6db74f9f886e424bef54
| 37,407 |
import logging
def get_logger(name: str) -> logging.Logger:
""" Gets the appropriate logger for this backend name. """
return logging.getLogger('proxytest.' + name)
|
d0e0f9de13d9b603326b70a6acdbff7f3288b421
| 37,409 |
def parse_str(s):
"""
parser for (stripped) string
:s: the input string to parse
:returns: the string, stripped of leading and trailing whitespace
"""
return s.strip()
|
f8f44a30384f634f6f07acd3de19bcb6c42541b6
| 37,411 |
def get_dict_fields(dict_obj):
"""Returns a list of fields in a `dict` object."""
return dict_obj.keys()
|
b4c8165ca8b883c6503c64d62e31ab99c932884b
| 37,418 |
def is_holidays(holidays_dt, day_dt):
"""
:param holidays_dt: List of holidays with format datetime
:param day_dt: Day with format datetime to analyze
:return: True if day is a holiday, False if not
"""
holidays_dt = [i.date() for i in holidays_dt]
return day_dt.date() in holidays_dt
|
5a8db2929fdde4402bef87f355eb991cd2825e17
| 37,423 |
import re
def clause_count(doc, infinitive_map):
"""Return clause count (heuristic).
This function is decorated by the
:func:`TRUNAJOD:surface_proxies.fix_parse_tree` function, in order to
heuristically count clauses.
:param doc: Text to be processed.
:type doc: Spacy Doc
:param infinitve_map: Lexicon containing maps from conjugate to infinitive.
:type infinitive_map: dict
:return: Clause count
:rtype: int
"""
n_clauses = 0
regexp = re.compile("VerbForm=Fin")
regexp_perif = re.compile("Perif")
for token in doc:
verb_or_aux = token.pos_ in {"VERB", "AUX"}
if verb_or_aux and not regexp_perif.search(token.tag_):
if regexp.search(token.tag_):
n_clauses += 1
return n_clauses
|
98edc098f625cc8f8efb8f892df14f14c03c32a2
| 37,433 |
def humanize_key(key):
"""Returns a human-readable key as a series of hex characters."""
return ':'.join(["%02x" % ord(c) for c in key.get_fingerprint()])
|
caa98d4fe392627cc153dcc0dd9f29ca42548efe
| 37,434 |
def koma_sepp(n):
"""
Take input integer n and return comma-separated string, separating
1000s.
>>> koma_sepp(131032047)
'131,032,047'
>>> koma_sepp(18781)
'18,781'
>>> koma_sepp(666)
'666'
"""
return '{:,}'.format(n)
|
e72ebc81bf116720f17a005af7bff2b40569a822
| 37,440 |
def soundspeed(temperature=27, salinity=35, depth=10):
"""Get the speed of sound in water.
Uses Mackenzie (1981) to compute sound speed in water.
:param temperature: temperature in deg C
:param salinity: salinity in ppt
:param depth: depth in m
:returns: sound speed in m/s
>>> import arlpy
>>> arlpy.uwa.soundspeed()
1539.1
>>> arlpy.uwa.soundspeed(temperature=25, depth=20)
1534.6
"""
c = 1448.96 + 4.591*temperature - 5.304e-2*temperature**2 + 2.374e-4*temperature**3
c += 1.340*(salinity-35) + 1.630e-2*depth + 1.675e-7*depth**2
c += -1.025e-2*temperature*(salinity-35) - 7.139e-13*temperature*depth**3
return c
|
782bb031d879d8f7ffb9e412de716e78710abe4f
| 37,441 |
import requests
def read_data(url_page, parser):
"""
Call requests.get for a url and return the extracted data.
Parameters:
url_page -- url of the Billboard data
parser -- Instantiated parser (either ParseWeek() or ParseYear().
"""
req = requests.get(url_page)
parser.feed(req.text)
return parser.result
|
d9d8bedc0a18b64a197e007cf0fdc63d5a1e63cb
| 37,448 |
from typing import Tuple
import re
def parse_source_type_name(field_type_name: str) -> Tuple[str, str]:
"""
Split full source type name into package and type name.
E.g. 'root.package.Message' -> ('root.package', 'Message')
'root.Message.SomeEnum' -> ('root', 'Message.SomeEnum')
"""
package_match = re.match(r"^\.?([^A-Z]+)\.(.+)", field_type_name)
if package_match:
package = package_match.group(1)
name = package_match.group(2)
else:
package = ""
name = field_type_name.lstrip(".")
return package, name
|
45a48a2ad53b3b98618d8a82a3bf2cb75cdab250
| 37,452 |
def solution(exponent: int = 30) -> int:
"""
For any given exponent x >= 0, 1 <= n <= 2^x.
This function returns how many Nim games are lost given that
each Nim game has three heaps of the form (n, 2*n, 3*n).
>>> solution(0)
1
>>> solution(2)
3
>>> solution(10)
144
"""
# To find how many total games were lost for a given exponent x,
# we need to find the Fibonacci number F(x+2).
fibonacci_index = exponent + 2
phi = (1 + 5 ** 0.5) / 2
fibonacci = (phi ** fibonacci_index - (phi - 1) ** fibonacci_index) / 5 ** 0.5
return int(fibonacci)
|
e61be3f0ed92954c6b7a0d25baffa9d6d40107a1
| 37,453 |
def split_curves(curves, param):
"""Split curves into lists sorted by the given parameter
Parameters
----------
curves : array_like of Curve
all curves
param : str
key of parameter to sort after
Returns
-------
split_curves : list of list of Curve
"""
out = {}
for curve in curves:
val = curve.params[param]
if val not in out.keys():
out.update({val: [curve]})
else:
out[val].append(curve)
return list(out.values())
|
3b5e3f4fca8720ef5c50a24732d39f5f41dc4690
| 37,456 |
from typing import Tuple
import math
def get_roll_and_shift(
input_offset: Tuple[float, ...],
target_offset: Tuple[float, ...]
) -> Tuple[Tuple[int, ...], Tuple[float, ...]]:
"""Decomposes delta as integer `roll` and positive fractional `shift`."""
delta = [t - i for t, i in zip(target_offset, input_offset)]
roll = tuple(-math.floor(d) for d in delta)
shift = tuple(d + r for d, r in zip(delta, roll))
return roll, shift
|
b2233aa0f8f22072239b46bc8eb0ef730ff53334
| 37,463 |
def normalise_toolshed_url(tool_shed):
"""
Return complete URL for a tool shed
Arguments:
tool_shed (str): partial or full URL for a
toolshed server
Returns:
str: full URL for toolshed, including
leading protocol.
"""
if tool_shed.startswith('http://') or \
tool_shed.startswith('https://'):
return tool_shed
return "https://%s" % tool_shed
|
4837f69122dc841549a4fc1923300be4eb04057c
| 37,464 |
from typing import OrderedDict
def parse_MTL(filename):
""" Return an ordered dict from a Landsat "MTL" metadata file
Args:
filename (str): MTL filename
Returns:
OrderedDict: dict of MTL file
"""
data = OrderedDict()
with open(filename, 'rt') as fid:
for line in fid:
split = line.split(' = ')
if len(split) == 2:
data[split[0].strip().strip('"')] = split[1].strip().strip('"')
return data
|
b06aa302475a0a4a5ee756db2d7f7aa02a44efd6
| 37,468 |
def _tensor_name(tensor):
"""Get a name of a tensor without trailing ":0" when relevant."""
# tensor.name is unicode in Python 3 and bytes in Python 2 so convert to
# bytes here.
name = str(tensor.name)
return name[:-2] if name.endswith(':0') else name
|
57b05fd2aaa7f65e49f9eb27538e9d1dfbe1d5c0
| 37,475 |
def listdict_to_listlist_and_matrix(sparse):
"""Transforms the adjacency list representation of a graph
of type listdict into the listlist + weight matrix representation
:param sparse: graph in listdict representation
:returns: couple with listlist representation, and weight matrix
:complexity: linear
"""
V = range(len(sparse))
graph = [[] for _ in V]
weight = [[None for v in V] for u in V]
for u in V:
for v in sparse[u]:
graph[u].append(v)
weight[u][v] = sparse[u][v]
return graph, weight
|
fb4b113317f78320add25940adc2d2f04797e118
| 37,477 |
def filter_tags(tags, prefixes=None):
"""Filter list of relation tags matching specified prefixes."""
if prefixes is not None:
# filter by specified relation tag prefixes
tags = tuple( t for t in tags if any(( t.startswith(p) for p in prefixes )) )
return tags
|
4378831c0f6ebf290c9a6d0e33e7be1f57acb26d
| 37,479 |
def get_dict_value_insensitive(d: dict, k: str):
""" Returns a value matching to a case insensitive key of a dict
Args:
d (dict): The dict
k (str): The key
Returns:
val: The matching value
"""
return {key.lower(): val for key, val in d.items()}.get(k.lower(), None)
|
3c730c58fad48faa1bc6421f110b2174ba7d088c
| 37,480 |
def is_cwl_record(d):
"""Check if an input is a CWL record, from any level of nesting.
"""
if isinstance(d, dict):
if d.get("type") == "record":
return d
else:
recs = list(filter(lambda x: x is not None, [is_cwl_record(v) for v in d.values()]))
return recs[0] if recs else None
else:
return None
|
dbfa01c8d24d78e6da4fac0a4f912e3b11c56023
| 37,483 |
def unit_interval(x, xmin, xmax, scale_factor=1.):
"""
Rescale tensor values to lie on the unit interval.
If values go beyond the stated xmin/xmax, they are rescaled
in the same way, but will be outside the unit interval.
Parameters
----------
x : Tensor
Input tensor, of any shape.
xmin, xmax : float
Minimum and maximum values, which will be rescaled to the
boundaries of the unit interval: [xmin, xmax] -> [0, 1].
scale_factor : float, optional
Scale the unit interval by some arbitrary factor, so that
the output tensor values lie in the interval [0, scale_factor].
Returns
-------
y : Tensor
Rescaled version of x.
"""
return scale_factor * (x - xmin) / (xmax - xmin)
|
4083e1904eefeec606e8a22e53485f7007257e71
| 37,489 |
def decoder_inputs_and_outputs(target_words, base_vocab):
"""Convert a sequence of tokens into a decoder input seq and output seq.
Args:
target_words (list[unicode])
base_vocab (Vocab)
Returns:
input_words (list[unicode])
output_words (list[unicode])
"""
# prepend with <start> token
input_words = [base_vocab.START] + target_words
# append with <stop> token
output_words = target_words + [base_vocab.STOP]
return input_words, output_words
|
ec66ec0fa7161d65ce6dea6688aa32e44f1b6377
| 37,492 |
def join_paths(*args) -> str:
"""Collect given paths and return summary joined absolute path.
Also calculate logic for `./` starting path, consider it as "from me"
relative point.
"""
summary_path = ""
for path in args:
# Check if path starts from slash, to remove it to avoid errors
if path[0] == "/":
path = path[1:]
# Check if path given in logical form (starts from "./")
elif path[:2] == "./":
# Remove leading "./" to perform proper paths joining
path = path[2:]
# Check if path ends with slash, to remove it to avoid errors
if path[len(path)-1] == "/":
path = path[:len(path)-1]
summary_path += "/" + path
return summary_path
|
12f79f94954202c643f6fb14ae58eb855d5e96c7
| 37,500 |
def group_by(df, group_by_col, value_col):
"""take a dataframe and group it by a single column and return the sum of another"""
return df.groupby([group_by_col])[value_col].sum()
|
e82943568b8d107c0045af45a4923a442bf07486
| 37,505 |
import re
def clearColors(message):
"""
Clears ANSI color codes
>>> clearColors("\x1b[38;5;82mHello \x1b[38;5;198mWorld")
'Hello World'
"""
retVal = message
if isinstance(message, str):
retVal = re.sub(r"\x1b\[[\d;]+m", "", message)
return retVal
|
4d5edbe7a2899803f14a2d1cdd043d65d3a25718
| 37,515 |
def rename_tree(tree, names=None):
"""Rename the leaves of a tree from ints to names"""
# rename leaves to integers
for node in list(tree):
if node.is_leaf():
tree.rename(node.name, int(node.name))
if names:
# rename leaves according to given names
for i, name in enumerate(names):
tree.rename(i, name)
return tree
|
9ce485c73a2f71653e1bec4e78a44aaff7e9a654
| 37,520 |
def logout(identity):
"""Logout the user.
:returns: a dict with the operation result
"""
if not identity:
return {'no-data': ''}
return {'success': 'Successfully logged out.'}
|
31bdee658dde3b636f2840c2c8a1b428c5049623
| 37,528 |
def add_desi_proc_joint_fit_terms(parser):
"""
Add parameters to the argument parser that are only used by desi_proc_joint_fit
"""
#parser.add_argument("-n", "--nights", type=str, help="YEARMMDD nights")
parser.add_argument("-e", "--expids", type=str, help="Exposure IDs")
parser.add_argument("-i", "--inputs", type=str, help="input raw data files")
return parser
|
80c23dcfe1e91df2b4d42ca066a697715b10d39d
| 37,531 |
def get_shape(card):
"""Returns the card's shape
Args:
card (webelement): a visible card
Returns:
str: card's shape
"""
return card.find_element_by_xpath(".//div/*[name()='svg']/*[name()='use'][1]").get_attribute("href")[1:]
|
fc7fc60766625a22ac9bf9942ccd5bf32d80d959
| 37,534 |
def get_iterable(input_var):
"""
Returns an iterable, in case input_var is None it just returns an empty tuple
:param input_var: can be a list, tuple or None
:return: input_var or () if it is None
"""
if input_var is None:
return ()
return input_var
|
ad98d537e711a4357c1527df86b00d977d017a30
| 37,536 |
def check_category(driver, domain):
"""Check domain category on Fortiguard."""
print("Checking Fortiguard proxy")
driver.get(f"https://www.fortiguard.com/webfilter?q={domain}&version=8")
category = driver.find_element_by_xpath("//h4[@class='info_title']")
return category.text.replace("Category: ", "")
|
4bd2f32b4df01971ba985daeb0134229e896f92a
| 37,537 |
import ast
def to_dict(value):
""" Create a dictionary from any kind of incoming object """
if value is None:
return {}
if isinstance(value, dict):
myreturn = value
else:
myreturn = ast.literal_eval(value)
return myreturn
|
a215554ca0bb86775b5cf97c793e163c78123fac
| 37,538 |
def get_path(path, npa):
""" creates path string from list """
return ''.join(path[:npa+1])
|
46e0c1351facde66ab8de23628c7196544921fb9
| 37,539 |
import pytz
from datetime import datetime
def eventIsNow(event):
"""Checks if an event object is happening right now.
Args:
event: Object with 'start' and 'end' datetimes or dates.
Returns:
Whether the event is now.
"""
if 'start' not in event or 'end' not in event:
return False
# Since Google returns all datetimes with the timezone of the calendar,
# and we're assuming this server is running in the same timezone,
# equalize all the timezones for time comparison.
start = event['start'].replace(tzinfo=pytz.utc)
end = event['end'].replace(tzinfo=pytz.utc)
return start <= datetime.now().replace(tzinfo=pytz.utc) <= end
|
f07735d3254e66c618776391914209cca902e532
| 37,541 |
from typing import List
from typing import Tuple
def bounded_rectangle(
rect: List[Tuple[float, float]], bounds: List[Tuple[float, float]]
) -> List[Tuple[float, float]]:
"""
Resize rectangle given by points into a rectangle that fits within bounds, preserving the aspect ratio
:param rect: Input rectangle [ll, ur], where each point is (y, x)
:param bounds: Input bounding rectangle [ll, ur]
:return: Bounded rectangle with same aspect ratio
"""
assert len(rect) == len(bounds) == 2
assert rect[0][0] <= rect[1][0] and rect[0][1] <= rect[1][1]
assert bounds[0][0] <= bounds[1][0] and bounds[0][1] <= bounds[1][1]
w_input = rect[1][1] - rect[0][1]
h_input = rect[1][0] - rect[0][0]
w_bound = bounds[1][1] - bounds[0][1]
h_bound = bounds[1][0] - bounds[0][0]
w = w_input
h = h_input
# find new rect points
while w > w_bound or h > h_bound:
if w > w_bound:
# need to bound w
a_w = w_bound / w
w = w_bound
h = h * a_w
if h > h_bound:
# need to bound w
a_h = h_bound / h
h = h_bound
w = w * a_h
rect_out = [rect[0], (rect[0][0] + h, rect[0][1] + w)]
return rect_out
|
30da7769b7ea6d8cf69d1c791614d7db1999d335
| 37,545 |
import time
def getTimeStr(seconds):
"""Get HH:MM:SS time string for seconds.
"""
if seconds < 86400:
return time.strftime('%H:%M:%S', time.gmtime(seconds))
else:
return time.strftime('{}d%H:%M:%S'.format(int(seconds) // 86400), time.gmtime(int(seconds)))
|
174fab592b2edeae81a8bdd6688810eee8c5a53b
| 37,548 |
def celsius_to_fahrenheit(temp):
"""Simple temperature conversion Cº to Fº"""
return temp * 1.8 + 32
|
d5574ffc5bb4e10e7e51af836c6a60dee76f488f
| 37,552 |
def json_to_uri(credentials_json):
"""
Convert JSON object containing database credentials into a string
formatted for SQLAlchemy's create_engine, e.g.:
drivername://user:password@host:port/dbname
It is assumed that the json has already been validated against
json_ops.CREDENTIALS_SCHEMA
:param json credentials_json: JSON object containing database credentials
:return str credentials_str: URI for connecting to the database
"""
return \
credentials_json["drivername"] + "://" + \
credentials_json["username"] + ":" + \
credentials_json["password"] + "@" + \
credentials_json["host"] + ":" + \
str(credentials_json["port"]) + "/" + \
credentials_json["dbname"]
|
821994b3d4d7bc8cda4bfb4324a4c23023586c70
| 37,553 |
def percentage(x, y):
"""
Convert x/y into a percentage. Useful for calculating success rate
Args:
x (int)
y (int)
Returns:
str: percentage formatted into a string
"""
return '%.2f%%' % (100 * x / y)
|
361b427b413ef989dc2aec8d804a30641d0c49e8
| 37,555 |
def global_accuracy(task_accuracies, test_samples_per_task):
"""
Calculate global accuracy of the model based on accuracies from single tasks accounting number of test samples per task.
:param task_accuracies: list of accuracies for each task
:param test_samples_per_task: list of test samples for each task
:return: total/global accuracy in %
"""
accurate_samples = sum([round((task_acc / 100) * task_samples) for task_acc, task_samples in zip(task_accuracies, test_samples_per_task)])
return (accurate_samples / sum(test_samples_per_task)) * 100
|
eab9c9000d16504ace30dc276faa1d24eeb427aa
| 37,556 |
def speed2dt(speed):
"""Calculate the time between consecutive fall steps using the *speed* parameter; *speed* should be an int between 1 and 9 (inclusively). Returns time between consecutive fall steps in msec."""
return (10-speed)*400
|
676fd396ca83cedc1a6e15addc06abdfd98bced9
| 37,564 |
def _flip_top_bottom_boundingbox(img, boxes):
"""Flip top bottom only bounding box.
Args:
img: np array image.
boxes(np.ndarray): bounding boxes. shape is [num_boxes, 5(x, y, w, h, class_id)]
"""
height = img.shape[0]
if len(boxes) > 0:
boxes[:, 1] = height - boxes[:, 1] - boxes[:, 3]
return boxes
|
ad196f59f85d5a6027e0a17ce6d543303c102357
| 37,565 |
def get_subclasses(c):
"""
Get all subclasses of a given class
"""
return c.__subclasses__() + sum(map(get_subclasses, c.__subclasses__()), [])
|
c38c6d9df23039c816d508663c5f40a84b9de299
| 37,566 |
def get_wind_power(agent):
""" Check if the wind generator is active. If it is, get the power out of it, otherwise return 0"""
wind_power = 0
if agent.wind_generator.is_active():
wind_power = agent.wind_generator.erogate()
return wind_power
|
971e70694b53fc7d2189a2eaf102f84ddf04e769
| 37,569 |
import mpmath
def cdf(x):
"""
Cumulative distribution function (CDF) of the raised cosine distribution.
The CDF of the raised cosine distribution is
F(x) = (pi + x + sin(x))/(2*pi)
"""
with mpmath.extradps(5):
x = mpmath.mpf(x)
if x <= -mpmath.pi:
return mpmath.mp.zero
if x >= mpmath.pi:
return mpmath.mp.one
return mpmath.mpf('1/2') + (x + mpmath.sin(x))/(2*mpmath.pi)
|
a1554e207af751fb3fcf85db80ec2c3c760dd551
| 37,572 |
def total_penup_travel(gs):
"""
Compute total distance traveled in a given ordering
"""
def distance_between_each_pair(gs):
gs = iter(gs)
prev = next(gs)
for g in gs:
yield prev.distance_to(g)
prev = g
return sum(distance_between_each_pair(gs))
|
af7d20a5954dc31e873d9a4148c37d31dc69ed61
| 37,583 |
import re
def getProteinSequences(path_to_data: str) -> dict:
"""
Read protein sequence data file and extract protein sequences
"""
with open(path_to_data) as file:
data = file.read()
# Isolate protein sequences (using key: CRC64 with 12 empty spaces before start)
pstart = [m.start() for m in re.finditer('CRC64', data)]
pend = [m.start() for m in re.finditer("\n//", data)]
proteins = {}
for idx in range(len(pstart)):
proteins[idx] = re.sub(' ', '', re.sub('\n', '', data[pstart[idx]+12:pend[idx]]))
return proteins
|
3b9ebe071b16aa3af8cb85560fe71b68c609072a
| 37,585 |
def apply_function_on_array(f, input_data):
"""Apply a function on input data.
This method will apply a function on the input data. If the input data
is 1-d, it will expand the data to 2-d before feeding into the function,
and then squeeze the output data back to 1-d if possible.
Parameters
----------
f : (np.ndarray) -> np.ndarray
The function that will be applied to input data.
input_data : np.ndarray
The input data.
Returns
-------
np.ndarray
"""
# expand the input data to 2-d if it is 1-d
if len(input_data.shape) == 1:
input_data = input_data.reshape([-1, 1])
ret = f(input_data)
# revert back to 1-d if necessary.
if len(ret.shape) == 2 and ret.shape[1] == 1:
ret = ret.reshape([-1])
else:
ret = f(input_data)
return ret
|
b22f955fdd80692719e9ae7422f73a6d09668a38
| 37,587 |
def next_biggest(target, in_list):
"""
Returns the next highest number in the in_list.
If target is greater the the last number in in_list, will return the last
item in the list.
"""
next_highest = None
for item in in_list:
if item > target:
next_highest = item
break
if next_highest is None:
next_highest = in_list[-1]
return next_highest
|
4e5b8602e10fc8e9373c23a931e20bf454b6e21f
| 37,598 |
def order_by_dependence(parameters):
"""
Takes a list of parameters from a dynamoDB table and organize them by dependence.
The output is a list of lists; for each sub-list there is a root parameter
(that do not depend on anything) and the parameters that do depend
"""
# Selects all table items that does not depend on others:
roots = [leaf for leaf in parameters if 'dependence' not in leaf.keys() or leaf['dependence']==None]
# Selects all table items that does depend on others:
leafs = [leaf for leaf in parameters if 'dependence' in leaf.keys() and leaf['dependence']!=None]
graphs = []
for root in roots:
# A graph starts with a root:
graph = [root]
branches = [root['name']]
for leaf in leafs:
# If a leaf depends on any parameter present in that graph, add it to that graph:
if leaf['dependence']['name'] in branches:
graph.append(leaf)
branches.append(leaf['name'])
# Put this graph (that starts with a certain root) in the list of graphs:
graphs.append(graph)
return graphs
|
2e3f888e80c354bb414955c133da12eb23ed13b0
| 37,600 |
def log_request_entries(log_file='fastemplate.log'):
"""
Retrieves the amount of log entries.
:param str log_file: name of the log file
:return: int
"""
lines = open(file=log_file, mode='r').readlines()
return len(lines)
|
b5f0710b9f4f6314c3e7cd1a73d5734c2b763193
| 37,606 |
def find_operation(api, key_op):
"""
Find an operation in api that matches key_op. This method first attempts to find a match
by using the operation name (nickname). Failing that, it attempts to match up HTTP methods.
Args:
api - A Swagger API description (dictionary)
key_op - A Swagger operation description (dictionary)
Returns:
An operation that matches key_op, or None if nothing found
"""
operations = api['operations']
for op in operations:
if op['nickname'] == key_op['nickname']:
return op
for op in operations:
if op['method'] == key_op['method']:
return op
return None
|
8d565f97acff1023a7ea68dbcec4335754864d2f
| 37,608 |
import math
def volumen_cilindro(radio: float, altura: float) -> float:
""" Volumen de un cilindro
Parámetros:
radio (float): Radio de la base del cilindro
altura (float): Altura del cilindro
Retorno:
float: El volumen del cilindro readondeado a un decimal
"""
area_base = math.pi * (radio ** 2)
volumen = area_base * altura
return round(volumen, 1)
|
f97c187c65ce0e8ac6e3b74d8afa6657bc79bd93
| 37,610 |
def signed_number(number, precision=2):
"""
Return the given number as a string with a sign in front of it, ie. `+` if the number is positive, `-` otherwise.
"""
prefix = '' if number <= 0 else '+'
number_str = '{}{:.{precision}f}'.format(prefix, number, precision=precision)
return number_str
|
26406b5aab7537a37aa073d21d552f04eb3950e9
| 37,614 |
def _filter_vocab(vocab, min_fs):
"""Filter down the vocab based on rules in the vectorizers.
:param vocab: `dict[Counter]`: A dict of vocabs.
:param min_fs: `dict[int]: A dict of cutoffs.
Note:
Any key in the min_fs dict should appear in the vocab dict.
:returns: `dict[dict]`: A dict of new filtered vocabs.
"""
for k, min_f in min_fs.items():
# If we don't filter then skip to save an iteration through the vocab
if min_f == -1:
continue
vocab[k] = dict(filter(lambda x: x[1] >= min_f, vocab[k].items()))
return vocab
|
0854c8a6bbf0c9c3805cc4b733589d36209bff58
| 37,615 |
def prompt(choices, label='choice'):
"""
Prompt the user to choose an item from the list. Options should be a list
of 2-tuples, where the first item is the value to be returned when the
option is selected, and the second is the label that will be displayed to the
user.
"""
if len(choices) == 0:
raise ValueError('The list of choices is empty')
lines = ['%d) %s' % (i + 1, item[1]) for i, item in enumerate(choices)]
index = input('\n'.join(lines + ['', 'Please select a %s: ' % label]))
while len(index) < 1 or int(index) < 1 or int(index) > len(choices):
index = input('Please enter a valid choice: ')
return choices[int(index) - 1][0]
|
9c9c000f03c4e9752780787bd14aac53609f83c7
| 37,618 |
def attack(decrypt_oracle, iv, c, t):
"""
Uses a chosen-ciphertext attack to decrypt the ciphertext.
:param decrypt_oracle: the decryption oracle
:param iv: the initialization vector
:param c: the ciphertext
:param t: the tag corresponding to the ciphertext
:return: the plaintext
"""
c_ = iv + c
p_ = decrypt_oracle(bytes(16), c_, c[-16:])
return p_[16:]
|
80106b2376a8fa2d30afe96e5a763d6153ed3936
| 37,624 |
import threading
def start_timer(timeout, callback):
"""Start a timer using the threading library (in seconds)."""
tmr = threading.Timer(timeout, callback)
tmr.start()
return tmr
|
eef2c4ddf512e6111c18fcdbfa65de31c75b4a20
| 37,625 |
def _file_col(col):
"""
Converts a given column in a maze to the corresponding actual line
number in the maze.
Args:
col (int): The column of the block the maze object.
Returns:
int: The column number in the file corresponding to the given
column in the maze.
"""
return 2 * col + 1
|
85c3ab8c9f2a0608cae61af22b162ddba3d03b5a
| 37,632 |
from typing import List
def render_include_source_code(
col_offset: int, include_path: str, include_code: str
) -> List[str]:
"""Annotate included source code with additional information about
the source path of the included source.
Args:
col_offset: a col offset of the whole source code which is included
include_path: a path to the module which is included
include_code: a content of the module at path `include_path`
Returns:
formatted source code
"""
print(f"PyParams: including module source: {include_path}")
s_col_offset = " " * col_offset
comment_line = f"{s_col_offset}PyParams: auto include source of `{include_path}`"
header_lines = [
f'{s_col_offset}"""\n{s_col_offset}' + "-" * (80 - col_offset),
f"{s_col_offset}{comment_line}",
s_col_offset + "-" * (80 - col_offset) + f'\n{s_col_offset}"""',
]
include_lines = header_lines + [s_col_offset + l for l in include_code.split("\n")]
comment_line = f"{s_col_offset}INCLUDE END OF `{include_path}`"
include_lines += [
f'{s_col_offset}"""\n{s_col_offset}' + "-" * (80 - col_offset),
f"{s_col_offset}{comment_line}",
s_col_offset + "-" * (80 - col_offset) + f'\n{s_col_offset}"""',
]
return include_lines
|
ae578e8369b68ae26008ca4185640c98dceb2b08
| 37,638 |
def _extend_pads(pads, rank):
"""Extends a padding list to match the necessary rank.
Args:
pads ([int] or None): The explicitly-provided padding list.
rank (int): The rank of the operation.
Returns:
None: If pads is None
[int]: The extended padding list.
"""
if pads is None:
return pads
pads = list(pads)
if len(pads) < rank:
pads.extend([0] * (rank - len(pads)))
if len(pads) < (2 * rank):
pads.extend(pads[len(pads) - rank:rank])
return pads
|
ce1342f3973b852259ea97d710c733ba2d90cace
| 37,639 |
def get_row_index(preDict, usrDict):
"""
Get the row positions for all words in user dictionary from pre-trained dictionary.
return: a list of row positions
Example: preDict='a\nb\nc\n', usrDict='a\nc\n', then return [0,2]
"""
pos = []
index = dict()
with open(preDict, "r") as f:
for line_index, line in enumerate(f):
word = line.strip().split()[0]
index[word] = line_index
with open(usrDict, "r") as f:
for line in f:
word = line.strip().split()[0]
pos.append(index[word])
return pos
|
1058f5fcad5ab88066312dabf931e1ac5519b193
| 37,640 |
import re
def strip_namespace(path):
"""Removes namespace prefixes from elements of the supplied path.
Args:
path: A YANG path string
Returns:
A YANG path string with the namespaces removed.
"""
re_ns = re.compile(r"^.+:")
path_components = [re_ns.sub("", comp) for comp in path.split("/")]
pathstr = "/".join(path_components)
return pathstr
|
5613411de8d796d3b671bbb94f055168eba2f5c7
| 37,642 |
def like_prefix(value, start='%'):
"""
gets a copy of string with `%` or couple of `_` values attached to beginning.
it is to be used in like operator.
:param str value: value to be processed.
:param str start: start place holder to be prefixed.
it could be `%` or couple of `_` values
for exact matching.
defaults to `%` if not provided.
:rtype: str
"""
if value is None:
return None
return '{start}{value}'.format(start=start, value=value)
|
8ef7e3fa2fc50723f483cc443e4bcbc098c16d32
| 37,643 |
def safe_unichr(intval):
"""Create a unicode character from its integer value. In case `unichr` fails, render the character
as an escaped `\\U<8-byte hex value of intval>` string.
Parameters
----------
intval : int
Integer code of character
Returns
-------
string
Unicode string of character
"""
try:
return chr(intval)
except ValueError:
# ValueError: chr() arg not in range(0x10000) (narrow Python build)
s = "\\U%08x" % intval
# return UTF16 surrogate pair
return s.decode('unicode-escape')
|
15c42a3ca0c528a1b27a6e1cb87bd2d788fafabf
| 37,652 |
def create_variant_to_alt_read_names_dict(isovar_results):
"""
Create dictionary from variant to names of alt reads supporting
that variant in an IsovarResult.
Parameters
----------
isovar_results : list of IsovarResult
Returns
-------
Dictionary from varcode.Variant to set(str) of read names
"""
return {
isovar_result.variant: set(isovar_result.alt_read_names)
for isovar_result in isovar_results
}
|
aeff30e04dd479e020c1fdcea867f0f6c0a17d97
| 37,659 |
def _get_is_negative(offset_string: str) -> bool:
"""Check if a string has a negative sign."""
is_negative = False
if offset_string.count('-') > 0 or offset_string.count('–'):
if offset_string.count('-') == 1 or offset_string.count('–') == 1:
is_negative = True
if offset_string.count('S') > 0:
if offset_string.count('S') == 1 and offset_string[-1] == "S" and is_negative is False:
is_negative = True
offset_string_negative_check = (
offset_string.replace(' ', '')
.replace('"', '')
.replace('„', '')
.replace('+', '')
.replace('-', '')
.replace('–', '')
.replace('€', '')
)
if len(offset_string_negative_check) > 2:
if offset_string_negative_check[0] == '(' and offset_string_negative_check[-1] == ')':
is_negative = True
return is_negative
|
589ae036a290f97450a8f32f3ad72acfd8ee267d
| 37,661 |
from datetime import datetime
def generate_birthdays(birthdays: list, year_to_generate: int):
"""
generate birthdays from lists
:param birthdays:
:param year_to_generate: how many year from this year to add to the event
:return:
"""
this_year = datetime.now().year
event_list = []
for birthday in birthdays:
for year in range(this_year, this_year + year_to_generate):
date = birthday.in_year(year)
event_list.append([birthday, date])
return event_list
|
158c68da9f171904f76d2104dd6a6035a6bf7d39
| 37,669 |
def popup_element(value, title=None, format=None):
"""Helper function for quickly adding a popup element to a layer.
Args:
value (str): Column name to display the value for each feature.
title (str, optional): Title for the given value. By default, it's the name of the value.
format (str, optional): Format to apply to number values in the widget, based on d3-format
specifier (https://github.com/d3/d3-format#locale_format).
Example:
>>> popup_element('column_name', title='Popup title', format='.2~s')
"""
return {
'value': value,
'title': title,
'format': format
}
|
a30c88cd4dec6470643548807cfde9e608a6e8dd
| 37,672 |
import requests
def get_object(
token: str,
url: str = "https://dev-api.aioneers.tech/v1/",
object: str = "dotTypes",
) -> list:
"""Get JSON object.
Parameters
----------
token : str
Token which was returned from the user login.
url : str = "https://dev-api.aioneers.tech/v1/"
Url of the API.
object : str = "dotTypes"
Object to be extracted from the API.
Returns
-------
list
List of JSON objects.
Raises
------
ValueError
Raises ValueError when the input is not correct.
"""
url = url.strip("/")
object = object.lower()
if object == "metrictypes":
url += "/metricTypes"
elif object == "metrics":
url += "/metrics"
elif object == "dottypes" or object == "trackingobjecttypes":
url += "/trackingObjectTypes"
elif object == "dots" or object == "trackingobjects":
url += "/trackingObjects"
elif object == "actions":
url += "/actions"
elif object == "actiontemplates":
url += "/actionTemplates"
elif object == "measuretemplates":
url += "/measureTemplates"
elif object == "measures":
url += "/measures"
elif object == "initiativetemplates":
url += "/initiativeTemplates"
elif object == "initiatives":
url += "/initiatives"
else:
raise ValueError
response = requests.request(
"GET", url, headers={"Authorization": f"Bearer {token}"}
)
response.raise_for_status()
return response.json()["data"]["payload"]
|
c0ad1ba7caf13aafde888fdaad8a1670f6964c78
| 37,677 |
def get_endpoint(svc):
"""
Given a service object, return a formatted
URL of the service.
"""
return f"{svc.get('protocol')}://{svc.get('host')}:{svc.get('port','80')}{svc.get('path','/')}"
|
ade630e7dd4446c89382022f06998a5d8918f699
| 37,680 |
import torch
def create_length_mask(data, lengths):
"""
Create lengths mask for data along one dimension.
"""
n_sequences, max_length, _ = data.shape
lengths_mask = torch.zeros(n_sequences, max_length)
for i, length in enumerate(lengths):
lengths_mask[i, :length + 1] = 1
return lengths_mask
|
2d0c4e8730f2ddf070fc94f024526fd6a01cda44
| 37,685 |
def get_size(img):
"""Return the size of the image in pixels."""
ih, iw = img.shape[:2]
return iw * ih
|
392cb997016982d9e9bfaae9b7d202e01e66e8b0
| 37,689 |
def total_accessibility(in_rsa, path=True):
"""Parses rsa file for the total surface accessibility data.
Parameters
----------
in_rsa : str
Path to naccess rsa file.
path : bool
Indicates if in_rsa is a path or a string.
Returns
-------
dssp_residues : 5-tuple(float)
Total accessibility values for:
[0] all atoms
[1] all side-chain atoms
[2] all main-chain atoms
[3] all non-polar atoms
[4] all polar atoms
"""
if path:
with open(in_rsa, 'r') as inf:
rsa = inf.read()
else:
rsa = in_rsa[:]
all_atoms, side_chains, main_chain, non_polar, polar = [
float(x) for x in rsa.splitlines()[-1].split()[1:]]
return all_atoms, side_chains, main_chain, non_polar, polar
|
34c4cba6b8ac5092a1cf5194a6f7d7a3e037477e
| 37,698 |
def get_sleepiest_guard(sleep_record):
"""Finds guard in sleep_record who spent the most total minutes asleep.
returns: ('guard', total_minutes_slept)
"""
sleepiest = '', 0
for guard in sleep_record:
sleep_mins = 0
for minute in sleep_record[guard]:
sleep_mins += sleep_record[guard][minute]
if sleep_mins > sleepiest[1]:
sleepiest = guard, sleep_mins
print(sleepiest)
return sleepiest
|
060f2d73471e4328100bca1759cf0e4dd6446dd1
| 37,700 |
def int_to_binary(d, length=8):
"""
Binarize an integer d to a list of 0 and 1. Length of list is fixed by `length`
"""
d_bin = '{0:b}'.format(d)
d_bin = (length - len(d_bin)) * '0' + d_bin # Fill in with 0
return [int(i) for i in d_bin]
|
297c6633e984143af564d885c523c6f8d719a4e2
| 37,701 |
import jinja2
def render(data, template):
"""render jija2 template
Args:
data(obj): dict with data to pass to jinja2 template
template(str): jinja2 template to use
Returns: string, rendered all, or pukes with error :)
"""
with open(template, 'r'):
templateLoader = jinja2.FileSystemLoader(searchpath="./")
templateEnv = jinja2.Environment(loader=templateLoader)
template = templateEnv.get_template(template)
outputText = template.render(data=data)
return outputText
|
caf24bccd0351f72f5750bcb7c43e676994fecea
| 37,702 |
def get_options_from_json(conf_json, ack, csr, acmd, crtf, chnf, ca):
"""Parse key-value options from config json and return the values sequentially.
It takes prioritised values as params. Among these values, non-None values are
preserved and their values in config json are ignored."""
opt = {'AccountKey':ack, 'CSR':csr, 'AcmeDir':acmd, 'CertFile':crtf, 'ChainFile':chnf, 'CA':ca}
for key in opt:
if not opt[key] and key in conf_json and conf_json[key]:
opt[key] = conf_json[key]
continue
opt[key] = None if opt[key] == '' or opt[key] == '.' or opt[key] == '..' else opt[key]
return opt['AccountKey'], opt['CSR'], opt['AcmeDir'], opt['CertFile'], opt['ChainFile'],\
opt['CA']
|
1833e230750050b13f36156e83c3bf8a973cff62
| 37,705 |
def current_url_name(context):
"""
Returns the name of the current URL, namespaced, or False.
Example usage:
{% current_url_name as url_name %}
<a href="#"{% if url_name == 'myapp:home' %} class="active"{% endif %}">Home</a>
"""
url_name = False
if context.request.resolver_match:
url_name = "{}:{}".format(
context.request.resolver_match.namespace,
context.request.resolver_match.url_name,
)
return url_name
|
1ea2b6ef60a532131dc1c519fc3c5208b29c468b
| 37,707 |
import hashlib
def HashFile(filename):
"""Returns SHA-256 hash of a given file."""
if isinstance(filename, list):
filename = filename[0]
try:
return hashlib.sha256(
open(filename, "rb").read()).hexdigest()
except IOError:
return "UNKNOWN FILE HASH"
|
6529334d79246ad113bed7bfcb3b84cc59679f90
| 37,708 |
def identity(test_item):
"""Identity decorator
"""
return test_item
|
799d2325e04066c0dfa405d24d5718b67eb64a00
| 37,709 |
def _tensor_max(*args):
"""Elementwise maximum of a sequence of tensors"""
maximum, *rest = args
for arg in rest:
maximum = maximum.max(arg)
return maximum
|
3046b6ae14368a7275f74ade42a1b179ae38b95e
| 37,710 |
def doing_pcomp(row_trigger_value: str) -> bool:
"""Indicate whether the row_trigger is for position compare."""
return row_trigger_value == "Position Compare"
|
b6433fc126bb56eefc4c9c73f21e4fb1a82f65d0
| 37,711 |
def gen_bwt_array(s: str, suf_tab: list[int]) -> list[str]:
"""
computes bwt array using suf_tab
:param s: text for which bwt array is being computed
:param suf_tab: suffix array for the input text
:return: a bwt array for text
"""
s += '$'
bwt_array: list[str] = []
for suf in suf_tab:
bwt_array.append(s[suf - 1])
return bwt_array
|
a946519f8068e4aba04177afb2db032efc45e82e
| 37,712 |
def gwei_to_ether(wei):
"""Convert gwei to ether
"""
return 1.0 * wei / 10**9
|
95567f47f6e12d4aa3bbfdf7b0d6f1feaa96a9bd
| 37,717 |
def postprocess(simdata):
"""
Make an arbitrary edit to the simulation data, so we can check the postprocessing call works.
"""
mycol = simdata.cols['B']
simdata.data[4,mycol] = 123456.
return simdata
|
0f3c8303d90b4f52a1d504bc4ba267a6854021e4
| 37,722 |
import yaml
def load_yaml_file(file_path):
"""
Loads a yaml file and returns a dictionary with the contents.
Args:
file_path (str):
Path to the yaml file
Returns:
yaml_dict:
Dictionary with the contents of the yaml file
"""
with open(file_path, "r") as stream:
yaml_dict = yaml.safe_load(stream)
return yaml_dict
|
c0e2067d248dff3695380aa92c97ab621fae0d96
| 37,724 |
import logging
def get_handler_filename(logger):
"""Gets logger filename
Parameters:
* logger (object): log file object
Returns:
* str: Log file name if any, None if not
"""
for handler in logger.handlers:
if isinstance( handler, logging.FileHandler ):
return handler.baseFilename
return None
|
bdaa47977c14601aa2217fc8a3c734e97b9a0295
| 37,729 |
def ros_subscribe_cmd(topic, _id=None, _type=None):
"""
create a rosbridge subscribe command object
messages on subscribed topics will be sent like this:
outgoing_msg = {"op": "publish", "topic": topic, "msg": message}
see rosbridge_library capabilities/subscribe.py
:param topic: the string name of the topic to subscribe to
:param _id: optional id to identify subscription for later unsubscribe calls
:param _type: ROS msg type as string
not passed on:
(optional) "throttle_rate": <int>,
(optional) "queue_length": <int>,
(optional) "fragment_size": <int>,
(optional) "compression": <string>
"""
command = {
"op": "subscribe",
"topic": topic
}
if _id:
command["id"] = _id
if _type:
command["type"] = _type
return command
|
b001bf487894a1fa238997b21d7264eb802312ed
| 37,732 |
def set_mode(mode_input):
"""
Setter of mode of mapping based on mode input
Parameters:
(bool) mode_input: The mode input
Returns:
(bool) mode: The result mode
"""
mode = None
if mode_input is not None and isinstance(mode_input, bool) and mode_input == True:
mode = mode_input
else:
mode = None
return mode
|
79752605ce416c34a4a0efd6a5abde7e97096e8d
| 37,734 |
def selected(data, select):
"""
Takes data and removes any values/columns not in SELECT parameter
:param data: List of data entries to be SELECT'ed. ex:
[
{ 'stb': 'stb1',
'title': 'the matrix',
'rev': '6.00',
'date': '2017-05-01',
'provider': 'Warner Brothers',
'time': '12:30' },
{ ... }
]
:param select: List of SELECT parameters. ex: ['stb', 'rev', 'title']
:return: List of data with only keys matching SELECT parameters
"""
result = []
for entry in data:
result += [{key: entry[key] for key in select}]
return result
|
da7dec6686ee57ec5e89f78e552eb5476f27c66c
| 37,743 |
def _masked_array_repr(values, mask):
"""Returns a string representation for a masked numpy array."""
assert len(values) == len(mask)
if len(values.shape) == 1:
items = [repr(v) if m else '_' for (v, m) in zip(values, mask)]
else:
items = [_masked_array_repr(v, m) for (v, m) in zip(values, mask)]
return '[%s]' % ', '.join(items)
|
9324e3343ceefeda6c9676b0303988faa5a35474
| 37,748 |
def concat(list_a: list, list_b: list) -> list:
"""
Concatenates two lists together into a new list
Example:
>>> concat([1, 2, 3], [4, 5, 6])
... [1, 2, 3, 4, 5 6]
:param list_a: First list to concatenate
:param list_b: Second list to concatenate
:return: Concatenated list
"""
result = list_a + list_b
return result
|
c4fd1bf4c579ed48c599699d2f76277d85b47264
| 37,750 |
def get_reading_level_from_flesch(flesch_score):
"""
Thresholds taken from https://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests
:param flesch_score:
:return: A reading level and difficulty for a given flesch score
"""
if flesch_score < 30:
return "Very difficult to read"
elif flesch_score < 50:
return "Difficult to read"
elif flesch_score < 60:
return "Fairly difficult to read"
elif flesch_score < 70:
return "Plain English"
elif flesch_score < 80:
return "Fairly easy to read"
elif flesch_score < 90:
return "Easy to read"
else:
return "Very easy to read"
|
54903df2bc4114de663fb85af8500fe1cb26ddc5
| 37,752 |
import json
import requests
import hashlib
def get_wikidata_image(wikidata_id):
"""Return the image for the Wikidata item with *wikidata_id*. """
query_string = ("https://www.wikidata.org/wiki/Special:EntityData/%s.json"
% wikidata_id)
item = json.loads(requests.get(query_string).text)
wdata = item["entities"][wikidata_id]["claims"]
try:
image = wdata["P18"][0]["mainsnak"]["datavalue"]["value"].replace(" ", "_")
except KeyError:
print("No image on Wikidata.")
else:
md = hashlib.md5(image.encode('utf-8')).hexdigest()
image_url = ("https://upload.wikimedia.org/wikipedia/commons/thumb/%s/%s/%s/64px-%s"
% (md[0], md[:2], image, image))
return image_url
|
c946cd9b2b73cb6140cddf7197f7095ded71bd8f
| 37,754 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.