content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def gloss(s: str, gloss_file: str) -> str:
"""Restores characters in s from gloss_file."""
gloss_list = list(gloss_file)
g = gloss_list.pop(0)
def degloss_repl(matchobj):
return gloss_list.pop(0)
o = re.sub(g, repl=degloss_repl, string=s)
return o | 83084835fc5b9f5e6b2af28e72e34219490570d4 | 589,351 |
from functools import reduce
import itertools
def day01(input_data, n_for_combination):
"""
From the input list, find the [n_for_combination] entries that sum to 2020
and multiply them together.
Args:
input_data [list] : python list of integers
n_for_combination [int] : length of subs... | 0fef508039751b8cbaee6bc9b806336f23787f33 | 589,352 |
def price_data(sp_available=False, sp_traded=False, ex_best_offers=False, ex_all_offers=False, ex_traded=False):
"""
Create PriceData filter list from all args passed as True.
:param bool sp_available: Amount available for the BSP auction.
:param bool sp_traded: Amount traded in the BSP auction.
:pa... | 1739292341d3b3253744d3a8dc66457a1422f994 | 589,353 |
def _number_neighbours(building_geometry, obstructions_gdf, obstructions_sindex, radius):
"""
The function computes a buildings" number of neighbours.
"radius" research radius for other adjacent buildings.
Parameters
----------
building_geometry: Polygon
obstructions_gdf: Polygon GeoDa... | 6171894c305b84ad3b6a30e5dba1c7dffec9418f | 589,354 |
import hashlib
def sha256(filepath):
"""
Function to calculate sha256 of a file in disk
Params:
- filepath (str): Path where the file is stored
Return:
- sha256 hash calculated
"""
fd = open(filepath, 'rb')
hasher_256 = hashlib.sha256()
chunk = fd.re... | e5b6bec1f63ed748c009ffb1dcd8ec1ff6bf1a44 | 589,359 |
def get_overwrite_no_response_dto(claim: dict, higher_level_node: str, higher_level: int) -> dict:
"""Get the DTO for updating a claim request which has an expired node
Args:
claim: Actual stored claim object to update
higher_level_node: id of the node to replace
higher_level: dragonchai... | 6a52bbab5d7f9d484e6d217146ff3ad6e1fca638 | 589,366 |
import cgi
def check_content_type(content_type, mime_type):
"""Return True if the content type contains the MIME type"""
mt, _ = cgi.parse_header(content_type)
return mime_type == mt | faf22b8c546b6846a690d33fbaa4df5525cfc255 | 589,367 |
def make_url_given_id(expid):
"""
Get url of JSON file for an experiment, give it's ID number
:param expid: int with experiment ID number
"""
return "https://neuroinformatics.nl/HBP/allen-connectivity-viewer/json/streamlines_{}.json.gz".format(expid) | 152d4895595bf86b1fd44fcdc9e3cdc87ee1a2b6 | 589,377 |
def yes_no_formatter(value, **_):
""" Handle True/False from Django model and 1/0 from raw sql """
if value is None:
return ''
if value == 1: # boolean True is equal to 1
return 'Yes'
if value == 0: # boolean False is equal to 0
return 'No'
assert False, "Unable to convert ... | a2a7389f5b541d37bbe8f7d3cf49328181c91b1e | 589,378 |
def word_from_id(integer, tokenizer):
"""Convert integer (value) to corresponding vocabulary word (key) using tokenizer.word_index dictionary"""
for word, index in tokenizer.word_index.items():
if index == integer:
return word
return None | 9d0abab94a585f4f95d15e9d924f9de463392764 | 589,387 |
import re
def clean_period_char(text):
"""Remove all period characters that are not decimal points.
:param text: string text to clean
:type text: str
:return: cleaned string
:rtype: str
"""
period_pattern = re.compile(r'\.(?!\d)')
return re.sub(period_pattern, '', text) | 231c4cdcba5e7f0a85ca7bb0d621044ef1bfa0b4 | 589,391 |
def pluralize(word: str, n: int, plural: str = 's', append: bool = True) -> str:
"""Pluralize a word.
Args:
word (str): The word to pluralize. `str` is called on this.
n (int): The number that decides if the word should be plural
or not. If this number is 1, the word will not be
... | a4a1b315a57f3ae4adfb881edde15507ead1a7c6 | 589,393 |
def count_unique_items(items):
"""
Count the unique items in a list. Similar to calling collections.Counter(items).items(), but it doesn't require
that items be hashable.
:return: A list<(item, item_count)>
"""
unique_items = []
unique_item_counts = []
for item in items:
if item... | 68570dc131ff718e9d2a53255b7b6d1690594c69 | 589,394 |
def exist(ubids, specs):
"""Checks that all ubids are in the specs
Args:
ubids (seq): [ubid1, ubid2, ubid3, ...]
specs (seq): [{spec1}, {spec2}, {spec3}]
Returns:
bool: True or False
"""
return set(ubids).issubset(set(map(lambda x: x['ubid'], specs))) | ac6d77fbf51972fa1a20dbe1c5763db5bce5d8f4 | 589,396 |
import torch
def dt_dqn(s, a, r, ns, d, q_local, q_target, gamma):
"""Calculate temporal-difference delta_t using fixed Q-targets. This works for batches of tuples.
Parameters
----------
s : torch.tensor
Current state (size [n * m], where n is the batch size and m is the number of features in... | 00f56871ef0e6fd6680958b9ac456cf5545fad17 | 589,402 |
def get_available_plugins(plugins):
""" Returns a string containing a list of available plugins in the given PluginCollection"""
av_plugins=''
for plugin in plugins:
av_plugins += plugin.identifier + ', '
return av_plugins[:-2] | bcdbe2cc1941e1d14c4230e740c8e7e88d2f227d | 589,407 |
import struct
def pack_point(x, y, r, g, b, i = -1, u1 = 0, u2 = 0, flags = 0):
"""Pack some color values into a struct dac_point.
Values must be specified for x, y, r, g, and b. If a value is not
passed in for the other fields, i will default to max(r, g, b); the
rest default to zero.
"""
if i < 0:
i = m... | e554da4776c002517956833dd8d8159169f5f59e | 589,408 |
def _compute_nm_conf_filename(mac):
"""
Compute a filename from a mac address
- capitalized it
- replace ':' by '_'
- add .conf at the end
"""
return "%s.conf" % mac.replace(':', '_').upper() | 503ee2b636440cef1108013ea2cde66ee2742bd7 | 589,409 |
def parse_response(resp):
"""Parse requests response.
`resp` will have the following format:
{'base': 'stations',
'clouds': {'all': 20},
'cod': 200,
'coord': {'lat': 46.05, 'lon': 14.51},
'dt': 1495803600,
'id': 3196359,
'main': {'humidity': 37,
... | dfac31dbefac4ba196f6c0bf13192375ab96b599 | 589,412 |
def chunker(seq, size):
"""
Chunk a list into chunks of size `size`.
From
https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks
Parameters
----------
seq: input list
size: size of chunks
Returns
-------
The list of lists of ... | 8f6290ab50d9dfc22e7b5de2c91c44c3ef50a7e0 | 589,413 |
def get_water_resource_flows(fl):
"""
Subsets the flow list for all water resource flows,
excluding resource/air
:param fl: df in standard flowlist format
:return: df in standard flowlist format
"""
flows = fl[fl["Flowable"].str.startswith("Water")]
flows = flows[flows["Context"].str.st... | abee2646feb5b9a70b7145e8e5eac2dcbff1260e | 589,414 |
def is_create_group(string, nickname):
"""
Test if this is a group creation message.
"""
if string == f"{nickname} created the group.":
return True
return False | 40d510df0076e9080507bde6c9b26a1e9698eef0 | 589,415 |
import math
def acosh(x):
"""Get acosh(x)"""
return math.acosh(x) | f2a73af0870e2f1958670663e957b7edc2e23eee | 589,416 |
def parse_games_losses(r):
""" Used to parse the amount of games lost by a team.
"""
return int(r.get("wedVerloren", 0)) | 61f12cf213b40b3035dffa8ee2ef88f8fa99e2c5 | 589,417 |
def _expand_ALL_constant(model, fieldnames):
"""Replaces the constant ``__all__`` with all concrete fields of the model"""
if "__all__" in fieldnames:
concrete_fields = [f.name for f in model._meta.get_fields() if f.concrete]
i = fieldnames.index("__all__")
return fieldnames[:i] + concre... | 435422d6d9a4b7ef4122d6e5cb8d709414c3bd49 | 589,418 |
def get_dof_by_criterion(space, criterion):
""" Return dofs with coordinates satisfying a given condition.
Args:
space: The function space.
criterion: A boolean function which takes a coordinate (numpy array).
Outputs:
dof_no: A list of global indices of dofs where criterion is Tru... | 06d41a73eff3ecdcbc541f7aadba7c3be7b7c628 | 589,422 |
import re
def clean_text(text):
"""Remove new lines and multiple spaces and adjust end of sentence dot."""
text = text.replace("\n", " ")
text = re.sub(r'\s+', ' ', text)
for _ in range(3):
text = text.replace(' . ', '. ')
return text | 83616ce52cd8959b3542dd8df2a07071ca16ac88 | 589,425 |
def p_op(op):
"""
String from operator
:param op: operator
:return: lowercase operator
"""
return str(op).lower() | 38df39037dfea84ca742027e97de4484f6593286 | 589,430 |
def update_parameters(parameters, grads, learning_rate=1.2):
"""
使用梯度更新参数
Args:
parameters: 包含所有参数的python字典
grads: 包含所有参数梯度的python字典
learning_rate: 学习步长
Return:
parameters: 包含更新后参数的python
"""
# 从"parameters"中读取全部参数
W1 = parameters["W1"]
b1 = parameters["b... | 8242ab46833f2f75d8f3b33d72c7899fe11127eb | 589,431 |
import six
def call_module(module, one_hots, row_lengths, signature):
"""Call a tf_hub.Module using the standard blundell signature.
This expects that `module` has a signature named `signature` which conforms to
('sequence',
'sequence_length') -> output
To use an existing SavedModel
file you ma... | efd8a7b991c2f8c95abbed55566d882a4af750c2 | 589,442 |
def find(search_list, value):
"""
Find the value in the search list, return its index
"""
def search(left, right):
if left > right:
raise ValueError("value not in array")
if left == right:
if search_list[left] != value:
raise ValueError("value ... | 378c6a942870c57b013c1787eae429b1d606747f | 589,444 |
def parse_multi_keys(item: str, sep: None | str = None) -> str:
"""Parse keys that contain one or more spaces (see **sep**).
The first word in the to-be returned key is decapitalized.
Examples
--------
.. code:: python
>>> out = parse_multi_keys('A B')
>>> print(repr(out))
... | 71b797c95f4d1feccb860df4a023c54d7aa91f57 | 589,446 |
def _devicePixelRatioF(obj):
"""
Return obj.devicePixelRatioF() with graceful fallback for older Qt.
This can be replaced by the direct call when we require Qt>=5.6.
"""
try:
# Not available on Qt<5.6
return obj.devicePixelRatioF() or 1
except AttributeError:
pass
tr... | 155e498b4be19d572c213f01782156e68c2a60c5 | 589,448 |
import io
import json
def util_load_json(path: str) -> dict:
"""Load json file to dict object
Args:
path (str): The path of the file
Returns:
dict: The JSON data from the file
"""
with io.open(path, mode='r', encoding='utf-8') as file:
return json.loads(file.read()) | 695dac45575d5d3a4efb93fa42ba56c643e70bbd | 589,449 |
def quote_and_escape(value):
"""Quote and escape a string.
Adds enclosing single quotes to the string passed, and escapes single
quotes within the string using backslashes. This is useful for passing
'extra vars' to Ansible. Without this, Ansible only uses the part of the
string up to the first whi... | 951e580f06859ebdb405f6ae327737a2eacf5a69 | 589,450 |
from pathlib import Path
def cleaning(*, path: Path, extension: str, affix: str) -> None:
"""Deletes all files in a Path with certain extension and name termination.
Parameters:
path: Path - directory where to delete files
extension: str - extension of files to errase
affix: ... | a9f305090fd6a105dc9d2cb08a98b75fdf12f35b | 589,453 |
def parse_args_to_dict(args, args_list):
"""
parse arguments
Args:
args: arguments parsed with argparse module
args_list: specify which arguments needs to be in output
Returns:
a dictionary of parameters
"""
params = {}
for arg in vars(args):
... | 5b7a69813a08c7d6ae9e4f934c0d59d7ceed9bd6 | 589,455 |
def is_cubefree_string(s):
"""check if s is a cubefree string, i.e. there is no substring of the form ttt"""
l = len(s)
for i in range(l - 2):
for j in range(1, (l - i) // 3 + 1):
if s[i : i + 2 * j] == s[i + j : i + 3 * j]:
return False
return True | 12ee5f9d2527303f92724def4933cb21cd504874 | 589,457 |
def getmeta(resource_or_instance):
"""
Get meta object from a resource or resource instance.
:param resource_or_instance: Resource or instance of a resource.
:type resource_or_instance: odin.resources.ResourceType | odin.resources.ResourceBase
:return: Meta options class
:rtype: odin.resources.... | a5e676f75bda3f314ceeec52fb1a44a113734c2d | 589,462 |
def parse_ev_key(tadkey):
"""
tadkey - the key for the evidence dictionary
output - Information stored in the evidence key
i.e. [ID, Chromosome, Start, End, UCSC lookup]
"""
chrom = tadkey.split(':')
ID = chrom[1]
start = chrom[2].split('-')
end = start[1]
start = start[0]
c... | 960ccf0c214f0be3fedead126a6f1a7c35124b18 | 589,466 |
def package_available(pkg):
"""Test whether a package is available or not
Parameters
----------
pkg : string
Name of the package to look for
Returns
-------
pkg_available : bool
*True* if the package is available, *False* otherwise
"""
try:
exec('import %s' ... | 81af51478d24e9b4983a5ea2e0577cfadc268217 | 589,469 |
def match_relationships(package_archive, relationship_sets):
"""
Validate that `package_archive` DebArchive satisfies all the relationships
of a `relationship_sets`. Return True if valid and False otherwise.
"""
archive_matches = None
for relationships in relationship_sets:
status = rela... | f738fd9ce78f56f7f5931264dd32ada86f2aa442 | 589,475 |
def all_algorithms(request):
"""All color distance algorithms."""
return request.param | a83431ea5935be00da16f4e6b47df2eba1aadf72 | 589,476 |
import re
def evaluate_job_file(filename: str, metrics: list) -> tuple:
"""
Receive an filename and metrics (list of dicts containing metrics)
and return an poor level and words with match
"""
poor_level = 0
words = []
with open(filename) as file:
content = file.read()
for me... | 9ea029b55bf3a3312d421c0bfb550e2f17db28d1 | 589,480 |
def get_col(node, default=-1):
"""Gets the col_offset of a node, or returns the default"""
return getattr(node, "col_offset", default) | 9be828fa53f0a92ddb28922715b6e89ae47fe6c1 | 589,481 |
def collapse_record(record, separator = '.', root=None):
"""Collapses the `record` dictionary. If a value is a dictionary, then its
keys are merged with the higher level dictionary.
Example::
{
"date": {
"year": 2013,
"month" 10,
"day": 1... | 03724bf5e06869e7289c5936ef998bec7a4c8a13 | 589,486 |
def get_matching_service_template_file(service_name, template_files):
"""
Return the template file that goes with the given service name, or return
None if there's no match. Subservices return the parent service's file.
"""
# If this is a subservice, use the parent service's template
service_na... | 82050f1605f0561db3c21fd988a2888d2cbb33c1 | 589,489 |
def class_as_str(classes: dict, class_index: int) -> str:
"""Get class name from class index
"""
return classes[class_index]['name'] | 3e28789a59bbc84b41296c615db224b4124f11f8 | 589,496 |
def compute(fromObj, toObj):
"""Compute the access from one object to another object."""
access = fromObj.GetAccessToObject(toObj)
access.ComputeAccess()
return access | d74ce9d2646ffdbe4c6db198e494d4f2a60789e0 | 589,498 |
def camel_to_dash(s: str):
"""
Convert a camelCasedName to a dash-cased-name
:param s: the camelCasedName
:return: the dash-cased-name
"""
return "".join(["-" + c.lower() if c.isupper() else c for c in s]).lstrip("-") | d13fe6aef38fa586b3249b387cb7981172a4c4b9 | 589,501 |
def t0(M_r: float, t_r: float, n: float) -> float:
"""
t0 = t_r - M_r / n
:param M_r: mean anomaly at t_r
:type M_r: float
:param t_r: reference time
:type t_r: float
:param n: mean movement
:type n: float
:return: t0
:rtype: float
"""
return t_r - M_r / n | 6dbf76333a7faaad0a31dbd9a8f55f038f79844f | 589,502 |
def is_visible(df, doc):
"""Returns True if docfield is visible in print layout and does not have print_hide set."""
if df.fieldtype in ("Section Break", "Column Break", "Button"):
return False
if hasattr(doc, "hide_in_print_layout"):
if df.fieldname in doc.hide_in_print_layout:
return False
if df.permleve... | b1373b71f34dc0136dc931a71fc7184e7be67a4a | 589,510 |
def get_image_ids(roi_seg, args):
"""Get the image ids to which ROIs will be attached
:param roi_seg: an ROI segmentation object
:type roi_seg: ``sfftkplus.formats.roi.ROISegmentation``
:param args: command line arguments
:type args: ``argparse.Namespace``
:return dict image_ids: dictionary... | 1fc329fe99aab4f5230bc11a0ab729ce8518f475 | 589,513 |
def abserr(expected, actual):
"""Computes the absolute error between `expected` and `actual`.
:param float expected: The expected value.
:param float actual: The actual value.
:return: ``abs(actual-expected)``
:rtype: float
"""
return abs(actual - expected) | c92452c76c2d4b77222415bec2ab7a9b87dbc8fc | 589,515 |
def get_sci_val(decimal_val):
"""
returns the scientific notation for a decimal value
:param decimal_val: the decimal value to be converted
:return: the scientific notation of the decimal value
"""
sci_val = ''
if decimal_val is not None:
if decimal_val == 0:
sci_val = '0... | aa6c0fe9ed2217591cbd0dafa46b80e6267a91a2 | 589,518 |
def air_impedance(sound_speed: float, air_density: float) -> float:
"""Calculates the Characteristic Impedance of the Air.
Args:
sound_speed (float): Sound speed in the air [m/s].
air_density (float): Air density [kg/(m^3)]
Returns:
float: Characteristic Impedance of the Air [Rayl]... | 067162a4c9bbeb72de29ca972a7b628580ecb431 | 589,519 |
def u(z, theta = -2):
"""Calculates utility function
Args:
z (float): Input to find utility, found as function of x, q, pi and model parameters
theta (float): A model parameter given as -2
Returns:
(float): Utility
"""
return (z**(1 + theta)/(1 + theta)) | a4749e184c3498a834046e2539c81d16d7c48c67 | 589,522 |
def pad_id(ref_id):
"""Add leading zeros to the RID to keep à length of 4"""
rid = str(ref_id)
# Fill the rid with the needed number of zero
if 4 - len(rid) > 0:
zeros_to_add = 4 - len(rid)
rid = "0" * zeros_to_add + rid
return rid | 65798aac669405534cf90e2f532c10d9217830da | 589,524 |
import json
def str_json(jo, indent=4, sort_keys=False, separators=(', ', ': ')):
""" returns formatted str with json kwargs: indent=2, sort_keys=False
"""
return json.dumps(jo, indent=indent, sort_keys=sort_keys, separators=separators) | 9e7b5bc5cccebbf1405296258317868a73f85243 | 589,525 |
def colon_hex(hexstr, interval) -> str:
""" Convert hexstr to colon seperated string every interval
:param hexstr: The hex string to convert.
:param interval: The interval number.
:return: The colon seperated string.
"""
assert len(hexstr) % interval == 0
return ':'.join(hexstr[i:i + interv... | ef9a51ed99f9c11ba93937fd039decc12194e00c | 589,528 |
from typing import Dict
from typing import Any
from typing import List
def annotation_to_entities(annotation: Dict[str, Any]) -> List[Dict[str, Any]]:
"""Flatten the annotation dict to a list of 'entities'."""
entities = []
for paragraph in annotation['paragraphs']:
paragraph_id = len(entities)
paragrap... | 0f95827abc721d035979cfa50a8734fd096d31c6 | 589,535 |
def f2measure(precision, recall):
"""Returns the f2measure (or F2-score)"""
return (1.0 + (2 ** 2)) * ((precision * recall) /
((2 ** 2 * precision) + recall)) | c4736b1612340804f08c67034d04f99b582822b4 | 589,537 |
def pi_using_float(precision):
"""Get value of pi via BBP formula to specified precision using floats.
See: https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula
:param precision: Precision to retrieve.
:return: Pi value with specified precision.
"""
value = 0
for k i... | a68126129c5fac24ed643af0bd43fcb0a6a65137 | 589,539 |
def is_illegal_char(char: int) -> bool:
"""True if char is the base-26 representation of one of i, o, l."""
if char in [8, 11, 14]: # i, l, o
return True
return False | 84f63d6061cad6a2cd2c5e8984135594a9ca6d58 | 589,540 |
def get_stamp(qcval, quartiles):
"""
Return the stamp letter for the given QC value
:param qcval: QC val for a dispersion
:param quartiles: Quartile dictionary
:return: str (one letter)
"""
stamp = 'N'
if qcval is not None:
if qcval > quartiles[75]:
... | 025ae93935a01a1307eb237e366825ce7e7775d6 | 589,541 |
def filt(sub_image, kernel):
"""filt, filt a sub_image with kernel, sub_image and kernel **must** be the same size.
Inputs:
sub_image:
kernel: np.array like, the kernel of the filter
Return:
pixel: a pixel value
"""
assert kernel.shape[0] == kernel.shape[1]
assert sub_ima... | a3dcd77b1814c0b089da7aded208436c19369f1a | 589,546 |
def removeKey(d, key):
"""Returns a dictionary with a key removed
Args:
d: a dictionary
key: the key to be removed
Returns:
copy: a copy of the dictionary d with the key removed
"""
copy = dict(d)
del copy[key]
return copy | d25c5dd3e6c5be5587e5e3318d10645a6e552266 | 589,547 |
def _if_match_passes(target_etag, etags):
"""
Test the If-Match comparison as defined in section 3.1 of RFC 7232.
"""
if not target_etag:
# If there isn't an ETag, then there can't be a match.
return False
elif etags == ['*']:
# The existence of an ETag means that there is "a... | 759505e9f68e990212f080c6dcea68db1dd7fec3 | 589,548 |
def set_nested_item(d, list_of_keys, value):
"""Sets the item from a nested dictionary. Each key in list_of_keys is
accessed in order and last item is the one set. If value is None, item is
removed.
Args:
d: dictionary
list_of_keys: list of keys
value: new value
Returns: d ... | 58759460c46f9d7c34b6f504777639b829f0dc74 | 589,549 |
def not_junk(line):
"""Return False on newlines and C-style comments."""
return line[0] != '#' and line != '\n' | a43b486a6e1e0126e86069ba0d9c089c502f7b34 | 589,551 |
def cfg_tobool(v):
"""
>>> cfg_tobool('yes')
True
>>> cfg_tobool('true')
True
>>> cfg_tobool('T')
True
>>> cfg_tobool('1')
True
>>> cfg_tobool('no')
False
>>> cfg_tobool('false')
False
>>> cfg_tobool('F')
False
>>> cfg_tobool('0')
False
>>> cfg_tob... | 169c0a0aad1d1efedbbe7c6f8ce726baccf253dc | 589,553 |
def toHexString(value):
""" Returns a clean hex (no hash) string for a given input """
return str(hex(value))[2:] | 9d02cd3cbc469c25c0235de658cf69bb8861d260 | 589,555 |
import socket
def find_free_port(num):
""" Finds a free port on the server.
:param num : Number of free ports required.
:type num: Integer
:return port : free port no.
:rtype: Integer
"""
ports = []
for _ in range(0, num):
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)... | 5f0bae77fdf48c136abb6c5b52ae1a93b3cd4f43 | 589,559 |
def make_prior_fn(fn_name, args):
"""
Return a function that draws samples from the specified distribution.
:param fn_name: The name of a ``numpy.random.Generator`` method used to
generate samples.
:param args: A dictionary of keyword arguments.
As a special case, ``fn_name`` may be set to... | fc1eadbec3bb9f28a73435e7e0d2106d77e9fe22 | 589,563 |
def _empty_list_entry(schema):
"""Generate an empty list entry for the provided schema.
"""
entry = {}
for ldap_field, _obj_field, _field_type in schema:
entry[ldap_field] = []
return entry | b16edfe6f49786707fb1330536e7bfd985908dfa | 589,564 |
def is_case_pv_graded(products):
"""Returns True if pv_grading is True for atleast one of the products on the application"""
gradings = {product.get("good", {}).get("is_pv_graded") for product in products}
return "yes" in gradings | 16a9e7ed3d3a795c0fba5fb4cfbe81df715e611d | 589,565 |
from typing import Optional
def get_intersection(box1: list,
box2: list) -> Optional[tuple]:
"""
Get intersection of the two boxes.
:param box1: First box.
:param box2: Second box.
:return: Intersection box or None if no intersection.
"""
# Unpack coordinates
x1, ... | 3d63ed3fec62fb241839a1ab03c5416abb5e2dbf | 589,569 |
def get_metric(report, metric_uuid: str):
"""Return the metric with the specified uuid."""
return [subject["metrics"][metric_uuid] for subject in report["subjects"].values()
if metric_uuid in subject["metrics"]][0] | edc36bd26d69cb9230daffff9ca75b4306656727 | 589,571 |
def map_chunk_to_roi(chunk_id, roi, chunks):
""" Given a chunk id, roi and the chunk shape, determine the coordinate
overlap, both in the roi's and the chunk's coordinate sytem.
Arguments:
chunk_id [listlike[int]] - the nd chunk index.
roi [tuple[slices]] - the region of interest
ch... | 3bac1cc80801e4309c4c6fa9d039d4a73113ca9d | 589,577 |
import random
def generateDistribution(maxLength, totalCount, numDice, randomness):
"""
Returns a bell curve distribution.
maxLength controls how wide your x-axis will be.
totalCount is the total number of points you want to generate.
numDice is the number of random numbers you want to add togeth... | 0415a90ece99c22634f6abb2b652e93c410f9310 | 589,578 |
def extract_machine_code(assembly_lines):
"""
Extract machine code from assembly line dictionaries.
Args:
assembly_lines (list(dict)): List of assembly line info
dictionaries to extract machine code from. See
:func:`~.get_assembly_line_template` for details on what
... | 757dd311e13a5c73fb3715b7195349555c02aab4 | 589,582 |
def cleanup(form_data):
"""Helper Function to strip out empty field values"""
return {key:val for key,val in form_data.items() if val} | 6bed29c66a233da26453c4eca7fa1e9d4399b949 | 589,589 |
def content_by_name_substring(content, name):
"""
:type content: dict
:param content: The python dict form of the content that has been returned from a query to KairosDB
:type name: string
:param name: This is the string that will be used to match, as a lowercase substring, the things that we want ... | 3b98efe646e89ef6b51c27c92c210b02f174503d | 589,594 |
from typing import Iterable
from typing import Hashable
from typing import Set
def to_set(
iterable: Iterable[Hashable]
) -> Set[Hashable]:
"""
Convert iterable to set.
If elements of the iterable are also iterable (may not be hashable),
they will be converted to tuples.
:param iterable:... | fa4c473d84ac2f96cc86303d7bbe9e1c0917ad56 | 589,597 |
def ensure_list(obj):
"""
This function ensures that *obj* is a list. Typically used to convert a
string to a list, for instance ensuring the *fields* as an argument is a
list.
"""
if obj is None:
return [obj]
if not isinstance(obj, list):
return [obj]
return obj | 9e3fd18b29cfdb987845d320419186cb9da11f8c | 589,598 |
def remove_tz(ts):
"""
Remove Timezone components of a Time String.
Parameters
----------
ts : str
String of Time with Timezone.
Returns
-------
str
String of Time without Timezone.
"""
return ts.replace('T', ' ').replace('Z', '') | 267379ed980dc07b679302b93a41dbdd8b02ea8d | 589,599 |
import math
def get_cosine_learning_rates(lr_min: float, lr_max: float, f: float, N: int):
"""Decay the learning rate based on a cosine schedule of frequency `f`.
Returns a list of `N` learning rate values in the interval `[lr_min, lr_max]`.
"""
lr = []
for i in range(N):
freq = f * i / N... | e1b6632cc2b47b29cbb3d1032170a22f143f8c95 | 589,601 |
def cost_function(pos_neg, off_on):
"""
Cost function for a sequence of control messages, lower is better.
:param pos_neg: count of forward<->reverse transitions, cost=10
:param off_on: count of off->on transitions, cost=5
:return: cost
"""
return 10 * pos_neg + 5 * off_on | 0bcb718daa00da0eb2fc7cd491b0a6726db65361 | 589,604 |
def list2set(seq):
"""
Return a new list without duplicates.
Preserves the order, unlike set(seq)
"""
seen = set()
return [x for x in seq if x not in seen and not seen.add(x)] | 6fcd073b366fb5b58a666ed994b3d5163a36916f | 589,606 |
def formatExc (exc):
""" format the exception for printing """
try:
return f"<{exc.__class__.__name__}>: {exc}"
except:
return '<Non-recognized Exception>' | b92ecc58a14317d3d0055b648bad2eda586a4a85 | 589,607 |
def is_community_only(user, project):
"""Return True is this project or user should only be shown community ads"""
if user.is_authenticated() and user.profile.as_opt_out:
return True
if not project.allow_promos:
return True
return False | d8490c3776978c76d0b1d8d34b0b85ed0b79c47a | 589,609 |
def ReadOnlyAttrDictView(backing):
"""Wraps a dict to provide a read-only view of its contents.
Dict keys can also be accessed by attribute.
Args:
backing: Dict-like object to wrap.
Returns:
Read-only Mapping that can be accessed by index (['foo']) or attr (d.foo).
"""
class Wrapper:
"""Wrap... | 8d25e2eee8ee9e757582fa1fd693da0b4ab6ce9e | 589,611 |
import pkgutil
def get_submodules(mod):
"""Get all submodules of a given module"""
def catch_exceptions(module):
pass
try:
m = __import__(mod)
submodules = [mod]
submods = pkgutil.walk_packages(m.__path__, m.__name__ + '.',
catch_exce... | fa30d3e99b583cda8efacadd5b5efa972b267ec3 | 589,612 |
from typing import Callable
import functools
import time
def timer_decorator(func: Callable):
"""
Basic decorator that prints the execution elapsed time of a function.
:param func func: Function to decorate.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
t1 = time.time()
... | f1cc7290658d754ac5dece0ef0cec60574bd7330 | 589,614 |
from datetime import datetime
def path_and_rename(instance, filename):
"""Renames and paths document file on upload
The filename is based on the primary key of the document object.
If the primary key does not exist, the filename is the current datetime.
When this function is called, the document's c... | 18bab2e4669130ef3ecadbcc2a4a365d11c9305e | 589,617 |
def get_id_by_name(name, parent_folder_id, drive, file_type = 'all'):
"""
Returns list of ids for folders or files with title = name in the drive folder
with id = parent_folder_id
Parameters
--------------
name : string
name of folder or file
parent_folder_id : string
... | c7fef487ffb95e0b38649fb686eed2993a61f8a7 | 589,623 |
def extract_patches_stride(image, patch_size, stride):
"""Using the input image, take a strided sampling of patches from the image
The patches are extracted (cropped copies) using the patch_size and stride.
If the patch size and stride do not evenly cover the source image in width
or height, the fracti... | 28d064eeb035b8612cdc7b7d2d38f9347c612c44 | 589,624 |
import torch
import copy
def crop_boxes(boxes: torch.Tensor, x_offset: int, y_offset: int) -> torch.Tensor:
"""
Peform crop on the bounding boxes given the offsets.
Args:
boxes (torch.Tensor): bounding boxes to peform crop. The dimension
is `num boxes` x 4.
x_offset (int): crop... | fd876119ef0c1282eed3cbb3ee62c639ab46d1d1 | 589,632 |
def parse_row(input_row, parsers):
"""given a list of parsers (some of which may be None)
apply the appropriate one to each element of the input_row"""
return [parser(value) if parser is not None else value
for value, parser in zip(input_row, parsers)] | b07bfb085432feae6a919ea121bedf5c4105f7e9 | 589,637 |
from datetime import datetime
def pretty_date(t, now=None, strftime="%b %d %Y %H:%M"):
"""Parse datetime to readable timestamp
Within first ten seconds:
- "just now",
Within first minute ago:
- "%S seconds ago"
Within one hour ago:
- "%M minutes ago".
Within one day ago:
... | 9350b1c32e234af9a7e0a35d3b4342453e26ef05 | 589,644 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.