content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _GetProfileInfoDict(profile_info):
"""Convert profile_info to a dict.
Args:
profile_info (ArtifactProfileInfo): The artifact profile_info.
Returns:
A dictionary containing profile info.
"""
ret = {}
which = profile_info.WhichOneof('artifact_profile_info')
if which:
value = getattr(profil... | bedaa3ea996139ffba4f70c95bfa490b908a1e63 | 624,996 |
import argparse
def parse_args(args):
"""Parse command line parameters.
Args:
args ([str]): command line parameters as list of strings.
Returns:
:obj:`argparse.Namespace`: command line parameters namespace.
"""
parser = argparse.ArgumentParser()
parser.add_argument('config', type... | be2931dc5d101355c6489ca78ecad6187e6159d0 | 624,997 |
def nodeTypeNameMatches(node, matchtype):
""" Returns true if the node's type base name matches the given type.
A matchtype of None is assumed to match any node.
"""
return True | d8bd187cefc756fec829d9bf647c3be91123dee4 | 624,998 |
def form1(x, y, n, ind, ax, line):
"""Default annotation for plots with 1 line"""
return f"x: {x:.5g}\ny: {y:.5g}" | 7eee751b7f3b3ea8e892ddffd088f276363d8ea8 | 624,999 |
import socket
def is_ipv4_address(addr):
"""
Check if an address is a valid IPv4 address
Note that something like '1.1.1' is considered to be valid.
Because '1.1.1' can be abbreviation of '1.1.1.0'
"""
try:
socket.inet_aton(addr)
return True
except (socket.error, ValueErr... | e562d1fc998c156978054da5e193f5ad9827a4b8 | 625,000 |
from typing import Dict
from typing import List
from typing import Tuple
from typing import Any
def dictionary_to_tuple(dictionary: Dict) -> List[Tuple[Any, ...]]:
"""Return a tuple from a dictionary."""
return list(dictionary.items()) | c19ed843f02b076b314636cb3a0ee7466723d440 | 625,001 |
def double_to_single_callable(application):
"""
Transforms a double-callable ASGI application into a single-callable one.
"""
async def new_application(scope, receive, send):
instance = application(scope)
return await instance(receive, send)
return new_application | daeb00905912f1a55cf4f4e0a597d2ae2e0146a9 | 625,003 |
from typing import Iterable
def build_dataset_name(estimate: int, years: Iterable) -> str:
"""Produce a nicely formatted dataset name."""
unique_years = sorted(set(years))
if len(unique_years) > 1:
years_range = f'{min(unique_years)}–{max(unique_years)}'
else:
years_range = unique_year... | 8c21d3dd3079443734143487a9a45f70da596e6a | 625,005 |
from typing import Optional
def get_duration(duration: Optional[float]) -> float:
"""Return 0 if the given duration is negative else, return the duration.
>>> get_duration(None)
0
>>> get_duration(-10)
0
>>> get_duration(12)
12.0
"""
if duration is None or float(duration) < 0:
... | 682adedfe2d352a2413e40ed6f3b39bbf02ea7e2 | 625,006 |
def letter_only(guess, abc):
"""
Checks if the player's guess is a single ASCII letter only.
:param abc: the alphabet used in the proverbs
:type abc: str
:param guess: the player's guess
:type guess: str
:return: True | False
:rtype: bool
"""
if len(guess) == 1 and guess.upper()... | e6822eab984c6c8d0c15e103ced88bed348620cc | 625,007 |
def klGaussian(mean_1, mean_2, sig2=1.):
"""Kullback-Leibler divergence for Gaussian distributions."""
return ((mean_1 - mean_2) ** 2) / (2 * sig2) | 53d6ddfc1e6794355a532f2bf7ae4d65c828316f | 625,010 |
def derive_folder_name(url, replaces):
"""
"""
sanitize = lambda x: x.replace('/', '.')
for service in replaces:
if url.startswith(service):
url = replaces[service] + url[len(service):]
return sanitize(url)
for generic in ['http://', 'https://', 'git://', 'svn://']:
... | 4b4a0db661cd8689d1b21046add5ff602a4568fe | 625,011 |
def do_something_on_the_raw_log(line: str):
"""
this is an example preprocessing hook.
"""
return line | 3736b0aa8b4c974bee655fe2dcb4f1a3f650fc6c | 625,012 |
def size_increment(added_content, deleted_content):
"""
:param added_content: content added to wiki by an user
:param deleted_content: content deleted from wiki by an user
:return: ratio of added to deleted content
useful to identify deletion vandalism, where a vandal can remove data in large amount... | 6a1a0909fc819a89fbccd1340558d0d6fdb987ce | 625,013 |
def generic(
target, namespace, pass_cond=None, message="deserialization object",
default=None):
"""Deserialize object similarly to keras .get.
Parameters
----------
target : object
target deserialization object.
namespace : object
namespace to search in.
Keywor... | d56a36a1b47f9a8233c6b9a40f43e797014f4c97 | 625,014 |
def keywords_template(keywords: list) -> list:
"""Flex Message 留言關鍵字
Args:
keywords (list): 關鍵字列表
Returns:
list: 關鍵字
"""
comments = []
for each in keywords:
data = {
"type": "text",
"text": each,
"flex": 0,
"margin": "xl",... | 4ea6f1ac15fad47fabf81192aee824cc40e8e6e2 | 625,015 |
import socket
def handle_udp_send(data: bytes,
sock: socket.socket,
ip: str,
port: int) -> int:
"""Handle sending a datagram.
This mainly exists so we can make a partial of it.
Args:
data (bytes): Message payload to send.
sock (... | e813b3c91588a79d0debaf85bb6a87689a8e053b | 625,016 |
import os
def get_condor_node_name(nodename):
"""
On a condor system, add the SlotID to the nodename
:param nodename:
:return:
"""
if "_CONDOR_SLOT" in os.environ:
nodename = "%s@%s" % (os.environ["_CONDOR_SLOT"], nodename)
return nodename | d67c73d1de345ac215f0c102765b6d81a453c16b | 625,017 |
def get_prefix(headword, length):
"""
Return the prefix for the given headword,
of length length.
Note that the procedure implemented here is the result
of reverse engineering, since no official specification
has been published by Kobo so far. YMMV.
:param headword: the headword string
... | be7c36bcb1b46b52bef34be1ec67a7efcccabcca | 625,018 |
def eqrr(registers, a, b, c):
"""(equal register/register) sets register C to 1 if register A is equal to register B. Otherwise, register C is set to 0."""
registers[c] = int(registers[a] == registers[b])
return registers | bc25cefd642f3fbc2d4aebb1217e4477bdf5b2ce | 625,019 |
import sys
def python_info():
"""Returns Python data.
"""
return {
'version': '%s.%s.%s-%s%s' % sys.version_info,
'executable': sys.executable,
'path': sys.path
} | 74ec42c1f5ba9796f723792b68f922f4e42981f0 | 625,020 |
import os
import shutil
def save_structure_to_subdirectory(args):
""" Save structure data to its intermediate subdirectory, under a custom
prefix.
Inputs:
args['structure_edges']: the data's uri to save to /outputs
args['prefix']: prefix to add to the new filename. Currently u... | 3cf072f7e571ded3fbe56b70ed91586158e0bcbe | 625,022 |
def oi_to_args(issues):
""" Return a set containing all arguments in the list of open issues."""
res = set()
for i in issues:
res &= set(i.arguments)
return res | 17b3568def4e679a606ab6c715d8a37a778b1487 | 625,023 |
import hashlib
import os
def make_filename_from_sop(sop):
"""Turn a SOPInstanceUID into a filename
Expects sop to be a Unicode string
"""
md5 = hashlib.md5()
md5.update(sop.encode())
digest = md5.hexdigest()
# path = "{}/{}/{}/{}.dcm".format(
path = os.path.join(
digest[:2],
... | a349d6c903d1a70ced4f098196895941d67b6d49 | 625,024 |
def isValidPositiveInteger(number):
"""
Check if number is valid positive integer
Parameters
----------
number : int
Returns
-------
bool
Author
------
Prabodh M
Date
------
29 Nov 2017
"""
if isinstance(number, int) and number > 0:
return Tru... | 0f8524a00b5d69436f8c2208b4b5b42702e72b01 | 625,025 |
def to_int(value: str | None) -> int | None:
"""Safely convert string value to int."""
if value is None:
return None
try:
return int(value)
except (ValueError, TypeError):
return None | ea64f96fdcc2317283ed9359ea6d5110dde1fc46 | 625,026 |
def normalize(img):
"""
For the implemented model, normalization is not required. Keeping this function empty.
"""
return img | dd6e5b2effe2d9ba0c882e94120267c3eaef1e98 | 625,027 |
def smart_truncate(text, limit=100, suffix='...'):
"""
Truncates a text to the end of the last word before
reaching `limit`, and adds `suffix` to the end.
Since it is using Python's slicing, negative values
work, too.
:param text: <str>
:param limit: <int>
:param suffix: <str>
:ret... | 4b95d3b200f9e54adbb681f3db9206b3c5a9d7e6 | 625,028 |
import torch
def get_flat_weights(model):
"""Gets all model weights as a single flat vector."""
return torch.cat([p.data.view(-1, 1) for p in model.parameters()], 0) | b52586d5aa7a8eea7c1adcd89a1e7d9b4ea2ac3e | 625,029 |
def byte_to_string(byte_input: bytes, encoding="utf-8") -> str:
""" encoding """
return byte_input.decode(encoding) | 8b8e77667c638985bc87d752d174a0c029e6f1ca | 625,030 |
def _get_ftype_from_filename(fn, ext_unit_dict=None):
"""
Returns the boundary flowtype and filetype for a given ModflowFlwob
package filename.
Parameters
----------
fn : str
The filename to be parsed.
ext_unit_dict : dictionary, optional
If the arrays in the file are specif... | 6b76b4797312f045c8bd6673d3aa74128cafbde9 | 625,031 |
import os
def folder_size(path):
"""Return total size of a folder, including contents/subfolders."""
if not os.path.isdir(path):
return 0
total_bytes = 0
for entry in os.scandir(path):
if entry.is_dir(follow_symlinks=False):
total_bytes += folder_size(entry.path)
el... | 304435d9d631628d7d8d381d6b1a5e4760291a21 | 625,032 |
def ALYD(request):
"""Area, Length, Young, Density.
Group of common properties of structures using consistent units.
"""
return request.param | d71e538e24afc9bb75920d5abd51ce13f4b9c80c | 625,033 |
def QA_util_ms_stamp(ms):
"""
explanation:
直接返回不做处理
params:
* ms->
含义: 时间戳
类型: float
参数支持: []
return:
float
"""
return ms | 45e97ac56ee857d16feef115d49903f1eec6fbc8 | 625,034 |
import string
def entry_point_name_to_identifier(entry_point_name):
"""Transform an entry point name into an identifier suitable for inclusion
in a PyPI package name."""
try:
entry_point_name.encode('ascii')
ascii_name = entry_point_name
except UnicodeEncodeError:
ascii_name = ... | 9af3e32cd0095092e53ac21b78e8233ef377db06 | 625,035 |
def greatest_product_subarray(arr:list, subarray_len:int):
""" returns the subarray having the greatest product in the array and the greatest product
Args:
arr (list): list of integers
subarray_len (int): length of subarray
Returns:
(list,int): subarray,max product
"""
if s... | d0db3dd519fb88e2d1c491ce0766cf5b40ab2f3c | 625,037 |
def get_accounts(how_many=10):
"""Return list of account names."""
return [f'account-{i}' for i in range(how_many)] | 3b6dd6ce31bcc95b8fb4d4685d31668fba971192 | 625,038 |
import re
def standardizeLocation(s, dic):
""" Standardize Locations
Args:
s: string to standardie
dic: dictionary key= pattern, value = to replace with
Returns:
string: standardized string or not match original string
"""
for loc in dic:
if re.sea... | f361aef160cc4dc2a6da85fee2f7e8abf445aedb | 625,039 |
import math
def calculate_distance(psi, angle_in_degrees):
""" Calculate the distance the mudball flies. """
angle_in_radians = math.radians(angle_in_degrees)
distance = .5 * psi ** 2 * math.sin(angle_in_radians) * math.cos(
angle_in_radians)
return distance | 4e60a9afa1289d0bb3eaa3ae37bc10239d40c044 | 625,040 |
def get_descriptive_adjectives(tree, gender):
"""
Returns a list of adjectives describing pronouns for the given gender in the given dependency tree.
:param tree: dependency tree for a document, output of **generate_dependency_tree**
:param gender: 'male' or 'female', defines which pronouns to search f... | 9ce632d1a8d5a9b2cb5f53305acabd9d45ae8acb | 625,041 |
def confirm(prompt):
"""
Get user confirmation from standard input.
Parameters
----------
prompt: str
The message to show.
Returns
-------
True or false depending on whether the user has answered with yes or no.
"""
answer = ''
while answer.lower() != 'y' and answer.... | 61e9cd6f3626b3fe88cb8ebbf39e5fda7d3e859f | 625,042 |
import torch
def get_latent_embedding(model, data_loader, num_classes, device):
"""
Computes the latent embedding, i.e. z for each element of a dataset. The corresponding z values are directly
organized by classes, such that they can readily be used for visualization purposes later.
Parameters:
... | e10f9f82c3ddc45a7b5d7cc21fd67e78b952e4e4 | 625,043 |
def numerical_filter(df, filter_):
"""
Compute an boolean condition setting which rows of DataFrame `df` should remain based on
the numerical filter defined in the dict `filter_`.
:param df: Pandas DataFrame containing core data
:param filter_: Dictionary defining the filters
:return: condition... | 5ddb5deef0a467256c4c2fbf74df20d826528261 | 625,044 |
def sum_atomic_map(atomic_map: dict) -> dict:
"""Optimized for summing the values within a polar strength map."""
atomic_map_values = atomic_map.values()
if len(atomic_map_values) == 0:
raise IndexError("The atomic map must have length greater than zero.")
# sum and round the countable values
... | 295325831ad942302c9160e0144eb7854cdb7748 | 625,045 |
def listAppend(list:list,appendObj):
"""Syntatic sugar. This appends the obj to the list and returns it."""
if appendObj: list.append(appendObj); return appendObj | 23abab209e4ab2b1fc668355c1b366b9908024a5 | 625,046 |
def mult(x, y):
"""docstring"""
return x, y | a1bbbac51f1db10d4a2782c9417c7fde3c5320a7 | 625,047 |
def lunit():
"""In : None.
Out: {""} (a language : a set).
"""
return {""} | 00f524bb909d45a52d177714da927d74603049b2 | 625,048 |
def win(word_list):
"""
Check the user has guessed the right word or not.
Arguments:
word_list -- the word list.
Returns:
True/False -- return True if the word has been guessed right alse return false.
"""
if '_' not in word_list:
return True
else:
return... | 7bb8dd7be145aa323f69798679ce829140731817 | 625,049 |
import torch
def compute_bpp(prob: torch.Tensor, num_pixels: int, batch_reduction='mean'):
""" bits per pixel
Args:
prob (torch.Tensor): probabilities
num_pixels (int): number of pixels
"""
assert isinstance(prob, torch.Tensor) and prob.dim() == 4
p_min = prob.detach().min()
i... | e84c50383b55030b937c06b6772fba1cd94959ba | 625,050 |
import numpy
def calc_inverse_d_by_hkl_abc_cosines(h:float, k:float, l:float,
a:float, b:float, c:float,
cos_alpha:float, cos_beta:float, cos_gamma:float):
"""
Calculate 1/d for given reflections h, k, l
and unit cell parameters defined as a, b, c, cos(alpha), cos(beta), cos(gamma).
... | 6756bf4bcbcffa5e6c031c712b399c247763f97e | 625,051 |
import torch
def GlobalAvgPooling(x):
"""
Input: (batch, channels, height, weight)
Output: mean, (batch, channels)
"""
b, c, h, w = x.shape
x = x.view(b, c, h*w)
mean = torch.mean(x, dim=2)
return mean | 68e7ad05cf2ddc9cb9c8b851dfc3893b171f0cff | 625,052 |
def abbr_longstr(dc, text, w):
"""ClientDCを使って長い文字列を省略して末尾に三点リーダを付ける。
dc: ClientDC
text: 編集対象の文字列
w: 目標文字列長(pixel)
"""
if w <= 0 and text:
if dc.GetTextExtent(text)[0] <= dc.GetTextExtent(u"...")[0]:
return text
else:
return u"..."
width = dc.GetTextEx... | 2e3bd8b3fd76ac47f82e1abf808ebc4039f53161 | 625,053 |
def adjust_learning_rate_poly(optimizer, initial_lr, iteration, max_iter):
"""Sets the learning rate
# Adapted from PyTorch Imagenet example:
# https://github.com/pytorch/examples/blob/master/imagenet/main.py
"""
lr = initial_lr * ( 1 - (iteration / max_iter)) * ( 1 - (iteration / max_iter))
if ... | b2186ff54b0d9caef5883073b501538b3cf4ebaf | 625,054 |
def epc_calc_hdr(reg_dict):
"""
Returns True if high dynamic range is enabled, False otherwise
Parameters
----------
reg_dict : dict
The dictionary that contains all the register information
Returns
----------
bool
True if HDR enabled, false otherwise
"""
hdr_en... | 257c05cbd6d85a733409faa76b29954d2cf0a1b5 | 625,055 |
def revisar_opciones(args):
"""
Verifica que el usuario halla usado las opciones de linea de comandos corretamente
----
regresa
str => ruta del archivo smaps
"""
if not (args.smap or args.pid) : # No utilizo ninguna opcion
print("Utilize al menos una de las opciones:")
prin... | 1cebdcc4fcf817edda34fc6da0cc09c8f21c3e2e | 625,056 |
def get_image_urls(post):
"""Returns a list of URLs for all images in a scraped Post object"""
image_urls = {key: val for key, val in post.flat_json_dict.items() if "display_url" in key}
return list(set(image_urls.values())) | 9eb09a0988deb33be4a765732a519c6c77be56fe | 625,057 |
from typing import Callable
def _get_runname(
func: Callable) -> str:
"""Return run name from function.
Args:
func (Callable): target function.
Return:
runname (str): run name string.
"""
return '.'.join([func.__module__, func.__name__]) | c16a9b1407817536f6f523b79f6a75f449032d38 | 625,058 |
def get_failed_conditions(conditions):
"""Get a comma separated string for the conditions that failed."""
if conditions is None:
return ''
return ', '.join([c.condition.name for c in conditions if not c.nominal]) | 6b329333d10305cb21dbc11254221e6737f342f5 | 625,060 |
import re
def parse_html(html):
""" 解析页面信息, 顺便保存商品图片"""
info = []
l = re.findall("<a title=(.*)</li>", html)
for i in l:
single_info = []
# 商品标题
tilte = re.findall('"(.*)" ddclick=', i)
tilte[0] = tilte[0].replace(",", "")
single_info += tilte
# 商品链接
... | bb71d11ab60d583ec0d0f787c24cf2821863fdf1 | 625,061 |
import math
def fit(s, prop):
""" A fit made to the reflectance vs absorption coefficient from the data
set.
"""
P = 0.019892974 * math.e ** (-0.651220312*s)
prop.s.append(s)
prop.Ps.append(P)
return P | 12fb8231ec8707e2b3fb44927652edc8ff229c16 | 625,062 |
def hidden() -> str:
"""A command that is hidden from the default help command."""
return "Suprise" | fc3ad23f7cd515d077c29d1a1aa695c5b89ac8c7 | 625,063 |
import click
import sys
import requests
import random
def suggest_recipes():
"""
Get suggested a random meal recipe from theMealDB API.
"""
click.echo("Categories: American, British, Canadian, Chinese, Dutch, Egyptian, " +
"French, Greek, Indian, Irish, Italian, Jamaican, Japanese, Kenyan, Ma... | 011367908365e941dacbbf71163b5cc94906bea3 | 625,065 |
def get_uniprot_secondaries(uniprot_result):
"""
Get secondary accession identifiers from UniProt text result
:param uniprot_result:
:return:
"""
accession_lines = [l for l in uniprot_result.split('\n') if l.startswith('AC')]
secondaries = []
for ac_line in accession_lines:
secon... | bca4cced24d2aa8f1200aee7d4bf0f05c5913bb3 | 625,066 |
import yaml
def read_config(yaml_in):
""" Convert YAML config file into dictionary """
with open(yaml_in) as f:
return yaml.safe_load(f) | 24a45aee350e9ac038fdc697f5b3dd5c8759a6bf | 625,067 |
def clean_missing_exports_long(exports, fill_na_value=0):
"""Clean the exports data in long format by removing records with missing
product code and then filling missing values with fill_na_value
(which is 0 by default).
"""
return (exports.dropna(subset=['product_code'])
.fillna(... | 3f92b092cb4a6cae6e13945b0e1a6389cc6b3e34 | 625,068 |
def transit_x_axis_intercept(px: float, py: float, ox: float, oy: float) -> float:
"""Given an object at position px, py and an observer as ox, oy this returns the
value on the x axis of the transit line."""
x = px + py * (ox - px) / (py - oy)
return x | 0903547003586cfa87718adf6a279ece4a065120 | 625,069 |
import re
def truncate(text, words=25):
"""Remove tags and truncate text to the specified number of words."""
return ' '.join(re.sub('(?s)<.*?>', ' ', text).split()[:words]) | 42cc1f0520a92a6bcbc46501e37dcb6832d8f93f | 625,070 |
import re
def parseTimeControlTag(tag):
"""
Parses 'TimeControl' PGN header and returns the time and gain the
players have on game start in seconds
"""
match = re.match("^(\d+)\+?(\-?\d+)?$", tag)
if match:
secs, gain = match.groups()
return int(secs), int(gain) if gain is not ... | af528426cb91893bc995c0a42b5d26e081a7b10c | 625,072 |
def count_distinct(collection, key, exclude=None):
"""Get the number of distinct values for key in the specified database collection"""
values = collection.distinct(key)
if exclude is not None and exclude in values:
values.remove(exclude)
return len(values) | 894428df0a3d913963c33ce2940c01305a5b700e | 625,073 |
def make_qs(listname: list) -> str:
"""Create a list of '?'s for use in a query string.
This is a convenience function that will take a list and return a string
composed of len(list) queston marks joined by commas for use in an sql
VALUES() clause.
Args:
listname: The... | 94468ea155d87935ed9df9bf3abea939b2673f20 | 625,074 |
import re
def filter_text(text):
""" Filter out retweet-prefix, urls, html-codes, hashtags, handles, and extra whitespaces
:param text: a string
:return: cleaned text
"""
return re.sub(
r'(RT @\S+:)|(RT)|(https?:\S+)|(&\S+;)|(@\S+)|(#\S+)', '',
text
) | d1b5763e62622ff3a8c87d0ade9b72b8e77ce55e | 625,075 |
from pathlib import Path
def create_hdf_dir(experiment_dir: Path, create_on_work: bool = False) -> Path:
"""
Create a directory in which the HDF results files for an HSR
experiment can be stores and return the Path to the directory.
.. attention::
Unless you are working on the MPI-IS cluster ... | 6cb9c2731cba53e033b4c248f68b09f2246abb62 | 625,076 |
import glob
import os
def delete_fits_from_folder(fits_dir):
"""
Deletes the FITS files from fits_dir
:param fits_dir: The dir containing the FITS files
:return: True if successfully removed else False
"""
fits_files = glob.glob(os.path.join(fits_dir, "*.fits"))
if fits_files:
for ... | fff2cbbca10091569b7bd51b837c30558acc216a | 625,077 |
def strategy_best(cookies, cps, history, time_left, build_info):
"""
The best strategy that you are able to implement.
"""
return None | bb24ffab8f0d8c239af608ca53001ff6d67d2e56 | 625,078 |
import requests
import re
import shutil
def download_image(url):
"""Download an image given the url"""
response = requests.get(url, stream=True)
content_disposition = response.headers["content-disposition"]
match = re.search(".*filename=?(\S*)", content_disposition)
if match:
filename = ma... | 027a0ceb0425f22bcd84ca87982bac0ddcb5dffd | 625,079 |
import numpy
def evalg(m, d, a, b, rho, wvno, om):
"""Layered half space problem for Rayleigh-wave."""
gbr = numpy.zeros(5, dtype=numpy.complex_)
wvno2 = wvno * wvno
om2 = om * om
# Set up halfspace conditions
xka = om / a[m]
xkb = om / b[m] if b[m] > 0.01 else 0.0
ra = numpy.sqrt(wvn... | 83e8d9601edc34da69cc732540b2e0ea1f03bec8 | 625,080 |
import glob
import os
import logging
def bag_file_exists(bag_path):
"""
Check if the bag file are present
:param bag_path: Location of the folder containing ROS bag
"""
files = glob.glob(os.path.join(bag_path, "*.bag"))
if files:
for bag in files:
logging.info("Bag found a... | bb82d407e07a8fda0f4e24c895f57901597c58d7 | 625,081 |
def foundToken(s, loc, toks):
"""
PyParsing action to run when a token is found.
:returns: Token as a string
"""
#print 'found token', toks.dump()
#print 'returning the token', toks.token
return toks.token | cff35d798c6830a32931efc184bb87cd0d102fe3 | 625,082 |
def requires_replacement(changeset):
"""Return the changes within the changeset that require replacement.
Args:
changeset (list): List of changes
Returns:
list: A list of changes that require replacement, if any.
"""
return [r for r in changeset if r["ResourceChange"].get(
... | 6f58f9428845df630cec287f54b749cc87a489d4 | 625,085 |
def ctrl_selector(t, observation, action_manual, ctrl_nominal, ctrl_benchmarking, mode):
"""
Main interface for various controllers.
Parameters
----------
mode : : string
Controller mode as acronym of the respective control method.
Returns
-------
action : : array of shape ``[d... | 73670094f3af73df5c4feb4c18b0ae2b50f81d96 | 625,086 |
def is_ordered_permutation(perm):
"""
Check if the permutation is ordered.
:param perm Tuple
Tuple of sentence indices, e.g. (1,2,5)
"""
return all(perm[i] < perm[i+1] for i in range(len(perm)-1)) | 5346a4971c4b588db28fb1ce05a82c81d0a35ac8 | 625,088 |
import sqlite3
from typing import List
def get_columns(conn: sqlite3.Connection) -> List[str]:
"""Get column names in the order just like it is returned from the DB.
:param conn: Connection to the database
:type conn: sqlite3.Connection
:return: A list of column names in the database.
:rtype: Lis... | 0a77342e40f9f80f7ac62b3767fd7e93913a3ef5 | 625,089 |
import math
def round_repeats(repeats, global_params):
"""Round number of filters based on depth multiplier."""
multiplier = global_params.depth_coefficient
if not multiplier:
return repeats
return int(math.ceil(multiplier * repeats)) | 76f47f5ae407d252fc4343acfdbfe1c158b812dd | 625,090 |
import socket
def daemon_exists(host, port):
"""
Returns true if the daemon is running.
"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
try : sock.connect((host, port))
except: return False
return True | 72423f8dcfdffb94b0a2b1e75031295eea0317f0 | 625,091 |
import re
def build_parameter_column_names(number_of_ports=2,format="RI",parameter="S"):
"""Return a list of column names based on the format and number of ports. Enter
number_or_ports as a integer and format as text string such as 'RI','MA' or 'DB'"""
column_names=["Frequency"]
prefix_1=""
prefix... | d8b2b8c611e07985ae74ad2d4ed391bfd119e380 | 625,092 |
def separate (spamlist):
"""
separate list items with a comma and space
Args: (list spamlist)
Return: list separated by comma and space
"""
result = ', '.join(spamlist) #takes items in a iterable and joins the into one string
return result | 5b1767519b34853c9de0c5093e9c65bfe68c9b5d | 625,093 |
def search_types(results: dict):
"""
Convert Elasticsearch results into RPC results conforming to the
"search_types" method.
"""
# Convert the ES result format into the API format
search_time = results['search_time']
type_counts = results['aggregations']['type_count']['counts']
type_to_c... | 62b1b21dc5366ecf424754bed760e2e52c8e8099 | 625,094 |
import pandas
def _try_to_numeric(x):
"""Wrapper around :func:`pandas.to_numeric` that returns
the input unaltered if it's a string or another non-numeric type.
In the use case when some of the elements are not numeric, e.g.
``S001,00200,S003``, make sure none are converted. This:
_try_to_nume... | 870933bbaeaff09ce6f2bb3549aaeaba6d2a9c33 | 625,096 |
def get_spawn_weight(mod, tags):
"""
Calculates the spawn weight of the given mod for the given tags.
Parameters
----------
mod : DatRecord
The mod to calculate the spawn weight for.
tags : list[str]
List of applicable tag identifiers.
Returns
-------
int
C... | 508cc49e2f68d27492989e7acb81c874f2de4a4d | 625,098 |
def instance_matches_data():
"""Confirm that all arg_set_list in a dictionary is present in an instance"""
def _does_instance_match_data(instance, data):
err_list = {}
for field in data.keys():
# Common error types
try:
if not hasattr(instance, field):
... | e8c3dfc36194e74b77dfcf5a24ecca7ea7e207aa | 625,099 |
def humantime(ms):
# Docstring
"""
Converts timespan in milliseconds to a humanly readable string.
--------------
ms : int or float
Time in milliseconds
--------------
Examples :
>>> humantime(194159)
'3 min, 14 sec, 159 ms'
"""
time_dict = {'ms' : ... | c381cbc30c882f5bbe3ddf7ba1668b8a2211bb31 | 625,101 |
import sys
def _is_unbound_present(item_obj, filterset):
"""
Returns True if item_obj is a bound method and that its unbound version is in filterset
:param item_obj:
:param filterset:
:return:
"""
if sys.version_info >= (3,):
# Python 3
not_bound_fct = getattr(item_obj, '__... | 0061f9335bc33b953d75ef82867c984f0f9fab57 | 625,102 |
import torch
def calculate_dihedrals(p, alphabet):
"""Converts the given input of weigths over the alphabet into a triple of dihederal angles
Args:
p: [BATCH_SIZE, NUM_ANGLES]
alphabet: [NUM_ANGLES, NUM_DIHEDRALS]
Returns:
[BATCH_SIZE, NUM_DIHEDRALS]
"""
sins = torch.s... | 381add4de653ba30b1049248666296520530a539 | 625,103 |
def find_pivot_index(nums):
"""
Suppose a sorted array A is rotated at some pivot unknown to you
beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element. NOTE: The array will not contain duplicates.
"""
min_num = nums[0]
pivot_index = 0
left = 0
right =... | ecfc5c3202d65d206a1d80b3aaec8de890c8b9b0 | 625,104 |
def getMonthString(my_list):
"""Given a list of months creates the string representing the sequence"""
if not isinstance(my_list, (list, tuple)):
my_list = [my_list, ]
dic = {
1: 'JANUARY', 2: 'FEBRUARY', 3: 'MARCH',
4: 'APRIL', 5: 'MAY', 6: 'JUNE',
7: 'JULY', 8: 'AUGUST', 9:... | c9639ec1191d062604f85e4cd0bc0fb29d239dd3 | 625,105 |
def constant(name: str) -> object:
"""Return a placeholder singleton with its own type.
Multiple calls with the same name return the same value.
For example:
```
def get_item(dictionary, key, default=constant("not_passed")):
if default is constant("not_passed"):
return dictiona... | 0032a7b8979290c38c7bbbf8f2768cd3d780c2b8 | 625,106 |
def s3_md5(s3key, blocksize=65536):
"""Hexadecimal md5 hash of a file stored in Amazon S3"""
return s3key.etag.strip('"').strip("'") | d0d0258001fab054d26854526213015987d46bb2 | 625,108 |
import os
def counting_number_of_files(path):
"""
Count the number of data files in the folder.
"""
count = 0
for f in os.listdir(path):
if os.path.isfile(os.path.join(path, f)):
count += 1
return count | 432f45dd91a201e573bf9542be81779cad1b795f | 625,109 |
def all_type(dataframe):
"""
Find all availble EV connector types in column ['EV Connector Types']
Attributes
--------------------------
dataframe: DataFrame
The DataFrame to deal
Return
--------------------------
type_dict: dict
A list of all availible connector types
... | 76907de262e9120959524a87a348a80eab1c3dfb | 625,110 |
def encode_string(node, encoding_string = None, codes = None):
"""
store the codes in a string
left branch is 0, right branch is 1
return False if tree (node) does not exist
"""
if not node:
return False
if codes is None:
codes = {}
if encoding_string is None:
en... | 459b47b747ba7e91f413de7b6ce5f0da999ef2a0 | 625,111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.