content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import List
from typing import DefaultDict
def __distinct_elems(mols: List[DefaultDict[str, int]]) -> List[str]:
"""Get the distinct elements that form the molecules."""
elems = set()
for mol in mols:
for key in mol:
elems.add(key)
return list(elems) | f96f4be0768d33253b30fb9278a616126f96720b | 647,445 |
def detect_entity_cols(file):
"""
For now, we assume that the entity column is the first one
:param file:
:return: a list of indices of entity columns
"""
return [0] | c60a35bcc890a2552bfe63097f601a6d1d11920d | 647,446 |
import random
def delay_exponential(base, growth_factor, attempts):
"""Calculate time to sleep based on exponential function.
The format is::
base * growth_factor ^ (attempts - 1)
If ``base`` is set to 'rand' then a random number between
0 and 1 will be used as the base.
Base must be gr... | 15cea06599ac26f03fd1b89c9d2c56342fb8dc96 | 647,447 |
def dijkstra (mazeMap, startLocation) :
"""
Return the routing table of every nodes sarting from startLocation.
"""
bestNodes = {(startLocation):((),0)}
toseeNodes = [startLocation]
while toseeNodes :
node = toseeNodes.pop(0)
neighbours = mazeMap[node]
dist = bestNod... | 587cdaded317b3291f7787a4138ee79e8d995332 | 647,448 |
def valid_data():
"""Valid sample data"""
data = {
"version": 1,
"diag": 0,
"state": 0,
"poll": 0,
"final": 0,
"control_plane_independent": 0,
"authentication_present": 0,
"demand_mode": 0,
"multipoint": 0,
"detect_mult": 1,
... | 788773ae5a253c919ca22d2e2194c9a72ef07886 | 647,449 |
import re
def resolve_sample_from_line(samples, line):
"""
Resolves sample names by splitting fasta line
on non-word characters.
"""
line = re.split("[ \t]", line)
matched_sample = [x for x in samples if x in line]
if len(matched_sample) == 1:
return matched_sample[0]
r... | 691c094276041d886d22e0a9e005c355bfd31a5f | 647,450 |
from typing import Union
from pathlib import Path
import os
import sys
def parse_spec(spec: Union[Path, str]) -> str:
"""
This functions parses a user's module specification into a module identifier that can be imported.
A module specification can either be the name of an installed module, or the path to ... | b81441657c41c187d88706addceac88d945ac9c0 | 647,451 |
def implies(a: bool, b: bool) -> bool:
"""Implication (IF...THEN)"""
return (not a) or b | 378a01b5c857346488355a2ba71d0ea9b02126dd | 647,453 |
import os
def get_script_folder_name():
"""Returns the folder where Enso commands are found. This function
is responsible for ensuring that this folder exists: it must not
return a path that is not present! It is expected to place this
folder in some platform-specific logical location."""
enso_comm... | 63794d7e988d14aec5e7a5077b863b98c445291c | 647,454 |
def _get_acq_time(start, default_value=-1):
"""Private helper function to extract the heuristic count time
The SPEC-style plans inject a heuristic 'count_time' (which has
different meanings in different contexts) as a top-level key in the
RunStart document.
Parameters
----------
start : Do... | ad5bdffb0951abe30873c847f6611d37310651db | 647,456 |
def _DictToTuple(to_sort):
"""Converts a dictionary into a tuple of keys sorted by values.
Args:
to_sort: A dictionary like object that has a callable items method.
Returns:
A tuple containing the dictionary keys, sorted by value.
"""
items = to_sort.items()
items.sort(key=lambda pair: pair[1])
... | 4fccdfcd7a8e4f03e7b12de05aa87ad0a9bfe96f | 647,457 |
def curry(f, *a, **kw):
"""curry(f,x)(y) = f(x,y) or = lambda y: f(x,y)
modified from python cookbook"""
def curried(*more_a, **more_kw):
return f(*(a + more_a), **dict(kw, **more_kw))
# make docstring for curried funtion
curry_params = []
if a:
curry_params.extend([e for e in... | a5698e9ed84bd7b692d261327b58588f9a5ee0af | 647,458 |
def median(obj, time=200):
"""Helper function to apply a median filter to an xarray object."""
return obj.rolling(time=time, center=True).median() | e2dcb7154f7bfb607be108333834f7b05353aebf | 647,459 |
def file_contains_doctests(path):
"""Scan a python source file to determine if it contains any doctest examples.
Parameters
----------
path : str
Path to the module source file.
Returns
-------
flag : bool
True if the module source code contains doctest examples.
"""
... | 6ebeecaa96278be103db1ea577accf6ee63f2442 | 647,460 |
def parse_hex_color(color):
"""Parses a hex format color string, i.e. #ccc or #12ab34, into an (r, g, b) tuple."""
color = color.strip('#')
if len(color) == 3:
color = ''.join(ch*2 for ch in color)
if len(color) == 6:
r = int(color[0:2], base=16) / 255
g = int(color[2:4], base=16... | 95398d933dd29f8654d4ad5dd6b49e9e7f59ae11 | 647,461 |
def cal_intersection(points):
"""
Calculate the intersection of diagonals.
x=[(x3-x1)(x4-x2)(y2-y1)+x1(y3-y1)(x4-x2)-x2(y4-y2)(x3-x1)]/[(y3-y1)(x4-x2)-(y4-y2)(x3-x1)]
y=(y3-y1)[(x4-x2)(y2-y1)+(x1-x2)(y4-y2)]/[(y3-y1)(x4-x2)-(y4-y2)(x3-x1)]+y1
:param points: (x1, y1), (x2, y2), (x3, y3), (x4, y4).
... | 6e4902136b516aa7930c96985b27b5cf3bb1ba1c | 647,462 |
def user_input():
"""User input method returns the array.
Args:
None.
Returns:
A tuple consisting of the array, size of the array, and number
of rotations.
Raises:
None.
"""
print("\nWelcome to the array reversal program! \n\nYou will be"
" asked to en... | 0e233631289198f0e082603da6215f498d22e1ad | 647,463 |
def alignValue(value, align):
"""
Align a value to next 'align' multiple.
>>> alignValue(31, 4)
32
>>> alignValue(32, 4)
32
>>> alignValue(33, 4)
36
Note: alignValue(value, align) == (value + paddingSize(value, align))
"""
if value % align != 0:
return value + alig... | f0331e6e8a363fdc41af863d86ce0903f2fd47a5 | 647,464 |
import itertools
def maxDistToClosestB(seats):
"""
:type seats: List[int]
:rtype: int
"""
ans = 0
for seat, group in itertools.groupby(seats):
if not seat:
K = len(list(group))
ans = max(ans, (K+1)/2)
... | 701505c46c768781460c02b336c4a4c88bee1573 | 647,465 |
def make_list(value):
"""Return a list of items from a comma-separated string.
Surrounding whitespace will be stripped from the list items. If the
provided string is empty, an empty list will be returned. This function
will also accept the value None and return an empty list.
"""
if value is No... | e7ceb8e49c1ab6fa4618065c3b25d1a31f6ccb2e | 647,466 |
def cmd_across_all_procs(hap_objects, method, *arg, **kargs):
"""Return the result of a command executed in all HAProxy process.
.. note::
Objects must have a property with the name 'process_nb' which
returns the HAProxy process number.
:param hap_objects: a list of objects.
:type hap_... | cc5aa41a61d0974693af7a9d7c0fb04bb2bd99b1 | 647,467 |
import os
import subprocess
def run_single(assay, test_dir):
"""
Returns:
string indicates complete status
"""
os.chdir(os.path.join(test_dir, assay))
print("*" * 20 + "running " + assay + "*" * 20)
subprocess.check_call('sh run_shell.sh', shell=True)
subprocess.check_call('sh sjm.... | 4a7ef7cf7157ddd829a89afe5c42f9940ce02385 | 647,468 |
def combine(background_img, figure_img):
"""
Finding the green pixel of figure image and then replace by background pixel.
:param background_img: SimpleImage, the image of background.
:param figure_img: SimpleImage, the image of figure.
:return: SimpleImage, the figure image with all green pixel rep... | ff23fa9b69d4ccda6a85703d656f65ef226d5d0e | 647,469 |
def nestedmap(f, args, type=list):
"""
Map `f` over `args`, which contains elements or nested lists
"""
result = []
for arg in args:
if isinstance(arg, type):
result.append(list(map(f, arg)))
else:
result.append(f(arg))
return result | ed286a1d1f529042c2dd3df21f112b1afd3d7262 | 647,470 |
def evaluateModel(model, variables):
"""
Evaluates a model given all datapoints required.
LModel model the model to be evaluated
dict variables the variables of the model
Remark Need to restrict the global values used for evaluation.
return float
"""
... | e56bc24aad9c48e10e4c9e5f9b41a784bd60b1af | 647,472 |
import math
def part_1(memory_loc):
"""Get the manhattan distance from a location to the centre of a
(1-indexed) spiral array
Arguments
---------
memory_loc : int, the location of the starting point. Locations are
numbered anticlockwise from the centre, and head right first, e.g.
... | 05d9490c7695b5635ba936352a32985009533cad | 647,473 |
def suppression_factor(delta_g, derivative_nk):
"""Gera o fator de supressão"""
return ((2*delta_g) + derivative_nk) / 3 | eee62216a90dd7a77eca82b14247318fb0d0ff97 | 647,474 |
def parserDateToString(date):
"""Funkcja zmieniająca obiekt datetime.date na string postaci YYYYMMDD"""
date = str(date)
date = date.replace('-','')
return date | 8d115683e90b4ed98cf4cf586a64878399e69ac3 | 647,475 |
from pathlib import Path
import os
def slices_filename_content_hash() -> dict:
"""create a dict of filename: content for slices"""
docker_slices = {}
path = Path.cwd().joinpath(
os.path.join(os.path.dirname(os.path.realpath(__file__)), "slices")
)
for file in path.iterdir():
docker... | bb55703008d29a6d44c902ea6a10651d30efbdf8 | 647,476 |
def rgb_to_hex(rgb):
"""Converts an rgb tuple to hex string for web.
>>> rgb_to_hex((204, 0, 0))
'CC0000'
"""
return ''.join(["%0.2X" % c for c in rgb]) | 40e325c766b486f8f55148f094fd6776f8d53e76 | 647,477 |
import pytz
def tz_aware(dt, tz):
"""
Ensures that a datetime object is time zone aware.
Only makes changes to naive datetime objects.
:param dt: datetime -- any valid datetime object
:param tz: string in IANA time zone database format -- the timezone to attach to the object
:returns: datetim... | b055e1442badab7f8cc9ebb980f05704a1edf455 | 647,478 |
def calc_energy(pos, vels):
"""calculates the sum of the total energies of the moons. Each moon's
potential energy is the sum of the absolute values of its position
components. Its kinetic energy is the sum of the absolute values of its
velocity components. The total energy for a moon is the product ... | 39c5c352a22da43cce158ab6e076e39860729afc | 647,479 |
def poly_desc(W, b):
"""Creates a string description of a polynomial."""
result = 'y = '
for i, w in enumerate(W):
result += '{:+.2f} x^{} '.format(w, len(W) - i)
result += '{:+.2f}'.format(b[0])
return result | ef2a870916581f2da48aed7010a81adf3af823f1 | 647,481 |
import argparse
def parse_args(args):
"""
Information extracted from: https://mkaz.com/2014/07/26/python-argparse-cookbook/
https://docs.python.org/3/library/argparse.html
:return: parse.parse_args(args) object
You can use obj.option, example:
options = parse_args(args)
options.user # to ... | 7b06c98bf373ffd0f6e0b77f043b939e7584cb22 | 647,482 |
def list_projects(service, filter_list):
"""Build service object and return the result of calling the API 'list' function for the projects resource."""
operation = service.projects().list(filter=filter_list).execute()
return operation | fffdd3e581f0ef9e8d329f937d4d5d8dcdbf0a62 | 647,483 |
from bs4 import BeautifulSoup
def get_chapter_list(html):
"""get the joke of the html"""
print(html)
soup = BeautifulSoup(html, 'lxml')
# joke_content = soup.select('#contents')[0].get_text()
# head = soup.select('head')[0]
# print("head: \n", head)
# chapter_list = soup.find(class_='list... | dc2b3a2eacfb959a8a5d61a1cbd53f75058d9e8d | 647,484 |
import argparse
def get_options():
"""Get arguments from command line.
Parameters
----------
Returns
-------
"""
parser = argparse.ArgumentParser(description="""
Simple tool to unmess your photos.
Usage:
tidy_mypics --source /my/messy/photos/ --target /my/tidy/photos/
... | 4c85f18190d5432399ddcd3725f93b8e44334281 | 647,485 |
def get_prefix(network):
"""Convert network type to prefix of address
:param network: testnet or mainnet
:type network: str
:returns: tbnb or bnb
"""
return 'tbnb' if network == 'testnet' else 'bnb' | ba4af04093f5486be68c70df20d87733d4f146fa | 647,486 |
def get_size_from_image(img):
"""
`calc_st_pos_for_centering()` の引数計算が面倒だったので関数化。
"""
return (img.shape[1], img.shape[0]) | b8322b6fb8a5788591b949fb39d17964fbd4f9d1 | 647,487 |
import pathlib
import errno
import os
def mkdir_p(target, is_file=False):
"""Create the directory path to the target.
If the target is a file, create the path to its parent (directory)
:param str target: path to a target directory or file
:param bool is_file: Indicates whether the target is a file
... | c9b2e3e078369fc651dd58908d82af9b8cf83a4c | 647,488 |
def __insert_color_custom(txt, s, c):
"""insert HTML span style into txt. The span will change the color of the
text located between s[0] and s[1]:
txt: txt to be modified
s: span of where to insert tag
c: color to set the span to"""
return txt[:s[0]] + '<span style="font-weight: bold;color: {0}... | 60e7177b588c48c20a5146a92e49f99ad232eb5a | 647,489 |
def normURLPath(path):
"""
Normalise the URL path by resolving segments of '.' and '..'.
"""
segs = []
pathSegs = path.split('/')
for seg in pathSegs:
if seg == '.':
pass
elif seg == '..':
if segs:
segs.pop()
else:
seg... | 78abcc6c1cce17e5678baac10af96db508b3d57a | 647,490 |
def compose1(f, g):
"""Return a function that composes f and g.
f, g -- functions of a single argument
"""
def h(x):
return f(g(x))
return h | 8d4829a787b78826f1c03d5e9621fb7d6a6ea56c | 647,491 |
import numpy
def rotation_invariant_LBP(img, radius=6, neighbors=8):
"""
~旋转不变LBP~
rx, ry为采样点对于中心点坐标的偏移量
x1,x2,y1,y2是为双线性插值做准备
tx,ty为通过减运算将坐标偏移量映射到0到1之间
w1,w2,w3,w4为根据权重计算公式计算的结果
LBP特征图像的邻域的LBP值累加,累加通过与操作完成,对应的LBP值通过移位取得
旋转不变计算各种情况,取最小值
"""
dst = numpy.zeros(
(img.shape... | e432878cc32339b49d6cd3ecc33c6fcfeae1e23d | 647,492 |
import platform
def get_system_type():
"""
获得系统的类型
:return: 字符串类型的系统类型
"""
return platform.system() | e3613351143dc0cf018b26ee35384b5bcb1f9f22 | 647,493 |
def get_messages_per_weekday(msgs):
"""Gets lists of messages for each day of the week (7 lists in a dictionary total).
Args:
msgs (list of MyMessage objects): Messages.
Returns:
A dictionary such as:
{
day_of_the_week (int 0-6): list off all messages sent on th... | aaa509db067a0b42a3d6af0ff5bdbe4128cde9f5 | 647,494 |
def aq(string):
"""
Add the quotes " characters around a string if they are not already there.
Parameters
----------
string : str
just a string to be formatted
Returns
-------
str
a string with " character at the beginning and the end
"""
tmp = string
if n... | c255361e546703eb35cc88af6745001dfee62327 | 647,495 |
def _is_valid_back_ref(index):
"""
Helper method used to ensure that we do not use back-reference values
that would produce illegal byte sequences (ones with byte 0xFE or 0xFF).
Note that we do not try to avoid null byte (0x00) by default, although it would be technically possible as well.
:param in... | ea8c62d7a0676c8b68116317515e9b2a89fdfb88 | 647,496 |
def get_ordersize():
"""
place holder for getting proposed order size based on reserves
available on exchange.
:return:
"""
return 0.01 | 8ae203c0e5f3cce8a29a898301f4c053ffb29b43 | 647,497 |
import torch
def edge_loss(disp, img):
"""Computes the smoothness loss for a disparity image
The color image is used for edge-aware smoothness
"""
grad_disp_x = torch.abs(disp[:, :, :, :-1] - disp[:, :, :, 1:])
grad_disp_y = torch.abs(disp[:, :, :-1, :] - disp[:, :, 1:, :])
grad_img_x = torch... | cee22a18da59f873afb58a29d193a62b0fcdea73 | 647,498 |
def resnet_params(model_name):
""" Map resnet model name to parameter coefficients. """
params_dict = {
# Coefficients: block, res
"resnet18": ("BasicBlock", 224),
"resnet30": ("BasicBlock", 224),
"resnet54": ("Bottleneck", 224),
"resnet101": ("Bottleneck", 224),
... | 6e7b1d621654ec67fed4118b4d37e922a3feb55b | 647,500 |
import argparse
def get_args():
""" this function grabs input arguments from the command line """
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input-file', help="The input file to use")
parser.add_argument('-o', '--output-file', help="The output file to write to")
args = parse... | 241ac3fecf46e8b8c74732fe098d24668e025aac | 647,501 |
def pbc_images(atom, box):
"""
It returns copies of the original Atom object, thus is slower
than pbc_positions.
:param atom: pmx.models.Atom or PositionAtom
:return: list of pmx.models.Atom (all 27 periodic images)
"""
res = []
images = [
(a, b, c)
for a in (-box[0], 0,... | 634da281d625b219354db228defd72ebba192454 | 647,502 |
import os
import configparser
def appium_temp_ini(request):
"""Write an appium config file."""
def fin():
os.remove('stere.ini')
request.addfinalizer(fin)
parser = configparser.ConfigParser()
parser['stere'] = {'library': 'appium'}
with open('stere.ini', 'w') as config_file:
... | a142a2e1f657d235947437062797330fac351ee9 | 647,503 |
def decorator_test():
""" Dummy function for authorization header"""
return True | fc19c145ad43e16ba28f7d3c5d9081f62521f985 | 647,504 |
def event_split(string, event_type):
"""Return a list of event type and event action.
Args:
string (str): The supplied string that will be splitted.
event_type (str): The event type (execute, log, set, etc).
Returns:
list: A list of the splitted string
Examples:
>>> is... | f5193878ebba6344b343fb57c58c6032e5bab41e | 647,505 |
def format_time( seconds ):
"""
Formats the time, in seconds, to a nice format. Unfortunately, the :py:class:`datetime <datetime.datetime>` class is too unwieldy for this type of formatting. This code is copied from :py:meth:`deluge's format_time <deluge.ui.console.utils.format_utils.format_time>`.
:param ... | dba02e146b363b5a468a2a5939d9ab96dafaf838 | 647,506 |
def _invert_dict(data):
"""{a: [b]} -> {b: [a]}"""
inv_dict = {}
for key in data.keys():
for value in data[key]:
inv_dict[value] = inv_dict.get(value, []) + [key]
return inv_dict | d92dfdb63cace79f5936e030b77d39ebbe282579 | 647,507 |
from typing import Any
from pydantic import BaseModel # noqa: E0611
import importlib
def build_model(model: Any, backend: str) -> BaseModel:
"""
Build a correct model wrapper given the backend
:param model: any neural network models, see backend folder for more
details
:param backen... | a6e74545e31dab479ab9bbf7532ace3e88d9b90e | 647,509 |
import re
def convert_token(token):
"""Convert the token into a bool value or a numeric value, if it is one.
If the value is ``'True'`` or ``'False'``, then the matching ``bool`` value is returned.
If the value matches the regular expression ``'^[0-9]+$'``, then it is converted to an ``int`` value.
... | a0b4e7aba718fae0dfea9e012581ae47658990b6 | 647,510 |
def get_cover_url(video_json):
"""
parse cover url from video_json
:param video_json:
:return:
"""
return video_json.get('origin_cover') or video_json.get('cover') | 4ad862428241c220af27249fab5b50c02bd47760 | 647,511 |
def hotspot():
"""Mock hotspot tuple."""
return (0, 0) | ba9dab35d399ede2c01233247af2c66758bfe377 | 647,512 |
from collections import OrderedDict
def get_mock_phy_tb_fields_delete():
"""mock rt对应的物理表结构, 字段删除情况"""
columns = OrderedDict()
columns["thedate"] = "int"
columns["dtEventTime"] = "varchar"
columns["dtEventTimeStamp"] = "bigint"
columns["localTime"] = "varchar"
columns["field1"] = "varchar... | f7c1100bb31fcc0c63c3490d3ddf4ccf2bf20bf4 | 647,513 |
def insert_on_duplicate_update(engine,data):
"""
:param engine:
:param data:
:return:
"""
sql='insert into security_lookup_cn_wave_10(ticker,time_x,price,adj_factor)' \
' values (%s,%s,%s,%s)' \
' on duplicate key update ticker=values(ticker),time_x=values(time_x),price=values(p... | b8c235af48ea92057807b81c34db9b59349d821f | 647,514 |
async def compare_versions(version1:str, version2:str) -> str:
"""take two versions with a 3 decimal points and return the higher one"""
v1 = version1.split('.')
v2 = version2.split('.')
if int(v1[0]) > int(v2[0]):
return version1
if int(v1[0]) < int(v2[0]):
... | ea4ea4b998de2b92c26fdb2f731e7b22a380f114 | 647,516 |
import random
def samplePosition(chromSizes):
"""Get a random (sequence, position) pair from a chromSizes dict. Very
inefficient, but it shouldn't matter much.
"""
genomeSize = sum(chromSizes.values()) # could pull this outside the function easily
genomePos = random.randint(0, genomeSize - 1)
... | 75c3921af115ddf90e8b35bdf44b978c9985c691 | 647,517 |
def average_true_area(truth, cc, look_at):
"""
Calculates average true area of all considered cells
"""
area = 0
cellcount = 0
for p in cc:
if not look_at[p]:
continue
t = cc[p]
if t==0:
continue
cellcount += 1
area += (truth==t).su... | bd596e02e89bf3dc014a5ee571f84921b5c54114 | 647,518 |
import ipaddress
def _to_subnet(subnet):
""" used to cache subnet conversions used by in_subnet """
return ipaddress.ip_network(subnet) | fe3b3767145096e3e7f280f473e1a0b090e8ba17 | 647,519 |
def parse_command_byte(byte_val: int) -> str:
"""Command byte"""
if byte_val == 0xC2:
return "Configure temporary registers"
elif byte_val == 0xC1:
return "Answer / Read registers"
elif byte_val == 0xC0:
return "Configure registers"
else:
raise ValueError(f"Unknown re... | 2b2a4b6953bd52d7f716600fcbf9cc309a4e26b4 | 647,520 |
import sys
def load(filename):
"""Open dict text file, check for errors, & make word list."""
try:
with open(filename) as my_file:
my_list = my_file.read().strip().split('\n')
my_list = [x.lower() for x in my_list]
return my_list
except IOError as e:
pri... | 1812edd9aea1fbf4aac0d979c244afac2248b227 | 647,522 |
import argparse
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='VGG19 inference')
parser.add_argument('--model', dest='model', help='Model path',
required=True)
parser.add_argument('--input_dir', dest='input_dir', help='Directory wh... | f27d1ff245ccdf8831c6648795ae0f2e2c8ff152 | 647,523 |
from typing import List
import os
def compare_folder_with_files(folder: str, file_list: List[str]) -> bool:
"""Compare file existing in two folders
Args:
folder: path to a folder
file_list: list of files which must be found in folder
Returns:
True if files in file_list were all f... | e89441ac39fbe1562b6e6ac90e9305a2d48e025e | 647,524 |
def memory_in_gb(bytes: int) -> float:
"""
Converts a memory amount in bytes to gigabytes.
:param bytes:
:return:
"""
gb = 2 ** 30
return bytes / gb | d8d9206c934a15cff1538b95c4daed671d36cf94 | 647,526 |
def get_page_size(h1_content):
"""
:param h1_content: determine the total number of pages we have to scrape for
:return: the number of pages that are contained in the report
"""
# Iterate through each row and find 'page'
for row in h1_content:
# If contains pages, we assume its greater t... | 18d83019034423988db34c7ac19e0bf4011675a4 | 647,527 |
import re
def version_greater_or_equal_than(version_str, other_version_str):
""" Checks if a version number is >= than another version number
Version numbers are passed as strings and must be of type "N.M.Rarb" where N, M, R
are non negative decimal numbers < 1000 and arb is an arbitrary string.
For ... | 94d5232851f63ac5b6c2d0d2a2ad5df68729c1db | 647,528 |
import os
def modules():
"""
Get all the module names for the package.
:rtype: list[str]
"""
names = []
dirname = os.path.dirname(os.path.dirname(__file__))
for filename in os.listdir(dirname):
names.append(filename)
return names | e6b24c83f1c5383adb7bd14ab9fa4d75656ccb0d | 647,529 |
def find_diff_indexes_and_lenght_on_same_size_values(value_one, value_two):
"""Find the diff indexes and lenght of the difference, as follows below, and return on an array of diffs. Some more details follows below:"""
"""(a) on the first different char in a sequence, save that index on a buffer along with t... | f9469178d7813ee736f593cf64f3fa0eac1da4cb | 647,530 |
from typing import List
def fixture_family_tag_names(vcf_tag_name: str, family_tag_name: str) -> List[str]:
"""Return a list of the family tag names"""
return [vcf_tag_name, family_tag_name] | def503a86ea26f989cfd46a2b98af1379d5ddf47 | 647,531 |
from typing import OrderedDict
def list_projects(cells, realname_dict):
""" Given a list of cells, which have 'Project' set, come up with a set of headings
to print and return a list of (name, heading, cells) tuples.
The list of names will be converted to a sorted set.
"""
if realname_dict... | a2cf451dbcaee03a7925c540f64cfb3750fab970 | 647,532 |
import random
def assembly_roulette(fracs):
"""In the case where this is only one assembly (i.e., low reactor fidelity),
this method chooses the index
Parameters
----------
fracs : list
the assembly distribution, assumed to be normalized
Returns
-------
idx : int
... | 836ec8297910c9b3d319a9f0e50d331c87b49167 | 647,533 |
def decorator1(f1):
"""make f1 only work on odd numbers"""
def inner_func1(arg1, arg2):
if (arg1%2 != 0) and (arg2%2 != 0):
return f1(arg1, arg2)
return None
return inner_func1 | 7fd82ab02605f710a55231ab69a645cd4ac589fd | 647,534 |
import math
def Percentile(values, percentile):
"""Returns a percentile of an iterable of values. C = 1/2
The closest ranks are interpolated as in "C = 1/2" in:
https://en.wikipedia.org/wiki/Percentile
"""
values = sorted(values)
index = len(values) * percentile - 0.5
floor = max(math.floor(index), 0... | 1ab78b82d41422ecb566f2e325d28bcecd0f9380 | 647,535 |
def formulatostring(formula, operators, numbers):
""" Convert a formula represented as a tree into a string representation
"""
calc = ""
left = formula[0]
op = operators[formula[1]]
right = formula[2]
if isinstance(left, list):
left = formulatostring(left, operators, numbers)
else:
left = str(numbers[left]... | 4a239f87d63014b09392832a64589dcb71195397 | 647,536 |
import argparse
def get_training_args():
"""
Defines the command line arguments necessary to kick off a training session
:return: the command line arguments provided from stdin
"""
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--textdir",
help="The dire... | 547bf938f7601b3426bf949df6949485320875d0 | 647,537 |
import math
def distance(p0, p1):
"""
returns distance between two pubg points in meters
:param p0: point 1
:param p1: point 2
:return:
"""
return math.sqrt((p0[0] - p1[0]) ** 2 + (p0[1] - p1[1]) ** 2 +
(p0[2] - p1[2]) ** 2) / 100 | 82cdac882b58ccbe4f7190b260e13518494f5b02 | 647,539 |
def ask_for_continuation(iteration: int) -> bool:
"""
Ask the user if we can proceed to execute the sandbox.
:param iteration: the iteration number.
:return: True if the user decided to continue the execution, False otherwise.
"""
try:
answer = input(
"Would you like to proc... | 93f007c7ac40bf618eee04dea01e25c2a85cc005 | 647,540 |
import requests
def get_ipam_roles(url, headers):
"""
Get dictionary of existing IPAM roles
"""
api_url = f"{url}/api/ipam/roles/"
response = requests.request("GET", api_url, headers=headers)
all_roles = response.json()["results"]
roles = []
for role in all_roles:
role_info = d... | d912691e86812bb8adf478fc4cd0329e4b1ce86c | 647,542 |
def node_bounds(*nodes):
"""Get the min and max for the x- and y-coordinates for an iterable of `daft.Node`s."""
xs = list(n.x for n in nodes)
ys = list(n.y for n in nodes)
return (min(xs), max(xs)), (min(ys), max(ys)) | 4248961bbbc3ca0c6618d9a255bae41c8b904d81 | 647,543 |
def _GenerateUpdateMask(args):
"""Constructs updateMask for patch requests.
Args:
args: The parsed args namespace from CLI.
Returns:
String containing update mask for patch request.
"""
hive_metastore_configs = 'hive_metastore_config.config_overrides'
labels = 'labels'
arg_name_to_field = {
... | 8292a8bbdc5b386575a788b310ab724345e3aa96 | 647,544 |
def getFormatGID(locs, point, SPLIT = 0.0005):
"""
[NEW] 根据经纬度计算城市网格编号
Args:
locs (TYPE): Description
point (TYPE): [lng, lat]
Returns:
TYPE: Description
"""
if point[0] == '0' and point[1] == '0':
return 0
else:
# LATNUM = int((locs['north'] - locs['south']) / SPLIT + 1)
LNGNUM = int( (locs['eas... | fae60f6958232b1c23490eb72f764a7849361344 | 647,545 |
def find_prime(x):
"""
Usage: Find largest prime numbers within a list of integer.
Argument:
x : a list of integer.
Return:
an integer
Examples:
find_prime([0,1,2,3,4,5])
>>>5
find_prime([0,1])
>>> "No prime number in list"
... | 55edd2efcfa7c82a963bd7eab813d3c672416e6d | 647,546 |
def sphinx_format_parameter(param):
"""Fix for Sphinx #519"""
if param.endswith('_'):
return f'{param[:-1]}\\_'
else:
return param | 0d69ff97496971a9dc01c41764eee71196a55471 | 647,547 |
def verify_command(mn,aa,cmd,why=None,**kwargs):
"""
mn - the OmstNET instance
aa - address of device
cmd - function with args to be called
why - an optional text string to display between tests
**kwargs - optional compare values when reading back data
Sends commands, verifies responses, an... | eefbff6f01f8b1f4532f3e7706cc53ae9a0490b4 | 647,548 |
def initialize_device(module, luks_type, device):
"""Initialize LUKSMeta. This is required only for LUKS1 devices.
Return <error>"""
if luks_type == "luks1":
args = ["luksmeta", "test", "-d", device]
ret, _unused, err = module.run_command(args)
if ret == 0:
return None
... | d9f94ab1ca6216f6e0191781939270131d376978 | 647,549 |
def cert_get_serial(cert):
"""
Fetch the serial number from the certificate.
:param cert:
:return: serial number
"""
return cert.serial | 2051b04277543bafe68c10146f8920e9d9d2fcc5 | 647,550 |
from typing import Optional
from typing import Union
from typing import List
from typing import Tuple
def normalize_to_list(
value: Optional[Union[str, List[str], Tuple[str, ...]]]
) -> List[str]:
"""
Takes the different formats of options containing multiple values and
returns the value as a list obj... | a85a8dd102ffad99ecec8bd3695e09342c99a9a6 | 647,552 |
import torch
import random
def preprocess_seq_for_rnn(x, num_alphabets, cfg, augment=True):
""" pre-processing steps for PLUS-RNN pre-training """
tokens = torch.zeros(len(x) + 2, dtype=torch.long) + (num_alphabets - 1)
tokens[1:len(x) + 1] = x
if not augment:
return tokens
elif cfg.mask... | b110fe833925e68de79b159b0d014b16a641ec32 | 647,553 |
import os
def process_staticfiles_dirs(staticfiles_dirs, default_prefix='/'): # settings.STATIC_URL
"""
normalizes all elements of STATICFILES_DIRS to be of ('prefix','/root/path/to/files') form
the prefix gets added after STATIC_URL
"""
staticlocations = []
for staticdir in staticfiles_dirs:... | 99bec9d6a0553bcc0305e19792c7ada012a08521 | 647,554 |
def flatten_package_lock_dependencies(package_lock_dependencies):
"""
Flattens package.lock dependencies
:param package_lock_dependencies:
:return: tuple(flat_array, dep_mapping)
WHERE
array flat_array is a flat array of all dependencies
dict dep_mapping is a tree representing nested dependenci... | 6e194160aec6775454142fdeb223c0eaa1f66d02 | 647,555 |
import torch
def _select_initial_step(func, t0, y0, order, rtol, atol, norm, f0=None):
"""Empirically select a good initial step.
The algorithm is described in [1]_.
References
----------
.. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
Equations I: Nonstiff P... | 6d5f774e09f15280c2d0995690963588fd146967 | 647,556 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.