content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def class_of ( object ):
""" Returns a string containing the class name of an object with the
correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
'a PlotValue').
"""
if isinstance( object, str ):
return add_article( object )
return add_article( object.__class__.__na... | 673176ee78a0e302af099e892ff585638ff3e0cd | 58,594 |
from typing import List
from pathlib import Path
import glob
async def densenet_xgboost_weights() -> List[str]:
"""
Get available weights options for model.
"""
return {
'denseNet': [Path(f).as_posix().rsplit('/', maxsplit=1)[-1].split('.')[0]
for f in glob.glob("model_wei... | cf346645a53d9937995958a9752bef001d2ff3fe | 58,595 |
def build_from_sample(samples, total_size):
"""Restores the image from the list of coordinate tuples."""
image = np.zeros([total_size, total_size])
for sample in samples:
x = sample[0]
y = sample[1]
image[x, y] += 1
return image | 6ea19f1030e90c53e1d3726fec43af60ee3f1fec | 58,596 |
import torch
def eval_batch_s2cnn(mlp, s2cnn, data, batch_idxs, criterion, device_id=0):
""" evaluate a batch for the s2cnn """
geometry = data["features"]["geometry"][batch_idxs, ...]
atom_types = data["features"]["atom_types"][batch_idxs, ...]
atom_types_one_hot = to_one_hot(atom_types, NUM_ATOM_TYP... | a8f23d8f36c449ddff9940e937df938136aa129f | 58,597 |
def dropout_forward(x, dropout_param):
"""
Performs the forward pass for (inverted) dropout.
Inputs:
- x: Input data, of any shape
- dropout_param: A dictionary with the following keys:
- p: Dropout parameter. We drop each neuron output with probability p.
- mode: 'test' or 'train'. If ... | 6e867d67b726ac4e361ca424729e9293f3810940 | 58,598 |
def detect_spikes(df, spiky_var, sliding_window=624, z=4, daynight=False):
"""Detect spikes on slow data according to Papale et al. (2006)
Parameters
----------
df: pandas DataFrame that contains the spiky variable, a daytime key
(day=1, night=0)
spiky_var: string that designate the spiky v... | 586d71fbf220180697eb2842b8de3fe1d6adeef7 | 58,599 |
def hourly(interval):
"""Returns a schedule appropriate for establishing an hourly backup.
args:
interval: Hourly interval - every how many hours should
this backup run? [0 - 23]
minute: On what minute should this backup run? [0 - 59]
"""
return Schedule(ScheduleFrequency.Ho... | ecd8b3071a074d5bfe129912fb56b47a3104eb4d | 58,600 |
def bfi(value, msb, lsb, field):
"""! @brief Change a bitfield value."""
mask = bitmask((msb, lsb))
value &= ~mask
value |= (field << lsb) & mask
return value | f4a0145e6063acd00753709b82ff5bb520f34ece | 58,601 |
def GetAllSteps(id):
"""Gets all of the screenshots of a script."""
return db.GqlQuery('SELECT * FROM ScriptStep WHERE script_id = :1', id) | 2715a8a0478bb692dd2876ffeeccd6df7439ee8e | 58,602 |
def _parse_int(s, start, end):
"""Parse a number and check for overflows"""
result = 0
i = start
while i < end:
c = ord(s[i])
if ord("0") <= c <= ord("9"):
try:
result = result * 10
if result > 1000000000: # this is not going to overflow in CPy... | 9719efbdbbd230c26ec5824ca150fbcc1e062057 | 58,603 |
import numpy
from typing import Iterable
from typing import Tuple
def build_train_generator(X: numpy.array, y: numpy.array,
batch_size: int = 500) -> Iterable[Tuple[numpy.array]]:
"""
Builds the generator that yields features and their labels.
:param X: features.
:param y: b... | 70e11ac58b2abb2203218fbeedfc46dacb9313c7 | 58,604 |
def process_seq_data(data_map, states, projection_horizon):
"""
Split the sequences in the training data to train the decoder.
"""
outputs = data_map['outputs']
sequence_lengths = data_map['sequence_lengths']
active_entries = data_map['active_entries']
current_treatments = data_map['current_... | 4c0d1e7e2b59c7f62bc7fdaf4f474a9b52d513fa | 58,605 |
def outliers_tietjen(x, k, hypo = False, alpha = 0.05):
"""
Tietjen-Moore test [1]_ to detect multiple outliers in a univariate
data set that follows an approximately normal distribution.
The Tietjen-Moore test [2]_ is a generalization of the Grubbs' test to
the case of multiple outliers. If testin... | 4141bf238fbd74481cc1ac22063fb9af54cd4c41 | 58,606 |
def get_writer(experiment, **kw):
"""
Factory function returning the writer/executor for the passed experiment
in printing mode.
Invokes :func:`get_experiment_writer`.
:param experiment: The experiment for which to generate the robot worklists.
:type experiment: :class:`thelma.entities.experime... | af44c899419a64ed710417c429c1f517cf36d432 | 58,607 |
def sub(I1, I2):
"""Calculate the substraction of two intervals as another interval
Keyword arguments:
I1 -- the first interval given as a tuple (a, b)
I2 -- the second interval given as a tuple (c, d)
"""
(from1, to1) = I1
(from2, to2) = I2
return (from1 - max(from2, to2), to1 - min(f... | 832c6ee8f290fa57e1695e4e753b4ff1ef4489b9 | 58,608 |
def get_status_of_request():
"""Return the current status of the executing request."""
input_file = request.files['task_request']
task_status_request = Request_pb2.TaskStatusRequest()
task_status_request.ParseFromString(input_files.read())
if task_status_response.current_task_id == task_status_request.request... | 0ec5bf9b2ab9bcd3ac818978c0f4ffa60a9328dd | 58,609 |
def flood_path(starts, wall_func):
""" Returns a dict mapping a tile to it's next tile which is closest to a start """
frontier = deque(starts)
parents = {t: t for t in starts}
while frontier:
top = frontier.popleft()
for neighbor in top.neighbors:
if not wall_func(neighbor) ... | 485dcac83a5438f7c6e5ed9d5cb205acc48059a9 | 58,611 |
def boolean_to_format(value, target_format):
"""Convert bool to specified format"""
if target_format == float:
ret = float(value)
elif target_format == str:
if value == 1:
ret = "true"
else:
ret = "false"
else:
ret = value
return ret | bc8939fca5de285a7ad3dab93c18a0f75c4d3b9b | 58,612 |
def flat_list(source):
"""Make sure `source` is a list, else wrap it, and return a flat list.
:param source: source list
:returns: flat list
"""
if not isinstance(source, (list, tuple)):
source = [source]
r = []
list(map(lambda x: r.extend(x)
if isinstance(x, (list, tuple))
... | d118388794cdef72200ad43ab88d9f964b633851 | 58,614 |
def umfpack_zl_col_to_triplet(*args):
"""umfpack_zl_col_to_triplet(SuiteSparse_long n_col, SuiteSparse_long const [] Ap, SuiteSparse_long [] Tj) -> SuiteSparse_long"""
return __umfpack.umfpack_zl_col_to_triplet(*args) | 09823910f5ecfa7bc40cc0f8eeccaee5eeb8a01c | 58,615 |
def eval_simple_expr(row, tree):
"""Evaluate simple_expr"""
if tree[0] == 'IDENTIFIER':
return eval_identifier(row, tree[1])
elif tree[0] == 'STRING' or tree[0] == 'literal':
return eval_string(tree[1])
elif tree[0] == 'function_call':
return eval_function_call(row, tree[1])
... | 8e5f0ccddb983950bcf9f9ed71d6d07cb366a03f | 58,616 |
def rotate(img, angle, resample=False, expand=False, center=None):
"""Rotate the image by angle.
Args:
img (numpy ndarray): numpy ndarray to be rotated.
angle (float or int): In degrees degrees counter clockwise order.
resample (``PIL.Image.NEAREST`` or ``PIL.Image.BILINEAR`` or ``PIL.Im... | a300cb446bb776434b197972d0e7aa010a688112 | 58,617 |
def array_from_clipboard(*, dtype=None, ndim=None, **read_clipboard_kwargs):
"""
Returns an array of values from the clipboard.
"""
data = read_clipboard(**read_clipboard_kwargs)
return isopy.asanyarray(data, dtype=dtype, ndim=ndim) | fc7dfdc25f14fb24fd5818105887a6b1f1953e99 | 58,618 |
def odeA(K, xpart, ypart, z, zprime, conn_data, y):
"""Convert a connection integration problem to the
callback style used by scipy ODE solvers.
Parameters:
K : rank
xpart : Coefficient of dx in connection (function conn. data -> matrix)
ypart : Coefficient of dy in connection (funct... | feff6c5f67f000ab487eadea9552d7af1f1dd5ad | 58,619 |
def everything_in(req_dict):
"""Gets all requirements in a requirements dict."""
return uniqueify(req for req_list in req_dict.values() for req in req_list) | b42104c5a94e3799ebdd4b8b7c1bdea2cf5d0aa5 | 58,620 |
def mesh2UVmap(mesh_data):
"""
generate uv map from mesh data
:param mesh_data:
:return: uv position map and corresponding texture
"""
[uv_h, uv_w, uv_c] = default_uvmap_shape
vertices = mesh_data['vertices']
colors = mesh_data['colors']
triangles = mesh_data['full_triangles']
# ... | 906dcba5d38ecc2d045c51cb42b4004178acbb44 | 58,621 |
import math
def ruler(start, end, ticks=4, sub_ticks=4, absolute=False, snap=False, **kwds):
"""
Draw a ruler in 3-D, with major and minor ticks.
INPUT:
- ``start`` -- the beginning of the ruler, as a list,
tuple, or vector.
- ``end`` -- the end of the ruler, as a list, tuple,
or ve... | 761adf4d1c25ba461c457b5dc111c20963cfe37d | 58,622 |
def make_complete_graph(num_vertices, backend="python"):
"""
Constructs a complete graph.
The pairing function is: ``k = v1 + v2 * (v2 - 1) // 2``
:param int num_vertices: Number of vertices.
:returns: a 2 x K grid of (vertex, vertex) pairs.
"""
if backend == "python":
return _make... | 3e10512586967201b23b273caf559ffec9e0aafe | 58,623 |
def nms(dets, thresh, force_cpu=False, gpu_id=None):
"""Dispatch to either CPU or GPU NMS implementations."""
if dets.shape[0] == 0:
return []
if gpu_id is not None and not force_cpu:
return gpu_nms(dets, thresh, device_id=gpu_id)
else:
return cpu_nms(dets, thresh) | f0c66742cd079d6e989971683febe93aa3b81df3 | 58,624 |
def load_cnvs(cnvs_in, phenos):
"""
Load and filter de novo CNVs
"""
elig_chroms = ['chr{}'.format(k) for k in range(1, 23)]
cnvs = pd.read_csv(cnvs_in, sep='\t')
keep_rows = ((cnvs['sample'].isin(phenos.keys())) & \
(cnvs['chr'].isin(elig_chroms)) & \
(c... | 60042fa326e6fd9f3e07ed97423e12834f20605f | 58,625 |
def git_ref_from_eups_version(version: str) -> str:
"""Given a version string from the EUPS tag file, find something that
looks like a Git ref.
"""
return version.split("+")[0] | c6a429878c2150ce58b262e9f1fb187226336b0b | 58,626 |
def levelSet(img, region_id, obj_uid, image_paras):
"""Identifies nested depressions using level-set method.
Args:
img (np.array): The numpy array containing the image.
region_id (int): The unique id of the region.
obj_uid (int): The object id of the region.
image_paras (dict): ... | 0b4153686d7bcdddf28ebf5d5ed9a6560354f981 | 58,627 |
def fetch_users_cli(
ldap_server,
ldap_username,
ldap_password,
admin_group,
editor_group,
verbose,
skip_deactivate,
dry_run
):
""" Updates the list of users/course attendees by fetching matching users
from a remote LDAP server.
This is curren... | 1af4181779856556843496dbd2e0290c66fce6dd | 58,628 |
def insert_hit_count_js_variables(parser, token):
"""
Injects JavaScript global variables into your template. These variables
can be used in your JavaScript files to send the correctly mapped HitCount
ID to the server (see: hitcount-jquery.js for an example).
{% insert_hit_count_js_variables for [... | 129778e45c99ebe9bd9db0abc6f4007eb3c8f5f5 | 58,629 |
import re
def page_to_books(page_content):
"""Funkcija poišče posamezne knjige, ki se nahajajo v spletni strani in
vrne njih seznam"""
izraz = re.compile(r'<tr>.*?<td><i><a (.*?)</td></tr>', re.DOTALL)
return [m.group(0) for m in re.finditer(izraz, page_content)] | 2954ef11dce788b1232976d9b523f9e0b9a69cfc | 58,630 |
def lowerfirst(value):
"""Un-capitalizes the first character of the value."""
return value and value[0].lower() + value[1:] | ea3b0f98ba4c14febb7937b781ec066258c7ad73 | 58,631 |
import random
def rgbAverage(col1, col2):
"""col1 (str): hex value of color 1
col2 (str): hex value of color 2
Returned value (str): hex value of average color"""
r1, g1, b1 = strhexToRgb(col1)
r2, g2, b2 = strhexToRgb(col2)
if(random.random()>=0.5):
r = int((r1+r2)/2+0.5)
g = ... | ebeaba32e5a7127f92b47a09ae4fd89f204f8310 | 58,632 |
def create_random_test(data_list: list, using_themes_dict: dict) -> list:
"""
Creates instance of test.
:param data_list: List of tasks from pull in json format.
:param using_themes_dict: Dictionary with themes which will be used for current grade.
:return: List with test instance (theme - conditio... | 3161043a2aa6c49d3e6a7e61c204ba14562c93b2 | 58,633 |
import random
def adult_generate_random_range_dim2(filepath,dim_1_low,dim_1_high,dim_2_low,dim_2_high,num=500):
"""
6, 8 and 10
"""
queryPool=[]
query=[]
for _ in range(num):
left1 = random.randint(dim_1_low, dim_1_high)
right1 = random.randint(left1, dim_1_high)
query.... | b47955a6d1a65838d3f3c60fa10a8047e7d8dcf9 | 58,634 |
def collapse(iter_flow_result:dict)->list:
""" Return iter_flow dict result as a single flat list"""
nested_lists = [iter_flow_result[k] for k in iter_flow_result.keys()]
flat_list = [item for sublist in nested_lists for item in sublist]
return(flat_list) | ada0d654ed36df8168b4835fbde3b91b7f56fb72 | 58,635 |
def return_posts(keywords):
"""Function to return the posts that the user wants based on the keyword/s"""
posts = []
# run a for loop of queries on the list of keywords entered to get the posts corresponding to the keywords
for word in keywords:
x = []
# query to find title of posts
... | 1ffd598e3b352176045f986093309e248dbd66a3 | 58,637 |
from typing import Callable
from typing import Tuple
from typing import List
def pad_array(
pad: Callable = pad,
spacing: Tuple[int, int] = (150.0, 0.0),
n: int = 6,
port_list: List[str] = ["N"],
width: float = 100.0,
height: float = 100.0,
layer: Tuple[int, int] = LAYER.M3,
) -> Component... | 670a3ab42096122ce1ed6552cf2c3ae646a4d59e | 58,638 |
def is_arborescence(G):
"""
Returns True if `G` is an arborescence.
An arborescence is a directed tree with maximum in-degree equal to 1.
Parameters
----------
G : graph
The graph to test.
Returns
-------
b : bool
A boolean that is True if `G` is an arborescence.
... | d1dd1a1e3048639cd28cd940a767c8f568ec72b5 | 58,639 |
def _GetTargetSelection(args, explicit_targets=None):
"""Find all TMS570 nodes matching constraints."""
target_list = explicit_targets
if not target_list:
target_list = args.target
available_nodes = set(n for n in _NETWORK_CONFIG.aio_nodes
if n.tms570_node or n.snake_name == 'unknow... | 6ae2dffd249c69019498a0148c1930f8443ff84e | 58,640 |
async def not_authenticated(
req: Request,
exc: NotAuthenticated,
) -> JSONResponse:
"""Return invalid access token response.
:param req: The original starlette request
:param exc: The exception that was raised
"""
return JSONResponse(
status_code=exc.status_code,
content={... | 98fddb381789cd632b0c7fc9209870c75a4ca766 | 58,641 |
def interpolate(series, indices):
"""Linearly interpolate series on indices."""
not_included = [t for t in indices if t not in series.index.values]
new_indices_series = pd.Series(index=not_included, data=[np.nan] * len(not_included))
with_new_indices = series.append(new_indices_series).sort_index()
... | 8a4a98c5e6310a83dcda2ac3b99a3a69f9fa63ae | 58,643 |
def present(name, url, branch="master",
credential_id="", implicit=True, **kwargs):
"""
Jenkins Global pipeline library present state method
:param name: pipeline library name
:param url: url to remote repo
:param branch: remote branch
:param credential_id: credential id for repo
... | 83a4ff43bddd5326ce8f4923301a30058163ae53 | 58,644 |
import warnings
def __comparelist(*args):
"""
Args:
*args: Multiple list type variables can be passed to be compared for length
Returns: 2 when lists are different lengths, 0 when list lengths are equal
"""
length = len(args[0])
if any(lst is None for lst in args):
raise ListEr... | 7eff26e7e8fb05d9e3c132b4966859a37b5de90d | 58,645 |
def call_plugin(type, capability, *args, **kwargs):
"""Call a plugin from the HOST_TEST_PLUGIN_REGISTRY.
Args:
capability: Plugin capability we want to call.
args: Additional parameters passed to plugin.
kwargs: Additional parameters passed to plugin.
Returns:
True if the c... | 55a661536a6e2d25857f7aa85b6d2ad067556373 | 58,646 |
def insert(path, # type: str
value, # type: JSON
create_parents=False, # type: bool
xattr=False # type: False
):
# type: (...) -> Spec
"""
Insert a value at a given path in a document.
:param str path: ... | 914aac3bbc3958eb3d4c57b08d41cd0cd3e0502f | 58,647 |
def _attr_getter(obj, attr):
"""
Return the attribute value of an individual DOM node.
Parameters
----------
obj : node-like
A DOM node.
attr : str or unicode
The attribute, such as "colspan"
Returns
-------
str or unicode
The attribute value.
"""
# Sc... | e0b0667a3edde59f8fd97db2d967d4dd21244f34 | 58,649 |
def milestones(born, limit=80):
"""
Calculate the actual milestone dates.
Arguments:
born -- The given year to calculate milestones from.
limit -- An upper limit of years to calculate results to. By setting
it to 80 years, it tipically covers most of our lifespans.
"""
year = born
r... | 96f1da944a66674707de9341f5127bebea3aa180 | 58,650 |
def remove_ligand(input_structure_path: str, output_structure_path: str, properties: dict = None, **kwargs) -> int:
"""Execute the :class:`RemoveLigand <utils.remove_ligand.RemoveLigand>` class and
execute the :meth:`launch() <utils.remove_ligand.RemoveLigand.launch>` method."""
return RemoveLigand(input_s... | 522c872db91df472d508478143bbd6b3aa37e1a9 | 58,652 |
from typing import Callable
import collections
def build_hypcluster_eval(model_fn: Callable[[], tff.learning.Model],
num_clusters: int) -> tff.Computation:
"""Builds a computation for performing HypCluster evaluation."""
with tf.Graph().as_default():
# Wrap model construction in a g... | 0d759855e5a2e99add93e612179a1086e5930107 | 58,653 |
def cwltool_no_container_option():
"""Annotate click command as consume the --no_container option.
This option is for the CWL CLI runner interface.
"""
return planemo_option(
"--no-container",
"--no_container",
is_flag=True,
default=False,
use_global_config=True,... | 0432207de30dbfc343ca5c4ac47b74f4ddc17dea | 58,655 |
from typing import Mapping
from typing import Tuple
from typing import Any
from typing import Optional
from typing import Dict
def fill_tuple_keys(
d: Mapping[Tuple[Any], Any],
length: Optional[int] = None,
repeat: bool = False,
fill_method: str = 'bfill',
) -> Dict[Tuple[Any], Any]:
"""Fill tuple... | a6ff8ad977d452a9e479871da9d75d0b55064bd9 | 58,656 |
from typing import Iterable
from typing import Tuple
from typing import List
from typing import Set
import inspect
import ast
def translate_rules(ruletypes: Iterable[type], writer: RuleWriter) -> Tuple[List[str], Set[str]]:
"""
Translates each of a number of Rules, recursively handling superclasses until one ... | 94ecc04060fb31b21c4d1741b7e4da4b1fead16c | 58,658 |
def _get_form(request, activity):
"""Returns the activity form."""
if activity.confirm_type == "image":
form = ActivityImageForm(request.POST, request.FILES, request=request, action=activity)
elif activity.confirm_type == "free":
form = ActivityFreeResponseForm(request.POST, request=request... | b471c5be1ed6bf79f1735dae45fa632220d60bb8 | 58,659 |
from typing import Optional
from typing import Set
def package_qualified_class(
class_name: Optional[str], package_name: str, all_classes: Set[str]
) -> Optional[str]:
"""Return a package name qualified class, as long as the class is one
of the classes we are processing in this package.
xAOD.Jet -> p... | 3a5d29fae0f760ffe0e9c1434e7d846dbdee106c | 58,661 |
def train_model(model_id, x_train, y_train):
""" Train an EmberNN classifier
:param model_id: (str) model type
:param x_train: (ndarray) train data
:param y_train: (ndarray) train labels
:return: trained classifier
"""
if model_id == 'lightgbm':
return train_lightgbm(
x... | 4125831259be38fb43ba702680c49e1fd3e79c1a | 58,662 |
from typing import Union
import asyncio
async def prompt_number(client, ctx: commands.Context, the_msg: discord.Message, member: discord.Member, limit: int = 1000) -> Union[int, None]:
""" Prompts the user for a number.
:param ctx: The context.
:param member: The member that is gonna be prompted. """
... | ac41189de6696a78f4a3b00bf2b76817adecd90c | 58,665 |
def changes(new_cmp_dict, old_cmp_dict, id_column, columns):
"""Return a list dict of the changes of the
rows that exist in both dictionaries
User must provide an ID column for old_cmp_dict
"""
update_ldict = []
same_keys = set(new_cmp_dict).intersection(set(old_cmp_dict))
for same_ke... | 0b10755dcac69eb11bf47fdd2309308e0d2266c8 | 58,666 |
import zipfile
import tarfile
from pathlib import Path
def _get_archive_writer(output_path):
"""
Detects and returns the appropriate archive writer
output_path is the pathlib.Path of the archive to write
"""
if not output_path.suffixes:
raise ValueError('Output name has no suffix: %s' % o... | 1ac22bb5b402a56cc89489e370f87b1afcd7c80b | 58,667 |
from typing import Union
from pathlib import Path
def relative_to(
path: Union[str, Path], source: Union[str, Path], include_source: bool = True
) -> Union[str, Path]:
"""Make a path relative to another path.
In contrast to :meth:`pathlib.Path.relative_to`, this function allows to keep the
name of th... | 26caa33770617361406915c9b301b5fe1a0ba9ef | 58,668 |
def calcNormErrors(analytical, analysis, domain, eSignFactor):
"""
(array, array, array, str) -> array, array
"""
assert len(analytical) == len(analysis)
assert len(domain) == len(analysis)
a = np.array(analytical)
f = np.array(analysis)
e = [float(fi - ai) / max(abs(a)) for ai, fi in zi... | ad6cf06d15378ed8e7aee646ac89bdf1e8d74beb | 58,669 |
from typing import Union
def pause(process: Union[ProcessNode, int, str], timeout: int = 5) -> bool:
"""Pause the specified process.
Paused processes will not continue execution, and can be unpaused later.
Params
------
process
The process to kill.
timeout
Timeout (in seconds... | a956d9784938369b39eb0ca34cf964d6557d463f | 58,670 |
from typing import Type
import warnings
import json
def load_v1_json(
json_str: str,
base_class: Type[CalibrationInfo] = CalibrationInfo,
):
"""Load a json string that was created using imucal <= 2.0."""
warnings.warn(
"Importing a legacy calibration file, will use default values for all param... | e60873cd03b08e443110ecc2dd59ca314dc5c1c3 | 58,672 |
def bbox_to_rect(bbox, color):
"""Convert bounding box to matplotlib format."""
# Convert the bounding box (upper-left x, upper-left y, lower-right x,
# lower-right y) format to the matplotlib format: ((upper-left x,
# upper-left y), width, height)
return plt.Rectangle(xy=(bbox[0], bbox[1]), width=b... | 08cd4c405577743b85c92affd78227b4f8d53ec8 | 58,673 |
def _normalize_value_string(s):
"""Flatten value into a single line."""
final_lines = []
for line in s.splitlines():
line = line.strip()
# remove line continuation \
if line.endswith('\\'):
line = line[:-1]
final_lines.append(line)
return ''.join(final_lines) | 00ce1b63eb4418bd490df754a50d2ad4bbd7618a | 58,674 |
import time
def timed(func):
"""This decorator prints the execution time for the decorated function"""
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print("[{}] run in {}s".format(func.__name__, round(end-start, 2)))
return result
return ... | 813ad55600badc69341838f2696333cadf1fd677 | 58,676 |
def return_csl_format_export(solr_data, csl_style, export_format, journal_format, request_type='POST'):
"""
:param solr_data:
:param csl_style:
:param export_format:
:param request_type:
:return:
"""
if (solr_data is not None):
csl_export = CSL(CSLJson(solr_data).get(), csl_styl... | d73e737547dc7196feee66c78e91c60c0b6ec312 | 58,677 |
def get_alignment_rotation_matrix_from_svd(point_cloud: np.ndarray) -> np.ndarray:
"""Applies SVD to fit an ellipsoid to the point cloud. The resulting V contains the rotation matrix required to
align the 3 principal axes of the ellipsoid with the x, y, z coordinate axes.
Args:
point_cloud: point c... | 897d48ad17ca1a9751b72cd681db65f8d7a7a806 | 58,678 |
def packing_fraction_state(state):
"""
Calculates the packing fraction of a state.
Parameters
----------
state : :class:`peri.states.ImageState`
Returns
-------
Float
The volume fraction
"""
return state.get('obj').get()[state.inner].mean() | fc9cc7c3aea2bcb9415aa3591f85a76c6c6a1412 | 58,680 |
def load_data(one_hot: bool=False, dataset: bool=False):
"""Load MNIST dataset into an optional tf.data.Dataset object.
Args:
one_hot (bool):
Maybe convert labels to one-hot arrays.
dataset (bool):
Should return tf.data.Dataset object. (default: {False})
Examples:
... | feefa96c2715168358ff3a770e283719824d02a4 | 58,681 |
def z_function(input_str: str) -> list:
"""
For the given string this function computes value for each index,
which represents the maximal length substring starting from the index
and is the same as the prefix of the same size
e.x. for string 'abab' for second index value would be 2
For the v... | 6fa265237488ab141b99109ac45a6bf088b6f08a | 58,682 |
def get_creds(filename):
"""
Read credentials from a file. Format is:
URL
USERNAME
PASSWORD
Parameters
----------
filename: string
path to the file with the credentials
Returns
-------
list as [URL, USERNAME, PASSWORD]
"""
f = open(filename, "r")
lines =... | 7b308a2e140a809e0bb11804750370bb4326796d | 58,683 |
def create_path(createFn):
""" Decorator to create a path from the path provided """
def decorator(fn):
def wrapper(self, *args, create=False):
path = fn(self, *args, create=create)
if create:
createFn(path)
return path
return wrapper
retur... | e4fecc33e051f0b1384f9b3b41f49fcd938357c9 | 58,684 |
def get_message_stream(wl_id, params={}):
""" Gets up to 30 messages from Watchlist (wl_id) according to additional params
"""
all_params = ST_BASE_PARAMS.copy()
for k, v in params.items():
all_params[k] = v
return R.get_json(ST_BASE_URL + 'streams/watchlist/{}.json'.format(wl_id), params=al... | 99d74fa00f2ec23fa121786ea1fdc7e8181b4abc | 58,685 |
def uri_base(uri):
"""
Get the base URI from the supplied URI by removing any parameters and/or fragments.
"""
base_uri = uri.split("#", 1)[0]
base_uri = base_uri.split("?", 1)[0]
return base_uri | 8655b8717261dcd419f1c3ac0153ec51d348ca57 | 58,686 |
def sequalsci(val, compareto) -> bool:
"""Takes two strings, lowercases them, and returns True if they are equal, False otherwise."""
if isinstance(val, str) and isinstance(compareto, str):
return val.lower() == compareto.lower()
else:
return False | 5e96233ead44608ce70ad95e936c707af8bcb130 | 58,687 |
import typing
def rnd_sampling(feature_dict: dict,
sample_size: int,
epsilon_perc=0.1,
random_state=42,
categories: typing.Optional[list] = None):
"""
Creates subsets of thresholds of specified size, for each feature, drawn uniformly at rando... | 2f447677d57efdd5964291408ecb83af03b7bfe0 | 58,688 |
def add_colorbar(im, aspect=20, pad=0.5, **kwargs):
"""Add a vertical color bar to a plot.
Parameters
----------
im : ScalarMappable
The output of `sfs.plot.soundfield()`, `sfs.plot.level()` or any
other `matplotlib.cm.ScalarMappable`.
aspect : float, optional
Aspect ratio o... | 983497107de43687447897c10f345161b3ae7e58 | 58,689 |
from typing import Literal
def _get_period_range_edges(
first: Period,
last: Period,
freq: BaseOffset,
closed: Literal["right", "left"] = "left",
origin="start_day",
offset: Timedelta | None = None,
) -> tuple[Period, Period]:
"""
Adjust the provided `first` and `last` Periods to the r... | d86ac395df92c04518e6bb9354328b9471e5c714 | 58,690 |
def projection_dist(v):
"""
Pairwise projection distance between the elements specified by the first axis of 'v'. Each element of 'v' (v[0],
v[1], ...) is assumed to be a matrix with orthonormal rows.
:param v: Input matricies
:type v: tf.Tensor
:return: Projection-distance matrix between the e... | 33420663f26a3c8d70730813c9077bad77559a17 | 58,691 |
def find_peaks(hist):
"""Find peaks in the histogram corresponding to physical events
:param hist: histogram of coincident signals
:return: list of peaks with [start_time, end_time, duration, n_pixels_affected]
"""
last = 0
peaks = []
for i in range(len(hist)):
if hist[i] > 0 and las... | 341f59ae9eecb0efa7af208a6633ad7870dc73e6 | 58,692 |
def n_rots(request):
"""Number of rotations in random layer."""
return request.param | 93d55281a83be9e4acba951d1de8a9e7d5081182 | 58,693 |
import json
def get_hash(inp):
"""
Creates a SHA-256 hash of a input dictionary
:param inp: dict, such as block, tx
"""
b = json.dumps(inp, sort_keys=True).encode()
h = SHA256.new()
h.update(b)
return h.hexdigest() | b02ed08463e70b334720ed50f2ca32fdd877c0c7 | 58,694 |
import re
def add_boolean_transfer(row):
"""Compute boolean Series which return True if the "header" starts with given
regex 'answer_subject', False if not.
To be used with methods such as: `apply(func, axis=1)` or
`apply_by_multiprocessing(func, axis=1, **kwargs)`.
Parameters
----------
... | 60f5e1ab04c6575a1fdb789afe4204873af80ced | 58,695 |
def calc_E_SV(A_A):
"""1年あたりの機械換気設備の基準一次エネルギー消費量 (6)
Args:
A_A(float): 床面積の合計(付録Aによる定まる値) (m2)
Returns:
float: 1年あたりの機械換気設備の基準一次エネルギー消費量 (MJ/年)
"""
# 係数 a_SV, b_SV
a_SV, b_SV = get_table3_coeff(A_A)
# 1年あたりの機械換気設備の基準一次エネルギー消費量 (9)
E_SV = get_E_SV(A_A, a_SV, b_SV)
ret... | 3e1987788a74df32a9ded18c3ebad0de9231f97b | 58,696 |
def dft_phase(x, y, freq):
"""
Discrete fourier transform to calculate the ASTC phase
given x, y, and an array of frequencies
Parameters
----------
x : `array`
Array in which to calculate
y : `array`
Returns:
----------
phase : `list`
... | d6f583f0330fba754cb369fcf2aac41b771587db | 58,697 |
def redeem_voucher(voucher_id, federal_site):
""" If the Ticket exists and is not redeemed, redeem it at federal_site.
"""
try:
ticket = Ticket.objects.get(record_locator=voucher_id)
if ticket.redemption_entry is None:
ticket.redeem(federal_site)
else:
# Thi... | 0645b4d03563bcd2087c36cb516b672a1c389e4f | 58,699 |
from typing import Any
def try_to_cuda(t: Any) -> Any:
"""
Try to move the input variable `t` to a cuda device.
Args:
t: Input.
Returns:
t_cuda: `t` moved to a cuda device, if supported.
"""
try:
t = t.cuda()
except AttributeError:
pass
return t | 9b6643f169c1eb8fc65de8b1bff55668f8cba950 | 58,700 |
def filter_status_sensitive(production_id):
"""
敏感状态
:param production_id:
:return:
"""
if not production_id:
return False
condition = {
'production_id': production_id,
'status_delete': STATUS_DEL_NO
}
production_sensitive_info = get_production_sensitive_row(*... | 358bda8e224d86380a318d86cf3d1b89b65135b3 | 58,701 |
def diff6circlek(delta, gamma, energy_kev=None, wavelength=1.0, lab=None):
"""
Calcualte incident and final wavevectors in diffractometer axis using detector angles
:param delta: float angle in degrees in vertical direction (about diff-z)
:param gamma: float angle in degrees in horizontal direction (abo... | ef6d6efd7ec6892b0ead82acf66bb833144b5752 | 58,702 |
def fixtableforhtml(tablecolumn):
"""
fix the formatting to make the decimals into percents and
add comma seps to long numbers
"""
new_table = []
for x in tablecolumn:
if float(x) < 1:
x = str(round(float(x) * 100, 2))+"%"
else:
x = int(float(x))
... | f57f2ef4145a7389e6160316750e64d0903ddc02 | 58,703 |
def refine_baseline(baseline, heights, detection_maps, downsample, crop_engine, detection_threshold=0.3):
"""
Refines the input baseline using fitting 2nd order polynom to the baseline detection map.
:param baseline: numpy array of input baseline coords
:param heights: list of input line heights [ascend... | f36e5edc52fd10b69b259528421d4904acbc365e | 58,704 |
def provides(iface):
"""
Matches an object that provides the given interface.
"""
return Provides(iface) | a142ab3aa391fc84c56a91b3c41e3e22c119ce62 | 58,705 |
def getGasDensity(grid=None, ppar=None):
"""Calculates the gas density distribution in a protoplanetary disk.
Parameters
----------
grid : radmc3dGrid
An instance of the radmc3dGrid class containing the spatial and frequency/wavelength grid
ppar : dictionary
A diction... | 113b4a18f0a420ccea8fdaf9674521465af5132a | 58,706 |
def extract_finding(doc, audit):
"""
Given a header, examine the relevant context and see if we have
a finding on our hands that corresponds to the given audit.
"""
headers = sentences(doc, "HEADER")
if not headers:
return None
# we know this page has a header. attempt to extract the... | 657b8f9f1fcbec4646e53540c1865acad2b1f151 | 58,707 |
from scipy.optimize import brentq
def s_of_rew(rew,A_w,G0,Rg,ah):
"""
Inverse function of rew_of_s. Uses brentq for root finding.
Parameters
----------
rew : float
rest equivalent width of absorption
A_w : float
Defined in eq. 6, Tinker & Chen 2008, ApJ
G0 : float
N... | f9cfe1daa8ff64385b9007981f7c07732df5e70e | 58,708 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.