content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def __cve_details(data, db):
"""
Get a CVE details.
"""
_cve = data.parameter
_query = "SELECT cve_description FROM CVE WHERE cve LIKE ?;"
res = []
res_append = res.append
# Title
res_append("[*] Detail for CVE '%s':" % _cve)
r = db.raw(query=_query, parameters=(_cve,)).fetchone()
if r is not None:
res_append("\n %s" % r[0])
res_append("\n")
return "\n".join(res)
|
3bf786e84095592ca861c939c4919c68afa67d4a
| 38,347 |
def test_device(tmp_path):
"""Create an AVD configuration file."""
config_file = tmp_path / ".android" / "avd" / "testDevice.avd" / "config.ini"
config_file.parent.mkdir(parents=True)
# Write a default config. It contains:
# * blank lines
# * a key whose value explicitly contains an equals sign.
with config_file.open("w") as f:
f.write(
"""
avd.ini.encoding=UTF-8
hw.device.manufacturer=Google
hw.device.name=pixel
weird.key=good=bad
PlayStore.enabled=no
avd.name=beePhone
disk.cachePartition=yes
disk.cachePartition.size=42M
"""
)
return config_file
|
0d99da2ed0669d96a367b4fe119a7de07b8f56fc
| 38,348 |
import random
def pick_one(namelist):
"""Pick a random name from the list"""
return random.choice(namelist)
|
7b85e973942951b60362d5668fb7dd66b344bd93
| 38,350 |
def get_model_family_color(model_family):
"""Returns the canonical color for a model family."""
# Derived from sns.color_palette("colorblind").
canonical_colors = {
"vit": "#0173B2",
"bit": "#DE8F05",
"simclr": "#029E73",
"efficientnet-noisy-student": "#555555",
"wsl": "#CC78BC",
"clip": "#CA9161",
"vgg": "#949494",
"alexnet": "#949494",
"mixer": "#D55E00",
"guo": "#000000",
}
assert model_family in canonical_colors, f"Specify color for {model_family}."
return canonical_colors[model_family]
|
41e304519b13aedc0db038a24c24984291540943
| 38,352 |
def is_module_available(module_name):
"""Return True if Python module is available"""
try:
__import__(module_name)
return True
except ImportError:
return False
|
527092a60534e263dd9f8e8ce43bbfcb0ba19f31
| 38,355 |
def au_to_mkm(au: float) -> float:
"""
1 AU = 149,597,870.7 KM
:param au: dist in AU
:return: dist in millions of KM
"""
return au * 141.6
|
489fcf94c5c25ca99bcdd20a7a1df3c14a4e1ab3
| 38,356 |
def format_date_key(date_field):
"""
format a datetime into year-month-date format
"""
return date_field.strftime('%Y-%m-%d')
|
5db1a5624cf650427e64f3322e03dc6e9bd12e4b
| 38,360 |
def filter_dual_selection(sele1_atoms, sele2_atoms, idx1, idx2):
"""
Filter interactions between selection 1 and selection 2
Parameters
----------
sele1_atoms: list
List of atom label strings for all atoms in selection 1
sele2_atoms: list
List of atom label strings for all atoms in selection 2
idx1: int
Atom index for cation
idx2: int
Atom index for aromatic atom
Returns
-------
bool
True if interaction should be included
"""
return ((idx1 in sele1_atoms) and (idx2 in sele2_atoms)) or ((idx1 in sele2_atoms) and (idx2 in sele1_atoms))
|
11acadc1c958a021aeb1d7b0cb7345851b9a00ee
| 38,361 |
import yaml
def load_config_dict_from_file(fp):
"""Function to load a dict of configuration settings from a yaml file"""
with open(fp, 'r') as config_file:
config_dict = yaml.safe_load(config_file.read())
return config_dict
|
50d07ffa7fdd7ab1523d8e48248b42dbf28e5b7b
| 38,364 |
def nav(root, items):
"""Access a nested object in root by item sequence."""
for k in items: root = root[k]
return root
|
357b735c548ac2124941d5c8e8b53b73638d0d92
| 38,366 |
def lr_scheduler(optimizer, epoch, lr_decay=0.3, lr_decay_epoch=2, number_of_decay=5):
"""
lr_scheduler method is written for decay learning rate by a factor of lr_decay
every lr_decay_epoch epochs
:param optimizer: input optimizer
:param epoch: epoch number
:param lr_decay: the rate of reduction, multiplied to learning_rate
:param lr_decay_epoch: epoch number for decay
:param number_of_decay: total number of learning_rate reductions
:return:
optimizer
"""
if lr_decay_epoch * number_of_decay < epoch:
return optimizer
if (epoch+1) % lr_decay_epoch:
return optimizer
for param_group in optimizer.param_groups:
param_group["lr"] *= lr_decay
return optimizer
|
887c013f4f1efbe4cc6ebb1479d678df58f9a00c
| 38,377 |
async def startlist() -> dict:
"""Create a startlist object."""
return {
"id": "startlist_1",
"event_id": "event_1",
"no_of_contestants": 0,
"start_entries": [],
}
|
f66299795bfb674b7e97396200d381022c4413a2
| 38,379 |
import pathlib
def get_cache_dir(predefined_path=None):
"""Get the cache directory path and potentially create it.
If no predefined path provided, we simply take `~/.mltype`.
Note that if one changes the `os.environ["home"]` dynamically
it will influence the output of this function. this is done
on purpose to simplify testing.
Parameters
----------
predefined_path : None or pathlib.Path or str
If provided, we just return the same path. We potentially
create the directory if it does not exist. If it is not
provided we use `$HOME/.mltype`.
Returns
-------
path : pathlib.Path
Path to where the caching directory is located.
"""
if predefined_path is not None:
path = pathlib.Path(str(predefined_path))
else:
path = pathlib.Path.home() / ".mltype"
path.mkdir(parents=True, exist_ok=True)
return path
|
8c2ff5ecc40a1d3d1399b4f02ddb04759938430e
| 38,380 |
def twoValueImage(image, G, background='white'):
"""将图像变黑白
:param image: Image对象
:param G: 阈值
:param background 背景颜色, 默认为白色
:return: Image对象
"""
# 转成灰度图
image = image.convert('L')
# image.show()
for y in range(0, image.size[1]):
for x in range(0, image.size[0]):
g = image.getpixel((x, y))
if background == 'white':
if g > G:
image.putpixel((x, y), 255)
else:
image.putpixel((x, y), 0)
else:
if g > G:
image.putpixel((x, y), 0)
else:
image.putpixel((x, y), 255)
return image
|
1569b704040af53e2185c18d369be7dfa4ace34b
| 38,386 |
def remove_domain(hn):
"""Removes domain suffix from provided hostname string
Args:
hn (str): fully qualified dns hostname
Returns:
str: hostname left by removing domain suffix
"""
return hn.split(".")[0]
|
07e5136d06f4206f7cd071cda14d3db677f7a37b
| 38,387 |
import re
def standardize(s):
"""
字符串标准化
去除所有空格
去掉末尾最后一个 的
小写转大写
中文字符替换: (),【】:“”’‘;
:param s:
:return:
"""
s = re.sub(r'\s+', '', s)
s = re.sub(r'的$', '', s) # 去掉末尾最后一个 的
s = re.sub(r',未特指场所$', '', s)
s = s.upper()
s = re.sub(r'(', '(', s)
s = re.sub(r')', ')', s)
s = re.sub(r',', ',', s)
s = re.sub(r':', ':', s)
s = re.sub(r'【', '[', s)
s = re.sub(r'】', ']', s)
s = re.sub(r'“|”|’|‘', '"', s)
s = re.sub(r'】', ']', s)
s = re.sub(r';', ';', s)
return s
|
53beb2c588a9a69d5bff1d389f7e3b627d9577d6
| 38,399 |
def startswithlow(x, start, startlow=None):
"""True if x starts with a string or its lowercase version. The lowercase
version may be optionally be provided.
"""
if startlow is None:
startlow = start.lower()
return x.startswith(start) or x.lower().startswith(startlow)
|
18b0b19cfaa62e0c2d2a3350226e167cb8065e8c
| 38,408 |
import string
def ignore_whitespace(a):
"""
Compare two base strings, disregarding whitespace
Adapted from https://github.com/dsindex/blog/wiki/%5Bpython%5D-string-compare-disregarding-white-space
"""
WHITE_MAP = dict.fromkeys(ord(c) for c in string.whitespace)
return a.translate(WHITE_MAP)
|
9f90e0cd10744fe337f9469913654d0dd951f2a5
| 38,416 |
def word_to_put_req(word_vectors_map, word):
"""
Translate a word to a PUT request to be sent to DynamoDB
"""
return {
'PutRequest': {
'Item': {
'word': {
'S': word
},
'vector': {
'L': [{'N': str(n)} for n in word_vectors_map[word]]
}
}
}
}
|
1734463d60869c4c51ba40f61ad19e16ead75345
| 38,422 |
import time
def iso_time(value=None):
"""Format a timestamp in ISO format"""
if value == None:
value = time.localtime()
tz = time.timezone / 3600
return time.strftime('%Y-%m-%dT%H:%M:%S-', value) + '%(tz)02d:00' \
% vars()
|
889a94f6a3fcbc088726fab4eaac36aff5057f4c
| 38,423 |
def key_prefix(key):
"""Returns the key prefix that can be used to find the latest key with that given prefix."""
return key.split('{')[0]
|
fe6c3390ebe7a183b790d9743b3e0d6ef90113cb
| 38,426 |
import re
def extract_tag(etree_tag):
"""An etree tag comes in the form: {namespace}tag. This returns the tag"""
match = re.match(r'(?:\{.+\})?(.+)', etree_tag)
if not match:
return ""
return match.group(1)
|
78e780543b95e36116dfcbad78323e73b6e6fea4
| 38,428 |
import random
def train_test_split(df, test_size):
"""Randomly selects data, and splits it based upon
the specified test size.
Usage: `train_test_split(df, test_size)`
Returns training and testing data.
If a float is input as test_size, it's treated as percentage."""
# If our test_size is a float, we're going to treat it as a percentage.
# We need to calculate and round, because k below requires an integer.
if isinstance(test_size, float):
test_size = round(test_size * len(df))
# Sampling test indices.
test_idx = random.sample(population=df.index.tolist(), k=test_size)
train_df = df.drop(test_idx) # Training data / test indices dropped.
test_df = df.loc[test_idx] # Testing data / only test indices.
return train_df, test_df
|
1b010ebc47ad900f520f570b7918d8de74e19895
| 38,432 |
def is_type(valid_type):
"""Returns a validator function that succeeds only for inputs of the provided valid_type.
:param type valid_type: the type that should be considered valid for the validator
:returns: a function which returns True its input is an instance of valid_type, and raises TypeError otherwise
:rtype: callable
"""
def validate(value, should_raise=True):
if not isinstance(value, valid_type):
if should_raise:
raise TypeError(
"Expected value of type {expected}, actual value was of type {actual}.".format(
expected=valid_type, actual=type(value)
)
)
return False
return True
return validate
|
84b7090671f70e84b4f259d69789153e517b8c79
| 38,444 |
def get_config_option(options, option_name, optional=False):
"""Given option_name, check and return it if it is in appconfig.
Raises ValueError if it is missing and mandatory
"""
option = options.get(option_name)
if not option and not optional:
raise ValueError('"{0}" is mandatory and is not set in the app.config file'.format(option_name))
return option
|
7b8bb2cebab02ff832b01b4b88f33f4c2fe67574
| 38,445 |
def parse_usb_id(id):
""" Quick function to parse VID/PID arguments. """
return int(id, 16)
|
05c22e38fa7ce813c042c1dc8e45e4b36549723d
| 38,447 |
def split_obs(obs):
"""Split a dict obs into state and images."""
return obs['state'], obs['img']
|
ebb043f2b75c2a9e12883ef8fe49595c3a751483
| 38,450 |
from typing import List
def _get_difference_by(fields1: List[str], fields2: List[str]) -> List[str]:
"""Get list with common fields used to decimate and difference given Datasets
Args:
fields1: Fields of 1st Dataset
fields2: Fields of 2nd Dataset
Returns:
List with common fields to decimate and difference given Datasets
"""
difference_by = []
common_fields = set(fields1) & set(fields2)
for field in ["time", "satellite"]:
if field in common_fields:
difference_by.append(field)
return difference_by
|
f80b36788c895269e41f6b2a67fe8961c58fb73c
| 38,453 |
def to_second(dt):
"""
Truncates a datetime to second
"""
return dt.replace(microsecond = 0)
|
191cb118fa35dfa3dc92e58aebeb60b4a3661beb
| 38,459 |
def share_zeros(x):
"""Calculate the share of 0s in a pandas.Series."""
return (x == 0).sum() / len(x)
|
f626695404c43a1520b023a952c733111ce289f1
| 38,466 |
def transform_point(point, direction, value):
"""
Moves point in direction
:param point: Point for movement
:type point: DB.XYZ
:param direction: Direction of movement. Vector
:type direction: DB.XYZ
:param value: The amount of movement
:type value: int or float
:return: New moved point
:rtype: DB.XYZ
"""
return point + direction * value
|
996c4978be165b31b3b60c24cd6927840f6ced94
| 38,474 |
from typing import Union
def _dedup(data: Union[list, tuple]) -> list:
"""Remove duplicates from a list/tuple, then return a new clean list"""
ndata = []
for d in data:
if d in ndata: continue
ndata.append(d)
return ndata
|
0d152445a8c44b14d42476f31e34727e0373a1d1
| 38,477 |
from typing import Dict
def sparse_dot(sp_vector1: Dict, sp_vector2: Dict) -> int:
"""calculates the dot product of two sparse vectors
>>> a = {0: 1, 1: 2, 2: 3}
>>> b = {0: 4, 1: 5, 2: 6}
>>> sparse_dot(a, b)
32
>>> c = {0: 6, 1: 5, 2: 4}
>>> d = {0: 4, 1: 5, 2: 7, 3: 15}
>>> sparse_dot(c, d)
77
"""
sum = 0
smaller_vector = sp_vector1 if len(sp_vector1) <= len(sp_vector2) else sp_vector2
bigger_vector = sp_vector2 if len(sp_vector1) <= len(sp_vector2) else sp_vector1
for pos,val in smaller_vector.items():
if pos in bigger_vector:
sum += smaller_vector[pos] * bigger_vector[pos]
return sum
|
9639e196507a76bfad790baf29411c7a3f1e460c
| 38,479 |
def create_list(colour):
"""utility function for creating list from colour measurements points
Args:
colour ([numpy.ndarray]): [column wise list containing measurements]
Returns:
[list]: [list of measurements ]
"""
fList = []
for o in range(0, len(colour)):
mInput = [colour[o][0], colour[o][1]]
x, y = float(mInput[0]), float(mInput[1])
fList += [(x, y)]
return fList
|
89184d13956087ce5696498871223aea7415ca7b
| 38,480 |
def explained_variance(preds, targets):
"""
Calculate the explained variance between predictions and targets
Args:
preds(Tensor): predictions
targets(Tensor): ground truth
Returns:
Var: explained variance
"""
return (1 - (targets - preds).var() / targets.var()).asnumpy()
|
eb04e0cde784bcd15e50dd0b0345ece85b687cd1
| 38,481 |
import requests
def retrieve_url(url):
"""
Given a URL (string), retrieves html and
returns the html as a string.
"""
html = requests.get(url)
if html.ok:
return html.text
else:
raise ValueError("{} could not be retrieved.".format(url))
|
90137fbcb8c91f6c58f47da3b75fbbc524b26ce7
| 38,484 |
def uid_to_device_id(uid):
"""
Turn UID into its corresponding device ID.
"""
return uid >> 72
|
c81ca0d65be1d9351716e8f9b89676755c3af191
| 38,485 |
def print_func(msg: str) -> bool:
"""
print_func()
Print a hash guarded msg
"""
length = len(msg) + 4
fullhashline = ""
for _ in range(0, length):
fullhashline += "#"
sparsehashline = "#"
for _ in range(1, (length - 1)):
sparsehashline += " "
sparsehashline += "#"
print(
"".join(
[
fullhashline,
"\n",
fullhashline,
"\n",
sparsehashline,
"\n",
"# ",
msg,
" #",
"\n",
sparsehashline,
"\n",
fullhashline,
"\n",
fullhashline,
]
)
)
return True
|
18014b770e3197462bf541717b62f5e73753cd73
| 38,486 |
def GetNextLine(File):
"""Get the next line in a file ignoring lines beginning with *
a space or empty lines. If the end of file is reached None is returned
otherwise a string with the line will be returned."""
while 1:
Line = File.readline()
if len(Line) == 0:
return None
elif Line[0] == '*' or Line[0] == '\n' or Line[0] == ' ':
continue
else:
return Line
|
0aa3a605df40233ce0329943f1767a371a8f861b
| 38,488 |
def _log_msg(name: str, size: int) -> str: # pragma: no cover
"""Return log message for creation of file.
Args:
name (str): Name of the created file.
size (int): Size of the created file.
Returns:
str: Log message with information about the created file.
"""
i = 0
units = ['B', 'KB', 'MB', 'GB', 'TB']
while size >= 1000:
size = round(size / 1000)
i += 1
size_str = '%d%s' % (size, units[i])
return "%s | %s" % (name, size_str)
|
9b4b6fb40aed78e10e11e7ddbd8905189917a0a9
| 38,489 |
def collapsed_form(form):
"""Render a collapsed form."""
return {'form': form}
|
5de13024af447b8a9cf8f06afb94a325888569ad
| 38,490 |
def get_beads_2_M(sigma, SI=False):
"""
Computes conversion from beads/sigma^3 to mol/L.
If SI True, sigma is expected in meters. Otherwise, in Angstroms.
"""
# Avogadro's number [molecules/mol]
NA = 6.022E23
# conversion of meters^3 to L
m3_2_L = 1E3
# conversion of meters to Angstroms [A]
A_2_m = 1E-10
if not SI:
sigma *= A_2_m # converts from A to m
# conversion from beads/sigma^3 to mol/L (M)
beads_2_M = (NA * sigma**3 * m3_2_L)**(-1)
return beads_2_M
|
420ea4b681ba81cd23388053850a6916ee4e834e
| 38,492 |
import random
import string
def random_id(length=12) -> str:
"""
generates a random string using the url-safe base64 characters
(ascii letters, digits, hyphen, underscore).
therefore, each letter adds an entropy of 6 bits (if SystemRandom can be trusted).
:param length: the length of the random string, defaults to 12
:return: a random string of the specified length
"""
rand = random.SystemRandom()
base64_chars = string.ascii_letters + string.digits + '-_'
return ''.join(rand.choice(base64_chars) for _ in range(length))
|
fa96ebfc407a840d52c185bd486d87b5931aa0a3
| 38,495 |
import json
def read_cn5_surface_text_from_json(input_file):
"""
Reads conceptnet json and returns simple json only with text property that contains clean surfaceText.
:param input_file: conceptnet json file
:return: list of items with "text" key.
"""
def clean_surface_text(surface_text):
return surface_text.replace("[[", "").replace("]]", "")
items = []
for l_id, line in enumerate(open(input_file, mode="r")):
item = json.loads(line.strip())
text = clean_surface_text(item["surfaceText"])
items.append({"text": text})
return items
|
09ff9a177620b765411d04664fcb81d3df11b144
| 38,496 |
def validate_password(password):
"""Validates a password
Notes
-----
The valid characters for a password are:
* lowercase letters
* uppercase letters
* numbers
* special characters (e.g., !@#$%^&*()-_=+`~[]{}|;:'",<.>/?) with the
exception of a backslash
* must be ASCII
* no spaces
* must be at least 8 characters
Parameters
----------
password: str
Password to validate
Returns
-------
bool
Whether or not the password is valid
References
-----
http://stackoverflow.com/q/196345
"""
if len(password) < 8:
return False
if "\\" in password or " " in password:
return False
try:
password.encode('ascii')
except UnicodeError:
return False
return True
|
3d92419af09494a0d98c7bca07c9237ce60dad42
| 38,499 |
def format_phone(phone):
"""
Format a string as a phone number.
"""
if len(phone) == 10:
return "(" + phone[:3] + ") " + phone[3:6] + "-" + phone[-4:]
else:
return phone
|
7506c7c5b3724b27435c54048a478a73edf16ece
| 38,504 |
def update_status_message(name, status):
"""Create an update status message
Args:
name (str): name of data provider
status (bool): flag indicating whether or not new files have been downloaded
Returns:
str: update_status_message
"""
if status:
return name + ": Update available"
else:
return name + ": No updates"
|
99757b6657606deb16694d6413e1a81138d149d3
| 38,508 |
def merge_maps(*maps):
"""
Merge the given a sequence of :class:`~collections.Mapping` instances.
:param maps: Sequence of mapping instance to merge together.
:return: A :class:`dict` containing all merged maps.
"""
merged = {}
for m in maps:
merged.update(m)
return merged
|
c3d1c393179a41f80506e1523535b7bf9c2152ed
| 38,509 |
def round_down(value, base):
"""
Round `value` down to the nearest multiple of `base`.
Expects `value` and `base` to be non-negative.
"""
return int(value - (value % base))
|
b77bee19f404020be551489f972284f5ee8015ba
| 38,511 |
def compare_locations(loc1, loc2):
"""Checks whether locations are within 1kb of each other"""
if loc1[0] == loc2[0] and loc1[2] == loc2[2] and abs(int(loc1[1]) - int(loc2[1])) < 1000:
return 'close'
else:
return 'far'
|
be29c4e7004d5c4b45463e38e65d22c277002b9f
| 38,513 |
def calc_absent(marks):
""" Function which returns the count of absent students. """
absent_count = 0
for mark in marks:
if mark == 0:
absent_count += 1
return absent_count
|
444c56dcabe4824c76f44bf07119fb14eedec15f
| 38,514 |
def parse_authors(authorstr: str):
"""
Create an array of authors from an author list (in the name <email> format) separated
by comma
"""
return [a for a in authorstr.split(",") if a.strip() != "" ]
|
e5e799cad6897a8b4fe77d6488c5cf3375fb0856
| 38,525 |
def set_equal(one, two):
"""Converts inputs to sets, tests for equality."""
return set(one) == set(two)
|
4f1be741dc3f5d68fd5b540701e5c02aaee73465
| 38,529 |
def human_size(size, units=(' bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB')):
"""
Returns a human readable string representation of bytes
"""
return "{}".rjust(6 - len(str(size))).format(str(size)) + units[0] if size < 1024 else human_size(size >> 10, units[1:])
|
84dba431ddddbfd5a6d6c68712a448a8b970ee61
| 38,538 |
def parse_archive_filename(filename):
"""
Read the filename of the requested archive and return
both the chart name and the release version.
"""
chunks = filename[:-4].split('-')
chart_name = '-'.join(chunks[:-1])
version = chunks[-1]
return chart_name, version
|
c35f0e0f1eae45f1cd5f6317528341c6c507b32d
| 38,540 |
def have_same_shapes(array1, array2):
"""
Returns true if array1 and array2 have the same shapes, false
otherwise.
@param array1:
@param array2:
@return:
"""
return array1.shape == array2.shape
|
58f5460687ce0ccb7e648527a025a3121b6d5f6b
| 38,544 |
def get_file_or_default(metric_file):
""" Returns the module name from which to extract metrics. Defaults to cohorts.metrics
:param str metric_file: The name of the module to extract metrics from
:return: The name of the module where metric functions reside
"""
return metric_file if metric_file is not None else 'cohorts.metrics'
|
18cfc8a2a892af5cc038fd22aa7f88838aaec270
| 38,546 |
import requests
def get_gear(name,realm="sargeras"):
"""Query the raider.io server for gear information on a character and return as a formatted string"""
url = f"https://raider.io/api/v1/characters/profile?region=us&realm={realm}&name={name}&fields=gear"
response = requests.get(url).json()
gear = response["gear"]
message = f"{name}'s Gear:\n" \
f"--------------------\n" \
f"Equipped Item Level: {gear['item_level_equipped']}\n" \
f"Total Item Level: {gear['item_level_total']}\n" \
f"Artifact Traits: {gear['artifact_traits']}\n" \
f"-------------------\n"
return message
|
ebe1f53eed37b0dadccb3ca25c5e7a5384f66228
| 38,552 |
def template_format(template):
"""Parse template string to identify digit formatting,
e.g. a template med#####.xml.gz will give output (#####, {:05})
"""
num_hashes = sum([1 for c in template if c == "#"])
return "#"*num_hashes, "{:0" + str(num_hashes) + "}"
|
16e4b7d24a992b82aa652d4918319f9bbecca5b4
| 38,553 |
def rxn_query_str(reactant, product, rxn_id):
"""
Generate cypher MERGE query for reactant and product node.
"""
return "MERGE (r: Molecule {smiles_str:\""+ reactant +"\"}) MERGE (p: Molecule {smiles_str:\""+ product +"\"}) MERGE (r)-[:FORMS {rxn_id: "+ str(rxn_id) +"}]->(p)"
|
3f28f800013a19d8a608c42dd8013ad66fa42e26
| 38,555 |
def grid_points_2d(length, width, div, width_div=None):
""" Returns a regularly spaced grid of points occupying a rectangular
region of length x width partitioned into div intervals. If different
spacing is desired in width, then width_div can be specified, otherwise
it will default to div. If div < 2 in either x or y, then the corresponding
coordinate will be set to length or width respectively."""
if div > 1:
px = [-length / 2.0 + (x / (div - 1)) * length for x in range(div)]
else:
px = [length]
if width_div is not None:
wd = width_div
else:
wd = div
if wd > 1:
py = [-width / 2.0 + (y / (wd - 1)) * width for y in range(wd)]
else:
py = [width]
pts = []
for x in px:
for y in py:
pts.append((x, y))
return pts
|
b3ef8807fcca1c518b73e6a7339a45f8aa3cd4e1
| 38,557 |
def p_a2(npsyns, ninputs):
"""
Probability of selecting one input given ninputs and npsyns attempts. This
uses a binomial distribution.
@param npsyns: The number of proximal synapses.
@param ninputs: The number of inputs.
@return: The computed probability.
"""
p = 1. / ninputs
return npsyns * p * ((1 - p) ** (npsyns - 1))
|
9a245105445c07e31e74aa2fe56cec31612cb7aa
| 38,560 |
from typing import OrderedDict
def unique_list(sequence):
"""
Creates a list without duplicate elements, preserving order.
Args:
sequence (Sequence): The sequence to make unique
Returns:
list: A list containing the same elements as sequence, in the same order, but without duplicates.
"""
return list(OrderedDict.fromkeys(sequence))
|
1939aca821e745959c3ab9be35e304fb453b55dc
| 38,561 |
from typing import Tuple
def string_from_sentence(sentence: Tuple[Tuple]) -> str:
"""Get sentence as string from list of list representation
Args:
sentence (Tuple[Tuple]): Sentence in list of list representation
Returns:
str: Sentence as string
"""
return ''.join([edge[-1] for edge in sentence])
|
c7abf8ff452835b6bbc5706e5e3718453dc5162c
| 38,563 |
import re
def import_file(
client, filename, file_type=None, dirname=None, new_name=None, new_model_type="asm"
):
"""Import a file as a model.
Note: This function will not automatically display or activate
the imported model. If you want that, you should take the file name
returned by this function and pass it to file:open.
Users of the old import_pv function should start using this
function instead.
Args:
client (obj):
creopyson Client.
filename (str):
Source file name.
file_type (str, optional):
File type.
Valid values: "IGES", "NEUTRAL", "PV", "STEP".
Defaults to None. Will analyse filename extension
*.igs*|*.iges* => IGES
*.stp*|*.step* => STEP
*.neu* => NEUTRAL
*.pvz* => PV
dirname (str, optional):
Source directory.
Defaults is Creo's current working directory.
new_name (str, optional):
New model name. Any extension will be stripped off and replaced
with one based on new_model_type.
Defaults to None is the name of the file with an extension based
on new_model_type..
new_model_type (str, optional):
New model type.
Valid values: "asm", "prt"
Defaults to "asm".
Returns:
str: Name of the model imported
"""
data = {"filename": filename, "new_model_type": new_model_type}
if file_type is None:
if re.search(r".*\.(igs|iges).*", filename):
data["type"] = "IGES"
elif re.search(r".*\.(stp|step).*", filename):
data["type"] = "STEP"
elif re.search(r".*\.(neu).*", filename):
data["type"] = "NEUTRAL"
elif re.search(r".*\.(pvz).*", filename):
data["type"] = "PV"
else:
raise TypeError(
f"`{filename}` extension was not recognized, fill in file_type."
)
else:
data["type"] = file_type
if dirname is not None:
data["dirname"] = dirname
if new_name is not None:
data["new_name"] = new_name
return client._creoson_post("interface", "import_file", data, "file")
|
5f1e329e101bba6b71c57dbcd650ee0ced033044
| 38,565 |
def select_unique_pvcs(pvcs):
"""
Get the PVCs with unique access mode and volume mode combination.
Args:
pvcs(list): List of PVC objects
Returns:
list: List of selected PVC objects
"""
pvc_dict = {}
for pvc_obj in pvcs:
pvc_data = pvc_obj.get()
access_mode_volume_mode = (
pvc_data["spec"]["accessModes"][0],
pvc_data["spec"].get("volumeMode"),
)
pvc_dict[access_mode_volume_mode] = pvc_dict.get(
access_mode_volume_mode, pvc_obj
)
return pvc_dict.values()
|
03d46bd9d3350d84205c8031bdf6143f2e3bbf8c
| 38,566 |
def headers(group_id, token):
"""
Generate the headers expected by the Athera API. All queries require the active group, as well as authentication.
"""
return {
"active-group": group_id,
"Authorization" : "Bearer: {}".format(token)
}
|
f86edb9151da099bf9818ffbf8a4eb66f4becb67
| 38,567 |
def get_shorter_move(move, size):
"""
Given one dimension move (x or y), return the shorter move comparing with opposite move.
The Board is actually round, ship can move to destination by any direction.
Example: Given board size = 5, move = 3, opposite_move = -2, return -2 since abs(-2) < abs(3).
"""
if move == 0:
return 0
elif move > 0:
opposite_move = move - size
else:
opposite_move = move + size
return min([move, opposite_move], key=abs)
|
635ee3038a4b78318658288f7876144f82333ebb
| 38,568 |
def verb_forms(s):
"""
From a given verb makes 4-element tuple of:
infinitive: The verb itself
-s: The third form
-ing: Continuous tense
-ed: Past simple tense
"""
words = s.split()
verb = words.pop(0)
third = cont = past = None
if verb[-1] == '^':
verb = verb[:-1]
cont = past = verb + verb[-1] # stop-s # stop-P-ing # stop-P-ed
elif verb[-1] == 'e':
cont = past = verb[:-1] # merge-s # merg-ing # merg-ed
elif verb[-1] in 'sxz' or verb[-2:] in ('ch', 'sh'):
third = verb + 'e' # fix-e-s # fix-ing # fix-ed
elif verb[-1] == 'y':
third = verb[:-1] + 'ie' # tr-ie-s # try-ing # tr-i-ed
past = verb[:-1] + 'i'
return tuple(' '.join([form] + words)
for form in ((verb),
(third or verb) + 's',
(cont or verb) + 'ing',
(past or verb) + 'ed'))
|
ab343e5a64f082e42601a0911f399b0c088f1bc7
| 38,570 |
def is_dark(x, y):
"""
Determine if a given pixel coordinate is a 'dark' pixel or not.
"""
# Odds are (0,0), (0,2), (1,1), (1,3)
# Evens are (0,1), (0,3), (1,0), (1,2)
return (x + y) % 2 == 0
|
0bf137a98e89dc6f9b688aa8e467b709ff53991a
| 38,572 |
from datetime import datetime
def create_database(redis_db):
"""
Create an empty Redis database structure.
"""
destiny_version = "D2"
db_revision = "0"
# Set revision to "0"
# print(destiny_version + ":" + revision)
# redis_db.set(destiny_version + ":" + "revision", "0")
# set metadata to empty:
redis_db.set(destiny_version + ":" + "metadata:date", str(datetime.now()))
redis_db.set(destiny_version + ":" + "metadata:revision", db_revision)
redis_db.set(destiny_version + ":" + "metadata:update_type", "forced")
redis_db.set(destiny_version + ":" + "metadata:successful", "True")
return True
|
5191eedf75c075a0e855c1a4a087077a4c1dbdbc
| 38,573 |
import re
def tokenize(line):
"""Split up a line of text on spaces, new lines, tabs, commas, parens
returns the first word and the rest of the words
>>> tokenize("This,Test")
('This', ['Test'])
>>> tokenize("word1 word2 word3")
('word1', ['word2', 'word3'])
>>> tokenize("word1, word2, word3")
('word1', ['word2', 'word3'])
"""
tokens = [x for x in re.split("[ \f\n\r\t\v,()]+", line) if x]
return tokens[0], tokens[1:]
|
17b6b2b479208ed01be32b13b8231ed8c3adf143
| 38,575 |
def normalize(df):
""" Normalizes data to [0,1].
"""
# copy the dataframe
df_norm = df.copy()
# apply min-max scaling
for column in df_norm.columns:
df_norm[column] = (df_norm[column] - df_norm[column].min()) / (df_norm[column].max() - df_norm[column].min())
return df_norm
|
67ed8ac72df8750b34ff87c132d22b04df9be918
| 38,576 |
def utf8len(strn):
"""Length of a string in bytes.
:param strn: string
:type strn: str
:return: length of string in bytes
:rtype: int
"""
return len(strn.encode("utf-8"))
|
d43215730e1bfbb9beb593033b6d8339b45cce2b
| 38,578 |
def get_certificate_fields_list() -> list:
"""Function to get a list of certificate fields for use with struct.unpack()
:return: a list of certificate fields for use with struct.unpack()
:rtype: list
"""
return [
"signer",
"certificate_version_type",
"certificate_type",
"issuer",
"hashedID",
"start_tbs_data",
"hostname_length",
"hostname",
"craca_id",
"crl_series",
"start_validity",
"spacer",
"certificate_duration",
"filler",
"psid",
"verification_key_indicator",
"ecc_public_key_y",
"start_signature",
"ecc_public_key_x_indicator",
"ecc_public_key_x",
"s"
]
|
ec960c5c8031e70bec37390e7164b4997bc18931
| 38,579 |
def to_density_matrix(state):
"""
Convert a Hilbert space vector to a density matrix.
:param qt.basis state: The state to convert into a density matrix.
:return: The density operator corresponding to state.
:rtype: qutip.qobj.Qobj
"""
return state * state.dag()
|
4bdbb2e1dc142408628b5d769c368cbf8bbaf673
| 38,580 |
def append_code(html, code, *args):
"""
Appends the given code to the existing HTML code
"""
if args:
# Format added code first
code = code.format(*args)
return "{0}\n{1}".format(html, code)
|
79d40e6f22c682c37a450c9a025ea09f4ba7a624
| 38,581 |
import math
def get_normalized(vector):
"""Returns normalized vector (2-norm) or None, if vector is (0, 0).
:param vector: of this vector a normalized version will be calculated
:type vector: 2d list
:rtype: normalized version of the vector
"""
result = None
x = vector[0]
y = vector[1]
if not (x == 0 and y == 0):
#Norm of (0,0) is not defined.
n = math.sqrt(x*x+y*y)
result = [x/n, y/n]
return result
|
8e21929bf5b64378d40ed1e1e546a5da9a74af2a
| 38,583 |
def make_grad_fn(clf):
"""Return a function which takes the gradient of a loss.
Args:
clf (Classifier): the classifier whose gradient we are interested in.
Returns:
f (function): a function which takes a scalar loss and GradientTape and
returns the gradient of loss w.r.t clf.weights.
"""
def f(loss, tape):
return tape.gradient(loss, clf.weights)
return f
|
b94c72e0072107e3d9f0e4c8ce2b212fb3393cdd
| 38,590 |
def cummulative_length(fasta, keys):
"""Return the sum of the lengths represented by `keys`."""
keys = set(keys)
lengths = []
for name, seq in fasta.records.items():
if name in keys:
lengths.append(len(seq))
return sum(lengths)
|
eb9daff5e8a6998dbada873900838bdd84fd6ba1
| 38,595 |
import torch
def compute_bounds_from_intersect_points(rays_o, intersect_indices,
intersect_points):
"""Computes bounds from intersection points.
Note: Make sure that inputs are in the same coordiante frame.
Args:
rays_o: [R, 3] float tensor
intersect_indices: [R', 1] float tensor
intersect_points: [R', 2, 3] float tensor
Returns:
intersect_bounds: [R', 2] float tensor
where R is the number of rays and R' is the number of intersecting rays.
"""
intersect_rays_o = rays_o[intersect_indices] # [R', 1, 3]
intersect_diff = intersect_points - intersect_rays_o # [R', 2, 3]
intersect_bounds = torch.norm(intersect_diff, dim=2) # [R', 2]
# Sort the bounds so that near comes before far for all rays.
intersect_bounds, _ = torch.sort(intersect_bounds, dim=1) # [R', 2]
# For some reason the sort function returns [R', ?] instead of [R', 2], so we
# will explicitly reshape it.
intersect_bounds = intersect_bounds.view(-1, 2) # [R', 2]
return intersect_bounds
|
c2692668531472008412c241c8a268a9334b17ad
| 38,608 |
def centerS(coor, maxS):
"""
Center vector coor in S axis.
:param coor: coordinate of vector from S center to M=0
:param maxS: value representing end of estatic axis
:return: S centered coordinate
"""
return int(maxS / 2.0 + coor)
|
d575ddece916889a614971e7c3e45ada12faac71
| 38,612 |
def period_to_int(period):
"""
Convert time series' period from string representation to integer.
:param period: Int or Str, the number of observations per cycle: 1 or "annual" for yearly data, 4 or "quarterly"
for quarterly data, 7 or "daily" for daily data, 12 or "monthly" for monthly data, 24 or "hourly" for hourly
data, 52 or "weekly" for weekly data. First-letter abbreviations of strings work as well ("a", "q", "d", "m",
"h" and "w", respectively). Additional reference: https://robjhyndman.com/hyndsight/seasonal-periods/.
:return: Int, a time series' period.
"""
mapper = {
"annual": 1,
"a": 1,
"quarterly": 4,
"q": 4,
"daily": 7,
"d": 7,
"monthly": 12,
"m": 12,
"hourly": 24,
"h": 24,
"weekly": 52,
"w": 52,
}
if period not in mapper.keys():
raise ValueError(f"{period} is not a valid value for the 'period' argument.")
return mapper[period]
|
c416acdaff008707bb1f5ad0143e984f4974d9c6
| 38,615 |
def formatter(format_string, kwargs):
"""
Default formatter used to format strings. Instead of `"{key}".format(**kwargs)`
use `formatter("{key}", kwargs)` which ensures that no errors are generated when
an user uses braces e.g. {}. Bear in mind that formatter consumes kwargs
which in turns replaces an used key with empty string "". This can generate
unusual behaviour if not well used.
"""
for key, val in kwargs.items():
key2 = "{%s}" % (key)
if key2 in format_string:
# explicitly convert val to str
format_string = format_string.replace(key2, str(val))
kwargs[key] = ""
return format_string
|
175a6279c8dca0276483b94ba2f6aed9215aefa5
| 38,616 |
import math
def GrieFunc(vardim, x, bound):
"""
Griewangk function
wiki: https://en.wikipedia.org/wiki/Griewank_function
"""
s1 = 0.
s2 = 1.
for i in range(1, vardim + 1):
s1 = s1 + x[i - 1] ** 2
s2 = s2 * math.cos(x[i - 1] / math.sqrt(i))
y = (1. / 4000.) * s1 - s2 + 1
y = 1. / (1. + y)
return y
|
a607f00aa44d55ba139cf4b766f334cccb9ffe11
| 38,627 |
import re
def get_cves_from_text(text):
"""
Extracts CVE from the input text.
:param text: text from which the CVEs are extracted
:return: extracted CVEs
"""
cve_pat = r'CVE-\d+-\d+'
return re.findall(cve_pat, text.upper())
|
be97a73159cdc71d69db8504d91ea30d3a7d2d49
| 38,628 |
import six
def get_strings(value):
"""
Getting tuple of available string values
(byte string and unicode string) for
given value
"""
if isinstance(value, six.text_type):
return value, value.encode('utf-8')
if isinstance(value, six.binary_type):
return value, value.decode('utf-8')
return value,
|
6517c5e2053d1facaf4282da720aaa91ca0ab2e7
| 38,635 |
from typing import Counter
def word_vocab_count(text):
"""
Counts the number of words and vocabulary in preprocessed text.
"""
counts = Counter([
word[0].lower()
for paragraph in text
for sentence in paragraph
for word in sentence
])
return sum(counts.values()), len(counts)
|
b8e47ccc9a028a7d2fcc9ccabef6f833f0f9df34
| 38,648 |
def ensure_unicode(x, encoding='ascii'):
"""
Decode bytes to unicode if necessary.
Parameters
----------
obj : bytes or unicode
encoding : str, default "ascii"
Returns
-------
unicode
"""
if isinstance(x, bytes):
return x.decode(encoding)
return x
|
e37087eb0e2e17cd1b318cbe7bd997c3f3a1c0e2
| 38,649 |
def mean(data):
"""
Get mean value of all list elements.
"""
return sum(data)/len(data)
|
32884e9f1a29b2a37422ec1da04d0c59b6b67d3c
| 38,651 |
from pathlib import Path
import pathlib
def notebook_path() -> Path:
"""Return path of example test notebook."""
notebook_path = pathlib.Path(__file__).parent / pathlib.Path(
"assets", "notebook.ipynb"
)
return notebook_path
|
a3c64350de0bdf680014a253fdbcb0e08ecd362a
| 38,652 |
def patch_grype_wrapper_singleton(monkeypatch, test_grype_wrapper_singleton):
"""
This fixture returns a parameterized callback that patches the calls to get a new grype wrapper singleton
at that path to instead return the clean, populated instance created by test_grype_wrapper_singleton.
"""
def _test_grype_wrapper_singleton(patch_paths: list):
for patch_path in patch_paths:
monkeypatch.setattr(
patch_path,
lambda: test_grype_wrapper_singleton,
)
return _test_grype_wrapper_singleton
|
f95f45f80a8af1a71f1f8ee1ef55162b63ddc9af
| 38,656 |
def bai_path(bamfilepath):
"""Return the path to BAI file in the same directory as BAM file."""
return f"{bamfilepath}.bai"
|
16b642cb40d8c88cd08edba39fea758ec8a4be91
| 38,657 |
def get_min_max(data_column):
"""Function that gets min and max values from a column
Args:
data_column (list): list of data in the column
Returns:
min_value (float): min value in the column
max_value (float): max value in the column
"""
min_index = data_column.idxmin()
max_index = data_column.idxmax()
min_value = data_column[min_index]
max_value = data_column[max_index]
return min_value, max_value
|
ed4c947c7168aaadf88a4c31595984e3b1f3fa7d
| 38,659 |
def folder_name(unit_name):
"""
Extract folder name from full unit name
Example:
Unit 01 - Example unit
returns:
Unit 01
"""
return unit_name.strip()
|
dda9c5806e147119c2bb4d803790777703b3ec38
| 38,660 |
def checkanswer(response, correct_code, json):
"""Takes API response and checks if the response is correct.
Appends value 'API_status' to answer indicating if response correct or not
:param response: requests; response returned by API calls
:param correct_code: int, result code for no errors
:return dict; coverted json of answer (if correct) and 'API_status'
"""
if response.status_code != correct_code:
return {'API_status': False, 'error_code': response.status_code}
elif json:
return {'response': response.json(), 'API_status': True}
else:
return {'API_status': True}
|
335f208c25bbd41bdb0ef9a8967f3805679d616c
| 38,667 |
import re
def get_boundingbox(s) -> dict:
"""
Using the input string (for bbox), parse out the x1, y1, x2, y2 coordinates (i.e. BoundingBox)
and return a dictionary containing the left/top/right/bottom values.
The response dictionary defaults the left/top/right/bottom to 0.
"""
bb_rgx = r'''(?<=bbox )([0-9]{0,4}) ([0-9]{0,4}) ([0-9]{0,4}) ([0-9]{0,4})'''
bb = {
"left":0,
"top":0,
"right":0,
"bottom":0
}
match = re.search(bb_rgx, s.get('title'))
if match:
bb["left"] = int(match.group(1))
bb["top"] = int(match.group(2))
bb["right"] = int(match.group(3))
bb["bottom"] = int(match.group(4))
return bb
|
820559484a9f9c3af409d512318ca9370ef8e042
| 38,671 |
def get_column(su, i):
""" get the ith column of the sudoku """
return [su[j][i] for j in range(len(su))]
|
ff35098f14bed4cef938a4a4e6af3d60fb4e7be3
| 38,674 |
from typing import Any
def is_integer(thing: Any) -> bool:
"""
A function that returns whether the given value is an integer. Note that this will return
``False`` for the value, ``True``, which is different from normal Python.
:param thing: the value to check.
:return: ``True`` if the value is an integer.
"""
return isinstance(thing, int) and not isinstance(thing, bool)
|
f8707dabf95286e03a37240f27517f45f7abd1b2
| 38,675 |
def multiply_operator(word: str, factor: int = 1):
"""
Multiply the string 'word' for the 'factor' value
:param word: string to be multiplied
:param factor: it's default value is 1
:return: multiplied string
"""
return word * factor
|
505221d2003b8aa1db41abba205d9211f4462aef
| 38,682 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.