content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import yaml
def read_conda_environments(env_paths: list):
"""
Read in a list of paths to yaml conda environment definitions.
Used to create package whitelists for conda-mirror
:param env_paths: A list of paths to conda environment definition yaml files
:return: a list of packages defined in the ... | 8b8ac992334d8c71446becf30c970143acd23304 | 603,175 |
def get_building_of_entry(service_dict):
"""Extract the configured building constraint from an yaml service entry
:service_dict: service dict from yaml
:returns: building that is set
"""
# get constraints
constraint_list = service_dict['deploy']['placement']['constraints']
# convert them to... | 81017a981552f381f617d40c77ede4611270c9af | 603,176 |
def extract_last_solution(inFile,outFile):
"""
Extracts from a file the last solution saving it in another file.
Rerturns true if a solutions is found.
"""
solution = False
sol = ""
for line in reversed(open(inFile,'r').readlines()):
if not solution:
if line.startswith("----------"):
... | a0f3088d38c8cbee4c22ee134721c2561cca9de6 | 603,179 |
def date_to_time_period(date):
"""
Converts part of a date to what xlabel that would be.
Parameters
----------
date : string
eg 2020-10.
Returns
-------
str
The time period the partial date represents.
"""
if len(date) == 0:
return "all time"
else:
... | c98265e233f97cfe4308e4000cc5b82483bbe265 | 603,186 |
def _nodes_to_road_section(origin: str, destination: str) -> str:
"""Create a road section 'A->B' from two nodes 'A' and 'B'."""
return f"{origin}->{destination}" | bafdda719f0d09705471f8edac312c9577e926c4 | 603,189 |
def remap_seq_names(otu_list, int_map):
"""Returns list with seq names remapped.
- otu_list: list of lists containing sequence names in an OTU.
- int_map: mapping between names in otu_list and original names.
"""
res = []
for otu in otu_list:
curr_otu = []
for seq in otu:... | 28db669a3e1fb6d8d654cbb8c5178c6ed907e608 | 603,192 |
def camelize(text):
"""Returns Node names such as i64 -> R64 and less_than -> LessThan."""
return "".join([w.lower().capitalize() for w in text.split("_")]) | c366bddaf6d195b1a09dd4dcc289e01a7466c18b | 603,198 |
import torch
def iou_loss(inputs, targets, weight=None, box_mode="xyxy", loss_type="iou", reduction="none"):
"""
Compute iou loss of type ['iou', 'giou', 'linear_iou']
Args:
inputs (tensor): pred values
targets (tensor): target values
weight (tensor): loss weight
box_mode ... | c70804ff67179ce457ff302591130852215ceaea | 603,200 |
def check_if_valuemap_exists(module, zbx, name):
"""Checks if value map exists.
Args:
module: AnsibleModule object
zbx: ZabbixAPI object
name: Zabbix valuemap name
Returns:
tuple: First element is True if valuemap exists and False otherwise.
Second element is... | e05e10efbc71bee1504f0122b46b5bd3df5425fb | 603,204 |
def central_crop(images, mask, x_crop=27, y_crop=45, z_crop=27):
""" crops symmetrically along the x, y and z axis.
# Arguments
images: tuple containing the baseline and follow-up images.
mask: array, contains the segmentation mask.
x_crop: int, default 27, size to crop at the beginning ... | 5922c213dd3f69955dc238bcb1760850e0954c71 | 603,205 |
def pretty_conjunction(conjunction):
"""Pretty-print a conjunction. Use parentheses as necessary.
E.g. ["a", "b"] -> "(a & b)"
Args:
conjunction: List of strings.
Returns:
A pretty-printed string.
"""
if not conjunction:
return "true"
elif len(conjunction) == 1:
return conjunction[0]
e... | 5283aec989ec3a4422d904724da73630ed1bde5d | 603,211 |
import requests
def _get_ip(url):
"""Return our external IP sourced from ipify.org"""
return requests.get(url).text.strip() | 0487134dbdc57925d461a89b739822934adf98cc | 603,212 |
def isBefore(date_1, date_2):
"""Compares to dates to see if date_1 is before date_2.
Args:
date_1 (Date): The first date.
date_2 (Date): The second date.
Returns:
bool: True (1) if date_1 is before date_2, False (0)
otherwise.
"""
return date_1.before(date_2) | 29553935558388211ae67accbacf99a47093393d | 603,214 |
def create_payload_for_request(template_data, user_input_dict, existing_data=None):
"""
This function creates the payload using the user provided input based on the respective template data
and the existing data
template_data
dict which contains the data required for the resource(security rule,... | d7396d0e7f581acdfd2a48f1895dd81aba694c8c | 603,216 |
def extract_tree(root, ordered_RD):
"""
Extract all nodes from the tree below root node using deepth-first search.
reture:
a list has the structure [[node_id, start_idx, end_idx, average_RD, level_id, parent_id],\
[...]...]
"""
level = 0
node_id = 0
... | 1b9fe3837d086ae5571b801400a1e8d1e7e7012c | 603,219 |
def slurp(text, offset, test):
"""Starting at offset in text, find a substring where all characters pass
test. Return the begin and end position and the substring."""
begin = offset
end = offset
length = len(text)
while offset < length:
char = text[offset]
if test(char):
... | 9a6ad8da3ef9434e30927c7cceab26279abf940a | 603,220 |
def remove_empty(dictionnary) -> dict:
"""Remove items whose value is None in a dictionnary."""
return {k: v for k, v in dictionnary.items() if v is not None} | 2304192ca52c0e7a08e2002d1638f2931e79fc88 | 603,221 |
def create_fts_metadata(all_keywords, action_metadata, source_fts_metadata_actions, extra_metadata):
"""
Create an FTS metadata dictionary.
Parameters
----------
all_keywords: list
List of all keywords associated with the resource
action_metadata: list
List of action metadata fo... | c1db5efd7a9c4b3cf32fbca414eb9dc3455e007b | 603,224 |
import time
def _wait_for_lb(module, cloud, lb, status, failures, interval=5):
"""Wait for load balancer to be in a particular provisioning status."""
timeout = module.params['timeout']
total_sleep = 0
if failures is None:
failures = []
while total_sleep < timeout:
lb = cloud.net... | b0cee567f7c0b2b4adde9991a02f0491be404d1f | 603,225 |
def entry_markdown(entry):
"""Generate the Markdown for the specified entry."""
enumerated_item = "1. "
indent = " " * len(enumerated_item)
issue_url = (
f"https://github.com/Microsoft/vscode-python/issues/{entry.issue_number}"
)
issue_md = f"([#{entry.issue_number}]({issue_url}))"
e... | af320364039f5b046eb338afc216e049e436623c | 603,227 |
def task_id_eq(task_id, body, message):
"""Return true if task id equals task_id'."""
return body['id'] == task_id | 78cc870cb4c5ea4483ba3bb08f9ae8d7dde1e2d4 | 603,232 |
import requests
import xmltodict
def parsere3(uri):
"""Parse Re3Data from XML to Python dictionary.
This script uses the API for the Registry of Research Data Repositories
at http://re3data.org/ to pull information about major data repositories
and then parses it into a usable Python format, from XML.... | 507dae771613096f3cff532cfbea55a5b8f94bcb | 603,233 |
from typing import List
from typing import Dict
from typing import Any
import torch
def moco_collator(batch: List[Dict[str, Any]]) -> Dict[str, List[torch.Tensor]]:
"""
This collator is specific to MoCo approach http://arxiv.org/abs/1911.05722
The collators collates the batch for the following input (ass... | 7b38a770b36afacb25f21eca19bfba7789488c8e | 603,234 |
def add_leading_dot(s, not_empty=None):
"""Adds leading dot.
Args:
s (string): string to recieve leading dot.
not_empty (bool): whether to add leading dot to empty string.
"""
if not_empty is None:
not_empty = True
if len(s) == 0 and not_empty:
return s
if not s.sta... | 65f5dee54d02752c0db78440353e919dff7aff6b | 603,236 |
def flatten(obj, ltypes=(list, tuple)):
"""Flatten a nested variable, by default only list/tuple combinations.
Source: Mike C Fletcher's flatten http://www.bit.ly/2ULLMnm
"""
ltype = type(obj)
obj = list(obj)
i = 0
while i < len(obj):
while isinstance(obj[i], ltypes) and not (
... | 29d4ebb5fea56dce12f0cefe9daf741959ca571a | 603,239 |
def vote_percentage(ticket):
"""
Get the percentage value of votes a ticket receives
:param ticket: The requested ticket to get vote percentage for
:return: percentage of votes received in relation to other tickets
"""
count = ticket.votes.count()
if count == 0:
return ... | 420c32110695288f3529ed72224148034be4d07e | 603,241 |
def axisRange(staPhaList,plotPhase,xOffsets,yOffsetRatios):
"""
Get the axis range for tele waveform plot
"""
minP = staPhaList[0][1]
maxP = staPhaList[-1][1]
minS = staPhaList[0][2]
maxS = staPhaList[-1][2]
minDist = staPhaList[0][3]
maxDist = staPhaList[-1][3]
ystart = minDist... | 2567afbd16d5dfe74a6ff1343dbb146051bd9420 | 603,242 |
def format_arn(partition=None, service=None, region=None, account=None,
resource=None, resource_type=None, resource_name=None,
defaults_from=None):
"""Return an ARN composed from the specified components.
Provide either resource or both resource_type and resource_name.
defaul... | 59577f3d58b72cd2b688782763cc8a2cedc4bff6 | 603,243 |
import math
def get_fig_size(fig_width_cm, fig_height_cm=None):
"""Convert dimensions in centimeters to inches.
If no height is given, it is computed using the golden ratio.
"""
if not fig_height_cm:
golden_ratio = (1 + math.sqrt(5))/2
fig_height_cm = fig_width_cm / golden_ratio
s... | 830a8aae13680f27639156d3e6108256f6841040 | 603,244 |
def possibly_active(context, category):
"""
Returns CSS class 'active' for submenu if the respective path is
requested. E. g. Request path '/gemeinde/foo/bar' returns 'active' for
category 'gemeinde'.
"""
if context.request.path.startswith("/" + category):
return "active" | bbd6e00248cdc036f624f8d86a94719c18d2c3e7 | 603,246 |
def count_increased_part2(values):
"""
Count how many measurements increased in a three-measurement sliding window
:param values: List of values
:returns: Number of measurements that increased in a three-measurement sliding window
"""
# how many measurements increased in three-measurement slidi... | 22fd441f91d5e4c84cfe6c46ab37d5b2f212fa78 | 603,247 |
def dpi_to_dpmm(dpi):
"""
Convert dpi (dots per inch) to dpmm (dots per millimeter)
Args:
dpi (int):
Returns:
float: dots per millimeter
"""
return dpi / 25.4 | 2dec78dfc1e6b5471c0fec14160b7290b1ec0562 | 603,249 |
import itertools
def count_overlaps(field):
""" Count the points in field with a value greater than 1 (indicating that more than
one line intersected that point.)
"""
all_points = itertools.chain(*field)
num_overlaps = len([i for i in all_points if i > 1])
return num_overlaps | c18fe92c7f3d4460df6a3f8e603e3f0dbcdd7e8d | 603,251 |
def is_zipcode_empty(zipcode):
"""
Check for an empty Zipcode object to detect for empty Excel rows.
:param zipcode: Zipcode
:return: Boolean
"""
if zipcode.city_town is None \
and zipcode.zipcode is None \
and zipcode.ap_lynn is None \
and zipcode.ap_nsmha is... | 0c7fc9783ba658afb3357a5bddc32880536c0fcd | 603,252 |
import random
import string
def create_random_letters(digit):
"""
生成随机字母
:param digit: 大小写混合,参数为位数(长度)
:return:
"""
letters_list = [random.choice(string.ascii_letters) for i in range(digit)]
# string.ascii_letters=abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
random_letters = "... | 64fe5920bacc8cfd4b29ae5ae1f9f7551745644a | 603,255 |
def get_neighborhood(neighs, longitude, latitude):
""" Returns the neighborhood of the input point. We assume that a
point can only be contained in one neighborhood (otherwise data is broken)
Args:
neighs: Dictionary mapping neighborhoods and their area
longitude: Longitude of the input poin... | 657d26c84f647ffaa6414939d709de6643a51fbf | 603,258 |
def recursive(accumulate=False):
"""
Decorator that labels a Pipe method as recursive. This means, that method func will first be called on
the Pipe's inputs and then on the Pipe itself.
If accumulate is set to True, then the result from calling the method on a given Pipe will be
used as input to th... | 1197ea9d8aa1fec507b2c843e37f3f22c8b43d84 | 603,264 |
def canvas2px(coord, dmn, dpi):
"""
Convert matplotlib canvas coordinate to pixels
"""
return int(round(coord * dmn * dpi)) | be722062d3a21eb3622e16d9a79d25906ca47cc0 | 603,265 |
def find_dna_compliment(DNA: str) -> str:
"""Return a compliment of a DNA string
>>> find_dna_compliment('AATTGCCGT')
'TTAACGGCA'
>>> find_dna_compliment('TTAACGGCA')
'AATTGCCGT'
"""
# start with an empty compliment DNA
compliment = ''
# take each character and append its opposite
... | 7bc00ae4de56aa9cb0104e3c275011a8ccb8d3be | 603,266 |
def makeInputStr(minVal, maxVal, count):
"""
Create a default input string for a given test dimension.
"""
return "{0}:{1},{2}".format(minVal, maxVal, count) | 0af578a056d7b3f1ea31082904f3b91aea5f12b3 | 603,268 |
def results_to_dict(res):
"""
Convert pkgcheck NonSolvableDeps* result into dicts for checking.
"""
out = []
for r in sorted(res.output, key=lambda r: r.package):
out.append({
'__class__': r.name,
'attr': r.attr,
'category': r.category,
'deps'... | b30da594309d45536fedf1af171d8e1cccd9946e | 603,270 |
import struct
def _H(n):
"""
Pack an integer into a network-order two-byte string.
@param n: The integer to pack. Only values that fit into 16 bits are
supported.
@return: The packed representation of the integer.
@rtype: L{bytes}
"""
return struct.pack(">H", n) | 4f7deacb4d9a4f1fc6524ef76cd5dbcc05f9a981 | 603,273 |
def is_user_in_group(user, group):
"""
Return True if user is in the group, False otherwise.
Args:
user(str): user name/id
group(class:Group): group to check user membership against
"""
result = False
users = group.get_users()
if user in users:
return True
groups = ... | 1493e20680d533e1f3c1fd45ba2379424046a98e | 603,274 |
def self(client):
"""Requests information on current user."""
return client.get_user_self() | adb969a056e16d4db9f892c7f3335c1970eb4c78 | 603,275 |
def get_bgpvpn_differences(current_dict, old_dict):
"""Compare 2 BGP VPN
- added keys
- removed keys
- changed values for keys in both dictionaries
"""
set_current = set(current_dict.keys())
set_old = set(old_dict.keys())
intersect = set_current.intersection(set_old)
added = set_cu... | 81224c192f289fb1e13658ec2ca65093caecc310 | 603,276 |
def dict_to_schema_uri(uri_dict):
"""
Build MDStudio WAMP JSON schema URI from dictionary
:param uri_dict: dictionary describing WAMP JSON Schema URI
:type uri_dict: :py:dict
:return: MDStudio WAMP JSON Schema URI
:rtype: :py:str
"""
return u'{type}://{group}/{compon... | ffeaa8972f6671e3d5b571036681285e97054c42 | 603,278 |
import requests
def open_url(url):
"""
新增header,并request访问
:param url: str, url地址
:return: str, 目标url地址返回
"""
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) '
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.3... | f6e96e07d5a44ce5f4971e3d92f7a4103fa8c15e | 603,279 |
def create_email_text(vendor_firstname, date_start, date_end, amount, payment_method, email):
"""
Create full text of an email tailored to the details of the vendor and reporting period.
Parameters
-------
vendor_firstname : str
First name of the vendor receiving the email.
date_start :... | ee90611c752ccff86b5924f0f2baf7217f49ec47 | 603,280 |
def infer_task(y, goal="class"):
"""Infer the task corresponding to a target column.
If goal is provided, only look at number of unique values to
determine the classification task.
Parameters
----------
y: pd.Series
Target column from which to infer the task.
goal: str, optional (... | d416530f165ffbfd251ea228652a84999797f947 | 603,285 |
def gen_record_set(use_resource_record=False, **kwargs):
"""Generate a record set."""
data = {
'Name': 'placeholder_name',
'Type': 'CNAME',
'Value': 'placeholder_value'
}
if use_resource_record:
data['ResourceRecords'] = kwargs.pop('ResourceRecords', [
{'Value... | e190c94ec9280d892361fc78177db5e2d84991a8 | 603,286 |
def fibonacci(number:int) -> int:
"""
Returns the n'th fibonacci sequence number
>>> fibonacci(number=10)
55
"""
PHI = (1 + 5 ** 0.5) / 2
return int((PHI**number - (-PHI)**(-number))/(5**0.5)) | b6932e3473140230467a87a3042c79313dac6847 | 603,287 |
def safe_unix_name(name):
"""
Piano chord names might contain slash - /
This might break file saving because / is a directory separator in Unix
"""
return name.replace('/', '-slash-') | 567b9e9c17933b7eebcc62b11363543832a6168c | 603,288 |
import re
def read_changelog_section(filename, single_version=None):
"""Reads a single section of the changelog from the given filename.
If single_version is None, reads the first section with a number in its
heading. Otherwise, reads the first section with single_version in its
heading.
Args:
- singl... | 34e17cc0901b9b48fc33dbe5d5f931b1558a2787 | 603,290 |
def make_grouped_share(df, variable, name="share"):
"""Normalise a variable (for using in grouped dfs)"""
df[name] = df[variable] / df[variable].sum()
return df | 258f93b82bac8439f002e4f4b1bd95a3c04878a0 | 603,292 |
def has_radical(mol):
"""
Finds if a pybel.Molecule has Radicals.
Radicals have an atomic number of 0.
Parameters
----------
mol : pybel.Molecule
A molecule.
Returns
-------
bool
True if there are any radicals.
"""
return any(a.atomicnum == 0 for a in mol.at... | 0708e60f2281d56723f4dbe4bee3352306b8b53c | 603,293 |
def get_namespace_by_name(namespace_name: str, client) -> str:
""" Returns namespace id of a namespace with name <namespace_name> """
namespaces = client.list_namespaces()
for n in namespaces.get("Namespaces"):
if n.get("Name") == namespace_name:
return n.get("Id")
raise RuntimeError... | 5303f44b4157928a96eb07cb59dc1f6c76116c21 | 603,297 |
def Credible_Set(position, posterior, threshold):
"""Function that finds the credible set according to a set threshold"""
total = sum(posterior)
bounds = threshold*total
#make into tuples
tuple_vec = []
for i in range(0, len(position)):
tup = (position[i], posterior[i])
tuple_vec... | 132bcc9dd90dca95b2dbfafeafd686881610f3dd | 603,308 |
import torch
def load_model_pytorch(path: str):
"""
Load a Pytorch at a given path
https://pytorch.org/tutorials/beginner/saving_loading_models.html
:param path: Path to model to load
:return: Pytorch model
"""
model = torch.load(path)
model.eval()
return model | 6222225977a64f69014177ad2c430e8964f4a3f8 | 603,309 |
from typing import Dict
from typing import Any
def without(dct: Dict[Any, Any], exclude: Any) -> Dict[Any, Any]:
"""
>>> without({'a': 1, 'b': 2}, 'a')
{'b': 2}
>>> without({'a': 1, 'b': 2}, 'c')
{'a': 1, 'b': 2}
"""
return {k: v for k, v in dct.items() if k != exclude} | 411a807684e3377975a90b1fa2e14f495cb149cd | 603,317 |
def weighted_sum(pdf, col_name):
"""
Return weighted sum of Pandas DataFrame col_name items.
"""
return (pdf[col_name] * pdf['s006']).sum() | e9954ca2ee7e09f58abbf2420da9824a2e079d3a | 603,321 |
def get_file_name(path: str) -> str:
"""return the file name without extension given a path
Args:
path (str): absolute path to the file
Returns:
(str): file name
"""
return path.split("/")[-1].split(".")[0] | df11e5eb0ee66b2b612dcfc9a6de594911990421 | 603,322 |
import struct
def gen_format_string(formats, size=None, expand=False):
"""
Generate a format string specifying the byte alignment given a list of the
form ["<pattern1>:<count1>", "<pattern2>:<count2>", ...]. For example,
>>> gen_format_string(["id4s:2", "f2d"])
would return "id4sid4sf2d".
F... | a0c8efbab9da74bd0d29ff57ce5f9f419d841499 | 603,326 |
import re
def get_relevant_warnings(log_file):
"""Extract relevant warnings from a LaTeX log file."""
overfull_lines = re.findall(r"Overfull \\hbox .*", log_file)
undefined_references = re.findall(r"LaTeX Warning: Citation `.*?' on page .*", log_file)
return overfull_lines + undefined_references | d949f5ead789ed6866d5017e02d9de2dc77f4576 | 603,330 |
def rot_char(character, n):
"""Rot-n for a single character"""
if character.islower():
return chr(((ord(character)-97+n)%26)+97)
elif character.isupper():
return chr(((ord(character)-65+n)%26)+65)
else:
return character | 401be5cfd78816c833db8391c7e973a42bb2710d | 603,332 |
def isNan(x):
"""check for nan by equating x to itself"""
return not x == x | f01ec6a5a5d04113d9c7c1630131802e412ade77 | 603,333 |
def hdr(tag):
"""Create a node which can be used to represent h1, h2, etc. tags
(and their content) hierarchically as a tree, rather than the flat
html way
:param tag: [bs4.element.Tag]
:return: [dict] header node
"""
level = int(tag.name[1:])
return {
'tag' : tag,
... | 5996b1af20cbd2fa9997b93b06d6fe0a38c2d933 | 603,336 |
import hashlib
def _get_hash(bytestring):
"""Get sha256 hash of `bytestring`."""
return hashlib.sha256(bytestring).hexdigest() | 5737ec1e830d9355e9726dcce7e1ba8c168d05cb | 603,338 |
def map_values_to_autolev_symbols(constants):
"""Returns a dictionary mapping the autoleve symbol names to the ones
used in Python model.
Parameters
==========
constants : dictionary
Maps python symbol names to floats.
Returns
=======
d : dictionary
Maps autolev symbol ... | c478c43a29623f9bd29ad5158b8f7dc89dcd0bb9 | 603,339 |
def get_vit_lr_decay_rate(name, lr_decay_rate=1.0, num_layers=12):
"""
Calculate lr decay rate for different ViT blocks.
Args:
name (string): parameter name.
lr_decay_rate (float): base lr decay rate.
num_layers (int): number of ViT blocks.
Returns:
lr decay rate for the... | 368cf5426f4ffab1a3a1c95b7fd404f7fd4fbedd | 603,342 |
def contingency_table(ys, yhats, positive=True):
"""Computes a contingency table for given predictions.
:param ys: true labels
:type ys: iterable
:param yhats: predicted labels
:type yhats: iterable
:param positive: the positive label
:return: TP, FP, TN, FN
>>> ys = [True, True, T... | 83efd6b17654dc6424d933723c84fb162dc04263 | 603,348 |
import requests
def get_buffer(url):
"""
Retrieve a buffer from a URL as an in-memory buffer.
:param url: URL for a given document to request
:return: bytes, request response
"""
# Get response
response = requests.get(url)
if response.status_code == 404:
return None
else:
... | b51be3090dd0475b69ff51d8a15ed5c336db12c6 | 603,351 |
def severity_num_to_string(severity_num: int) -> str:
"""
transforms severity number to string representation
:param severity_num: Severity score as Integer
:return: Returns the String representation of the severity score
"""
if severity_num == 1:
return 'Info'
elif severity_num == 2... | eeaa49bd3ebafde667256a78a47f056522f601b7 | 603,352 |
def strbin2dec(strbin):
"""
Convert a string representing a binary value into a
string representing the same value in decimal format.
"""
strdec = "0"
for i in range(1, strbin.__len__()+1):
strdec = str(int(strdec)+int(strbin[-i])*int(pow(2, i-1)))
return strdec | b239667c802e1a11d2b669b8ef1e89e7f3181cb1 | 603,354 |
def to_camel_case(s):
"""Given a sring in underscore form, returns a copy of it in camel case.
eg, camel_case('test_string') => 'TestString'. """
return ''.join(map(lambda x: x.title(), s.split('_'))) | 7ab4acc31c8a152631d50cb64f00a1ee20747e57 | 603,357 |
def make_position_string(length):
"""
Takes the length of the state and returns a string 01234... to be
displayed in the interaction to make it easier for the user to pick
the position of the pair to be moved.
make_position_string(int) -> string
"""
string = ""
for i in range(0,leng... | 707615f1ab32cdf0d48928af23e87b3841e1ac8e | 603,359 |
def msbit2lsbit(b, length):
"""
Convert from lsbit of signal data to msbit of signal data, when bit numbering is msb0
Reference: https://github.com/ebroecker/canmatrix/wiki/signal-Byteorder
:param b: msbit in msb0 numbering
:param length: signal length in bits
:return: lsbit in msb0 numbering
... | 95d6efa1a241c461601927b9f07b47e61ac76481 | 603,360 |
import base64
def _base64_url_encode(s: bytes) -> str:
"""Base64 encode.
Example:
>>> from stkclient import _base64_url_encode
>>> _base64_url_encode(b'foo')
'Zm9v'
"""
return base64.b64encode(s, b"-_").rstrip(b"=").decode("utf8") | f84dc4ff6bd498385e1eb2db520bb7ea3449569b | 603,361 |
def _operation(mocker):
"""Fixture providing handler operation."""
return mocker.Mock(return_value='operation body') | 5b862ab22af68d1b45ef098abd03b152536eb247 | 603,363 |
import time
def process_rate(num_seqs, stime):
"""
Calculate amount of time to process sequences
:param num_seqs: Number of sequences processed
:type num_seqs: int
:param stime: Start time in seconds (since the epoch)
:type stime: float
:return: Number of sequences processed per second
... | aa127c7db83d72a4ddd7b247a04c02a4595cd86d | 603,364 |
def min_max(lst):
"""
Function that returns both the minimum and maximum number of the given list/array.
:param lst: an array of integers.
:return: returns a list with the smallest then largest numbers in the array.
"""
return [min(lst), max(lst)] | 0c73cd81c53c2fd6b42a820d131870ece99e7f25 | 603,367 |
def get_move(move):
"""
Parses the possible moves into the direction and the amount
E.g. R2 (2 blocks to the right), L8 (8 directions to the left)
Args:
move (str):
Returns:
tuple. Direction of the move and amount of bocks moved
"""
return move[0], int(move[1:]) | e137dfd66ed23e9b56dfed76f7362cc094c9c0f4 | 603,369 |
import math
def include_revision(revision_num, skip_factor=1.1):
"""Decide whether to include a revision.
If the number of revisions is large, we exclude some revisions to avoid
a quadratic blowup in runtime, since the article is likely also large.
We make the ratio between consecutive included revision num... | 791789624887940bbb8db5de1157b69ededd0988 | 603,371 |
def parse_float(src, key, nentries=1):
"""
Parse a dictionary ``src`` and return a float or a list of float specified by ``key``.
This function checks that the value or values specified by ``key`` is of
type float or list of float and raises a ``ValueError`` otherwise.
:param dict src: the source... | 25c156322fc1526fa4314fd8bda2dce80367169c | 603,373 |
def default_panels(request, parsed_case):
"""Return a list with the gene panels of parsed case"""
panels = parsed_case['default_panels']
return panels | b539c9a739a917744b4adeaeca985115419d830f | 603,378 |
import time
def task_dots(storage):
"""
Task that prints dots forever.
"""
print(".", sep=" ", end="", flush=True)
time.sleep(.25)
return True | 15e06d2048f9664ae70dedeb8d3f6efd8774c3d1 | 603,379 |
from typing import List
def find_unused_bank(edge_banks: List[int]) -> int:
"""
Given a list of banks used in one clock, find a bank index that isn't used, or -1 if all are used
:param edge_banks:
:return:
"""
for i in list(range(len(edge_banks))):
if i not in edge_banks:
r... | b59e622fde507ae13231c02f29334760796091d8 | 603,381 |
def overlapping_samples(dataset_samples, request_samples):
"""Check that samples provided by user are contained in either VCF of dataset object
Accepts:
dataset_samples(list): the list of samples contained in the dataset or the VCF
request_samples(list): the list of samples provided by user
... | f08222a9d5a50d1e7892c0167df1f538018bec74 | 603,382 |
import re
def parse_blob_path(path):
"""Parse a gcs path into bucket name and blob name
Args:
path (str): the path to parse.
Returns:
(bucket name in the path, blob name in the path)
Raises:
ValueError if the path is not a valid gcs blob path.
Example:
`bucket_name,... | a5c774caa6bc23ff1f3ccf9c0262d7e64dd97526 | 603,383 |
def collapse_lines(str):
""" strip() each line in a string and return the remaining non-empty lines joined together"""
return ''.join(filter(bool, (line.strip() for line in str.split('\n')))) | abd6721d4e12bda0966d7ee0a68384531bef9eab | 603,385 |
def printName(name):
"""takes a name (string) and will print out "Your name is:" along with the name capitalized. Returns the capitalized name.
example: printName("julie")
will print: Your name is: Lucy
"""
name = name.capitalize()
print("Your name is:", name)
return name | 7216ea3b68a6b144fd139d9556548a6cdef608a1 | 603,389 |
def common_errors_remark(common_errors):
"""Generate remark for common errors and issues detection."""
if common_errors["display_results"]:
if common_errors["failed"] != 0:
return "<li>fix common errors</li>"
else:
return ""
else:
return "<li>setup common erro... | be4103f83cc05e85772e565630a088b17edec1ec | 603,390 |
import smtplib
def connect_smtp(user, password, server="smtp.office365.com", port=587):
"""Make a SMTP connection"""
server = smtplib.SMTP(server, port)
server.ehlo()
server.starttls()
server.login(user, password)
return server | ec19c57520179811543a7494cf23bf32360e66bf | 603,395 |
def get_slot_value(intent, slot_name, default=None, avoid=[""]):
"""Function to safely return a slot value from the dictionary.
Only returns non-default value if intent contains a value for the slot,
and that value is not an empty string.
"""
if slot_name in intent['slots'] and "value" in intent['s... | 774487f1cc362467f11e9ff1177f0b8cea68241f | 603,397 |
def to_dict(key_func, value_func):
"""
Returns a function which returns a dictionary by collecting the
given iterable by key_func and value_func.
"""
def dict_collector(iterable):
return {key_func(item): value_func(item) for item in iterable}
return dict_collector | 2aeb4ce58d6327a489c6991b90f2541bed887cf7 | 603,398 |
import json
def load_config(path):
"""
load model's config
:param path: path for load
:return: config
"""
with open(path, 'r') as fd:
return json.load(fd) | 8eed40da756cedb1a8197fdf3cb99ca616b31a23 | 603,399 |
def is_under_remote(ref, remote):
"""Return True if a Git reference is from a particular remote, else False.
Note that behavior is undefined if the ref is not fully qualified, i.e.
does not begin with 'refs/'.
Usage example:
>>> is_under_remote("refs/remotes/origin/mywork", "origin")
T... | c971abfe2964e85880bfc996f39cc43e55470088 | 603,404 |
def get_temperature_rise_spec_sheet(page_number: int) -> float:
"""Retrieve the temperature rise based on the spec sheet from MIL-C-39010.
:param page_number: the spec sheet to retrieve the temperature rise
for.
:return: _temperature_rise; the spec sheet temperature rise.
:rtype: float
:rai... | 533cc1cf5c62092e20377f670402ec506f2d0ce9 | 603,406 |
def normalize(array):
"""
This function normalizes a numpy array to sum up to 1 (L1 norm)
"""
return array/array.cumsum()[-1] | a3ec4e9f867b7548c1fefca3807fa846508a20bc | 603,411 |
def bigness_factor(wort_gravity):
"""Wort 'bigness factor' for hop utilization.
Parameters
----------
wort_gravity : float
Average specific gravity of wort during boil.
Returns
-------
bigness_factor : float
Multiplicative factor for hop utilization based on wort
... | 951ec78fb757e885783227cf405c06651213e37e | 603,413 |
def del_none(d):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
"""
# For Python 3, write `list(d.items())`; `d.items()` won’t work
# For Python 2, write `d.items()`; `d.iteritems()` won’t work
for key,... | d32bd91788508bfbf036451745e1c73ced11da45 | 603,414 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.