content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def pf_mobility(phi, gamma):
""" Phase field mobility function. """
# return gamma * (phi**2-1.)**2
# func = 1.-phi**2
# return 0.75 * gamma * 0.5 * (1. + df.sign(func)) * func
return gamma | 10045807bdb030c362d700d61789c0a490aad93b | 707,223 |
import argparse
def parse_args():
"""Parse commandline arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('--minSdkVersion', default='', dest='min_sdk_version',
help='specify minSdkVersion used by the build system')
parser.add_argument('--targetSdkVersion', default='',... | 4ccbb4fa225abbe4eaa249a2dbc537d338559b62 | 707,224 |
import os
def cases():
"""
Loads all filenames of the pre-calculated test cases.
"""
case_dir = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'cases'
)
cases = []
for dir_path, _, files in os.walk(case_dir):
cases = cases + [os.path.join(dir_path, f) fo... | 1e8cbf1001cb52ab5875b38714f1edca664f867c | 707,226 |
def get_master_name(els):
"""Function: get_master_name
Description: Return name of the master node in a Elasticsearch cluster.
Arguments:
(input) els -> ElasticSearch instance.
(output) Name of master node in ElasticSearch cluster.
"""
return els.cat.master().strip().split(" "... | 0371dac1fdf0fd6b906646e1882e9089d9dfa12c | 707,227 |
def smith_gassmann(kstar, k0, kfl2, phi):
"""
Applies the Gassmann equation.
Returns Ksat2.
"""
a = (1 - kstar/k0)**2.0
b = phi/kfl2 + (1-phi)/k0 - (kstar/k0**2.0)
ksat2 = kstar + (a/b)
return ksat2 | ae413d7ed55862927e5f8d06d4aff5bfc0e91167 | 707,228 |
def organize_by_chromosome(genes, transcripts):
""" Iterate through genes and transcripts and group them by chromosome """
gene_dict = {}
transcript_dict = {}
for ID in genes:
gene = genes[ID]
chromosome = gene.chromosome
if chromosome not in gene_dict:
chrom_genes =... | 2f55d29a75f5c28fbf3c79882b8b2ac18590cdb2 | 707,229 |
def get_word_combinations(word):
"""
'one-two-three'
=>
['one', 'two', 'three', 'onetwo', 'twothree', 'onetwothree']
"""
permutations = []
parts = [part for part in word.split(u'-') if part]
for count in range(1, len(parts) + 1):
for index in range(len(parts) - count + 1):
... | 5a4c042cc0f3dedb297e2513bf638eac4278e0a6 | 707,230 |
import tempfile
def env_to_file(env_variables, destination_path=None, posix=True):
"""
Write environment variables to a file.
:param env_variables: environment variables
:param destination_path: destination path of a file where the
environment variables will be stored. t... | c242ff4d6956922b2ccceecaef5b95640116e75a | 707,231 |
def CanEditHotlist(effective_ids, hotlist):
"""Return True if a user is editor(add/remove issues and change rankings)."""
return any([user_id in (hotlist.owner_ids + hotlist.editor_ids)
for user_id in effective_ids]) | dc29c74e2628930faffb12b6772046564ffb8218 | 707,232 |
def dice_counts(dice):
"""Make a dictionary of how many of each value are in the dice """
return {x: dice.count(x) for x in range(1, 7)} | 427703283b5c0cb621e25f16a1c1f2436642fa9f | 707,233 |
def events(*_events):
""" A class decorator. Adds auxiliary methods for callback based event
notification of multiple watchers.
"""
def add_events(cls):
# Maintain total event list of both inherited events and events added
# using nested decorations.
try:
all_events = cl... | 601f7d55ff4d05dd0aca552213dcd911f15c91b6 | 707,235 |
from typing import List
def dict_to_kvp(dictionary: dict) -> List[tuple]:
"""
Converts a dictionary to a list of tuples where each tuple has the key and value
of each dictionary item
:param dictionary: Dictionary to convert
:return: List of Key-Value Pairs
"""
return [(k, v) for k, v in d... | 2b856ebb218884a4975d316bebe27546070f2083 | 707,236 |
def convert_and_remove_punctuation(text):
"""
remove punctuation that are not allowed, e.g. / \
convert Chinese punctuation into English punctuation, e.g. from「 to "
"""
# removal
text = text.replace("\\", "")
text = text.replace("\\", "")
text = text.replace("[", "")
text = text.re... | 2de1f930ca76da7fec3467469f98b0e0858e54a0 | 707,237 |
import re
def _get_ip_from_response(response):
"""
Filter ipv4 addresses from string.
Parameters
----------
response: str
String with ipv4 addresses.
Returns
-------
list: list with ip4 addresses.
"""
ip = re.findall(r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)... | ac36a3b729b0ce4ba13a6db550a71276319cbd70 | 707,238 |
def EscapeShellArgument(s):
"""Quotes an argument so that it will be interpreted literally by a POSIX
shell. Taken from
http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python
"""
return "'" + s.replace("'", "'\\''") + "'" | 132a3b1bb8a0e7b3c92ac15e2d68337eeef19042 | 707,239 |
def read_csv_to_data(path: str, delimiter: str = ",", headers: list = []):
"""A zero-dependancy helper method to read a csv file
Given the path to a csv file, read data row-wise. This data may be later converted to a dict of lists if needed (column-wise).
Args:
path (str): Path to csv file
... | f60e163e770680efd1f8944becd79a0dd7ceaa08 | 707,240 |
import os
def current_user():
"""Returns the value of the USER environment variable"""
return os.environ['USER'] | 75d588d801a5afcd2037a05c7dc5e990532eb114 | 707,241 |
def approx_match_dictionary():
"""Maps abbreviations to the part of the expanded form that is common beween all forms of the word"""
k=["%","bls","gr","hv","hæstv","kl","klst","km","kr","málsl",\
"málsgr","mgr","millj","nr","tölul","umr","þm","þskj","þús"]
v=['prósent','blaðsíð',\
'grein','hát... | 021c7de862b2559b55051bc7267113d77132e195 | 707,242 |
def getInputShape(model):
"""
Gets the shape when there is a single input.
Return:
Numeric dimensions, omits dimensions that have no value. eg batch
size.
"""
s = []
for dim in model.input.shape:
if dim.value:
s.append(dim.value)
... | 628f61a995784b9be79816a5bbcde2f8204640be | 707,243 |
def kewley_agn_oi(log_oi_ha):
"""Seyfert/LINER classification line for log([OI]/Ha)."""
return 1.18 * log_oi_ha + 1.30 | 5e6b71742bec307ad609d855cced80ae08e5c35c | 707,244 |
from typing import Tuple
import os
def get_load_average() -> Tuple[float, float, float]:
"""Get load average"""
return os.getloadavg() | 48942b9dbd5c1c38e0c9e13566521d96e980b7a7 | 707,245 |
def permissions_vsr(func):
"""
:param func:
:return:
"""
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper | a7e01f7711cab6bc46c004c4d062930c2a656eee | 707,246 |
def multiply_str(char, times):
"""
Return multiplied character in string
"""
return char * times | cc69f0e16cba1b8c256301567905e861c05291ea | 707,247 |
def calories_per_item(hundr, weight, number_cookies, output_type):
"""
>>> calories_per_item(430, 0.3, 20, 0)
'One item has 64.5 kcal.'
>>> calories_per_item(430, 0.3, 20, 1)
'One item has 64.5 Calories.'
>>> calories_per_item(1, 1000, 10, 1)
'One item has 1000.0 Calories.'
>>> calories_... | 9ca16eee8aa8a81424aeaa30f696fb5bec5e3956 | 707,248 |
def solar_true_longitude(solar_geometric_mean_longitude, solar_equation_of_center):
"""Returns the Solar True Longitude with Solar Geometric Mean Longitude,
solar_geometric_mean_longitude, and Solar Equation of Center,
solar_equation_of_center."""
solar_true_longitude = solar_geometric_mean_longitude +... | a335bb82002846eb2bc2106675c13e9f3ee28900 | 707,249 |
import stat
import functools
import operator
def flags(flags: int, modstring: str) -> int:
""" Modifies the stat flags according to *modstring*, mirroring the syntax for POSIX `chmod`. """
mapping = {
'r': (stat.S_IRUSR, stat.S_IRGRP, stat.S_IROTH),
'w': (stat.S_IWUSR, stat.S_IWGRP, stat.S_IWOTH),
'x... | 9acfeb4d9b90a12d2308c0ec992cfbb47f11000c | 707,250 |
def maximumToys(prices, k):
"""Problem solution."""
prices.sort()
c = 0
for toy in prices:
if toy > k:
return c
else:
k -= toy
c += 1
return c | 0ce709ff7b106b5379217cb6b7f1f481d27c94e7 | 707,251 |
def findUsername(data):
"""Find a username in a Element
Args:
data (xml.etree.ElementTree.Element): XML from PMS as a Element
Returns:
username or None
"""
elem = data.find('User')
if elem is not None:
return elem.attrib.get('title')
return None | f7b6bb816b9eeeca7e865582935a157cdf276928 | 707,252 |
def fix_empty_strings(tweet_dic):
"""空文字列を None に置換する"""
def fix_media_info(media_dic):
for k in ['title', 'description']:
if media_dic.get('additional_media_info', {}).get(k) == '':
media_dic['additional_media_info'][k] = None
return media_dic
for m in tweet_dic... | 436daaeb9b96b60867d27812ed7388892ab79b1a | 707,253 |
def read_data():
"""Reads in the data from (currently) only the development file
and returns this as a list. Pops the last element, because it is empty."""
with open('../PMB/parsing/layer_data/4.0.0/en/gold/dev.conll') as file:
data = file.read()
data = data.split('\n\n')
data.pop(-... | da75e237bbc7b2168cd5af76eefaf389b29d4b30 | 707,254 |
def dice_coefficient(x, target):
"""
Dice Loss: 1 - 2 * (intersection(A, B) / (A^2 + B^2))
:param x:
:param target:
:return:
"""
eps = 1e-5
n_inst = x.size(0)
x = x.reshape(n_inst, -1)
target = target.reshape(n_inst, -1)
intersection = (x * target).sum(dim=1)
union = (x *... | c73cd86ed11bf89d94fb84db16186d6ace39d814 | 707,256 |
import pydoc
def locate(name):
"""
Locate the object for the given name
"""
obj = pydoc.locate(name)
if not obj:
obj = globals().get(name, None)
return obj | 24f31b241ffcbd2e983889f209bff9a1ff8b1fc3 | 707,257 |
import argparse
def parse_args():
"""parse args for binlog2sql"""
parser = argparse.ArgumentParser(description='Parse MySQL binlog to SQL you want', add_help=False)
connect_setting = parser.add_argument_group('connect setting')
connect_setting.add_argument('-h', '--host', dest='host', type=str,
... | e6ef917b97ea15097b30684a1069ea1c74b16064 | 707,258 |
import requests
def get_quote_data(ticker):
"""Inputs: @ticker
Returns a dictionary containing over 70 elements corresponding to the
input ticker, including company name, book value, moving average data,
pre-market / post-market price (when applicable), and more."""
site = "https://query1.finance.... | a23d7e091547ceca3c66f0ae90e84ea9f89d4e1c | 707,259 |
import torch
def _old_extract_roles(x, roles):
"""
x is [N, B, R, *shape]
roles is [N, B]
"""
N, B, R, *shape = x.shape
assert roles.shape == (N, B)
parts = []
for n in range(N):
parts.append(x[n:n+1, range(B), roles[n]])
return torch.cat(parts, dim=0) | 07a7be138558baa28ab1a10e2be2c7f17501ae96 | 707,260 |
def is_valid_table_name(cur, table_name):
"""
Checks whether a name is for a table in the database.
Note: Copied from utils.database for use in testing, to avoid
a circular dependency between tests and implementation.
Args:
cur: sqlite3 database cursor object
table_name (str): name t... | f1efc66220baa215a73f374da19842ab38c619be | 707,261 |
import re
def sub_repeatedly(pattern, repl, term):
"""apply sub() repeatedly until no change"""
while True:
new_term = re.sub(pattern, repl, term)
if new_term == term:
return term
term = new_term | e57c648fb057f81e35e0fc2d2dc57edd0b400baf | 707,262 |
def create_lexicon(word_tags):
"""
Create a lexicon in the right format for nltk.CFG.fromString() from
a list with tuples with words and their tag.
"""
# dictionary to filter the double tags
word_dict = {}
for word, tag in word_tags:
if tag not in word_dict:
word_dict[ta... | 3a91671d559f5924ec9326520db6e11a1672fee4 | 707,263 |
import ipaddress
def ip_only(value):
"""
Returns only the IP address string of the value provided. The value could be either an IP address,
and IP network or and IP interface as defined by the ipaddress module.
Parameters
----------
value : str
The value to use
Returns
-----... | 149b202969c0ccb4e0c5e55417ce0231f1b5fc11 | 707,265 |
def area_triangle(base, height):
"""
"""
return (base * height) / 2.0 | 474e1a090dc7af9d68eaab35e6b04e5e165b6777 | 707,267 |
def get_table_6():
"""表 6 蓄熱の採用の可否
Args:
Returns:
list: 表 6 蓄熱の採用の可否
"""
table_6 = [
('不可', '不可', '可', '可', '可'),
('不可', '不可', '可', '可', '可'),
('不可', '不可', '可', '可', '可'),
('不可', '不可', '可', '可', '可'),
('不可', '不可', '可', '可', '可'),
('不可', '不可',... | 4ecd4526ed9ce67b7a5d22b67dd804059807e94d | 707,268 |
import random
def is_prime(number, num_trials=200):
"""Determines whether a number is prime.
Runs the Miller-Rabin probabilistic primality test many times on the given number.
Args:
number (int): Number to perform primality test on.
num_trials (int): Number of times to perform the Miller... | 78478437c08bcbd5e4c690466e4fe51bb4fad5ce | 707,269 |
from pathlib import Path
from typing import List
import os
def get_proj_libdirs(proj_dir: Path) -> List[str]:
"""
This function finds the library directories
"""
proj_libdir = os.environ.get("PROJ_LIBDIR")
libdirs = []
if proj_libdir is None:
libdir_search_paths = (proj_dir / "lib", pr... | efeacd08940c1f8706cd86aa0c5da50b498608e6 | 707,270 |
def str2num(s):
"""Convert string to int or float number.
Parameters
----------
s : string
String representing a number.
Returns
-------
Number (int or float)
Raises
------
TypeError
If `s` is not a string.
ValueError
If the string does ... | 5dfaed567a66fc7d3ee46cbb70d9c408d38fcbfe | 707,271 |
import os
def get_html_templates_path():
"""
Return path to ABlog templates folder.
"""
pkgdir = os.path.abspath(os.path.dirname(__file__))
return os.path.join(pkgdir, "templates") | e72caf4a2558298ec909aff04bfde381abba256f | 707,272 |
from typing import OrderedDict
import inspect
def _get_new_args_dict(func, args, kwargs):
"""Build one dict from args, kwargs and function default args
The function signature is used to build one joint dict from args and kwargs and
additional from the default arguments found in the function signature. Th... | ad7553e7b778b8f7b499217c7ee4ad7328958809 | 707,273 |
def find_dead_blocks(func, cfg):
"""Find all immediate dead blocks"""
return [block for block in cfg if not cfg.predecessors(block)
if block != func.startblock] | 3f72e0a573b1ef617511f2b9ec3d2e30c7ba6554 | 707,274 |
def num_list(to_parse):
"""
Creates list from its string representation
Arguments:
to_parse {string} -- String representation of list, can include 'None' or internal lists, represented by separation with '#'
Returns:
list[int] -- List represented in to_parse
"""
if len(... | b444554e37434b5ae42ebc913bcc0f9b99c65ce9 | 707,275 |
def read_user(str):
""" str -> dict """
pieces = str.split()
return {
'first': pieces[0],
'last': pieces[1],
'username': pieces[5],
'custID': pieces[3],
'password': pieces[7],
'rank': 0,
'total': 0
} | fcb24a2b791f0df8f40ea4080cdabe83d51fe068 | 707,276 |
from typing import Union
from typing import List
import shlex
import subprocess
def _run(cmd: Union[str, List[str]]) -> List[str]:
"""Run a 'cmd', returning stdout as a list of strings."""
cmd_list = shlex.split(cmd) if type(cmd) == str else cmd
result = subprocess.run(cmd_list, capture_output=True)
... | 74fc47f531e8eef9f77b80798f0b5505b57968da | 707,277 |
def compFirstFivePowOf2(iset={0, 1, 2, 3, 4}):
"""
task 0.5.6
a comprehension over the given set whose value is the set consisting
of the first five powers of two, starting with 2**0
"""
return {2**x for x in iset} | a7b04ab6b127ef5ee7fdd3598b1569e171fd009e | 707,278 |
def __pairwise__(iterable):
""" Converts a list of elements in a list of pairs like:
list -> (list[0], list[1]), (list[2], list[3]), (list[4], list[5]), ...
:param iterable: Input list.
:return: List of pairs of the given list elements.
"""
a = iter(iterable)
return zip(a, a) | 59eae23e0e6f9ccba528f9632caf77fe28698c5b | 707,279 |
def read_ground_stations_extended(filename_ground_stations_extended):
"""
Reads ground stations from the input file.
:param filename_ground_stations_extended: Filename of ground stations basic (typically /path/to/ground_stations.txt)
:return: List of ground stations
"""
ground_stations_extende... | 2492dc8d5c55f124696aafbec11d74e609c3f397 | 707,281 |
import uuid
def shortPrescID():
"""Create R2 (short format) Prescription ID
Build the prescription ID and add the required checkdigit.
Checkdigit is selected from the PRESCRIPTION_CHECKDIGIT_VALUES constant
"""
_PRESC_CHECKDIGIT_VALUES = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ+'
hexString = str(... | db491d3fe299adfbcd6f202eb46bc4669f829613 | 707,282 |
import ast
def get_module_docstring(path):
"""get a .py file docstring, without actually executing the file"""
with open(path) as f:
return ast.get_docstring(ast.parse(f.read())) | e253372bfb6f65907a5461332d14c414c2370c66 | 707,283 |
def transform(f, a, b, c, d):
"""
Transform a given function linearly.
If f(t) is the original function, and a, b, c, and d are the parameters in
order, then the return value is the function
F(t) = af(cx + d) + b
"""
return lambda x: a * f(c * x + d) + b | a47b3f4f3dc1e3ed5ddb6155bcd67b8297c298ed | 707,284 |
import logging
def log_command(func):
"""
Logging decorator for logging bot commands and info
"""
def log_command(*args, **kwargs):
slack, command, event = args
user = slack.user_info(event["user"])
log_line = 'USER: %s | CHANNEL ID: %s | COMMAND: %s | TEXT: %s'
command... | 8ab4f36ff6c01a3799061f532d0c25ec04d725e8 | 707,285 |
import os
def expand_home_folder(path):
"""Checks if path starts with ~ and expands it to the actual
home folder."""
if path.startswith("~"):
return os.environ.get('HOME') + path[1:]
return path | 3746859cc16b77dcfd02c675db81bfe4a195a85f | 707,286 |
def centered_mols(self, labels, return_trans=False):
"""
Return the molecules translated at the origin with a corresponding cell
Parameters
----------
labels : int or list of ints
The labels of the atoms to select
print_centro : bool
Print the translation vector which was detect... | 858fd2b43f0ac9eaca3db94108f9bec0dbf305c7 | 707,287 |
import json
def load_config(path='config.json'):
"""
Loads configruation from config.json file.
Returns station mac address, interval, and units for data request
"""
# Open config JSON
with open(path) as f:
# Load JSON file to dictionary
config = json.load(f)
... | 5522f023ed3293149613dcc2dc007e34d50f3fa8 | 707,288 |
import torch
def log_px_z(pred_logits, outcome):
"""
Returns Bernoulli log probability.
:param pred_logits: logits for outcome 1
:param outcome: datapoint
:return: log Bernoulli probability of outcome given logits in pred_logits
"""
pred = pred_logits.view(pred_logits.size(0), -1)
y ... | 6369d893cc9bfe5c3f642f819511798d01ae3ae9 | 707,289 |
import functools
def partial_at(func, indices, *args):
"""Partial function application for arguments at given indices."""
@functools.wraps(func)
def wrapper(*fargs, **fkwargs):
nargs = len(args) + len(fargs)
iargs = iter(args)
ifargs = iter(fargs)
posargs = (next((ifargs,... | 1b45e0bd8baea869d80c6b5963c6063f6b8fbdd4 | 707,290 |
def augment_features(data, feature_augmentation):
"""
Augment features for a given data matrix.
:param data: Data matrix.
:param feature_augmentation: Function applied to augment the features.
:return: Augmented data matrix.
"""
if data is not None and feature_augmentation is not None:
... | 687a7ff2a4b61131f5d95e1f7d6eb77d75bd6f06 | 707,291 |
def copy_keys_except(dic, *keys):
"""Return a copy of the dict without the specified items.
"""
ret = dic.copy()
for key in keys:
try:
del ret[key]
except KeyError:
pass
return ret | b1e57db9dbacbc2a7c502c36082f40598a0f4b90 | 707,292 |
import random
import math
def get_params(img, scale, ratio):
"""Get parameters for ``crop`` for a random sized crop.
Args:
img (PIL Image): Image to be cropped.
scale (tuple): range of size of the origin size cropped
ratio (tuple): range of aspect ratio of the origin aspect ratio crop... | 80838328fc9383731e1a853c8dc572228d1a4567 | 707,293 |
def generate_html_from_module(module):
"""
Extracts a module documentations from a module object into a HTML string
uses a pre-written builtins list in order to exclude built in functions
:param module: Module object type to extract documentation from
:return: String representation of an HTML file
... | 3e59931f3716dd3c50dfdda3ba17807b62f04c14 | 707,294 |
def getlineno(frame):
"""Get the line number from a frame object, allowing for optimization."""
# FrameType.f_lineno is now a descriptor that grovels co_lnotab
return frame.f_lineno | b8c8d6fb3ebb8784d10250a42526b31e185e9b7a | 707,295 |
def format_len(x):
"""
>>> format_len('abc')
3
>>> format_len(('(', ('(', 'def', ')'), 'yz', ')'))
11
"""
if not isinstance(x, (list, tuple)): return len(x)
if len(x) > 3: sep_len = 2 * (len(x) - 3)
else: sep_len = 0
return sum(map(format_len, x)) + sep_len | 723afb58bfed0cfb7fbd25a12b86b257bf8b40df | 707,296 |
def _uid_or_str(node_or_entity):
""" Helper function to support the transition from `Entitie`s to `Node`s.
"""
return (
node_or_entity.uid
if hasattr(node_or_entity, "uid")
else str(node_or_entity)
) | 82f5747e8c73e1c167d351e1926239f17ea37b98 | 707,297 |
def answer(panel_array):
""" Returns the maximum product of positive and (odd) negative numbers."""
print("panel_array=", panel_array)
# Edge case I: no panels :]
if (len(panel_array) == 0):
return str(0)
# Get zero panels.
zero_panels = list(filter(lambda x: x == 0 , panel_arra... | 7169fba8dcf6c0932722dcbc606d6d60fdaf3ed1 | 707,298 |
import subprocess
def exec_command_rc(*cmdargs, **kwargs):
"""
Return the exit code of the command specified by the passed positional arguments, optionally configured by the
passed keyword arguments.
Parameters
----------
cmdargs : list
Variadic list whose:
1. Mandatory first ... | bfe4f5bbdcbed6cfc3c8f52abffe2be7107fd091 | 707,299 |
def readCoords(f):
"""Read XYZ file and return as MRChem JSON friendly string."""
with open(f) as file:
return '\n'.join([line.strip() for line in file.readlines()[2:]]) | 0cf1a9d07b4b3fe1836ce5c8a308ff67b5fe4c70 | 707,300 |
def get_or_create(session, model, **kwargs):
"""
Creates and returns an instance of the model with given kwargs,
if it does not yet exist. Otherwise, get instance and return.
Parameters:
session: Current database session
model: The Class of the database model
**kw... | 4d3e4f0da5ca61789171db5d8d16a5fa06e975cc | 707,301 |
import os
def get_environ_list(name, default=None):
"""Return the split colon-delimited list from an environment variable.
Returns an empty list if the variable didn't exist.
"""
packed = os.environ.get(name)
if packed is not None:
return packed.split(':')
elif default is not None:
... | 3e59962558b127790e456a79edf6175d1c3f7bbe | 707,302 |
def reverse_complement(sequence):
""" Return reverse complement of a sequence. """
complement_bases = {
'g':'c', 'c':'g', 'a':'t', 't':'a', 'n':'n',
'G':'C', 'C':'G', 'A':'T', 'T':'A', 'N':'N', "-":"-",
"R":"Y", "Y":"R", "S":"W", "W":"S", "K":"M", "M":"K",
"B":"V", "V":"B", "D": ... | d28e520a9159cb4812079b4a7a5f2f6eb5723403 | 707,303 |
def clean_acl(name, value):
"""
Returns a cleaned ACL header value, validating that it meets the formatting
requirements for standard Swift ACL strings.
The ACL format is::
[item[,item...]]
Each item can be a group name to give access to or a referrer designation
to grant or deny base... | 1cceb2af22d2f5bbf223a0eb381b4c6643d76f0e | 707,305 |
def soup_extract_enzymelinks(tabletag):
"""Extract all URLs for enzyme families from first table."""
return {link.string: link['href']
for link in tabletag.find_all("a", href=True)} | 7baabd98042ab59feb5d8527c18fe9fa4b6a50af | 707,306 |
def custom_field_sum(issues, custom_field):
"""Sums custom field values together.
Args:
issues: List The issue list from the JQL query
custom_field: String The custom field to sum.
Returns:
Integer of the sum of all the found values of the custom_field.
"""
... | 32c1cce310c06f81036ee79d70a8d4bbe28c8417 | 707,307 |
def build_target_areas(entry):
"""Cleanup the raw target areas description string"""
target_areas = []
areas = str(entry['cap:areaDesc']).split(';')
for area in areas:
target_areas.append(area.strip())
return target_areas | 48e76a5c1ed42aed696d441c71799b47f9193b29 | 707,308 |
import pathlib
def list_files(directory):
"""Returns all files in a given directory
"""
return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')] | a8c5fea794198c17c2aff41a1a07009984a8e61f | 707,309 |
from typing import Union
def score_normalization(extracted_score: Union[str, None]):
"""
Sofa score normalization.
If available, returns the integer value of the SOFA score.
"""
score_range = list(range(0, 30))
if (extracted_score is not None) and (int(extracted_score) in score_range):
... | 74501e9351296037ecc90ae647155e3c6b76ae01 | 707,310 |
def format_dev_sub_dev_id(pciIdPair):
"""
pciIdPair (int pci device id, int pci sub device id or None)
"""
if pciIdPair[1] is None:
return "(0x%08X, None)" % pciIdPair[0]
return "(0x%08X, 0x%08X)" % pciIdPair | fded71eee57f4fac60175bfb015845bf1eba58f7 | 707,311 |
def polynom_prmzt(x, t, order):
"""
Polynomial (deterministic) parameterization of fast variables (Y).
NB: Only valid for system settings of Wilks'2005.
Note: In order to observe an improvement in DA performance w
higher orders, the EnKF must be reasonably tuned with
There is very ... | 80d3f9563c5f8a04a65de7d2d22f5d49d35c71fe | 707,312 |
import errno
import os
def pid_exists(pid):
"""Check whether pid exists in the current process table."""
if pid < 0:
return False
try:
os.kill(pid, 0)
except OSError as e:
return e.errno == errno.EPERM
else:
return True | 0ebefcc958e629aac6d06e6d79d8aaa1acf7607b | 707,313 |
def clap_convert(txt):
"""convert string of clap values on medium to actualy number
Args:
txt (str): claps values
Returns:
number on claps (int)
"""
# Medium annotation
if txt[-1] == "K":
output = int(float(txt[:-1]) * 1000)
return output
else:
return int(txt) | 253e0e2be4f37f1994637bbfc80edfc5d72bc4e5 | 707,314 |
import io
def write_phase1_capsummary(inst, isStringIO=True):
"""
Write out a multiweek summary of capacity, demand, understaffing.
:param inst: Model instance
:param isStringIO: True (default) to return StringIO object, False to return string
:return: capacity summary as StringIO object or a str... | 6d6e7d083693b74ea27e7f10cec4899735f32541 | 707,315 |
def project_disk_sed(bulge_sed, disk_sed):
"""Project the disk SED onto the space where it is bluer
For the majority of observed galaxies, it appears that
the difference between the bulge and the disk SEDs is
roughly monotonic, making the disk bluer.
This projection operator projects colors that a... | 5faf8f7d8d0d780f61586f7fae39f4ba04d3752d | 707,316 |
def revcomp(sequence):
"""
Find reverse complementary sequence
:param sequence: The RNA sequence in string form
:return: The reverse complement sequence in string form
"""
complement = {"A": "U", "U": "A", "C": "G", "G": "C", "N": "N"}
revcompseq = ""
sequence_list = list(sequence)
s... | c66b9ad967e612fa97f18bb2932e7eb4bbee8245 | 707,317 |
import time
def timesince():
"""
Get the amount of time since 00:00 on 1 January 1970,
the raw date before formatting it.
"""
return time.time() | 7e6944d74172947c4ac990c0fa993524ab865e18 | 707,318 |
def effective_area(true_energy, reco_energy, simu_area):
"""
Compute the effective area from a list of simulated energy and reconstructed energy
Parameters
----------
true_energy: 1d numpy array
reco_energy: 1d numpy array
simu_area: float - area on which events are simulated
Returns
... | b17efa390a1ae14bb8ecb959740bad8c391b1d2e | 707,320 |
def physical_cpu_mhz(vir_connection):
""" Get the CPU frequency in MHz using libvirt.
:param vir_connection: A libvirt connection object.
:type vir_connection: virConnect
:return: The CPU frequency in MHz.
:rtype: int
"""
return vir_connection.getInfo()[3] | f6a404a6d531940fbc762f493e90355e2fc78690 | 707,321 |
def addstream(bot, input):
"""Add a stream from the notify list"""
if not input.admin: return False
if not input.group(2): return
stream = input.group(2).lower()
if not stream in bot.config.streams:
bot.config.set_add('streams', stream)
bot.reply("Added {0} to stream list".format(stream))
else:
bot.reply("{... | 48465633ea58968efca31231eb5e1a47a537c979 | 707,322 |
def fmt(n):
"""format number with a space in front if it is single digit"""
if n < 10:
return " " + str(n)
else:
return str(n) | 976acc22cafd6d6bdb4e251853f49a114b63ec21 | 707,324 |
def get_handler_name(method: str, url_path: str, path_params: dict):
"""
Возвращает имя необходимого хендлера для рефлексифного вызова метода
:param method: Метод
:param url_path: URL
:param path_params: Параметры
:return:
"""
handler = url_path.replace('/', '_')
for key, value in pa... | e8060538a6bf73e6291ecbcbec14f11997a53507 | 707,325 |
import argparse
def parse_args():
"""Process input arguments"""
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('genotypes', metavar='G', help="Genotype table")
parser.add_argument(... | 276aed3028ae4d9614b7afae58ece670b8d2b806 | 707,326 |
def _always_run(*args, **kwargs) -> bool:
""" This returns False to indicate that the step is not already completed. """
return False | db31e0ac20ac0eef410fb051928308ce7414f5b6 | 707,327 |
def has_anonymous_link(node, auth):
"""check if the node is anonymous to the user
:param Node node: Node which the user wants to visit
:param str link: any view-only link in the current url
:return bool anonymous: Whether the node is anonymous to the user or not
"""
if auth.private_link:
... | c5941bce3f0110dfcd5e9bbb19bae0682c5e731f | 707,328 |
def is_successful(gsm_log):
"""
Success is defined as having converged to a transition state.
"""
with open(gsm_log) as f:
for line in reversed(f.readlines()):
if '-XTS-' in line or '-TS-' in line:
return True
return False | 9bab6837c8e6b818cceb025c5df9aed78074edcf | 707,329 |
def indicator(function_array_to_be_indicated, its_domain, barrier):
"""the indicator influences the function argument, not value. So here it iterates through x-domain and cuts any
values of function with an argument less than H"""
indicated = []
for index in range(len(its_domain)):
if its_domain... | 440f423b7b25b0d152bc691acd3d7dea6c785aed | 707,330 |
def _causes_name_clash(candidate, path_list, allowed_occurences=1):
"""Determine if candidate leads to a name clash.
Args:
candidate (tuple): Tuple with parts of a path.
path_list (list): List of pathlib.Paths.
allowed_occurences (int): How often a name can occur before we call it a cla... | 3b874e4ea6d8780483100e464e3325321c82689e | 707,331 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.