content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
import re
def remove_indentation(content: str) -> str:
"""
Removes indentation from a given string that contains multiple lines.
It removes spaces before new lines by the first line spaces at the beginning.
Args:
content(str): The sting that we want to clean from the indentation.
Returns:
str: The unindented content.
"""
indentation = next(iter(re.findall("^\n*( *)", content)), "")
unindented = re.subn(f"(\n){indentation}", r"\1", content)[0].strip()
return unindented
|
76419258643c80597f442b6f48dae8167e4a1cad
| 84,606 |
def adjacentDiag(x1, y1, x2, y2):
"""Adjacency including diagonals."""
if 1 >= x1 - x2 >= -1 and 1 >= y1 - y2 >= -1:
return True
return False
|
35a5120da9a423fad321b5576bdedde0ddd314af
| 610,807 |
import json
def ExtractJQuery(jquery_raw):
"""Extract and return the data inside a JQuery as a dict object."""
data_part = u''
if not jquery_raw:
return {}
if '[' in jquery_raw:
_, _, first_part = jquery_raw.partition('[')
data_part, _, _ = first_part.partition(']')
elif jquery_raw.startswith('//'):
_, _, first_part = jquery_raw.partition('{')
data_part = u'{{{0:s}'.format(first_part)
elif '({' in jquery_raw:
_, _, first_part = jquery_raw.partition('(')
data_part, _, _ = first_part.rpartition(')')
if not data_part:
return {}
try:
data_dict = json.loads(data_part)
except ValueError:
return {}
return data_dict
|
09cc1061537f85824b77ff072b24dfa8672d19d3
| 597,900 |
def percent_nan(data_series):
"""
For data_series, calculate what proportion of rows are NaN.
@param data_series: data to check for NaNs
@type data_series: Series
@return: A number representing the proportion of data in data_series that is NaN
@rtype: Float
"""
nan_count = data_series.isna().sum()
row_count = len(data_series)
if row_count == 0:
percent = 0
else:
percent = nan_count/row_count
return percent
|
f03998b0a7d98112566bc339ed118891d8d05a7e
| 612,333 |
def query_adapter(interface, request, context=None, view=None, name=''):
"""Registry adapter lookup helper
If view is provided, this function is trying to find a multi-adapter to given interface
for request, context and view; if not found, the lookup is done for request and context,
and finally only for context.
:param interface: adapter provided interface
:param request: current request
:param context: current context; if context is None, request context is used
:param view: current view
:param name: adapter name
"""
registry = request.registry
if context is None:
context = request.context
adapter = registry.queryMultiAdapter((context, request, view), interface, name=name) \
if view is not None else None
if adapter is None:
adapter = registry.queryMultiAdapter((context, request), interface, name=name)
if adapter is None:
adapter = registry.queryAdapter(context, interface, name=name)
return adapter
|
81c164ab122717cb31d001f3cf632da49183da87
| 688,891 |
def split_by_pred(pred, iterable, constructor=list):
"""Sort elements of `iterable` into two lists based on predicate `pred`.
Returns a tuple (l1, l2), where
* l1: list of elements in `iterable` for which pred(elem) == True
* l2: list of elements in `iterable` for which pred(elem) == False
"""
pred_true = constructor()
pred_false = constructor()
for item in iterable:
if pred(item):
pred_true.append(item)
else:
pred_false.append(item)
return pred_true, pred_false
|
dc0c43cd5d34869566f283d92038aaa4a53d5c62
| 25,689 |
def _slice_fn_tensor_pair(x, idxs):
""" Slice function for tensors.
Parameters
----------
x : `torch.Tensor`, `shape=(n_data, )`
Input tensor.
idxs : `List` of `int`
Indices to be taken.
Returns
-------
x : `torch.Tensor`, `shape=(n_data_chosen, )`
Output tensor.
"""
return x[0][idxs], x[1][idxs]
|
78abca7437f214973afbbbeeab62949c35827b35
| 146,189 |
from typing import Optional
def format_ipfs_cid(path: str) -> Optional[str]:
"""Format IPFS CID properly."""
if path.startswith('Qm'):
return path
elif path.startswith('ipfs://'):
return path.replace('ipfs://', '')
|
eca4a79bc2ba4151495831b51bbd50df68f73025
| 15,667 |
def create_sloping_step_function(start_x, start_y, end_x, end_y):
"""
create sloping step function, returning start y-value for input values below starting x-value, ending y-value
for input values above ending x-value and connecting slope through the middle
:param start_x: float
starting x-value
:param start_y: float
starting y-value
:param end_x: float
ending x-value
:param end_y: float
ending y-value
:return: function
sloping function as described above
"""
gradient = (end_y - start_y) / (end_x - start_x)
def step_function(age):
if age < start_x:
return start_y
elif start_x <= age < end_x:
return gradient * age + start_y - gradient * start_x
elif end_x <= age:
return end_y
return step_function
|
67c8778a9aaba03cb7847de59dd018e128876ba0
| 665,715 |
def merge_with(f, *dicts):
"""Returns a dict that consists of the rest of the dicts merged with
the first. If a key occurs in more than one map, the value from the
latter (left-to-right) will be the combined with the value in the former
by calling f(former_val, latter_val). Calling with no dicts returns {}."""
d = dict()
for _dict in dicts:
for k in _dict:
if k in d:
d[k] = f(d[k], _dict[k])
else:
d[k] = _dict[k]
return d
|
1ddb503b6a000932d115f8045676c409e05abe5c
| 678,119 |
import io
def _read_bytes(fp, size, error_template="ran out of data"):
"""
Read from file-like object until size bytes are read.
Raises ValueError if not EOF is encountered before size bytes are read.
Non-blocking objects only supported if they derive from io objects.
Required as e.g. ZipExtFile in python 2.6 can return less data than
requested.
"""
data = bytes()
while True:
# io files (default in python3) return None or raise on
# would-block, python2 file will truncate, probably nothing can be
# done about that. note that regular files can't be non-blocking
try:
r = fp.read(size - len(data))
data += r
if len(r) == 0 or len(data) == size:
break
except io.BlockingIOError:
pass
if len(data) != size:
msg = "EOF: reading %s, expected %d bytes got %d"
raise ValueError(msg % (error_template, size, len(data)))
else:
return data
|
388a244d26bf030db1fc18086c64779a34bf904e
| 680,993 |
def get_score(score):
"""
Get the score in the from the csv string
"""
# If you're having parsing problems I feel bad for you, son.
# I got 99 problems, but regex ain't one.
remove_these = ["(", "SO", "OT", ")"]
for r in remove_these:
score = score.replace(r, "")
return int(score)
|
d6865d22eb33140b214720e5d0e4b1c198325140
| 495,309 |
def Q_distcooler(P_mass, Cp, t_coolwater_exit, tp):
"""
Calculates the heat load of distilliat cooler.
Parameters
----------
W_mass : float
The mass flow rate of distilliat, [kg/s]
Cp : float
The heat capacity of distilliat, [J/(kg * degrees C)]
t_coolwater_exit: float
The end temperature of cool distilliat, [degrees C]
tp : float
The temperature of boiling distilliat, [degrees celcium]
Returns
-------
Q_distcooler : float
The heat load of distilliat cooler, [W] , [J/s]
References
----------
Дытнерский, формула 2.2, стр.45
"""
return P_mass * Cp * (tp - t_coolwater_exit)
|
200a3fc54e81f1cb5cbd6179e6857b7a599be1e4
| 594,264 |
def first(iterable, default=None):
"""Return the first element of an iterable, or a default if there aren't any."""
try:
return next(x for x in iter(iterable))
except StopIteration:
return default
|
54d7e8aa01304a6ddde2e636e96a6ecb36791a15
| 538,385 |
import math
def getChar(inputValue, chars):
"""
Return a character in the given char list, according to the given input value
Parameters
----------
inputValue : float
Value you want to tranform to char
chars : str
List of chars you will use to select a char to represent the input value
"""
charArray = list(chars)
interval = len(charArray)/256
return charArray[math.floor(inputValue*interval)]
|
fa579ef5ff8b0f76a48b5b5d1cf29ebad43ecd53
| 467,827 |
from typing import Tuple
def get_axis_collision_distances(
p1: float, w1: float, v1: float,
p2: float, w2: float
) -> Tuple[float, float]:
""" Gets the distance to the entry and exit points of a collision on
one axis.
Parameters:
p1: float - Position of first object
w1: float - Width of first object
v1: float - Velocity of first object
p2: float - Position of other object
w2: float - Width of other object
Returns:
Tuple of entry and exit distances.
Tuple[float, float]
"""
# The distance from the right side of the first
# object to the left side of the other object
r_to_2l = p2 - (p1 + w1)
# The distance from the left side of the first
# object to the right side of the other object
l_to_2r = (p2 + w2) - p1
if v1 > 0:
distance_entry = r_to_2l
distance_exit = l_to_2r
else:
distance_entry = l_to_2r
distance_exit = r_to_2l
return (distance_entry, distance_exit)
|
8ff6e39e7426099ab29017f4b976867a9b2c375a
| 116,374 |
def _sample_distribution_over_matrix(rng):
"""Samples the config for a distribution over a matrix.
Args:
rng: np.random.RandomState
Returns:
A distribution over matrix config (containing a tuple with the name and
extra args needed to create the distribution).
"""
# At this point, the choices here are arbitrary. We know some things about
# the spectrum of the hessian for various problems we care about but certainly
# not all. For example see: https://arxiv.org/abs/1901.10159.
# These selections define a distribution over spectrum. This distribution is
# NOT like the ones found in prior work, but tries to be broader, and
# (hopefully) will contain spectrum from real problems.
choice = rng.choice(["normal", "linspace_eigen", "uniform", "logspace_eigen"])
if choice == "normal":
mean = rng.normal(0, 1)
std = rng.uniform(0, 2)
return choice, {"mean": mean, "std": std}
elif choice == "uniform":
min_v = rng.uniform(-3, 1)
max_v = min_v + rng.uniform(0, 5)
return choice, {"min": min_v, "max": max_v}
elif choice == "linspace_eigen":
min_v = rng.uniform(0.01, 50)
max_v = min_v + rng.uniform(0, 100)
return choice, {"min": min_v, "max": max_v}
elif choice == "logspace_eigen":
min_v = 1e-5
max_v = rng.uniform(1, 1000)
return choice, {"min": min_v, "max": max_v}
|
20c39319f217e62bd33e06f4f556030f133baff7
| 660,063 |
def listify(item):
"""
Check if an item is enclosed in a list and make it a list if not
:param item: item to convert to a list
:return: list containing the original item
"""
if not isinstance(item, list) and item is not None:
return [item]
else:
return item
|
298e973eb2b285567131c2eb4b134be7cb3ffb09
| 536,375 |
def pass_bot(func):
"""This decorator is deprecated, and it does nothing"""
# What this decorator did is now done by default
return func
|
b8043b87b762db9f7b78617ad253aaca9dcd4369
| 659,205 |
import functools
def qutip_callback(func, **kwargs):
"""Convert `func` into the correct form of a QuTiP time-dependent control
QuTiP requires that "callback" functions that are used to express
time-dependent controls take a parameter `t` and `args`. This function
takes a function `func` that takes `t` as its first parameter and an
arbitrary number of other parameters. The given `kwargs` set values for
these other parameters. Parameters not contained in `kwargs` are set
*at runtime* from the `args` dict.
"""
partial_func = functools.partial(func, **kwargs)
def callback(t, args):
if args is None:
args = {}
return partial_func(t, **args)
return callback
|
8d20a3fc75bd673a3b5576e2d147162d13ca19ba
| 663,755 |
def _pass(x):
"""Format text without changing it."""
return x
|
0357342fa3654343e0db3fd349c15e1596f2b77c
| 479,497 |
def NoTests(path, dent, is_dir):
"""Filter function that can be passed to FindCFiles in order to remove test
sources."""
if is_dir:
return dent != 'test'
return 'test.' not in dent
|
ad9ce5a0a4df693a2fa2589808a393b8d30b7a23
| 52,873 |
def filter_rule_ids(all_keys, queries):
"""
From a set of queries (a comma separated list of queries, where a query is either a
rule id or a substring thereof), return the set of matching keys from all_keys. When
queries is the literal string "all", return all of the keys.
"""
if not queries:
return set()
if queries == 'all':
return set(all_keys)
# We assume that all_keys is much longer than queries; this allows us to do
# len(all_keys) iterations of size len(query_parts) instead of len(query_parts)
# queries of size len(all_keys) -- which hopefully should be a faster data access
# pattern due to caches but in reality shouldn't matter. Note that we have to iterate
# over the keys in all_keys either way, because we wish to check whether query is a
# substring of a key, not whether query is a key.
#
# This does have the side-effect of not having the results be ordered according to
# their order in query_parts, so we instead, we intentionally discard order by using
# a set. This also guarantees that our results are unique.
results = set()
query_parts = queries.split(',')
for key in all_keys:
for query in query_parts:
if query in key:
results.add(key)
return results
|
daf5a40754c34342d0707c2334be2ad9de0444e0
| 677,518 |
import math
def _map_tile_count(map_size: int, lod: int) -> int:
"""Return the number of map tiles for the given map.
Args:
map_size (int): The base map size in map units
lod (int): The LOD level for which to calculate the tile count
Returns:
int: The number of tiles in the given map's tile grid
"""
return math.ceil(4 ** (int(math.log2(map_size)) - 8 - lod))
|
8ced1676043098a3cfddc106b0aaab0e2745e5b2
| 677,397 |
def Fibonacci_digit(n):
"""Return the index of the first term in the Fibonacci sequence to contain n digits.
The Fibonacci sequence is defined by the recurrence relation:
F(n) = F(n-1) + F(n-2), where F(1) = F(2) = 1.
Parameters
----------
n : int
The resulting number of digits. The Fibonacci sequence at the resulting index is
desired to contain `n` digits.
Returns
-------
int
The index of the first term in the Fibonacci sequence that contains `n` digits.
Examples
--------
The index of the first term in the Fibonacci sequence containing 3 digits.
>>> Fibonacci_digit(3)
12
The index of the first term in the Fibonacci sequence containing 1000 digits.
>>> Fibonacci_digit(1000)
4782
"""
if n == 1:
return 1
F = [1,1]
while len(str(F[-1])) < n:
F.append(F[-1] + F[-2])
return F.index(F[-1]) + 1
|
de66f2d4f809051a8696d4b60828aee73bfa9681
| 483,396 |
def cu_mask_to_int(cu_mask):
""" A utility function that takes an array of booleans and returns an
integer with 1s wherever there was a "True" in the array. The value at
index 0 is the least significant bit. """
n = 0
for b in reversed(cu_mask):
n = n << 1
if b:
n |= 1
return n
|
2ac11b0a7845771808cec3779edf975f6239632b
| 465,148 |
def encode_special_characters(user_string):
"""
Encode Special Characters for user's search Strings
Args:
user_string(string): raw string to encode
Returns:
Encode string for elasticsearch
"""
if user_string is None:
return ""
sp_chars = ['+', '-', '=', '|', '<', '>', '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', '*', '?', ':', '\\', '/']
# List of special characters can be found here: https://www.elastic.co/guide/en/elasticsearch/reference/2.4/query-dsl-query-string-query.html#_reserved_characters
output_list = []
for char in user_string:
if char in sp_chars:
# replace
output_list.append(char.replace(char, '\\' + char))
else:
output_list.append(char)
return "".join(output_list)
|
00d31e32a823028a08333bd59000f52b64dafcf9
| 32,502 |
def get_second_validate_param(tel_num):
"""
Assemble param for get_second_validate
:param tel_num: Tel number
:return: Param in dict
"""
param_dict = dict()
param_dict['act'] = '1'
param_dict['source'] = 'wsyytpop'
param_dict['telno'] = tel_num
param_dict['password'] = ''
param_dict['validcode'] = ''
param_dict['authLevel'] = ''
param_dict['decode'] = '1'
param_dict['iscb'] = '1'
return param_dict
|
efbd31c56e3fdd4cb0e75bcae92cf51d996aac5d
| 22,146 |
def isValidChannelName(channelName):
"""
Determines whether the given channel name is in a valid format.
"""
if channelName[0] != "#":
return False
for char in "\x07 ,?*": # \x07, space, and comma are explicitly denied by RFC; * and ? make matching a channel name difficult
if char in channelName:
return False
return True
|
ea5ab661f117e9c91eff3b3a11cf6bc66f625dd9
| 442,514 |
import re
def filter_tests(filters, test_ids):
"""Filter test_ids by the test_filters.
:param list filters: A list of regex filters to apply to the test_ids. The
output will contain any test_ids which have a re.search() match for any
of the regexes in this list. If this is None all test_ids will be
returned
:param list test_ids: A list of test_ids that will be filtered
:return: A list of test ids.
"""
if filters is None:
return test_ids
_filters = list(map(re.compile, filters))
def include(test_id):
for pred in _filters:
if pred.search(test_id):
return True
return list(filter(include, test_ids))
|
d8ca31fddb052dde7eaaa21c777e2963e705a598
| 40,353 |
def temperature_over_total_temperature(
mach,
gamma=1.4
):
"""
Gives T/T_t, the ratio of static temperature to total temperature.
Args:
mach: Mach number [-]
gamma: The ratio of specific heats. 1.4 for air across most temperature ranges of interest.
"""
return (1 + (gamma - 1) / 2 * mach ** 2) ** -1
|
a1fea37f80df9eff21716f273b6270cfa7fcd302
| 37,882 |
import math
def iterate_pagerank(corpus, damping_factor):
"""
Return PageRank values for each page by iteratively updating
PageRank values until convergence.
Return a dictionary where keys are page names, and values are
their estimated PageRank value (a value between 0 and 1). All
PageRank values should sum to 1.
"""
pagerank = dict()
newrank = dict()
# Assign initial values for pagerank
for page in corpus:
pagerank[page] = 1 / len(corpus)
repeat = True
while repeat:
# Calculate new rank values based on all of the current rank values
for page in pagerank:
total = float(0)
for possible_page in corpus:
# We consider each possible page that links to current page
if page in corpus[possible_page]:
total += pagerank[possible_page] / len(corpus[possible_page])
# A page that has no links is interpreted as having one link for every page (including itself)
if not corpus[possible_page]:
total += pagerank[possible_page] / len(corpus)
newrank[page] = (1 - damping_factor) / len(corpus) + damping_factor * total
repeat = False
# If any of the values changes by more than the threshold, repeat process
for page in pagerank:
if not math.isclose(newrank[page], pagerank[page], abs_tol=0.001):
repeat = True
# Assign new values to current values
pagerank[page] = newrank[page]
return pagerank
|
55ecbae0d470bd63d1f33c5d0f5bbdd2fe4806d7
| 230,771 |
def stripped(v):
"""Cleans string to remove quotes"""
return v.strip('"').strip("'")
|
48514b274f9d0b1a884dd2a8add134ba5b82afbf
| 513,020 |
def gasfvf2(unit='unit1', z=0.8, temp=186, pressure=2000):
"""
Gas FVF calculated in other units
unit: choice of units (unit1: RB/scf, unit2: res m3/std m3)
for unit1, inputs temp in Rankine (Fahrenheit + 460), pressure in psia or psig
for unit2, inputs temp in Kelvin, pressure in psia or psig
"""
if unit == 'unit1':
return(0.00503676 * z * temp / pressure)
if unit == 'unit2':
return(0.350958 * z * temp / pressure)
|
732270809bfef7760ec4fb71470653dcfcb2265e
| 362,379 |
def mean(lst):
"""Return the average of a float list."""
length = len(lst)
return sum(lst)/float(length) if length != 0 else None
|
d9b669cb438afc66c4ccd8acfd10b63121c5f003
| 418,889 |
def prepare_args(args):
"""
Prepare arguments to be used as the API expects it
:param args: demisto args
:return: transformed args
"""
args = dict((k.replace("-", "_"), v) for k, v in list(args.items()))
if "is_public" in args:
args["is_public"] = args["is_public"] == "True"
return args
|
eaf0d7f7f30390d02481ff01e9eea4a7b3262ef2
| 626,969 |
def cast_no_data_value(no_data_value, dtype):
"""Handles casting nodata values to correct type"""
int_types = ['uint8', 'uint16', 'int16', 'uint32', 'int32']
if dtype in int_types:
return int(no_data_value)
else:
return float(no_data_value)
|
e5d4fab57ca00b154990890aafee5ebc8290207d
| 126,464 |
def max_length(tensor):
"""
Return max length of the tensor
"""
return max(len(t) for t in tensor)
|
ccf2bcaec70f20338396e9c7db5ab21233336f22
| 497,853 |
import requests
def get_html(zipcode):
"""
Get the html to be parsed.
:param zipcode:
:return: html from web.
"""
url = f'https://www.wunderground.com/weather-forecast/{zipcode}'
response = requests.get(url)
return response.text
|
28cdb00b7746017b69e955a379eb2f248a675fe2
| 615,761 |
import collections
def get_gt_distribution(experience, get_block):
"""
Get the ground-truth distribution of an experience buffer.
:param experience: List of transitions.
:param get_block: Function that returns the ground-truth state-action block for each transition.
:return: Number of samples for each state-action block.
"""
dist = collections.defaultdict(lambda: 0)
for transition in experience:
key = get_block(transition.state, transition.reward, transition.next_state)
dist[key] += 1
dist = dict(dist)
return dist
|
6dcba0e714d9d98a530c16fcfa12679980b46871
| 40,881 |
def getShortestPaths(paths):
""" Returns a list containing only the shortest paths. The list may contain
several shorters paths with the same length.
"""
shortestPaths = []
shortestLength = 99999
for path in paths:
if len(path) < shortestLength:
shortestLength = len(path)
for path in paths:
if len(path) == shortestLength:
shortestPaths.append(path)
return shortestPaths
|
679ce4d747291d00cdb4875bef9360e595fbdb64
| 288,396 |
import time
import requests
import uuid
import webbrowser
def _check_for_api(launch_browser=False, timeout=5):
"""Helper method to check for the API to be live for up to 15 seconds and then optionally launch a browser window
Args:
launch_browser(bool): flag indicating if the browser should be launched on success == True
timeout(int): Number of seconds to wait for the API before returning
Returns:
bool: flag indicating if the API is ready
"""
time.sleep(1)
success = False
for _ in range(timeout):
try:
resp = requests.get("http://localhost:10000/api/ping?v={}".format(uuid.uuid4().hex))
if resp.status_code == 200:
success = True
break
except requests.exceptions.ConnectionError:
# allow connection errors, which mean the API isn't up yet.
pass
# Sleep for 1 sec and increment counter
time.sleep(1)
if success is True and launch_browser is True:
time.sleep(2)
# If here, things look OK. Start browser
webbrowser.open_new("http://localhost:10000")
return success
|
ffed20b56e7acb1625593f30cb452f9c9dea8681
| 590,235 |
def extract_layers_by_str(model, layers):
"""
Returns references to layers from model by name
Parameters
----------
model : torch.nn.Module
model where layers should be extracted from
layers : iterable of str
iterable which contains the names of the respective layers
Returns
-------
list
list with references to specified layers
"""
def extract_layer_Torch(model, layer):
"""
Extract a reference to single layer from model
Parameters
----------
model : torch.nn.Module
model where layers should be extracted from
layer : str
name of respective layer
Returns
-------
nn.Module
reference to layer
"""
submod = model
if '.' in layer:
# split actual layer name and 'path' to layer
prefix, name = layer.rsplit('.', 1)
# extract layer
for l in prefix.split('.'):
submod = getattr(submod, l)
else:
name = layer
return getattr(submod, name)
return [extract_layer_Torch(model, l) for l in layers]
|
9c25579a129f45b16bf67f061497123dfd285f73
| 607,962 |
import random
def slice_dir_to_int(slice_dir):
"""
Convert slice direction identifier to int.
Args:
slice_dir: x|y|z|xyz (string)
Returns:
0|1|2 (int)
"""
if slice_dir == "xyz":
slice_direction_int = int(round(random.uniform(0, 2)))
elif slice_dir == "x":
slice_direction_int = 0
elif slice_dir == "y":
slice_direction_int = 1
elif slice_dir == "z":
slice_direction_int = 2
else:
raise ValueError("Invalid value for 'training_slice_direction'.")
return slice_direction_int
|
b1a94b4cb2753128fc7403ceca99ffeb9591e810
| 204,811 |
def sdf_supported_property_non_string(property_name):
"""
Check to verify that this property is support natively in SDF
(without modification)
:param property_name name to check
:return: boolean true/false
"""
supportedProperties = ["minimum",
"maximum", "uniqueItems", "default", "exclusiveMinimum"]
# readOnly, enum, $ref handled in a special function,
# to rename / reorder properties
if property_name in supportedProperties:
return True
else:
return False
|
ccc8108dbcc1eb5cb665050b1a5874fcc2ec7b3a
| 601,900 |
from typing import Tuple
import re
def replace_code(
begin_delim: str, end_delim: str, content: str, new_code: str
) -> Tuple[str, int]:
"""Replaces text delimited by `begin_delim` and `end_delim` appearing in `content`, with `new_code`.
Returns new string and number of matches made."""
return re.subn(
fr"{re.escape(begin_delim)}([\s\S]*?){re.escape(end_delim)}",
new_code.replace(
"\\", "\\\\"
), # Need to escape backslashes twice for re package
content,
)
|
ab7cfff3c3ae7b0356a1b3558b2fa36c1beb5401
| 683,657 |
def calibrate_2band(instr1, instr2, airmass1, airmass2, coeff1, coeff2,
zero_key='zero', color_key='color', extinct_key='extinction'):
"""
This solves the set of equations:
i_0 = i + A_i + C_i(i-z) + k_i X
z_0 = z + A_z + C_z(z-i) + k_z X
where i_0 and z_0 are the instrumental magnitudes, A_i and A_z are the
zero points, C_i and C_z are the color terms, k_i and k_z are the
atmospheric coefficients, and X is the airmass.
The solution is of the form:
(1+C_i)i = b_i + C_i z
(1+C_z)z = b_z + C_z i
where
b_i = i_0 - A_i - k_i X
b_z = z_0 - A_z - k_z X
so that
i = (C_i b_z + C_z b_i + b_i) / d
z = (C_z b_i + C_i b_z + b_z) / d
where
d = (1+C_i+C_z)
Parameters
----------
instr1: array-like
Instrumental magnitudes of filter 1
instr2: array-like
Instrumental magnitudes of filter 2
airmass1: array-like
Airmass for each observation in filter 1
airmass2: array-like
Airmass for each observation in filter 2
coeff1: array-like
List of coeffients for calibrating instrumental magnitudes for
instrument 1.
* coeff1[0]: zeropoint
* coeff1[1]: color coeffcient
* coeff1[2]: extinction coefficient
coeff2: array-like
List of coeffients for calibrating instrumental magnitudes for
instrument 2
returns
-------
mag1: array-like
Calibrated magnitude 1
mag2: array-like
Calibrated magnitude 2
"""
b1 = instr1 - coeff1[zero_key] - coeff1[extinct_key]*airmass1
b2 = instr2 - coeff2[zero_key] - coeff2[extinct_key]*airmass2
d = 1 + coeff1[color_key] + coeff2[color_key]
mag1 = (coeff1[color_key]*b2 + b1*(1+coeff2[color_key])) / d
mag2 = (coeff2[color_key]*b1 + b2*(1+coeff1[color_key])) / d
return (mag1,mag2)
|
df3d586646098b0c723032406a5ffbea8df11eb9
| 101,504 |
def rayleigh_vel(longitudinal_vel, transverse_vel):
"""
Approximate Rayleigh velocitiy.
Parameters
----------
longitudinal_vel : float
transverse_vel : float
Returns
-------
rayleigh_vel : float
Notes
-----
[Freund98] Freund, L. B.. 1998. `Dynamic Fracture Mechanics`.
Cambridge University Press. p. 83. ISBN 978-0521629225.
"""
poisson = (longitudinal_vel ** 2 - 2 * transverse_vel ** 2) / (
2 * (longitudinal_vel ** 2 - transverse_vel ** 2)
)
if poisson <= 0:
raise ValueError
return transverse_vel * (0.862 + 1.14 * poisson) / (1 + poisson)
|
d99c572eb38f03ae0d3fa8701a6e51ee45fb7533
| 287,332 |
def get_r(x,y,z):
"""Get density r"""
den = x**2+z**2
return den
|
24a39524ee9e07aa23b19f5a030a1bf3f4c0f8ac
| 379,147 |
def list_sync(api, instance="", **params):
# type (ApiClient, str) -> list[dict[str]]
"""
list all the communities of an instance. If no instance is provided , all the communities
Args:
api: the ApiClient instance to use for requests
instance: the instance id
**params: optional dictionary of search parameters as defined in https://api.lumapps.com/docs/community/list
Returns:
list: a list of Lumapps Community resources
"""
if not params:
params = dict()
if not params.get("fields", None):
params[
"fields"
] = "cursor,items(adminKeys,instance,status,title,type,uid,userKeys,authorId, description)"
if not params.get("body", None):
params["body"] = {"lang": "en"}
if instance:
params["body"]["instanceId"] = instance
result = api.get_call("community", "list", **params)
return result
|
4aa389c68d7d3a96da3bf552300661e3d5df6733
| 157,878 |
def center(map, object):
"""
Center an ee.Image or ee.Feature on the map.
Args:
map: The map to center the object on.
object: The ee.Image or ee.Feature to center.
Returns:
The provided map.
"""
coordinates = object.geometry().bounds().coordinates().getInfo()[0]
bounds = [[point[1], point[0]] for point in coordinates]
map.fit_bounds(bounds)
return map
|
60a2baa1c4f83b0e9b1221bcc474f109c35cbd7a
| 701,034 |
def burst(group):
"""
Returns the number of shots the fire mode will make.
"""
if group["fire_mode"] == "auto":
shots = 3
else:
shots = 1
return shots
|
8e46adbe3814103df7c3390f3c17368e4f391da0
| 193,310 |
def judgement(seed_a, seed_b):
"""Return amount of times last 16 binary digits of generators match."""
sample = 0
count = 0
while sample <= 40000000:
new_a = seed_a * 16807 % 2147483647
new_b = seed_b * 48271 % 2147483647
bin_a = bin(new_a)
bin_b = bin(new_b)
last16_a = bin_a[-16:]
last16_b = bin_b[-16:]
if last16_a == last16_b:
count += 1
seed_a = new_a
seed_b = new_b
sample += 1
return count
|
9d778909ba6b04e4ca3adbb542fce9ef89d7b2b7
| 3,698 |
def key_of_max(d):
"""Return key associated with maximum value in d.
>>> key_of_max({'a':1, 'b':2})
'b'
"""
keys = list(d.keys())
keys.sort()
return max(keys, key=lambda x: d[x])
|
01ee05b37d8c8bbaa12c184aba422c2e3ac2e438
| 58,831 |
import glob
def find_all_filetype(data_dir, extension):
""" Finds all files in a directory, returns their path
Args:
data_dir (str): path to where your MitoGraph output data are
extension (str): the extension to search for (e.g. ".gnet", ".mitograph")
Returns:
path_list (list of strings): a list where each element is a string containing the path for desired files (with extension)
(e.g. path_list = [sample1.gnet, sample2.gnet])
"""
# create a string to search for, include a wildcard * in place of the name of the file
search_criteria = "".join([data_dir, "/*", extension])
# use glob.glob to do the searching and retreive your list!
path_list = glob.glob(search_criteria)
return path_list
|
90668bd0c8dbbcfcfc5b8a786d74b22fd76dd35c
| 296,162 |
def calculate_average_since(hrs_after_time):
""" Calculate average heart rate after specified date
This function first sums all of the heart rates after the specified date.
It then divides the summed heart rates by the total number of heart rate
entries. The result is the sum of the heart rates after the entered time.
:param hrs_after_time: a list of heart rate values that were entered after
the specified time ("heart_rate_average_since")
:returns: an integer indicating the average heart rate of the patient after
a certain date
"""
total_entries = len(hrs_after_time)
average_since = sum(hrs_after_time) / total_entries
return average_since
|
68c587200cfdcc0bd8607cb2a2485acf72c93681
| 355,232 |
def get_sentence_length(train_data_set, test_data_set):
"""
Acquire the longer of the maximum sentence lengths of training data and test data.
:param train_data_set: Raw sentence for training data
:param test_data_set: Raw sentence for testing data
:return: Maximum sentence length
"""
if max([len(sentence.split(" ")) for sentence in train_data_set]) > max([len(sentence.split(" ")) for sentence in test_data_set]):
sentence_length = max([len(sentence.split(" ")) for sentence in train_data_set])
else:
sentence_length = max([len(sentence.split(" ")) for sentence in test_data_set])
return sentence_length
|
7131158d9af35deeef2d7de07508ba6080931fbf
| 257,184 |
from typing import Dict
import re
def wikitext_detokenize(example: Dict[str, str]) -> Dict[str, str]:
"""
Wikitext is whitespace tokenized and we remove these whitespaces.
Taken from https://github.com/NVIDIA/Megatron-LM/blob/main/tasks/zeroshot_gpt2/detokenizer.py
"""
# Contractions
text = example["text"]
text = text.replace("s '", "s'")
text = re.sub(r"/' [0-9]/", r"/'[0-9]/", text)
# Number Separators
text = text.replace(" @-@ ", "-")
text = text.replace(" @,@ ", ",")
text = text.replace(" @.@ ", ".")
# Punctuation
text = text.replace(" : ", ": ")
text = text.replace(" ; ", "; ")
text = text.replace(" . ", ". ")
text = text.replace(" ! ", "! ")
text = text.replace(" ? ", "? ")
text = text.replace(" , ", ", ")
# Double Brackets
text = re.sub(r"\(\s*([^\)]*?)\s*\)", r"(\1)", text)
text = re.sub(r"\[\s*([^\]]*?)\s*\]", r"[\1]", text)
text = re.sub(r"{\s*([^}]*?)\s*}", r"{\1}", text)
text = re.sub(r"\"\s*([^\"]*?)\s*\"", r'"\1"', text)
text = re.sub(r"'\s*([^']*?)\s*'", r"'\1'", text)
# Miscellaneous
text = text.replace("= = = =", "====")
text = text.replace("= = =", "===")
text = text.replace("= =", "==")
text = text.replace(" " + chr(176) + " ", chr(176))
text = text.replace(" \n", "\n")
text = text.replace("\n ", "\n")
text = text.replace(" N ", " 1 ")
text = text.replace(" 's", "'s")
return {"text": text}
|
ad06cc5c394684a265e6e91e29d3744466f18eb6
| 666,702 |
import yaml
def dump_to_string(data)-> str:
"""
Dumps 'data' object to yaml string
"""
result = yaml.safe_dump(data,
default_flow_style=False,
default_style=None,
explicit_start=None)
return result
|
234927a81831d92820bf8599a7b27ee7e256793f
| 661,280 |
def coor_to_int(coor):
"""
Convert the latitude/longitute from float to integer by multiplying to 1e6,
then rounding off
"""
return round(coor * 1000000)
|
b0ec7507887d492dc92e6b9452ac7091db558888
| 292,800 |
def decorate_if_staff(decorator):
"""
Returns decorated view if user is staff. Un-decorated otherwise
(the inverse version of decorate_if_no_staff)
"""
def _decorator(view):
decorated_view = decorator(view) # This holds the view with decorator
def _view(request, *args, **kwargs):
if request.user.is_staff: # If user is staff
return decorated_view(request, *args, **kwargs) # view with decorator
else:
return view(request, *args, **kwargs) # view without decorator
return _view
return _decorator
|
d0532dc935d2be3a296058f44d271acab72b790a
| 309,673 |
def toSet(hashes):
"""
converts the hashes (iterable) to a corresponding set of hashes
"""
s = set()
for val in hashes:
s.add(val)
return s
|
7b5f5c86af52afa00ce2c8cf642826a7ecfa885f
| 182,118 |
import copy
def merge_normalized_sequence_analyzers(sequence_analyzers):
"""Merges SequenceAnalyzers and returns the result
SequenceAnalyzers copied and normalized setting their individual total
frequency to one. The sum of all normalized SequenceAnalyzers is then
returned.
Args:
sequence_analyzers: List of SequenceAnalyzers to merge.
Returns:
The resulting normalized merge of the SequenceAnalyzers.
"""
# copy input to avoid mutation
sas_copy = [copy.deepcopy(sa) for sa in sequence_analyzers]
# normalize sequences analyzers
for sa in sas_copy:
sa.total_freq = 1
# add all sequences analyzers to the first
for sa in sas_copy[1:]:
sas_copy[0] += sa
return sas_copy[0]
|
adfb9290da867f19b43d04b9d51c84a630edc880
| 203,190 |
def get_identifier(commit_datetime, commit_hash, trt_version, branch):
"""
Returns an identifier that associates uploaded data with an ORT commit/date/branch and a TensorRT version.
:param commit_datetime: The datetime of the ORT commit used to run the benchmarks.
:param commit_hash: The hash of the ORT commit used to run the benchmarks.
:param trt_version: The TensorRT version used to run the benchmarks.
:param branch: The name of the ORT branch used to run the benchmarks.
:return: A string identifier.
"""
date = str(commit_datetime.date()) # extract date only
return date + "_" + commit_hash + "_" + trt_version + "_" + branch
|
a0c64a414caa057ba09dea15c888482eeeb31bc0
| 397,504 |
from typing import List
import math
def equal_split(s: str, width: int) -> List[str]:
"""
Split the string, each split has length `width` except the last one.
"""
num = int(math.ceil(len(s) / width)) # python3
return [s[i * width: (i + 1) * width] for i in range(num)]
|
46ae233f314136e36913834f40576a78fdab7bdf
| 683,464 |
import yaml
def get_credentails_from_file(auth_file):
"""Read the vault credentials from the auth_file.
:param auth_file: Path to file with credentials
:type auth_file: str
:returns: Token and keys
:rtype: dict
"""
with open(auth_file, 'r') as stream:
vault_creds = yaml.safe_load(stream)
return vault_creds
|
75872999cccfc5b19edbb9bb250503a8d6b0c532
| 397,089 |
def get_gender_from_wiki_claims(clm_dict):
"""
From clim_dict produced by pywikibot from a page, tries to extract the gender of the object of the page
If it fails returns None
N.B. Wikidata's categories for transgender male and female are treated as male and female, respectively
>>> from gender_novels.corpus_gen import get_gender_from_wiki_claims
>>> site = pywikibot.Site("en", "wikipedia")
>>> page = pywikibot.Page(site, 'Zeus')
>>> item = pywikibot.ItemPage.fromPage(page)
>>> dictionary = item.get()
>>> clm_dict = dictionary["claims"]
>>> get_gender_from_wiki_claims(clm_dict)
'male'
:param clm_dict: dict
:return: str
"""
try:
clm_list = clm_dict["P21"]
gender_id = None
for clm in clm_list:
clm_trgt = clm.getTarget()
gender_id = clm_trgt.id
if (gender_id == 'Q6581097' or gender_id == 'Q2449503'):
return 'male'
if (gender_id == 'Q6581072' or gender_id == 'Q1052281'):
return 'female'
if (gender_id == 'Q1097630'):
return 'non-binary'
except (KeyError, AttributeError):
return None
|
dc85408e1680ed5acf066d5663e46ec805fdc0b9
| 268,505 |
def generate_prefixes(vocabulary):
"""Return a set of unique prefixes from the given list of strings."""
# Generate prefixes using the first half of each string
return set(word[:len(word)//2] for word in vocabulary)
|
b5b2f46170ef21ff4b259ec19c9deb680a852c07
| 272,654 |
def find_children_by_type(component, target_type):
"""Recursively find all children of the component and it's decendents by type.
:param component: Component instance to start seach from
:type component: class instance
:param target_type: class to match with instances
:type target_type: class
:return: All instances of type 'target_type' that are descendents of 'component'
:rtype: list
"""
results = []
try:
for c in component.children:
if isinstance(c, target_type):
results.append(c)
results += find_children_by_type(c, target_type)
except AttributeError:
pass
# No children
return results
|
98c2db35586878047c7c3523dd41142a1e044b55
| 488,465 |
async def handleIconBytes(response):
"""Handles returning of iconBytes response value.
Args:
response (aiohttp.ClientResponse): Request response
Returns:
bytes: Icon image in bytes
"""
return await response.read()
|
e219d8fe2c09a1b60cc890a18d8a4dc77ba665fd
| 530,737 |
def acquire_category(soup):
"""
Take a BeautifulSoup content of a book page.
Return the category of the book.
"""
table = soup.ul.find_all('a')
category = table[2].string
return category
|
ce0f28cab0809959d89f684d1d1e5ba060abb51a
| 42,133 |
def get_bulk_download_links(page):
"""Extracts the bulk download links from the BeautifulSoup object.
Parameters
----------
page : bs4.BeautifulSoup
The bs4 representation for the bulk download page
Returns
-------
download_links : dict
A dictionary containing the download links
"""
section = page.find("section")
links = section.find_all("a")
download_links = dict()
current_state = None
for link in links:
if "name" in link.attrs:
current_state = link["name"]
elif "href" in link.attrs:
if link["href"].startswith("mailto:"):
continue
session = link.text.strip()
state_links = download_links.get(current_state, list())
state_links.append({"session": session, "link": link["href"]})
download_links[current_state] = state_links
return download_links
|
09459d6930d8966309217885328f7600d48d4e48
| 194,368 |
import typing
def identifier_path(it: typing.Union[typing.Type[object], typing.Callable]) -> str:
"""Generate an identifier based on an object's module and qualified name. This can
be useful such as for adding attributes to existing objects while minimizing odds
of collisions and maximizing traceability of the related party.
Args:
it: The object to generate the identifer from.
Returns:
The generated identifier string.
"""
return "__" + "_".join(it.__module__.split(".") + [it.__qualname__])
|
6702c0d98c93d5ffbccbef4bdbca9884302358f6
| 588,377 |
def epsilon(i, j, k):
"""
Return 1 if i,j,k is equal to (1,2,3), (2,3,1), or (3,1,2);
-1 if i,j,k is equal to (1,3,2), (3,2,1), or (2,1,3);
else return 0.
This is used in the multiplication of Pauli matrices.
Examples
========
>>> from sympy.physics.paulialgebra import epsilon
>>> epsilon(1, 2, 3)
1
>>> epsilon(1, 3, 2)
-1
"""
if (i, j, k) in [(1, 2, 3), (2, 3, 1), (3, 1, 2)]:
return 1
elif (i, j, k) in [(1, 3, 2), (3, 2, 1), (2, 1, 3)]:
return -1
else:
return 0
|
7e4bffa3898a727c697a47d9002021b886671a5d
| 501,960 |
import importlib
def get_cls(module_name, class_name, relaxed=True):
""" Small helper function to dynamically load classes"""
try:
module = importlib.import_module(module_name)
except ImportError:
if relaxed:
return None
else:
raise ImportError("Cannot load module: %s" % module_name)
try:
return getattr(module, class_name)
except AttributeError:
if relaxed:
return None
else:
raise NotImplementedError("Cannot load class: %s.%s" % (module_name, class_name))
|
5c400001708d402951ec0e3353f93d795a15d82f
| 487,006 |
def Lsynch_murphy(sfr, nu):
"""
Synchrotron luminosity model, taken from Eq. 9 of Bonaldi et al.
(arXiv:1805.05222).
Parameters
----------
sfr : array_like
Star-formation rate, in Msun/yr.
nu : array_like
Frequency, in GHz.
Returns
-------
L_synch : array_like, float
Synchrotron luminosity in W Hz^-1.
"""
freq_fac = nu**(-0.85) / (1. + (nu / 20.)**0.5)
return 1.9e21 * sfr * freq_fac
|
e5309f3d36040aa11a68ef9b67433909f59c281f
| 363,771 |
def _extract_comment(_comment):
"""
remove '#' at start of comment
"""
# if _comment is empty, do nothing
if not _comment:
return _comment
# str_ = _comment.lstrip(" ")
str_ = _comment.strip()
str_ = str_.lstrip("#")
return str_
|
ce4290e5534833b104c5e16874566562fa772b57
| 502,957 |
def _filter_keys(d, pred):
"""Filter the dict, keeping entries whose keys satisfy a predicate."""
return dict((k, v) for k, v in d.items() if pred(k))
|
de7afa9e635b3d2cf891edcf4e509c4f85fb9391
| 488,813 |
def askYesOrNo(msg):
""" Asks a Yes/No question. Returns True/False. """
while True:
edit = input('\n' + msg + ' (y/n): ')
if edit == 'y':
return True
elif edit == 'n':
return False
else:
print('Please enter Yes ("y") or No ("n").')
|
27bc05b508dfb635c32eec23677a2567ec3a3812
| 239,844 |
def Concrete01Funct(fc, ec, fpcu, ecu, discretized_eps):
"""
Function with the equation of the curve of the Concrete01 model.
For more information, see Kent-Scott-Park concrete material object with
degraded linear unloading/reloading stiffness according to the work of Karsan-Jirsa and no tensile strength.
@param fc (float): Compressive concrete yield stress (negative).
@param ec (float): Compressive concrete yield strain (negative).
@param fpcu (float): Concrete crushing strength (negative).
@param ecu (float): Concrete strain at crushing strength (negative).
@param discretized_eps (float): Variable strain.
@returns float: Stress in function of variable strain.
"""
if discretized_eps > ec:
eta = discretized_eps/ec;
return fc*(2*eta-eta*eta);
else:
Ttangent = (fc-fpcu)/(ec-ecu)
return fc + Ttangent*(discretized_eps-ec);
|
d2cde0730ca677c3ba710f64227ad6b658656d04
| 153,400 |
def from_saved_model(layer):
"""Returns whether the layer is loaded from a SavedModel."""
return layer.__module__.find('keras.saving.saved_model') != -1
|
2616dc31d2a6523304259664ce73f0f57a81ebd9
| 79,268 |
def format_states(states):
"""
Format logging states to prettify logging information
Args:
states: logging states
Returns:
- formated logging states
"""
formated_states = {}
for key, val in states.items():
if isinstance(val, float):
if val < 1e-3:
val = '{:.4e}'.format(val)
else:
val = '{:.4f}'.format(val)
formated_states[key] = val
return formated_states
|
4612914f26813b9dd4cea527ec54f3d03ec5284f
| 664,209 |
def unprocess_image(image):
""" Undo preprocess image. """
# Normalize image to [0, 1]
image = (image / 2) + 0.5
image = image * 255.0 #[0,1] to [0,255] range
return image
|
68b8bddfa0d33530687e753bc0f2a07c9be4e425
| 54,045 |
def set_spines(ax, plot_params):
"""
Sets spines of the shift graph to be invisible if chosen by the user
Parameters
----------
ax: Matplotlib ax
Current ax of the shift graph
plot_parms: dict
Dictionary of plotting parameters. Here `invisible_spines` is used
"""
spines = plot_params["invisible_spines"]
if spines:
for spine in spines:
if spine in {"left", "right", "top", "bottom"}:
ax.spines[spine].set_visible(False)
else:
print("invalid spine argument")
return ax
|
4e74ce30f52d465e9470f608cd8c909dfae4d0a5
| 704,069 |
def decimal_hours(timeobject, rise_or_set: str) -> float:
"""
Parameters
----------
timeobject : datetime object
Sunrise or -set time
rise_or_set: string
'sunrise' or 'sunset' specifiying which of the two timeobject is
Returns
-------
float
time of timeobject in decimal hours
"""
assert rise_or_set == "sunrise" or rise_or_set == "sunset"
if timeobject:
ret = timeobject.hour + timeobject.minute / 60
if ret == 0:
return 0.0
else:
return ret
elif rise_or_set == "sunrise":
return 0.0
else:
return 23.999
|
44fe260abf8751cb78cf6e484dbf223d05233713
| 28,046 |
def is_capacity_empty(capacity):
"""
Check for an empty Capacity object to detect for empty Excel rows.
:param capacity: Capacity
:return: Boolean
"""
if capacity.ap is None \
and capacity.capacity is None:
return True
return False
|
e40374765f2266433fd1eed910d8cd686def41ef
| 580,746 |
def KtoF(tmp):
"""Standard Kelvin to Fahrenheit Temperature conversion"""
tmp = tmp - 273.16
return 9. / 5. * tmp + 32.
|
92e8a2a3cc4b1c2f4cf9fb7cb3d2ec7681412d27
| 350,585 |
def build_sg_graph_dict(sg):
""" Builds a dictionary of dependencies for each node, where each node can have either component
or supplier dependents or both. If a node has no dependents of a certain type, the key is missing.
A node with no dependents has an empty dictionary."""
def type_tag(node):
return list(filter(lambda t: t in ("component", "supplier"), sg.nodes[node].tags))[0]
g = {n: {} for n in sg.nodes.keys()}
for e in sg.edges:
if "potential" not in e.tags:
g[e.dst][type_tag(e.src)] = g[e.dst].get(type_tag(e.src), []) + [e.src]
return g
|
ecd8c1b0488b04a2cde4a1b030d96de5a78cc948
| 85,793 |
def GetLinkType(messages, link_type_arg):
"""Converts the link type flag to a message enum.
Args:
messages: The API messages holder.
link_type_arg: The link type flag value.
Returns:
An LinkTypeValueValuesEnum of the flag value, or None if absent.
"""
if link_type_arg is None:
return None
else:
return messages.Interconnect.LinkTypeValueValuesEnum(link_type_arg)
|
2200b02ec80beba4d5e0c90087487d82d2eb7c9e
| 450,443 |
def ids_to_sentence(ids, id2word):
""" Converts a sequence of ids to a sequence of symbols.
ids: a list, indices for the padded sequence.
id2word: a dict, a mapping from ids to original symbols.
result: a list of symbols.
"""
return [id2word[i] for i in ids]
|
6176bf4f2f9a46458a5b1b247c2e62afb3f1fa7e
| 377,514 |
def get_modified(raw):
"""
Extract last modification date of Libris post.
To be used as 'published' date in reference note
on Wikidata.
@param raw: json object of a Libris edition
@type raw: dictionary
"""
return raw["modified"]
|
10df4f9b81dc0c99f2181e6db2662d552ba9c595
| 376,600 |
def _is_hdf(fmt: str) -> bool:
""" Check if format is of HDF type (this includes netcdf variants)
"""
fmt = fmt.lower()
return any(f in fmt for f in ('netcdf', 'hdf'))
|
1c7f661970330ef3fb7e9070bf1a0abc5e9d1213
| 182,409 |
def sort_terms(terms):
"""
Returns a list of two sympy expressions where the expression is
positive and the second expression is negative.
Parameters
----------
terms : list of sympy expressions
A list with length of 2 where one element is positive and
the other is negative (starts with a minus symbol)
Returns
-------
tuple of sympy expressions
A tuple where the first element is positive and the
second is negative.
"""
neg = None
pos = None
for term in terms:
if str(term)[0] == '-': # negative terms should start with a '-'
neg = term
else:
pos = term
assert neg, 'No negative terms ' + str(terms)
assert pos, 'No positive terms ' + str(terms)
return pos, neg
|
c5ff1d091c6c76edc8a90a3fd0583cc5173016bf
| 296,019 |
import requests
def get_bytes_from_url(url): # pragma: no cover
"""
Reads bytes from url.
Args:
url: the URL
Returns:
the bytes
"""
req = requests.get(url)
return req.content
|
bf00ec24300167cea4f75df809d65f1991af4ea8
| 32,247 |
def transform_fn(transforms, params, invert=False):
"""
(EXPERIMENTAL INTERFACE) Callable that applies a transformation from the `transforms`
dict to values in the `params` dict and returns the transformed values keyed on
the same names.
:param transforms: Dictionary of transforms keyed by names. Names in
`transforms` and `params` should align.
:param params: Dictionary of arrays keyed by names.
:param invert: Whether to apply the inverse of the transforms.
:return: `dict` of transformed params.
"""
if invert:
transforms = {k: v.inv for k, v in transforms.items()}
return {k: transforms[k](v) if k in transforms else v for k, v in params.items()}
|
b7fdad98037bddc1de8243750d9352fe74f251d1
| 439,641 |
def evaluate_postfix(expression):
"""
Evaluates a postfix expression using a shift/stack
"""
def plus(x, y):
return x+y
def minus(x, y):
return x - y
def multiply(x, y):
return x*y
def div(x, y):
return x / y
operators = {'+': plus,
'/': div,
'-': minus,
'*': multiply}
stack = list()
for char_ in expression:
if char_ not in operators:
stack.append(int(char_))
else:
left = stack.pop()
right = stack.pop()
res = operators[char_](left, right)
stack.append(res)
return stack[0]
|
8f0505218f9ea97489918ffa9a4320b33e06336d
| 278,862 |
from typing import Any
def original_case(value: str, **kwargs: Any) -> str:
"""Return the input string without any modifications."""
return value
|
d56303b5774414da63f55cf38f174b7e78f932e3
| 207,623 |
def _is_special_name(name):
"""Determine whether or not *name* is a "__special__" name.
:param str name: a name defined in a class ``__dict__``
:return: ``True`` if *name* is a "__special__" name, else ``False``
:rtype: bool
"""
return name.startswith("__") and name.endswith("__")
|
e4b4ce58e7df5b89677a1f45b9bc921d51116e78
| 527,081 |
def mk_outro(background='black'):
"""Generate the finishing code for a PyMol script."""
return """
# Viewing options
bg_color black
reset
"""
|
f17af141fb390e3c4a60c1f29f8c361b05910af2
| 385,191 |
def to_query(cols, vals):
"""Returns a query from a list of columns and values"""
vals = ["'"+val+"'" if isinstance(val,str) else val for val in vals]
query = ['{} == {}'.format(cols[i],vals[i]) for i,_ in enumerate(cols)]
query = ' and '.join(query)
return query
|
850235bff3ddd0bc188e087e398b4f12f14febd9
| 138,129 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.