content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def add_cushions(table):
"""
Add space to start and end of each string in a list of lists
Parameters
----------
table : list of lists of str
A table of rows of strings. For example::
[
['dog', 'cat', 'bicycle'],
['mouse', trumpet', '']
... | bbe1a23ac84ac29aef7f450c9977949f4223dd15 | 657,923 |
def WmiBaseClasses(connWmi, className):
"""
This returns the base classes of a WMI class.
"""
# Adds the qualifiers of this class.
klassObj = getattr( connWmi, className )
# It always work even if there is no object.
return klassObj.derivation() | 97eabc1c185f9471d1af11abdff564bd5c6eb18d | 657,925 |
import re
def validate_rdm_string(ops: str) -> str:
"""Check that a string for rdms are valid.
Args:
ops (str): String expression to be computed.
Returns
(str): Either 'element' or 'tensor'.
"""
qftops = ops.split()
nops = len(qftops)
assert (nops % 2) == 0
if any(... | 0361cbe283e2a8adbcab8c6ca19cbee7338a977d | 657,926 |
def add_into_dict(input_key, incon_tuple, incon_dict):
"""
Two step:
0. under the same backends pair
* 1. the same input, choose largest.
2. different inputs with small distance. Do not update
"""
if input_key not in incon_dict.keys() or incon_dict[input_key][1] < incon_tuple[1]:
inc... | 95b25705eae6f46525cf92062b8643b9a2d98eb3 | 657,927 |
import subprocess
def get_hash():
"""
Get latest commit hash
:return:
>>> get_hash()
'0650ffee018272f630fea535df44e75f0e3224f4'
"""
cmd_str = 'git log -1 --format="%H"'
exitcode, hash_str = subprocess.getstatusoutput(cmd_str)
if exitcode != 0:
hash_str = ''
return hash... | 265fe5b6aeb87bf49afb2918007ee3d6e43ef7a2 | 657,928 |
def can_handle_identifier(identifier):
""" This package handles packages where identifier starts with SUDS#
"""
return identifier.startswith('SUDS#') | 22f5e67125ac4a3dd0c74301c6f5d37bbcc91680 | 657,929 |
def ete_dendrogram(corpus, tree, outputfile=None,
fontsize=5, save_newick=True, mode='c', show=False,
color_leafs=False, save=False, return_svg=True):
"""
Draw a dendrogram of the texts in the corpus using ETE.
Parameters
----------
corpus : `Corpus` instan... | 672b08a614a6a3ee966dcfda58c272cf88eb8642 | 657,930 |
from typing import Mapping
from typing import Optional
def env() -> Mapping[str, Optional[str]]:
"""
Returns a dictionary that maps environment variable names to values. The
values are either None or strings. String values can contain references to
other environment variables in the form `{FOO}` where... | c9b8cb845b5a1e708aa697bad587390541f9e55d | 657,931 |
def load_BAC_positions( gff2_file ):
"""! @brief load BAC IDs from GFF file """
BAC_IDs = {}
with open( gff2_file, "r" ) as f:
line = f.readline()
while line:
if line[0] != "#":
parts = line.strip().split('\t')
try:
BAC_IDs[ parts[0] ].append( { 'start': int( parts[3] ), 'end': int( parts[4] ),... | e4429d0dc87ddfc27e783468c1bc03b217fdca3d | 657,932 |
import os
def check_file(file_path, directory_path=None):
"""
Check if file exists.
"""
if directory_path:
file_path = os.path.join(directory_path, file_path)
return os.path.isfile(file_path) | adbab68aa0a6d845dfc4c27dd8404c9e1e4a0360 | 657,933 |
def solution(X, A):
"""
DINAKAR
Clue -> Find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X
[1, 3, 1, 4, 2, 3, 5, 4]
X = 5 ie. {1, 2, 3, 4, 5} here 1 to X/5 is completed so we re... | 7659f339e068773306a93876466a9135cf75b308 | 657,934 |
import os
def generate_new_filename(filename, prefix):
"""
Generates a new filename with a new prefix in front of the filename.
:param filename: the name of the original file
:param prefix: the prefix to add to the filename
:return: the new filename complete with path
"""
directory, name ... | d851a2e61f931c0f08164306d3408fcff9bcef61 | 657,935 |
def is_loc_free(loc, tile_grid):
"""
Checks whether a location in the given tilegrid is free.
"""
if loc not in tile_grid:
return True
if tile_grid[loc] is None:
return True
return False | 19237f3966341a4786079fe114d7338c018a9d91 | 657,936 |
import string
def _default_devour(text):
"""
The default devour function (strips out whitespace).
"""
i = 0
while i < len(text) and text[i] in string.whitespace:
i += 1
return text[i:] | a4ee9d76f934e2b7fd242e95d39d1d173eea0e36 | 657,937 |
import subprocess
import re
import os
def cluster_sequences(sequences, similarity):
"""Takes a list of sequences and clusters them by some amount. CD-HIT must
be installed."""
lines = [f">{i}\n{s.upper()}" for i, s in enumerate(sequences)]
try:
with open("chains.fasta", "w") as f: f.write("\n... | 0a7506f5cee6f63e5459c14d0146b09efaa325a6 | 657,938 |
def heading(text, level):
"""
Return a ReST heading at a given level.
Follows the style in the Python documentation guide, see
<https://devguide.python.org/documenting/#sections>.
"""
assert 1 <= level <= 6
chars = ("#", "*", "=", "-", "^", '"')
line = chars[level] * len(text)
re... | 43ef5bc1fdfb6c34279e9aa74ac420c1b1110e3a | 657,939 |
def parse_text_file(tf):
"""
Parse a text file and return an n-choose-2 array of the elements. The array returned has the distance from the first
element to all other elements, and then the second element to n-1 elements (all but the first), and then the
third element to n-2 elements (all but the first ... | c49a8cc4f89a4c154c5631223f0a2e4ac174a005 | 657,940 |
import requests
def get_api_result(word):
""" GTS uzerinden kelimeyi getirir """
headers = {
"User-Agent": "APIs-Google (+https://developers.google.com/webmasters/APIs-Google.html)"
}
api_url = "http://www.sozluk.gov.tr/gts"
params = {"ara": word}
result = requests.get(api_url, param... | 8d5722f169cfe90769fdb456f474e169c3568919 | 657,941 |
def index():
"""Index Route."""
return "Index" | 0bef5e7b43028f0528ce22380cc5f16447d8fc0b | 657,942 |
def crop_box(img):
"""returns a cropbox for an image in which removes as much white boarder as possible without
removing any pixeles that are not == (255,255,255)"""
width,height = img.size
xs = []
ys = []
pixeles = img.load()
for w in range(width):
for h in range(height):
... | 946179a05ad7fcd7784d4dd1942a143a36f5765b | 657,943 |
import json
def _str_to_tiptap_markup(text):
"""Convert a plain text string into a TipTap-compatible markup structure"""
return json.dumps(
{
'type': 'doc',
'content': [
{'type': 'paragraph', 'content': [{'type': 'text', 'text': paragraph}]}
for ... | a5edbc0b5e844b77db61ae2b5d87eee14d271fda | 657,944 |
def process_dataset(df, train_validation_ratio = 0.8):
"""Given a dataset, perform train-validation split and generate minibatches"""
x_train, y_train, x_val, y_val = None, None, None, None
# image data
xS = None
# dankness score
yS = df.dankness
return (x_train, y_train, x_val, y_val) | cfe6c5eff91e557f62a5fd923be49df39d3b6a38 | 657,945 |
def simple_logged_task(a, b, c): # pylint: disable=invalid-name
"""
This task gets logged
"""
return a + b + c | b0092371098c7dd6b795fda820e33490a8b4c99a | 657,947 |
def set_pass_code():
"""
Set and validate the password
:return: string
"""
pass_code = input("Enter your Oracle Commerce Cloud backend pass-code: ")
while True:
if len(pass_code) >= 5:
return pass_code
else:
pass_code = input("Enter your Oracle Commerce Cl... | 52fa5a74df1d9d6e58d59de7dbe1c8f2cc76b6d0 | 657,948 |
import re
def remove_from_text(raw_text: str, symbols: list) -> str:
"""
Removes every symbol/character in the given symbols list from a given string,
raw_text.
"""
return re.sub("|".join(symbols), "", raw_text) | 9e3f62788de70a663005daca35443f2f2b7de742 | 657,949 |
def get_factors(x):
"""Returns a list of factors of given number x."""
factors = []
#iterate over range from 1 to number x
for i in range(1, x+1):
#check if i divide by number x evenly
if (x % i == 0):
factors.append(i)
return factors | 29b63efc435cfd54d8f384f3d5fbd18b12d3627d | 657,950 |
def wd_edge_list(data):
"""with-document edge list
Arguments:
data {[type]} -- [description]
Returns:
[type] -- [description]
"""
wd_edge_list = []
for s1i, s1 in enumerate(data): # even for doc title, odd for doc sents
for s2i, s2 in enumerate(data):
... | 1fd61d6e78458090905b63f6ffc4cdf9366e8d2d | 657,951 |
import json
def sos_pro (max_punt,puntaje_logrado,nombre,dificultad):
"""cambia el puntaje del usuario en caso de que la puntuacion lograda haya sido mayor que su
puntuacion maxima,la puntuacion lograda se determina a traves de la funcion 'fin_juego'"""
cambiado = False
if max_punt < puntaje_logr... | 0088a25df4d48e82eb0b09eceafd408c0a8e24c8 | 657,952 |
import glob
import os
def get_gt_patterns(annotators):
"""Obtains the set of files containing the patterns and its occcurrences
given the annotator directories.
Parameters
----------
annotators: list of strings (files)
List containing a set of paths to all the annotators of a given piece.... | 720db1665f1a8ebc596ab0438ac8025660438c37 | 657,953 |
def root_node_only_token_stream(request):
"""
Fixture that yields strings that will generate a token stream that creates a single root node.
"""
return request.param | 0a340d78057716157677a79525c0c57707817daa | 657,954 |
def load_conll_ner(file_path, kwargs: dict = {}):
""" Load NER """
rows = []
cnt = 0
sentence = []
label = []
with open(file_path, encoding="utf8") as f:
for line in f:
line = line.strip()
if len(line) == 0 or line.startswith("-DOCSTART") or line[0] == "\n":
... | 19677120df94ec36ba2127c1a20abf7385442377 | 657,955 |
import os
def expand_cvar(s, expr, search_paths=['.']):
"""search through a string to find any import expressions and load them into s, looking in specified search paths"""
vars = expr.findall(s)
for v in vars:
fname = v[2:-1]
found = False
for path in search_paths:
fu... | 8ae0edd18844688a1d7dd3eb45a8dfc5aae74095 | 657,956 |
import numpy
def _ltri_ix(n, ndims):
"""
Generates lower-triangular part indexes in arbitrary dimensions.
Args:
n (int): dimension size;
ndims (int): number of dimensions;
Returns:
Indexes in an array.
"""
if ndims == 1:
return numpy.arange(n)[:, numpy.newaxis]... | 3a427cd88c3c57397a51b5cb46eb5a79d8130a72 | 657,957 |
def request_to_info(req, info):
"""Given a request multidict, populate the info dict."""
keys = ["subjects", "anatomy", "preproc", "model", "ffx",
"rois", "maps", "peaks", "params", "contrasts"]
for key in keys:
info[key] = req.getlist(key)
info["ffxspace"] = req.get("ffxspace", "")
... | ec684c694fffb9007c7d8fb8e829e962c061660a | 657,958 |
def risk_assessment(roi, bankruptcy_definition, years, risk_counter):
"""Risk Assessment of Bankruptcy Calculation
Args:
roi (list): The farm scenario
bankruptcy_definition (list): The threshold line of bankruptcy
years (int): No. of years for analysis
risk_c... | 040b46114839250d71c53d58a59727a007499c1e | 657,959 |
def dict_intersection(a: dict, b: dict):
"""Elements that are the same in a and b"""
return {k: v for k, v in a.items() if k in b and b[k] == v} | 75998566a9babf85c9f9a5a7b334154c8dbc0040 | 657,960 |
def _read_config(filename):
"""
Read config file into `c`. Variables in config file are formatted
as `KEY=VALUE`.
"""
c = {}
with open(filename, "r") as f:
for line in f:
key, val = line.split("=")
key = key.strip()
val = val.strip()
c[key... | b4399703a09453800a2ba896b2c71324fbb2b3ad | 657,961 |
def takeover(request, user):
"""
Login the current user to any other user.
Args:
request: Django HTTP request instance with already authorized user.
user: takeovered user.
Returns:
True if takeover was performed or False.
"""
if not hasattr(request, 'user') or not reques... | 379c409c535a3c917f86dcb9443c2468a9dcd574 | 657,962 |
def format_contributor(contrib):
"""
Helper function to format the details properly.
"""
name_str = 'Name: ['
contrib = contrib.replace(':', ':')
contrib = contrib.replace('htpps', 'https')
contrib = contrib.replace('Name:[', name_str)
contrib = contrib.replace('Name : [', name_str)
... | f0a4b295cc734fddab7b37d67ec27245f97e1954 | 657,963 |
def is_business_type(business_type_choice, on_default_path=False):
"""Returns a function to assert whether the wizard step should be shown
based on the business type selected.
The `on_default_path` allows the returned function to return a default
value if the business type hasn't been filled in yet. Th... | a8b7d192af6f8620b02829adf80c9cf8a1ec77bc | 657,964 |
import re
def natural_sort_key(sort_key, _nsre=re.compile('([0-9]+)')):
"""
Pass to ``key`` for ``str.sort`` to achieve natural sorting.
For example, ``["2", "11", "1"]`` will be
sorted to ``["1", "2", "11"]`` instead of ``["1", "11", "2"]``
:param sort_key: Original key to be processed
:retur... | 69a2a18701fdcf72041cdac9037c19b3f2561c6c | 657,965 |
def contains_digit(text):
"""Returns true if any digits exist in the text"""
return any(c.isdigit() for c in text) | 593bd0fa600fd6e7fae7ef77a16f32f0adaf6fe6 | 657,966 |
import platform
def get_os():
""" Get the current operating system.
Lower-case strings are used to identify operating systems.
@return: A pair of OS identifier and OS release (e.g. "xp") strings.
"""
name, host, rls, ver, mach, proc = platform.uname()
name = name.lower()
if name == "micro... | b16ae8f2df8a6037c44546825f0785429fd1f06c | 657,967 |
def dot_product(A, B):
"""
Perform a dot product of two vectors or matrices
:param A: The first vector or matrix
:param B: The second vector or matrix
"""
# Section 1: Ensure A and B dimensions are the same
rowsA = len(A); colsA = len(A[0])
rowsB = len(B); colsB = len(B[0])
i... | 6b3439fe085fbb81758e3a830c094d36fc1c621b | 657,968 |
def mask_according_to_word_pos(x, word_positions, word_positions_to_mask, mask_all_positions=False, mask_token="<mask>"):
"""mask timesteps in x that correspond to word positions that we wish to mask"""
masked_x = []
for token, word_pos in zip(x, word_positions):
if word_pos in word_positions_to_mas... | 1567e7b397d7e532768fcfa7ac7e60d302d3aa1d | 657,969 |
def many_any(lst, k):
""" Returns True if at least k elements of lst are True;
otherwise False. Do this in one line for extra credit.
Hint: use a list comprehension.
Example:
>>> many_any([True, True, False, True], 3)
True
>>> many_any([True, True, False, False], 3)
False
"""
re... | 2e277dd5a97fb9f1f13ea8272f7b7b223312381f | 657,970 |
import math
def largest_numeric_increase_infant_mortality(data_by_country):
""" Which country had the largest increase in Infant mortality for both sexes from 2005 to 2015?
Parameters:
data_by_country: dictionary with different data for countries.
Returns:
Tuple(String, String) - (Qu... | 972ade7cd38b0b06b963b5762ced6a46a0a5273d | 657,971 |
def s3_key_smart_join(parts, is_dir):
"""
Note, it assume that there's no such double slack in your path. It ensure
that there's only one consecutive "/" in the s3 key.
:type parts: typing.List[str]
:param parts: list of s3 key path parts, could have "/"
:type is_dir: bool
:param is_dir: i... | e53f2ddfd0ceef44200db7ea54f4be35111f1eef | 657,972 |
def calc_min_rm_and_dlet(list_rm, list_dlet):
""" calculates the robustness margins/delta let values for all tasks
based on the analyses of all cause-effect chains defined for a given system
:param list_rm: list of dicts
:param list_dlet: list of dicts
:rtype: dict, dict
"""
rm = dict()
... | 70f7bc77ed64a24a915cf49268fc725b5ba66069 | 657,973 |
def r_2(mu, state):
"""Position Vector from secondary body (i.e. Moon) to the satellite
Args:
state (np.array): state vector of satellite in non-dimensional
circularly restricted three body coordinates
Returns:
np.array
"""
return [(state[0] + 1 - mu), state[1],... | 2f7c12a2f182a6e59786039d968974187133dcf2 | 657,974 |
def collect_reducer_count(values):
"""Return the number of values
>>> collect_reducer_count(['Sheep', 'Elephant', 'Wolf', 'Dog'])
4
"""
return len(values) | f398326ffb9932a8a033d158140f065cff6d6453 | 657,975 |
import secrets
def generate_token(length : int=32) -> str:
"""
Uses the secrets.token_hex() method to generate a
a hexidecimal token
Parameters
----------
length : int
The desired length of token
Returns
-------
str
The hexidecimal string generated by Pyth... | f2524b306910c40717f0512cb233dc34a19f2636 | 657,976 |
def fib(n: int) -> int:
"""Fibonacci Number Generator.
This will give you the n'th number in the Fibonacci sequence
Args:
n: The number position in the Fibonacci sequence
Returns:
The n'th number of in the Fibonacci sequence
"""
if n < 2:
return n
else:
ret... | 4b15ac2afcf5287db87af4f03a7a7a3be00891af | 657,977 |
def _extra_if_info(node):
"""Returns extra information about a given interface based on its type."""
def _serial_bsd_client(node):
"""Get serial device path."""
devname = node.get('IODialinDevice')
if devname is not None:
return {'devname': devname}
return {}
de... | 9fbd0b843025c212f3dd8ce0f5ce92b892dc0af2 | 657,978 |
def B(value):
"""Returns 1 if value is truthy, 0 otherwise."""
return 1 if value else 0 | ce788b5fa6aff71379dd3ca326e2e4e2e5da950f | 657,979 |
def leading(value):
"""
Strip all leading whitespaces.
:param value: The value
:type value: str
:return: The value with all leading whitespaces removed
:rtype: str
"""
return value.lstrip() | f77fcf0ceb615af7d49fa6b473a9bb9ce72a2da3 | 657,981 |
import random
def get_digit():
"""Choose a random digit."""
digit = random.choice(range(10))
return digit | 0c9228723b41cd8747a4c289cbab77645f36ccd4 | 657,982 |
def last_char_to_vowel(word):
"""Intended for abbreviations, returns the vowel for illative etc based
on how the last character is pronounced in Finnish."""
assert isinstance(word, str)
# We iterate over characters of the word, because the last might be a
# punctuation, perhaps.
for last in reve... | 653fed73a742f6aa4af8cd6104850641da335e05 | 657,983 |
import argparse
def parse_args():
"""
parsing and configuration
:return: parse_args
"""
desc = "Tensorflow implementation of pix2pix"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('--module', type=str, default='test_dataset',
help='Module t... | 2917ca86145c493449b271b3ecd574addb2ce7ca | 657,984 |
import math
def hypotenuse(a, b):
"""
Compute the hypotenuse of a right triangle with sides of length a
and b.
>>> hypotenuse(3, 4)
5.0
>>> hypotenuse(12, 5)
13.0
>>> hypotenuse(7, 24)
25.0
>>> hypotenuse(9, 12)
15.0
"""
h = math.sqrt(a*a + b*b)
return h | dc4190c06acd1506d2c4fc57ebf19c4a37ea249f | 657,985 |
def box_text(text, width, offset=0):
"""
Return text inside an ascii textbox
"""
box = " " * offset + "-" * (width + 2) + "\n"
box += " " * offset + "|" + text.center(width) + "|" + "\n"
box += " " * offset + "-" * (width + 2)
return box | cc4bd6ba46920d02caf1ee4e2dbb769c397945f7 | 657,987 |
def add_class(form_widget, css_class):
""" Adds a css class to a django form widget """
return form_widget.as_widget(attrs={'class': css_class}) | 9f9559698233e93ee8828a0132de9378bed7c15d | 657,988 |
def get_thresholds(threshs_d: dict) -> tuple:
"""
Parameters
----------
threshs_d : dict
Thresholds configs
Returns
-------
names : list
Name for the threshold
thresh_sam : int
Samples threshold
thresh_feat : int
Features threshold
"""
names ... | ba9984fa94ab209f1b863175eb55bb4985a92a65 | 657,990 |
def _field_name_grib1_to_grib2(field_name_grib1):
"""Converts field name from grib1 to grib2.
:param field_name_grib1: Field name in grib1 format.
:return: field_name_grib2: Field name in grib2 format.
"""
return field_name_grib1.replace('gnd', 'ground').replace('sfc', 'surface') | 439e7e6d101e04d3d02f2d783321812a1acda7a9 | 657,992 |
def _composite_zlevel(zlevelA, zlevelB):
"""
Determine the zlevel of a composite
DFun A(B(x))
Parameters
----------
zlevelA, zlevelB : int or None
zlevel parameter of composite DFun
Returns
-------
int or None
zlevel of composite function
"""
if zlevelA is ... | 2e4db7f816ce3f48da47a182d23124493d1035d1 | 657,993 |
def get_descriptors(image, filtered_coords, wid=5):
""" For each point return, pixel values around the point
using a neighbourhood of width 2*wid+1. (Assume points are
extracted with min_distance > wid). """
desc = []
for coords in filtered_coords:
patch = image[coords[0]-wid:coords[0]+wid+... | e1e7b67ff88d9546e6be1e2f5bdd80287d14ffce | 657,994 |
def write_to_file(filepath, data_to_write):
"""
TO DO:
This function takes any <data_to_write>, converts it into a string via the str()
function (if possible), and then writes it to a file located at <filepath>. Note
that this function is a general writing function. It should not use the .csv
mo... | a0879d88ebfea1e4308910e355ef9ff9b0088b41 | 657,995 |
def callback_ResetDropdown(window):
"""
Updates the dropdown after newVal is selected and applied
Parameters
-------------
window = GUI object
Returns None
-------------
"""
# set values and value to empty to get rid of previously specified answers
window['changeMod'].update('C... | a04075aa205fed91efc6bfd4fffc944498c26913 | 658,000 |
def _get_afpm_id(line: str, line_upper: str) -> int:
"""
parses the superelement header::
BEGIN AFPM=2
BEGIN BULK AFPM=2
BEGIN BULK AFPM = 2
"""
sline = line_upper.split('=')
try:
afpm_id = int(sline[1])
except (IndexError, ValueError):
msg = 'expected "... | 2c83ee23d3dc54af5b8ac1858531664021ea60fe | 658,001 |
def dice_jaccard(y_true, y_pred, smooth=1, thr=None):
"""
Computes Dice and Jaccard coefficients.
Args:
y_true (ndarray): (H,W)-shaped groundtruth map with binary values (0, 1)
y_pred (ndarray): (H,W)-shaped predicted map with values in [0, 1]
smooth (int, optional): Smoothing facto... | e633fe7546809edf5445c6a5e313d705b38438ef | 658,002 |
def my_implementation(x):
"""Calculate the square of the input; a placeholder numerical method."""
return x ** 2 | bb1f938f64bac39616dcd5b8cf8cb54f5c3984a8 | 658,003 |
import tempfile
import sys
def create_temp_file(suffix=''):
"""
Creates, opens and returns a temporary file.
Note this file will not be automatically deleted by Python.
"""
os_fd, filename = tempfile.mkstemp(suffix=suffix, text=True)
if sys.version_info[0] >= 3:
return open(filename, '... | 6839d0e3f25f5c4d9f7c6b7c4d1ddbe91645d25b | 658,005 |
def checksum(number):
"""Calculate the checksum."""
return (int(number[:-2]) + int(number[-2:])) % 97 | 3abccadc69716d5a2332a40a4663768ce7a538a4 | 658,006 |
def project_with_node_view(arr, g):
""" correctly selects the parts of the array, that are visible when g is a node view
When using node views, centralities are still returned for the entire graph
this function properly returns only that part of the array that is currently selected by that node view
... | 64ee0c1814c04227bcdf7a3af3dab4f30db895c6 | 658,008 |
def _select_compcor(compcor_cols, n_compcor):
"""Retain a specified number of compcor components."""
# only select if not "auto", or less components are requested than there actually is
if (n_compcor != "auto") and (n_compcor < len(compcor_cols)):
compcor_cols = compcor_cols[0:n_compcor]
return ... | f8c7936a7bb8a675d98cb2bf2ffea203f796c0b6 | 658,009 |
def HSVtoRGB(h, s, v):
"""Convert HSV values to RGB
Algorithm is taken from https://www.cs.rit.edu/~ncs/color/t_convert.html
"""
if s == 0:
# Achromatic, i.e. gray
gray = v * 255
return gray,gray,gray
# Calculate our "sectors"
h /= 60
i = int(h)
# A few intermed... | 17b51b81addb6ba0872529fabb63553f1d97dea9 | 658,011 |
def _get_version_docs_action():
"""
Simple helper for returning a log action to show version docs
"""
return {
"action_open_url": {
"label": "Version Docs",
"tooltip": "Show docs for version formats",
"url": "https://support.shotgunsoftware.com/hc/en-us/articl... | 44132ed2c0d2552767a186970a981503e130a775 | 658,012 |
def _object_by_name(name,root=None):
"""Look up an object by dotted-name notation."""
bits = name.split(".")
if root is None:
try:
obj = globals()[bits[0]]
except KeyError:
try:
obj = __builtins__[bits[0]]
except KeyError:
o... | 13c2544e748461dcec1d2c8902433ef67ca23ecd | 658,013 |
def generalize_version(package):
"""Add `.*` to package versions when it is needed."""
dep = package
if ("=" in dep or (dep[-1].isdigit() and "." in dep)) and not dep[-2:] == ".*":
dep += ".*"
if " " in dep and not "." in dep.split()[1]:
dep += ".*"
return dep | b0ba536926b8fa6177ed692c21f668da5e09ff41 | 658,015 |
def coroutine(func):
""" A helper function decorator from Beazley"""
def start(*args, **kwargs):
g = func(*args, **kwargs)
g.next()
return g
return start | d338709a8e564ca1c37fc133b51038f882db937e | 658,016 |
def ph_color_code(value):
"""
:param value: This is a pH value which is having its color multiplexed.
Description:
This takes a pH value as input and returns a color to be used in the form of a string.
"""
if value > 12.6:
return 'navy'
elif value >11.2:
return 'blue'
elif value >9.8:
return 'dodgerb... | eac3f1dc83e2a9a75dbfc1a913a9f2d0ecb0bc67 | 658,017 |
import torch
def gaussian_kl(mu, logsigma):
""" Analytically compute KL divergence between the multivariate gaussian defined by
the input params (assuming diagonal covariance matrix) and N(0, I).
Arguments:
mu (torch.Tensor): Mean. Expected size (N x num_variables)
logsigma (torch.T... | 0117a327f1181eaf647eba55f2e40c0886138144 | 658,018 |
def query_merge(query: dict, **kwargs: dict) -> dict:
"""
Merge a dictionary and key word arguments into a single dictionary.
Used to merge a MongoDB query and key word arguments into a single query.
:param query: The dictionary to merge.
:param kwargs: The key word arguments to merge.
:return... | 5a53047cdc2983225815506203f9134de371c0c0 | 658,019 |
def search_to_url(search: str) -> str:
"""Transform user search terms into ready to use URL"""
search = search.lower().replace(" ", "%20")
return f"https://uk.indeed.com/jobs?q={search}&l=United%20Kingdom" | b5291f39fb7bd1722ef46c0e8a662e42f8b26f1c | 658,020 |
def determine_format(tileSource):
"""
Given a tile source, return the vendor format.
:param tileSource: a large_image tile source.
:returns: the vendor or None if unknown.
"""
metadata = tileSource.getInternalMetadata() or {}
if tileSource.name == 'openslide':
if metadata.get('opens... | dd40ecfa44498c2237cba0729213d9abe3d9e855 | 658,021 |
import re
def capitalize_sentences(text: str) -> str:
"""Return text capitalizing the sentences. Note that sentences can end
in dot (.), question mark (?) and exclamation mark (!)"""
pattern = re.findall(r"[\w\s,]+[!.?]\s*?", text)
sentences = (t.strip() for t in pattern)
capitalized = " ".join... | 5249b5a314c34ce032337c42834b3395c541ec2a | 658,022 |
def unpack_performance_metrics_OLD(batch_performance_metrics):
""" Unpacks batch performance metrics DataFrame into a python standard dictionary
Targets old data storage schematic PRIOR TO JULY 25, 2019
Input:
- batch_performance_metrics: pandas DataFrame
Output:
- unpacked_batch_m... | efbe6c3a2857cf548c9e3a80adf63158c27960b2 | 658,023 |
def fake_pgettext(translations):
"""
Create a fake implementation of pgettext, for testing.
"""
def _pgettext(context, text):
return translations.get((context, text), text)
return _pgettext | 38b05f8cf51a787642f2af0057fe6c0fcfd09453 | 658,024 |
def get_MA_period():
"""
get the time range for Moving Average
:return: int type, a number (time range (unit: day)) which will pass to function moving_average
"""
SAM_period = int(
input('\nPlease enter the time range (unit: day) \nyou expect for Moving Average (enter a number): '))
retu... | 5dc21157799adccf3e4db8046bc569916b44a2c5 | 658,025 |
def __find_number_of_repeats(seq_before, seq, seq_after):
"""
Finds the number of repeats before or after a mutation.
:param seq_before: the genomic sequence before the mutation (str)
:param seq: the genomic sequence of the mutation (str)
:param seq_after: the sequence after the mutation (str)
... | 63ca022ec9a529e70e3080b16c9a59a91e1c5cf6 | 658,026 |
from datetime import datetime
def next_month(dte):
"""
Return a date that is the first of the month after the current dte.
Argument:
dte - the date being used to compute the next month
"""
month = dte.month
year = dte.year
if month == 12:
month = 1
year += 1
el... | 7275904aa7f3acab00637d6b24c459c80ca44f27 | 658,027 |
def _upper_case_first_letter(name):
"""
Function that convert first character of name to UPPER case
:param name: String which first character will be converted to UPPER case
:return: String with first character in UPPER case
"""
indices = set([0])
return "".join(c.upper() if i in indices els... | 7059daa4e97708bcaf400c9faaec241cebb8de7f | 658,028 |
def parse_argument(arg):
"""Helper function for wild arguments"""
if arg in ["No", "N", "NO", "OFF", "off", "n", "no"]:
arg = "no"
else:
arg = "yes"
return arg | ef6725e615724344728f7d9461e765d449b4e084 | 658,029 |
def _rfv_str_ ( var ) :
"""String representaion of the RooFormulaVar
"""
return '%s : %s' % ( var.expression() , var.getVal() ) | 72d5fa52d02450a4ad8b54b394a838d54887a1b9 | 658,030 |
import re
import os
def link_ids_to_input(data_dir, sample_regex, replicate_regex=''):
"""
Link sample ids to data files.
Args:
data_dir (string): parent directory containing all sample-specific
directories/files.
sample_regex (string): regex pattern to extract sample ids from... | d8a5a9ab474d0ee5681aca914f08365170facc07 | 658,031 |
import os
import shutil
def copy_if_newer(src, dest):
"""Copy src to dest if src is newer and return a bool indicating whether
the copy took place.
"""
if (not os.path.exists(dest)
or os.stat(src).st_mtime > os.stat(dest).st_mtime):
shutil.copy2(src, dest)
return True
retur... | c3c276c3eb02a1a78a3aa7a63e2222c6aa3009b1 | 658,032 |
def kelvin_to_celsius(kelvin):
"""
Convert kelvin temperature to celsius.
"""
return kelvin-273.15 | 91fe9431de8c08ffe7072379bdc1100d27925afc | 658,033 |
def sec2hour_min_sec(seconds):
"""
Convert elapsed seconds to hours, minutes and seconds
#Credits: https://codereview.stackexchange.com/questions/174796/convert-seconds-to-hours-minutes-seconds-and-pretty-print
Parameters
----------
seconds : long int
elapsed seconds
Returns
-------
str
string with conve... | 3e6013a625d674a1e0d0ffdd1f6306681dd28c1d | 658,035 |
def _firstResult(gen):
"""
Return the first element of a generator and exhaust it.
C{MethodicalMachine.upon}'s C{collector} argument takes a generator of
output results. If the generator is exhausted, the later outputs aren't
actually run.
@param gen: Generator to extract values from
@ret... | 3bdfda49c664426be9f524fcfd1dd086cc9679a8 | 658,036 |
def convert_type(t, v):
"""Convert value 'v' to type 't'"""
_valid_type = ['int', 'float', 'long', 'complex', 'str']
if t not in _valid_type:
raise RuntimeError(
'[-] unsupported type: '
f'must be one of: {",".join([i for i in _valid_type])}')
try:
return type(eva... | 53b4e40942bc0d9d0b8abaeebe5921ea4a6a5c80 | 658,037 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.