content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
async def twochars_async(arg):
"""
Formats a string of two characters into the format of (0X), useful for date formatting.
:param arg: The string
:return: String
"""
if len(arg) == 1:
return f"0{arg}"
return arg | 6312888e1b84c54ba85e712c774eaab3d46b9692 | 622,522 |
from typing import Union
from typing import Literal
import requests
def __ping_wayback_machine(url: str) -> Union[Literal[False], str]:
"""Check the Web Archive for an archived URL."""
r = requests.get(f"https://archive.org/wayback/available?url={url}").json()
if not r["archived_snapshots"]:
retur... | a7cbf74891206d723ae1747bf6a3071cc3b0968b | 622,523 |
from datetime import datetime
def str_to_datetime(s):
"""
Parse ISO datetime string and return a datetime object
:param str s: date/time string
:return: datetime object, None if not a valid date/time string
:rtype: datetime.datetime | None
"""
t = None
for fmt in ('%Y-%m-%dT%H:%M:%S.... | 0d250d19f88a74e1778dfc052e9638a15c5635b1 | 622,526 |
def get_lsb (string, n):
"""
Get LSB with lenght=n of string
:param string: string
:param n: integer
:returns: string
"""
return str(string[-n:]) | 84ae5d3ebc9e9983b4083fe2c97c61693f32c43c | 622,528 |
def singleChoiceWithSubParams(parameters, name, type_converter = str):
""" single choice with sub parameters value and chosen subparameters. Returns -1 and None if no value was chosen.
:param parameters: the parameters tree.
:param name: the name of the parameter.
:param type_converter: function to conv... | be9a990510bf64b4146f29270cbc077ec4911206 | 622,531 |
def _LowercaseDict(d):
"""Returns a copy of `d` with both key and values lowercased.
Args:
d: dict to lowercase (e.g. {'A': 'BcD'}).
Returns:
A dict with both keys and values lowercased (e.g.: {'a': 'bcd'}).
"""
return {k.lower(): d[k].lower() for k in d} | fb6e329f62d57cc7282bd4ea46803ce6e612d958 | 622,537 |
def load_vocab(filename):
"""Loads vocab from a file
Args:
filename: (string) the format of the file must be one word per line.
Returns:
d: dict[word] = index
"""
# try:
d = dict()
with open(filename) as f:
for idx, word in enumerate(f):
word = word.str... | 31a55c752113ef5223d56e893e0ef12f68074acc | 622,538 |
def HasValue(entity, property_name):
"""Returns whether `entity` has a property value with the provided name."""
return property_name in entity._values # pylint: disable=protected-access | 7397b0342a051f7c96eb4f606bb02ea2ff4d523c | 622,539 |
def default_layout(fig, n):
"""Setup a default layout for given number of axes.
Args:
fig: matplotlib figure
n: Number of axes required
Returns:
List of Axes
Raises:
ValueError: When no ax axes or > 9*9 are required. When no figure is given.
"""
if fig is None:
... | c60af1f483e8951b183be5c447630543a2caa060 | 622,544 |
import sqlite3
def check_priv(dbName, uid):
"""
checks the database to see if the user has the title of privileged.
Parameters:
dbName: String. Name of the database, derived from terminal.py
uid: 4 character string. Unique ID of the user, used for loads the things in the program.
Returns:
check: Boole... | c2856ae8ad201a769efde159f7a4f29c39514fe7 | 622,545 |
def captureStandardization(df, columns=None):
"""A function factory that creates a function for standardizing all columns
in df with each columns mean and standard deviation."""
if columns is None:
columns = df.columns
stdParams = {}
for c in columns:
mu = df[c].mean()
sigma2... | 8d873aea0edc9d0e0d6fdec01c82005f5cb039d2 | 622,547 |
def _token_str(token):
"""Shorten token so we do not leak sensitive info into the logs"""
if len(token) < 10:
# for some reason too short to reveal even a part of it
return "???TOOSHORT"
return token[:3] + '...' | 7f3282b5cd9f176f87cbbdc15da921991ba6f69c | 622,551 |
def get_requested_grants(settings):
"""Retrieve any valid requested_grants from dict settings
:param settings: dictionary which may contain key, requested_grants,
with comma delimited list of roles to grant.
:returns: list of roles to grant
"""
if ('requested_grants' in setting... | 4a61e0594b1c05a3334399071e8d4ec7ee78d29f | 622,558 |
def parse_input(input_data):
"""
Returns an array of unique cities and a dictionary of the distances between them
Each line of the input data must be in the format: City1 to City2 = 123
"""
lines = input_data.splitlines()
cities_arr = []
cities_dict = {}
distances = {}
for line in li... | f3713e2c1012f3418cbc298e1af1b24f644432d7 | 622,562 |
import math
def Log_Nash_Sutcliffe(SimulatedStreamFlow, ObservedStreamFlow):
"""
(SimulatedStreamFlow, ObservedStreamFlow)
Logarithmic Nash-Sutcliffe model efficiency coefficient
"""
x = SimulatedStreamFlow
y = ObservedStreamFlow
A = 0.0 # dominator
B = 0.0 # deminator
tot = 0.0
... | b4220b4849f53027ee63c046c08db069e8d3c563 | 622,563 |
def get_shared_vocab(vocab1, vocab2):
"""Return intersection of two vocabs."""
shared_words = set(word for word in vocab1 if word in vocab2)
return {word: idx for idx, word in enumerate(shared_words)} | f909a86c4911cdfca7221f14299bd1e5ac887395 | 622,569 |
def CommaCode(inputList):
"""Takes a list value as an argument and returns \
a string with all the items separated by a comma \
and a space, with and inserted before the last item."""
inputList[-1] = 'and ' + str(inputList[-1])
return ", ".join(inputList) | 0d17e28b1742c12a4518eefc2d80719b9f933724 | 622,571 |
def normalize_url(url):
"""Make sure the url is in correct form."""
result = url
if not result.endswith("/"):
result = result + "/"
return result | d7a7559f0f096271384eb236065d259931bc476d | 622,574 |
def get_dot_indices(face_index_from_1):
"""Get indices (from 0 through 20) corresponding to dots on the given face (from 1 through 6)."""
if face_index_from_1 == 1:
return [0]
elif face_index_from_1 == 2:
return [1,2]
elif face_index_from_1 == 3:
return [3,4,5]
elif face_inde... | 76fe27dc0c9bcaa8f4d79c6ff4f6b5a0e26a3914 | 622,577 |
def dict_factory(cursor, row):
"""
Replace the row_factory result constructor with a dictionary constructor.
Args:
cursor: (object) the sqlite3 database cursor object.
row: (list) a result list.
Returns:
d: (dictionary) sqlite3 results dictionary.
Raises:
"""
d ... | a0ad657d27cad4ddec95e57e7a04f94803357dc9 | 622,578 |
def _str2h5attr(data: str) -> str:
"""Add a str prefix to distinguish an actual string from the other types saved as strings"""
return f"str {data}" | 6014d2970eba3250f10505cb0c9d8aeb5f877027 | 622,581 |
def program_entry(program):
"""
Template tag {% program_entry program %} is used to display a single
program.
Arguments
---------
program: Program object
Returns
-------
A context which maps the program object to program.
"""
return {'program': program} | e43075dfbe3bde21e2b5f90d317ff09f4d7cdc76 | 622,585 |
def parametrized(dec):
"""This decorator can be used to create other decorators that accept arguments"""
def layer(*args, **kwargs):
def repl(f):
return dec(f, *args, **kwargs)
return repl
return layer | 151b1d49af56b1a91981ec0f6684489a46d16d7a | 622,589 |
def changeset_revision_reviewed_by_user( user, repository, changeset_revision ):
"""Determine if the current changeset revision has been reviewed by the current user."""
for review in repository.reviews:
if review.changeset_revision == changeset_revision and review.user == user:
return True
... | 397cb1c58851ced4c2a9d42525084f295fcb4744 | 622,590 |
def startswith_in_list(src, items):
"""
Comparaison de type "startswith" avec une liste de 'match' possibles
"""
for k in items:
if src.startswith(k):
return k
return False | 5c68b1c6362c60708cbe86ec33d15fa4ecc4e330 | 622,591 |
def get_first_non_none_value(*configs, key, default=None, callback=None):
"""Get the first non-None value for a key from a list of dictionaries.
This function allows to prioritize information from many configurations by changing
the order of the inputs while also providing a default.
Examples
----... | 14c4a20bc7a8f475d77df1c087c82b35d76fc6ab | 622,595 |
def get_item(dictionary, key_id):
"""Returns value in dictionary from the key_id.
Used when you want to get a value from a dictionary key using a variable
:param dictionary: dict
:param key_id: string
:return: value in the dictionary[key_id]
How to use:
{{ mydict|get_item:i... | ad716220c33d727c2f1bc8e2216295763aba663b | 622,596 |
import logging
def create_logger(logger_name: str) -> logging.Logger:
"""Set up logging using the `logger_name`"""
logger = logging.getLogger(logger_name)
# Create console handler if not already present
if not logger.handlers:
ch = logging.StreamHandler()
formatter = logging.Formatte... | 3166f7e5cf041caf0ec2dc1d03c11ed2b93bc0c4 | 622,598 |
def select_type(pathways, stype):
"""Selects all pathways of a given type
Parameters
----------
pathways : list
List of pathways to be analyzed
stype : str
Type of the pathways to be selected.
Possible values are "REPH", "NONR".
"""
di = d... | 836dbcd9d9cff7e86a2af76b746111015d2e3dce | 622,599 |
def has_field(block, field_name):
""" Return whether the block has a field with the given name. """
return field_name in block.fields | 1d8068f01da08c2ce966e75172c624b6d16fc0e8 | 622,602 |
def get_scores(classProbabilities, trueLabels):
"""
Get scores of correct class
:param classProbabilities: list: list of arrays of prediction probabilities for each class
:param trueLabels: list: correct class labels
:return: list: scores for correct class
"""
return [p[l] for p, l in zip(cl... | 4d1ea3d85e8219f3a610d20924584506c3d71a95 | 622,604 |
def get_generic_field_dict(cve, field):
"""
Attempts to extract the dictionary associated to the field
from the provided cve.
If none is found, returns an empty dictionary.
Parameters
----------
cve : dict
The dictionary generated from the CVE json.
Returns
-------
dict... | 3ea9e01628af96354fc23fc387798f0c58fd0aed | 622,608 |
def fake_frames(seq_name, field_name, value_seq):
""" Make fake frames for multiframe testing
Parameters
----------
seq_name : str
name of sequence
field_name : str
name of field within sequence
value_seq : length N sequence
sequence of values
Returns
-------
... | fe8bd94834e29f91b034f066bb102dfbf0cc600b | 622,614 |
def _dms2dd(d, m, s, dir):
"""
convert lat/lon degrees/minutes/seconds into decimal degrees
"""
degrees = float(d) + (float(m) / 60) + (float(s) / 3600)
if dir in ['S', 'W']:
degrees = degrees * -1
return degrees | 388cfc4e4c11e592d92986a86d0e49424f36a43b | 622,616 |
def flatten_dict(d: dict):
"""Flattens dictionary with subdictionaries.
Arguments:
d {dict} -- Dict to flatten
Returns:
flattened {dict} -- Flattened dict
"""
def items():
for key, value in d.items():
if isinstance(value, dict):
for subkey, sub... | 9cab28f30459e1bc2cda67bd1c10dd78bc2d83ec | 622,617 |
def parse_content_type(content_type):
"""Cleans up content_type."""
if content_type:
return content_type.split(';')[0].strip().lower()
else:
return '' | 6ae0721ffbf4c1bbe3eedc85f3e13ec466576a4b | 622,620 |
def getSpan(array):
"""Return the span of `array`
span(array) = max array(s) - min array(s)
"""
return array.max() - array.min() | 887a7384b4ae377af8301ac8133b34198da9e549 | 622,624 |
def cropToAspectRatio(frame, size):
"""
Crop the frame to desired aspect ratio and then scales it down to desired size
Args:
frame (numpy.ndarray): Source frame that will be cropped
size (tuple): Desired frame size (width, height)
Returns:
numpy.ndarray: Cropped frame
"""
... | 3b2816d14156ffbd63dfc654c05b2967e567bf2e | 622,625 |
def get_env_variable_str(d: dict):
"""
Creates a list of all the environment variables, that are relevant for the message generator.
:param d: dict, usually the the environment variables of the OS (as provided by os.locals())
:return: [str], of the format "<variable name>: <variable value>"
"""
... | bdd1c8a416326e7d4f302122557223486f970764 | 622,628 |
def GetContainerArgs(name: str):
"""Returns the command/arguments to start a process in a container.
Args:
name: The container name.
Returns:
The list with the command and arguments.
"""
return [
"container.py",
"run",
"--cpurate",
"100",
"--ram",
"60000",
"... | a42d956b725f6278a0c00e079de22c94d0996969 | 622,629 |
def indent_lines(block,
num_tabs=1, expand_tabs=True, tab_size=4,
skip_first_line=False):
"""Return `block` indented with additional tabs on each line.
Parameters
==========
block : string
Block to indent after newlines
num_tabs : integer
Number of ... | bb0495d2eb9de26ac2f9aa9511ff1ef929c937e1 | 622,631 |
def applier(f):
"""Returns a function that applies `f` to a collection of inputs (or just one).
Useful to use in conjuction with :func:`dlt.util.compose`
Args:
f (function): Function to be applied.
Returns:
callable: A function that applies 'f' to collections
... | ee1039fcd46eac6653dc64ad759934d86cc04f20 | 622,632 |
import math
import random
def split_data(ids, train_ratio=0.8, validation_ratio=0.1, test_ratio=0.1):
"""Split list of sample IDs randomly with a given ratio for the training, validation and test set."""
# Check validity of ratio arguments
if train_ratio + validation_ratio + test_ratio != 1.0:
ra... | 42f498b31e2f33414e406627929c897bc86a3b90 | 622,633 |
def getSpan(W):
"""Return the span of W
sp(W) = max W(s) - min W(s)
"""
return W.max() - W.min() | 27368e700e986f8352a7c2dc65cc5ca59a3105f3 | 622,637 |
from io import StringIO
def run_command(control, cmd, ok_codes=None):
"""
Run a spack or git command and get output and error
"""
ok_codes = ok_codes or [0, 1]
res = StringIO()
err = StringIO()
control(*cmd, _out=res, _err=err, _ok_code=ok_codes)
return res.getvalue(), err.getvalue() | 0fc96682e1f937908bf90f11b61d5d214c43ef53 | 622,642 |
import re
def find_meta(meta, meta_file):
"""Extract __*meta*__ from `meta_file`."""
meta_match = re.search(r"^__{meta}__\s+=\s+['\"]([^'\"]*)['\"]".format(meta=meta), meta_file, re.M)
if meta_match:
return meta_match.group(1)
raise RuntimeError("Unable to find __{meta}__ string.".format(meta=... | e58372db8500e129bd4d7550fac015413ac7c42c | 622,654 |
def get_excluded_varaibles(all_features, excluded_features):
"""
Returns a list of feature names to be excluded from feature scaling
Parameters:
all_features: List of features returned from choose_featuers for clustering
excluded_features: List of features in all_features to be excluded from featur... | 9cf354c66406b5d14a18f9e9d40276a85f7ddcc7 | 622,659 |
import re
def is_coordinate(s):
"""Check if input is a coordinate."""
matches = re.search(
r'([+-]?([0-9]{1,2}):([0-9]{2})(:[0-9]{2})?\.?([0-9]+)?)', s)
return False if matches is None else True | 50b65374d6bbcf6461f473d1bc4c13301ff72700 | 622,665 |
import re
def binary_conversion(txt):
"""Convert binary txt to ascii string."""
if len(txt) % 8 > 0:
raise ValueError(f"txt length is not base 8. The value of txt: {txt}")
ascii_message = "".join([chr(int(byte, 2))
for byte in re.findall(r"\d{8}", txt)]
... | bb187099c297e8a307c9707f46eb710d24d6ed9c | 622,666 |
def HermiteP(n, x):
"""
Hermite polynomial of rank n Hn(x)
Parameters
----------
n: order of the LG beam
x: matrix of x
Returns
-------
Hermite polynomial
"""
if n == 0:
return 1
elif n == 1:
return 2 * x
else:
return 2 * x * HermiteP(n - 1, ... | bc3ef4aa5feaad3bdf3ae8bcc695c6f0c81070fa | 622,667 |
def parse_arxiv_url(url):
"""
examples is http://arxiv.org/abs/1512.08756v2
we want to extract the raw id and the version
"""
ix = url.rfind('/')
idversion = url[ix + 1:] # extract just the id (and the version)
parts = idversion.split('v')
assert len(parts) == 2, 'error parsing url ' + ... | 768f949914140954cc435101f7763e6b7c303bdf | 622,675 |
def format_go_time(dt):
"""Format datetime in Go's time.RFC3339Nano format which looks like
2018-10-04T15:08:53.229364634+03:00
If dt tzinfo is None, UTC will be used
"""
prefix = dt.strftime('%Y-%m-%dT%H:%M:%S')
nsec = dt.microsecond * 1000
tz = dt.strftime('%z') or '+0000'
return '{}.... | 4f399d946d6ef8a4bad203bedf832c080277a3a6 | 622,677 |
def GeBuildConfigAllBoards(ge_build_config):
"""Extract a list of board names from the GE Build Config.
Args:
ge_build_config: Dictionary containing the decoded GE configuration file.
Returns:
A list of board names as strings.
"""
return [b['name'] for b in ge_build_config['boards']] | a64cd6aac932f898fd38614a0914638b0f02612b | 622,684 |
def round_to_nearest(x):
"""Python 3 style round: round a float x to the nearest int, but
unlike the builtin Python 2.x round function:
- return an int, not a float
- do round-half-to-even, not round-half-away-from-zero.
We assume that x is finite and nonnegative; except wrong results
if ... | 88a3d4954ecc10526aad8e60924bd0b5ccd64773 | 622,687 |
import crypt
def check_hash(p,s,sha):
"""
Checking the password with given sha with crypt
"""
c_pass = crypt.crypt(p,s)
if c_pass == sha:
return 1
else:
return 0 | 76cf1e7fe31852ae28a2963414facebe44c8a7fe | 622,688 |
def count_increases_in_window(numbers, window_length=3):
"""Count number of times sum of the window with window_length increases."""
increases = 0
for index, _ in enumerate(numbers[:-window_length]):
prev_window = sum(numbers[index:index + window_length])
cur_window = sum(numbers[index + 1:i... | 2f61bf6350cdb927ea0870bbc9665c825e77ddc6 | 622,689 |
def _compare_ch_names(names1, names2, bads):
"""Return channel names of common and good channels."""
ch_names = [ch for ch in names1 if ch not in bads and ch in names2]
return ch_names | 42f078bbd85c1d956abce5c6f2bc7ab7416e4ab8 | 622,691 |
import hashlib
def sha256(hashable) -> str:
"""Use instead of the builtin hash() for repeatable values."""
if isinstance(hashable, str):
hashable = hashable.encode("utf-8")
return hashlib.sha256(hashable).hexdigest() | cabe79cb18c80085ef9f16ab2105e27aeceb1b7e | 622,698 |
def put_whitespace(in_str):
"""
Replace periods (.), underscores (_) and hyphens (-) in `in_str` with spaces
"""
return in_str.replace(".", " ").replace("-", " ").replace("_", " ") | 3191cadafb189fb3067fcb383d8a7456d74ce2f0 | 622,702 |
def split_instr(instr):
"""
Given an instruction of the form "name arg1, arg2, ...",
returns the pair ("name", "arg1, arg2, ...").
If the instruction has no arguments, the second element of
the pair is the empty string.
"""
result = instr.split(None, 1)
if len(result) == 1:
return result[0], ""
e... | 7bbc6ecf20c478ccce963be9f37fca0a330d3d80 | 622,703 |
import torch
def update_var(old_mean, old_var, old_count, new_mean, new_var, new_count):
"""Update mean and variance statistics based on a new batch of data.
Parameters
----------
old_mean : array_like
old_var : array_like
old_count : int
new_mean : array_like
new_var : array_like
... | 107727b96eddad12c70805bbb058b4d8bcd96101 | 622,706 |
import torch
def load_checkpoint(resume_path):
"""
Resume from saved checkpoints
:param resume_path: Checkpoint path to be resumed
"""
checkpoint = torch.load(resume_path)
epoch = checkpoint['epoch']
mnt_best = checkpoint['monitor_best']
# load architecture params from checkpoint.
... | 8a1659bd2441f198ed3cce41e83556a320a31272 | 622,707 |
def get_fields_from_fieldsets(fieldsets):
"""Get a list of all fields included in a fieldsets definition."""
fields = []
try:
for name, options in fieldsets:
fields.extend(options['fields'])
except (TypeError, KeyError):
raise ValueError('"fieldsets" must be an iterable of tw... | d69a6311eaee536ac3161fca4db05c2c50f03662 | 622,708 |
from typing import IO
from typing import Any
from typing import Optional
import struct
def read_bytes_as_value(f: IO[Any], fmt: str, nodata: Optional[Any] = None) -> Any:
"""Read bytes using a `struct` format string and return the unpacked data value.
Parameters
----------
f : IO[Any]
The IO ... | 4e80a46fafe0bbc845d369c66bf7f5962a010dae | 622,710 |
def readable_timedelta(days):
""" Display days in a human readable way
original function by Syed Marwan Jamal
Arguments:
- days : (int) amount of day to translate
Returns:
- : (str) human readable string with date
"""
number_of_weeks = days // 7
number_of_days = days % ... | ce91c00fe35255f8eb2e505cb8441df1f5aa979e | 622,712 |
def read_metadata(metadata_file):
"""
Function that returns a dictionary object from a KEY=VALUE lines file.
:param metadata_file: Filename with the KEY=VALUE pairs
:return: Dictionary object with key and value pairs
"""
if not metadata_file:
return {}
with open(metadata_file) as f:... | d25996c08cd35df5ec38140ba17d3949bc87e27d | 622,713 |
import sqlite3
def openDb(database_filepath):
"""Return opened database connection."""
database_connection = sqlite3.connect(database_filepath)
database_connection.row_factory = sqlite3.Row
return database_connection | 8c5a30ef8e8ca94d4beb437a584fd512ba56c8cc | 622,714 |
def select_nodeids(xmrs, iv=None, label=None, pred=None):
"""
Return the list of all nodeids whose respective [EP] has the
matching *iv* (intrinsic variable), *label*, or *pred* values. If
none match, return an empty list.
"""
def datamatch(nid):
ep = xmrs.ep(nid)
return ((iv is ... | a34ffacde47d80fd7ee0c315705620689cf54c0f | 622,715 |
def get_console_logging_level(verbose, quiet):
"""
Returns the logging level for the console based on the verbose and quiet
flags.
Logging levels can be found here:
https://docs.python.org/2/library/logging.html#logging-levels
logging.WARNING is 30 and the default console logging level. Each v... | 1b7cf58771e3400c157fae0b74bab7c1d7c2a2cc | 622,716 |
def validate_scale_count(value, _):
"""Validate the `scale_count` input."""
if value is not None and value < 3:
return 'need at least 3 scaling factors.' | a36bba3750676e61b8a7da31f9a14ffb7c777571 | 622,717 |
import math
def _geometric_mean(nums) -> float:
"""Return geometric mean of nums : n-root(a1 * a2 * ... * an)"""
exponent = 1 / len(nums)
product = math.prod(nums)
return product ** exponent | 7ff8718dd3cec0b30b42ad2a830252dd7ac123be | 622,719 |
from typing import Counter
def life(before):
"""
Takes as input a state of Conway's Game of Life, represented as an iterable
of ``(int, int)`` pairs giving the coordinates of living cells, and returns
a `set` of ``(int, int)`` pairs representing the next state
"""
before = set(before)
neig... | 79df7fbff7314588a141b550679b354616e077ae | 622,720 |
import re
import click
def click_validate_reposlug(ctx, param, value):
"""Validate reposlugs (Click callback)
:param ctx: Click context
:type ctx: class:`click.Context`
:param param: Click params
:type param: dict
:param value: reposlugs to validate
:type value: tuple
:return: val... | f7f7ed4405da69486c917854a2066827365c832f | 622,721 |
from typing import List
def linspace(start, end, num) -> List[int]:
"""Linear spaced points within a division. Like numpy.linspace"""
delta = (end - start) / (num - 1)
return [int(start + i*delta) for i in range(num)] | efa05a6f680530d277ccef803f350b272a65b47d | 622,731 |
def convert_data(datain):
"""converts the output of the ADC into a voltage
Arguments
----------
datain : list
A list of bytes (the raw output of the adc)
Returns
-------
float
a float indicating a voltage between 2.5v and -2.5v - This will
not be adjusted for PGA ga... | ae3bbb56f537e59d669df386cba5f1370968cb24 | 622,740 |
def calc_acc(ta, precip, tacc=274.16, **config):
"""
calculate accumulation when precip is below threshold
:param ta: grid of current temperature (K)
:param precip: grid of current precipitation (mm)
:param tacc: temperature threshold for accumlation (K)
:return: acc: grid of accumulation in cu... | 5f5474a801af90d50b9811a2eb45333c49c33147 | 622,743 |
def scroll_with_mousewheel(widget, target=None, modifier='Shift', apply_to_children=False):
"""scroll a widget with mouse wheel
Args:
widget: tkinter widget
target: scrollable tkinter widget, in case you need "widget" to catch mousewheel event and make another widget
to scroll, ... | d993586b7703b286f9a17406a1858c8e7f4c8507 | 622,746 |
def compute_etan(sch1, sch2, cos2phi, sin2phi):
"""Compute tangential ellipticity."""
return - (sch1 * cos2phi + sch2 * sin2phi) | 87c3a2831847604b88110b6c4c58aac2c73cce4d | 622,753 |
def prepare_project(project_manager, project_name="working_project"):
"""
* load working project if the project is exist.
* create working project if the project is not exist.
Parameters
----------
project_manager : ProjectManager
a ProjectManager instance
project_name : str
... | 0e564acff166117a388607c2357a9fb412a88d2f | 622,754 |
def clean_dollars(x):
"""
Used to clean up dollar fields of $ and commas
"""
if type(x) != float:
return x.replace('$','').replace(',','').replace('city','') | f31efc374aa24ab051efa69e61a273d15a62d62d | 622,756 |
def decode_parent(parent):
"""
Function used to decode encoded parent vector into a value for function eval.
Parameters
----------
parent : encoded parent vector
Returns
-------
evaluation of parent on f(x)
"""
sign = 1
if parent[0][0] < 0:
sign = -1
number... | 59f4e6b9d4efd26821a2b551dced2e5d8b67bcbb | 622,757 |
import math
def michalewicz(ind, m=10.):
"""Michalewicz function defined as:
$$ f(x) = - \sum_{i=1}^{n} \sin(x_i) \sin( \frac{i x_i^2}{\pi} )^(2*m)$$
with a search domain of $0 < x_i < \pi, 1 \leq i \leq n$.
"""
return - sum(( math.sin(ind[i]) * (math.sin(((i+1.)*(ind[i] **2.))/math.pi))**(2.*m) f... | 74128ad086d81a0cf634a891de93827e1aad1960 | 622,758 |
def set_brackets(pathway):
"""
Function defines levels of all brackets in expression. The output will be used by function <check_brackets>
Example 1:
expression: A B (C,D)
levels: -1,-1,-1,-1,0,-1,-1,-1,0
Example 2:
expression: (A B (C,D))
levels: 0,-1,-1,-1,-1,1,-1,-1,... | d1931d5212ed88b3d5d8ca74cd617c23b114d9e6 | 622,763 |
def shared_branch_length_to_root(t, envs):
"""Returns the shared branch length for a single env from tips to root
t: phylogenetic tree relating sequences
envs: dict of {sequence:{env:count}} showing environmental abundance
Returns {env:shared_branch_length}
"""
working_t = t.copy()
res... | 86c3df9af08530706396483052284a735b6cc0fc | 622,764 |
def read_dist(file):
"""Read in a distribution
# Distribution of StackScore values at Harvard, 2015-06-24
#
#record_count stackscore fraction_of_records
13560805 1 0.98078307
76281 2 0.00551701
48500 3 0.00350775
24538 4 0.00177471
...... | 48c15ef05f15dfd81e0f5e17972039d1228ac529 | 622,770 |
import pathlib
def get_path(obj):
"""Convert a str into a fully resolved & expanded Path object.
Args:
obj (:obj:`str` or :obj:`pathlib.Path`): obj to convert into
expanded and resolved absolute Path obj
Returns:
:obj:`pathlib.Path`: resolved path
"""
return pathlib.P... | 7e8d7e3568b8adf111064cf496c7da863978b8f6 | 622,772 |
def is_unique(var_values):
"""
Checks whether a variable has one unique value.
"""
return len(var_values.unique()) == 1 | f3b1483346cbce4ed677b3d79a677f7cb2d7ebae | 622,773 |
def tailcuts_clean(geom, image, pedvars, picture_thresh=4.25,
boundary_thresh=2.25):
"""Clean an image by selection pixels that pass a two-threshold
tail-cuts procedure. The picture and boundary thresholds are
defined with respect to the pedestal dispersion. All pixels that
have a si... | 914f7555f1d225a615928a81a5f83ac477dc6239 | 622,777 |
def get_opatch_version(module, msg, oracle_home):
"""
Returns the Opatch version
"""
command = '%s/OPatch/opatch version' % oracle_home
(rc, stdout, stderr) = module.run_command(command)
if rc != 0:
msg = 'Error - STDOUT: %s, STDERR: %s, COMMAND: %s' % (stdout, stderr, command)
... | 9294cde16543b0560fda93c4e18d9bf5549110be | 622,781 |
from typing import Union
from pathlib import Path
from typing import List
def split_on_dot(line: Union[str, Path], only_last_dot: bool = False) -> List[str]:
"""
Split a string on the dot character (.).
Args:
line: The line ot split on.
only_last_dot: Only split on the last occurrence of ... | 2e84f74169c89c4911a0eb385317d1bc59395525 | 622,784 |
import json
def readJSON(filepath):
"""
Imports the content of the json file at the given filepath.
Parameters
----------
filepath : str
Path to the json file which will be read.
Returns
----------
The content of the json file as a dictionary.
"""
with open(filep... | fe9042fbc63fb29705c1ef609ac63650557e03a8 | 622,786 |
def strip_keys(key_list):
""" Given a list of keys, remove the prefix and remove just
the data we care about.
for example:
['defender:blocked:ip:ken', 'defender:blocked:ip:joffrey']
would result in:
['ken', 'joffrey']
"""
return [key.split(":")[-1] for key in key_list] | 986a9f83ae773a49d7872bf328e12d80f0039a75 | 622,787 |
import functools
def partial(f, *args, **kwargs):
"""
Create partial while preserving __name__ and __doc__.
:param f: function
:type f: callable
:param args: arguments
:type args: dict
:param kwargs: keyword arguments
:type kwargs: dict
:return: partial
:rtype: callable
""... | ea2afc23dcb031cca1e0a4bd2a4f44e25766da0d | 622,790 |
import json
def encode_recommendation(rec, dims):
"""This function encodes a representation and associated list of dimensions
into a JSON dictionary. This dictionary contains keys giving the name of
the associated hyperparameter and the suggested value of that dimension of
the hyperparameter set.
... | 7abb3c7b9d2004d60272cd06cc91bbc8c0fc972a | 622,791 |
def _translate_int(exp, length):
""" Given an integer index, return a 3-tuple
(start, count, step)
for hyperslab selection
"""
if exp < 0:
exp = length+exp
if not 0<=exp<length:
raise ValueError("Index (%s) out of range (0-%s)" % (exp, length-1))
return exp, 1, 1 | 99f6fb362fa81d028ca2eea638f3c5684132dba9 | 622,792 |
from typing import Union
from typing import Dict
def _format_peak_comment(mz: Union[int, float], peak_comments: Dict):
"""Format peak comment for given mz to return the quoted comment or empty string if no peak comment is present."""
if peak_comments is None:
return ""
peak_comment = peak_comments... | dd303655f0b163af27ab043ce69efdefa53d28b6 | 622,794 |
def get_force_datakeeper(self, symbol_list, is_multi=False):
"""
Generate DataKeepers to store by default results from force module
Parameters
----------
self: VarLoad
A VarLoad object
symbol_list : list
List of the existing datakeeper (to avoid duplicate)
is_multi : bool
... | 1321948d15f07914de30dab648d643121d94d491 | 622,795 |
def isNorm(s):
"""
Check whether a given value is a normalized Jacques-ID string.
The given value must be a string of exactly eight characters, and each
of those characters must be a non-padding base-64 digit with the only
non-alphanumeric symbols being + and /
Parameters:
s : str | mixed - the va... | 692cdb6feccd929942fa523a147c8a010fb96991 | 622,799 |
def decorate_init(init_decorator):
"""
Given a class definition and a decorator that acts on methods,
applies that decorator to the class' __init__ method.
Useful for decorating __init__ while still allowing __init__ to be
inherited.
"""
def class_decorator(cls):
cls.__init__ = init... | 44a46562339d9e0d7d44aded6d5d7b9e808d3f21 | 622,803 |
def pad_data(data, pad_amount, pad_value=b"\x00", start_at=0):
""" Pad a piece of data according to the padding value and returns the
result. Use start_at to specify an offset at the starting point. """
end_position = len(data) + start_at
if end_position % pad_amount != 0:
pad_size = pad_amount ... | c8501e8017a961691960028439bd5e92ff7335b1 | 622,806 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.