content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
import subprocess
import pickle
def get_options(project, branch):
"""Get the list of known options for a project."""
print("Working on %(project)s (%(branch)s)" % {'project': project,
'branch': branch})
# And run autohelp script to get a seriali... | c7cc2dcc0263475219cd99a0306b47a066a9309c | 639,345 |
def add_atmark(name):
"""先頭に@マークを付与する。"""
return '@' + name | fb1a3b7054e927dcb74e4f47617aa8dfbb58a3a6 | 639,346 |
def GetDiskConfig(dataproc, boot_disk_type, boot_disk_size, num_local_ssds,
local_ssd_interface):
"""Get dataproc cluster disk configuration.
Args:
dataproc: Dataproc object that contains client, messages, and resources
boot_disk_type: Type of the boot disk
boot_disk_size: Size of the... | 9a7254992900d9e325eac2eba21bfb5bbfa7d680 | 639,347 |
import os
def getExclusionSet(cmdargs):
"""
Return a set of the ESA ID strings for any zip files we wish to exclude (e.g. because
we already have them). Input is a text file of these strings, optionally including
their full path, i.e. as full file names, or just as plain ID strings.
Each on... | 96d4030da6f79037a380de729b9a9e0fe1567f22 | 639,348 |
import os
def checkFile(fname):
"""file name if file exists, None otherwise"""
if os.path.isfile(fname):
return fname
else:
return None | 2a9b2f7fd7d842ec36bf5f921fc61b2891256431 | 639,349 |
def _get_port_to_string(iface):
"""Simple helper which allows to get string representation for interface.
Args:
iface(list): Which IXIA interface to use for packet sending (list in format [chassis_id, card_id, port_id])
Returns:
str: string in format "chassis_id/card_id/port_id"
"""
... | 3d1da011c2bc63657020043f7a0aca1e14e5f276 | 639,350 |
import os
import json
def load_hyperparameters():
"""Load the Hybrid Job hyperparameters"""
hp_file = os.environ["AMZN_BRAKET_HP_FILE"]
with open(hp_file) as f:
hyperparams = json.load(f)
return hyperparams | a40dff636968694199f1f24cee85f3dafc0bf98b | 639,351 |
from enum import Enum
def create_relationships_rec(t):
"""Recursive part of create_relationships, searches through cobjects."""
if type(t) is tuple:
if t[0] == 'co':
return {t[1]}
elif t[0] is dict:
return create_relationships_rec(t[1]) | \
create_relati... | 0e719ec01ba07ec64f6d091c9b5a06d5103cd589 | 639,352 |
def __ask_int(message):
"""
Asks User for an Integer Value
Args:
message = str - Input from Console
"""
value = ''
while not isinstance(value, int):
value = input(message)
try:
value = int(value)
return value
except:
print("The... | d88c1d1f9794b6ac653d95899d6d9472e9276718 | 639,353 |
def default_matching(name: str, target_version: int) -> str:
"""Default matching method
"""
return name | d6fbaca343c3ef7899a56363dace550a1a60f6cf | 639,355 |
def register_package(g, builder):
"""Giver runs and wizard runs both use this prompt."""
test_pypi = builder.use_test_server
g.text(" ")
proceed = g.prompt(
"Register package? ", True,
"To upload to the test server you must have first registered the "
"package with the test site.... | 7d6797b2a783458a8652fc9bc52e43805fc6c46d | 639,357 |
from typing import Tuple
def extended_euclidian_gcd(left: int, right: int) -> Tuple[int, int, int]:
"""Solve left * x + right * y = gcd(left, right) and return r, x, y."""
new_x, new_y, new_r = 0, 1, right
old_x, old_y, old_r = 1, 0, left
while new_r != 0:
quotient = old_r // new_r
old... | 4d4244f87f518bee8e57f866a2ec6eca7b2bc262 | 639,358 |
def hex_to_rgb(value):
"""Converts colour from hex triplet into rgb tuple.
value (str): colour as hex triplet
"""
value = value.lstrip('#')
lv = len(value)
return tuple(int(value[i:i+lv//3], 16) for i in range(0, lv, lv//3)) | 77f8141f055403cd84564820f0d826425e8500f8 | 639,359 |
import base64
def safe_base64_decode(string):
"""
Adds back in the required padding before decoding.
"""
padding = 4 - (len(string) % 4)
string = string + ("=" * padding)
return base64.urlsafe_b64decode(string) | 506cfdf03d1e453b8b2a67bac0e2b6659fe64611 | 639,360 |
def merge_vals(x, y):
"""Combine keys in dict."""
if x == y:
return x
if isinstance(x, list) and isinstance(y, list):
return [*x, *y]
return [x, y] | c0900ab3c6e28486e94c72e041ed4aa5c708c5e8 | 639,361 |
def add_replace_filter(source, args, index):
"""Add the hxlreplace filter to the end of the pipeline."""
original = args.get('replace-pattern%02d' % index)
replacement = args.get('replace-value%02d' % index)
tags = args.get('replace-tags%02d' % index)
use_regex = args.get('replace-regex%02d' % index... | 6e8120ef47e6fb69ac7484d67a5d433a9934b647 | 639,362 |
def true_stress(tech_stress, tech_strain):
"""
Calculate the true stress data from technical data
Parameters
----------
tech_stress : array-like float
stress data from tensile experiments
tech_strain : list of float
strain data from tensile experiments
Returns
-------
... | 327c4912f4c5c8bbda9cd229c2eed8dd3e9bb798 | 639,364 |
import hashlib
def hash_string(strdata: str) -> str:
"""Hash a string
:param strdata: string data to hash
:return: hexdigest
"""
return hashlib.sha1(strdata.encode('utf8')).hexdigest() | 29d25ebe6993d3c8ac7c236cf020a4fc83aff61a | 639,366 |
def SortAndGrid(table,order):
"""table => {s:{p:{c:{a:{}}}}}"""
grid=[]
for (server,ports) in table.items():
for (port,configfiles) in ports.items():
for (configfile,appnames) in configfiles.items():
for appname in appnames.keys():
line=[]
for col in order.values():
if col=="s":
line.... | a9c5e15972e2412ebf1a670567d81ecaaa642393 | 639,367 |
def get_rpy2_factorvector_index_map(fac):
"""returns dict mapping factor vector indices to factors"""
mapping = dict([(i + 1, f) for i, f in enumerate(fac.levels)])
return mapping | e826d10705323e1c5ff7ee548a16fea28399c6c3 | 639,368 |
def _cast_data_timeline_to_list(data, timeline):
"""Cast data and timelines as lists for WAMP serialization.
The so3g HKArchiveScanner returns data as either native g3 types or numpy
arrays. We need them to be lists in order for WAMP to accept them.
Parameters
----------
data : dict
Da... | 4092abc538f66eb47e5feb6f531a2ca530d454dc | 639,369 |
def empty_filepath():
"""didn't use /tmp because it makes Travis sad"""
return 'empty.txt' | 2d113aea810bbf4641c6425945c0764a217042c9 | 639,370 |
def reciprocal_overlap(astart, aend, bstart, bend):
"""
Calculates reciprocal overlap of two ranges
:param `astart`: First range's start position
:type `astart`: int
:param `aend`: First range's end position
:type `aend`: int
:param `bstart`: Second range's start position
:type `bstart`... | 886afbba383a9a3c037b84df0ee30c1d01cc4131 | 639,371 |
import itertools
def combine_dictionaries(dictionaries):
"""Combine a list of non-overlapping dictionaries into one.
Args:
dictionaries (list): List of dictionaries.
Returns:
dict: The combined dictionary.
Examples:
>>> combine_dictionaries([{"a": 1}, {"b": 2}])
{'a... | f61535e51f8c8af5dd98adb526b8b428a6a17425 | 639,372 |
def tree_similarity_ratio(ted, t1, t2):
"""
Return the similarity ratio from 0 to 1 between two trees given their edit distance
`ratio` idea from [DiffLib](https://fossies.org/dox/Python-3.5.1/difflib_8py_source.html)
"""
# print(ted)
# import networkx as nx
# empty_tree = nx.DiGraph()
... | 5ed52f83aaafeaa64e9597ed628cf83c8fd9a454 | 639,373 |
def get_E_tot(in_path: str) -> float:
"""
Args:
in_path (str) - direct path to the log file from the VASP run
Return:
E_tot (float) - total calculated energies
This function suppose to parse log type file from the VASP run
and return the total energy of the structure ( 1 F= -...)
... | 189866935eff3f5cab8cbef4fe584c404df1e582 | 639,374 |
def prune_entries(bucket, pypi_dict, dump_dict):
"""
Since the wheel data set is updated incrementally, we need to check
if existing entries have been deleted from pypi and prune them accordingly.
"""
def fn_in_pypi(name, pkg_ver, fn):
if name in pypi_dict\
and pkg_ver in pyp... | 94c3d02159fd9294f1bdbefdf18a0225130826e4 | 639,375 |
def is_number(s):
"""
This function checks if given input is a float and returns True if so, and False if it is not.
:param s: input
:return: Boolean.
"""
try:
float(s)
return True
except ValueError:
return False | 652656c88719a886a1230dc514fd11d650deab04 | 639,376 |
def get_stage_list(n_stages, stage_ratios):
"""Get stage label."""
if n_stages == 3:
return [0, 1, 2]
stage_values = []
stage = 0
threshold = stage_ratios[stage] * n_stages
for x in range(n_stages):
if x >= threshold:
stage += 1
threshold += stage_ratios[s... | 3573783be2a15d443af8f54f4a633b8b86382618 | 639,377 |
def get_shared_otus(biom_tables,min_count,percentage):
""" Moves through a list of biom tables, returns OTUs that have at least some minimum count
that are present in a minimum percentage of samples across ALL of the biom tables
Pass:
biom_tables = a list of biom_table objects
min_count = the mini... | ba57b3c7b8d215f3da2a77088a451a073783c08f | 639,378 |
def home():
"""Return a basic string."""
return "Hello, World!" | 19707e63a6d699f01be8893f2a9d0821ffd6bdb7 | 639,379 |
def get_product_kernel(kernel_list, additive=False):
"""Given a list of kernel functions, return product kernel."""
def product_kernel(x1, x2, ls, alpha):
"""Kernel returning elementwise-product of kernel matrices from kernel_list."""
mat_prod = kernel_list[0](x1, x2, ls, 1.0)
for kerne... | 2dad0b10ca8f24cdf4e959cc17c5679cc10f59c2 | 639,380 |
def model_arguments(parser):
"""Add model specific args to the parser"""
group = parser.add_argument_group(
title='Model Arguments',
description="""\
These flags are set by Cloud ML from the hyperparameters defined
in the API call. They will be passed in as normal command line flags.
... | 710554cdfd1fe839e7f4dab1dca5560d0d6280e2 | 639,381 |
import torch
def init_lm_state(lm_model: torch.nn.Module):
"""Initialize LM hidden states.
Args:
lm_model: LM module.
Returns:
lm_state: Initial LM hidden states.
"""
lm_layers = len(lm_model.rnn)
lm_units_typ = lm_model.typ
lm_units = lm_model.n_units
p = next(lm_m... | af439cc237747bbcbb8508f5f93e5ced7468369b | 639,382 |
from bs4 import BeautifulSoup
def soupify(html, vars=[]):
"""
Convert html string to beautiful soup
"""
return BeautifulSoup(html.format(vars), "html.parser") | 3018bb41bf59dc356d8d987b29ec01420b86a662 | 639,383 |
import array
def _prepare_for_sound(mls):
"""
Re-scale the MLS so that is a proper array of bytes. This allows us to use
it with an audio device. We assume 16-bit precision.
"""
new_mls = []
int_max = 2**15 - 2
for sample in mls:
if sample == 0:
# Min UInt16
... | fb90c3e4f1b9b2aa7dd36bd2310a48540495f048 | 639,384 |
import json
def jsonify_parameters(params):
"""
When sent in an authorized REST request, only strings and integers can be
transmitted accurately. Other types of data need to be encoded into JSON.
"""
result = {}
for param, value in params.items():
if isinstance(value, (int, str)):
... | 19beacf0cb5f7437bc3f6c10d8f76cba5ea36583 | 639,385 |
import logging
def get_logging_level(level: str) -> int:
"""Get the logging level as a logging module constant.
:param level: `str` The log level to get.
:returns: The log level, defaults to `INFO`
"""
return getattr(logging, level.upper(), logging.INFO) | 06c64fc904c8269e7bb65cf9ec403f747eb8861d | 639,387 |
import os
def files_endswith_exists(dir, endswith_filters):
"""
Search if at least one file exists in 'dir' that ends with one of the specified filters
:param dir: search path (folder)
:param endswith_filters: tuple of file endings to filter e.g. (".n42",".res")
:return: True if at least one file ... | 468bd0c7f3b72021d0ce8b1483b1036aedee22bd | 639,388 |
import argparse
def parseargs() -> argparse.Namespace:
"""Parse args for plotter."""
parser = argparse.ArgumentParser(description="Plot data from network simulations.")
parser.add_argument(
"type",
type=str,
choices=["both", "bi", "multi"],
help="The type of network to plot... | d882279c7989f26d91267a2ecb029c133d894b3e | 639,389 |
def ld_block_end_line():
"""Constant XML comment text for end of link def block"""
return "END ORIGINAL LINK DEFS -->" | ea6d6f7af7e862139ef2d029f997d695e081b182 | 639,390 |
def calc_linear_terms(data_table, key = "fitflux", verbose=False):
"""
:param key:
:param data_table:
:param verbose:
:return:
"""
## x1-x2
dx = data_table["lambda_eff"][0] - data_table["lambda_eff"][1]
if verbose: print(dx)
## y1 - y2
dy = data_table[key][0] - data_table[key... | af6910ffe08a0a535c45c6c6ef01bf73664d8076 | 639,391 |
def _get_ping_userdata(test_ip):
"""
Returns the post VM creation script to be added into the VM's userdata
:param test_ip: the IP value to substitute into the script
:return: the bash script contents
"""
if test_ip:
return ("#!/bin/sh\n\n"
"while true; do\n"
... | 56837bc665d2622ae9e384295b5adfa593276da5 | 639,392 |
import os
def is_same_path(path_a, path_b):
"""
Compare the given paths.
Paths are expanded and normalized on comparison.
:param path_a: Path to compare.
:type path_a: str
:param path_b: Path to compare.
:type path_b: str
:return: True if the paths are the same.
:rtype: bool
... | ee389356dd04438c6d45151ff065f3b446836481 | 639,393 |
def judge(str_d, decimal):
"""
判断得到的商值的小数位数是否满足条件
:param str_d: 商值
:param decimal: 结果中保留的小数位数
:return: 满足返回True,否则返回False
"""
if '.' not in str_d:
return False
else:
if len(str_d) - str_d.index('.') - 1 < decimal:
return False
return True | 54a130b7decb43bfe817d42f50e2f4d21af64d85 | 639,394 |
def get_model_name(step):
"""
Return filename of model snapshot by step
:param step: global step of model
:type step: int
:return: model snapshot file name
:rtype: str
"""
return 'network-snapshot-{:06d}.pth'.format(step) | 1517e3104bf5cae654f5d6350a177a1d16f8ac13 | 639,395 |
from os.path import isfile, getmtime
def sourcemorerecent(sourcefile, targetfile):
""" Returns True if sourcefile is more recent than targetfile
"""
if isfile(targetfile):
time_source = getmtime(sourcefile)
time_target = getmtime(targetfile)
return time_source > time_target
else:
return True | b75c2e1ed7101d6337b752ba212939e6b555e80b | 639,396 |
def recursive_example(x: int) -> bool:
"""
pre: x >= 0
post[]:
__old__.x >= 0 # just to confirm __old__ works in recursive cases
_ == True
"""
if x == 0:
return True
else:
return recursive_example(x - 1) | 4eaac0157cd10f9d55fda560702040b673e0e1be | 639,398 |
import hashlib
def sha256(s):
"""Return SHA256 digest of the string `s`."""
return hashlib.sha256(s).digest() | a27a485bebe0b14f7e70f5f6f665b03d1ea43069 | 639,399 |
def build_path(package_name: str) -> str:
"""Build path from java package name."""
return package_name.replace(".", "/") | 7ef955bf28cd60a3350420cab1160c15c46cee09 | 639,400 |
def extList(l, item):
"""Add 'item' to list 'l', return index of 'item'"""
l.append(item)
return len(l)-1 | da384911802053d67ef5b8409ad97917ced36049 | 639,401 |
def parse_branch_ref(filename):
"""Given a filename of a .git/HEAD file return ref path.
In particular, if git is in detached head state, this will
return None. If git is in attached head, it will return
the branch reference. E.g. if on 'master', the HEAD will
contain 'ref: refs/heads/master' so 'refs/heads/... | e7a9df3e72460b4bc3ac7f97fd6f830cda309b22 | 639,402 |
from typing import Dict
def calculateHandlen(hand: Dict[str, int]) -> int:
"""Calculate hand length
Args:
hand:
Returns:
int: the length (number of letters) in the current hand.
"""
return sum(hand.values()) | 830d95ed3379e74f561bd0de6f70ff69d2b9271f | 639,403 |
import argparse
def parse_args():
"""Parse in command line arguments"""
parser = argparse.ArgumentParser(description='Test a Fast R-CNN network')
parser.add_argument(
'--dataset',
help='training dataset')
parser.add_argument(
'--cfg', dest='cfg_file', required=True,
he... | 13b5b7d28babc8193b308af063e948828cde9430 | 639,404 |
def dot(v, w):
"""向量的点乘"""
return sum(v_i * w_i for v_i, w_i in zip(v, w)) | e4766d392aac1578146037e6ee11edf413171c98 | 639,405 |
def get_args_as_string(frame, showFuncName=True):
"""
Returns the args of the input frame object as a string.
"""
# arguments => True
# locals => False
# statics => False
# in_scope_only => True
vars = frame.GetVariables(True, False, False, True) # type of SBValueList
... | 154f92d5267c7c1f3a0f74994fef1a42dc1fba59 | 639,406 |
import numpy
def sample_as_dict(sample):
"""Return sample object in dict format.
Args:
sample (list/dict/dimod.SampleView): Sample object formatted as a list,
Numpy array, dict, or as returned by dimod samplers.
Returns:
list: Copy of `sample` formatted as a dict, with variable i... | 97a6361a3c4ee7c5a728aaa27575526106278e0d | 639,407 |
from pathlib import Path
def stringify_metadata(path):
"""Underlying code to generate the metadata string, for any file format"""
path = Path(path)
magic = "META01;"
escaped_name = path.name.replace('"', '\\"')
namestr = f'name="{escaped_name}";'
with open(path, 'rt') as script_file:
... | 6e397db058bc364222128fe7355ebb9f616f6623 | 639,408 |
def commonp(json_data):
"""
Function receives the input json data
"""
for item, value in json_data.items():
if item == 'name':
if isinstance(value, int):
msg = 'Name of the product can not be an integer'
return {"status": "Failed!", "message": msg}, 40... | 62abb41bf8b543d931d3c1097391319da05179de | 639,409 |
def reject_name(species):
"""Species name be rejected, and not recorded in the DB."""
return (
species.split(None, 1)[0] in ("unclassified", "uncultured", "unidentified")
or species == "environmental samples"
) | 54fda50fc3f418003abf1d6cc727755c738993da | 639,411 |
def normalize_url(url: str) -> str:
"""Normalize URL
Arguments:
url {str} -- A URL
Returns:
str -- A normalized URL
"""
# remove string after "?" to comply with Pydantic AnyHttpUrl validation
# e.g. http:/example.com/test.js?foo=bar to http://example.com/test.js
splitted = ... | 86131ea4afc377748b8d280f2486f7abfa0e19f4 | 639,412 |
import os
def find_comp_mkfile(dirname):
""" Find component makefile (aos.mk) from dirname and its subdirectory,
exclude out, build, publish folder """
mklist = []
for root, dirs, files in os.walk(dirname):
tmp = (root + '/').replace("\\", "/")
if '/out/' in tmp or '/build/' in tmp or... | a953b4325099f5fb6769b36cfcb41ba6d3398528 | 639,413 |
import math
def calculate_tail_correction(num_particles, box_length, cutoff):
"""
The tail correction associated with using a cutoff radius.
Computes the tail correction based on a cutoff radius used in the LJ energy calculation in reduced units.
Parameters
----------
num_particles :... | 5b1571bd032c38a4a506e24fffcad448152f19c1 | 639,414 |
def is_prime(number):
"""
Find if a number is prime
Complexity: O(sqrt(NUMBER))
If n is a non prime integer then there is a prime
p that divides n (p | n) and p^2 <= n. We use the
same technique to find if n is a prime or not.
"""
if number == 0 or number == 1:
return False
... | 99ceca11b811e8cbccb09581df8a6eec0bca65b2 | 639,415 |
def rv(sv):
"""
Position part of state vector
:param sv: Stack of state vectors, can be one in stack IE column vector
:return: Position part, will be stack matching sv
"""
return sv[:3,:] | 5222f40db21fa6415cd52a73d72d294043f61709 | 639,416 |
import random
def mix_all_writers(data):
"""
> input:
[ [writer1, [[label, ...], [label, ...], [label, ...], ... ]],
[writer2, [[label, ...], [label, ...], [label, ...], ... ]],
.
.
.
]
> output:
[[label, ...], [label, ...], [label, ...], ... ]
"""
output =... | 4ef875c1de61a2317c91632da3f915f52a03fa6d | 639,417 |
import argparse
import os
def construct_parser():
"""Return argument parser."""
parser = argparse.ArgumentParser(
prog="jound",
description="A word generator using statistics from a book",
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument(
"-... | ce58bc5d50e2e37c0ec9a4f0368987345f605f2c | 639,418 |
def get_surt_association_script(surt, sheet):
"""Creates the beanshell script for a SURT->Sheet association."""
return "appCtx.getBean(\"sheetOverlaysManager\").addSurtAssociation(\"%s\", \"%s\" );" % (surt, sheet) | a1ff769144714b4d00e6855f3220838895eee08f | 639,419 |
def int_or_none(value):
"""Return integer equivalent or None for a given value.
:param value: value to be parsed
:returns: None if value=None else int(value)
"""
if value is None:
return None
if value == "":
return None
return int(value) | ab2a5fa05dea5c0c48c67b661fcda365b9b4654e | 639,420 |
def auth_response():
"""Moltin auth response fixture."""
return {
'expires': 1524486008,
'identifier': 'client_credentials',
'expires_in': 3600,
'access_token': 'xa3521ca621113e44eeed9232fa3e54571cb08bc',
'token_type': 'Bearer',
} | fe945c7d23f60a11fca05369bad17867a8b3d4b3 | 639,421 |
def match_sequences(seq1, seq2, diff_tol=1e-6):
"""
Given two lists (each item is int or float):
seq1 and seq2 with same sum, the method returns
matched indices and values.
Example:
seq1 = [1, 3, 1]
seq2 = [2, 1, 2]
return: [[(0,0),1],
[(1,0),1],
[(1,1),1],
[(1,2),1],
[(2,2),1]]
"""
# ... | 57efd07a6379ce6567a739fb7cf61157b4761d0f | 639,422 |
def get_citation_links(session, profile_url):
"""
From the given url to Google scholar page, extract all absolute links to
paper citations.
Args:
session (HTMLSession)
profile_url (str): a url to a person's Google Scholar page.
Returns:
list: list of absolute URLs to paper ci... | 38d040217db7b95c35a614011bbd2286c315991a | 639,424 |
def unique_common_chains(similar_chains, verbose=False):
"""
Given a dictionary of pairwise sequence-similar chains (output of the similar_chains function),
returns a "unique-common" chains-type dictionary, in which the keys are those chains to which most of the
chains in the model are common-to, and as... | 92911760afc51e7f5710809d2b1bf42528c6d88a | 639,425 |
def pig_latin(input):
"""
Given a phrase, return that phrase, translated to pig latin.
RULES:
1) For words that begin with consonant sounds,
all letters before the initial vowel are placed at the end of the word sequence.
Then, "ay" is added. Example:
pig -> igpay
2) When words begin w... | 3dbe269782d1e571d1127974e83a9057edecee12 | 639,426 |
def get_label_from_loader(loader, representation=None):
"""Pull label info from loader class"""
label = getattr(loader, "label", None)
if label is None:
label = loader.__name__
if representation:
# Add the representation as suffix
label = "{0} ({1})".format(label, representation[... | 4205f081cf49b2fb013594a05487839290d811b1 | 639,427 |
def from_date_to_mobile_consumers(date: str) -> float:
"""turns date into time"""
hours_f = float(date[11:13])
minutes_f = float(date[14:16])
mobile_consumers_f = float(date[17:19])
mmobile_consumers_f = float(date[20:23]) / 1000
return mmobile_consumers_f + mobile_consumers_f + minutes_f * 60 +... | 976682e6b6d637bc4b324b1a153914c43b1ea440 | 639,428 |
from operator import add
def element_wise(list1, list2):
"""
Perform element wise sum between two lists.
"""
return list(map(add, list1, list2)) | cac2b99227701461f0a9f02f30195129fec69208 | 639,429 |
def firfbe(a,wi,Abe):
"""
FIR Find Band Edges
% w = fir_fbe(a,wi,Abe);
% find band edges of an FIR filter using Newton's method
% using initial estimates
%
% A : a(1)+a(2)*cos(w)+...+a(n+1)*cos(n*w)
% wi : initial values for the band edges
% Abe : value of H at the band edges
... | b14b3c51a8635366436a2d1ac16560a8a329a1b7 | 639,430 |
import torch
def sum_rightmost(value: torch.Tensor, dim: int):
"""Sum out ``dim`` many rightmost dimensions of a given tensor.
Args:
value: A tensor of ``.dim()`` at least ``dim``.
dim: The number of rightmost dims to sum out.
"""
if dim == 0:
return value
required_shape =... | 9214bc18e08cd08efa946ec84740c283901e06f5 | 639,431 |
from pathlib import Path
from typing import Optional
def load_latest_model(model_folder: Path) -> Optional[Path]:
"""Finds the latest model inside the folder where
all the models are saved
Args:
model_folder (Path): folder containing the models
Returns:
Path: file path of the most re... | 62818ca57b6e2e4ae97890c30eca1e21b6fd0d45 | 639,432 |
def Mgap(d, Cij):
"""
returns the resonator gap between the lid and resonator to provide the necessary capacitance:
given the capacitance and resonator diameter
equation 13
"""
return 0.695*d*d/(100*Cij-2.61*d) | 41338166b855ede68b9a02c83703809cdbe08cd1 | 639,433 |
def load_events(filename, energy_thr = 0.01, nof_events = -1):
"""
load photon events from a text file (W,E,X,Y,Z,WX,WY,WZ), remove events with energy below threshold
:param filename: file name to load events from
:param energy_thr: energy threshold, events with energy below threshold will be thrown out... | 817b65af714f40be30c173bcfd3f1dc80f32ac6a | 639,434 |
def bytes_to_hex(bytes_str):
"""Convert a byte string to it's hex string representation"""
return ''.join(["%02X " % ord(x) for x in bytes_str]).strip() | d4d8cca6483bb8859efb1fe5163a1b5c3d8339c8 | 639,435 |
import subprocess
import sys
import os
def lspci_nvidia():
"""Check for and return the count of nvidia gpus."""
gpus = 0
try:
gpus = int(
subprocess.check_output(
"lspci | grep -i nvidia | awk '{print $1}' "
"| cut -d : -f 1 | sort -u | wc -l",
... | d45c2b0b73a43a3c0fcfcc31a4b36aca98c52cb3 | 639,437 |
import functools
import numpy
def nKron(AMatrix, BMatrix, *args):
"""
Recursively execute kron n times. This function has at least two matrices.
:param AMatrix: First matrix
:param BMatrix: Second matrix
:param args: If have more matrix, they are delivered by this matrix
:return: The result o... | e16734c0c6811a8b00bfe91ab3297e194bbf195f | 639,438 |
def prefix(values, content):
"""
Discover start and separate from content.
Will raise ValueError if none of the starts match.
"""
for value in values:
if content.startswith(value):
break
else:
raise ValueError('invalid starts')
content = content[len(value):... | 54efd93d5611b40683d382c640e20a6b43c08827 | 639,439 |
def _parameter_mapping(pairs):
"""
Find the parameter substitution we need so that expressions can
be evaluated without having to traverse a chain of
model.layer.parameter.value
"""
left,right = zip(*pairs)
pars = list(sorted(p for p in set(left+right) if p is not None))
definition = dic... | a18c9085f2588f14886a3070fd0b293f89f7700d | 639,440 |
import os
def read_file(dir_path, file_path):
"""
Read contents of a .py file and return as text
:param dir_path: str
:param file_path: str
:return: str
"""
goal_dir = os.path.join(dir_path, file_path)
with open(os.path.abspath(goal_dir), 'r') as fp:
contents = fp.read()
re... | 4921fb3c416e7bdfa1deaa7768be77ec2c276327 | 639,441 |
def add_inputs(input_1: float, input_2: float, *extra) -> float:
"""
adds 2 or more numbers together
:param input_1: first number
:type input_1: float
:param input_2: second number
:type input_2: float
:return: all the inputs added together
:rtype: float
"""
... | a28e92787f51a2b4525562dcfb74ffd9a3c61d3b | 639,442 |
import os
def all_file_path(root_directory, extension_name):
"""
:return: 遍历文件目录
"""
file_dic = {}
for parent, dirnames, filenames in os.walk(root_directory):
for filename in filenames:
if 'filter' not in filename:
if filename.endswith(extension_name):
... | 52a664aa0eb3ff9cb1860e2093f51607a8e54bf6 | 639,443 |
def find_matching_lunch_time(grade, tag_times):
"""
Uses the class of the corresponding tag to find the matching lunch times, then returns the matched lunch times.
"""
match = list(filter(lambda x: grade + "_lunch" in x, tag_times))
if(len(match) > 0):
return match[0]
else:
retu... | f934df17441ba53fd4c4c156822a320c84834eea | 639,444 |
def linear_rampup(current, rampup_length):
"""Linear rampup"""
assert current >= 0 and rampup_length >= 0
if current >= rampup_length:
return 1.0
else:
return current / rampup_length | ed567370750deee9353aae27de3b6b906023d18f | 639,445 |
def applianceSystemStoragePath(config):
"""
Returns the path to the internal appliance persistent storage.
"""
return config['storage.system.path'] | 2af2ec4ccd4a9999b00370c0cf251c293053a6eb | 639,446 |
import math
def DistanceBetweenCoordinates(lat1, lon1, lat2, lon2):
"""Distance between two coordinate pairs (in km)
Based on:
http://cyberpython.wordpress.com/2010/03/31/python-calculate-the-distance-between-2-points-given-their-coordinates/
"""
lat1_r = math.radians(lat1)
lat2_r = math.radians(lat2)
l... | c808b03ccfad3e7b16a42bd58118159da00f1c8e | 639,447 |
import os
def find_freesurfer_data():
"""
Returns the freesurfer data path defined in the environment.
"""
try:
dir_freesurfer_data = os.getenv('SUBJECTS_DIR')
except:
dir_freesurfer_data = None
return dir_freesurfer_data | fb3be607cefa2538320d52525fcfa15bdeea652a | 639,448 |
def get_room_info(listing):
"""
returns room info of listing
"""
room_info = listing.find('div', {'class', '_kqh46o'}).text
split_info = [i.split() for i in room_info.split(' · ')]
room_dict = {}
for i in split_info:
if i not in [['Studio'], ['Half-bath']]:
if len(i) == ... | dc4c05d5c2a2791cbb076db457c116fe04cb9e2b | 639,449 |
import json
def read_result(outfile):
""" Reads the result of an experiment """
return json.load(open(outfile, "rb")) | 1fd7f75db7b5580f3064ff213e616ebd6c4428cd | 639,450 |
def directory_structure(tmpdir):
"""Create a directory structure like this:
root
_____|___________________
| | | |
repo Main.java epic.py other_repo
________|________ ______|_________
... | 601d630c2a6251ae88c5d86abd3320e0aa07e336 | 639,451 |
def __count_statistic(pkey, pvalue, ptotalurls, ptotaltime):
"""
Count stat by each url
:param pkey: url
:param pvalue: list of req.times
:param ptotalurls: total urls
:param ptotaltime: total time
:return: list of data [
count of requests,
... | 6df34696888adf734158a40547da1944fa98e376 | 639,452 |
def _escape_regexp(s):
"""escape characters with specific regexp use"""
return (
str(s)
.replace('|', '\\|')
.replace('.', '\.') # `.` has to be replaced before `*`
.replace('*', '.*')
.replace('+', '\+')
.replace('(', '\(')
.replace(')', '\)')
.r... | 4f84107041c3b3fc99c83cd7ec4ece5a4483eec1 | 639,453 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.