content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _system_state_change(state, device):
"""Check if system state would change."""
if state == 'present':
if device:
return False
return True
if state == 'absent':
if device:
return True
return False
return False | ffd3b2f9f60fa1c3c8eb211a3e66332e12ef1972 | 639,119 |
def strip_fields(tup):
""" 对tuple中的每个域做 strip """
return tuple(f.strip().replace(' ', '') for f in tup) | 07ec8bc6abfc4c164a429705d6de2945caa301d4 | 639,120 |
def get_ami_id(conn, name):
"""Return the first AMI ID given its name"""
images = conn.get_all_images(filters={'name': name})
conn.close()
if len(images) != 0:
return images[0].id
else:
raise RuntimeError('{} AMI not found'.format(name)) | cc9fd0bc450b1a93ce0f8609fa9d948b3500189b | 639,121 |
from typing import Callable
def return_constant_value(value: float) -> Callable:
"""
For situations below in which we just need a function that returns a constant value.
Args:
value: The value that the function will return
Returns:
The function that returns the value, ignoring the ti... | 4449243d4ae1e688cd531f43622e1fa5c7b14eca | 639,122 |
def anyviolation(tickets, i, rule):
""" does the i'th field in any ticket violate the given rule? """
for ticket in tickets:
val = ticket.values[i]
if rule.anyok(val):
continue
return True
return False | 5fb17e20f560def1c6f9c14a4735b9a165ef5b4b | 639,123 |
def get_config_from_code():
"""
在代码中,配置扫描目录列表及敏感词列表
:return:
"""
dir_list = [r'C:\Users\Administrator\PycharmProjects\Sensitive_Prober\test',
r'C:\Users\Administrator\PycharmProjects\Sensitive_Prober\utils']
sensitive_list = ['PyYAML', 'abc']
return dir_list, sensitive_list | 5a9af98269f83c413cfcdb20d89411da427cfe22 | 639,124 |
def list_isos(cfg, distribution, isos):
"""generate a list with available ISOs"""
for release in cfg[distribution]['isos']:
for flavour in cfg[distribution]['iso_flavours']:
for architecture in cfg[distribution]['architectures']:
name = '-'.join((distribution, release, archit... | e14797d1bcda6d7a217c7235abde846d483e7cf8 | 639,125 |
import os
def parse_path(path):
"""Parse a path into a dict(path,dirname,filename,name,extension)"""
d = {'path': path}
d['dirname'], d['filename'] = os.path.split(path)
if d['filename'].startswith('.'):
d['name'], d['extension'] = d['filename'], ''
else:
d['name'], _, d['extensi... | 34e750aae0c908a05cba09ba44aa067aa335f6ab | 639,126 |
def convert_macaddr(addr):
"""Convert mac address to unique format."""
return addr.replace(':', '').lower() | 020d90ccfa50287ae29f0bc2bedeb1d19da62c71 | 639,127 |
def ingest_configs(datacube_env_name):
""" Provides dictionary product_name => config file name
"""
return {
'ls5_nbar_albers': 'ls5_nbar_albers.yaml',
'ls5_pq_albers': 'ls5_pq_albers.yaml',
} | e61f6e8316cfe7cb8cf1768c465e9283530cc07b | 639,128 |
def storeUpdateResult(cache):
""" Store results
Update T0
Store temperaure results into a dataframe and
save it in the cache.
"""
timeStep = cache['ts']
TProfile = cache['TProfile']
T = cache['T']
cache['T0'] = T.copy()
TProfile[:,timeStep] = T.reshape(1,-1)
return cach... | 7272855fd553b5571a8451f779ddc0c60c8d8d67 | 639,129 |
def merge(lst):
""" concatenate the lists back in order for the next step """
new_list = []
for sublist in lst:
new_list.extend(sublist)
return new_list | a2179d84d8b064cc2d2dc615fb9807500c9e58cf | 639,130 |
from typing import Any
from typing import Optional
from typing import Dict
def default_target_fcn(actor: Any, instances: tuple, kwargs: Optional[Dict] = None):
"""
A target function that is executed in parallel given an actor pool. Its arguments must be an actor and a batch of
values to be processed by th... | 1ccfba2df2ac9f9f20e929557dadf880b634f044 | 639,131 |
import typing
def parse_tuple_string(argument: typing.Union[str, typing.Tuple, typing.List],
type_func=int) -> typing.Optional[typing.Tuple]:
""" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) """
if argument is None:
return None
if isinstance(argument, str):
ret... | 45af8c412b00015c8fe434fe89ed802fe9dcedce | 639,132 |
def _get_1d_shape(in_shape):
"""helper function for Grad TopK"""
out_shape = 1
for i in in_shape:
out_shape *= i
return (out_shape,) | b1f621c70a6af9661dd99c5cc93515bcad12f1b7 | 639,133 |
def inject(L,lst,v):
"""
expends the len(L) by len(lst). puts value v in expanded position
Preserves values in L, at the end LL should have v in positions lst
"""
k = i = j = 0 #i indexes L, j indexes lst, and k is total length of LL
if lst == []:
return L
LL = []
N = len(L) + le... | fee38dade098ac063e99d3d4fbeea8f9f713fbba | 639,134 |
def _get_title(title, parent, default):
""" Get a sensible title for a dialog! """
if title is None:
if parent is not None:
title = parent.GetTitle()
else:
title = default
return title | c566329d2781144a1d0aba883ba6e5d5b9c1889d | 639,135 |
def get_comments(youtube, video_id, channel_id):
"""Retrieve the authors' channelIds of all of the comments,
of all of the uploaded videos, for the authorized user's channel."""
#global nextPageToken
results = youtube.commentThreads().list(
part="snippet",
videoId=video_id,
#allThread... | 427c6031a507ffade0f877b15aab47d6a8858b98 | 639,137 |
def _CheckChangeHasEol(input_api, output_api, source_file_filter=None):
"""Checks that files end with atleast one \n (LF)."""
eof_files = []
for f in input_api.AffectedSourceFiles(source_file_filter):
contents = input_api.ReadFile(f, 'rb')
# Check that the file ends in atleast one newline character.
i... | 6836b9f57227736b52bd477f16a5a676efbc89b8 | 639,138 |
def _get_new_connection(self, conn_params):
"""Opens a connection to the database."""
self.__connection_string = conn_params.get('connection_string', '')
conn = self.Database.connect(**conn_params)
return conn | 05761e48bdf41ef2f2199cbf99a29f75a0878fb8 | 639,139 |
import time
def _sort_job_help(t, featured):
"""
Auxiliar function
"""
result = t
if isinstance(t, time.struct_time):
result = list(t)
if featured:
result.insert(3, 99)
return result | 6076b496cfa85eaf7c7b46dd0283c45510d8061a | 639,141 |
import os
import json
def config_initial(config_file_path):
"""
Loads the config.json file with basic initial configuration.
Creates a 'root.log' file for root logger.
:param config_file_path: path
:return: configuration_dictionary
"""
log_setting = {
'version': 1,
'handle... | 28be0d46b770f8fe99019b2745380d202da373ee | 639,142 |
import os
def _build_path_tree(path_map, basepath, sep=os.path.sep, dictcls=dict):
"""
Convert a flat mapping of paths to values into a nested structure of
dict-line object (``dict``'s by default), mirroring the directory hierarchy
represented by the paths relative to ``basepath``.
"""
def pr... | fa811951439f5fb6f01a232f7f139552a72eb1a9 | 639,143 |
import torch
def gradient(y, x, grad_outputs=None):
"""Compute dy/dx @ grad_outputs"""
if grad_outputs is None:
grad_outputs = torch.ones_like(y)
grad = torch.autograd.grad(y, [x], grad_outputs=grad_outputs, create_graph=True)[0]
return grad | 1d551a4ac757ec0d47b694ec819739dec718dfe6 | 639,144 |
def _host_url_property():
"""
Retrieves the best guess that can be made for an absolute location up to
the path, for example: https://host.com:1234
"""
def getter(self):
if 'HTTP_HOST' in self.environ:
host = self.environ['HTTP_HOST']
else:
host = '%s:%s' % (s... | 73c20a92b9d398ebd4a59b79e88118ea34107f0f | 639,145 |
def try_divide(x, y, val=0.0):
"""
Try to divide two numbers
"""
if y != 0.0:
val = float(x) / y
return val | b93888afc784e319840b5410d3e771d8cb3a5cc7 | 639,146 |
def select_from_batch(advs, batch):
"""
Take a rollout-shaped list of lists and select the
indices from the mini-batch.
"""
indices = zip(batch['rollout_idxs'], batch['timestep_idxs'])
return [advs[x][y] for x, y in indices] | d0a20c1cd260f952e83c07d96a2747d9f42c36f8 | 639,147 |
def _before_underscore(s):
"""
:type s: str
:rtype: str
>>> _before_underscore('LC80880750762013254ASA00_IDF.xml')
'LC80880750762013254ASA00'
>>> _before_underscore('LC80880750762013254ASA00_MD5.txt')
'LC80880750762013254ASA00'
>>> _before_underscore('383.000.2013137232105971.ASA')
... | c3245b850381878d153543a1a45e6d42aa41da46 | 639,148 |
from typing import Any
def s_type(something: Any) -> str:
"""
Вывести укороченное название типа
>>> s_type(9)
'int'
>>> s_type(None)
'NoneType'
>>> class MyTestClass: pass
>>> s_type(MyTestClass())
'MyTestClass'
>>> s_type(Union[int, type(None)])
'typing.Union[int, None... | 35781692028fb7bd43692e33d9d51e9eb4981984 | 639,149 |
from datetime import datetime
from typing import List
def parse_text(now: datetime, key: str, group: List[str]) -> str:
"""
Handles the Text presentation
https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html#text
"""
# Era designator
if key == "G":
# no length impli... | 575862948d6442a73c8d270e4caed2c39ad50ddb | 639,150 |
import argparse
def parseargs():
"""
Parse commandline arguments
Returns
-------
args parsed from input
"""
parser = argparse.ArgumentParser(prog="xslt_converter.py")
parser.add_argument("xslt",
help="The xslt file to convert input to output with")
parser.... | 17a0d2b893e8c5b17670a998b6207b3e80ef6da5 | 639,151 |
def _get_instance(cluster, table, **kwargs):
""" Eliminates unrequired instances """
priority = []
for instance in cluster:
priority.append(kwargs[table["Database"][instance]])
return cluster[priority.index(min(priority))] | 1dd6fd2a6bbfbc2332ec17dee7738a486982d3d2 | 639,153 |
from os.path import splitext
def _splitext(p):
"""
"""
try:
s = splitext(p)
except (AttributeError, TypeError): # Added TypeError for python>=3.6
s = (None, None)
return s | debbca0bbbfa84f80173805fb842f92529cf61f8 | 639,156 |
def is_valid_uni(uni):
""" Validate the syntax of a uni string """
# UNIs are (2 or 3 letters) followed by (1 to 4 numbers)
# total length 3~7
if not isinstance(uni,str):
return False
if len(uni) < 3 or len(uni) > 7:
return False
if uni[:3].isalpha():
# 3 letters
return uni[3:].isnumeric()
elif uni[:2].... | 77df11c5a4fe857cd9e74a4dd13496244ee9a57f | 639,157 |
def create_payload(url, script="alert('test');"):
""" Create the payload for the URL
>>> create_payload("http://127.0.0.1/php?id=1")
http://127.0.0.1/php?id=<script>alert('test');</script> """
data = url.split("=")
open_and_close_script = ("<script>", "</script>")
return data[0] + "=" + open_and... | b6985ca3270dcdae2328ede746140510aa42b063 | 639,158 |
def get_fixed_participant_matches():
"""There are 10 control females and 7 viable PD females. Thus to use most of the data set possible, the 3 of the control females will need to match with 3 PD males
9 of these control females will be a fixed match. 7 control and PD female matches were done so simply by o... | 5ecaa4f925faa85ff24ce339b1d129c9b1fb2f18 | 639,159 |
import argparse
def runs_per_test_type(arg_str):
"""Auxilary function to parse the "runs_per_test" flag.
Returns:
A positive integer or 0, the latter indicating an infinite number of
runs.
Raises:
argparse.ArgumentTypeError: Upon invalid input.
"""
if arg_s... | 978f02677c8425c57e6b3b9b709bc83f47c9f14d | 639,160 |
def _rear_right_tire_pressure_supported(data):
"""Determine if rear right tire pressure is supported."""
return data["status"]["tirePressure"]["rearRightTirePressurePsi"] is not None | dad0c415ae4ab11b7d2626741bfbf723b5893c22 | 639,161 |
def _convert_palette_to_dict(palette):
"""Minimizing duplicate code"""
return {'is_24_bit': palette.is_24_bit, 'is_custom': palette.is_custom, 'is_included_with_repo':
palette.is_included_with_repo, 'palette_id': palette.palette_id, 'name': palette.name, 'description':
palette.descriptio... | 3769a42f21793856edd851be900f33f6a3877286 | 639,163 |
def ChangeExtension(file_name, old_str, new_str):
"""
Change the 'extension' at the end a file or directory to a new type.
For example, change 'foo.pp' to 'foo.Data'
Do this by substituting the last occurance of 'old_str' in the file
name with 'new_str'. This is required because the file name may c... | f214c4f2109713b39681fd67d5984392d8fa3f47 | 639,164 |
from datetime import datetime
import pytz
import json
def create_mqtt_payload(unix_epoch=0, acc_x=0, acc_y=0, acc_z=0, id=None):
"""
Creates a WindIO MQTT payload based on a motion sensor box log file line.
Example for payload from WindIO documentation:
{
"content-spec": "urn:spec://eclipse.org/u... | 01ebad3e5f5fc893f98f2fc1dfa39d4ec4f61894 | 639,165 |
def _build_bit_string_set(b_strings, dif_qubits, dif_values):
"""
Creates a new set of bit strings from b_strings, where the bits
in the indexes in dif_qubits match the values in dif_values.
Args:
b_strings: list of bit strings eg.: ['000', '011', ...,'101']
dif_qubits: list of integer... | 1b320e5e7fbe353951608c4aa7c3ecc84134da2c | 639,167 |
def _filter_subword(sentence, pattern_list):
"""
If the sentence contains any pattern in the pattern_list as a single word or phrase,
return true, else false
"""
word = False
sentence = sentence.replace('-', ' ')
sentence = sentence.replace('/', ' ')
sentence = sentence.replace('_', ' '... | 240db283d67a66d3089f7ea4a64160b0a903ae3d | 639,169 |
def split(iterable, f):
"""Split an iterable ``I`` into two iterables ``I1`` and ``I2`` of the
same type as ``I``. ``I1`` contains all elements ``e`` in ``I`` for
which ``f(e)`` returns True; ``I2`` is the complement of ``I1``."""
i1 = type(iterable)(i for i in iterable if f(i))
i2 = type(iterable)(... | 48234a60f3befdec86bac45a1189b0b3412529bd | 639,170 |
import configparser
def config_handle(path):
"""
用于对Config配置文件进行操作,初始化config_path
:param path: config文件路径
:return: 返回config对象
"""
config = configparser.ConfigParser()
config.read(path)
return config | 8ea3e6af51370b36b947a98bfa283cef00916d0e | 639,171 |
def logEq(a, b):
"""Returns 1 if the logical value of a equals the logical value of b, 0 otherwise"""
return (not a) == (not b) | 3abbc64ce6ff29864f9bc08a0971febcd4c8dfff | 639,172 |
def get_model_limiter(instance):
"""
Returns a {primary_col:primary_key} for
an instance of a different model. Usually
used with ReferenceFields.
"""
cls = instance.__class__
primary = cls.get_primary()
return { primary: getattr(instance, primary) } | c7432c9f4fe4b10dc01c1c38a5e144a933a15516 | 639,173 |
def node_tree(nodes, current_node):
"""
递归:获取节点的子节点
"""
for node in nodes:
if node["parent_id"] == current_node["id"]:
current_node["children"].append(node)
node_tree(nodes, node)
return current_node | 88ec0982f659d8a30ab9a996b4025dc776bbd507 | 639,174 |
def a1decimal(n):
"""
Esta funcion recibe un numero y devuelve un float con solo un decimal
"""
return float(int(n*10))/10 | f250d57b7712ebc65b0110e8e6b3eed9cca417ad | 639,175 |
import hashlib
def md5(string):
"""
Calculates a MD% sum of the provided string
:param string: The string to calculate teh MD% sum
:returns: MD% sum of the provided string
"""
return hashlib.md5(string.encode('utf-8')).hexdigest() | b8414267094e0f8ccd7275d69fb5bf0ffbd648fa | 639,176 |
def to_hex_color(x):
"""Ignore alpha"""
if isinstance(x[0], float):
x = [int(255*_x) for _x in x]
return '#{:02X}{:02X}{:02X}'.format(x[0], x[1], x[2]) | a50f0be91c333ad673e0355a351091f908aae398 | 639,177 |
import json
def _store_db(obj):
"""
Takes a dictionary keyed by unique message permalinks and writes it to the JSON file on disk.
:param obj:
:return:
"""
with open('message_db.json', 'w') as json_file:
json_file.write(json.dumps(obj))
return True | b21365eb4f86004680e99020c38d40a692dabf9e | 639,178 |
def contains(haystack, needle):
""" returns true if needle is in haystack """
ind = haystack.searchsorted(needle)
ind.clip(0, len(haystack) - 1, ind)
return haystack[ind] == needle | f76157804bab111267067ee9efe0aa448613b6ca | 639,179 |
def marginalise(pd_y, cpd_xy):
"""
Marginalise p(X|Y) with respect to p(Y). We get a new distribution p(X).
"""
pd_x = {}
for y, p_y in pd_y.items():
for x, p_xy in cpd_xy[y].items():
p_x = pd_x.get(x, 0.0)
pd_x[x] = p_x + (p_xy * p_y)
return pd_x | 86367b4177bfcc8b8c9cc5b63a0d5e2799a323c4 | 639,180 |
def cloud_mask_ls8(image):
"""
Function to mask clouds based on the pixel_qa band of Landsat 8 SR data
:param {ee.Image} image input Landsat 8 SR image
:return {ee.Image} cloudmasked Landsat 8 image
"""
# Bits 3 and 5 are cloud shadow and cloud, respectively.
cloudShadowBitMask = (1 << 3)
... | d3284468d8acf2c00d5d5061333a1990f7c6b8e9 | 639,181 |
def solve(grades):
"""
Return grades rounded up to nearest 5 if above 38, otherwise, do not round
the score.
"""
rounded_grades = []
for grade in grades:
if grade >= 38:
rounded = ((grade + 5) / 5) * 5
if rounded - grade < 3:
grade = rounded
... | 42012d042ec6e997abb419f5cbcac78b607ca0b0 | 639,182 |
def human_int(s):
"""Returns human readable time rounded to the second."""
s = int(round(s))
if s <= 60:
return '%ds' % s
m = s/60
if m <= 60:
return '%dm%02ds' % (m, s%60)
return '%dh%02dm%02ds' % (m/60, m%60, s%60) | 5619175716e59074e83f704e3b6cda0f517aca1a | 639,183 |
import uuid
def new_config_file(tmpdir_factory):
"""Only create the filename, but not the actual file."""
testDir = tmpdir_factory.mktemp('test')
configFile = testDir.join(uuid.uuid4().hex + '.ini')
return str(configFile) | e24a6dfbbb5b8fc434ce58de5f6b3d5678c50019 | 639,184 |
def get_dist_fast(point, bb):
"""Calculate the distance between a ``point`` and a bounding box ``bb`` by adding up the x- and y-distance.
:param point: a point given by [x, y]
:param bb: the bounding box of a baseline polygon
:type point: list of float
:type bb: Rectangle
:return: the distance ... | 2563704d8d23140a3adf6a2e4632ac2a36c2fae4 | 639,185 |
def get_fingerprints():
"""
fingerprints are stored in plain text file, one fingerprint per file
the result is sorted
"""
with open('fingerprints.txt', 'r') as lines:
sqlipat = [line.strip() for line in lines]
return sorted(sqlipat) | 801fa5ab3670a58a7c89b8a7a60787e16a295f40 | 639,186 |
import os
import glob
def identify_files_in_dir(path):
"""Identify the json files in the given directory recursively."""
return [target for file_path in os.walk(path) for target in glob.glob(os.path.join(file_path[0], '*.json'))] | aef49bf462243e1a4c35c557904be8c8cf12d043 | 639,187 |
def put(a, ind, v, mode='raise'):
"""
Replaces specified elements of an array with given values.
The indexing works on the flattened target array. `put` is roughly
equivalent to:
::
a.flat[ind] = v
Parameters
----------
a : ndarray
Target array.
ind : array_like
... | 8e4e915f49f3159a890f8a79306ca80e2e57006f | 639,189 |
import json
def jinja_resilient_substitute(value, json_str):
"""jinja custom filter to replace values based on a lookup dictionary
Args:
value ([str]): [original value]
json_str ([str]): [string encoded json lookup values]
Returns:
[str]: [replacement value or original value if n... | d8b2e566d36c91d47fcce7b839fe801de5b73e91 | 639,190 |
def fliptable(l, b, i):
"""(╯°□°)╯︵ ┻━┻"""
b.l_say(fliptable.__doc__, i)
return True | 522a9c671bca47a3dc3114f78ca9974fbb2a9473 | 639,191 |
import glob
import os
def get_filenames_in_folder(folderpath, pattern="*"):
"""Return the files or folder names inside a folder.
Args:
folderpath (str): Folder path.
pattern (str): Pattern to find.
Returns:
list: list of files
Examples:
>>> l = get_filenames_... | cf262c4c1dfcee85c5f1f14ac008c6c8534f7e3a | 639,192 |
def polygon2bbox(polygons):
"""
:param polygons: list[list[float]] ,each list[float] is one
simple polygon in the format of [x1, y1, ...,xn,yn]
:return: list[list[float]], each list[float] is one simple
bounding box candidates, list[float]: [x_min, y_max, x_max-x_min, y_max-y_min]
"""
bbox... | 4ea14805a09e46974502735a20220dcc159b2157 | 639,194 |
import io
def ReadSymbolTable(path, skip_epsilon=False):
"""Read a bijective symbol table in OpenFst text format."""
symbol2label = {}
label2symbol = {}
with io.open(path, mode='rt', encoding='utf-8') as reader:
for line in reader:
line = line.rstrip('\n')
fields = line.split()
assert le... | f77d3971fc9663dd94c19c5ad5f92e73db5b26aa | 639,195 |
import gzip
def build_geneinfo(bed):
"""
Loads bed file into a dictionary with the key being the name and a string being the value
Input:
BED -- a bed file to load
Return:
A dictionary with the key being the name position of the bed file and the values being the
ordered bed... | 2cfc4ef90c62db9dd10b9f0a1bd8e7a13df7bacb | 639,196 |
from sys import argv
def check_if_cmdinp():
"""
Check if there is a commandline argument for reading patterns from file
"""
if len(argv) > 1:
return argv[-1]
return "" | 36ed836a9f50f5e15c9c8ac662b3a2ac96d61790 | 639,197 |
import sqlite3
def table_drop(cursor, table_name):
"""
Delete a table
Returns:
``True`` if table was removed, ``False`` else
"""
sql_command = f"DROP TABLE '{table_name}';"
try:
cursor.execute(sql_command).fetchall()
except sqlite3.OperationalError:
return False
... | 88a4e9eb5c54d4e27564ba02c4c81bb23b003646 | 639,199 |
def std_value(x: float, m_x: float, s_x: float) -> float:
"""
This function computes standardized values of a sequence value
given its mean and standard deviation.
"""
return (x - m_x) / s_x | 5802d7da10813c07c67fa34c93bb54569ab02e37 | 639,200 |
import sys
def current_version_string():
"""Current system python version as string major.minor.micro"""
return "{0}.{1}.{2}".format(sys.version_info.major,
sys.version_info.minor,
sys.version_info.micro) | 99ca259339655d003b8779df4c0b0416e9c4c175 | 639,202 |
def diff_split_by_fields(txt):
"""Returns dictionary object, key is fieldname, value is it's diff"""
result = {}
current = None
lines = txt.split("\n")
for line in lines:
if line[:4] == "--- ":
continue
if line[:4] == "+++ ":
line = line[4:].strip()
... | b75ee94b6a1e05c44ae266f7f3a65c25ba1769f8 | 639,204 |
import os
import re
def convert_aosconfig_asm(aosconfig_h):
""" convert aos_config.h to IAR asm format """
if not os.path.isfile(aosconfig_h):
print ("[ERROR]: No such file %s" % aosconfig_h)
return 1
patten = re.compile(r"#define\s+(\w*)\s+(.*)")
macro_list = []
with open (aoscon... | 62e01dc1c59687b7663ab915c7a09c1c5c38f73f | 639,205 |
def isPointInBox(p, b):
"""
category: General Utility Functions
Return whether a given point is within a given box.
For use with standard def boxes (position|rotate|scale).
"""
return ((abs(p[0]-b[0]) <= b[6]*0.5) and (abs(p[1]-b[1]) <= b[7]*0.5)
and (abs(p[2]-b[2]) <= b[8]*0.5)) | 05a3acf57d84dd4dc6a9b69efda8c73c0d706060 | 639,206 |
def load(state):
"""Create and setup the state from pickled data.
Returns a factory instance.
"""
name, data = state
obj = globals()[name]()
obj.__setstate__(data)
return obj | 20e1a0aa8dd8d428447ff986b4eeb30a80887def | 639,207 |
def add(v1, v2):
"""
Returns the addition of a two 2-D vectors.
"""
return (v1[0] + v2[0], v1[1] + v2[1]) | 40ddea20e33efec8a3f1cdb41964a404247deed5 | 639,208 |
import torch
def text_embedding(x):
"""Makes a phrase embedding out of all the word embeddings which constitutes it."""
return torch.sum(x, dim=1) | aca311a445ad3834752efab68bd727a9d0018a6e | 639,209 |
def hhv(series, n):
"""求series在n个周期内的最高值"""
hhv_data = series.rolling(n).max()
return hhv_data | 6410b1e673e976035fe010c76aacb9ce4fd7a0df | 639,210 |
def instance_on_host(instance, host_name):
"""
Returns true if the instance is located on the host
"""
if host_name != instance['OS-EXT-SRV-ATTR:host']:
return False, "instance is not on host"
return True, "instance is on host" | a203dcd31f4efbad453c9f265bfbd50c0609635e | 639,211 |
from typing import Dict
def format_selector_movements(info:Dict[str,str])->str:
"""Callback to parse the accounts/cards into a string format """
return f"{info['name']} - {info.get('currency','')}" | 7e7bfa98b2af7ae59f8d785f3ad1db9c701e4b09 | 639,212 |
def has_advertise(soup):
"""
This method is used to judge whether a WorldPress website can advertise.
:param soup: The soup of this website. soup comes from BeautifulSoup(r.text, 'lxml').
:return: A String. "True" or "False".
"""
for script in soup(["script", "style"]):
script.decompose... | 1b253f728d8a6f01f2a76be34b5967d0b4b1d86c | 639,213 |
def cystic_teratoma_adult():
"""Construct a test fixture for adult cystic teratoma. Tests the
pediatric flag.
"""
return {
"concept_id": "mondo:0004099",
"label": "adult cystic teratoma",
"aliases": ["cystic teratoma of adults"],
"pediatric_disease": None,
"xrefs"... | e65a4418e132cc2d69d34ea6ea75a09a30478273 | 639,214 |
def combine_offsets(f, chunk_size=50):
"""
Combine function calls with offset and limit instead of total amount
:param chunk_size: Size of the chunks
:return: All results of the chunks
"""
def chunked_wrapper(self, amount, *args, **kwargs):
return [
item
for offs... | 08e2911251bd7066abef2208b97c02e2d41bf97c | 639,215 |
def second(obj):
"""
get second element from iterable
"""
try:
it = iter(obj)
next(it)
return next(it)
except TypeError:
return obj
except StopIteration:
return | 10b7317ad6abafeb4eab5d85e3e30e67b5d8eb21 | 639,216 |
def is_anagram(s1, s2):
""" Figures out if the two strings are anagrams.
Complexity: O(n)
Args:
s1: str
s2: str
Returns:
boolean, True if s1 is an anagram of s2.
"""
letters = {}
for c in s1:
if c in letters:
letters[c] += 1
else:
... | b46d02dad00f480bd7feaaf286e61538b8b5f4d1 | 639,217 |
def set_and_true(key, _dict):
"""Is key in dict and value True?
Args:
key (str): Key to lookup in dictionary.
_dict (dict): The dictionary.
Returns:
bool: Is key in dict and value True?
"""
return key in _dict and _dict[key] is True | ceb88511d0c09c6805c5b1c9ba173e687aa752ce | 639,218 |
def _quantized_forward(self, *args, **kwargs):
"""Forward method for a quantized module."""
if not self.training and hasattr(self, "_quantized"):
return self._quantized(*args, **kwargs)
return self._prepared(*args, **kwargs) | d92bab45b6180cd6d5ee88eae2202c0862ded5f6 | 639,219 |
def tf_trans(T):
""" Return translation vector from 4x4 homogeneous transform """
assert T.shape == (4, 4)
return T[0:3, 3] | 3661bb6fe3c16cf3e144b5b471f527dadf8f2335 | 639,220 |
def funtion_n(x, a, n):
"""
"""
if x < a:
return 0.0
return (x - a)**n | 1e376d8645e85d75163edcd986b84a77745c8a1a | 639,221 |
def get_watch_literals_for_clause(claus):
"""
return tuple of the clause watch literals
@param claus:
@return:
"""
claus.watch_literals = claus.get_two_watch_literals()
claus.possible_watch_literals = list(set(claus.possible_watch_literals) - set(claus.watch_literals))
return claus.watch... | 18985e7b09766dd416cf5b0b5d12b5bccf97a6be | 639,223 |
def alloc_sync(malloc, free):
"""sync just mallocs whose has free"""
return malloc[~free.isin(malloc)].dropna() | 914685b6e7c03212705cba3da9704b8783f229c8 | 639,224 |
def develop(envelope):
"""
Remove the envelope from a message.
:param envelope: PokerTHMessage object that envelops a message
:return: PokerTH message from the envelope
"""
msg = [v for _, v in envelope.ListFields() if v != envelope.messageType]
assert len(msg) == 1
assert msg[0].IsInit... | 0398b6f61ff2e36dec38f56833a90110041d45a2 | 639,225 |
def get_necessary_amount(unspent_transactions, amount, size='small'):
""" Calculates the minimum necessary amount needed to pay the required bitcoins of a transaction.
:param unspent_transactions: list of the unspent transactions from a bitcoin address.
:type unspent_transactions: list
:param amount: d... | 05819b9b70c486b0d6b0828611da3c9dabb6f82b | 639,226 |
def bedExtractIDText(bed_file, gene_ids_param):
"""Extract bed-12 tracks according the gene names."""
if type(gene_ids_param) != str: # so it's list
gene_ids = set(gene_ids_param)
else:
gene_ids = set([gene_ids_param])
output = []
f = open(bed_file, "r")
for line in f:
g... | 1029e911510d64845c7961da943b7a5b402f0c57 | 639,227 |
def servo_duty_cycle(pulse_ms, frequency = 60):
"""
Formula for working out the servo duty_cycle at 16 bit input
"""
period_ms = 1.0 / frequency * 1000.0
duty_cycle = int(pulse_ms / 1000 / (period_ms / 65535.0))
return duty_cycle | e21c48c033e0ad97650547f1d715f1483a0e02b5 | 639,228 |
def find_party_exp_ratio(mlvl, plvl_list):
"""计算组队状态下, 怪物的基础经验值加成。
"""
counter = 0
for plvl in plvl_list:
if abs(plvl - mlvl):
counter += 1
if counter >= 2:
ratio = 1.0 + (counter - 1) * 0.15
else:
ratio = 1.0
return ratio | 067759187095ba74fbcba5289dce2c2179f92030 | 639,229 |
def nrefrac(wavelength, density=1.0):
"""Calculate refractive index of air from Cauchy formula.
Input: wavelength in nm, density of air in amagat (relative to STP,
e.g. ~10% decrease per 1000m above sea level).
Returns N = (n-1) * 1.e6.
"""
# The IAU standard for conversion from air to vacuum wavele... | 0c6e8e6a962561b7bd2c1ee185d2313d99267e11 | 639,230 |
def get_age_schedule_table(schedules):
"""
Generate a table of initial ages, schedule number,
period number, and current age.
"""
age_schedules = {}
for i in range(0, 200, 10):
age_schedules[i] = {}
for a, schedule in enumerate(schedules):
age = i
sch... | aea6d744068b82442c79c6e97fb0ebe1aee0263a | 639,231 |
def sort_results(results):
"""Sorts file names based on designated part number.
File names are expected to be in the form :
{task_id}.{part number}.{extension}
:param results: a list of file names to be sorted
:type results: list of str
"""
return sorted(results, key=lambda x: x.split(... | 90f1371ffb01c1c747ba9d74bf0a206071f2335b | 639,232 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.