content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def interpolate_image_at_mask(
*, image, bad_msk, maxfrac=0.90, buff=4,
fill_isolated_with_noise=False, weight=None, rng=None, iso_buff=1,
):
"""
interpolate the bad pixels in an image
Parameters
----------
image : array
the pixel data
bad_msk : array
boolean array, True... | 2b0d1f8fde2a5b8bb09c56e0521fe8982e5efc68 | 3,603,200 |
from typing import List
def weave_helper(first: List[int], second: List[int]) -> List[List[int]]:
""" Does the recursion to find the weaving of the ramaining
of the list excluding the first char of the first list """
sufix_weaving: List[List[int]] = weave(first[1:], second)
result: List[List[int]] = []
for wea... | d0ef6390b836d80be195ff455e96190d27509f9a | 3,603,201 |
from typing import Sequence
def compute_offset_slots(start_slot: Slot, end_slot: Slot) -> Sequence[Slot]:
"""
Return the offset slots that are greater than ``start_slot`` and less than ``end_slot``.
"""
return [Slot(start_slot + x) for x in SHARD_BLOCK_OFFSETS if start_slot + x < end_slot] | 8750385aae199c5bf5371604615cca9ebecd5a06 | 3,603,202 |
import re
import json
def resolve_type(session: Session, link: str) -> ProductType:
"""
Given a link, it will return the ProductType
"""
if not re.search('bookrags.com', link):
return ProductType.UNKNOWN
try:
page = session.get(link).text
json_raw = re.search(
'... | 814733595e9eacd824681ad981265ded80370523 | 3,603,203 |
def material():
"""Factory associated with Elasticity.
"""
return Elasticity() | eeb0c30a2644348244801f88aca1aa5a4f5280ea | 3,603,204 |
import time
def get_spam_score(
message: Message, email_log: EmailLog, can_retry=True
) -> (float, dict):
"""
Return the spam score and spam report
"""
LOG.d("get spam score for %s", email_log)
sa_input = to_bytes(message)
# Spamassassin requires to have an ending linebreak
if not sa_... | 81e7d5535a375231bc53dea85b418b326eb0375c | 3,603,205 |
def changeArc(G, i ,j):
"""
change statistic for Arc
"""
return 1 | 90b33be8ac87a67362b43185e688e8fdff218e64 | 3,603,206 |
def normalize_numbers_in_sent(sent, remove_pos=False, never_split=None):
"""
Given a sentence, perform preprocessing and normalize number words to digits.
:param sent: sentence (str)
:return: a list of normalized words from the sentence
"""
out_words = []
words, sigfigs = preprocess(sent, re... | 7c306598dd0b35a3b1f341582ebaa9bfab49c0ba | 3,603,207 |
def compute_expires_at(ipn):
"""
Compute the expiration date of the payment.
:param ipn: the ipn object
"""
for key, value in PREMIUM_IDS.iteritems():
if ipn.item_number == value:
number_of_months = int(key.replace("p", "").replace("f", ""))
break
else:
... | 8a49f0549bb4591d6f496580a4d44ca94d322e85 | 3,603,208 |
def test_override_secrets_using_fn():
"""
Just another way for overriding KEYS method
"""
with mock.patch('awsvault.core.boto3') as boto3:
boto3.client().get_secret_value.return_value = AWS_SECRETS_MOCK.get("DATABASE")
def override(name):
if name == 'DB_PASS':
... | 6e4c76bd9db834b917fb010f7f87b9309d47159b | 3,603,209 |
import logging
import time
def get_time_range_for_stage(user_id, stage):
"""
Returns the start ts and the end ts of the entries in the stage
"""
curr_state = get_current_state(user_id, stage)
if curr_state is None:
start_ts = None
curr_state = ps.PipelineState()
curr_state... | 5bf71aedfbdcfad72d37ce2e33580df3e6438abd | 3,603,210 |
def eval_input_fn(data, batch_size):
"""An input function for evaluation or prediction"""
inputs = None
try:
# If there are labels, then we evaluate
features, labels = data
inputs = (dict(features), labels)
except:
# If there are no labels --> prediction
inputs ... | 4186bd22b6d3064198df58954e6773c46661c03b | 3,603,211 |
def browser_key_press_h(key_1="", key_2=""):
"""Type text using Browser Helium Functions and press hot keys.
Args:
key_1 (str): Keys you want to simulate or string you want to press
Eg: "tab" or "Murali". Defaults: ""
key_2 (str, optional): Key you want to simulate with combination to k... | 248973d646a49bf3b8ac059ac9e9cd4baf57ad4d | 3,603,212 |
def _jq_format(code):
"""
DEPRECATED - Use re.escape() instead, which performs the intended action.
Use before throwing raw code such as 'div[tab="advanced"]' into jQuery.
Selectors with quotes inside of quotes would otherwise break jQuery.
If you just want to escape quotes, there's escape_quotes_if... | 3c46caa1a02798a7b8539a92a6b68f29e3dcd63c | 3,603,213 |
def corrupt_single_entity(triple: tf.Tensor, all_triples: tf.Tensor,
max_entity_id: int,
head_corrupt_prob=0.5,
debug_head_corrupted=None,
debug_tail_corrupted=None,
name=None):
""" Rand... | 8094290e4136a798882e633f8a7a599a57a1e58b | 3,603,214 |
import yaml
def get_access_token_yaml(token_yaml):
"""Utility function to read in access token yaml
Parameters
----------
token_yaml: str
Path of the token yaml file
Returns
-------
dict
Dicitonary with the access token parameters
"""
try:
with open(token_... | 39d98c9f08a9e7ee4690986d40f5252c8775006d | 3,603,215 |
def initial_policy(observation):
"""A policy that sticks if the player score is >= 20 and his otherwise
Parameters:
-----------
observation:
Returns:
--------
action: 0 or 1
0: STICK
1: HIT
"""
return 0 if observation[0] >= 20 else 1 | 03e6cf5deb5dded598cb625fb68ad98cf3f356cc | 3,603,216 |
from bs4 import BeautifulSoup
from datetime import datetime
import os
def __db_upsert(session: scoped_session,soup: BeautifulSoup, t_search: TSearch, ranking: int, max_ranking: int,search_time: datetime, my_url: str, wordjoin: str) -> int:
"""DB登録更新処理
得られた検索結果をスクレイピングし検索結果をDBに登録する処理をおこなう
Parameters
... | 6c8516c228523a2e5f06467ca0d4ff594de4df09 | 3,603,217 |
def _make_path_tree(basepath, path):
"""
Return a list of paths leading to the destination path.
:param basepath: Base path to search under. MUST begin with a '/'.
:param path: Path to search for.
:returns: Tuple of (full path, list of paths from root level to the given path)
Tests::
... | 660fbb21378d8596b6ddf1f427cd180121a1395c | 3,603,218 |
import codecs
import os
def fetch_data(cand, ref):
""" Store each reference and candidate sentences as a list """
references = []
if '.txt' or '.en' in ref:
reference_file = codecs.open(ref, 'r', 'utf-8')
references.append(reference_file.readlines())
else:
for root, dirs, files... | a72bce7f54ba93773425ae15081ea34b0be33f4e | 3,603,219 |
from typing import List
import aiohttp
async def fetcher(
urls: List[str],
output=False,
task_per_second: int = 1000,
forbidden_max: int = 10,
output_number: int = 100,
):
"""
Main function to run the programs here with default parameters, etc...
I don't think that this is even a nesse... | 27e33dad9db08e4b554ad35c7bf72a170391a7d0 | 3,603,220 |
def levinson_durbin(r, order):
"""
from http://aidiary.hatenablog.com/entry/20120415/1334458954
"""
a = np.zeros(order + 1)
e = np.zeros(order + 1)
# k = 1
a[0] = 1.0
a[1] = - r[1] / r[0]
e[1] = r[0] + r[1] * a[1]
lam = - r[1] / r[0]
for k in xrange(1, order):
# upd... | f58918eff73d8055ab430c373bbc368876653434 | 3,603,221 |
def transform_action_space(env_name_or_creator):
"""Wrapper for gym.Envs to have their action space transformed.
Args:
env_name_or_creator (Union[str, Callable[]]: String specifier or
env_maker function.
Returns:
Type[TransformedActionSpaceEnv]: New TransformedActionSpaceEnv cl... | cd644b6f04b0a1335a66b21b58d17b6aab02042b | 3,603,222 |
import urllib
import json
def geocode (street, house_number, house_letter, city):
"""Geocoding with Kartverket Matrikkel/Vegnavn REST service"""
# time.sleep(1)
if house_number:
if street[-1] == "-": # Avoid Kartverket bug
street = street[0: len(street) - 1]
if ":" in street:
street = street.replace("... | 2574f760c6e198f94b4dee6b9d8926d094a20953 | 3,603,223 |
from typing import Type
def test_option_plan_to_policy():
"""Tests for option_plan_to_policy()."""
cup_type = Type("cup_type", ["feat1"])
plate_type = Type("plate_type", ["feat1", "feat2"])
cup = cup_type("cup")
plate = plate_type("plate")
state = State({cup: [0.5], plate: [1.0, 1.2]})
de... | 5d3082e8a7e6bd3bffb2397be2a312689c62f27c | 3,603,224 |
import turtle
def getturtle() -> turtle.Turtle:
"""Return the Turtleobject itself.
No argument.
Only reasonable use: as a function to return the 'anonymous turtle':
Example:
>>> pet = getturtle()
>>> pet.fd(50)
>>> pet
<turtle.Turtle object at 0x0187D810>
>>> turtles()
[<tur... | da45c4ae8d1b8291c5bfd6a556d45ffc0f2bff0d | 3,603,225 |
def get_behavior(name):
"""Returns an instance of the given behavior."""
return Behavior.get_behaviors(name)() | 9e62f8c4d514b4c54b39b7884259f9f7ff49b628 | 3,603,226 |
def schwartzberg(poly):
"""
Alterantive name for the Isoareal Quotient
"""
return iaq(poly) | fb48b20e115b6fa8f4e4b8a559afeb24cbe9792a | 3,603,227 |
def _kde_support(data, bw, gridsize, cut, clip):
"""Establish support for a kernel density estimate."""
support_min = max(data.min() - bw * cut, clip[0])
support_max = min(data.max() + bw * cut, clip[1])
return np.linspace(support_min, support_max, gridsize) | 52711f45f0b8f2e430b708babd56210f2686dbb8 | 3,603,228 |
def get_exact_ijs_(f, parallel=True, verbose=False, backend="loky"):
"""
Takes the metric f and returns the function get_exact_ijs(f,X,IJ), which
calculates the distances between pairs given in array IJ.
Parameters
----------
f: function
The metric. Takes two points from the data set an... | 97e748d5c4bcdc3b3d5cc32e3dba1e1417077989 | 3,603,229 |
from typing import Optional
from typing import Sequence
def get_function_scaling_policy(function_id: Optional[str] = None,
policies: Optional[Sequence[pulumi.InputType['GetFunctionScalingPolicyPolicyArgs']]] = None,
opts: Optional[pulumi.InvokeOptions] =... | 2ef0d899080a858cd7a507dcc90a1447d50db305 | 3,603,230 |
def identity_block(inputs, filters, name, strides=1, training=True):
"""
resnet卷积块
:param inputs: 卷积块的输入
:param filters: 卷积核的数量
:param name: 卷积块名字相关
:param strides: 为1时候不改变特征层宽高,为2就减半
:param training: 是否是训练模式
:return : x
"""
filter1, filter2, filter3 = filters
x = layers.Con... | 2092cf79c7c43fe7fc999fa673b224df4599d336 | 3,603,231 |
from openeo_udf.api.datacube import DataCube
def datacube_from_file(filename, fmt='netcdf') -> 'openeo_udf.api.datacube.DataCube':
"""
Converts source files of different formats into openeo_udf.api.datacube.DataCube in memory
:param filename: the file on disk
:param fmt: format to load from
:... | 8fbe04b399cd718c00f67bbde187cdacbbc24537 | 3,603,232 |
import functools
def read_tf_records(batch_size, tf_records, interleave=True):
"""
Args:
batch_size: batch size to return
tf_records: a list of tf_record filenames
interleave: iwhether to interleave examples from multiple tf_records
Returns:
a tf dataset of batched tensors
... | 3ed3dde9db3ff0e6527eb93da875c3cc868088b2 | 3,603,233 |
def score_distribution(num_players, difficulty = Difficulty.MEDIUM):
"""Return a list of score distributions given the number of players and the difficulty."""
#initialize scores list
scores = []
for i in range(num_players,0,-1):
scores.append(i)
#adjust scores so its average is the same as other... | fa21a1bfe4684f16e9c680ada677b9a764b08063 | 3,603,234 |
import torch
def glu(x: torch.Tensor, dim: int = -1):
"""Generalized linear unit nonlinear activation.
Expects 2*n_units-dimensional input.
Half of it is used to determine the gating of the GLU activation
and the other half is used as an input to GLU,
"""
return nn.functional.glu(x, dim) | 45042030ffbf03908e8431c016ad9d0b7fa4ce67 | 3,603,235 |
def serial_christie_lamp_status(connection):
"""Build the lamp status list for a Christie projector
This list has format [(lamp1_hours, lamp1_on), (lamp2_hours, lamp2_on)]"""
connection.reset_input_buffer()
# Get lamp hours
l1_hours_response = serial_send_command(connection, "(LPH?)", char_to_rea... | 353f1286cdd74bce8aa1078c93a17f7b4b8508d9 | 3,603,236 |
def entropy_shannon(signal):
"""
Computes the shannon entropy. Copied from the `pyEntropy <https://github.com/nikdon/pyEntropy>`_ repo by tjugo.
Parameters
----------
signal : list or array
List or array of values.
Returns
----------
shannon_entropy : float
The Shannon... | b469e4d9b0706324baa624528d7b279fc5a19cc4 | 3,603,237 |
import os
def get_datastore(request, job_id):
"""
Download a full datastore file.
:param request:
`django.http.HttpRequest` object.
:param job_id:
The id of the requested datastore
:returns:
A `django.http.HttpResponse` containing the content
of the requested artif... | 621a9e3f22f6a3e6ab4a8365b5312a8420fb4c21 | 3,603,238 |
def basic_xml_tree():
"""Basic XML tree used for testing."""
xml_tree = ET.Element("root")
xml_tree.text = "100"
xml_level_1 = [ET.SubElement(xml_tree, "leaf1"), ET.SubElement(xml_tree, "leaf2")]
return xml_tree | 553a98cc58c49627d56c1d24e5b47f5ec7417d64 | 3,603,239 |
import typing
def upgrade_database(
config: Config,
engine: Engine,
metadata: MetaData,
*,
revision: str = 'head',
module_name: typing.Optional[str] = None,
) -> None:
"""Upgrades the database schema to the chosen ``revision`` (default is
head).
"""
script = ScriptDirectory.fr... | f9313d0ce1899791f2056306751be801b0b18e77 | 3,603,240 |
def encrypt_decrypt(plaintext, key, decrypt):
""" Use a Vigenere cihper to encrypt or decrypt the message."""
# Convert the key into an array of offsets.
offset = []
if decrypt:
for i in range(len(key)):
offset.append(26 - (ord(key[i]) - ord_a))
else:
for i in range(len(k... | 7af986cdbc12a9e344a5f570265dfa89c0ff901b | 3,603,241 |
import ast
def parse(code, para, module):
"""Annotate user code.
Return annotated code (str) if annotation detected; return None if not.
code: original user code (str)
"""
global para_cfg
global prefix_name
para_cfg = para
prefix_name = module
try:
ast_tree = ast.parse(code... | 154a59d2b59cbc0ec603d022dc3d74060d090ca1 | 3,603,242 |
def compiler(program: list):
"""
Compiles a whole multiline program and returns the final result (current Register).
:param program: The whole multiline commands separated with \n as a string list.
:return: Returns the final program output.
"""
REGISTER.clear()
i = 0
while i < len(progra... | 6ce7ee11d6b834afa98b66bf9995021ba74dcae6 | 3,603,243 |
import time
import traceback
def withdraw(body):
"""
自动提现
:param headers:
:return:
"""
time.sleep(0.3)
url = 'https://ios.baertt.com/v5/wechat/withdraw2.json'
headers = {
'User-Agent': 'KDApp/1.8.0 (iPhone; iOS 14.2; Scale/3.00)',
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-... | 209469d986b24d488f09d0426517d02524fbc459 | 3,603,244 |
def parse_http_response(response):
"""Extract all triples from HTTP response object."""
logger.info("Extracting new information from HTTP request/response...")
# Prepare for parsing
request = response.request
triples = []
# Create new individual which becomes the subject of all triples
re... | 842d69422899f2a0e9dffb2e92ef9564e6ecde6e | 3,603,245 |
def kneeJointCenter(frame,hip_JC,delta,vsk=None):
"""Calculate the knee joint center and axis function.
Takes in a dictionary of xyz positions and marker names, as well as an index.
and takes the hip axis and pelvis axis.
Calculates the knee joint axis and returns the knee origin and axis
Markers ... | f1c9608455468843bb802914d5134ec994921475 | 3,603,246 |
def getOpenFileName(*args, **kwargs):
"""
Wrapper for the :func:`~PyQt5.QtWidgets.QFileDialog.getOpenFileName`
function, which automatically applies several standard options and makes
using filters easier.
%(optional)s
Returns
-------
filename : str
The filename that was chosen... | 20f0d074fb010e4b1548c591739ee595f91bff9f | 3,603,247 |
def get_log_km_brenda_blk(
posterior: Dataset, ec4: str, organism: str, substrate: str
) -> DataArray:
"""Get a DataArray of log kms for the brenda-blk model."""
# if substrate not in posterior.coords["substrate"]:
# substrate = "unknown substrate"
ec4_sub = f"{ec4}|{substrate}"
if ec4_sub not i... | de1ed23b2544aa8e3852ae9a63a00c5185e44632 | 3,603,248 |
def addDefaultArgs(parser, defaultLog="none"):
"""!Add default arguments common to all commands."""
parser.add_argument("--version", action="version",
version=f"Isle {isle.__version__}")
parser.add_argument("-v", "--verbose", action="count", default=0,
help="M... | b06877fa8b5aaa23b98458105bb38fa4f4c78214 | 3,603,249 |
import scipy
def preprocess_data(mat):
"""
This function is a Matlab rewritten function from
https://gitlab.stimulate.ovgu.de/christoph.reichert/visual-spatial-attention-bci
:param mat: matrix loaded with read_mat library
:return: features extracted from the specific file
"""
bci_exp = mat... | 52292a7c4e4815487093b11db49e618e4bc213b9 | 3,603,250 |
def wfg(P):
""" Speed of sound; [m / s]
saturation rise of"""
return region4.wfg(P) | 05fcb202138ad1b3e25c019c49b751c9f2e25171 | 3,603,251 |
import torch
def reduce_int_float(input_value, average, all_reduce, device):
"""Reduce an integer or float by converting it to tensor,
performing reduction and, finally, casting it back to the initial type.
"""
data_type = type(input_value) # save the original data type
tensor = torch.Tensor([i... | cc10f2d830821f24d71cb728e9bc20ea2bd2aa51 | 3,603,252 |
def create_OHE(df):
"""
Codifica los Cromosomas y los Alelos en OHE.
:param df: Pandas DataFrame con los datos de la petición.
:type df: Pandas DataFrame.
:return: Pandas DataFrame con los datos transformados.
:rtype: Pandas DataFrame.
"""
def isValue(x,i):
if x == str(i):
... | 92064dbb9937cdd2b4e4e24bb9f2d5e181d41e31 | 3,603,253 |
import math
def compute_decimal_val_for_fractional_num(digits, base):
"""Return the representation of a number in the base 10 system.
Parameters:
digits: str -- string representation of number (in given base)
base: int -- base of given number
Return: int -- integer representation of ... | f5f22e77bc028348b9a51687093b8f5bef936cb3 | 3,603,254 |
import argparse
def parse_args():
"""
Parse command-line arguments
"""
parser = argparse.ArgumentParser(description='Delete atmosphere level '
'files')
parser.add_argument('-l', '--log-level',
help='set logging level (default... | afe0cf0a744b0fcc77aeee07b26a900ef50fbea3 | 3,603,255 |
def send_limit_message(context: CallbackContext, chat_id: int, messages: dict) -> tuple:
"""
Send error message about unsupported platform
:param context: telegram context
:param chat_id: chat id with user
:param messages: dict with templates of messages
:param platform: platform name
:retur... | af6380cf6982ac2b24935f81afc957552f78e566 | 3,603,256 |
def compute_index(capacity, from_data_table=True):
"""Compute the index from the given capacity.
Strongly recommended: use the data table.
Can be done either from the computed capacities table or computed directly the from equations.
Parameters
----------
capacity: float
Capacity value... | 2f45f18cfa22cd0ac8e28efc2659c7fb018ca954 | 3,603,257 |
def load_ref_system():
""" Returns 5-trigonal-bipyramidal as found in the IQMol fragment library.
All credit to https://github.com/nutjunkie/IQmol
"""
return psr.make_system("""
P 0.0000 -0.0011 0.0000
Cl 0.0000 2.0091 0.0000
Cl 1.7511 -0.9... | 127f19c17905ad84cf4ff20c80432e4c488b56b7 | 3,603,258 |
from textwrap import dedent
import yaml
def load_yaml_from_docstring(docstring: str) -> dict:
"""Loads YAML from docstring."""
split_lines = trim_docstring(docstring).split("\n")
# Cut YAML from rest of docstring
for index, line in enumerate(split_lines):
line = line.strip()
if line.s... | e0178f98fc6a7fd607387bc4f4df90d127652b57 | 3,603,259 |
import random
def make_batch_pay_data(busi_type, client_tp):
"""
批量代付标识,预付卡业务不填
:param busi_type:
:return:
"""
if busi_type == "03":
batch_pay = ""
elif client_tp == "1":
batch_pay = "2"
else:
batch_pay = random.choice(["1", "2"])
return batch_pay | 28992bfe369f0befd3fc78022a2f1035174243c8 | 3,603,260 |
from typing import List
def make_prog(prog_path: str, c_files: List[File]) -> File:
"""
Compile one program from its source C files.
"""
o_files = [
compile(c_file)
for c_file in c_files
]
prog_file = link(prog_path, o_files)
return prog_file | 065791d168ec893c41020a50ce9d98d75864f87a | 3,603,261 |
from operator import concat
def factory(architecture):
"""get a model class
Args:
conf: the model conf
Returns:
a model class"""
if architecture == 'dblstm':
return dblstm.DBLSTM
elif architecture == 'leaky_dblstm':
return leaky_dblstm.LeakyDBLSTM
elif archit... | e7fbb09a1284942aac7b80b8c8f61a61727382da | 3,603,262 |
from pathlib import Path
import os
def clean(record: str) -> int:
"""
Clean up all cached data related to record.
:param (str) record: User-supplied record file.
:return: True if successfully cleaned; otherwise False.
:rtype: int
"""
counter = 0
for file in Path(os.getcwd() + "/cache... | bd0e48d35ab5a6fdf0a82d5a9b1ed81a404c600b | 3,603,263 |
def min_os_level(release):
"""
Usage::
class Tests (unittest.TestCase):
@min_os_level('10.6')
def testSnowLeopardCode(self):
pass
"""
return _unittest.skipUnless(
os_level_key(os_release()) >= os_level_key(release),
f"Requires OSX {releas... | 9985ac07eabe0f76e860cbbb5f2518f784cd861d | 3,603,264 |
import sys
def tree_command(args, packages=None, exit_on_failure=True):
"""Display dependency tree for a single package or the entire environment
:param args: Command arguments
:param packages: Collection of packages
:param exit_on_failure: Enable/disable exiting application on failure
:return: No... | 392d834ba7de0c39eeae094ee74fc71cd64a53e2 | 3,603,265 |
def user_info(username):
"""User info"""
user = get_user(login=username)
if user:
con, conn = connection()
con.execute("SELECT idnote, title, note_type FROM note_view WHERE creator_id = %s", escape_string(
str(user['iduser'])))
notes = con.fetchall()
con.execute("... | 8ba2a7d917c7d7aecd3a71d4343dca61e38a02e9 | 3,603,266 |
def chi_squared_homogeneity(*args, statistic: str = "likelihood_ratio"):
"""Chi-squared test for homogeneity.
Checks whether all data groups follows the same data distribution.
Assumptions:
None.
Test statistic:
The same statistics from the Chi-squared test for goodness of
fit... | 1b3506752a965e09f6611200f9b36be69f80c2f7 | 3,603,267 |
def read_data_from_mongodb(rack_name="all", unit='C'):
""" Read data from mongo db """
rack_data = RackData()
rack_temperature = RackTemperature()
raw_data_dict = rack_data.get_rack_temperature_data(rack_name)
if raw_data_dict is None:
return None
dict_data = {}
for rack_name in... | e1a564c59051ca103b2af0b089a0d0a8f120734b | 3,603,268 |
def list_steps(df, step_type=None):
"""
Function that finds and lists the step number(s) corresponding to a step type.
Or lists them if you specify nothing as second argument
ARGS :
- df [PANDAS.DATAFRAME] : your global rheology data
- step_type
* [STRING], has to be one of : 'amplitude... | 2bcb60c6adb5e757f51a9f7d3fee2b1a03506b8c | 3,603,269 |
def read_mh_z19():
""" Read the CO2 PPM concenration from a MH-Z19 sensor"""
result = read_mh_z19_with_temperature()
if result is None:
return None
ppm, temp, s = result
return ppm, temp, s | ca746b879f28eac9677c4420c4fb4a5c30873fca | 3,603,270 |
from typing import Optional
def get_cluster(cluster_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetClusterResult:
"""
Cluster details.
Latest API Version: 2020-10-01.
:param str cluste... | b78644aa140cb03b4b37aac3a1adeb9794faf919 | 3,603,271 |
def ignore(*exceptions, retval=None):
"""Execute function ignoring any one of the given exceptions if raised."""
def wrapper(func):
@wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
if not ... | 8e5729e4ec7f9a5a9d5c974c021bfca6151a391a | 3,603,272 |
def remove_recorders(osi):
"""Removes all recorders"""
return osi.to_process('remove', ['recorders']) | c63f23a031a5c957fd8667fc5be87fbd96b26a1e | 3,603,273 |
def removeCutsFromFootprint(footprint):
"""
Find all graphical items in the footprint, remove them and return them as a
list
"""
edges = []
for edge in footprint.GraphicalItems():
if edge.GetLayerName() != "Edge.Cuts":
continue
footprint.Remove(edge)
edges.app... | ddb047e00f98d73037abb5d9dc0a2e00de457f56 | 3,603,274 |
def addPhoto(link, fullPath,object):
""" add new photo
perm: link = the link to the photo
perm: object = the object this photo Belongs to as Model object
return the new photo object if added or false if failed"""
try:
photo = Photos(link=link, full_path=fullPath ,object=object)
db.session.add(photo)
db.s... | b6606a1c6c264c08c4c7e6f569783c3fc156050a | 3,603,275 |
from typing import OrderedDict
def to_options(split_single_char_options=True, **kwargs):
"""Transform keyword arguments into a list of cmdline options
Imported from GitPython.
Original copyright:
Copyright (C) 2008, 2009 Michael Trier and contributors
Original license:
BSD 3-Clause "... | b5835d8d9f52fed1ba34799c319be06e9913a1e3 | 3,603,276 |
def main_ctx():
"""Return a reference to the global Z3 context.
>>> x = Real('x')
>>> x.ctx == main_ctx()
True
>>> c = Context()
>>> c == main_ctx()
False
>>> x2 = Real('x', c)
>>> x2.ctx == c
True
>>> eq(x, x2)
False
"""
global _main_ctx
if _main_ctx is None... | b4a85d6badbbdb239dde158f5406fc48209ccf3b | 3,603,277 |
def plot_confusion_matrix(y_true, y_pred, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues, axis_font_size=12):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=Tru... | 7c6bdf68cf0f82826b947ba7572e8449254525ed | 3,603,278 |
def make_primitive_smoothed(cas_coords, smoothing_level=2):
""" Generates smoothed primitive from a list of coordinates.
Parameters
----------
cas_coords : list(numpy.array or float or tuple)
Each element of the list must have length 3.
smoothing_level : int, optional
Number of time... | bcb94241eb9a82482b523a07bb276f48b9ca91db | 3,603,279 |
def manager():
"""Retrieves the default top-level manager"""
global _defaultManager
return _defaultManager | 0b917f263010553565d45f527531f3f6bcb7c631 | 3,603,280 |
import inspect
def getclasses():
"""return a list of classes defined in `__all__`"""
classes = []
for name, member in getmembers():
if inspect.isclass(member):
classes.append(member)
return classes | ab734ac5578ba4b8fed342d2c9d41a294937b5e7 | 3,603,281 |
def load_lang_data(corpus_name, topk=10000):
"""
Load {topk} sentences from the corpus named by {corpus_name}.
"""
fpath = corpus_name + '.' + tokenizer_name
tokens = []
with open(fpath) as f:
for i, line in enumerate(f):
tokens.append(list(map(int, line.split(' '))))
... | af26319304d364f18d40fca645f7e28cc382bf10 | 3,603,282 |
def conductor_response_processor(conductor_response, req_id, transaction_id):
"""Build a response object to be sent to client's callback URL from Conductor's response
This includes Conductor's placement optimization response, and required ASDC license artifacts
:param conductor_response: JSON response from... | ca4254596b89a5f51dbeb2c624832efda4dd77df | 3,603,283 |
from typing import Match
def gen_ruby_html(match: Match) -> str:
"""Convert matched ruby tex code into plain text for bbs usage
\ruby{A}{B} -> <ruby><rb>A</rb><rp>(</rp><rt>B</rt><rp>)</rp></ruby>
Also support | split ruby
\ruby{椎名|真昼}{しいな|まひる} ->
<ruby><rb>椎名</rb><rp>(</rp><rt>しいな</rt><rp>)</rp>... | bd603b67a61812152f7714f3a13f48cac41db277 | 3,603,284 |
import numpy
def FingerprintMol(mol):
""" generates the EState fingerprints for the molecule
Concept from the paper: Hall and Kier JCICS _35_ 1039-1045 (1995)
two numeric arrays are returned:
The first (of ints) contains the number of times each possible atom type is hit
The second (of floats) contain... | 034b78422c4add407457fdf88c3178d529229b16 | 3,603,285 |
import time
def _generate_request_id():
"""
生成一个请求 id,暂时用 (时间戳 % 60 分钟)
:return:
"""
return int(time.time() * 1000 % (60 * 60 * 1000)) | b334265d41b68fc3455297bbc21065e7cb064920 | 3,603,286 |
def SkipIf(should_skip):
"""Decorator which allows skipping individual test cases."""
if should_skip:
return lambda func: None
return lambda func: func | 135486c94640231328089115d61ba2d1eb87e46a | 3,603,287 |
def generic_image_dataset_summary():
"""
Return a short HTML summary of a DatasetJob
"""
job = job_from_request()
return flask.render_template('datasets/images/generic/summary.html', dataset=job) | 26919ae503d0a6decb0d13143aeb7dcd617d5fdf | 3,603,288 |
def Choice(*choices):
""" note that the class of the choices becomes a base class, e.g. issubclass(Choice(1,2,3), int) == True """
if not len(choices):
raise ValueError(f"cannot define Choice without any choices")
if any(type(c) is not type(choices[0]) for c in choices):
raise ValueError(f"a... | dcbb638d2e062562e7692572d60c13f80acce033 | 3,603,289 |
from typing import List
import torch
def add_sine_features(
data_list: List[Data],
n_jobs: int = 1,
only_physical_cores: bool = False,
verbose: bool = False,
) -> List[Data]:
"""Add the Sine matrix for the given data of a homogeneous graph.
Args:
data_list (list of :class:`torch_geomet... | 7571ac175d79dc41405d380ad130100b760b30be | 3,603,290 |
def cache_execute(fn, cache, pass_kwargs=False, return_tuple=True, expand_fn=None):
"""Decorator that adds caching to a function that executes
multiple tapes on a device.
This decorator makes use of :attr:`.QuantumTape.hash` to identify
unique tapes.
- If a tape does not match a hash in the cache,... | 51e8ea9f8cf6596df88e219268627b11bd42ee68 | 3,603,291 |
def get_hmslincs_annotations(cell_lines):
""" Returns metadata annotations for cell lines available
on LINCS DB
Parameters
----------
cell_lines: list of str
Name of cell lines
Return
------
dfs: pandas dataframe
dataframe of cell line annotations from HMS LINCS DB
for g... | 80ff21797e429a6dcdc5b44bae284caec68cb9dd | 3,603,292 |
def plot_trajectory_2color (data, movie_ID):
"""Separately plot two channel trajectories of a given movie side by side.
Args:
data (pandas dataframe): dataframe containing parsed data. At the very
least, must contain the columns 'color', 'movie_ID', and 'parsed'.
movie_ID (str): uni... | 56eba8559e3fd2a6bd126b6ef5502924c5e13cb6 | 3,603,293 |
def yaml_cloudformation_constructor(loader, node):
""" Implements the yaml tag !Cloudformation
The tag takes a dict {stack: $stack_name, output: output_key}
as node (argument).
Example:
VpcId: !Cloudformation {stack: ${vpc_stack}, output: VPC}
VpcId: !Cloudformation {stack: ${vpc_stack}, r... | 5375081cdeaf1fa5a125c08c5cbbc71605439984 | 3,603,294 |
import os
def run_etl_query(rds=None):
"""
If we look in the batch_job_executions table and something is in a state other than COMPLETED or FAILED,
assume an ETL is in progress and don't shut the db down.
Also, if someone aborts an ETL job in Jenkins, we can get in a messed up state where a job execu... | b46aea17f2553e6be5d37ac379ca3d6eb257a034 | 3,603,295 |
from datetime import datetime
def convert_row(column_name_type, row):
"""
Make cell data more user friendly.
Args:
column_name_type (List[(str, str)]): A list of pairs of column names and types
row (dict): The row data as a dict
Returns:
A list containing row data transformed... | 2d5d29ea57f0fe22dd8c3c74b38a34ed16bf637d | 3,603,296 |
def dummy_data_generation(base_data):
"""TODO: REPLACE WITH NEWCASTLE DATA
"""
base_data['all_sectors'] = [
'community_arts_leisure',
'education',
'emergency_services',
'health',
'hospitality',
'military',
'offices',
'retail',
'storage'... | f341b23e795a24f425e423c67dcd63e07d39d7a0 | 3,603,297 |
def norm(x, train_stats):
"""
Normalize the data.
"""
return (x - train_stats['mean']) / train_stats['std'] | c7791c39b64a5041e537bb7554c0c4a7267d180c | 3,603,298 |
import random
import string
def randomstring(size=20):
"""Create a random string.
Args:
None
Returns:
result
"""
# Return
result = ''.join(
random.SystemRandom().choice(
string.ascii_uppercase + string.digits) for _ in range(size))
return result | 64ecd935130f6308367d02a5d699ea05c906cbb2 | 3,603,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.