content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import difflib
def compare_parameters(elem_a, elem_b):
"""
params is like "self;email;team_id;password;name"
:param elem_a:
:param elem_b:
:return: ratio
"""
if 'params' in elem_a.attrs and 'params' in elem_b.attrs:
if elem_a.attrs['params'] == elem_b.attrs['params']:
... | 3310c9d03d84d1ef14165a23e6280805b802a008 | 690,025 |
def gss(f, a, b, c, tau=1e-3):
"""
Python recursive version of Golden Section Search algorithm
tau is the tolerance for the minimal value of function f
b is any number between the interval a and c
"""
goldenRatio = (1 + 5 ** 0.5) / 2
if c - b > b - a:
x = b + (2 - goldenRatio) * (c... | 09050a75a28a420d436ff8a9380d781c4d1b0e3f | 690,026 |
import json
def get_count(json_filepath):
"""Reads the count from the JSON file and returns it"""
with open(json_filepath) as json_file:
data = json.load(json_file)
try:
return data["count"]
except KeyError:
return None | 22e6851d0739b36fd6fa179828ccb8e2f0a8e06e | 690,027 |
def nodesInTuples(setOfTuples):
"""
Show which nodes appear
"""
nodesList = []
for tupl in setOfTuples:
nodesList.extend(tupl)
return list(set(nodesList)) | 7ff235fb9b12434760f790bd23f05848a2b8f415 | 690,028 |
def split_by_univariate_data():
""" A fixture for univariate data that's split by.
"""
return {"A": {"y": [98, 99, 94]}, "B": {"y": [93, 92, 89]}} | a087e8826f1e8891160d962f2c4930ca858bbcbf | 690,031 |
def unwrap(datawrapper_class):
"""Decorator which feeds .data to the function, and returns result in DataWrapper"""
def new_decorator(old_func):
def new_func(*args, **kwargs):
data = args[0].data
result = old_func(data, *args[1:], **kwargs)
return datawrapper_class(r... | 8896b8829bc44bcb760b2319462c6218ab74f379 | 690,032 |
import argparse
def argparser():
"""
Command line argument parser
"""
parser = argparse.ArgumentParser(description='VAE collision detection')
parser.add_argument('--model', type=str, required=True)
parser.add_argument(
'--globals', type=str, default='./configs/globals.ini',
he... | 54e2bd73ab7095f9e877e45cd6de0338795e822b | 690,034 |
from bs4 import BeautifulSoup
import six
def _convert_toc(wiki_html):
"""Convert Table of Contents from mediawiki to markdown"""
soup = BeautifulSoup(wiki_html, 'html.parser')
for toc_div in soup.findAll('div', id='toc'):
toc_div.replaceWith('[TOC]')
return six.text_type(soup) | 90e1c58f194f54004539ee4cece082988add5050 | 690,035 |
def inputPlayerLetter():
"""Lets the player type which letter they want to be.
Returns a list with the player’s letter as the first item,
and the computer's letter as the second."""
letter = ""
while not (letter == "X" or letter == "O"):
print("Do you want to be X or O?")
letter = in... | ba43ae7b5873d2eca5180724a5ad772c68b426d2 | 690,036 |
import itertools
import random
def get_parameter_list(equal_concept_length, equal_transition_length, max_num_drifts):
"""Gets the list of parameter dictionaries for generating streams.
Parameters:
equal_concept_lenth (bool): If true, each parameter configuration will have concepts of equal length. Other... | 7ffbead857ea6567433f4666fe15e787d7b9fc4f | 690,037 |
import re
import logging
def check_edge(graph, edge_label):
"""
Parameters
----------
graph : nx.DiGraph
A graph.
edge_label : str
Edge label.
Returns
-------
int
Counts how many edges have the property `label` that matches `edge_label`.
"""
edge_label... | 44b81afbfbe5533a96ee941040ab5b09d00b687e | 690,038 |
import re
def freeze_resnet_blocks(model, layers, layer_name_base='res', inverse=False):
""" Set the given block layers in a resnet model to non-trainable.
The weights for these layers will not be updated during training.
This function modifies the given model in-place,
but it also returns the modif... | 835dc8c5ca32b6d3db4332f9216da8edbd4ff10f | 690,039 |
def stinger(input_string, ret=int()):
"""Returns a list(char_list,word_list,sentence,word_count,sentence_count)."""
char = str() # type: str
char_list = [] # type: list
word_list = [] # type: list
sentence = [] # type: list
char_count = int() # type: i... | c71ea4f183c405ec5a89ee487e1428a1ba7bdb39 | 690,040 |
def read_stick_face(degen_geom_file, lines, iline, log):
"""
DegenGeom Type, nXsecs
STICK_FACE, 5
sweeple,sweepte,areaTop,areaBot
"""
degen_geom_file.readline()
iline += 1
sline = degen_geom_file.readline().strip().split(',')
sline2 = lines[iline].strip().split(',')
assert sline... | 5bcce85143bd3280ab09ffe8b0fb3d4bb4a171c9 | 690,041 |
def package_installed(module, pkg):
"""
Determine if a package is already installed.
"""
rc, stdout, stderr = module.run_command(
'pacman -Q %s' % pkg, check_rc=False)
return rc == 0 | ced7fa1e575da9a141b0c87fef6b241e0e823674 | 690,042 |
def _get_call_args(arg_names, vararg_name, kw_name, varargs, kwargs):
"""
Decorator to integrate parameter names and values.
"""
call_dict = {}
varargs = tuple(varargs)
kwargs = dict(kwargs)
call_varargs = None
var_arg_cnt = len(varargs)
arg_names_cnt = len(arg_names)
if arg_na... | 8231eee97ab7df4c89109a1c0bca2bcef9998fab | 690,043 |
def show_devices_setup(creds, search_value, device_value, devicelist_result):
"""Show devices value test setup."""
return creds, search_value, device_value, devicelist_result | 57dac906143d3522b6ec41823a4c52b0e9cddd3c | 690,044 |
def _str_to_bytes(s):
"""Convert str to bytes."""
if isinstance(s, str):
return s.encode('utf-8', 'surrogatepass')
return s | 79e39f852461c87023f8ee69eb2cc392f0542b3e | 690,045 |
from typing import Any
def _pydantic_dataclass_from_dict(dict: dict, pydantic_dataclass_type) -> Any:
"""
Constructs a pydantic dataclass from a dict incl. other nested dataclasses.
This allows simple de-serialization of pydentic dataclasses from json.
:param dict: Dict containing all attributes and v... | 016e4285dc89d98fa988cc45aea5093d90bdf478 | 690,046 |
import importlib
def load_module(mod):
"""Load a python module."""
module = importlib.import_module(mod)
print(module, mod)
return module | 7cfe432b2837ce5d7531f1d6cbc0b279e0c353e2 | 690,047 |
def get_records(record_probs, point_rank_probs, groups):
"""Orders record and expected rank per points probabilities into a
list and trims decimal places.
"""
records = {group: [] for group in groups}
for group in groups:
for team, record_prob in sorted(record_probs[group].items(),
... | 7a21043965cf285fceb91537886f49bc0dc31cee | 690,049 |
import os
def get_atomic_mass_dict() -> dict[str, float]:
"""Builds a dictionary of atomic symbols as keys and masses as values.
Returns
-------
Dict of atomic symbols and masses"""
atomic_mass_dict = {}
dir_path = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(dir_pat... | d092028e34a8bc7f373ad15de8a0d2dc31c51906 | 690,050 |
def gcd(a, b):
"""Returns the greatest common divisor of a and b, using the Euclidean
algorithm."""
if a <= 0 or b <= 0:
raise ValueError('Arguments must be positive integers')
while b != 0:
tmp = b
b = a % b
a = tmp
return a | 8560344ce9af6c3835560cbda9f03963f4a21518 | 690,051 |
def sp_integrate_3D_ ( pdf ,
xmin , xmax ,
ymin , ymax ,
zmin , zmax ,
*args , **kwargs ) :
""" Make 3D numerical integration over the PDF
"""
if hasattr ( pdf , 'setPars' ) : pdf.setPars()
func = pdf... | 9ef1922dfea84713b7e65f92168d3e00306e0201 | 690,053 |
def find_server(dbinstance, params):
"""
Find an existing service binding matching the given parameters.
"""
lookup_params = params.copy()
for srv in dbinstance.servers:
# Populating srv_params must be in sync with what lookup_target()
# returns
srv_params = {}
for ... | 3525f5b246ef8943e2c710ed5f2313982eabb4c2 | 690,054 |
def transform_metrics_per_class(metrics_per_class, idx2word):
"""from list to dict, add one entry label"""
transformed_metrics_per_class = {}
for e in metrics_per_class:
e["label"] = idx2word[e["class_id"]]
transformed_metrics_per_class[e["label"]] = e
return transformed_metrics_per_clas... | 6279836a59768f9a22f43b2794f2d78df8531340 | 690,055 |
def get_edit_type(word, lemma):
""" Calculate edit types. """
if lemma == word:
return 'identity'
elif lemma == word.lower():
return 'lower'
return 'none' | 408885d247e0fd82e0656f4433e973baec0f71dc | 690,056 |
def getLocation(str):
"""
坐标转换116.305593-40.046283转为116.305593,40.046283
:param str:
:return:
"""
n_str = str.split('-')
return ",".join(n_str) | 56452063b8ec6cc04e1508fa393027c41bc396e4 | 690,057 |
def __is_global(lon, lat):
"""
check if coordinates belong to a global dataset
Parameters
----------
lon : np.ndarray or xarray.DataArray
lat : np.ndarray or xarray.DataArray
Returns
-------
bool
"""
if lon.max() - lon.min() > 350 and lat.max() - lat.min() > 170:
re... | 82340b5fef5d1826fac0eabd4c0adba0a6525a41 | 690,058 |
def quaternion_invert(quaternion):
"""
Given a quaternion representing rotation, get the quaternion representing
its inverse.
Args:
quaternion: Quaternions as tensor of shape (..., 4), with real part
first, which must be versors (unit quaternions).
Returns:
The inverse,... | 69f3596631eeae765a9b4d6d01d4f73bf8272970 | 690,059 |
import pandas
def create_update_method():
"""
Create model update method for scikit-learn models to be compatible with :class:`msdss_models_api:msdss_models_api.models.Model`.
See :meth:`msdss_models_api:msdss_models_api.models.Model.update`.
Author
------
Richard Wen <rrwen.dev@gmail.com>
... | 15b8531708a788d52ec56ab87efe4a0d4ad66b13 | 690,060 |
import os
import json
def get_detections_from_log(json_file, output_base_dir, video_file=None,
frame_rate=12, image_w=1920, image_h=1080,
image_folder='img1', img_extension='.jpg', prefix=None):
"""Parse log file from local regression test. Write to MOT form... | 3e913a1f9a259b3e7118deb7603a103d3921d946 | 690,061 |
import requests
from bs4 import BeautifulSoup
def get_callnmuber_nbin(isbn):
"""get callnumber form nbin net
:return:
"""
# isbn = "9789863125501"
# url = "http://nbinet3.ncl.edu.tw/search*cht/?searchtype=i&searcharg=9789863125501"
domain = "http://nbinet3.ncl.edu.tw"
base_url = "http://n... | d51e25b57c6479151b925145849e899ff2c7a2d4 | 690,062 |
import sys
def opt_validate (optparser):
"""Validate options from a OptParser object.
Ret: Validated options object.
"""
(options, args) = optparser.parse_args()
if not options.config:
optparser.print_help()
sys.exit(1)
elif not options.in_bam:
optparser.print_help()
... | 0402a5d4d6ea9d439bc8eefc08996adff90fe602 | 690,063 |
def _guess_platform_tag(epd_platform):
""" Guess the platform tag from the given epd_platform.
Parameters
----------
epd_platform : EPDPlatform or None
"""
if epd_platform is None:
return None
else:
return epd_platform.pep425_tag | 024b852071f92f31bae17885411788703a84ac61 | 690,064 |
import ast
from typing import OrderedDict
def mbta_route_list():
"""
From complete_routes.txt generated by fetch_mbta_routes, outputs list of possible mbta route_ids
Output: List of mbta route_ids
"""
f = open('complete_routes.txt', 'r')
complete_routes = ast.literal_eval(f.read())
#creat... | a55f0991f6640ce2c98a425b5a77f0d6128ce178 | 690,065 |
def parse_categories(eatery):
"""Parses the restaurant category.
Returns a list of strings.
"""
categories_arr = eatery.get("categories", "").split(", ")
categories = map(lambda x: x[1:-1], categories_arr)
return categories | 7ce8a6a9b477bd5a0fec698d3ed5b3524b0c4ef5 | 690,066 |
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(sorted(nums)[::2]) | 35508e6674a6606a3b445ab0da32a35fff9192a5 | 690,067 |
def correctPR(text):
"""
Remove the trailing space in the PR avlues.
:param text:
:return: corrected PR
"""
return text.replace(" ", "") | b18c5074dc584b08c9d5d6f024097e7a30c1ff18 | 690,068 |
def cubo_oct_coord_test(x, y, z): # dist2 = 2
"""Test for coordinate in octahedron/cuboctahedron grid"""
return (x % 2 + y % 2 + z % 2) == 2 | bb77a4660b98282f71932a4a2e8c3f97d8aebbd4 | 690,071 |
def get_colnames(main_colnames=None, error_colnames=None, corr_colnames=None,
cartesian=True):
"""
Utility function for generating standard column names
"""
if main_colnames is None:
if cartesian:
# main_colnames = [el for el in 'XYZUVW']
main_colnames = ... | 7139a73dbc2479a1899cdce1a9cb55d3c70a6b0b | 690,072 |
import os
def read_OS_var(var_name, mandatory=True, default_val=None):
"""
Read OS variable safely
:param var_name:
:param mandatory: raise Exception if variable does not exist - otherwise return None
:param default_val: provide a default return value if OS variable does not exist
:return: OS ... | 56c74f9cf1d2aea4cee5aa2702a25765c4f92eb0 | 690,073 |
def blinks_count(smiles_list):
"""
groups
:param smiles_list:
:return:
"""
res = []
for i in range(0, len(smiles_list), 4):
a = smiles_list[i: i + 4]
res.append(1) if sum(a) >= 2 else res.append(0)
for element in range(1, len(res) - 1):
if res[element - 1] != res... | debc4dbe50098ad4403acf0b772043f7b48ebfbd | 690,074 |
import decimal
def binary_to_decimal(man, exp, n):
"""Represent as a decimal string with at most n digits"""
prec_ = decimal.getcontext().prec
decimal.getcontext().prec = n
if exp >= 0: d = decimal.Decimal(man) * (1<<exp)
else: d = decimal.Decimal(man) / (1<<-exp)
a = str(d)
decimal... | e2a06efc82641e2f5d630b136d8290c721f3fefd | 690,075 |
def real_number(value):
"""判断是否是实数"""
if isinstance(value, (int, float)):
return value
elif isinstance(value, str):
return float(value)
elif isinstance(value, complex):
raise TypeError('不支持复数')
else:
raise ValueError('类型错误') | 0fcec8320f5d981addb9cc614eca893e9d0e5907 | 690,076 |
import math
def numDecks(numPlayers):
"""Specify how many decks of cards to put in the draw pile"""
return math.ceil(numPlayers*0.6) | 9ebdf4614a0319dd6fa28734b003182374bf8f9c | 690,078 |
def jpeg_header_length(byte_array):
"""Finds the length of a jpeg header, given the jpeg data in byte array format"""
result = 417
for i in range(len(byte_array) - 3):
if byte_array[i] == 0xFF and byte_array[i + 1] == 0xDA:
result = i + 2
break
return result | f6e3716264a0014990d23a3ccf105ae8695459d4 | 690,080 |
def __get_predicted_labels_from_neighbours(neighbour_labels, neighbour_distances, weights=None):
"""
Returns the predicted labels (as a binary indicator array) for an instance, based upon
the given neighbour_labels and neighbour_distances.
If weights is 'distance', each neighbour's vote will be inverse... | f445a23034dd575c2c36176b0fadd8d97efc9b78 | 690,081 |
def get_price(offer):
""" Returns a regular price from an offer listing, which is named differently on each site """
price_tag = offer.find("p", class_="price").strong
return price_tag | 92d6c10ada0c506c00c6816c572bf6745a72b2a6 | 690,082 |
def get_cluster_id_by_name(dataproc, project_id, region, cluster_name):
"""Helper function to retrieve the ID and output bucket of a cluster by
name."""
for cluster in dataproc.list_clusters(project_id, region):
if cluster.cluster_name == cluster_name:
return cluster.cluster_uuid, cluste... | 0ca5ea6183fbac0ceea6671d6aff1786ea26c3ca | 690,083 |
import argparse
import os
import sys
def argparser():
"""
Parses arguments.
For more information run ``python main.py -h``.
Returns
-------
args : dict
Parsed arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument("directory", type=str,
help="directory with the images")
parser.add_argum... | 1c77e9659b34bb1006f056eebeab76ea7a9dceb1 | 690,084 |
import random
def better(model1, model2, evaluator):
"""
:param model1: a model
:param model2: a model
:return: one of the two models, depending on the evaluation
"""
for model in (model1, model2):
if model.value is None:
model.value = evaluator(model)
prob_1_better = ... | 09582cc7b2b8f7246f1dc195e41932373394c319 | 690,085 |
def get_leaderboard_info(games, user, leaderboard):
"""Returns information for the leaderboards page and my_account
Searches games that user was in and compiles information
Args:
games
user
leaderboard
"""
leaderboard[user.username]['full_name'] = user.get_full_name... | ee439c92375994d2e62bc7635e4c317ddcc46d4f | 690,087 |
def diagpq(p, q=0):
"""
Returns string equivalent metric tensor for signature (p, q).
"""
n = p + q
D = []
for i in range(p):
D.append((i*'0 ' +'1 '+ (n-i-1)*'0 ')[:-1])
for i in range(p,n):
D.append((i*'0 ' +'-1 '+ (n-i-1)*'0 ')[:-1])
return ','.join(D) | 29e86f72338d31e8791f68331618273b17eb2cd9 | 690,088 |
def mag_to_flux(mag, zeropoint):
"""Convert a magnitude into a flux.
We get the conversion by starting with the definition of the magnitude scale.
.. math::
m = -2.5 \\log_{10}(F) + C
2.5 \\log_{10}(F) = C - m
F = 10^{\\frac{C-m}{2.5}}
:param mag: magnitdue to be converted ... | e3fd5d7cd97fd97517f42ed31a385a8b8b90c694 | 690,089 |
def make_init_message(*, dim, order, dt, t_final,
nstatus, nviz, cfl, constant_cfl,
initname, eosname, casename,
nelements=0, global_nelements=0):
"""Create a summary of some general simulation parameters and inputs."""
return(
f"Initiali... | dcc00c03d79b27ea9b2f5dcc8947b9a2d8e409d2 | 690,090 |
def typedlist(oktype):
"""Return a list that enforces a type signature on appends.
>>> intlist = typedlist(int)
>>> someints = intlist([1, 2, 3])
But this fails:
>>> someints = intlist(['1', '2', '3'])
"""
class TypedList(list):
def __init__(self, *lst):
if lst:
... | 57a47c64bcd7c72d01e6c4ae8ee23ff11a8aae5b | 690,091 |
import json
def main_compile_targets(args):
"""Returns the list of targets to compile in order to run this test."""
json.dump(['chrome', 'chromedriver'], args.output)
return 0 | 89885ec207a072d77c679c8a1b1b0ebc8e64a9f1 | 690,092 |
def get_atom_name(atom):
"""Formats an atom name for packing in .cif.
:param Atom atom: the atom to read.
:rtype: ``str``"""
return '"{}"'.format(atom._name) if "'" in atom._name else atom._name | 0853760eafb0108b130a4d764005bc2d2aa1fcc9 | 690,093 |
def get_features():
"""Returns the feature names
Returns:
list(str): list of strings containing names
"""
return ['min_len', 'max_len', 'upper', 'lower', 'mean', 'digits',
'letters', 'spaces', 'punct'] | cb440bdd3bfffe0497862fa0b343ebd29a31da37 | 690,094 |
def Ising_check(function):
"""Decorator to check the arguments of calling Ising gate.
Arguments:
function {} -- The tested function
"""
def wrapper(self, phi):
"""Method to initialize Ising gate.
Arguments:
phi {int, float} -- The used angle
Ra... | 7ea0bd5fa4981fac26c09e1c646d03f3eebf1e4a | 690,095 |
def p_(*args):
"""Get the name of tensor with the prefix (layer name) and variable name(s)."""
return '_'.join(str(arg) for arg in args) | f060c092e5f1e0d3e00a35cb87b69211805d12e6 | 690,096 |
import re
import difflib
def __verifyUpdate(old, new):
"""
Verifies than an update is needed, and we won't be just updating the timestamp
"""
old2 = re.sub('generated at (.*?) by', 'generated at ~~~~~ by', old)
#pywikibot.showDiff(old2, new)
update = False
for line in difflib.ndiff(old2.sp... | 93fa60477446ee1fed9f0d82d4e49aa0b4245e05 | 690,097 |
def neighborhoodCounts(subscripts, label, values):
"""
Compute the number of neighbors of each label directly adjacent to a
vertex.
Parameters:
- - - - -
subscripts : list
indices of directly-adjacent vertices / voxels
reshaped : int, array
label vector
values : accepte... | 611aa328a7e0187f5529cd09a4606b7449ec5c8f | 690,098 |
def lmean (inlist):
"""
Returns the arithematic mean of the values in the passed list.
Assumes a '1D' list, but will function on the 1st dim of an array(!).
Usage: lmean(inlist)
"""
sum = 0
for item in inlist:
sum = sum + item
return sum/float(len(inlist)) | e071892f28c7ee3ce85256bcaf42aae802a2ce7d | 690,100 |
def quote_remover(var):
"""
Helper function for removing extra quotes from a variable in case it's a string.
"""
if type(var) == str:
# If string, replace quotes, strip spaces
return var.replace("'", "").replace('"','').strip()
else:
# If not string, return input
... | 071cf9c790f76cd867e65001555d2429f01a4a20 | 690,101 |
def _read():
"""Returns a query item matching messages that are read."""
return f"is:read" | 58535cc3c85642d6cfd0ddd3d9f54ee83255c361 | 690,102 |
import argparse
import sys
def parse_args_visualizer():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument("--data_path", type=str, help="Data path", required=True)
parser.add_argument("--order_type", type=str, help="Order type", choices=['bfs','random'])
... | fbdef9f9b6faf13e81ec710720486776384eb05f | 690,103 |
def sieve(limit):
"""Returns list of prime numbers to given limit."""
numbers = [x for x in range(2, limit + 1)]
primes = []
while numbers:
primes.append(numbers.pop(0))
for item in numbers:
if not item % primes[-1]:
numbers.remove(item)
return primes | 3da085056a1ef5e5bb271fb05ead7e88f7b31a71 | 690,105 |
def write_code_aster_load(load, model, grid_word='node'):
"""writes a BDF load card in CA format"""
load_ids = load.get_load_ids()
load_types = load.get_load_types()
#msg = '# Loads\n'
msg = ''
(types_found, force_loads, moment_loads,
force_constraints, moment_constraints,
gravity_loa... | 9452c40855a0d291def9d99d43ec323552ab9ab2 | 690,107 |
def float_to_fp(signed, n_bits, n_frac):
"""Return a function to convert a floating point value to a fixed point
value.
For example, a function to convert a float to a signed fractional
representation with 8 bits overall and 4 fractional bits (S3.4) can be
constructed and used with::
>>> s... | bdfe4a66bc879b41aaced73a5eabad3164e568d7 | 690,108 |
import random
def random_replicate_name(len=12):
"""Return a random alphanumeric string of length `len`."""
out = random.choices('abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRTUVWXYZ0123456789', k=len)
return ''.join(out) | 88423a7ac2449e170d0f568ba1f33a0e03126808 | 690,109 |
def remove_nodes_from_dictionary(json_object: dict, field: dict) -> None:
""" Remove specific nodes from the dictionary. """
remove_nodes = field.get('removeNodes', '')
for node_to_remove in remove_nodes:
json_object.pop(node_to_remove, None)
return None | 2f033d2be6cecf55b13d061abb6be0c8109986c9 | 690,110 |
def _remove_leading_relative_paths(paths):
""" Removes the leading relative path from a path."""
removed = []
for path in paths:
if path.startswith("./"):
removed.append(path[2:])
else:
removed.append(path)
return removed | e45e4698fa8e73e87dfa05432c6af5a9a42489eb | 690,111 |
def hk_modes(hier_num):
"""
Generate modes in the HK hierarchy.
Parameters
----------
hier_num : int
Number in the HK hierarchy (hier_num = n means the nth model).
Returns
-------
p_modes : list
List of psi modes, represented as tuples.
Each tuple contains the h... | 57fe789043f9389b71f1097672320b921dba0faa | 690,112 |
import shutil
def get_gaussian_version():
"""
Work out if gaussian is available if so return the version else None.
"""
if shutil.which("g09") is not None:
return "g09"
elif shutil.which("g16") is not None:
return "g16"
else:
return None | 6fa256cec58fb40bbe672410e0563acf920e3d5e | 690,113 |
def _is_target_node(node: str) -> bool:
"""Check if it is valid target node in BEL.
:param node: string representing the node
:return: boolean checking whether the node is a valid target in BEL
"""
if node.startswith('bp') or node.startswith('path'):
return True
return False | cee9950e6ca173970a042e8058d5eecfe1dbf234 | 690,114 |
import locale
def decode_input(text):
"""Decode given text via preferred system encoding"""
# locale will often find out the correct encoding
encoding = locale.getpreferredencoding()
try:
decoded_text = text.decode(encoding)
except UnicodeError:
# if it fails to find correct encoding t... | 721e66332dbf4580ea3b5730527b97481a523de8 | 690,115 |
def fill_in_datakeys(example_parameters, dexdata):
"""Update the 'examples dictionary' _examples.example_parameters.
If a datakey (key in 'datafile dictionary') is not present in the 'examples
dictionary' it is used to initialize an entry with that key.
If not specified otherwise, any 'exkey' (key in ... | 28c0810c7de979d04520ec67fd60a9b505838758 | 690,116 |
def contrast(img, threshold):
"""
Constrast all pixels of an image given a threshold.
All pixels smaller or equal will be 0 and the other will be 255
"""
return (img > threshold) * 255 | a2c5cd449cb8333458892acbc5d2bc740d8ef1e2 | 690,117 |
def _intended_value(intended, unspecified, actual, name, msg):
"""
Return the intended value if the actual value is unspecified or has
the intended value already, and otherwise raise a ValueError with the
specified error message.
Arguments:
* `intended`: The intended value, or sequence of va... | 6ee1eb519629ae96c3ef87c319ec71548d603d87 | 690,118 |
def cortical_contrast(mean_gm, mean_wm):
"""Calculate the vertex-wise cortical contrast.
- cortical contrast = (mean WM intensity) - (mean GM intensity) /
( (mean WM intensity + mean GM intensity) / 2 )
:type mean_gm: float
:param mean_gm: The mean value of the gray matter ... | a01d8599a6a0d53ae978f111694bd47f133ce0bc | 690,119 |
def find_first(iterable, default=False, pred=None):
"""Returns the first true value in the iterable.
If no true value is found, returns *default*
If *pred* is not None, returns the first item
for which pred(item) is true.
"""
# first_true([a,b,c], x) --> a or b or c or x
# first_true([a,b... | 1f485f11155fdffbbf64566646836239cdb3319c | 690,120 |
def model_set(model):
"""Converts a model from a dictionary representation to a set representation.
Given a ``model`` represented by a dictionary mapping atoms to Boolean values,
this function returns the *set* of atoms that are mapped to ``True`` in the dictionary.
Paramters
---------
model ... | 3f2155d5298e328e3d564b355a5cb445625e371c | 690,122 |
import logging
def get_type(node):
"""Get xpath-node's type.(recursive function).
Args:
node: The xpath-node's root.
Returns:
return xpath-node's type.
"""
if node.keyword not in ['leaf','leaf-list']:
return None
type_stmt = node.search_one("type")
if not type_stmt:... | 8d80c1cad478c14bf761967fee3999924ad54042 | 690,123 |
def dict_to_list(d):
"""Converts an ordered dict into a list."""
# make sure it's a dict, that way dict_to_list can be used as an
# array_hook.
d = dict(d)
return [x[-1] for x in sorted(d.items())] | 6a56f890d3a5e6e9cb8a19fc5af8598bf3411d33 | 690,124 |
def halt_after_time(time,at_node,node_data,max_time=100):
"""
Halts after a fixed duration of time.
"""
return time>=max_time | c1d2b82d5a8b2019be8ea845bf5b135ed7c5209f | 690,127 |
def perform_authenticate(dispatcher, intent):
"""Authenticate."""
return intent.authenticator.authenticate_tenant(intent.tenant_id,
log=intent.log) | a12b4be7661a96e2efe6d9493af687e6d1cd4b84 | 690,128 |
def text_html_table(caption=None):
"""Return a text HtmlTable with a given caption for testing."""
if caption:
caption = f"<caption>{caption}</caption>"
return f"""
<table>
{caption}
<tr></tr>
<tr></tr>
</table>
""" | ab0c62a9a8eac2cb24e83216b05a25893bdbfe14 | 690,129 |
def is_even(k):
"""Solution to exercise R-1.2.
Takes an integer value and returns True if k is even, and False
otherwise. However, the function cannot use the multiplication, modulo, or
division operators.
"""
k_str = str(k)
last_digit = int(k_str[-1])
return last_digit in [0, 2, 4, 6, ... | 5495af93e5a62b54169b0a9edeb8889262f64449 | 690,130 |
def is_command(text):
"""
Checks if `text` is a command. Telegram chat commands start with the '/' character.
:param text: Text to check.
:return: True if `text` is a command, else False.
"""
if (text is None): return None
return text.startswith('/') | fda755a7622f8b232e4dfd3caa3183981b4dc601 | 690,131 |
def tree_update(tree, update, logger=None):
"""
Update a nested dictionary while preserving structure and type.
In the event of a key clash:
- Top level keys will mask lower level keys.
- Lower level keys will mask either non-deterministically or in order.
If you need to update lower l... | 2148b6f5f655cf56e7c8f909d9c145195283be13 | 690,132 |
from typing import List
from typing import Tuple
def longest_path(dir_str: str) -> str:
"""
To find the longest path to any dir/file.
Can be easily modified to get the longest path to just a file
:param dir_str: Directory string containing the directory structure
:return: longest directory path (... | 16929fe87a77503a23370b24af17a2d4b4316057 | 690,133 |
def columns(thelist, n):
"""
Break a list into ``n`` columns, filling up each row to the maximum equal
length possible. For example::
>>> l = range(10)
>>> columns(l, 2)
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
>>> columns(l, 3)
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]
... | 5e427e81009ded1cf5e670fd4b68360df338a0b7 | 690,134 |
from typing import List
from typing import Tuple
def configuration_key_intersection(*argv: List[Tuple[int, int]]
) -> List[Tuple[int, int]]:
"""Return the intersection of the passed configuration key lists.
Args:
*args (list[(int, int)]): any number of configuration ... | d40e05a7f3f06f086034ae8145dd994bdb4bc3b8 | 690,135 |
def get_vendor_name(cardname):
"""
Returns human-readable name of card vendor based on provided card name
@param cardname: string with card name, e.g., 'NXP JCOP J2A080 80K'
@returns human-readable vendor string
"""
if cardname.find('Feitian') != -1: return 'Feitian', None
if cardname.find('... | 06b93907f87265d58438b45e6a993bf237f91beb | 690,136 |
from typing import List
def find_first_in_list(txt: str, str_list: List[str]) -> int:
"""Returns the index of the earliest occurrence of an item from a list in a string
Ex: find_first_in_list('foobar', ['bar', 'fin']) -> 3
"""
start = len(txt) + 1
for item in str_list:
if start > txt.find... | c979db94ae1e81e3e7cbfc6118b371ab2338192f | 690,137 |
def create_Interfaces_Params(typeid, mainid, useip, ip, dns, port):
"""
typeid: 1-agent,2-SNMP,3-IPMI,4-JMX
mainid: 0-not default,1-default
useip: 0-usedns,1-useip
"""
interfaces = [{
"type": typeid,
"main": mainid,
"useip": useip,
"ip": ip,
"dns": dns,
... | aa4a6490a6423522b5a9e3a903d12f355320539a | 690,138 |
import json
def from_json(config_file_path):
"""Read data from a json file.
Check the file exists and create it if not.
We want to return an empty dict and not fail if the file contains no data.
:param config_file_path Path: Path representing the file-to-read.
:returns dict: config data (or an e... | 015840ad7eb969bc7c30f2ed4f4c0e20c69a7bba | 690,139 |
def small_peaks(feature):
"""
feature - pybedtools feature
returns center of clipper called peak (the middle of the narrow start / stop)
"""
try:
feature.start = (int(feature[6]) + int(feature[7])) / 2
feature.stop = ((int(feature[6]) + int(feature[7])) / 2) + 1
except In... | 2f530e75d925da109782a2d3ccc0003a41db0180 | 690,140 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.