content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _flavor_string(capacity_key, primary_disk):
"""Removed the _X_YEAR_TERM from capacity_key and adds the primary disk size, creating the flavor keyName
This will work fine unless 10 year terms are invented... or flavor format changes...
"""
flavor = "%sX%s" % (capacity_key[:-12], primary_disk)
re... | f6e0e291b6173bdc3a61cae8ab5f6a28c9d8d18e | 666,447 |
import os
def _exclude_paths_from_environ(env_prefix=''):
"""Environment value via `/login;/register`"""
paths = os.environ.get(env_prefix + 'WSGI_AUTH_EXCLUDE_PATHS')
if not paths:
return []
return paths.split(';') | 914e697be4e7d8f84d11b67be3ea8d98ee41435f | 666,448 |
def __evaluate_tree(predictor, input):
"""Function for evaluating a given decision tree on a given input."""
return predictor.evaluate(input) | d41816254a035e25edd7e20baf1f058010502559 | 666,449 |
import argparse
def get_parser():
"""Adds arguments to the command"""
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', type=str, default='lodopab')
parser.add_argument('--method', type=str)
parser.add_argument('--start', type=int, default=0)
parser.add_argument('--count', ty... | bb1d516b825718734ddc7432bdd4b1bb44d4f193 | 666,450 |
from numpy import array, arange, floor, ceil
def interpolationball(matrix, index, step, r, **kwargs):
"""Interpolation the value by the radius(ball).
The Inverse distance weighting is used to weight each value."""
position = index * step
w = []
v = []
for i in arange(ceil(index[0] - (r / ste... | 10300d78f58ae5dc480239f1954485e1f72fd258 | 666,451 |
import pickle
def load_pickle(path):
""" load pickle files into memory
"""
f = open(path, 'rb')
v = pickle.load(f)
f.close()
return v | efd324983e2cf2b7d399287689bbd3a89ddf3990 | 666,452 |
def format_df_candles(df, time_match_df, candles):
"""Format dataframe to aggregate more information.
Parameters
----------
df: pandas.Dataframe
time_match_df: pandas.core.series.Series
candles: pandas.core.series.Series
candle_type: int
Returns
-------
df: pandas.Dataframe
... | e56403434d2526ba00c45f14e3dbe0ee4765ff71 | 666,453 |
import struct
def readLong(f):
"""Read unsigned 4 byte value from a file f."""
(retVal,) = struct.unpack("L", f.read(4))
return retVal | 4f2554908eacd160cc3aabd3a4cdb8e03a5d17e0 | 666,454 |
def cabs2(x):
"""Fast abs^2 for complex numbers which returns a contiguous array."""
return x.real**2 + x.imag**2 | d6475b71fe1e35b3d19ee1609ddd85ba55ea692e | 666,455 |
def censor(y):
"""Use clip to turn zeros into tiny positive values"""
return y.clip(1e-6, y.max()) | e438bcc5402527363a0b96c6ea2241070f7df509 | 666,456 |
import json
def read_data_gemini():
"""Help function to read sample payload."""
with open('data/scan-test-data.json') as f:
data = json.load(f)
return data | 173fcc6d4e3fa4226bace8ea994b4051f35c88e0 | 666,457 |
def tank_geometry(geometry, om_key):
"""
Returns the IceTop tank geometry object corresponding to a given DOM.
"""
if om_key.om == 61 or om_key.om == 62:
return geometry.stationgeo[om_key.string][0]
elif om_key.om == 63 or om_key.om == 64:
return geometry.stationgeo[om_key.string][1]... | 2dc58089b9b3305b5e43fcb6a4896e4ee66b46b6 | 666,458 |
def java_string_hashcode(s):
"""source: http://garage.pimentech.net/libcommonPython_src_python_libcommon_javastringhashcode/"""
h = 0
for c in s:
h = (31 * h + ord(c)) & 0xFFFFFFFF
return ((h + 0x80000000) & 0xFFFFFFFF) - 0x80000000 | 2adf1f6735772237de227454b4f889105f892715 | 666,459 |
def get_levenshtein_distance(word1, word2):
"""
https://en.wikipedia.org/wiki/Levenshtein_distance
:param word1:
:param word2:
:return:
"""
word2 = word2.lower()
word1 = word1.lower()
matrix = [[0 for x in range(len(word2) + 1)] for x in range(len(word1) + 1)]
for x in range(len... | e4b00c81da5145f7432ddc5a96dc8688f0382941 | 666,461 |
import json
def config(filename: str = "config"):
""" Fetch config file """
try:
with open(f"{filename}.json", encoding='utf8') as data:
return json.load(data)
except FileNotFoundError:
raise FileNotFoundError("JSON file wasn't found") | 9eebf39a9cbd033ecb49a9a02c2b5573a06d7303 | 666,462 |
def ogrtype_from_dtype(d_type):
"""
Return the ogr data type from the numpy dtype
"""
# ogr field type
if 'float' in d_type.name:
ogr_data_type = 2
elif 'int' in d_type.name:
ogr_data_type = 0
elif 'string' in d_type.name:
ogr_data_type = 4
elif 'bool' in d_type.n... | 19ab7b80d014edb6c211b800fee480eaba6349cc | 666,463 |
import readline
def again(adv):
"""Repeat last command.
The actual repeating is in execute(), it digs here in readline's history.
Args:
adv: namedtuple holding the game data
Modifies:
adv: player's actual command ('again') is substituted with the command before or with an
... | 8d16634735f0609fb66ba17d7b3578a324d19b0c | 666,464 |
def recursive(n):
"""Using Brian Kernighan’s Algorithm. (Recursive Approach)"""
"""
Count the occurrence of count bits in a binary representation of a number.
:param n: The binary representation of a number.
:return: returns the count of 1s in a n.
"""
if not n:
return 0
return... | 40dc9fec207fcf76e295ef2d69e24f6cf0f97704 | 666,465 |
from datetime import datetime
def user_age(bday):
"""Given a user's birthday, prints their age to stdout
bday: a datetime
returns: void. prints to stdout
"""
today = datetime.today()
age = abs(today - bday)
yearsold = age.days // 365
return yearsold | bfb81961e1a489add63ff583b295501eb97f4ebb | 666,466 |
def check_min_version(version, min_version):
"""
:param version:
This is the version of robotframework.
:param min_version:
This is the minimum version to match.
:return bool:
True if version >= min_versiond and False otherwise.
"""
if version == "N/A":
... | eeaa669113eb69b124a34f6f9eb68fa8fe0de42d | 666,467 |
def get_label_code(label_name: str) -> int:
"""
Returns a code for a GitHub issue label to be added to the output JSON.
This makes the JSON smaller and therefore faster to download and parse.
NOTE: This must be kept in sync with `getLabelName()` in `index.html`.
"""
if label_name == "meta":
... | 7add84f7d8b80d5fe65d27f9dc28944c702e5096 | 666,468 |
def mniposition_to(mnipoint, affine):
"""
project the position in MNI coordinate system to the position of a point in matrix coordinate system
Parameters
----------
point : list or array
The position in MNI coordinate system.
affine : array or list
The position information of t... | 631a5fa1362099599511c85c0d3f07a76c3e8723 | 666,469 |
from typing import List
from typing import Tuple
def partition_leading_lines(
lines: List[str],
) -> Tuple[List[str], List[str]]:
"""
Returns a tuple of the initial blank lines, and the comment lines.
"""
for j in range(len(lines)):
if lines[j].startswith("#"):
break
else:
... | 3be97e68e26a333f886f6643f645b8075f2140fc | 666,470 |
def convert_16_to_8(value):
"""Scale a 16 bit level into 8 bits."""
return value >> 8 | 423d05e414bf6959b2b9a3903f2c074bc9fc09f3 | 666,471 |
from datetime import datetime
def is_time_in_given_format(time_string, time_format):
"""Tests whether a time string is formatted according to the given time
format."""
try:
datetime.strptime(time_string, time_format)
return True
except ValueError:
return False | 0fbde6aaf302a26411091d46cfbfb5cee37992c2 | 666,472 |
def from_str(s):
""" generate genotype from string """
genotype = eval(s)
return genotype | 50e78e49eb105c41ba2a259589006be4a7ad53e9 | 666,474 |
def _mangle_token(token):
"""Slaughter a token for public exposure"""
_tl = len(token)//2
return "{}{}".format('*' * (_tl), token[_tl+1:]) | 8e40dad2931f9b9630a291bef5f44e97809eeac2 | 666,475 |
def normalize_time(time):
"""Normalize time by carrying over excess seconds and minutes recursively.
time: Time object.
"""
if time.second < 60 and time.minute < 60:
return time
# carry over excess seconds
if time.second >= 60:
time.second -= 60
time.minute += 1
... | f57883002775ab7ffb1a2f9bfb27d2fc3594d441 | 666,476 |
import sys
def in_interactive():
"""Based on: https://stackoverflow.com/a/2356427/1565454"""
return hasattr(sys, "ps1") | da3a68808d10c881e9d9502cca81bf3a6b7049d9 | 666,477 |
def _sdss_info_to_urlpath_(baseurl, basename, bands=None):
""" band name inside the sdss url. *bands is not used.*
simply does:
"return baseurl+'/'+basename+'.fits.bz2'"
"""
return baseurl+"/"+basename+".fits.bz2" | 54fbad2cd0689c1633d05d21eeb88d185b52595b | 666,478 |
def numonlynoblank(tovalidate):
"""Returns T or F depending on whether the input is a single character in 0-9, or ."""
return tovalidate.isdecimal() | (tovalidate == '.') | 8882f1c94cdc6abff4de889aecbb455fd66193db | 666,479 |
def validate_blockchain(block):
"""Validate the submitted chain. If hashes are not correct, return false
block(str): json
"""
return True | 99b544d3c16a2a0c7dc8292d18061338d3d2079f | 666,480 |
import six
def to_unicode(session):
"""Convert incoming value to unicode string
:param session: Kim pipeline session instance
"""
return six.text_type(session.data) | 666d93a28fe2c233ef55fa0847b7075603e2e518 | 666,481 |
def prompt(text):
""" Add >>> and ... prefixes back into code
prompt("x + 1") # doctest: +SKIP
'>>> x + 1'
prompt("for i in seq:\n print(i)")
'>>> for i in seq:\n... print(i)'
"""
return '>>> ' + text.rstrip().replace('\n', '\n... ') | 76389b51e5c6095282e779cc19c73239840279f9 | 666,482 |
def increment(string):
"""
for "A", return "B"
for "AC", return "AD"
After AZ comes `A[`. That's OK for my purposes.
"""
rest = string[:-1]
last = chr(ord(string[-1]) + 1)
#print rest+last
return rest + last | 5b7ce40a24cda7d80f7d4f289677f2a67d636d7d | 666,484 |
def set_carry(self) -> int:
"""
Set the carry bit.
Parameters
----------
self: Processor, mandatory
The instance of the processor containing the registers, accumulator etc
Returns
-------
self.CARRY
The carry bit
Raises
------
N/A
Notes
-----
N... | 0f1d90b0665b4b2d25ebc11bb4302899d60bbf54 | 666,485 |
def read_quota_file(file_quota):
"""Read the quota information from a file generated with the command
'mmrepquota -j <fileset>."""
fin = open(file_quota,'r')
text = fin.readlines()
fin.close()
# Remove some control characters from the input.
text = [line.strip() for line in text]
retur... | 2512814fbebcee79747ff906672b91b6fbc0ac84 | 666,486 |
def cellsDirs(pos, size):
"""
Returns all possible directions in a position within a 2D array of given size.
"""
x, y = pos
width, height = size
dirs = []
if x > 0: dirs.append([-1,0])
if x < width-1: dirs.append([1,0])
if y > 0: dirs.append([0,-1])
if y < height-1: dirs.append(... | 2a7615e15f3e268ceb0f4fdb09cca140471bebfa | 666,487 |
def extend_vocab_OOV(source_words, word2idx, vocab_size, max_unk_words=15):
"""
Map source words to their ids, including OOV words. Also return a list of OOVs in the article.
WARNING: if the number of oovs in the source text is more than max_unk_words, ignore and replace them as <unk>
Args:
sour... | 1a71eaf5a5450d694be7566c406fb5ff0c97000e | 666,488 |
def get_idx_scores_mapping(scores):
"""Get mat index to scores mapping."""
return {i: score for i, score in enumerate(scores)} | 6c21eb1348b76731764e1624e38105c4af00409a | 666,489 |
def parse_metadata_json(data):
""" Function to parse the json response from the metadata or the
arxiv_metadata collections in Solr. It returns the results as a
list with the sentence, file name and title."""
# docs contains authors, title, id generated by Solr, url
docs = data['response']['docs']
... | 42d7b850513f76bc0f14d50012758657f78756f0 | 666,490 |
def _parse_color_string(colors, n=None, r=False, start=0, stop=1):
"""
Parses strings that are formatted like the following:
'RdBu_r_start=0.8_stop=0.9_n=10'
'viridis_start0.2_r_stop.5_n20'
'Greens_start0_n15'
"""
if isinstance(colors, str):
color_settings = colors.split('_')
... | c7ca24e7a8d345f94cdbabd623c60756aeeefe34 | 666,492 |
def select_dataset_file_for_each_worker(files, f_start_id, worker_num,
worker_index):
"""
Spliting the train file according to the worker index.
"""
num_files = len(files)
if worker_num > num_files:
remainder = worker_num % num_files
data_fil... | 8d98a81c47d4aa81ec211a8e7ca1a7a9e62bc1c0 | 666,493 |
def calc_years(seconds: int) -> int:
"""
Calculate years
:param seconds:
:return:
"""
return seconds // (60 * 60 * 24 * 365) | 21dc5f6354575f59c9f035d86c7d70ea3b797a98 | 666,494 |
import os
import pickle
def depickler(trainx: str, trainy: str, valx: str, valy: str, datadir: str) -> tuple[str, str, str, str]:
"""
Loads a set of pickle files for training neural networks
Args:
trainx (str): Training data file path
trainy (str): Training labels file path
valx (... | d89354c78faf69346081114b0e469745b4bf16ae | 666,495 |
def flip_box(box):
"""
box (list, length 4): [x1, y1, w, h]
"""
# Get top right corner of prediction
x1 = box[0]
y1 = box[1]
w = box[2]
h = box[3]
topRight = (x1 + w, y1)
# Top left corner of flipped box is:
newTopLeft = (1024. - topRight[0], topRight[1])
return [newTopLe... | 00e016de24d1a29d8845cc11f9fd7eac36c57dc0 | 666,496 |
import re
def multisplit(delimiters, string, maxsplit=0):
"""from SO. takes a list of delimiters and a string, and
returns a list of split string
"""
assert isinstance(delimiters, list)
regexPattern = '|'.join(map(re.escape, delimiters))
return re.split(regexPattern, string, maxsplit) | 29ef8df05d5bbeb07ea1ab884bab57f96de27a01 | 666,497 |
def preprocess_remove_unknow_paragraph(data: str, **kwargs):
"""
移除如下无用文本:
简体 | 繁体 | 无障碍阅读 | RSS订阅 国家税务总局 | 江西省人民政府 微博 微信 本站热词:税务缴税营改增税收增值税 首页 信息公开 新闻动态 政策文件 纳税服务 互动交流 首页 >信息公开>
:param data:
:param kwargs:
:return:
"""
special_glt_res = data.find('信息公开>')
if data.startswi... | ece9f8551e4a345f38a98885e2ff8a3e9147324a | 666,498 |
def bfd_is_auth_used(pkt):
""" is packet authenticated? """
return "A" in pkt.sprintf("%BFD.flags%") | 8f4949aaf264af040ed0e19039dea944739c63a4 | 666,499 |
def split(str, sep=None, maxsplit=-1):
"""Return a list of the words in the string, using sep as the delimiter string."""
return str.split(sep, maxsplit) | 013c637e8f6aa00b7389371f366f0fe2a06172b7 | 666,500 |
def inner_product(L1,L2):
"""
Inner product between two vectors, where vectors
are represented as alphabetically sorted (word,freq) pairs.
Example: inner_product([["and",3],["of",2],["the",5]],
[["and",4],["in",1],["of",1],["this",2]]) = 14.0
"""
sum = 0.0
i = 0
... | 4d93b0a6b36d2a2749486046e1693c4fb6e721ad | 666,501 |
import os
def is_dos_short_file_name(file):
""" examine if the given file is in the 8.3 form.
"""
fname, ext = os.path.splitext(file)
proper_ext = len(ext) == 0 or (2 <= len(ext) <= 4) # the ext contains the dot
proper_fname = file.isupper() and len(fname) <= 8
return proper_ext and proper_fn... | c4c5b85bf63d08cc31ded2d471b0c63d48d6c0f0 | 666,502 |
def getversion(idf):
"""return the version number"""
versions = idf.idfobjects["VERSION"]
return versions[0].Version_Identifier | 8ade54e1d9d8c69c9f6821121c1a6f8c2320afa5 | 666,504 |
from datetime import datetime
import os
def create_new_logfile(p):
"""
Creates a new log file
:param p: full path to directory in which the new log file is created
:return: full path to created log file
"""
# define filename
time_str_fn = datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
#... | be8dd9e871b43d8c6279ec3b67042364638c8b2c | 666,505 |
import asyncio
def async_test(loop=None, timeout=None):
"""
Decorator enabling co-routines to be run in python unittests.
:param loop: Event loop in which to run the co-routine. By default its ``asyncio.get_event_loop()``.
:param timeout: Test timeout in seconds.
"""
loop = loop or asyncio.ge... | b4d52e6bd46a081141f8e757b07fa76f2c10e1c2 | 666,506 |
def scrub_object(obj):
"""Remove protected fields from object (dict or list)."""
if isinstance(obj, list):
return [scrub_object(item) for item in obj]
elif isinstance(obj, dict):
clean_dict = {key: scrub_object(value)
for key, value in obj.items()
... | cfb24c1a7b63bb33364fd780d2ee21e1854b4381 | 666,508 |
def lopen_loc(x):
"""Extracts the line and column number for a node that may have an opening
parenthesis, brace, or bracket.
"""
lineno = x._lopen_lineno if hasattr(x, "_lopen_lineno") else x.lineno
col = x._lopen_col if hasattr(x, "_lopen_col") else x.col_offset
return lineno, col | 75545bb527dac4ab0ceffffbbd2c3f028ac4f898 | 666,509 |
def string_from_time(datetime_string):
"""
:param datetime_string: datetime string
:return: formatted time string
"""
return datetime_string.strftime("%Y-%m-%d_%H-%M-%S") | 2b86739f9f19ea5c2f8b8aef3d445807de8f0b18 | 666,510 |
import uuid
def generate_ids():
"""
Generates UUIDs for each of the profile's payloads.
:returns: Dictionary of payload identifiers
"""
payloads = ['info', 'ad_tracking', 'airdrop', 'store', 'siri', 'desktop', 'desktop_services', 'dock', 'energy',
'filevault', 'finder', 'firewall'... | 7230b2ac3799f7e04363ae7238997dc9af5c158f | 666,511 |
import torch
def wrapper_model( model):
"""
a model wrapper to deal with some overhead work
"""
model = model.cuda()
def my_wrapper_model(x):
x = torch.Tensor(x).long().cuda()
result = model(x).cpu().detach().numpy()
return result
return lambda x:my_wrapper_model(x) | 4311278bf9c2e2561ee5ac260a7b93d44b5e8f5a | 666,512 |
import sys
def g_fxn(depth=1):
"""Get the calling function name.
Args:
depth: caller function depth in the call stack (int)
Returns:
caller function (str)
"""
return sys._getframe(depth).f_code.co_name | b499875f067874f0be4354e423189da1ed8df3e6 | 666,513 |
import os
def has_freesurfer():
"""Check for Freesurfer."""
return 'FREESURFER_HOME' in os.environ | 508a75eecff4f1ab1c28ab88a0c8d78cdb8a6747 | 666,514 |
import torch
def to_tensor(pic):
"""Convert a ``numpy.ndarray`` to tensor.
See ``ToTensor`` for more details.
Args:
pic (numpy.ndarray): Image to be converted to tensor.
Returns:
Tensor: Converted image.
"""
img = torch.from_numpy(pic.transpose((2, 0, 1)))
return img.f... | 2365b6777dfc2195afd31f7e26148ba82fab692a | 666,515 |
def execute_with_client(quiet=False,
bootstrap_server=False,
create_client=True):
"""Decorator that gets a client and performs an operation on it."""
def wrapper(f):
def wrapper2(self, *args, **kwargs):
client = self.current_client(
... | bf9bda39ba20072c6b257d06c4b2351d36f95e96 | 666,516 |
def factorial(number):
"""
Factorial Using Recursion
Example :
5!
Factorial is denoted by !
Factorial(5) : 5 X 4 X 3 X 2 X 1 = 120
"""
if number == 0:
return 1
else:
print(f"{number}*", end=" ")
return number * factorial(number-1) | 1ef2c2c1a4f3213208b89e956f1f15976abf8044 | 666,517 |
def same_from_to(df):
"""
Cette fonction supprime les matchs supperposes.
Ceux-ci genere des vitesses a zero km/h dans la suite
du script.
"""
for i in df.index:
# Recuperer les lat/long
cur_long_from = df.loc[i,'long_from']
cur_lat_from = df.loc[i, 'lat_from']
... | b28bb413db59e6cc4ce2f56b567f07c09c729f3f | 666,518 |
def spark_cls_reduce(self):
"""Reduce function for Spark classes.
Spark objects connected to distributed data cannot be stored in Pickle
files. This custom reduce function enables Pickling of a string
representation of the Spark object.
"""
return str, (str(self),) | 664484882c8781e1698255402cc492b8805cc0cf | 666,520 |
def set_tags(request, tags, value):
"""Устанавливает get параметры в зависимости
от выбранных тегов"""
request_object = request.GET.copy()
if request.GET.get(value):
request_object.pop(value)
elif value in tags:
for tag in tags:
if tag != value:
request_ob... | 500e82a154fc2d39c0ebfb11163ef3c8f6bade93 | 666,521 |
from typing import Optional
def percent(flt: Optional[float]) -> str:
"""
Convert a float into a percentage string.
"""
if flt is None:
return '[in flux]'
return '{0:.0f}%'.format(flt * 100) | 937a1608be53460369210cdce9150547bcb1fe56 | 666,522 |
def stripe_to_eta(stripe):
"""Convert from SDSS great circle coordinates to equatorial coordinates.
Parameters
----------
stripe : :class:`int` or :class:`numpy.ndarray`
SDSS Stripe number.
Returns
-------
:class:`float` or :class:`numpy.ndarray`
The eta value in the SDSS (... | 89641df942911c9613ad4da82f498641043f2f6e | 666,523 |
def is_anagram(word: str, sorted_word, candidate):
"""
Compare between two strings and return True
in case <candidate> is anagram of <word>.
Otherwise return False.
:param word:
:param sorted_word:
:param candidate:
:return:
"""
# filter identical words:
if word.lower() != ... | 7984f5b54fa0d08f6952ac79790f01029df40631 | 666,524 |
def getBottomRight(listPts):
"""Returns the index of the bottom right most point, used in the start of some of
the algorithms
"""
points = sorted(listPts, key=lambda x: (x.point[1], -x.point[0]))
return listPts.index(points[0]) | f3e7211136206a9aa0881fc33ea9379950828e47 | 666,525 |
def nd_cross_variogram(x1, y2, x2, y1):
"""
Inner most calculation step of cross-variogram
This function is used in the inner most loop of `neighbour_diff_squared`.
Parameters
----------
x, y : np.array
Returns
-------
np.array
"""
res = (x1 - x2)*(y1 - y2)
return r... | 63197005b9340b4cc4cd5c187d8e8fe4745339e5 | 666,526 |
def c_any(iterable):
"""
Implements python 2.5's any()
"""
for element in iterable:
if element:
return True
return False | e2bb727d1c58d17354040969582be77ea739622c | 666,527 |
def get_pca_options(defaults=None):
"""Adding arguments for the pca subcommand
"""
if defaults is None:
defaults = {}
options = {
# Input fields to include in the PCA.
'--pca-fields': {
"action": 'store',
"dest": 'pca_fields',
"default": def... | b989795bc51719a7068f366d81e89a9f3368874b | 666,528 |
def is_set(b: int, val: int, v6: bool) -> bool:
"""Return whether b-th bit is set in integer 'val'.
Special case: when b < 0, it acts as if it were 0.
"""
if b < 0:
b = 0
if v6:
return val & (1 << (127 - b)) != 0
else:
return val & (1 << (31 - b)) != 0 | 62326cf74a9e21e9ef2a321f35b1f00e76a2cb90 | 666,529 |
def create_legend_panel(workflow_stat):
"""
Generates the bottom level legend panel content.
@param workflow_stat the WorkflowInfo object reference
"""
panel_str ="<script type=\"text/javascript+protovis\">\n\
var hc_footerpanel = new pv.Panel()\n\
.width(hc_footerPanelWidth)\n\
.height(hc_footerPanelHeight)\n\
.... | 68410a730ec1364216cf95057b930965061d0e44 | 666,530 |
import json
def to_string(obj):
"""Process Sigma-style dict into string JSON representation"""
return json.dumps(obj) | 10f7648f6f88ac8a0094fb675acf7dc9eee315e0 | 666,531 |
import numpy as np
def imscale(im, to_mean, print_ratio=False):
"""
input image [0,1], the aiming mean\n
if print_ratio then do so\n
return the scaled image
"""
assert(np.max(im)<=1)
ratio = to_mean/np.mean(im)
im = im*ratio
im = np.maximum(im,0.)
im = np.minimum(im,1.)
if ... | 791d5713ff16afcff6f9580f5b5c991b43541498 | 666,532 |
def get_normalized(row: int, col: int, plain_text_no_empty_chars: str) -> list:
"""
The plaintext should be organized in to a rectangle.
Normalized text is x characters long, dictating a rectangle with c * r
:param row:
:param col:
:param plain_text_no_empty_chars:
:return:
"""
norm... | 51f8a4938e9efebbc451acd1527c9bc3e3a75ebc | 666,533 |
import sys
import os
def resolveFilePath(filePath):
"""
Converts a file path into a module path compatible with import statements.
:type filePath: str
:rtype: str
"""
# Normalize file paths
#
pythonPaths = [os.path.normpath(x) for x in sys.path]
filePath = os.path.normpath(os.pat... | 634f163f468e44ffbdbf96861ba4774dff754483 | 666,534 |
def get_chromosome_names_in_GTF(options):
""" Function to get the list of chromosome names present in the provided GTF file. """
chr_list = []
with open(options.annotation, "r") as GTF_file:
for line in GTF_file:
if not line.startswith("#"):
chr = line.split("\t")[0]
... | 958708fc2564b4d33591701a9f3cf3bd12981b09 | 666,535 |
from typing import List
def tablinks(tabs: List[str]) -> str:
"""Adds list of tabs/sections for the reports that are able to be clicked. For every 6 tabs we push them onto a new line.
Parameters
----------
tabs : List[str]
List of tabs/sections for the reports.
Returns
-------
st... | ed3d82028b400a9aaf80c96cde42b1bd4a220696 | 666,536 |
from typing import Any
def process_arguments(**arguments: Any) -> dict[str, Any]:
"""Composition of behaviors intended prior to dispatching to library."""
return arguments | a0e079a243ef49e06a871c9339bfcaf7ea66d946 | 666,538 |
def mash_infusion(
target_temp, initial_temp, grain_weight, water_volume, infusion_temp=212
):
"""
Get Volume of water to infuse into mash to reach scheduled temperature
All temperatures in F.
http://howtobrew.com/book/section-3/the-methods-of-mashing/calculations-for-boiling-water-additions
... | 258fbe486201629f13868d080ae3a712a6bac743 | 666,539 |
from pathlib import Path
import sys
import os
import re
def getCondaVTK():
"""get the VTK installed by conda"""
vtk_libs = [
"vtkCommonComputationalGeometry",
"vtkIOCore",
"vtkIOLegacy",
"vtkCommonExecutionModel",
"vtkCommonDataModel",
"vtkCommonTransforms",
... | a4a5ef22119b986fe65ea72c395f1a4cebbfe453 | 666,540 |
def parse_args(argv):
"""Parse Alfred Arguments
Args:
argv: A list of arguments, in which there are only two
items, i.e., [mode, {query}].
The 1st item determines the search mode, there are
two options:
1) search by `topic`
2) search ... | a5a401abda9c00ecd4d21f6b361edfaf0b527bda | 666,541 |
def bool_like(value, name, optional=False, strict=False):
"""
Convert to bool or raise if not bool_like.
Parameters
----------
value : object
Value to verify
name : str
Variable name for exceptions
optional : bool
Flag indicating whether None is allowed
stric... | 5383d41471a5a780b07455dfd8d98c47df680ee8 | 666,542 |
def import_custom_event(my_module):
"""Import CustomEvent from my_module."""
return my_module.CustomEvent | c64c06b8c76754c80b9928a3c6f03baae974d6da | 666,543 |
from typing import MutableMapping
from typing import Optional
from typing import List
def extract_dependencies(content: MutableMapping) -> Optional[List[str]]:
"""
Extract the dependencies from the Cargo.toml file.
:param content: The Cargo.toml parsed dictionnary
:returns: Packages listed in the dep... | 7daed68e970210509979acdc600f0f11a68b266c | 666,544 |
def identity(obj):
"""Returns obj."""
return obj | 0ea589df24d3b480b604b9c67e56011d9b0102a6 | 666,545 |
from typing import Mapping
def subdict(d: Mapping, keys=None):
"""Gets a sub-dict from a Mapping ``d``, extracting only those keys that are both in
``keys`` and ``d``.
Note that the dict will be ordered as ``keys`` are, so can be used for reordering
a Mapping.
>>> subdict({'a': 1, 'b': 2, 'c': 3,... | ffd0578fa0ad642f6573ae392cb17e8c9220569f | 666,546 |
import json
def read_file(file):
"""
Reads file and return information in needed format.
"""
file = open(file, "r", encoding="utf-8")
data = json.load(file)
if type(data) == dict:
data = [data]
return data | 6255947fff3eb21b4b91ed11b7bb7ccf22ca7a82 | 666,547 |
import re
def validate_name(name, minlength=1, maxlength=30, fieldname='name'):
"""Validates a name with length and regular expression criteria.
Parameters
----------
name : str or QString
Name to be validated.
minlength : int
The minimum length of the name.
maxlength : in... | 731a0d844ef88250c2aa47323215d96f6e3a9d9e | 666,548 |
import yaml
def dump(obj, ofile):
"""dump yaml to an output file"""
with open(ofile, "w", encoding="utf-8") as f:
return yaml.safe_dump(obj, f, allow_unicode=True, indent=4) | d869f666905388df2a94fcca6648ae346dc513ef | 666,549 |
def hardlim(n):
"""
Hard Limit
"""
if n < 0:
return 0
else:
return 1 | 1d8f3cc3e6bbbdb59085bddbcf5fe255ec2c538f | 666,550 |
def comp_height(self):
"""Compute the height of the magnet
Parameters
----------
self : MagnetType13
A MagnetType13 object
Returns
-------
Hmag: float
The magnet's height [m]
"""
return self.Hmag | 8f3a1b09d0ab091b364abc418815d8fbe18e0e3b | 666,551 |
def strip_mate_id(read_name):
"""
Strip canonical mate IDs for paired end reads, e.g.
#1, #2
or:
/1, /2
"""
if read_name.endswith("/1") or read_name.endswith("/2") or \
read_name.endswith("#1") or read_name.endswith("#2"):
read_name = read_name[0:-3]
return read_nam... | 13d2467b837462c2a05ad0813cddc0279304d3d9 | 666,552 |
def build_content_type(format, encoding='utf-8'):
"""
Appends character encoding to the provided format if not already present.
"""
if 'charset' in format:
return format
return "%s; charset=%s" % (format, encoding) | 771eecd94e37cab1f3ffbf9a671bd77fe3639be1 | 666,553 |
def Inside_triangle(p, a, b, c):
""" inside_triangle(p, a, b, c)
p: point (x,y)
a, b, c: vertices of the triangle (x,y)
>>> inside_triangle(p, a, b, c)
"""
detT = (a[0]-c[0])*(b[1]-c[1]) - (a[1]-c[1])*(b[0]-c[0])
lambda1 = ((b[1]-c[1])*(p[0]-c[0]) - (b[0]-c[0])*(p[1]-c[1])) / detT
lambd... | 78aa765746d12cdc7c1b4a4c75d2a311584a5da4 | 666,554 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.