content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def camel2snake(txt: str) -> str:
"""Convert a CamelCasedString to a snake_cased_string"""
txt = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", txt)
txt = re.sub("__([A-Z])", r"_\1", txt)
txt = re.sub("([a-z0-9])([A-Z])", r"\1_\2", txt)
return txt.lower() | 7af8a13fb5543473d179d4104339888bca8b62dd | 569,642 |
def get_glyph(entity_type):
"""
Generates appropriate Font Awesome icon strings based on entity type strings, such as
a person icon (fa-male) for the 'person' entity, etc.
:param entity_type: String specifying the entity type to be visualized
:return: HTML string with the corresponding Font Awesome icon
"""
if ... | deba5b78515b7b9111a0ee7ce7e393d6efd9821d | 569,646 |
def _validate_float(s, accept_none = False):
"""
A validation method to convert input s to float or raise error if it is not convertable
"""
if s is None and accept_none :
return None
try:
return float(s)
except ValueError:
raise ValueError('Could not convert "%s" to float' % s) | fa457dcc2e775d9704b2628caaac5b031049657b | 569,650 |
import json
def read_alias_mapping(file_path):
"""Read and transform agent alias listing from a .json file."""
if not file_path:
return {}
with open(file_path, "r") as mapping:
data = mapping.read()
obj = json.loads(data)
aliases = {v: k for k, vs in obj.items() for v in vs}
... | 0042b1119dbd9079385103a7896b1799c8d2e44a | 569,653 |
import torch
def batch_mvp(m, v):
"""Batched matrix vector product.
Args:
m: A tensor of size (batch_size, d, m).
v: A tensor of size (batch_size, m).
Returns:
A tensor of size (batch_size, d).
"""
v = v.unsqueeze(dim=-1) # (batch_size, m, 1)
mvp = torch.bmm(m, v) #... | 810da2273dc568a63f18a9cca1caf4c448796778 | 569,654 |
def ToUnixLineEnding(s):
"""Changes all Windows/Mac line endings in s to UNIX line endings."""
return s.replace('\r\n', '\n').replace('\r', '\n') | 998a606d58bc5bc0407cd7b53509eb66c1250ecc | 569,657 |
def get_concat_peptide(front_coord_pair, back_coord_pair, front_peptide, back_peptide, strand, k=None):
"""
Get the concatenated peptide from possible match peptide.
Parameters
----------
front_coord_pair: str. coordinate string for the front exon pair.
back_coord_pair: str. coordinate string fo... | 704f0d364493233a1a95538844ef92e16838337e | 569,659 |
def ezip(e, l):
"""
Zips an element on the left side of a collection.
Examples
--------
Let us define a list `l`:
>>> l = [0, 1, 2]
Let us zip an element 'id' for each element of the l.
>>> ezip('id', l)
[('id', 0), ('id', 1), ('id', 2)]
"""
return map(lambda x: (e, x), l) | 626dc05a79631cd597162b77825bd4bc67dd75ed | 569,661 |
import json
def writeJson(file_name, data):
"""
Writes given dict data to given file_name as json.
Args:
file_name (string): Path to write data to.
data (dict): dict to write to given file_name.
Returns:
(string): full path where json file is.
"""
with open(file_name... | e17092d15ae1988ea9b34045834b23a8bef82219 | 569,665 |
def potential_temperature(
temp,
press,
gas_constant=287.058,
c_p=1039,
p_ref=100_000,
):
"""
Calculate potential temperature
----------
temp : xarray.DataArray
Atmospheric temperature [K].
press : xarray.DataArray
Atmospheric pressure [Pa].
gas_constant : flo... | 9c6a96f7fba0a29e664156ca0627a09bfb9c710e | 569,666 |
def filtdict(d, *keys):
"""
Keep dict items with the given keys
filtdict({"a": 1, "b": 2}, "b")
{'b': 2}
"""
return type(d)(i for i in d.items() if i[0] in keys) | c29b60ba14b72ffa8edfaa0f9c1c2c3e7ebc8860 | 569,668 |
def UniqueElements(x: list) -> list:
"""Returns unique elements of a list (not order preserving)."""
keys = {}
for e in x:
keys[e] = 1
return list(keys.keys()) | 258e725738f6f1d2b9637937d2e779e96e3b7341 | 569,670 |
def set_phone_silent_mode(log, ad, silent_mode=True):
"""Set phone silent mode.
Args:
log: Log object.
ad: Android device object.
silent_mode: set phone silent or not.
This is optional, default value is True (silent mode on).
Returns:
True if set successfully.
... | c12a32ea1d69ddde2748cbcf005949432f6c285c | 569,677 |
def pronoun_instance_dist(novel, words):
"""
Takes in a novel and list of gender pronouns, returns a list of distances between each
instance of a pronoun in that novel
>>> from gender_novels import novel
>>> summary = "James was his convicted of adultery. "
>>> summary += "wh... | 6bd4cf1b3b968c395b230f1a23d4d07325029659 | 569,678 |
import pickle
def encode_message(topic, data):
"""Encode a message for sending via 0MQ
Given a string topic name and a pickle-able data object, encode and prep
the data for sending via `send_multipart`
Returns a list of the form:
[
Bytes object of String (UTF-8),
Pick... | 73a083cc0edc574baf9843f245b3ee3a42ab35a0 | 569,679 |
import math
def ER_Theory(N,Kappa) :
"""
Apprixmate expression for the mean algerbaic connectivity of
ER graphs.
This formula is presented in:
Jamakovic, A., and Piet Van Mieghem. "On the robustness of complex networks by using the algebraic connectivity." NETWORKING 2008 Ad Hoc and Sensor Networks, Wireles... | 96d27d32be3ea5f1079776a3cb8ce89213ab8fbf | 569,683 |
def train_test_split(dataset, start, end):
"""Reserve dataset.examples[start:end] for test; train on the remainder."""
start = int(start)
end = int(end)
examples = dataset.examples
train = examples[:start] + examples[end:]
val = examples[start:end]
return train, val | b25d6acb2d5714f9261ae03f4379eeebfbd6b425 | 569,693 |
def _handle_validation_error(exc, context, response):
"""Generic error for 'ValidationError' exception."""
response.data = {
"error": "ValidationError",
"message": "Отправленные данные не прошли проверку",
"details": response.data,
}
return response | f6e3e227ac6c3853d3382b38ef6e99ddd56813b6 | 569,695 |
def align(vaddr, page_size=4096):
"""page align an address"""
slack = vaddr % page_size
pad = page_size - slack
aligned_vaddr = vaddr + pad
return aligned_vaddr | 209fa407f52c1b6a47d3b8e99d193dbd300c92ad | 569,698 |
def pipefunc(db, keys, funcname, *args, **kw):
"""Runs a pipeline with the given funcname on each given key.
This function is equivalent to:
[db.funcname(k, *args, **kw) for k in keys]
"""
p = db.pipeline()
func = getattr(p, funcname)
[func(k, *args, **kw) for k in keys]
return p.exe... | 97d760df7e7d414672affb1549125a8ff49b0079 | 569,701 |
def _get_node(view, f, *arg):
""" Find etree node for the field ``f`` in the view's arch
"""
return next((
n for n in view['tree'].iter('field')
if n.get('name') == f
), *arg) | f302fab464ee361770c01904f98979ccce7abee5 | 569,705 |
def size_to_str(size):
"""Converts a size, given in bytes length, to a string representation"""
sizes = ['bytes', 'KiB', 'MiB', 'GiB', 'TiB']
pos = 0
while size >= 1024:
size /= 1024
pos += 1
return '{:.2f} {}'.format(size, sizes[pos]) | 55b93623f4736beeb46f443b72dddc4d32cc3290 | 569,707 |
def _named(pattern, name):
"""Wraps a regex pattern in a named capture group"""
return f'(?P<{name}>{pattern})' | dbdcbc7e782f34249ebc5197f20ff383d28b091b | 569,718 |
import yaml
def load_config(filename="config.yaml"):
"""Load a .yml config file as a dictionary and return it."""
with open(filename, "r") as f_in:
return yaml.safe_load(f_in) | ee9f9f52d1aa42a05bf92585ef862c8a0f1fd947 | 569,719 |
import pathlib
import shutil
def copy_test_files(dest, source=None):
""" copy test images to temp directory, returns list of files copied """
if source is None:
source = pathlib.Path("tests/test_images")
else:
source = pathlib.Path(source)
files_copied = []
for source_file in ... | ec4e9131e751160f7df57abd158336a9c961fa86 | 569,721 |
def _shape_equal(shape1, shape2):
"""
Check if shape of stream are compatible.
More or less shape1==shape2 but deal with:
* shape can be list or tuple
* shape can have one dim with -1
"""
shape1 = list(shape1)
shape2 = list(shape2)
if len(shape1) != len(shape2):
return Fa... | baa31c193227a6474317ef4ab7617a55d7e7aec5 | 569,722 |
def _pooling_output_shape(
input_size, kernel_size, pad_l, pad_r, stride, dilation, ceil_mode
):
"""
Generates output shape along a single dimension following conventions here:
https://github.com/pytorch/pytorch/blob/b0424a895c878cb865947164cb0ce9ce3c2e73ef/aten/src/ATen/native/Pool.h#L24-L38
"""
... | a493ff3af672b675b670719b5d8a9a285162c148 | 569,724 |
from typing import List
from typing import Dict
from typing import Optional
def _payload(projects: List[str], identities: List[Dict], priority: int,
id: Optional[str], resource_types: Optional[List[str]]) -> Dict:
"""Create a cross-project resolver payload.
:param projects: List of target projec... | 0f9450bb7627b2cbb3a105f3e09718eff7fadce9 | 569,727 |
import warnings
def duration_in_dt(duration_in_sec: float, dt_in_sec: float) -> int:
"""
Return duration in dt.
Args:
duration_in_sec: duration [s] to be converted.
dt_in_sec: duration of dt in seconds used for conversion.
Returns:
Duration in dt.
"""
res = round(dura... | 23a33cf4f41b3ae632ad281272327451fd69e7cb | 569,728 |
def message_to_oscsysexpayload(message):
"""Convert a sysex message into an OSC payload string.
"""
return message.hex().replace(' ', '') | 78103aeae84f1ead27dfcae603362804ab4d9af5 | 569,730 |
def get_location_from_shapefile_record_name(shapefile_record_names_df, record_name):
"""
Get location for the shapefile record name given.
Args:
shapefile_record_names_df (pandas DataFrame) : dataframe of shapefile record names and the associated locations
location (str) ... | a726a50eea5512f82fbabf81d476f78a0383b86b | 569,731 |
def get_extension(name):
"""Returns the full extension for a given file.
Example: 'mytar.tar.gz' -> '.tar.gz'
"""
tmp=name.split('.')
ext=""
for s in tmp[1:]:
ext += "."+s
return ext | 2f447303987f2d791ce3f14e3d01f93c319d8902 | 569,732 |
def pandas_to_unique_df(idf,columns = 'source_ID', otype = 'list'):
"""
Take a dataframe, return a list or dictionary of dataframes from the uniques values of one of its colums.
Can be useful to plot basins_river more easily, I already needed it in some cases, I don't really remember why!
Bu... | 7c1115c294a1533588e890e8c3b54c1bd0a80db2 | 569,737 |
from typing import Union
from typing import Iterable
def wrap_scalar_value_in_list(value: Union[Iterable, int, str]) -> Iterable:
"""If a string or integer is passed, wrap it in a list."""
if isinstance(value, (int, str)):
return [value]
else:
return value | 186ce80e8032aa11275e8c9ee3b6b5e35c5b4117 | 569,739 |
def transformNull(requestContext, seriesList, default=0):
"""
Takes a metric or wild card seriesList and an optional value
to transform Nulls to. Default is 0. This method compliments
drawNullAsZero flag in graphical mode but also works in text only
mode.
Example:
.. code-block:: none
&target=transf... | 830f0f63a3fd85f6137b41a647ab53756b0e69df | 569,744 |
def _intersect_cut(shape, cutting_shape):
"""
intersect by cutting, so that the cutting shape defines
a part of the shape which is inside and a part which is
outside as two separate shapes.
"""
inside = shape.intersection(cutting_shape)
outside = shape.difference(cutting_shape)
return in... | 6406461b1c2555941b798c53948f28e4f96c35fb | 569,747 |
def print_metric(inp_dict, title=" ", verbose=True):
"""Prints metrics from dictionary"""
msg = ""
msg += f"\n\n{title}" + "<br />"
if verbose:
print(f"\n\n{title}")
for k_method, v_method in inp_dict.items():
msg += "<br />"
msg += f"{k_method}" + "<br />"
msg += "-"... | fd80e752ac5cd1fc290d6d1df04aab3ac90ce7e8 | 569,750 |
def create_mask_from_window(x):
"""
Creates a mask from an input matrix x, to identify the max entry of x.
Arguments:
x -- Array of shape (f, f)
Returns:
mask -- Array of the same shape as window, contains a True at the position corresponding to the max entry of x.
"""
### START CODE ... | 88a2d92857af3ec469242331b92a1c9dd48fc84b | 569,756 |
def subset_or_none(dict1: dict, dict2: dict) -> dict:
"""
If the keys of dict2 are a subset of the keys of dict1,
return a copy of dict1 updated with the values of dict2,
otherwise return an empty dict of the same type as dict1
"""
new_dict = dict1.copy()
new_dict.update(dict2)
if new_di... | c809bc00ed1731dc957951b4823c89fff5ee9e46 | 569,758 |
from pathlib import Path
def filename_for_plot(directory, zarr_path: str, qualifier: str = "") -> str:
"""Get a suitable output filename for a plot produced from a Zarr path"""
basename = Path(zarr_path).stem.replace(
".zarr", ""
) # handle ".zarr" and ".zarr.zip"
path = Path(directory, f"{ba... | 8361b4fc037c3bf3a28da1c0f9101b1dbac5d6e7 | 569,760 |
def recipient_format(first, last, addr):
""" Format receiption with email address and name if available """
if first == '' and last == '':
rec = addr
else:
rec = first+' '+last+' <'+addr+'>'
return rec | a356a5166d3ed0ea4fefa37393eea3b1768c837d | 569,761 |
def expandCommaSeparatedRanges(s):
"""
's' format - comma separated ranges or values
a-b,c,..,d,e-f,a etc.
Includes the first and the last value in the range
"""
range_list = s.split(',')
values = list()
for r in range_list:
# range a-b
if '-' in r:
... | 3bb2db4ca5e09021dd76322fd9c6670756cc78f2 | 569,763 |
def _min_dummies(dummies, sym, indices):
"""
Return list of minima of the orbits of indices in group of dummies
see `double_coset_can_rep` for the description of `dummies` and `sym`
indices is the initial list of dummy indices
Examples
========
>>> from sympy.combinatorics.tensor_can impor... | aa046ddfa9f26a161906e29a3681ff8358f6c8c0 | 569,765 |
def unpack(value, number=2, default=None):
"""Unpack given `value` (item/tuple/list) to `number` of elements.
Elements from `value` goes first, then the rest is set to `default`."""
if not isinstance(value, list):
if isinstance(value, tuple):
value = list(value)
else:
... | 9f5ec4f64bd81d1a656cdaf8b3e9cfe5ce4f8f6e | 569,767 |
def field2range(field):
"""Return the dictionary of swagger field attributes for a set of
:class:`Range <marshmallow.validators.Range>` validators.
:param Field field: A marshmallow field.
:rtype: dict
"""
validators = [
validator for validator in field.validators
if (
... | 57c84bc4ed248ecf0df3b27c5b59305880ed34b9 | 569,768 |
def _asls(y, baseline, p):
"""
The weighting for the asymmetric least squares algorithm (asls).
Also used by the improved asymmetric least squares algorithm (iasls).
Parameters
----------
y : numpy.ndarray, shape (N,)
The measured data.
baseline : numpy.ndarray, shape (N,)
... | 51fe324032c2d6a349aa98257140b7ce35f1dd5a | 569,769 |
def check_root_access(repos):
"""Return 1 iff the associated username is permitted to read REPOS,
as determined by consulting REPOS's Authorizer object (if any)."""
auth = repos.authorizer()
if not auth:
return 1
return auth.check_root_access(repos.rootname()) | b151f4c4d975c439166182bdab0172cf75bb60cf | 569,770 |
def uppercase(string: str) -> str:
"""Convert string into UPPER CASE.
Args:
string (:obj:`str`):
The string to convert.
Returns:
:obj:`str`: The UPPER CASED string.
"""
if not string:
return ""
return string.upper() | 52ba88ee9d26eba0b29bd3ba639f42caa18cdc22 | 569,771 |
def check_split_ratio(split_ratio):
"""
Checks that the split ratio argument is not malformed and if not transforms
it to a tuple of (train_size, valid_size, test_size) and normalizes it if
necessary so that all elements sum to 1.
(See Dataset.split docs for more info).
Parameters
--------... | e025550343ff071e59240b8a91f7df7f88536059 | 569,772 |
def _is_header(row: list) -> bool:
"""
Determine if a row is a header row.
Keyword arguments:
row -- the row to check
Returns: True if the row is a header row, False otherwise
"""
return row[0].strip().lower() == "company name" | 5701e1ed2fcc8520547725246aa301908bf1d3a3 | 569,777 |
def string_convert(string: str):
"""
将连字符格式转成小驼峰格式
example: user_name -> userName
"""
char_list = string.split("_")
# 首个单词不转换
for index, char in enumerate(char_list[1:], start=1):
char_list[index] = char.capitalize()
return "".join(char_list) | eb911982941320108fb35d01287d7124361ba6b8 | 569,781 |
import torch
import math
def double_phase_amp_phase(amplitudes, phases, three_pi=True, mean_adjust=True):
"""converts amplitude and phase to double phase coding
amplitudes: per-pixel amplitudes of the complex field
phases: per-pixel phases of the complex field
three_pi: if True, outputs values in ... | 888557d96922d60d04ff0e1246055a71157ec8fd | 569,782 |
def h_file_to_define(name):
"""
Convert a .h file name to the define used for the header
"""
h_name = name[:-2].upper()
h_name = "_" + h_name + "_H_"
return h_name | 5f2876229d39d1218a0f7731a4f0e4f17f8e34b5 | 569,787 |
def unique(pcset):
"""Removes duplicates from pcset."""
l = []
for x in pcset:
if x not in l:
l.append(x)
return l | d0b06dd2c93e3e63bfc5e2829e7aa3606ce30a61 | 569,793 |
def sir(w, t, p):
# pylint: disable=unused-argument
""" SIR: Simple model of disease spread
inputs:
w: vector of state variables [S,I,R]
where
S: Fraction of the population susceptible to the infection
I: Fraction on the population infected
R: Fraction of the population recov... | dc1174fccceb6e93be587025ca3e989e15a56def | 569,798 |
import json
def describe_recommendations(recommendations):
"""Returns a json string representation of recommendation with selected fileds.
Args:
recommendations: List(common.Recommendation)
"""
recommendations_sorted = sorted(recommendations, key=lambda x: x.principal)
data = []
for r in rec... | c2086ea29a75ce199be033669f346d5b0a7d9e54 | 569,799 |
def string_to_numbers(string):
"""
Convert a string to a list of numbers
:param string: Message as string
:return: Message as numbers
"""
vals = [ord(s) for s in string]
return vals | 53ffbcb4690aeb9bb349b0619be60f70cb9cdc29 | 569,800 |
def collect_errors(codebase, verbose=False):
"""
Collect and return a list of error strings for all `codebase`-level and
Resource-level errors. Include stack trace if `verbose` is True.
"""
errors = []
errors.extend(codebase.errors or [])
path_with_errors = [(r.path, r.scan_errors)
... | b8c5b7e91427431f826ac4d8db7c89564c5a756a | 569,801 |
def anySelected (tool, params, names):
"""Determine if any tool's named parameter value evaluates to True."""
anyTrue=False
for n in names:
if params[tool.i[n]].value: anyTrue=True
return anyTrue | 19eeca073157198b8b42c1e0b5ec4e5f70fbb57f | 569,802 |
import codecs
def read_file_content(path):
"""
Read file from given path
:param path: file path
:return: file content
"""
f = codecs.open(path, 'r', 'utf8')
content = f.read()
f.close()
return content | a4d7930397da9c73e4a36a348c73a85662012058 | 569,814 |
def extract_quantiles(in_dist, **kwargs):
"""Convert using a set of quantiles and the locations at which they are reached
Parameters
----------
in_dist : `qp.Ensemble`
Input distributions
Keywords
--------
quantiles : `np.array`
Quantile values to use
Returns
-----... | 84b5d889867dd4ebe540e2472ad3939e4624c32a | 569,816 |
from datetime import datetime
import re
def parse_iso_8601_timestamp(timestamp: str) -> datetime:
"""Parse a timestamp in ISO 8601 format to a datetime object."""
def shorten_to_milliseconds(match: re.Match) -> str:
return f"{match.group(1)}{match.group(2)[:6]}{match.group(3)}"
return datetime.s... | e20010234b8ba8d8ab681fbe830d51c23b018cfb | 569,817 |
def calculate_normalized_ged(data):
"""
Calculating the normalized GED for a pair of graphs.
:param data: Data table.
:return norm_ged: Normalized GED score.
"""
norm_ged = data["ged"]/(0.5*(len(data["labels_1"])+len(data["labels_2"])))
return norm_ged | b599d7c5ba0c5b75759a304abcad6d18604b8027 | 569,820 |
def get_global_dependency_results(global_result_dict, bear_instance):
"""
This method gets all the results originating from the dependencies of a
bear_instance. Each bear_instance may or may not have dependencies.
:param global_result_dict: The list of results out of which the dependency
... | 271f2adbd9d88c5f262bf15023ba4fba2de4d55a | 569,822 |
def user_input(prompt,default):
"""
Like 'raw_input' except that a default value can be specified.
"""
response = input(prompt+' ['+str(default)+']: ')
if response == '':
response = default
return response | b2f218ec53904f31bb28819c35b60c1170f12d73 | 569,826 |
def auto_raytracing_grid_size(source_fwhm_parcsec, grid_size_scale=0.005, power=1.):
"""
This function returns the size of a ray tracing grid in units of arcsec appropriate for magnification computations
with finite-size background sources. This fit is calibrated for source sizes (interpreted as the FWHM o... | d1536dc06b7de4df2f82a506291be603a0fdb557 | 569,828 |
def _error_message(thing, unit, value, path=None):
"""Format assertion error based on presence of path.
:param thing: Ownership type
:type thing: str
:param unit: Unit tested
:type unit: str
:param value: Actual value from test
:type value: str
:param path: Path tested
:type path: O... | d63e27e91d6217cffa6148b4a7aa9cf9ea767937 | 569,834 |
def highlight_row(row):
"""
highlight mutations in yellow and refseq in silver.
:param row: row of dataframe.
:return: row of colors.
"""
mut = row.mut
color_list = [""] * 7 + ["background-color: silver"] * 2 + ["background-color: yellow" if i == mut and i != 'N' else
... | a6cc8595a97a650ce8ef326af1326386d97ffa17 | 569,838 |
def get_nodename(soname, nodenames):
"""Generate DOT nodename."""
if soname in nodenames:
return nodenames[soname]
nn = len(nodenames)
seed = "".join([x if x.isalnum() else "_" for x in soname])
nn = "%s_%d" % (seed, nn)
nodenames[soname] = nn
return nn | 8dbe3bc405b3ad4604096c56d0f1ebe338adc958 | 569,845 |
def sort(s, reverse=False):
"""
Sort given string by ascending order.
If reverse is True, sorting given string by descending order.
"""
return ''.join(sorted(s, reverse=reverse)) | 2eafbf17b35c0ffa61e07de10e9cf434ff6b1169 | 569,846 |
def is_valid_role(user, role):
""" Check if role exists and is a server role """
for r in user.server.roles:
if r.name == role:
return True
return False | 328cc8353325ba701d122a1ceb52ce14216baf51 | 569,848 |
def get_taskid_atmptn(key_name):
"""
get jediTaskID and attemptNr from task attempt key name
"""
tmp_list = key_name.split('#')
jediTaskID = int(tmp_list[0])
attemptNr = int(tmp_list[1])
return jediTaskID, attemptNr | f3e7d96f61765fcb6efd58388bfab97e6aa0609e | 569,849 |
def dsys(self, kcn="", **kwargs):
"""Activates a display coordinate system for geometry listings and plots.
APDL Command: DSYS
Parameters
----------
kcn
Coordinate system reference number. KCN may be 0,1,2 or any
previously defined local coordinate system number.
Notes
--... | a89a12d6b85db4b3ccf305094dce510ce9d62169 | 569,855 |
from colorama import Fore, Style
from colorama import init
def show_supported(supported):
"""
Returns OK (in green) if supported evaluates to True, otherwise NOT OK (in red).
"""
try:
init()
startcolor = Fore.GREEN if supported else Fore.RED
stopcolor = Style.RESET_ALL
exc... | 9cecc3a18880364609e03fe9be45c250a96139c9 | 569,856 |
def list_of(conversion):
"""Generate conversion function to convert list of strings to list
of given type.
Caution: For integers representing boolean values, use conversion function
mfdnres.tools.bool_from_str, rather than simply bool.
>>> a = ["1","2"]
>>> list_of(int)(a)
[1,2]
A... | 22de88cdbb27588ee1ac8322b0490b33596f20a7 | 569,859 |
def createFreqDict(obj_list):
""" Function takes a list of items and create frequency map """
itemFreqMap = {}
for item in obj_list:
if item in itemFreqMap:
itemFreqMap[item] += 1
else:
itemFreqMap[item] = 1
return itemFreqMap | 675cb3b5cbaa4b356ebed7f4edd6e547d442f200 | 569,864 |
def _attrprint(d, delimiter=', '):
"""Print a dictionary of attributes in the DOT format"""
return delimiter.join(('"%s"="%s"' % item) for item in sorted(d.items())) | bdf71e201325d4219134d9f40df59725dea0d0e9 | 569,866 |
def pad(text, block_size):
"""
Adds PKCS7 padding to the text based on the block size.
Args:
text (str): The text to be padded.
block_size (int): The block size of the cipher.
Returns:
str: The padded text.
Raises:
ValueError: If the block size is not greater than ... | 55fa8404766f688ea4afc4b258808cedb6e3515c | 569,868 |
import random
def _sample_randint_on_boundary(upper, overweight_one=False) -> int:
"""Returns a random number in [1, upper) divisible by four, or 1."""
if overweight_one:
if random.random() < 0.5:
return 1
raw = random.randint(0, (upper - 1) // 4)
if raw == 0:
return 1
... | 72c088b69da93370546d7b1d228a8feaad553f20 | 569,871 |
def get_iiif_image_url(iiif_manifest):
"""Given a IIIF manifest dictionary, derives the value for the info.json
file URL, which can then be stored in the roll metadata and eventually
used to display the roll image in a viewer such as OpenSeadragon."""
resource_id = iiif_manifest["sequences"][0]["canvas... | 08ebad272edbf58578d615a17d858a103689eb55 | 569,872 |
def next_power_of_two(x: int) -> int:
"""
Get the next power of 2
:param x: int
:return: int. The next largest power of 2
"""
return 2 ** (x - 1).bit_length() | 9fbe0e06aa4e3325a1de38cbd5ccb4fe3e94851f | 569,876 |
def calc_padding(img_size,tile_size,tile_overlap):
"""
Calculates the padding needed to make an image an even multiple of tile size, given overlap
between tiles.
NOTE: With overlap, final dimensions are hard to visualize. The correct formula for width is
(((img_width // stride_w)-1) * stride_w... | 3192496136ed27d6c6b73ceec6026e1cc8188663 | 569,878 |
def int_or_float(x):
"""Return int or float value of x.
Args:
x (str): Value to convert.
Returns:
int or float:
Raises:
ValueError:
"""
try:
return int(x)
except ValueError:
try:
return float(x)
except ValueError:
rai... | 9c00267c0ade842cc9037b59e129ceaa15690f7a | 569,880 |
def generate_block(name, abstract, authors, contributors, types, tags, category,
img_url, article_url=None, deployment_url=None):
"""Generate json documentation for a training program block.
If both `article_url` and `deployment_url` are None, the block is assumed
to be a container f... | 6eea9125f8f459e68c4b057ea2cec27b22f14dfc | 569,881 |
def median(items):
###############################################################################
"""
>>> items = [2.3]
>>> median(items)
2.3
>>> items = [2.3, 8.1, 3.4, 1.5, 11, 3.42321]
>>> median(items)
3.4116049999999998
>>> items = [2.3, 8.1, 3.4, 1.5, 11, 3.42321, -3.1]
>>> me... | 4da56e982224abf4ecbf5ec31a21077bc0569747 | 569,882 |
import re
def unpack_contractions(text):
"""
Replace *English* contractions in ``text`` with their unshortened forms.
N.B. The "'d" and "'s" forms are ambiguous (had/would, is/has/possessive),
so are left as-is.
"""
# standard
text = re.sub(
r"(\b)([Aa]re|[Cc]ould|[Dd]id|[Dd]oes|[D... | d9ef9c7b2908c88b5471f760d6a76a7b168847c4 | 569,883 |
import math
def angle(point_1, point_2):
"""calculates the angle between two points in radians"""
return math.atan2(point_2[1] - point_1[1], point_2[0] - point_1[0]) | d91bb51e4d878a771311ff75a4cd55955e342a87 | 569,891 |
def FileDateToTimestamp(FDTimestamp):
"""
Turn a FILEDATE into a UNIX timestamp
"""
timestamp = (FDTimestamp - 116444736000000000) / 10000000;
return int(timestamp) | f64da4bedd81ad92a3575d1be67f25442b0a6ec9 | 569,894 |
import re
def validate_backup_window(window):
"""Validate PreferredBackupWindow for DBInstance"""
hour = r'[01]?[0-9]|2[0-3]'
minute = r'[0-5][0-9]'
r = ("(?P<start_hour>%s):(?P<start_minute>%s)-"
"(?P<end_hour>%s):(?P<end_minute>%s)") % (hour, minute, hour, minute)
range_regex = re.comp... | df6813d7ab00df18531fdf7aaf0590596586db7e | 569,897 |
import hashlib
def md5_convert(string):
"""
计算字符串md5值
:param string: 输入字符串
:return: 字符串md5
"""
m = hashlib.md5()
m.update(string.encode())
return m.hexdigest() | a4c38a73e2d4845734c7f2391ba5eb2858b33e8a | 569,900 |
def make_gene2wells_dict(fn, delim=',', header=True,
symbol_plate_well_ctrl=[0, 4, 6, 10]):
"""Produce a gene to well map from the annotation table file.
Parameters
----------
fn : string
The input filename. The file should be a comma or tab delimited
table.
... | 5d35645302601699f35565c18dcba408b1078835 | 569,901 |
def open_and_read(infile_path_and_name):
"""
opens a file and returns a long long long string
:infile_path_and_name: string of the path/path/txtFileName.txt from the current directory
"""
path = infile_path_and_name
with open(path, 'r') as file:
string = file.read().replace('\n', '')
... | 961b762e80c4e5c3287abbd6f064041ba7796a38 | 569,907 |
import torch
def mean_crossentropy_loss_alt(weights, targets):
"""
Evaluates the cross entropy loss
:param weights: torch Variable,
(batch_size, num_measures, seq_len, num_notes)
:param targets: torch Variable,
(batch_size, num_measures, seq_len)
... | 39b236f829886529da89237c5f4782ceee43b3d4 | 569,908 |
from datetime import datetime
from typing import Iterable
import requests
import re
def cors_get_station_lists_for_day(date: datetime) -> Iterable[str]:
"""
Given a date, returns the stations that the US CORS network
reports as available
"""
url = "https://geodesy.noaa.gov/corsdata/rinex/"
res... | 369a5de0c1ef2786cc03ce3160a0c6ef5a26bf30 | 569,909 |
def compose(scheme, authority, path, **kwargs):
"""Build an IRI out of constituent parts.
"""
return '{scheme}://{authority}{path}{query}{fragment}'.format(
scheme=scheme,
authority=authority,
path=path,
query='?{}'.format(kwargs['query']) if kwargs.get('query') else '',
... | c79a634f9c948ed9ef407eb110a25299a38a0e68 | 569,911 |
def is_pythagorean_triplet(a,b,c):
"""
Checks if a,b and c forms pythagorean triplet i.e., a^2 + b^2 = c^2
Parameters
----------
a : int
denotes positive integer a in a^2 + b^2 = c^2
b : int
denotes positive integer b in a^2 + b^2 = c^2
c : int
denotes positive integ... | e3b9ae0b05fdb57dcab068f6f391762e66bbedda | 569,915 |
import re
def GetMountPoint(mountlist, device):
"""
Example of mountlist:
/dev/sda1 on / type ext4 (rw)
proc on /proc type proc (rw)
sysfs on /sys type sysfs (rw)
devpts on /dev/pts type devpts (rw,gid=5,mode=620)
tmpfs on /dev/shm type tmpfs (rw,rootcontext="system_u:o... | f93ea3f1e1cf63b9cc0ef74f72b7919367b6c8d9 | 569,919 |
def print_decorate(msg,expr):
"""
Helper function to make a print decoration around lambda expression. It will print `msg`, and then return
the result of `expr`. If it typically used in expressions like
`lambda x: print_decorate("Processing {}".format(x), do_smth_with(x))`
:param msg: Message to pri... | 3abe040ec9e78c6d0e4357023972b13406914e1e | 569,923 |
def get_hijitreg_translations(flat):
"""
Parse a flatfile created by the ISIS program hijitreg and return a list of the average sample and line translations,
rounded to the nearest int.
Parameters
----------
flat : str
path to a flatfile (text file) created by the ISIS program hijit... | 942763837c9266288fbe448798c3e69bcc9c1b0f | 569,929 |
def update_field(pc, field, pc_data):
""" Updates field in-place.
"""
pc.pc_data[field] = pc_data
return pc | 9342ed03f202260f3eeec2c0c08ec64642d57838 | 569,937 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.