content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import Sequence
def wordpiece_tokens_to_normalized_text(wordpiece_tokens: Sequence[str]) -> str:
"""Concatenates wordpiece tokens to a normalized text and cleans up.
The wordpiece tokens are results from BERT tokenization. They may contain
symbols of '##' or ' ##' and some extra whitespaces. The fu... | f8dcdbb1c62b705495bd1c1cc7d35a928ebafa2c | 671,088 |
def get_string_by_card(all_strings, card=None, string_number=None):
"""Reduce the boundary_strings dataframe to a single card type or
a single string number
Args:
all_strings: dataframe
AdhSimulation.BoundaryCondition.boundary_strings dataframe
card: string
String ca... | d81144c39e3940763ac3ba6cf708f40982a5242f | 671,093 |
def which_percentile(value, d):
"""
Returns the percentile of 'value' in 'd's distribution.
:param value: The value whose percentile is required
:param d: A pandas.Series or Numpy array which represents the distribution
:return: int
"""
if len(d) == 0:
return 0
return sum(d < va... | b521836055ba33175e9950aaf73ccafa79177f9d | 671,094 |
from typing import List
from typing import Dict
from typing import Callable
def solve_volume_based_compartments(
compartments: List[Dict[str, float]], volume_nomo: Callable
) -> List[Dict[str, float]]:
"""Traverse a series of volume-based nomographs from the bottom compartment (retention)
to the top compa... | 6e20b552ab7dae1654e572230613c64f53c86bd4 | 671,097 |
import re
def build_key_pattern(genus):
"""Build a regex pattern for the genus key
Parameters:
genus - the genus of the file (a string)
The pattern has one subgroup: the genus and species name
"""
# --- Species name from index line ---
#
# Relies on the assumption that index lin... | c87787dbf2b25ba33c3b5da5b97860d6fd1271ae | 671,104 |
def first(t):
"""Return first item in array or None."""
return t[0] if t else None | b49b710920dcdf59f7ade26639048cb6a96fb6dc | 671,107 |
import torch
from typing import Optional
def torch_huber(
y_true: torch.Tensor,
y_pred: torch.Tensor,
sample_weight: Optional[torch.Tensor] = None,
a: float = 0.9,
):
"""Computes Mean Huber Error.
Args:
y_true: true target values.
y_pred: predicted target values.
sampl... | a8251b9ba8f32fe684fbe641eb9333f6d5bc85c6 | 671,108 |
def date_to_json(value, obj):
"""Serialize a Date value."""
if value is None:
return value
else:
return value.strftime('%Y-%m-%dT%H:%M:%S.%f') | c4426e17c7e08e6e357c8930f3f8ce7a0244f12f | 671,109 |
def _html_template(site_name, author, js_snippet, css_snippet):
"""Create a HTML Template given a site name,
author, snippet to include JS files and CSS files
"""
template_data = {
'site_name': site_name,
'author': author,
'js': js_snippet,
'css': css_snippet
}
wi... | 16726c344a441c43e097fbb0f5445f08fb767ecb | 671,117 |
def import_default(module_name, force=False, default=None):
"""
Provide an implementation for a class or function when it can't be imported
or when force is True.
This is used to replicate Pandas APIs that are missing or insufficient
(thus the force option) in early pandas versions.
"""
i... | ffaba80de90bdacb81422070e5edad22443a305d | 671,118 |
import math
def calc_distance_2points(p1: tuple, p2: tuple):
"""
uses the hypothenus method to calculate the straight line distance between two given points on a 2d cartesian plane.
:param p1: point 1
:param p2: point 2
:return:
"""
return math.hypot(p2[0] - p1[0], p2[1] - p1[1]) | c8962fce968d533044a677f169aa7d17a0091599 | 671,122 |
import time
def format_timestamp(secs):
"""Format a UNIX timestamp using ISO 8601 format.
Args:
secs: the number of seconds since the Epoch to convert into a timestamp
Returns:
an ISO 8601 compliant timestamp of the form "yyyy-mm-ddThh:mm:ssZ"
"""
return time.strftime("%Y-%m-%dT%H... | 8f5b90f6ecd34b43ae78905cd3e8e2e88ffe46e6 | 671,123 |
import re
def parse_table(table_lines):
"""Parse lines into a table.
Table example:
```txt
ID# Name Designation IAU/aliases/other
------- ---------------------------------- ----------- -------------------
0 Solar System Barycenter ... | 7bb45501cd13ff19105d700cb90c29ee5c136cbc | 671,124 |
def getBucketName(year, month, day, radar):
""" Get the name of a specific bucket where radar data is stored.
Args:
year: Year as an integer.
month: Month as an integer.
day: Day as an integer.
radar: The 4 letter name of the radar, a string.
Returns:
The bucket nam... | ba92936b7a4bf0df57d46a64b440701d6705035d | 671,125 |
import math
def __get_pooled_standard_deviation(s1: float, s2: float,
n1: int, n2: int) -> float:
"""Calcultes pooled standard deviation
Args:
s1 (float): standard deviation of sample 1
s2 (float): standard deviation of sample 2
n1 (int): no observa... | 6df03f669fbf41869b70d3dd085a26be4599f9af | 671,128 |
import ast
def status_from_analysis(line):
"""
Utility method to obtain the process status boolean flags from the relative line in the final analysis output
text file.
:param line: string from log file
:return: list of boolean status flags
"""
line = line.strip().split('\t')
return [a... | 7983bd8d9e74a457a019b912cdaa0a1b31272bd9 | 671,130 |
from pathlib import Path
import glob
import torch
def read_expert_trajectories(folder_path):
"""
reads expert features found in folder_path.
:return: torch tensor of all features of all expert trajectories.
:rtype: torch float tensor, shape of (num of total features x feature length)
"""
fea... | 1c8130671c10156c909ff528693d9984004a1538 | 671,131 |
def add_parser_arguments(parser):
"""Add arguments to an `argparse.ArgumentParser`."""
parser.add_argument(
'--data',
type=str,
help='path to AnnData object with "spliced", "unspliced", "ambiguous" in `.layers`',
)
parser.add_argument(
'--out_path',
type=str,
... | a26d5d918bb29c8f5bea8f312266d440ce07d4fd | 671,132 |
def manage_addBooleanIndex(self, id, extra=None,
REQUEST=None, RESPONSE=None, URL3=None):
"""Add a boolean index"""
return self.manage_addIndex(
id, 'BooleanIndex', extra=extra,
REQUEST=REQUEST, RESPONSE=RESPONSE, URL1=URL3) | e8a43ee859466bf1d8362ffad242eeeee954c199 | 671,133 |
def combineLabels(timexLabels, eventLabels, OLabels=[]):
"""
combineTimexEventLabels():
merge event and timex labels into one list, adding instance ids
@param timexLabels: list of timex labels for entities.
@param eventLabels: list of event labels for entities. Includes no instances labeled as ... | fcc3421c3f38787a5ee9e262b5a1056df0f95ad2 | 671,137 |
def is_image(tensor):
"""
Check if a tensor has the shape of
a valid image for tensorboard logging.
Valid image: RGB, RGBD, GrayScale
:param tensor: (np.ndarray or tf.placeholder)
:return: (bool)
"""
return len(tensor.shape) == 3 and tensor.shape[-1] in [1, 3, 4] | 738053703853410873befd7ece0154572ad926fd | 671,138 |
def slice_parents(parent1, parent2):
"""
Crossover method 1:
====================
Slices the seeds of both parents in the middle and combines them.
Retruns the combines new seeds.
"""
length = len(parent1) // 2
child_seeds = parent1[:length] + parent2[length:]
return child_seeds | d77fb0cd62a95d8601ec414b4d56fb2eeb5e1fbd | 671,139 |
def file_to_ids(file_path):
"""Read one line per file and assign it an ID.
Args:
file_path: str, path of file to read
Returns: dict, mapping str to ID (int)
"""
str2id = dict()
with open(file_path) as file:
for i, line in enumerate(file):
str2id[line.strip()] = i
... | 970085bae7df57dcde8c1ede5a14070f12aa2c55 | 671,141 |
from typing import Union
def is_close(
actual: Union[int, float], expected: Union[int, float], threshold: Union[int, float]
) -> bool:
"""Compare the difference between two input numbers with specified threshold."""
return abs(round(actual, 2) - round(expected, 2)) <= threshold | f2edf48d6475429b230fd751a3ef899461c84e1f | 671,142 |
def replace_consts_with_values(s, c):
"""
Replace the constants in a given string s with the values in a list c.
:param s: A given phenotype string.
:param c: A list of values which will replace the constants in the
phenotype string.
:return: The phenotype string with the constants replaced... | c04b44e338288709130ad930b833d6de4f3fece2 | 671,143 |
import random
def calculate_countdown__random(count: int, index: int, duration: int) -> int:
"""
把周期任务通过随机数的方式平均分布到 duration 秒 内执行,用于削峰
:param count: 任务总数
:param index: 当前任务索引
:param duration: 执行周期
:return: 执行倒计时(s)
"""
return random.randint(0, max(duration - 1, 1)) | 1c7854f6013d85c97d16f0b21bc851232faf6a8d | 671,146 |
def _retrieve_door_state(data, lock):
"""Get the latest state of the DoorSense sensor."""
return data.get_door_state(lock.device_id) | 99bd72bca095b8a375fd02e41310bd93963f8205 | 671,147 |
def read_file(filename):
"""Reads a file.
"""
try:
with open(filename, 'r') as f:
data = f.read()
except IOError as e:
return (False, u'I/O error "{}" while opening or reading {}'.format(e.strerror, filename))
except:
return (False, u'Unknown error opening or re... | 15df20899ad9c879fa8f8b7059fe70fa30bfb371 | 671,148 |
from typing import Dict
from typing import Any
import yaml
from pathlib import Path
def read_yaml_file(filename: str) -> Dict[str, Any]:
"""Reads a YAML file, safe loads, and returns the dictionary"""
cfg: Dict[str, Any] = yaml.safe_load(Path(filename).read_text())
return cfg | b8908e0069530ccd9f358841e5a9309c3d5b4e13 | 671,150 |
import torch
def mask_center(x: torch.Tensor, mask_from: int, mask_to: int) -> torch.Tensor:
"""
Initializes a mask with the center filled in.
Args:
mask_from: Part of center to start filling.
mask_to: Part of center to end filling.
Returns:
A mask with the center filled.
... | 5a6da46b0c50719abddd2de7d4e7882bca419b27 | 671,151 |
def map_to_lie_algebra(v):
"""Map a point in R^N to the tangent space at the identity, i.e.
to the Lie Algebra
Arg:
v = vector in R^N, (..., 3) in our case
Return:
R = v converted to Lie Algebra element, (3,3) in our case"""
# make sure this is a sample from R^3
assert v.size()[... | da0b9638b1eb1f6d0fbbeccdb7fdd6d68c80ffcd | 671,157 |
def quadratic_item_score(i):
"""Function is similar to inverted and linear functions but weights are decreasing at non-linear rate
and accelerate with the item position.
Parameters
----------
i : int
Item position.
Returns
-------
result : float
Inverted square ... | 462e8dc355b13da52ec959e983d03f04c34dffae | 671,158 |
def shrink_to_fit(column_sizes, terminal_width):
"""
If the total size of all columns exceeds the terminal width, then we need to shrink the
individual column sizes to fit. In most tables, there are one or two columns that are much
longer than the other columns. We therefore tailor the shrinking algorit... | 04f3d999a54736b81179fd8cfc36013ad30863f1 | 671,162 |
def swap(record):
""" Swap (token, (ID, URL)) to ((ID, URL), token)
Args:
record: a pair, (token, (ID, URL))
Returns:
pair: ((ID, URL), token)
"""
token = record[0]
keys = record[1]
return (keys,token) | 21d9dc45c44cc24e0c12ff85b0513321f58af558 | 671,164 |
def normalizeLanguage(lang):
"""
Normalizes a language-dialect string in to a standard form we can deal with.
Converts any dash to underline, and makes sure that language is lowercase and dialect is upercase.
"""
lang=lang.replace('-','_')
ld=lang.split('_')
ld[0]=ld[0].lower()
#Filter out meta languages suc... | 96890ea57435b3b3523f313af531691478bd75d2 | 671,165 |
def least_squares_gradient(y, tx, w):
"""
Compute the gradient of the mean square error with respect to w, and the current error vector e.
Takes as input the targeted y, the sample matrix w and the feature vector w.
This function is used when solving gradient based method, such that least_squares_GD() ... | ba6e4846367c0b67a31efac1ed68d161ca3a7b2a | 671,166 |
def find_ngrams(seq, n):
"""
Computes the ngrams for a sequence.
:type seq: a list of of strings
:param seq: a sequence
:return a list where ngrams are stored
"""
return zip(*[seq[i:] for i in range(n)]) | 2a8e138529eecb9dfdf3923abfe94adc284a8657 | 671,170 |
import re
def split_parts(sep, output):
"""Split the output string according to the regexp sep."""
regexp = re.compile(sep)
lines = output.split('\n')
idx = []
num = 0
for line in lines:
if regexp.search(line):
idx.append(num)
num = num + 1
arr = []
start = ... | 350d0c052e4f9eac171659155eb554940d3498fa | 671,175 |
def _multi_bleu(hypothesis, reference_set, aligner):
"""
Compute a list of scores with the aligner.
:param hypothesis: a single hypothesis.
:param reference_set: a reference set.
:param aligner: a callable to compute the semantic similarity of a hypothesis
and a list of references.
:return:... | 0731edfb542883581e499283587a5a602b025efd | 671,178 |
def is_number(s):
"""
Check if a string is a number
"""
try:
float(s)
return True
except ValueError:
return False | c9f5bc5010b4fb7ad6a293d3788ab4955dd1595d | 671,180 |
def execute(instructions):
"""
Execute instructions, return a tuple of accumulator and exit reason.
"""
index = 0
accumulator = 0
list_of_pc = set()
while True:
if index in list_of_pc:
return (accumulator, "cycle")
if index == len(instructions):
return... | 1576ba348f2d6381357f6f45ceec20740269d9ce | 671,184 |
import torch
def subsequent_chunk_mask(
size: int,
chunk_size: int,
num_left_chunks: int = -1,
device: torch.device = torch.device("cpu"),
) -> torch.Tensor:
"""Create mask for subsequent steps (size, size) with chunk size,
this is for streaming encoder
Args:
siz... | e06afa21778e92725e07445048ab60a2cfa24af0 | 671,190 |
from typing import Dict
def check_label_match(frame_labels: Dict, labelset: Dict) -> bool:
"""
Check that the labels of the frame matches the labels of the rules.
:frame_labels (Dict) The labels of the frame.
:labelset (Dict) The labels of the ruleset.
Return a boolean describing the status of t... | e5a22da70a89cf8201a8597cdefc71eac516107b | 671,193 |
def _handle_ai_platform_response(uri, response):
"""Handle response to AI platform from both get/post calls.
Args:
uri: Request uri.
response: Response from the request.
Returns:
Request results in json format.
Raises:
ValueError: When the request fails, the ValueError will be raised with
... | aafa4e2ee87be607595da825ca9ac57c707477ac | 671,194 |
def filter_abst(abst, slots_to_abstract):
"""Filter abstraction instruction to only contain slots that are actually to be abstracted."""
return [a for a in abst if a.slot in slots_to_abstract] | 698bb9b115810c34f77c7c9edd967f7b6a6f888a | 671,197 |
def lower_case_underscore_to_camel_case(text):
"""
Converts string or unicdoe from lower case underscore to camel case
:param text: str, string to convert
:return: str
"""
# NOTE: We use string's class to work on the string to keep its type
split_string = text.split('_')
class_ = text._... | 2c298593b32a59865c254c78b8099d17bd0cc5fd | 671,202 |
from typing import Any
def fqualname_of(obj: Any) -> str:
"""Gets the fully-qualified name for the given object."""
return "{}.{}".format(obj.__class__.__module__, obj.__class__.__qualname__) | 19f3e226846d3771ae8f4c15034d354aec7ba49f | 671,203 |
import re
def shell_escape_filename(filename):
""" Escape filename for use as shell argument. """
return re.sub(r'(\s|[\\\'"|()<>{}$&#?*`!;])', r'\\\1', filename) | 4fb5d85956f4d4031d6069d67b8444b79a3cbab9 | 671,211 |
import torch
def to_device(obj, device):
"""
Move a tensor, tuple, list, or dict onto device.
"""
if torch.is_tensor(obj):
return obj.to(device)
if isinstance(obj, tuple):
return tuple(to_device(t, device) for t in obj)
if isinstance(obj, list):
return [to_device(t, dev... | 346c2315e8e2d71ecf274629cea3f21b76e2c4d4 | 671,216 |
from typing import List
def are_supports_coordinated(orders: List[str]) -> bool:
"""Return False if any supports or convoys are not properly coordinated
e.g. if "F BLA S A SEV - RUM", return False if "A SEV" is not ordered "A SEV - RUM"
0 1 2 3 4 5 6
"""
required = {}
ordered = ... | dc480381e31044b9a8733bac5db65637524eb552 | 671,217 |
def _e_f(rho, rhou, e, p):
"""Computes the flux of the energy equation."""
return (e + p) * rhou / rho | 5eeb0b37834dbd4a49f8b8b281d63ac4c414324e | 671,218 |
def _extract_doc_comment_simple(content, line, column, markers):
"""
Extract a documentation that starts at given beginning with simple layout.
The property of the simple layout is that there's no each-line marker. This
applies e.g. for python docstrings.
:param content: Presplitted lines of the s... | ad9cb3f201072cf4d5e922f4e4bc4ed15ae2a864 | 671,227 |
from datetime import datetime
def DatetimeFromString(date):
"""Parses a datetime from a serialized string."""
if date == 'None':
return None
if not date or isinstance(date, datetime):
return date
# Strip bad characters.
date = date.strip('\t\n ')
valid_formats = [
'%Y-%m-%d %H:%M:%S.%f %Z',... | 622da29fbe312ef7063b560c15efc8b2dc740639 | 671,229 |
def anyone_certified(task, **kwargs):
"""
Default assignment policy, we leave the task
in the awaiting processing pool.
"""
return task | ac8d7a74c1cd2bd3dade79ef6b9f58f9e12a8b3a | 671,231 |
def rfnnodes(rf):
"""Return the total number of decision and leaf nodes in all trees of the forest."""
return sum(t.tree_.node_count for t in rf.estimators_) | f392e7d0985fa78a6123da3d4624a6b152e059a5 | 671,234 |
def sum_of_squares(limit):
""" Returns the sum of all squares in the range 1 up to and including limit. """
return sum([i ** 2 for i in range(limit+1)]) | df2c6ebf029b54d810e730cd5790128a37786952 | 671,236 |
def fact(n):
"""
factorial of n
:param n: int
:return: int
"""
if type(n) != int:
n = int(n)
if n == 1:
return 1
else:
acc = 1
for x in range(1,n+1):
acc = acc * x
return int(acc) | ebad82edfe209501081a7739e812a6a21e81901b | 671,239 |
def exponential_decay(lr0, s):
"""
Create exponential decay: reduce learning rate by s every specified iteration.
Parameters
----------
lr0 : float
initial learning rate
s: float
decay rate, e.g. 0.9 (mostly higher than in other methods)
Returns
-------
exponential_... | 715422d1a3af457ce601cd3727dda543de612369 | 671,245 |
def is_kwarg(argument: str) -> bool:
"""`True` if argument name is `**kwargs`"""
return "**" in argument | 016c5c0def8f78e8ef10b68f425d55aab880d4ee | 671,250 |
def isabs(s):
"""Test whether a path is absolute"""
return s.startswith('/') | 41d69b168a47829f8fd4b213624fca7f8682b022 | 671,252 |
def list_extremum(data: list, type=0) -> tuple:
"""
找到list中的极值,并返回索引,若极值有多个,则返回多个索引
Args:
data: list数据
type: 1表示执行最大值操作,0表示最小值操作
Returns:
极值,索引的列表
"""
if type == 1:
# 极大值
ex = max(data)
elif type == 0:
# 极小值
ex = min(data)
else:
... | adf513af5221491b51ae7a105f5feaa96617126a | 671,255 |
def filter_data(df, condition):
"""
Filter data by keeping only the values that satisfy
the conditions given
Parameters
- df: (pandas dataframe) dataframe
- conditions: (string) string that contains conditions to
be used to filter dataframe.
Ex: if the user... | 4a22f5baabfa316904b76269fcbdcb8a2e6e0b8e | 671,258 |
def _render(env, template_str, data):
"""Uses the environment to render the provided template string using the provided data"""
template = env.from_string(template_str)
return template.render(data) | 49cd566a45c3fa61bc6774ba527efdf350da9258 | 671,259 |
def ExtractDependencies(input):
""" Create a list of dependencies from input list of lines
Each element contains the name of the object and a list of
files that it depends on.
Dependencies that contain "/usr/" are removed as they are system headers. """
deps = []
for line in input:
headersLine = line.startswit... | 8c0f87af50342221c1c73356e9c3ffdefb690e03 | 671,262 |
def format_sbatch_options(**sbatch_options):
"""Format sbatch options"""
options = []
for k, v in sbatch_options.items():
val = ""
if v is not None:
val = f"={v}"
options.append(f"--{k}{val}")
return options | ac2db5d485a4cad15260b29cff9eda1fa4d0a647 | 671,267 |
def bytes2NativeString(x, encoding='utf-8'):
"""
Convert C{bytes} to a native C{str}.
On Python 3 and higher, str and bytes
are not equivalent. In this case, decode
the bytes, and return a native string.
On Python 2 and lower, str and bytes
are equivalent. In this case, just
just ret... | 158b56d0aef3c71921e1106ed74d1bfde33c79c3 | 671,269 |
import requests
def exec_request(url, timeout):
"""Executes request given in url and returns a dictionary with content"""
data = requests.get(url, timeout=timeout)
data.raise_for_status() # Raise in case of failed status
return data.json() | 63522420fe36e0e38c41c42b43a65208354bee1e | 671,270 |
def is_tachycardic(hr, age):
"""Evaluates if posted heart rate is tachycardic
Method curated by Braden Garrison
Tachycardia is defined as a heart rate that is above normal resting
rate. Specific tachycardic values are dependent upon patient age. More
info about tachycardia and its diagnosis can be... | 3acde139d26ac6a1f59fc59e3abc9f82de51accd | 671,272 |
def Compare(token1, token2):
"""Compares two tokens and determines their relative order.
Args:
token1: The first token to compare.
token2: The second token to compare.
Returns:
A negative integer, zero, or a positive integer as the first token is
before, equal, or after the second ... | fee9db18382d62faf0748cecfe1fad1f8124caee | 671,276 |
def _get_inner_type(typestr):
""" Given a str like 'org.apache...ReversedType(LongType)',
return just 'LongType' """
first_paren = typestr.find('(')
return typestr[first_paren + 1:-1] | abe352046f82f9b78f625a34791878276e28fb03 | 671,277 |
def set_fba_name(source, year):
"""
Generate name of FBA used when saving parquet
:param source: str, source
:param year: str, year
:return: str, name of parquet
"""
return source if year is None else f'{source}_{year}' | a7c5c484de1badad53c7cdb5ba6afb9bb81ec524 | 671,281 |
def aramaic_turoyo_input_normal(field, text):
"""
Prepare a string from one of the query fields for subsequent
processing: replace common shortcuts with valid characters
of Turoyo (Neo-Aramaic).
"""
if field not in ('wf', 'lex', 'root'):
return text
text = text.replace('\'', 'ʕ')
... | 6e89e73697510adae0213d1052cfe9844fe87a4c | 671,283 |
def Dictionary_to_XmlTupleString(python_dictionary):
"""transforms a python dictionary into a xml line in the form
<Tuple key1="value1" key2="value2"..keyN="valueN" />"""
prefix="<Tuple "
postfix=" />"
inner=""
xml_out=""
for key,value in python_dictionary.items():
inner=inner+'{0}="... | fe6a52b10dccc4e836bb12ec1c5b26017d075dcf | 671,285 |
def remove_fields_duplicated(bids_fields):
"""Remove duplicated fields in a list.
Args:
bids_fields: List of fields
Returns: list
"""
seen = set()
seen_add = seen.add
return [x for x in bids_fields if not (x in seen or seen_add(x))] | ad2571310762370805fe5ee42840a0f685ae7f14 | 671,286 |
def get_image_modality(image_modality):
"""Change image_modality (string) to rgb (bool), flow (bool) and audio (bool) for efficiency"""
if image_modality.lower() == "all":
rgb = flow = audio = True
elif image_modality.lower() == "joint":
rgb = flow = True
audio = False
elif imag... | 4c8485c67c2c568c473c6bfbf36b9d732a2fdbd2 | 671,287 |
def get_scan_resource_label(system_type: str) -> str:
"""
Given a system type, returns the label to use in scan output
"""
resource_label_map = {
"redshift_cluster": "Redshift Cluster",
"rds_instance": "RDS Instance",
"rds_cluster": "RDS Cluster",
}
resource_label = resou... | 8bb47f7b90d653f726a0e410786fa2d5876accbf | 671,293 |
def replaceValue(mapping, old, new, strategy=None):
"""
Replace old values with new ones following dict strategy.
The parameter strategy is None per default for inplace operation.
A copy operation is injected via strateg values like copy.copy
or copy.deepcopy
Note: A dict is returned regardles... | 750067aa862b5c0da0e121240a548d3c3b3b14ed | 671,297 |
def isIn( obj, container ):
"""
Returns a boolean whether or not 'obj' is present in 'container'.
"""
return obj in container | e0da69589466c30b6fc9865352fdd87c2733ea67 | 671,302 |
import hashlib
def wep_make_gravatar_img(email: str) -> str:
"""
Returns a string pointing to a Gravatar image based on an email address.
Args:
email: the email associated with a given Gravatar image
Returns:
a link of the form <https://www.gravatar.com/avatar/:hash>, where
`... | 8a2fb564850351ecbf6a47c81293bcc5181d7731 | 671,308 |
def total_travel_distance(journey):
"""
Return the total travel distance of your PyCon journey in kilometers
rounded to one decimal.
"""
return round(sum(trip.distance for trip in journey),1)
pass | add1401e8b718054570a410d3874a08abe7e3b4b | 671,313 |
def selection_sort(L):
"""
Implementation of a selection sort algorithm
Complexity: O(n^2)
:param L: List-object
"""
index = 0
while index != len(L):
for i in range(index, len(L)):
if L[i] < L[index]:
L[index], L[i] = L[i], L[index]
index += 1
... | 3cddaf75ccef2dd70e0005494d360d7679a7ce44 | 671,317 |
def _get_opt_provider(target, provider):
"""Returns the given provider on target, if present."""
return target[provider] if provider in target else None | e310f22e5e73ec80640ff0b61e5dcbe55278d2ab | 671,318 |
def luminance_newhall1943(V, **kwargs):
"""
Returns the *luminance* :math:`R_Y` of given *Munsell* value :math:`V`
using *Sidney M. Newhall, Dorothy Nickerson, and Deane B. Judd (1943)*
method.
Parameters
----------
V : numeric
*Munsell* value :math:`V`.
\*\*kwargs : \*\*, optio... | 3806a6957aaca700f3f3477eaa33746b37c33249 | 671,322 |
import collections
import json
def load_queries(path: str):
"""
Loads queries into a dictionary of query_id -> (query, question)
"""
queries = collections.OrderedDict()
with open(path) as f:
raw_json = f.read()
parsed_json = json.loads(raw_json)
for topic in parsed_json:
... | da76fe53f1f55d38ed09ad608b50f2183d5322c3 | 671,325 |
def mel_sampling(
audio, frame_duration_ms = 1200, overlap_ms = 200, sample_rate = 16000
):
"""
Generates audio frames from audio. This is for melspectrogram generative model.
Takes the desired frame duration in milliseconds, the audio, and the sample rate.
Parameters
----------
audio: np.a... | 72cb22ba976d6f91a9b69953d8bedcd33c4ab294 | 671,329 |
def examine_neighbors(g, x, y):
"""
Examine the 8 neighbors of the cell at coordinates "x" by "y", and return
the number of neighbor cells which are closed.
"""
c = 0
w, h = g.size()
if x - 1 >= 0:
if g.get(x - 1, y):
c += 1
if x + 1 < w:
if g.get(x + 1, y):... | 1ec8701aef08d8bf0af4f432028ba857aaff7a7c | 671,330 |
def determine_nonschema_privileges_for_schema(role, objkind, schema, dbcontext):
"""
Determine all non-schema privileges granted to a given role for all objects of objkind in
the specified schema. Results will be returned as two sets: objects granted write access
and objects granted read access.
We... | aa7a0583dbf135b45448ffb663c548a40e47e934 | 671,337 |
def number_freq_plots(runs, map_label):
"""Calculate the number of plots needed for allfreq plots and frequency
histogram plots
"""
num_cpu_plots = len(map_label)
has_devfreq_data = False
for run in runs:
if len(run.devfreq_in_power.data_frame) > 0:
has_devfreq_data = True
... | 0e7253fb20fcb790019b3e409222f5d26126ae48 | 671,339 |
def get_region(context):
"""
Return the AWS account region for the executing lambda function.
Args:
context: AWS lambda Context Object http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html
Returns:
str : AWS Account Region
"""
return str(context.invoked_functi... | 220a63aef52d97ec8bd5bc6803b7a33803cdaf2f | 671,349 |
def find_min_pos(input_list):
"""Function to find index with minimum value."""
length = len(input_list)
if length == 0:
return -1
curr_min = input_list[0]
curr_min_index = 0
for j in range(1, length):
if curr_min > input_list[j]:
curr_min = input_list[j]
curr_min_index = j
return cu... | d2d72b0fdf6ada026f7675f37ff7223384ec076f | 671,353 |
import requests
import time
def get_limited(url, params = None, auth = None):
""" Get a GitHub API response, keeping in mind that we may
be rate-limited by the abuse system """
number_of_retries = 0
resp = requests.get(url, params = params, auth=auth)
while resp.status_code == 403 and number_o... | 93674a23a108c129f692a5f83177d6f3962614d5 | 671,355 |
import collections
def index_rules_by_namespace(rules):
"""
compute the rules that fit into each namespace found within the given rules.
for example, given:
- c2/shell :: create reverse shell
- c2/file-transfer :: download and write a file
return the index:
c2/shell: [create reve... | f812e632ad35996f0245187c988d4f1ae18c42fb | 671,356 |
def which_argument(arguments, options):
"""Return which of the given constant options was specified in the given
argument source parsed by docopt."""
for check in options:
if arguments[check]:
return check | 7e0e9983bd5c510a0cb1d01f3e9a31b32a01b7f3 | 671,357 |
def each_n(iterable, n):
"""Iterate iterable with n-tuples."""
a = iter(iterable)
return zip(*[a] * n) | 620e0656d4b00bb32cc981f2ef1de96dd8cf7059 | 671,358 |
import copy
def _format_label(label_txt, values, date, date_format=None):
"""
Replaces '{date}' and other placeholders in label_txt by formatting with
date string and values given by -v key=value
"""
values = copy.deepcopy(values)
if 'date' not in values:
values['date'] = date.strftim... | 75ce6bfe453e59b831d6ab18b927926ec6ece0ab | 671,359 |
def construct_constraint(year, index):
"""
This function is a convenience function that returns a valid demand constraint for one year.
The wrapper function construct_constraint is needed because we need a reference to year in the wrapped
meet_demand function in model.buy[year, supplier, block] and mode... | 77dbbf75f23bbc2494fdb0a0b465c77fe2cd86de | 671,360 |
def parse(file_name):
"""Parse the data file into a list of int"""
with open(file_name, "r") as f:
return [int(x) for x in f.readline().split(",")] | c8781f2a75f7d1913f2cbe29a66ef4af3df1ce76 | 671,362 |
from typing import Optional
def PathFromLabel(label: str) -> Optional[str]:
"""Create a workspace relative path from a bazel label.
Args:
A bazel label, e.g. "//foo:bar.cc".
Returns:
A workspace-relative path, e.g. "foo/bar.cc". If the label does not resolve
to a path, returns None.
"""
# First, ... | 679c65b7bbd46ed92094339ce57555f346d3a3a8 | 671,363 |
import typing
import hashlib
def get_hashed_percentage_for_object_ids(
object_ids: typing.Iterable[int], iterations: int = 1
) -> float:
"""
Given a list of object ids, get a floating point number between 0 and 1 based on
the hash of those ids. This should give the same value every time for any
li... | 910fd689e79392f4bf9a7da1e6025a507a627d0f | 671,365 |
def check_poly_types(df):
"""
Special checks to ensure the Poly_Types field adheres to what we want apart
from domain/schema checks.
Args:
df: Pandas dataframe of feature class table containing the field 'Poly_Type'
Returns:
errors: list of error message strings to print to the c... | 22682646404d350271cffbb50134fb6c63b9dcba | 671,366 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.