content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def sched_exp(start, end, pos):
"""Exponential scheduler."""
return start * (end / start) ** pos | e98a3ac2dcdd6c787914c59bad3773d0a5d6e3ab | 645,957 |
def awg_sequence_acquisition_preamble():
"""
This function defines a standard AWG program preamble, which is used
regardless of the specific acquisition mode. The preamble defines standard
functionality of the user registers, which are used for dynamically
controlling e.g. number of iterations in a ... | e296e25f099620056b7e81e5aa7f57e0cfd8ae57 | 645,958 |
import copy
def get_object_state(obj, ignore_attributes=()):
"""Returns a dictionary with the state of the attributes of an object.
Note that this is not general. For example, it will throw an error for classes
that define a __slots__ field (like namedtuples).
Args:
obj: a Python object
ignore_attri... | 42377b5ae20bd4ceaa4f58cec3681b6ddc655eb6 | 645,959 |
def remove_trailings(input_string):
"""
Remove duplicated spaces.
"""
output_string = " ".join(input_string.split())
return output_string | f53cd6f55b1a5a43225223b3695d542b8c4876b6 | 645,960 |
def scaleFromRedshift(redshift):
"""
Converts a redshift to a scale factor.
:param redshift: redshift of the object
:type redshift: float or ndarray
:return: scale factor
:rtype: float or ndarray
"""
return 1. / (redshift + 1.) | 99501af0f5a2005ed952e8d01ad7533d02bfdf22 | 645,961 |
def get_idx_lag(idx_start, ar_iteration, forecast_cycle, input_k):
"""Provide the indices of past predictors."""
return idx_start + (forecast_cycle*ar_iteration) + input_k | 45ee938a59bb0ad5046f1d01aa7ad4626196c227 | 645,962 |
def FindFaces(gray, facecascade):
""" Find faces and retrun bounding boxes """
gray = gray
faces = facecascade
faces = faces.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=5,minSize=(5, 5))
return faces | 1c4a35276f288d02384f1f016b856918c296119b | 645,963 |
def user_data_from_registration_form(xform):
"""
Helper function for create_or_update_from_xform
"""
user_data = {}
if "user_data" in xform.form and "data" in xform.form["user_data"]:
items = xform.form["user_data"]["data"]
if not isinstance(items, list):
items = [items]
... | 43fac2af8ad83c06b07bba4e160f5b69651d31a7 | 645,964 |
import requests
def get_by_address(model_url, user_name, password):
"""
:param model_url:
:param user_name:
:param password:
:return:
"""
auth=(user_name, password)
response = requests.get(model_url, auth=auth).json()
return response | 1c189e58dc12be9ee9987e2746bba581ac71d58a | 645,965 |
def read_config(file_path):
""" Read cfg file into Python dict. """
config = {}
exec(open(file_path).read(), config)
del config['__builtins__']
return config | a9e26f91f59dbb54dfc3fdc99e958a87e699ff99 | 645,966 |
import socket
def tcp_listen():
"""Create a server socket, i.e. one which listens.
Returns (port_number, socket)"""
s = socket.socket(socket.AF_INET)
s.bind(("", 0))
s.listen(1)
addr, port = s.getsockname()
return (port, s) | ce57fac28287477638636a85a2c40316171cca09 | 645,967 |
import random
def random_jitter(value):
"""
Typical jitter that will add up to a second based on the provided `value`.
"""
return value + random.random() | faa8f0db6dbed09eac26770727e98b5ac90f5091 | 645,968 |
def get_bin_img_name(img_path):
"""
根据原始origin 文件路径,获取二值而且去噪声的文件路径
:param img_path:
:type img_path:str
:return:
"""
path_split = img_path.split('/')
file_name_split = path_split[-1].split('.')
file_name = file_name_split[0] # 文件名
# file_ext = file_name_split[1] # 扩展名
new_f... | 15aca9d6ef6207d892ef1abf7faf268dc212795b | 645,970 |
def calc_f_number(aperture_diameter,
focal_length):
"""
Calculate the f-number N (or f#) of an optical system.
https://en.wikipedia.org/wiki/F-number
Returns
-------
double : no units
"""
return focal_length / aperture_diameter | 93f8050ee7baa1d20f0431514f86412cca953af9 | 645,971 |
def NodeNameExist(line):
"""
Functions for parsing DOT file.
:param line: a line from DOT file
:return: whether there is a node name in this line
"""
if "CHEMBL" in line or "ASD" in line or "Chk1" in line or "B" in line or "F" in line:
return True
else:
return False | 9c4c59b6541dc1a5c28ef6caea1fbadf7d510409 | 645,972 |
from typing import Union
import os
def validate_tesseract(tesseract_path: str) -> Union[str, None]:
""" validate that the tesseract path is valid folder else raise an error
Args:
tesseract_path: Directory path to be validated
Returns:
(str or None): None if passed None, otherwise dir... | 63a1541fed9810c3bbcb8ccd5bb02a46161f763b | 645,973 |
def timezone_format(value):
""" Check the value of the timezeone offset and, if postive, add a plus sign"""
try:
if int(value) > 0:
value = '+' + str(value)
except:
value = ''
return value | e6abafec8c66b3891bba33a5f1110a4a406e9777 | 645,975 |
import json
def filter_bowtie(primers, output_file, primer3_output_DIR, species, TM=46,
hit_threshold=0, lower_tm=46, lower_hit_threshold=3, outp=1):
""" Check TMs of bowtie hits of given primers, on a given genome.
Filter the primers with too many nonspecific hits."""
for primer in list... | 376194719cd6bb4d8aff19c04d5b55b1305e5d93 | 645,976 |
import subprocess
import json
import fnmatch
def find_tags_to_copy(image_name, tag_patterns):
"""
Use Skopeo to list all available tags for an image
"""
output = subprocess.check_output(
["/var/task/skopeo", "inspect",
f"docker://{image_name}", "--override-os=linux"]
)
all_tag... | 8d927587a7497ca2b02259588a0be12a89159d6d | 645,978 |
import click
def prompt_for_dsn(dsn):
"""
Prompt interactively for postgres database connection details.
:return: dictionary with the keys: host, port, database, user, password
"""
click.echo('Please provide PostgreSQL connection info:')
# Note: Using '' as the prompt default is necessary to... | bf3f0ef3f5f9358d875e1747bc652b02cd48577f | 645,979 |
def fastFib(n, memo = {}):
"""
Assumes n is an int >= 0, memo used only by recursive calls
Returns Fibonacci of n
"""
if n == 0 or n == 1:
return 1
try:
return memo[n]
except KeyError:
result = fastFib(n-1, memo) + fastFib(n-2, memo)
memo[n] = result
... | 7b3cb2aa2b6f8eccde043ce9b800f2580ded6305 | 645,980 |
import json
def first_fold(fp):
"""
Create information of a new fold to the existing experimental results
Parameters
----------
fp : file
the first file to merge
Returns
-------
cv_info : dict
merged experimental results
"""
# load json file of the target fol... | 3b75764c991fe61009c2ed002c6f6ef169ea08ad | 645,981 |
def label_group_chunk(Focuses, labels, starts):
"""Group Selected labels together into One Label e.g. Combine Calls and Intro. Notes (Group these labels together)
Parameters
----------
focus : str or int
User defined Label to focus on
labels : list, shape [Epochs]->[labels]
List of ... | 5152334b6d51de55cbb40ff06912cbe825ad552c | 645,982 |
def escape_for_query(query_part: str) -> str:
"""Escapes all characters reserved by jriver in a natural string.
Do not put a complete query in here - this method is used to escape
reserved characters in a natural string that will be used as a query fragment.
This is usually the content of a field (e.g.... | 13635b9091fe11c335867893422da23844116160 | 645,983 |
import locale
def thousands(x):
"""
>>> thousands(12345)
'12,345'
"""
try:
locale.setlocale(locale.LC_ALL, "en_US.utf8")
except Exception:
locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
finally:
s = '%d' % x
groups = []
while s and s[-1].isdigit():
... | 79ee8aca31a37602d4fb0b6c4e367502ae08946e | 645,984 |
import re
def remove_articles(text):
"""remove articles"""
return re.sub(r'\b(a|an|the)\b', ' ', text) | 1fb5b4001ab071e532351c16b379c6b467c647a8 | 645,985 |
def Alignment2ExonBoundaries(alignment,
query_from=0,
sbjct_from=0,
add_stop_codon=1):
"""extract exon coordinates from a peptide2genome alignment.
Arguments
---------
aligment : list
List of tuples of the al... | 4df16ef12c969f7aad05a84109b2659e570f9ca6 | 645,986 |
def is_within(low, mid, high, eps):
"""General helper."""
return low - eps <= mid <= high + eps | 53c8768dfe698a76b7500ffdc0a1632039736c8a | 645,989 |
def create_firmware_update_payload(device_info: dict, compliance_data_list: list) -> list:
"""
Creates the payload to send to OME to execute the firmware update
Args:
device_info: A dictionary of dictionaries containing the type information for each device
compliance_data_list: A list of di... | 7040361cba99f608a82b59a9de2396fb6621ecac | 645,991 |
import os
import stat
def is_writeable(path):
"""\
Return True if the path is writeable by all of the populations
specified, False otherwise.
"""
if os.path.exists(path):
return (os.stat(path).st_mode & (stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)) != 0
raise OSError('no such file or d... | 89c0a7bf8e6d4b4da731b408f4dcb5bcfaaced56 | 645,992 |
def _target_file_name():
"""
File name to be used in `to_json_file()` testing.
"""
return 'dummy_target_file.json' | 3b40537d7c95d2102c9e499afdb47694f6a06f7d | 645,993 |
import os
def remove_directory_path(filename):
"""Remove the directory path from a path
Return the filename
Keyword arguments:
filename -- the original filename / path
"""
# Check the last os separator in the actual filename
if filename.rfind(os.sep) == -1:
return filename
fil... | 8c1a6aa0579a24d83f483d99ed434b12844c4221 | 645,994 |
def _class_valid(cls, entity_manager = None):
"""
Checks if the current model class reference is valid, according
to the currently defined data reference model.
A model class is valid in case the model is not a data reference
or in case the model is a data reference but the "real" model class
i... | ba70a50ed245fcea3d44d8af42e3c32bdfcc7552 | 645,995 |
import torch
def get_diff_weights(weights1, weights2):
""" Produce a direction from 'weights1' to 'weights2'."""
if isinstance(weights1, list) and isinstance(weights2, list):
return [w2 - w1 for (w1, w2) in zip(weights1, weights2)]
elif isinstance(weights1, torch.Tensor) and isinstance(weights2, t... | e1f9733fbaa181b538b81224de3661b32a226802 | 645,996 |
def tim_sort(A):
"""
The default python sorting algorithm
"""
return sorted(A) | 0fe5b9d9d79b5d36530106a845d307a9132970c1 | 645,997 |
def merge_sort(array):
"""merge sort"""
n = len(array)
if n > 1:
mid = n // 2
left = array[:mid]
right = array[mid:]
merge_sort(left)
merge_sort(right)
i, j, k = 0, 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
... | 7967c01eac35e95922ba9ea58d578dd70108034b | 645,998 |
import requests
def get_data_from_json_url(): # pragma: no cover
"""Extract information from json url."""
url = 'https://codefellows.github.io/sea-python-401d5/_downloads/cities_with_airports.json'
response = requests.get(url)
return response.json() | 18f82195aff936a06bdcd082b3253b34d7b47046 | 645,999 |
def filter_hsv_to_v(hsv):
"""
Experimental HSV to V (value).
Args:
hsv: HSV image as a NumPy array.
Returns:
Value values as a 1-dimensional NumPy array.
"""
v = hsv[:, :, 2]
v = v.flatten()
return v | 3d1f382d92501d9d9e0b0dedd832cdab2ed5e75d | 646,000 |
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
def straight_lines():
## checks if any player has completed the horizontal or verticle line
## takes len(board) iterations
for row in range(0, len(board)**2, len(board)):
first_in_row, row =... | 8953593d8f0d238c482d15e24229559ac19ca944 | 646,001 |
def a_dask(a):
"""Chunked"""
return a.chunk() | 20831e9825cf2c54f7a5be56481ace06466f2b80 | 646,002 |
def lasso_coordinate_descent_step(i, feature_matrix, output, weights, l1_penalty):
"""
Purpose: Compute the descent step for one feature
Input : Feature index, normalized feature matrix, output,
feature weights and L1_penalty
Output : Descent step for feature
"""
predictions = feat... | e0a2cd1b32dac11baa710f5de3b45f1656babbf5 | 646,003 |
def normalize_name(nm: str):
"""
convenience method that ensures we have some consistency on normalization of name
:param nm:
:return:
"""
return nm.replace("\u2019", "'").replace("\xa0", " ").strip().strip("'") | 219d646b6b2835decc889ad470eed13d24d5805d | 646,004 |
from typing import OrderedDict
def mapProfiles(settings):
"""Profile ID mapped to index in the list in an OrderedDict"""
profileMap = OrderedDict()
i = 0
print(settings)
while i < len(settings):
if "profileID" in settings[i]:
index = settings[i]["profileID"]
profil... | 7c0f8af6a2de877cb649ac53e14b80bc1e13c252 | 646,005 |
def test_datasource_connection(connection, body, error_msg=None):
"""Test a datasource connection. Either provide a connection id, or the
connection parameters within connection object.
Args:
connection: MicroStrategy REST API connection object.
body: Datasource Connection info.
err... | 96b1f08e7313583c12cb10d1b76bf3bdc17b2ab8 | 646,006 |
import os
def WorldName(args):
"""
Summary : Get and format the world name to be used
Parameters : command line arguments from the user (args)
Return : None
"""
if not os.path.isdir(os.path.join(os.getcwd(), 'worlds/')):
os.mkdir('worlds')
if args.world:
if not... | edb89f84b325cbc7d1d8dee74319b6b11ffbd44f | 646,007 |
def _noto_relative_path(filepath):
"""Return relative path from some noto root, or None"""
x = filepath.find('noto-fonts')
if x == -1:
x = filepath.find('noto-cjk')
if x == -1:
x = filepath.find('noto-emoji')
if x == -1:
return None
return filepath[x:] | ac2e9aa968bf65629072053ca2c3c3a09d426a7d | 646,009 |
def getCcpnChains(ccpProject, chainKey):
"""Descrn: Fetch a CCPN chain from a CCPN project using a list of object keys
Inputs: Implementation.Project, List of keys (Words or Ints)
Output: list of ccp.molecule.MolSystem.Chains
"""
molSystemCode, chainCodes = chainKey[0], chainKey[1:]
molS... | f7ca7cd0c7be5011e8110cf1d1383329e60b4d7f | 646,010 |
import jinja2
def load_template(in_template):
""" Returns a jinja2 template from file.
Parameters
---------
in_template: str
path and name of jinja2 template
Returns
-------
output_template: jinja template object
"""
with open(in_template, 'r') as default:
output_... | a5af11fd55fcf93dfc37e7330dcfc9d6e4a23c1e | 646,011 |
import re
def _external_rewrites(backend, data):
"""Rewrite external imports."""
# TFP
if backend == 'backend_tensorflow':
sub = 'import tensorflow_probability as tfp'
elif backend == 'backend_jax':
sub = 'import tensorflow_probability.substrates.jax as tfp'
elif backend == 'backend_numpy':
sub ... | 05e97b7e6c7698245f4ffebf452b2be3778875b1 | 646,012 |
def aggregate(A, X, C):
"""
aggregate residuals from N samples
Args:
A (b*n*k): weight of each feature contribute to code residual
X (b*n*d): original feature input
C (k*d): code words, with k codes, each with d dimension
Return:
E (b*k*d): residuals to each code
... | 91fd8ae878ae5d850bd1b1b05fef8a1fdd7cf0ca | 646,013 |
def estimate_backhaul_type(backhaul_lut):
"""
Estimate backhaul type.
"""
output = {}
preference = [
'fiber',
'copper',
'microwave',
'satellite'
]
perc_so_far = 0
for tech in preference:
for item in backhaul_lut:
if tech == item['t... | f916268b6b1c2d8e6a553af9501ab5ab58587501 | 646,014 |
def escape2dict(es_str, escapes='\n'):
"""
将下面两种形式的字符串分割为字典
'会员时长\n5 天'
'可用流量\n37.84 GB\n今日已用: 29.03MB'
:param es_str: 字符串
:param escapes: 转义符类型
:return:
"""
split_ret = [id.split(':', 1) for id in es_str.split('{}'.format(escapes))]
ret_dict = {}
flag = True
for i, s in ... | 2f3cd2ff3b8f1b44f587632520d7e880aa410348 | 646,015 |
def parse_ptimes(ln):
"""
Mini function for getting the time (in a string) from a line of an errlog file.
"""
timestring = ln.split(" ")[3]
return timestring | 4f2b80386fa78845e85d0c4c39efc5b30b70eb2a | 646,016 |
def wrap(x, low, high):
"""Wraps data between low and high boundaries."""
diff = high - low
while x > high:
x -= diff
while x < low:
x += diff
return x | 3a7ac9c9f63dbc61304322c7827774ce81ca3752 | 646,017 |
import os
def find_regular_files(path):
"""Finds all the regular files under a directory and returns the
tuples that would install such files"""
l = []
for dirpath, dirnames, filenames in os.walk(path):
base = dirpath.strip()
if base and filenames:
l.append(("/usr/share/aqu... | 08949a74d7c2feddb8595f367c66338f9fc5d7e4 | 646,018 |
def _get_chunks(text, length=200, overlap=50):
"""Splits text into chunks
Args:
text (str): Text
length (int, optional): Chunk length. Defaults to 200
overlap (int, optional): Chunk overlap. Defaults to 50
Return:
list: Text chunks
"""
l_total = []
l_partial = ... | 61d312114b3e1ee50fb2f43f8f288c7597ca2f0e | 646,019 |
def _get_header(soup):
"""Extract the column names from the "list-row-headings" class.
Parameters
----------
soup: bs4.BeautifulSoup
The html web page.
Returns
-------
list
Each element is a string with a column name.
"""
column_heading_class = "list-row-headings"
... | 43161030c6365c7b9de115ea1373697de0074f11 | 646,020 |
def getDistance (origin, point):
"""
Returns the distance between two points.
"""
dist = ((origin[0]-point[0])**2 + (origin[1]-point[1])**2)**0.5
return dist | aa945f7cbf9b1e06fdf999f1f2bd1bf75a0f4acd | 646,021 |
def delete(trie, word):
"""
search the trie and identify all nodes
if at one node it contains child only from character of this word,delete everything below the node
update the weight if at some level it is the maximum
Parameters
----------
word: the target word we want to delete
Return
------
a new trie th... | df465c344cdc32103fcb9a5a986e9ffcf88b9195 | 646,023 |
def cart_count(a) -> int:
"""
Count the number of items in the cart.
:param a: List of products. Untyped as I'm unsure how 'dict_items' type truly works.
:return: Int of the number of items in the cart.
"""
count = 0
# a is of type 'dict_items'
for i, this_tuple in enumerate(a):
... | e9c31fceab86ceed6b7099e835b0a17210b42218 | 646,024 |
def bfs_get_related(graph_dict, node):
"""
:param graph: Dictionary of key: ['value'] pairs
:param node: the key for which all related values should be returned
:return: All related keys as a list
"""
visited = [] # List to keep track of visited nodes.
queue = [] #Initialize a queue
... | 756aa1b7690c79aebfcc6459fd8bcf67a038e1bf | 646,025 |
def f(x):
""" just some silly function """
return x + 4 | 2a793bbff9960f673909325d7b51ed48879baa14 | 646,026 |
import re
def confirm(prompt, default='y'):
"""Confirmation prompt."""
default = default.lower()
if default not in ['y', 'n']:
default = 'y'
choicebox = '[Y/n]' if default == 'y' else '[y/N]'
prompt = prompt + ' ' + choicebox + ' '
while True:
some_input = input(prompt).strip(... | fce0b96825b5e22d7ea9f76e693a5a4753e14720 | 646,027 |
def check_format(cfg):
"""
We apply the following checks to configurations in dictionary format:
- For fields ending in `_class`, map None to empty string.
- If the `xyz_class` field is present, nesting has to happen and we add the `xyz`
field and initialize it with an empty dictionary.
- ... | 3ac29b9c93c802f9fb083d46ebcdf7d46aba3662 | 646,029 |
import yaml
def new_tpip():
"""Job for third party IP report generation"""
template = yaml.safe_load("""
steps:
- checkout
- run: sudo pip install -e .
- run: python scripts/tpip.py python_tpip.csv
- store_artifacts:
path: python_tpip.csv
docker:
- image: circle... | 6ec446f90fd9c3c52db167d4f2351c7707b710f6 | 646,030 |
def check_if_number_even(n):
"""
checks if int n is an even number
"""
if (n % 2) == 0:
return True
else:
return False | 3a46dadeb4a0afcd20cc4d2e693e680ba61f6805 | 646,032 |
from pathlib import Path
import subprocess
def fits_to_txt(fits_file: str) -> str:
"""
Dump visibilites from the uvf file using the fits_to_radplot utility.
``fits_to_radplot`` reads visibility data from the input file and write
amplitude, phase, and weight for each baseline to the text file.
Pa... | 3390584449a314a490f41ea5b056ced7eb7f28ba | 646,033 |
import os
def get_serial_by_id(dev_path: str) -> str:
"""Return a /dev/serial/by-id match for given device if available."""
by_id = "/dev/serial/by-id"
if not os.path.isdir(by_id):
return dev_path
for path in (entry.path for entry in os.scandir(by_id) if entry.is_symlink()):
if os.path... | c9cddad84273e5fecc4f580c0f8611e6dc3db05d | 646,034 |
def bubble_sort(items):
""" Implementation of bubble sort """
out = items.copy() # in place protection on items
for i in range(len(out)):
for j in range(len(out)-1-i):
if out[j] > out[j+1]:
out[j], out[j+1] = out[j+1], out[j] # Swap!
return out | f5edc948588374cdc037cfdbf8b3c0247c8de199 | 646,035 |
def is_close(first, second, rel_tol=1e-09, abs_tol=0.0):
"""
Almost equality for float numbers
:param first
:param second
:param rel_tol: relative tolerance, it is multiplied
by the greater of the magnitudes of the two arguments;
as the values get larger, so does the allowed difference
... | e341ea0fe01a90ae48145e9338c59f9da01f070f | 646,036 |
def user_id(uid):
"""Google user unique id to feedly ``:user_id`` format
:param uid: Google unique account UUID
:type uid: :class:`basestring`
:returns:
:rtype: :class:`basestring`
>>> user_id('00000000-0000-0000-0000-000000000000')
'user/00000000-0000-0000-0000-000000000000'
... | 1b65efb5848af6f4a90442d4de4506d62c6bd1fd | 646,037 |
def fr_has_silent_consonant(last_char: str, last_phoneme: str) -> bool:
"""True if last consonant is silent in French"""
# Credit: https://github.com/Remiphilius/PoemesProfonds/blob/master/lecture.py
if last_char in {"d", "p", "t"}:
return last_phoneme != last_char
if last_char == "r":
... | fa4dfa92961b0f30563e92529596f69c24d959fc | 646,038 |
def timedelta_to_seconds(delta):
"""
Take a timedelta object and return the total number of seconds.
"""
return delta.seconds + (delta.days * 86400) | 23bc2b9e36f58db68e39625e41dd4f0728d25457 | 646,039 |
def fetch_all_table_names(schema, eng):
"""
Finds all tables within a given schema.
"""
tables = eng.execute(
f"SELECT table_name FROM information_schema.tables WHERE table_schema = '{schema}';"
)
return [table[0] for table in tables] | afcabfb33a084e98b494aac8287c7c4e97ccde7d | 646,040 |
def is_xml_article_set(filename: str) -> bool:
"""
Check if input file is pubmed xml compressed archive from name.
Arguments:
filename {str} -- the name of the file
Returns:
bool -- true if file is compressed pubmed article set
"""
if filename.endswith('.xml.gz'):
retur... | 7a05e9daadee32ff59e07fa05304e446e32e77cb | 646,041 |
def digit_type(number):
"""
Check if the number is odd, even of add
@param number: Number that is being checked
@return: String which describes the number
"""
if number % 2 == 0:
return "even"
elif number % 2 == 1:
return "odd"
else:
return "fraction" | 385e0945efb489bdbaa66eabb21b013b24256820 | 646,042 |
def get_bd_addr(packet):
"""Helper function to get bd_addr filed from HCI CMD/EVT packet.
Args:
packet: packet object from pyshark.
Returns:
bd_addr value (MAC string). If the packet doesn't have bd_addr or not is not
HCI CMD/EVT, will return None.
"""
bd_addr = None
if 'bthci_evt' in packet:
... | 37b30d7b6770d526e9a60065358bcee1647e0726 | 646,043 |
def flag_to_kwarg(flag):
"""Convert flags into keyword arguments."""
_flag, *_value = flag.split()
flag_name = _flag.replace("--", "").replace("-", "_")
if _value:
value = _value.pop()
else:
value = True
return {flag_name: value} | 5a193f4d5b0bc2ea4706fa025c80dc70eb0ce3ae | 646,044 |
def greater(*, alpha=None, omega):
"""Define dyadic comparison function greater than.
Dyadic case:
3 > 2 3 4
1 0 0
"""
return int(alpha > omega) | 577a4c90eda4c8a3cfebdd315b64b540cd5feb01 | 646,045 |
def build_dest_dir(gearman_worker):
"""
Replace any wildcards in the provided directory
"""
if gearman_worker.lowering_id is not None:
return gearman_worker.collection_system_transfer['destDir'].replace('{cruiseID}', gearman_worker.cruise_id).replace('{loweringID}', gearman_worker.lowering_id).r... | da10f607f050dffa6214bf0f34177290aabb5c09 | 646,046 |
import requests
def is_in_dictionary(word):
"""
Checks whether a given word (string) is in the dictionary, by requesting it
from the dictionary.com website and checking for the 200 code.
"""
dc_url = "https://www.dictionary.com/browse/" + word.lower()
dc_page = requests.get(dc_url)
return ... | cc9ee2a7d64314d62ed28060e36c073fb61be287 | 646,047 |
def pick_donor(ads):
"""finds atom in adsorbate most likely to bind to metal Heuristic: N > O > P
> S > X > C > H :param ads: adsorbate atoms object :return: index of donor
atom in adsorbate
Args:
ads:
"""
donors = ['N', 'O', 'P', 'S', 'F', 'Cl', 'Br', 'I', 'C', 'H']
ads_symbols = ... | e4886c8d88830e344fb44a28e0cd0b8d9e6e4d36 | 646,049 |
from typing import Dict
from typing import Union
def od_parse(data: str) -> Dict[str, Union[str, list]]:
"""Parse od command output without argument, return a dict with the following keys: hex, ascii, list, text
Returns:
dict: with key hex, ascii, list, text
"""
text, asc_data, hex_data, list_... | c9eb69a988063009971af373dd88da6101a0dfe8 | 646,050 |
import re
def ShellEscape(arg):
""" Escape a single argument for passing into a remote shell
"""
arg = re.sub(r'(["\\])', r'\\\1', arg)
return '"%s"' % arg if re.search(r'[\' \t\r\n]', arg) else arg | 4fa85d982a7d8d64637ba524a1bba958a033f2c0 | 646,052 |
import re
def get_args(argv):
"""Store command-line args in a dictionary.
-, -- prefixes are removed
Items not prefixed with - or -- are stored as a list, indexed by 'args'
For options that take a value use --option=value
Consider using optparse or getopt (in Python standard library) instea... | 95395903a5fdfb8bc12c05df32e55006750cacf8 | 646,053 |
import math
def calc_term_count(order, var_count):
"""
Inputs: order- the order of the model
var_count- the number of variables in the model
Calculates the number of terms in a model.
"""
term_count = int(
math.factorial(order + var_count)
/ (math.factorial(order) ... | ac65c19885302bb8dae80ddd55721760c621fc6b | 646,054 |
import re
def timestamp_to_terraref(timestamp):
"""Converts a timestamp to TERRA REF format
Args:
timestamp(str): the ISO timestamp to convert
Returns:
The ISO string reformatted to match the TERRA REF time & date stamp. Returns the original
string if time units aren't specified
... | 0c571ce1b9fd39b0345cca68058bb6ee61c771e2 | 646,056 |
import click
def direct_runner(func):
"""Run the job locally via the DirectRunner."""
return click.option(
"--direct-runner",
default=False,
is_flag=True,
help="Run the job locally via the DirectRunner.",
)(func) | 6753c09d1400a1642eb5547da0c3cfdc34258565 | 646,057 |
def create_sub_mask_annotation(sub_mask, is_crowd, image_id, category_id, annotation_id):
# Find contours (boundary lines) around each sub-mask
# Note: there could be multiple contours if the object
# is partially occluded. (E.g. an elephant behind a tree)
"""
contours = measure.find_contours(sub_m... | aae1704fc849fc1d636d7551b2fae3ea57b4144b | 646,058 |
def ping():
"""
示例接口: http://127.0.0.1:8765/v1/utils/ping
:return:
"""
return "pong" | 4a52a1f3bd29e670b0077b0fa7fcb00824c2a977 | 646,060 |
def min_point(points, n_points):
"""
Return the index of the closest point to (0,0)
:param points: tuple of list for each coordinate
:param n_points: number of points
:return: the index of the selected point in the list
"""
min_y_indexes = [0]
min_y = points[1][0]
# Find minimum y
... | c06117007693aba8877952f88b6155df143f663b | 646,062 |
import re
from bs4 import BeautifulSoup
def remove_html_tags(text):
""" Removes HTML tags from text. """
# prevent missing white space in further deletion of html symbols
text = re.sub('<p>', ' ', text)
# add punctuation after headings
text = re.sub('</h1>', '. ', text)
text = re.sub('</h2>'... | 34d2b3e1f0e27457d7296149b89bf5eded1b62b3 | 646,063 |
def apply_embeddings(sequence, embeddings_dict, tokenizer):
""" Decomposes sequence into tokens using tokenizer and then converts tokens to embeddings using embeddings_dict. """
if sequence:
embeddings = [embeddings_dict['SOS']]
embeddings.extend([embeddings_dict[token] if token in embeddings_d... | 9d40db2fcd668cc22185f2eefd7876e37571492b | 646,064 |
def match_file(patterns, file):
"""
Matches the file to the patterns.
*patterns* (:class:`~collections.Iterable` of :class:`~pathspec.pattern.Pattern`)
contains the patterns to use.
*file* (:class:`str`) is the normalized file path to be matched
against *patterns*.
Returns :data:`True` if *file* matched; othe... | 62bbff1d93b96b27c98f857867b47db5470f7e40 | 646,067 |
def _is_2xx_status(status_code):
"""Returns 'True' if a given status code is one of successful."""
return str(status_code).startswith("2") | 16cdb950c791c4217996821328823be99e817f4c | 646,068 |
from datetime import datetime
def output_filename(filename, cli_args):
"""
Construct the output filename
"""
if cli_args.timestamp:
date_time = datetime.now().strftime("%m-%d-%Y_%H.%M.%S")
lname = filename.split(".")[0]
rname = filename.split(".")[-1]
new_filename = f"{... | 6a9ff52d64727c3f7921f3f29c3839c381923f39 | 646,069 |
import math
def update_one_contribute_score(user_total_click_num):
"""
item cf update similarity score by user
:param user_total_click_num:
:return: 1/log(1 + input)
"""
return 1 / math.log10(1 + user_total_click_num) | f04d309c1be4a061beff692c1aa942d8ee5f3ee6 | 646,070 |
def nCr(n,r):
"""Calculate ways of selecting *r* members out of a collection of *n*
members.
:param n: Size of the collection
:param r: Number of members to be selected from the collection
:returns: n!/[r!(n-r)!]
.. note::
:sup:`n` C :sub:`r` is typically read as *n co... | a4bd8de9e4b3339ef2c23c2fd7731106d89b5fe7 | 646,071 |
import copy
def firecrown_sanitize(config):
"""Sanitizes the input for firecrown, that is removes keys that firecrown
doesn't recognize
Parameters:
----------
config : dict
The dictinary that is ready for firecrown to munch on, but might have
extra keys that are augur specific... | 432f6d8edde835b640ec832e6c0de5abd15e24af | 646,072 |
def _write(obj, *args, **kwargs):
"""Helper for :meth:`write`; returns :mod:`protobuf` object(s)."""
cls_name = obj.__class__.__name__
func_name = f"write_{cls_name.lower()}"
try:
func = globals()[func_name]
except KeyError:
raise NotImplementedError(f"write {cls_name} to protobuf")
... | fcfa1e12b08fd399f58a07610674a1bf10249ea0 | 646,073 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.