content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import time
def gettime():
"""return timestamp"""
return time.time() | 38ac710463f03780c7289fd7746d137c51d6466e | 8,231 |
def abs_of_difference(num1: int, num2: int) -> int:
"""
precondition: parameters must be numbers
calculate difference between num1 and num2 and compute absolute value of the result
>>> abs_of_difference(-4,5)
9
>>> abs_of_difference(1,-3)
4
>>> abs_of_difference(2,2)
0
"""
r... | 6cb2ead6a3ed5899a84280f7356a44d515952c7b | 8,232 |
import os
def get_gpus():
"""
Get the number of gpus per node.
Args:
None
Returns:
num_gpus (int): number of gpus per node
"""
gpu_var = os.environ["SLURM_GPUS_PER_NODE"]
num_gpus = int(gpu_var)
return num_gpus | 667a2be1daf3472a1a30801936d635f8fdcb0a1d | 8,233 |
def int_to_float(value: int) -> float:
"""Converts a uniformly random [[64-bit computing|64-bit]]
integer to uniformly random floating point number on interval <math>[0, 1)</math>.
"""
fifty_three_ones = 0xFFFFFFFFFFFFFFFF >> (64 - 53)
fifty_three_zeros = float(1 << 53)
return (value & fifty_thr... | 7619ec8d0987d9cac06655cab4e2d0787f1e3232 | 8,237 |
def import_(path):
"""
Import string format module, e.g. 'uliweb.orm' or an object
return module object and object
"""
if isinstance(path, str):
v = path.split(':')
if len(v) == 1:
x = path.rsplit('.', 1)
if len(x) == 2:
module, func = x
... | 70327d474a10f1860012cad0de1bbe934840d9b2 | 8,240 |
import sys
def get_config_options():
"""
get config options list
"""
result = []
for class_name in dir(sys.modules['RepositoryModule']):
if class_name[0].isupper() and class_name != 'Repository':
result.append(class_name)
return result | ebbf9076b771a2522e4fdafee2e40749815d7251 | 8,241 |
def validate(value, ceiling):
"""
Checks if val is positive and less than the ceiling value.
:param value: The value to be checked (usually an int)
:param ceiling: The highest value "val" can be. (usually an int)
:return: True if val is less than ceiling and not negative
"""
value = int(val... | 0736674f74a38e0a583eeb2fae2ee1f441c1fda7 | 8,243 |
def erratum_check(agr_data, value):
"""
future: check a database reference has comment_and_corrections connection to another reference
:param agr_data:
:param value:
:return:
"""
# when comments and corrections loaded, check that an xref is made to value e.g. PMID:2 to PMID:8
return 'S... | f05b6835db3410b6e3705aab226571d916948594 | 8,245 |
def longestConsecutive3(list,missing=1):
""" assume list is a list
budget missing """
if len(list) == 0:
return 0
longest = 0
# print(range(len(list)-1))
starts = [ x for x in range(len(list)) ]
# print(starts)
for sindex in starts:
currentlen = 0
allow = missing
... | 52420837ee40be40e8d8d6ea9a6f25372bed8d55 | 8,246 |
def gen_vocab_dict(train_data):
"""
generate dict from training set's caption file (txt)
format of txt file:
id1 video_id1 caption1
id2 video_id2 caption2
...
"""
vocab = {}
inv_vocab = {}
vocab[''] = len(vocab)
inv_vocab[len(vocab) - 1] = ''
for line in train_data:
... | 56e7e596f20e2da81f1e40a059fca1bc80d21bde | 8,247 |
from typing import Dict
def calculate_frequency(lst: list) -> Dict[str, int]:
"""Calculate the frequency from a list."""
frequencies = {}
for item in lst:
if item in frequencies:
frequencies[item] += 1
else:
frequencies[item] = 1
return frequencies | b38deeddca3d57a9e4545a51feec0c245adce9b8 | 8,248 |
import numpy
def getelts(nda, indices):
"""From the given nda(ndarray, list, or tuple), returns the list located at the given indices"""
ret = [];
for i in indices:
ret.extend([nda[i]]);
return numpy.array(ret); | 91383b0b40d33f3c197bcb5b9d20900ae963cc47 | 8,249 |
def _RoundTowardZero(value, divider):
"""Truncates the remainder part after division."""
# For some languanges, the sign of the remainder is implementation
# dependent if any of the operands is negative. Here we enforce
# "rounded toward zero" semantics. For example, for (-5) / 2 an
# implementation may give ... | 2c9d70c30d135684b3016584ab9c61aad32b3f7d | 8,250 |
import os
def should_stop(experiment_path):
""" Checks if liftoff should exit no mather how much is left to run.
"""
return os.path.exists(os.path.join(experiment_path, ".STOP")) | bb3f52a9560d42c52cedaea9ea8a1f848b64d4b7 | 8,251 |
def first_dup(s):
"""
Find the first character that repeats
in a String and return that character.
:param s:
:return:
"""
for char in s:
if s.count(char) > 1:
return char
return None | 300d9c60123bbceff8efde84be43c26f527f2fc0 | 8,252 |
def type_check(tags):
"""Perform a type check on a list of tags"""
if type(tags) in (list, tuple):
single = False
elif tags == None:
tags = []
single = False
else:
tags = [tags]
single = True
if len([t for t in tags if type(t) not in (str,bytes)]) == 0:
valid = Tr... | 519fb2bcf0b8c8792465cc2e057e3dea8f611841 | 8,253 |
def input_position():
"""
input the position option for pasted QR code
"""
option = input('Please select the position (1:left-top, 2:right-top, 3:left-bottom, 4:right-bottom, 5:left-middle, 6:right-middle) for QR code: ')
if option == '':
pos = 1
print(' Use the default position, ... | 80e2b69d04991781515790c4fd0fbb6719d3e6d4 | 8,254 |
def return_countries():
"""
Get the countries available
:return: country JSON
"""
with open("country.json", "r") as country:
return country.read() | b927b6b4b6797a76fd047ed88c2809b66df206b9 | 8,256 |
def get_pbs_node_requirements(sys_settings,node_count):
"""Get the cpu and memory requirements for a given number of nodes
Args:
sys_settings (dict): System settings dict, as supplied from config_manager
node_count (int): Number of whole nodes on target system
Returns:
dict... | f4fd12dee6608a87e6c8b0f2f56e245e6be7c0fc | 8,257 |
from unittest.mock import Mock
def api_fixture():
"""Define a fixture for simplisafe-python API object."""
api = Mock()
api.refresh_token = "token123"
api.user_id = "12345"
return api | 2270391b02dd02de71a312ed6d6edd780c5bdff2 | 8,258 |
def select_table_value_from_page(**params):
"""从画面上选择出一个列表的数据"""
return """\
with open('../script_lib/parse_table_value.js', encoding='utf-8') as file:
script = file.read()
header = driver.execute_script(script, '{header_selector}')[0]
result = driver.execute_script(script, '{data_selector}')
... | d9e5087b50188b6c4e4125bfa396ae2e9b02a6db | 8,259 |
def families_lens():
"""."""
return ['Lens', 'LensRev'] | dd1c39ca606f100fc3efbf22be2a402507d262de | 8,260 |
def myreplace(old, new, s):
"""Replace all occurrences of old with new in s."""
result = " ".join(s.split()) # firsly remove any multiple spaces " ".
return new.join(result.split(old)) | 4355251d3c52424041ce86b2449843c565beb301 | 8,262 |
def cookie_session_name() -> str:
"""
Retorna o nome do cookie para a sessão.
"""
return "ticket_session" | eaa4517b0635ea8e57d07a46d90c6bcdc3d044e8 | 8,264 |
def maybe_pad(draw, regex, strategy, left_pad_strategy, right_pad_strategy):
"""Attempt to insert padding around the result of a regex draw while
preserving the match."""
result = draw(strategy)
left_pad = draw(left_pad_strategy)
if left_pad and regex.search(left_pad + result):
result = left... | 6e3a6f1481e9d432b63cc237e68f89035aa56588 | 8,265 |
def even(value):
"""Simple validator defined for test purpose"""
return not (int(value) % 2) | 1774e55ef53799ff16f232c3ca51c322cadf1d54 | 8,266 |
def find_permutation(s, pattern):
"""Find presence of any permutation of pattern in the text as a substring.
>>> find_permutation("oidbcaf", "abc")
True
>>> find_permutation("odicf", "dc")
False
>>> find_permutation("bcdxabcdy", "bcdxabcdy")
True
>>> find_permutation("aaacb", "abc")... | ba823208ed92fc3da9725081f3dfca87c5a47875 | 8,268 |
def thermal_conductivity_carbon_steel(temperature):
"""
DESCRIPTION:
[BS EN 1993-1-2:2005, 3.4.1.3]
PARAMETERS:
OUTPUTS:
REMARKS:
"""
temperature += 273.15
if 20 <= temperature <= 800:
return 54 - 0.0333 * temperature
elif 800 <= temperature <= 120... | cfeb40bcff2b2acb6bf8c60f1bea2b00f323207a | 8,270 |
def putListIntoInt(inList, base = 2):
"""takes a list of values and converts it into an int"""
string = "".join(str(i) for i in inList)
return int(string, base) | a73c3f64e44962a34d974098e0b04fe92395adc8 | 8,272 |
def false_pred():
"""Returns a predicate that always returns ``False``."""
def new_pred(*args):
return False
return new_pred | 07dcd2e8594bd27eb4d520b240a0e3e722c7bc79 | 8,273 |
import random
def __random_positions(max_position):
"""Generates two random different list positions given a max position.
The max position is exclusive.
...
Args:
max_position(integer): The maximum position
"""
[lhs, rhs] = random.sample(range(0, max_position - 1), 2)
return (lh... | ee35a6ed30400c885b7769962de483c34cc0ab41 | 8,274 |
def create_deployment(inputs,
labels,
blueprint_id,
deployment_id,
rest_client):
"""Create a deployment.
:param inputs: a list of dicts of deployment inputs.
:type inputs: list
:param labels: a list of dicts of depl... | 84b7a13c0ef6b67b20755bc92ecc6814db0be5b0 | 8,275 |
import re
def split_sentences(text, delimiter="\n"):
""" Split a text into sentences with a delimiter"""
return re.sub(r"(( /?[.!?])+ )", rf"\1{delimiter}", text) | 7f69afaa8add8947073d1bf4133da145fba81cac | 8,276 |
def items_iterator(dictionary):
"""Add support for python2 or 3 dictionary iterators."""
try:
gen = dictionary.iteritems() # python 2
except:
gen = dictionary.items() # python 3
return gen | e3da23ad32f491958887f14aae1f4d34a5d58c4e | 8,277 |
def control_game(cmd):
"""
returns state based on command
"""
if cmd.lower() in ("y", "yes"):
action = "pictures"
else:
action = "game"
return action | 669a7b4a9335719aa9176c32c9891f6d017a1bc0 | 8,278 |
import timeit
def run_trial(rep, num):
"""Sleep for 100 milliseconds, 'num' times; repeat for 'rep' attempts."""
sleep = 'sleep(0.1)'
return min(timeit.repeat(stmt=sleep, setup = 'from time import sleep', repeat=rep, number=num)) | fcdcea9e63531b7de12ccbf27ab584829b8354b9 | 8,279 |
def git_errors_message(git_info):
"""Format a list of any git errors to send as slack message"""
git_msg = [
{
"color": "#f2c744", "blocks": [
{
"type": "divider"
},
{
"type": "section", "text": {"type": ... | 192c1f5c85c4615828873795eb8f71d8ced4080e | 8,280 |
def Distribution_of_masses(**kwds):
"""
输出双黑洞质量的分布。(ratio_step 不能小于 0.01,可以通过增大 doa=100 提高精度)
Input:
共有三种输入方式,如下面的例子:
Eg1: mass1_scope = (5,75), mass2_scope = (5,75), mass_step = 2
Eg2: mass1_scope = (5,75), mass_step = 2, ratio_scope = (0.1,1), ratio_step = 0.1
Eg3: Mass_scope = (5, 30... | aaef2ddcf589f9a299685344f1ee076e469150bf | 8,282 |
def DecodePublic(curve, bb):
"""
Decode a public key from bytes. Invalid points are rejected. The
neutral element is NOT accepted as a public key.
"""
pk = curve.Decode(bb)
if pk.is_neutral():
raise Exception('Invalid public key (neutral point)')
return pk | 7bf8d7eb129fe640475fbf404354c204f3242954 | 8,283 |
def compact(it):
"""Filter false (in the truth sense) elements in iterator."""
return filter(bool, it) | 0d84d2e7c35447969bfb3b357389e416c71b40bd | 8,284 |
def session_capabilities(session_capabilities):
"""Log browser (console log) and performance (request / response headers)
data.
They will appear in `Links` section of pytest-html's html report.
"""
session_capabilities["loggingPrefs"] = {
"browser": "ALL",
"performance": "ALL"
}
return session... | ab87146f815dffa905a60d143f7aebf4a64d3ad0 | 8,285 |
def calculate_overlap_rate(inventor_class_nbr_group_count_dict):
"""
计算交叠率
:param inventor_class_nbr_group_patent_count:
:return:
"""
#发明家的总数
inventor_cnt = len(inventor_class_nbr_group_count_dict.keys())
#无法分组的发明家数量
cant_group_inventor = 0
for inventor, class_nbr_group_count_dic... | 0c59c8ffaf8407b4f1ede86c8a3b5b4202f211fc | 8,286 |
import ast
def _parse_mock_imports(mod_ast, expanded_imports):
"""Parses a module AST node for import statements and resolves them against
expanded_imports (such as you might get from _expand_mock_imports).
If an import is not recognized, it is omitted from the returned dictionary.
Returns a dictionary suit... | 50cb8e4e2469b7bf63deacf0a5085afcded0b5e3 | 8,287 |
import os
import numpy as np
def merge_coord_and_label_files(ROI_coords_dir):
"""
utils for merging different label and coord file before computing label masks if necessary
should be rewritten to more more general with glob("Coord*.txt) and glob("Labels*.txt)...
"""
list_coords = []
... | 0e6965aa1c7f3699f1e5f0b7fef957f09e680e85 | 8,288 |
def calc_field_size(field_type, length):
"""
Рассчитывает размер данных поля
:param field_type: Тип поля
:type field_type: string
:param length: Длина поля
:type length: int
:return: Длина поля в байтах
:rtype: int
"""
if field_type == 'B':
return length
elif field_t... | 677b28d03d02e45d2f7a771c3c895c16060c229a | 8,289 |
def SortByName(list_response):
"""Return the list_response sorted by name."""
return sorted(list_response, key=lambda x: x.name) | 5cb48e536790c9f246aebe2a38bba77f329c5ae9 | 8,290 |
import re
def unindent(string):
"""Remove the initial part of whitespace from string.
>>> unindent("1 + 2 + 3\\n")
'1 + 2 + 3'
>>> unindent(" def fun():\\n return 42\\n")
'def fun():\\n return 42'
>>> unindent("\\n def fun():\\n return 42\\n")
'def fun():\\n return 42'
>>> u... | 1179d4d4a67380b95d46b3234e4b09fb83f36041 | 8,292 |
import torch
def quad_kappa_loss(input, targets, y_pow=1, eps=1e-15):
"""
https://github.com/JeffreyDF/kaggle_diabetic_retinopathy/blob/master/losses.py#L22
:param input:
:param targets:
:param y_pow:
:param eps:
:return:
"""
batch_size = input.size(0)
num_ratings = 5
asse... | f7aab107d9264384f04f1b8ba331223adcb495aa | 8,293 |
def is_tag_exists(
lf_client,
account_id: str,
key: str,
) -> bool:
"""
Check if an Lake Formation tag exists or not
Ref: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lakeformation.html#LakeFormation.Client.get_lf_tag
"""
try:
lf_client.get_lf_tag(C... | 9f323ee97d4dfc67b183f5bcdc46229fd328eff6 | 8,294 |
def browse_repository(script, project, repository):
"""
Gets the list of repositories for the specified project
:param script: A TestScript instance
:type script: TestScript
:param project: The project for the repository
:type project: str
:param repository: The repository to browse
:typ... | c3c98c625b3ed0e1de3e795861eb29c9825ef5e8 | 8,295 |
import collections
def build_node_statistics(nodes, images):
"""Build a dictionary of cache statistics about a group of nodes."""
# Generic statistics applicable to all groups of nodes.
node_statistics = {
'provisioned': len(list(filter(lambda n: n.provisioned, nodes))),
'not provisioned':... | 6f1b6a7128a088168f3d31054458275d5f13df53 | 8,296 |
def render_instruction(name, content):
""" Render an arbitrary in-line instruction with the given name and
content """
return ':{}: {}'.format(name, content) | 2200ab1c865dbad871395476fc2227cc8995b3d1 | 8,297 |
def parse_agent_req_file(contents):
"""
Returns a dictionary mapping {check-package-name --> pinned_version} from the
given file contents. We can assume lines are in the form:
datadog-active-directory==1.1.1; sys_platform == 'win32'
"""
catalog = {}
for line in contents.splitlines():
... | 7d3516327ffaf147ee85c150921c876ba5ee2980 | 8,299 |
def make_etag(hasher):
"""Build etag function based on `hasher` algorithm."""
def etag(buf):
h = hasher()
for chunk in buf:
h.update(chunk)
return '"' + h.hexdigest() + '"'
return etag | 31963ebacf886298a60e383d2a0c278293a59012 | 8,301 |
def indexof(ilist, item):
""" returns the index of item in the list """
i = 0
for list_item in ilist:
list_item = list_item.strip()
if list_item == item:
return i
i += 1
print("ERROR failed to parse config, can't find item:", item)
exit(-4) | e6b24d8b6455433f7b6afd824045fbec0dfabfc6 | 8,302 |
from typing import List
from typing import Tuple
def deflate_spans(
spans: List[Tuple[int, int, int]]
) -> List[List[Tuple[int, int]]]:
"""[summary]
Args:
spans (List[Tuple[int, int, int]]): [description]
Returns:
List[List[Tuple[int, int]]]: [description]
"""
# assuming last... | 037c11b0c5d4707b2d19a0b0cc457a93908f5186 | 8,304 |
def operate_status_template(open_now: bool) -> tuple:
"""Flex Message 餐廳營業狀況
Args:
open_now (bool): 營業中
Returns:
tuple: (營業狀況, 營業文字顏色)
"""
if open_now:
operate_status = {
"type": "text",
"text": "營業中",
"size": "xs",
"color": "... | 366d291b5e847192401f76f0c8a560c02452cef7 | 8,305 |
def paramset_to_rootnames(paramset):
"""
Generates parameter names for parameters in the set as ROOT would do.
Args:
paramset (:obj:`pyhf.paramsets.paramset`): The parameter set.
Returns:
:obj:`List[str]` or :obj:`str`: The generated parameter names
(for the non-scalar/scalar c... | 0fc4732a7accff55f8015c5b46cb1c44c002ef18 | 8,306 |
import time
def get_items_serial_number(prefix, obj):
"""获取物品唯一货号"""
date_str = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
# 生成一个固定6位数的流水号
objmodel = obj.objects.last()
serial_number = objmodel.id if objmodel else 0
serial_number = "{0:06d}".format(serial_number + 1)
return... | c8482b0debe680b36845d3ee933d0771c4efe05f | 8,308 |
def header_string(key_length=0, number_of_seconds=2):
""" return a header string for the output file """
header_string = '#'
header_string += ' ' * (key_length+8)
header_string += ' 1 2 3 ' * number_of_seconds + '\n'
header_string += '#'
header_string += ' ' * (key_l... | 8da90fa3171be1f3ce20932777835c5f2239d4a0 | 8,311 |
from typing import Optional
def int_to_comma_hex(n: int, blength: Optional[int] = None) -> str:
"""
int_to_comma_hex
Translates an integer in its corresponding hex string
:type n: ``int``
:param n: Input integer
:type blength: ``Optional[int]``
:param blength: Add padding to reach length... | a1833b68b4c179070f454bb675909b3e3495b8cf | 8,312 |
def adcm_api_credentials() -> dict:
"""ADCM credentials for use in tests"""
return {"user": "admin", "password": "admin"} | a2efa47ee588086b0d5dc089728e18b9108964a8 | 8,313 |
import re
def Language_req(description):
"""Create a function that captures the language requirements from the job description"""
description = description.lower()
matches = re.findall(r"\benglish\sand\sgerman\b|\bgerman\sand\senglish\b\benglisch\sund\sdeutsch\b|\benglish\b|\benglisch\b|\bgerman\b|\bdeuts... | cb6ce14d3cba497f668c701d16c13fdfd78f5dc5 | 8,314 |
import logging
def matrix_hits(binary_matrix):
"""Gets the number of cells with value 1 in matrix."""
logging.info("Counting how many contacts are predicted.")
count = 0
(n1, n2) = binary_matrix.shape
for i in range(n1):
for j in range(n2):
if j > i:
count += ... | 0242b2844fb2f761e6ba542031f6b188e7d5286e | 8,315 |
from typing import Dict
import os
def registry() -> Dict[str, Dict]:
"""
Return a dictionary of problems of the form:
`{
"problem name": {
"params": ...,
},
...
}`
where `flexs.landscapes.RosettaFolding(**problem["params"])` instantiates the
rosetta folding... | acf7dc0edb4d241d345c5b22a1caf387416951f9 | 8,319 |
def str2bool(val):
"""Convert string to boolean value
"""
try:
if val.lower() in ['false', 'off', '0']:
return False
else:
return True
except AttributeError:
raise TypeError('value {0} was not a string'.format(type(val))) | 01d97b141686a79d310ab59a4acb318250b0746b | 8,320 |
def remove_outliers(df):
"""Summary Line.
Extended description of function.
Args:
arg1: Function will remove 1.5 IQR outliers from data set.
Returns:
Will return a data set with outliers within the 1.5 IQR range removed.
"""
q1 = df.quantile(0.25)
q3 = df.quantile(0.75)
iq... | 6333665ddfc4f77b12604c4161ba56c0818663eb | 8,321 |
def get_layers(net_param):
"""Get layers information.
Parameters
----------
net_param : caffe_pb2.NetParameter
A pretrined network description.
Returns
-------
layers : list
description of the layers.
version : string
version information of the pretrained model.
... | 6af46460f0ba9fa41111e265cd5e63a14b8ad5cb | 8,322 |
def get_all_coords(rdmol):
"""Function to get all the coordinates for an RDMol
Returns three lists"""
conf = rdmol.GetConformer()
x_coords = []
y_coords = []
z_coords = []
for atm in rdmol.GetAtoms():
x_coords.append(conf.GetAtomPosition(atm.GetIdx()).x)
y_coords.append(conf.... | 14399748a77d565f2d65f8ae8f47ec2924c64683 | 8,325 |
def evaluations(ty, pv):
"""
evaluations(ty, pv) -> ACC
Calculate accuracy using the true values (ty) and predicted values (pv).
"""
if len(ty) != len(pv):
raise ValueError("len(ty) must equal to len(pv)")
total_correct = total_error = 0
for v, y in zip(pv, ty):
if y == v:
... | 021c80dab1d4ed97876bebc882db3423af107ea5 | 8,327 |
def _is_member_of(cls, obj):
"""
returns True if obj is a member of cls
This has to be done without using getattr as it is used to
check ownership of un-bound methods and nodes.
"""
if obj in cls.__dict__.values():
return True
# check the base classes
if cls.__bases__:
f... | c5bfb2920efc3992a92da236471f1de85cdb27a1 | 8,328 |
import os
def _remove_creds(creds_file=None):
"""
Remove ~/.onecodex file, returning True if successul or False if the file didn't exist
"""
if creds_file is None:
fp = os.path.expanduser("~/.onecodex")
else:
fp = creds_file
if os.path.exists(fp):
os.remove(fp)
... | ea25ea62b825353bd5f71dc003ceb6e530aab7c6 | 8,331 |
from typing import Optional
from typing import Dict
from typing import List
def scripts(page_content: Optional[Dict]) -> List[str]:
"""
.. _`example reference server`: https://github.com/stellar/django-polaris/tree/master/example
Replace this function with another by passing it to
``register_integrat... | 8e591eace462a5649533811bf1c54575f5714174 | 8,332 |
import argparse
def describe_argparser():
"""
Return an argument parser for the describe function
"""
parser = argparse.ArgumentParser()
parser.add_argument("variant", help="Variant to describe, example: RV64GC")
return parser | a5c78d2c39373e73204fce8724e240ef084ab0b6 | 8,333 |
def _GetSheriffForTest(test):
"""Gets the Sheriff for a test, or None if no sheriff."""
if test.sheriff:
return test.sheriff.get()
return None | daa272df6a1882e1379531b2d34297da8bec37b3 | 8,334 |
def booth(args):
""" Booth function
Global minimum: f(1.0,3.0) = 0.0
Search domain: -10.0 <= x, y <= 10.0
"""
return (args[0] + 2*args[1] - 7)**2 + (2*args[0] + args[1] - 5)**2 | 8adf94d9e96ee19758a6e495775d8bdb10330794 | 8,335 |
def makeset(weatherpart):
"""
with open("WeatherWear/clothes.csv") as f:
reader = csv.reader(f)
next(reader)
data = []
for row in reader:
data.append(
[float(cell) for cell in row[:13]]
)
clothes = data
"""
clothes = [[0.0... | be8ca4b1e64585fed368bde0baa447a13d2da7e3 | 8,336 |
import math
def rainbow_search(x, y, step):
"""Returns RGB color tuple
"""
xs = math.sin((step) / 100.0) * 20.0
ys = math.cos((step) / 100.0) * 20.0
scale = ((math.sin(step / 60.0) + 1.0) / 5.0) + 0.2
r = math.sin((x + xs) * scale) + math.cos((y + xs) * scale)
g = math.sin((x + xs) * s... | dc1d05f24fe9fb44857210c9fd962ffa4465e1f9 | 8,339 |
def recursive_any_to_dict(anyElement):
"""
Recursive any nested type into a dict (so that it can be JSON'able).
:param anyElement: Just about any 'attrs-ized' instance variable type in Python.
:return: A dict structure
"""
if isinstance(anyElement, dict):
simple_dict = {}
for key... | 7e94c93c9470c218781ee0a0059f8b95b0f663e5 | 8,340 |
from typing import OrderedDict
def genListHeaders(P4Graph):
""" Generate the dictionnary of headers.
P4Graph : JSon imported file
Name, size
"""
headers = OrderedDict()
return headers | 6077d41968dc8958ebf1f0d55d1c05607d77915c | 8,341 |
def _int_to_riff(i: int, length: int) -> bytes:
"""Convert an int to its byte representation in a RIFF file.
Represents integers as unsigned integers in *length* bytes encoded
in little-endian.
Args:
i (int):
The integer to represent.
length (int):
The number of... | 9c382486be14af3e5ec22b5aed7c2d9dc3f21d57 | 8,343 |
import pathlib
def sample_odb_fixture():
"""Get the fully qualified path to the sample odb file."""
return str(pathlib.Path(__file__).parent.parent / "resources" / "sample.odb") | 12bb3567dc5c5e86bfd6c1042c1c4c3fe310b95a | 8,344 |
def reproject(link, node, epsg):
"""
reporoject link and node geodataframes
for nodes, update X and Y columns
"""
link = link.to_crs(epsg=epsg)
node = node.to_crs(epsg=epsg)
node["X"] = node["geometry"].apply(lambda p: p.x)
node["Y"] = node["geometry"].apply(lambda p: p.y)
retur... | 5ead99d074ea1d643f598d790b083dda511caa1a | 8,345 |
def to_class_name(value):
"""Convert the current view's object to a usable class name.
Useful for outputting a css-class for targetting specific styles or
javascript functionality on a per-view basis, for example:
<div class="siteContainer {% if request.path == '/' %}home{% else %}{{ object|to_class_n... | 384f566d3808c19d7ba1357b7cddc69a92ca0b5a | 8,346 |
def _create_fold(X, ids):
"""Create folds from the data received.
Returns
-------
Data fold.
"""
if isinstance(X, list):
return [x[ids] for x in X]
elif isinstance(X, dict):
return {k: v[ids] for k, v in X.items()}
else:
return X[ids] | 8c1308913f470632657b909114806875a30fa17f | 8,347 |
def dict_map(**fs):
"""Map especific elements in a dict.
Examples:
```pycon
>>> dict_map(a=int, b=str)(dict(a='1', b=123, c=True))
{'a': 1, 'b': '123', 'c': True}
>>>
```
"""
def _change_dict(d):
d = d.copy()
for k, f in fs.items():
if k in d:
... | ac67bf69df2aa1aead3da7443a83a09974f8a545 | 8,349 |
def StrContains(input_string, substring):
"""
Return True if the substring is contained in the concrete value of the input_string
otherwise false.
:param input_string: the string we want to check
:param substring: the string we want to check if it's contained inside the input_string
:return: Tr... | b04c22d567be6d1fce664f99719169b4585d75ea | 8,351 |
from typing import Iterable
def get_closest(iterable: Iterable, target):
"""Return the item in iterable that is closest to the target"""
if not iterable or target is None:
return None
return min(iterable, key=lambda item: abs(item - target)) | 9548954317e90574d7a6d232bc166bde2eea7863 | 8,352 |
import collections
def utils_vlan_ports_list(duthosts, rand_one_dut_hostname, rand_selected_dut, tbinfo, ports_list):
"""
Get configured VLAN ports
"""
duthost = duthosts[rand_one_dut_hostname]
cfg_facts = duthost.config_facts(host=duthost.hostname, source="persistent")['ansible_facts']
mg_fac... | e9d0c5aa6fbfbfe9fe5ecce4e389c6f286ee875b | 8,353 |
def normalise(matrix):
"""Normalises the agents' cumulative utilities.
Parameters
----------
matrix : list of list of int
The cumulative utilities obtained by the agents throughout.
Returns
-------
list of list of int
The normalised cumulative utilities (i.e., utility share... | 594a46c9f1f741509ac56439779597545e63f25d | 8,354 |
import os
def findFile(input):
""" Search a directory for full filename with optional path. """
_fdir, _fname = os.path.split(input)
if _fdir == '':
_fdir = os.curdir
flist = os.listdir(_fdir)
found = False
for name in flist:
if not name.find(_fname):
found = Tr... | 6b9fe7ad0facef2f38cab67f0228e7ca68c7ca36 | 8,356 |
def cmdline_from_pid(pid):
""" Fetch command line from a process id. """
try:
cmdline= open("/proc/%i/cmdline" %pid).readlines()[0]
return " ".join(cmdline.split("\x00")).rstrip()
except:
return "" | 61ca5cf3f109863e516a861f76dafd1d6e9dc749 | 8,357 |
def none_if_empty(tup):
"""Returns None if passed an empty tuple
This is helpful since a SimpleVar is actually an IndexedVar with
a single index of None rather than the more intuitive empty tuple.
"""
if tup is ():
return None
else:
return tup | 26ee7bb9720eaa532d901b9c1f6c4a0fb6f7a340 | 8,358 |
def print_melhor_time(funcao_atual_ou_futuro):
"""Função que imprirmi o melhor time.
Parameters
----------
funcao_atual_ou_futuro : list
Lista contendo um time de jogadores
Returns
-------
str
Texto organizando o time por posição
"""
gol, zag1, zag2, l... | 99c41728dea118cbcd8b6c61188f33f25a8663d1 | 8,359 |
def update_named_ports(mig, named_ports):
"""
Set the named ports on a Managed Instance Group.
Sort the existing named ports and new. If different, update.
This also implicitly allows for the removal of named_por
:param mig: Managed Instance Group Object from libcloud.
:type mig: :class: `GC... | 3a2bd1f591e32629b6257454a491173fb96824e2 | 8,361 |
def _attributes_equal(new_attributes, old_attributes):
"""
Compare attributes (dict) by value to determine if a state is changed
:param new_attributes: dict containing attributes
:param old_attributes: dict containing attributes
:return bool: result of the comparison between new_attributes and
... | 11c92f000f1811254db48a8def3e681a09e8a9a9 | 8,367 |
def open(self):
"""获取开盘价序列"""
return self.openArray[-self.size:] | a254b5a389c9b450a685926083b849584ae2a6f9 | 8,370 |
from datetime import datetime
def detect_resolution(d1: datetime, d2: datetime) -> int:
""" Detects the time difference in milliseconds between two datetimes in ms
:param d1:
:param d2:
:return: time difference in milliseconds
"""
delta = d1 - d2
return int(delta.total_seconds() * 1e3) | a5300254b9f2d84d8111fcb3ad9f222ce6b5a9a6 | 8,373 |
def total_distance(solution, distanceMap):
"""
Calculate the total distance among a solution of cities.
Uses a dictionary to get lookup the each pairwise distance.
:param solution: A list of cities in random order.
:distanceMap: The dictionary lookup tool.
:return: The total distance between all... | b478c09540fb93d210df895a9ed31939bf889121 | 8,374 |
import struct
def py_float2float(val, be=False):
"""
Converts Python float to 4 bytes (double)
"""
sig = '>f' if be else '<f'
return struct.pack(sig, val) | e828bdedc1bca3536d6c6b5c90bf0cb4bf958066 | 8,375 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.