content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import time
def get_local_time_str(for_file_name=False) -> str:
"""Return current time str in the format %Y-%m-%d %H:%M:%S"""
if not for_file_name:
cur_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
else:
cur_time = time.strftime("%Y-%m-%d--%H-%M-%S", time.localtime())
ret... | aeaae88c1ed33aa30318c486a3ecb8a413ce2f34 | 626,358 |
def get_diagnosis_info(result):
"""
Get additional info about login.
:attr result:
= authomatic.login().
"""
res = None
# check email possibility for Facebook
if result.provider.name == "facebook":
provider = result.provider
perm_url = provider.user_info_url + "/... | 3f3ade4d32176f1295eeaee0708571a55d0e561f | 626,359 |
import json
import os
def configure_cluster(worker_hosts=None, task_index=-1):
"""Set multi-worker cluster spec in TF_CONFIG environment variable.
Args:
worker_hosts: comma-separated list of worker ip:port pairs.
task_index:
Returns:
Number of workers in the cluster.
"""
tf_config = json.loads(o... | 260b0c6ec12fc824100c774853182a988af5baff | 626,361 |
def check_overlap(l1, r1, l2, r2):
"""
Check the overlap between two points
"""
# If one rectangle is on left side of other
if r1.x < l2.x or l1.x > r2.x:
return False
# If one rectangle is above other
if r1.y < l2.y or l1.y > r2.y:
return False
return True | 7f28a5a8f1a098586ddf426880642c988801399b | 626,362 |
import importlib
def load_module(module_name):
"""
Dynamically imports the specified module and returns it.
:param str module_name:
Name of the module to be imported as a string.
"""
return importlib.import_module(module_name) | 0b74e6facf1b8ee16b316b5d3d62260c86e3c0df | 626,363 |
from numpy import zeros
def CCD_scale(UC):
"""Returns 2D scale according to mean UC_psi for each CCD chip. Assumes
3840,3840 with 4x4 array of CCD chips. The result is normalized to
scale[2,2], which corresponds to the CCD with the beamstop."""
scale = zeros((4,4))
for i in range(4):
for j... | bd9f08eb29762c94d4edef18dd1646bd87b89114 | 626,364 |
def compare_close_2_ma_10(dailies):
"""
比较当前的收盘价和MA10的关系
:param dailies: 日线列表,10个元素,最后一个是当前交易日
:return: 0 相等,1 大于, -1 小于, None 结果未知
"""
current_daily = dailies[9]
close_sum = 0
code = None
for daily in dailies:
# 10天当中,只要有一天停牌则返回False
if 'is_trading' not in daily or d... | 93eccc22710f01872b3746fb92e43c873a1e48a2 | 626,365 |
def _scale_prof(step, rprof, rad=None):
"""Scale profile to take sphericity into account."""
rbot, rtop = step.rprofs.bounds
if rbot == 0: # not spherical
return rprof
if rad is None:
rad = step.rprofs.centers
return rprof * (2 * rad / (rtop + rbot))**2 | a9e0429496a1a0c565e79a986dcd08e7cf242a2f | 626,367 |
import math
def cell_vectors(cell):
"""
Calculate unit cell vectors for given cell dimensions -> [a, b, c, alpha, beta, gamma]
"""
a, b, c = cell[:3]
alpha, beta, gamma = [math.radians(i) for i in cell[3:6]]
x_v = [a, 0, 0]
y_v = [b * math.cos(gamma), b * math.sin(gamma), 0]
z_v = [0.... | 30844ba0e6769883a7e65958086282cf4ea94f79 | 626,369 |
def problem_profiling(problem_zz_interactions_graph):
"""
This method creates a program profile (zz gates/qubit).
Args:
ZZ interaction graph
Returns:
Dictionary (number of zz gates on each qubit)
"""
pp_dict = {}
for node in problem_zz_interactions_graph.nodes():
try:... | cd885d771a46ddafa4988dfce235d29a55702663 | 626,370 |
def item_empty_filter(d):
"""return a dict with only nonempty values"""
pairs = [(k, v) for (k, v) in d.items() if v]
return dict(pairs) | 177c15a58438f5a231d153cf1866051caf29a2fa | 626,371 |
def RMSDE(dataframe_period):
""""Calculates root mean squared deviation errors for a wave period provided in dataframe_period
NB, RMSE calculated for time periods of waves - not the same as in RMSDE_wave_check"""
# inverting current
dataframe = -dataframe_period
# for mean wave, get RMSE, which we w... | e7927dded74beb632e94c7bfbd426388e0ebd3c1 | 626,372 |
import numpy
def getQuadraturePhysPointsAndWeights(mesh,femSpace,quadrature,verbose=0):
"""
for convenience, hide steps for generating quadrature points and
weights, with Jacobians, on physical mesh based on points and
weights on reference element
returns points array that's nelem x nquadloc x 3
... | c154c4304447a8966cab11db416c5fa99fe3a008 | 626,373 |
def delegate(attribute_name, method_names):
"""Passes the call to the attribute called attribute_name for
every method listed in method_names.
(See SortedListP.py for an example.)
"""
def decorator(cls):
nonlocal attribute_name
if attribute_name.startswith("__"):
attribut... | 9ece79f92b51ae4bd9feb808868f41942dff9280 | 626,374 |
import torch
def compute_basic_cos_loss(outputs, true_dir):
"""
Compute integrated loss function of spherical regression
"""
reg_dir = outputs['direction']
reg_dir = reg_dir.reshape(-1, reg_dir.shape[-1])
true_dir = true_dir.reshape(-1, true_dir.shape[-1])
if true_dir.shape[-1] == 2:
... | 63e29bc0845765761ad40f3555f60114c03dae8c | 626,375 |
def check_value(rules, value):
"""
>>> RULES = parse_input(EXAMPLE)[0]
>>> check_value(RULES, 11)
True
>>> check_value(RULES, 12)
True
>>> check_value(RULES, 13)
True
>>> check_value(RULES, 55)
False
>>> check_value(RULES, 83)
False
"""
return any((mi <= value <= ... | 0a663417b2f4e0bec5ff1b548710d02169d8924e | 626,376 |
from datetime import datetime
def calculate_belowground_biomass(ds):
"""
1. rename biomass to agb
2. calculate bgb from agb based on power law relationship published by Mokany et al (2006) Eq 1
"Critical analysis of root: Shoot ratios in terrestrial biomes"
"""
print(f'calculating belowground ... | 77e930f79c80a97b9d83b50e30121fe2a0e50cbc | 626,377 |
def unicode_double_escape(s: str) -> str:
"""Remove double escaped unicode characters in a string."""
return bytes(bytes(s, "ascii").decode("unicode-escape"), "ascii").decode(
"unicode_escape"
) | f3d652ec9b50a64bae198b2dac73261bc87a2db0 | 626,378 |
def write_csv_file(dataframe, path):
"""
Write new file with provided dataframe
path: the path to the new file
dataframe: the data that need to be saved
"""
file_name = path+".csv"
dataframe.to_csv(file_name, sep='\t', encoding='utf-8')
print( "File {}.csv created".format(path))
ret... | be45f8285f1b5ad7975a41878d507efa9479d14c | 626,379 |
import pathlib
import xxhash
def _get_xxhash(file_path: pathlib.Path) -> str:
"""Compute the hash of the content of file_pathpath"""
n = file_path.stat().st_size
x = xxhash.xxh128()
m = 2 ** 23 # read 8MB each time
with file_path.open('rb') as f:
if n < m * 128: # <= 1GB, check the whole ... | 45c5fa74ecec96b6b7018e2c2af0069324b3989f | 626,380 |
def find_image_essex(client, image_name):
"""
Looks up the image of a given name in Glance.
Returns the image metadata or None if no image is found.
"""
images = client.get_images(filters={'name': image_name})
if images:
return images[0]
else:
return None | 6bbd2657dbcf5d519a91565c198b769f48d9cd87 | 626,381 |
def loadDataSet():
"""
创建Hole Foods数据集
"""
return [[1,3,4],[2,3,5],[1,2,3,5],[2,5]] | 4edbf457da311a3733ce49635f50e5dfba855952 | 626,382 |
def parse_remote(path,loopback=False,login_flag=False):
"""parse remote connection string of the form ``[[user@]host:]path``
Args:
path (str): remote connection string.
loopback (bool, default=False): if True, ensure *host* is used.
login_flag (bool, default=False): if True, prepend use... | 37e08f871551426c098a92803adbaf9a02d57308 | 626,383 |
def one_api(testCase, core):
"""
Get the only API registered against a given MimicCore.
:return: 2-tuple of ``region`` and ``service_id``
"""
service_id = None
api = None
# Since there is only 1 API it can be assumed to be either an internal
# or external API.
if len(core._uuid_to_... | 4935400c3ca03cdbb65605182c74ced8f2c594e6 | 626,384 |
def compose1(f, g):
"""Return the composition function which given x, computes f(g(x)).
>>> add_one = lambda x: x + 1 # adds one to x
>>> square = lambda x: x**2
>>> a1 = compose1(square, add_one) # (x + 1)^2
>>> a1(4)
25
>>> mul_three = lambda x: x * 3 # multiplies 3 to x
... | b387466b2b4ae56dea2dd8a30ed77119ce8185f4 | 626,385 |
import os
def getRecipients():
"""
Fetch email recipients from environment variable.
"""
emails = os.environ.get("EMAIL_RECIPIENTS", "jeremy.bowers@nytimes.com")
emails = emails.split(" ")
return emails | 0b469995c5bd99acdaf109dc0c93c2013c23fc24 | 626,387 |
def parsenumber(v, strict=False):
"""
Attempt to parse the value as a number, trying :func:`int`, :func:`long`,
:func:`float` and :func:`complex` in that order. If all fail, return the
value as-is.
.. versionadded:: 0.4
.. versionchanged:: 0.7 Set ``strict=True`` to get an exception if... | 43e65d7aad52003d217cc74d0e6929f61300b592 | 626,388 |
import io
def lex_add_disambig(x):
"""
x: lexicon string path.
"""
lex_dct = {}
with io.open(x, "r", encoding="utf8") as f:
for line in f.readlines():
wd = line.strip().split()[0]
phseq = " ".join(line.strip().split()[1:])
try:
lex_d... | 494750e0fb8fec8341d4175587d161b0fb3cbcb2 | 626,389 |
def convert_to_eth(wei):
"""
Convert wei to eth
:param wei: float, required
:return: float
"""
eth = wei / 1000000000000000000
return eth | d4b3a8fc1dc26481e46796ea2af62fe7f214b2f1 | 626,391 |
from typing import List
import os
def get_hook_dirs() -> List[str]:
"""Return the current directory."""
return [os.path.dirname(__file__)] | e04dc06e82310402998fbb15575ca05b31d72f70 | 626,392 |
import os
def depth(directory):
"""returns the integer depth of a directory or path relative to '/' """
directory = os.path.abspath(directory)
level = 0
while True:
directory, remainder = os.path.split(directory)
level += 1
if not remainder:
break
return level | 28059059a3d028701faae97b1b1705b4af8e3e35 | 626,393 |
import re
def extract_one_sentence(nkjp_match, left_context_min_length=100):
"""
NKJP matches return the matched word itself, plus its context on both
sides. This function attempts to take all three (left, match, right)
and extract one sentence.
Args:
nkjp_match (lxml.etree._Element): on... | 86b8b42135de3d8de637c77496dccffdd9f3efbe | 626,394 |
def multiply(x, y):
"""
python3 expose.py multiply 2 1
> 2
"""
return x * y | ec21fd9546081d9331f29c0a3149f1f34250438a | 626,395 |
def _get_properties(data_group, n_top_matches, map_size):
"""Return a dictionary of properties within an EMsoft h5ebsd file, with
property names as the dictionary key and arrays as the values.
Parameters
----------
data_group : h5py.Group
HDF5 group with the property data sets.
n_top_ma... | 622f6c9af4057c572e50b3c17f9aa266ae532d89 | 626,396 |
def missing_layers(dm_layers, ds_layers):
"""Find missing datamodel-layers in datasets."""
layers = [i.lower() for i in ds_layers]
layers = [i for i in dm_layers if i not in layers]
return layers | ec805b48405e1eb56a04dc28768da0fe1bafee7a | 626,397 |
import requests
def get_installation_token(installation_id, integration_jwt):
"""Create a GitHub token for an integration installation.
Parameters
----------
installation_id : `int`
Installation ID. This is available in the URL of the integration's
**installation** ID.
integration... | f9c9a21635d00dc2c0ef4aaff91ff41f7e25a177 | 626,398 |
import os
def insert_suffix(filename, suffix=""):
"""Create a new filename including the
suffix in the name
Input
-----
filename: str
suffix: str
"""
# Create new name
sfilename, extension = os.path.splitext(filename)
return "{0}_{1}{2}".format(sfilename, suffix, extension) | 998a03426f38d4f79e99f4c48955485a0440b6bb | 626,399 |
def get_data_files(dir_path):
"""
get all dot file with given path
dir_path: Path
"""
fnames = list()
# dir_path = Path(dir_path)
if dir_path.exists():
# if list(dir_path.glob('.*')):
# for item in list(dir_path.glob('.*')):
# fnames.append(item.name[1:])... | 1494be8385d7c6415b4ebbd637803d6d4e36d81d | 626,400 |
import re
import os
def parseSSHConfig():
""" parseSSHConfig() -> dict
read $HOME/.ssh/config and /etc/ssh/ssh_config; return multidimensional
dict host => directive => values
For example, /etc/ssh/ssh_config with contents
Host MyHost
User root
Port 22
would return:
{
"MyHost": {... | e4d095974e06a8feac3af10cd5edb4d1f1449630 | 626,401 |
def make_words(text):
"""
make a list of words from a large bunch of text
Strips all the punctuation and other stuff from a
large string, and returns a list of words
"""
replace_punc = [('-', ' '),
(',', ''),
(',', ''),
('.', ''),
... | a45b2b0cf4c9fd83addc002426da3b5196da15e8 | 626,402 |
import codecs
def load_dataset(dataset_file, relations):
"""
Loads a dataset file
:param dataset_file: the file path
:return: a list of dataset instances, (x, y, relation)
"""
with codecs.open(dataset_file, 'r', 'utf-8') as f_in:
dataset = [tuple(line.strip().split('\t')) for line in f... | 6af78c2d0bf5912f2c829ebcbb850fb1fc4b32f7 | 626,403 |
def home():
"""Home page
Test whether the service is started
:param
pass
:return:
pass
"""
return 'server has running ' | 8ddd65c3661a5c17c23cee1b47bd1e2d15ffcc11 | 626,404 |
import json
def reverse_json(str_list):
""" 反序列化
Args:
str_list list(str)
Returns:
data list(obj)
error list(tuple)
"""
data = []
error = []
for line in str_list:
try:
dic = json.loads(line)
data.append(dic)
except Excep... | 4afc598b2ae899a050637f7566afef4ba7cb0586 | 626,405 |
def createPolygonPolyline(type, coords):
"""Create WKT POLYGON or LINESTRING string.
Args:
type (str): ``POLYGON`` to create polygon, else will create ``LINESTRING``.
coords (list): Two item list representing single point coordinate.
Returns:
str: WKT POLYGON or LINESTRING string.
... | 109d2594c6088c15a70c1724580b83299ff06130 | 626,406 |
import requests
def get_access_result(target_url="https://cn.bing.com/", search_word=None):
"""
Args:
str:输入搜索字符串
Returns:
res:requests返回的response对象
Raises:
statuserror:爬取失败
"""
args = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win... | f5f797dcb4abf982a8e3e9e2fd49f5be6e2d3d94 | 626,407 |
def is_external(config):
"""
Checks if the configuration is for an external transport.
:param dict config: configuration to check
:return: True if external, False otherwise
:rtype: bool
"""
return config.get("external") == "1" | 814a5b7bcf8c1a3a71a49c945180f8f18fc2fceb | 626,408 |
def apoz_scoring(activation):
"""
Calculate the Average Percentage of Zeros Score of the feature map activation layer output
"""
activation = (activation.abs() <= 0.005).float()
if activation.dim() == 4:
featuremap_apoz_mat = activation.mean(dim=(0, 2, 3))
elif activation.dim() == 2:
... | 778a3f94c8cb02544bebd3691b5e8ae65f082e93 | 626,409 |
def obj_frequencies(df):
"""Total number of occurrences of individual objects over all frames."""
return df.noraw.OId.value_counts() | 6b642185dbd9f10201452bcad076c8a0da813949 | 626,410 |
def argmap(dikt):
"""
Decprator that wraps function signatures.
If we have a nixargs keyword argument, transform the arguments to
the function.
DIKT is a dictionary containing tuples of argparse style *args
mapped to the keyword arg name to map to. We convert the args into
keyword argument... | 52a722971f94af09b869227a56a4ce19c1acad78 | 626,411 |
import re
def non_greedy_match(word):
"""
The period matches any character, so this regular expression
matches any character between the underscores. To match as much
text as possible, it will have to use the asterisk.
:param word:
:return:
"""
return re.findall("_.*_", word) | ce9b4f921cb6cd2ec26e1042606e583fecaecc39 | 626,413 |
import random
def zip_code():
"""Random ZIP code, either in `#####` or `#####-####` format."""
format = '#####'
if random.random() >= 0.5:
format = '#####-####'
result = ''
for item in format:
if item == '#':
result += str(random.randint(0, 9))
else:
... | 8d1518f7ca4022960cef2b4231e8058840eff41a | 626,414 |
import re
def check_file(file_contents: str) -> bool:
"""Check file for the snippet"""
return bool(re.search(r"^if __name__ == \"__main__\":", file_contents, re.M)) | 974f4e29a92dc3c9f9c4b12c79af2940758cd8d6 | 626,415 |
import random
def get_computer_choice():
"""
get_computer_choice() --> string 반환
반환값: "가위" | "바위" | "보"
"""
li=("가위","바위","보")
computer=random.randint(0,2)
computer=li[computer]
return computer | 17c6286239e0641864660b63987278a3d807d88a | 626,416 |
def getInnerText(node):
"""
Get all the inner text of a DOM node (recursively).
"""
# inspired by http://mail.python.org/pipermail/xml-sig/2005-March/011022.html
inner_text = []
for child in node.childNodes:
if child.nodeType == child.TEXT_NODE or child.nodeType == child.CDATA_SECTION_NO... | c6a7dc3a9e49168cf0c971cac465312921c748f5 | 626,417 |
import os
import logging
import json
def github_auth(config_file):
"""Parse GitHub basic auth from the config file."""
if not os.path.isfile(config_file):
logging.warning("%s not found, not using GitHub authentication", config_file)
return
file_handler = open(config_file, 'r')
content... | 5931ccaa8ba61332e78c4b49e6d8355fdec6cee4 | 626,418 |
import configparser
def read_config_file(cfg_path="config.ini"):
""" Czyta plik konfiguracyjny """
config = configparser.ConfigParser()
config.read(cfg_path)
return config | 55e434b94db60dee151d525802cf3d078429c5cb | 626,419 |
import yaml
def load_yaml(path):
"""Load YAML file into Python object."""
with open(path, "r") as file_data:
data = yaml.safe_load(file_data)
return data | 4c2029673d42f85b11cd482b0a17d13097afbfb2 | 626,420 |
def dot(a, b, out=None):
"""
Dot product of two arrays. Specifically,
- If both `a` and `b` are 1-D arrays, it is inner product of vectors
(without complex conjugation).
- If both `a` and `b` are 2-D arrays, it is matrix multiplication,
but using ``a @ b`` is preferred.
- If either `a... | 266ea378f94e668355e3a58d1beb9ab6c7d65210 | 626,421 |
def cnt_freq(filename):
"""opens a text file with a given file name
and counts the frequency of occurrences of all the characters within that file"""
try:
#opens the file
with open(filename, 'r', encoding='utf-8') as file:
#creates an empty list
list_line = []
... | 89c6acd7700d74c54441d2ba662bfc69716b208d | 626,422 |
import requests
import json
def get_openid(appid,secret,code):
"""
向微信后台发送请求,获取用户的session_key和open_id
:param appid:开发者的APPID
:param secret:开发者的AppSecret
:param code:wx.login 返回的code
:return:{'session_key': 'kqJhkE9AYV0E6YRm4G0nNQ==', 'openid': 'oTZEu5beSes5Lha9wKhGt5icfCb4'}
"""
url = ... | 0222185c68aeefe0f6d10cce1d89cbef34304751 | 626,423 |
import os
import sys
def _get_all_test_modules(folder):
"""
Gathers all test modules
"""
modules = []
current_directory = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(current_directory, '..'))
test_directory = os.path.join(current_directory, folder) if folder else current_dire... | 0fd3fe28878bd488746fae156df77818332b9311 | 626,424 |
def labeller(n, symbol="q"):
"""Autogenerate labels for wires of quantum circuits.
Parameters
==========
n : int
number of qubits in the circuit
symbol : string
A character string to precede all gate labels. E.g. 'q_0', 'q_1', etc.
>>> from sympy.physics.quantum.circuitplot import ... | bd464c8ec7cc9e7ca32010184c983c46c16ffb2c | 626,425 |
def refine(title: str):
"""Refine the project name."""
refined = title.lower()
with open('./refine.txt', 'r') as file:
for line in file:
tokens = line.split('\t')
src = tokens[0]
if tokens[1].endswith('\n'):
dst = ''
else:
... | 4f91dbb5edc8d4e764bf4ef2f241ff762d8de652 | 626,426 |
def _get_api_name(func):
"""e.g. Convert 'do_work' to 'Do Work'"""
words = func.__name__.split('_')
words = [w.capitalize() for w in words]
return ' '.join(words) | 39eb8b01fa9a3e257f25d8870038543c3eb8d823 | 626,427 |
def _fix_uppercase(kwargs):
"""
Properly handle uppercase arguments which are normalized by click.
"""
if 'c' in kwargs:
kwargs['C'] = kwargs.pop('c')
return kwargs | 560f894b5c5324e284111f1235041924f3a54ac5 | 626,428 |
def pacific_centered_coordinates(obj):
"""The world should be divided between Icelandic (westernmost language) and
Tupi (easternmost language), i.e. between -17 and -36.
We chose -26 as divider because that puts cape verde to the west of africa.
"""
return [obj.longitude if obj.longitude > -26 else... | b9ecca90470e6a690f5b1c567ae0a03afb4e2eb8 | 626,429 |
import math
def inverse_kinematic(x, y, a1, a2):
"""
:param x: x position of end effector
:param y: y position of end effector
:param a1: length of member 1
:param a2: length of member 2
:return: angles of a 2 joint same plane robot arm
"""
# find q2 angle of the second joint
num ... | a5a9d16cbab28b50bbbe98425c9e384fe1b68eb6 | 626,430 |
import math
def process_time_interval_use(desired_time_interval, desired_time_scale):
"""
process the time interval to use
:param desired_time_interval: desired time interval to use
:param desired_time_scale: desired time scale used in power analysis
:return: final time interval for subsequent ste... | 109098ebc088bc22caebbdc1be087baa00f79384 | 626,431 |
import requests
def get_current_microsoft_public_keys(ms_signing_key_url='https://login.microsoftonline.com/common/discovery/keys'):
"""Returns the list of currently in use public keys.
Args:
ms_signing_key_url: The known url for the public keys
.. note::
These guys are updated approxim... | 8a107c00f17c3cfca1ffa353d5334737977deb8a | 626,432 |
from typing import Optional
def get_season_url(
base_url: str, year: Optional[int] = None, season: Optional[str] = None
) -> str:
"""Creates the URL for the season endpoint."""
if year is None or season is None:
return f"{base_url}/season"
return f"{base_url}/season/{year}/{season.lower()}" | 3d8520f65a65c2c4d8c4749a22acc269e076543a | 626,433 |
def intersection(lista, listb):
"""Return the intersection between two lists. Note,
for duplicate values, each duplicate will be returned as
we merely check if item in lista, is in listb."""
return [item for item in lista if item in listb] | bd97d4a1869d87701cd1b14dfaccf139b1a30e23 | 626,434 |
def _build_pruned_tree(tree, cases, tree2):
"""helper method for ``build_pruned_tree``"""
is_results = False
if isinstance(tree[0], str):
try:
name, icase, cases2 = tree
except ValueError:
print(tree)
raise
if isinstance(icase, int):
a... | dc1fc73dad1f21cbc1ab5ab66ec2522e98449fe8 | 626,435 |
import sys
import os
def get_sys_prefix():
""" Return sys.prefix as guaranteed abspath format.
"""
sys_prefix = getattr(sys, "real_prefix", getattr(sys, "base_prefix", sys.prefix))
sys_prefix = os.path.abspath(sys_prefix)
return sys_prefix | 56b1b626cda9696d354132234489d1f099f0ec46 | 626,437 |
def count_number_fishers_alive(dict_fishers,gamerunning):
"""
This function , count the number of fishers alive in the island, if is 1 the number of players
alive and the game is running, he catch the number, and form a message of the winner, otherwise
,return just return the number of players
@param dict_fis... | bed5e25602eb40fcc29f48c0ecfdf6ff0f4fc6a2 | 626,438 |
def bed4_to_node2coordinates(bed4):
"""Compute the node2coordinates DataFrame: exon name, chrom, start, end"""
node2coordinates = bed4\
[["name", "chrom", "chrom_start", "chrom_end"]]\
.set_index("name")
return node2coordinates | 2425dcc4d5ebbc2e0312d06cc85c69f27bbe076d | 626,439 |
def readpdb(file_name):
"""初始化数据存储"""
data = []
with open(file_name,encoding = 'utf-8') as file:
for line in file:
list = line.split( )
# print(list)
"""去除非数据行"""
if (len(list) > 10):
name = "".join(line[76:78].split())
... | 5706922a366aa8f27a38625aed7117ef8b3ad025 | 626,441 |
from typing import Counter
def count_layer_types(model):
"""Count layers by layer type.
Parameters
----------
model : keras.engine.training.Model
A Keras model.
Returns
-------
collections.Counter
Counter object containing number of layers in the model by layer type.
... | d34df3bb908244a0469ac7d998b9410381ed79c7 | 626,442 |
async def prefix_getter_static(prefix, message):
"""
Returns a prefix for the message.
This function is a coroutine.
Parameters
----------
prefix : `str`
The prefix to return.
message : ``Message``
The received message to parse the prefix from.
Returns
... | c7726ae81e6db546d49f364fc35f132bb9224730 | 626,443 |
import os
import json
import logging
def load_meta(model_dir):
"""
:param model_dir:
:return: meta_dict
"""
json_path = None
meta_dict = {}
for file in os.listdir(model_dir):
if file.endswith(".meta"):
json_path = file
break
try:
if json_path:
... | c4f6302eb0ddbf4a11749a8cb5c209c3570a4202 | 626,445 |
def all_unique(_list):
"""Return a boolean value indicating whether the list contains only unique items.
:return: Boolean value indicating whether the list contains only unique items
:rtype: bool
"""
if not isinstance(_list, list):
raise ValueError("List expected")
seen = set()
re... | df25945dbd17aa2ec5e73e0b5717703cf8aa9669 | 626,446 |
import torch
def silu(x):
"""
Smoothed ReLU (Sigmoid-ReLU)
"""
return x*torch.sigmoid(x) | 3ef82437e95585e41a0c73deaea03b08c228e0aa | 626,447 |
def title_query(q, wild=True, no_quote=False):
"""
Helps generate a title query.
Creates a simpler lucene query, and handles the case where the user might want to have spaces
eg::
query = title_query("RHSM : RCT Tool")
print query # title:"RHSM : RCT Tool"*
:param q:
:param wi... | e27d5c50fd20634ddb0d9a3504ee82a76c47803d | 626,448 |
def use_kd_tree(request):
"""Whether to use the KD Tree in CVTArchive."""
return request.param | 12989d688dc68bc00572a07a99aa099313f766f9 | 626,449 |
def _zero_based_index(i, l, start=True):
"""Compute the 0-based index from the slice index i in a list of length l
Assuming step is 1.
Examples
--------
>>> _concrete_index(2, 100)
2
>>> _concrete_index(2, 100, start=False)
2
>>> _concrete_index(-1, 100, start=False)
99
>>> ... | bbafa7a0ffbcf87ea2ff52b55b48b506aaef2367 | 626,450 |
def getColPermutations(possible_columns, max_num_of_perms = 100):
"""
Get all possible combinations given a list of column names
:return: Given Input = [a,b,c]
Then, Output= [ [a], [b], [c], [a,b], [a,c], [b,c] ]
"""
permutations = {col: 1 for col in possible_columns}
for perm_... | 9911eb68dabf2251e8f1e19515d5b6be60f9fbdb | 626,451 |
def compare_substring(a_str, b_str):
""" Helper for compare """
a_digit = a_str[0].isdigit()
b_digit = b_str[0].isdigit()
# string > int
if a_digit and not b_digit:
return -1
if not a_digit and b_digit:
return 1
if a_digit and b_digit:
# compare to digits
a_in... | 0ce1564869165d6ceaeb3aa188ac01b223db39f1 | 626,452 |
def checksum(spreadsheet):
"""
Calculate the checksum of a spreadsheet by summing up the ranges of all
lines.
>>> checksum([
... [5, 1, 9, 5],
... [7, 5, 3],
... [2, 4, 6, 8]
... ])
18
"""
return sum(
max(line) - min(line)
for line in spreadsheet
... | aff44ebd654bd4e59d49df9d0963a1f969d5b5b4 | 626,453 |
def get_qa_steps():
"""
Returns qa steps
"""
return (1.0, 2.0) | 2412899c4dcd427bf6261bbb6aaf17d6a8dd4961 | 626,455 |
def lsymm(self, ncomp="", nl1="", nl2="", ninc="", kinc="", noelem="",
imove="", **kwargs):
"""Generates lines from a line pattern by symmetry reflection.
APDL Command: LSYMM
Parameters
----------
ncomp
Symmetry key:
X - X symmetry (default).
Y - Y symmetry.
... | 4a4e356bf6694f8e55c77d54615cbc55dbcdd8a7 | 626,456 |
def comp_masses(self):
"""Compute the masses of the Lamination
Parameters
----------
self : Lamination
A Lamination object
Returns
-------
M_dict: dict
Lamination mass dictionary (Mtot, Mlam, Mteeth, Myoke) [kg]
"""
rho = self.mat_type.struct.rho
V_dict = self.... | 4ef2b61a382f0a1822eae86a8f138ecf85490de1 | 626,457 |
def get_xpath_parent(xpath, level=1):
""" Get the parent xpath at any level, 1 is parent just above the input xpath.
Args:
xpath (str): Input xpath
level (int, optional): Parent level. Defaults to 1.
Returns:
str: Parent xpath
"""
if not xpath.startswith("/"):
rais... | 55f9cea636908a668c8ea49757df6ec4c043b6dc | 626,458 |
def public(f):
""" decides if a function is public or not"""
f.public = True
return f | 32051a888276c4c1e8713b41a88a062b92714fd3 | 626,459 |
import io
import os
def read(*parts):
""" Reads in file from *parts.
"""
try:
return io.open(os.path.join(*parts), 'r', encoding='utf-8').read()
except IOError:
return '' | b37fd11f35722197b8103a50d9e83b56aebf448c | 626,460 |
def discover(parameter=0):
"""
Enumerate devices on host
"""
return 'discover', 'ifconfig -s | tail -n +2 | awk \'{print $1}\' | xargs echo -e NET: && lsblk -l | grep / | awk \'{print $1}\' | xargs echo DISK:' | ecfddc7ae04cecf5540ce7fd8c27b442c692efb1 | 626,462 |
def pad_list(xs, pad_value=0., pad_left=False):
"""Convert list of Tensors to a single Tensor with padding.
Args:
xs (list): A list of length `[B]`, which contains Tensors of size `[T, input_size]`
pad_value (float):
pad_left (bool):
Returns:
xs_pad (FloatTensor): `[B, T, inp... | 18b1f649fb10b54607d1dd8b2106172ac9af743e | 626,463 |
def get_cube_diff(cube_1, cube_2):
"""
Take the difference of two Iris data cubes.
Computed as cube_1 - cube_2.
Parameters
----------
cube_1 : Iris cube.
cube_2 : Iris cube.
Return
------
Iris cube containing the difference of cube_1 - cube_2
"""
diff_cube = cu... | 9d059f043f4ebecbb746babcfe472325837376d4 | 626,464 |
import os
def my_dataset(root, class_to_idx):
"""
This function creates the dataset as a set of directories paths that point
to each sample folder. In this way the samples are opened when needed and
only their path is always saved in memory.
Arg:
root (str): Root directory path.
c... | 42aaa5382b1a3faf0d7c054908b35b7888532eb9 | 626,465 |
def and_from_dict(kwargs):
"""
Generate a SQL And statement from a dict of keyword args
:param kwargs: Keyword arguments dict
:return: String AND statement
"""
return " AND ".join(f"{x} = %({x})s" if kwargs[x] is not None else f"{x} is %({x})s" for x in kwargs) | 2f10769dda29aefaf3963ef8a1cc89bef2213bf1 | 626,466 |
def PNewOTFTable (inOTF, access, tabType, tabVer, err,
numDet=1, numPoly=0, numParm=0):
""" Return the specified associated table
inOTF = Python OTF object
access = access code 1=READONLY, 2=WRITEONLY, 3=READWRITE
tabType = Table type, e.g. "OTFSoln"
tabVer = table... | edea1d30b0b8c519f7245de16764b46ff419ee24 | 626,467 |
import re
def uncamel(val):
"""Return the snake case version of :attr:`str`
>>> uncamel('deviceId')
'device_id'
>>> uncamel('dataCenterName')
'data_center_name'
"""
s = lambda val: re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\1', val).lower().strip('_')
return s(val) | 27c6b5338d8da39a6b45d420749457147738e416 | 626,468 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.