content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def trackPlot(mat, fig=None, groups=None, ratios=None, labels=None, cmap=None, norm=None, is2D=False, xticks=False):
"""
This function takes a matrix and generates a track figure with several panel according to a group structure that groups
several rows/cols of the matrix into one panel. This can be done fo... | 9b59507cb46d5ff4196e43311771357d5b2826a2 | 3,636,200 |
from typing import List
from typing import Optional
import sys
def concatenate(
*,
target_list: List[str],
is_colored: bool = False,
number_x: Optional[int] = None,
):
"""api to concatenate movie/picture (note: keyword-only argument)
Args:
target_list (List[str]): list of movies, pictures o... | 65b428de0f15374d0f5ca3b4f43b0eaed9185f80 | 3,636,201 |
def split_at(n, coll):
"""
Returns a tuple of ``(take(n, coll), drop(n coll))``.
"""
if n <= 0:
return [], coll
if coll is None:
return [], []
# Unfortunately we must consume all elements for the first case because
# unlike Clojure's lazy lists, Python's generators yield th... | 7c97e3ad7910b116e01c70925888ea371be11c72 | 3,636,202 |
def clip(x: ArrayLike, lo: ArrayLike = None, up: ArrayLike = None) -> ShapeletsArray:
"""
Element-wise, limits the values in an array
Parameters
----------
x: ArrayLike
Input array expression
lo: Optional ArrayLike (defaults: None)
Low values
up: Optional ArrayLike (defa... | 48c70dad730574a31b018c94c54cc785c680d6a1 | 3,636,203 |
def determineNewest(uid, homeType):
"""
Construct a query to determine the modification time of the newest object
in a given home.
@param uid: the UID of the home to scan.
@type uid: C{str}
@param homeType: The type of home to scan; C{ECALENDARTYPE},
C{ENOTIFICATIONTYPE}, or C{EADDRESS... | 88cfcd264639c6dc76807b4155592321e3a899b3 | 3,636,204 |
def get_data(limit = None, filename = "C:/Users/Marcel/OneDrive/Python Courses/Machine Learning/train.csv"):
"""
Reads the MNIST dataset and outputs X and Y.
One can set a limit to the number of rows (number of samples) by editing the 'limit'
"""
print("Reading in and transforming data...")
data... | 00933eb2b42180abbd8cf0e326d6e3b0c336131a | 3,636,205 |
def vech(A): # TODO: why not just use A[np.triu_indices(A.shape[0])]?
"""
Simple vech operator
Returns
-------
vechvec: vector of all elements on and below diagonal
"""
length = A.shape[1]
vechvec = []
for i in range(length):
b = i
while b < length:
vechv... | 197e700e1a0a010fedbb4aac7ca9545e49c07574 | 3,636,206 |
def file_size(value, fmt="{value:.1f} {suffix}", si=False):
"""
Takes a raw number of bytes and returns a humanized filesize.
"""
if si:
base = 1000
suffixes = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
else:
base = 1024
suffixes = ("B", "KiB", "MiB", "GiB"... | 272250966c0d301a86a136a7e84af6049e9fe47f | 3,636,207 |
def login():
"""
This method logs the user into the account.
It checks the username and the password in the database.
---
Args: None
Returns: If log in is successful redirects the user to account page
"""
if request.method == 'POST':
email = request.form.get('email')
pas... | 02ebd2b43b2f32465544efc8b8b5ff1684877fa8 | 3,636,208 |
def index_select_op_tensor(input, dim, index):
"""
input.index_select(dim, index) -> Tensor
See :func:`oneflow.index_select`
"""
return index_select_op(input, dim, index) | 8049ec1541c9120d505e07d1bd944fdeaf05d4ef | 3,636,209 |
def cull(dsk, keys):
""" Return new dask with only the tasks required to calculate keys.
In other words, remove unnecessary tasks from dask.
``keys`` may be a single key or list of keys.
Examples
--------
>>> d = {'x': 1, 'y': (inc, 'x'), 'out': (add, 'x', 10)}
>>> dsk, dependencies = cull... | b583f52835bc813e11092515aedb4d9943c7637c | 3,636,210 |
import torch
def validate_coot(config, model,
val_loader,
epoch,
constrastive_loss,
cmc_loss,
writer,
logger,
use_cuda=True):
"""Validate COOT model
Args:
model: COOT model
... | b6abd4fc6c6cb60ab1a82682754fd5f514c41ccf | 3,636,211 |
def iniStressProfile((z,dz),(zMin,zMax),ma):
"""initial acoustic stress profile
\param[in] z z-axis
\param[in] dz axial increment
\param[in] zMin start of new tissue layer
\param[in] zMax end of new tissue layer
\param[in] ma absorption coefficient
... | 60cfe2f240ea30bb278164b7211d6acaf7d4f778 | 3,636,212 |
def OpenCredentials(cred_path: str):
"""
Opens and parses an AWS credentials file.
:param cred_path: Path to the file containing the credentials
:return: A dict containing the credentials
"""
with open(cred_path) as file:
keys, values = map(lambda s: s.strip().split(','), file)
cred... | 2f224a92b6c3999a45f6d73bb90504663614a1ac | 3,636,213 |
def get_follow_users():
"""
Get all the users stored in the cookie
"""
follow_users = []
if "follow" in request.cookies:
follow_users = request.cookies["follow"]
follow_users = follow_users.split(delim)
return follow_users | df212f387af02938e4afc6baac24692598dd0f7f | 3,636,214 |
def generate_user_agent(os=None, navigator=None, device_type=None):
"""
Generates HTTP User-Agent header
:param os: limit list of os for generation, possible values:
"win", "linux", "mac", "android", "ios", "all"
:type os: string or list/tuple or None
:param navigator: limit list of browser... | cc5b4c251b088d61f00255c148c32a508c77dd1a | 3,636,215 |
def list_upcoming_assignments_calendar_events(request_ctx, **request_kwargs):
"""
Returns the current user's upcoming events, i.e. the same things shown
in the dashboard 'Coming Up' sidebar.
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:return: Li... | 2c7380eabe82f7180da3777a8cebc75a20345a32 | 3,636,216 |
def mse_loss(y,loc):
""" Mean squared error loss function
Use mean-squared error to regress to the expected value
Parameters:
loc: mean
"""
loss = (y-loc)**2
return K.mean(loss) | 9a3a1dc45680cf3ad8434d24c511041f7f054750 | 3,636,217 |
def _get_license_key_outputs(session):
"""Returns the account id and policy ARN for the license key secret if they exist"""
global __cached_license_key_nr_account_id
global __cached_license_key_policy_arn
if __cached_license_key_nr_account_id and __cached_license_key_policy_arn:
return __cached_... | a04aad32d9b192987462396023b117ecda91ea14 | 3,636,218 |
def get_sample_untransformed(shape, distribution_type, distribution_params,
seed):
"""Get a distribution based on specification and parameters.
Parameters can be a list, in which case each of the list members is used to
generate one row (or column?) of the resulting sample matrix. Ot... | 4b5a69920b8501ef4f57c9802dcea997c5df8587 | 3,636,219 |
import params
def __convert_sysctl_dict_to_text():
"""
Convert sysctl configuration dict to text with each property value pair separated on new line
"""
sysctl_file_content = "### HAWQ System Parameters ###########\n"
for key, value in params.hawq_sysctl.iteritems():
if not __valid_input(value):
r... | ccea96f72c0730ee072b7fc174f02d6f302282d6 | 3,636,220 |
from typing import Union
from typing import List
from typing import Dict
from typing import Any
from typing import Optional
from typing import cast
import requests
def vizualScript(
inputds: str,
script: Union[List[Dict[str, Any]], Dict[str, Any]],
script_needs_compile: bool = False,
properties: Optional[D... | 93ded6562e49110134ecbf1fade7c5c2b7a57582 | 3,636,221 |
def _to_sparse_input_and_drop_ignore_values(input_tensor, ignore_value=None):
"""Converts a `Tensor` to a `SparseTensor`, dropping ignore_value cells.
If `input_tensor` is already a `SparseTensor`, just return it.
Args:
input_tensor: A string or integer `Tensor`.
ignore_value: Entries in `dense_tensor` ... | bfbde83654a817ab12a85d4fa321eba6d731174d | 3,636,222 |
from datetime import datetime
import logging
def parse_date(date_str):
"""
>>> parse_date("22 April 2011 at 20:34")
datetime.datetime(2011, 4, 22, 20, 34)
>>> parse_date("9 July 2011")
datetime.datetime(2011, 7, 9, 0, 0)
>>> parse_date("September 2003")
datetime.datetime(2003, 9, 1, 0, 0)
... | cc56ce8517d9efd1de5f41a2ca645a54530635db | 3,636,223 |
import os
import tempfile
def readTmpFile( processPid ):
""" Read the temp file """
fileName = os.path.join( tempfile.gettempdir(), 'mms-' + str( processPid ) )
if not os.path.isfile( fileName ):
return None
f = open( fileName )
try:
fileContent = f.read()
# Handle the ... | a2b3bba95fce0c2d1c6014cb55daa03748733b5a | 3,636,224 |
def pkcs7_unpad_strict(data, block_size=16):
"""Same as `pkcs7_unpad`, but throw exception on incorrect padding.
Mostly used to showcase the padding oracle attack.
"""
pad = data[-1]
if ord(pad) < 1 or ord(pad) > block_size:
raise Exception('Invalid padding length')
for i in range(2, or... | 0cb7c2d66c30de8bac54ca714dfa05a29d4f0cbd | 3,636,225 |
def cut(d1: dict, d2: dict) -> dict:
"""Removes the keys/values in `d1` to `d2` if they do
not already exist (non-mutating action)
Examples:
.. highlight:: python
.. code-block:: python
from map_ops.operations import cut
d1 = {"foo": 1, "bar": 1}
d2 = ... | 4985d9cb6ff804149a4fddd85bd2c01dd72b9f0d | 3,636,226 |
def chiresponse(A,x):
"""
Deprecated, just use normal "response" function above!
The response function used in the chi squared fitting portion of the simulation.
Meant to imitate the actual response of a scintillator.
Inputs 2 vectors, and responds with a cos^x dependence.
Parame... | 95a07a63e63277a091100fa8519b329c6b2f90de | 3,636,227 |
def _remove_trailing_string(content, trailing):
"""
Strip trailing component `trailing` from `content` if it exists.
Used when generating names from view classes.
"""
if content.endswith(trailing) and content != trailing:
return content[:-len(trailing)]
return content | 775bafba5ea518e03499c9351b74ac472c265c9a | 3,636,228 |
from typing import List
from typing import Optional
import os
def data_downloader(genome_ids: List[str],
output_directory: Optional[str] = None,
metadata: Optional[str] = None) -> List[str]:
"""
Parameters
----------
genome_ids
A list of assembly access... | 4412d0cc6894dff652d5f84a05b106c255e36a7c | 3,636,229 |
def find_loop_size( public_key, subject=7 ):
"""
To transform a subject number, start with the value 1.
Then, a number of times called the loop size, perform the following steps:
- Set the value to itself multiplied by the subject number.
- Set the value to the remainder after dividing... | 831f5f3e9867b06640493226fa35a89251f5aad5 | 3,636,230 |
def lambda_local_ep(ngl, ind_passive, passive_el, disp_vector, dyna_stif, coord, connect, E, v, rho):
""" Calculates the lambda parameter of the local elastic potential energy function.
Args:
ngl (:obj:`int`): Degrees of freedom.
ind_passive (:obj:`numpy.array`): Index of passive elements.
... | 63925ebbd28710f1d9d3e3c64d8f364de1f76e36 | 3,636,231 |
from re import T
def from_spanning_matroid(matroid: tuple[set[T], list[set[T]]]) -> list[set[T]]:
"""Construct flats from a matroid defined by spanning sets.
Args:
matroid (tuple[set[T], list[set[T]]]): A matroid defined by spanning sets.
Returns:
list[set[T]]: The flats of a given matro... | 9b2ff51cec3be92b8442e9bc807f14a8ee4412dc | 3,636,232 |
import functools
def suppress_traceback(debug: bool = True) -> None:
"""
Decorator to suppress traceback when in debug mode.
Parameters
----------
debug: bool
turn on debug mode or not
Returns
-------
None
"""
def decorator(func):
@functools.wraps(func)
... | c5e595f274f2af21a2397d0f7592208a4284b360 | 3,636,233 |
import os
from nipype.utils.filemanip import split_filename
from clinica.utils.atlas import (
AtlasAbstract,
JHUDTI811mm,
JHUTracts01mm,
JHUTracts251mm,
)
from clinica.utils.statistics import statistics_on_atlas
def statistics_on_atlases(in_registered_map, name_map, prefix_file=Non... | e28a639539adeaa55691215511df0695403b2499 | 3,636,234 |
import tempfile
import os
def render_projection_from_filelist(files: list) -> str:
"""Render a full projection montage from the given list of files
Returns the filename to the output image, which must be manually
deleted after use.
"""
temp_dir = tempfile.TemporaryDirectory()
convert_filelis... | 69da08ca82e31bca28ef5dc19c2e4a078be72830 | 3,636,235 |
def get_value_for_attribute(attribute):
"""For a given key return the value.
Args:
attribute (str): Some metadata key.
Returns:
str: The value of the requested key, if key isn't present then None.
"""
path = '/computeMetadata/v1/instance/attributes/%s' % attribute
try:
... | 2b61f018988db90165f06e975a6478ba3f606652 | 3,636,236 |
def list_selected_groups(remote):
"""Returns a list of unique facegroup IDs for the current face selection (requires an active selection)"""
cmd1 = mmapi.StoredCommands()
key1 = cmd1.AppendSelectCommand_ListSelectedFaceGroups()
remote.runCommand(cmd1)
groups1 = mmapi.vectori()
cmd1.GetSelectComm... | 2ec5346c6e34c8fc35670a3061d65a92ec518c47 | 3,636,237 |
def make_user_variable(
id_name, cluster_name, w_name, d_name, y_tree_name, y_name, x_name_ord,
x_name_unord, x_name_always_in_ord, z_name_list,
x_name_always_in_unord, z_name_split_ord, z_name_split_unord,
z_name_mgate, z_name_amgate, x_name_remain_ord, x_name_remain_unord,
x_balance_name_ord, ... | d7f9f85a75df28e1db7f3dee71d625bbe99c6106 | 3,636,238 |
import re
def get_skip_report_step_by_index(skip_report_list):
"""Parse the missed step from skip a report.
Based on the index within the skip report file (each line a report), the
missed step for this entry gets extracted. In case no step could be found,
the whole entry could not been parsed or no r... | 7aa46050702aba07902ceec586175fce2226e1e3 | 3,636,239 |
import os
def write_api(entrypoint, kind="node", pkg_path=None, overwrite=False):
"""
"""
entrypoint_name = entrypoint['Name'].replace(".", "_").lower()
class_name = entrypoint['NewName']
class_dir = entrypoint['Module']
class_type = entrypoint['Type']
class_file = class_name.lower()
... | 794429bc29f24cff13f1ecbb65c4e6c1af3931e3 | 3,636,240 |
from typing import List
def constraint_notes_are(sequence: FiniteSequence, beat_offset: int, pitches: List[int]) -> bool:
"""Tells us if the context note on the given beat_offset
has the same pitches as the given list of pitches
"""
if beat_offset > sequence.duration:
return True
offset_ev... | 26a0182f708f310af0fa022e7ca6e3e34951fe3c | 3,636,241 |
import os
def make_anuga_params():
"""Function to make the example ANUGA parameters."""
params = pt.modelParams()
path = os.path.join(os.path.dirname(__file__), 'ex_anuga_data.npz')
data = np.load(path)
# pull depth and stage from that data
depth = data['depth']
qx = data['qx']
qy = d... | 218132f33adefbe29e251dd6f29d1efc56af26b1 | 3,636,242 |
from re import T
def clip(tensor: T.Tensor, a_min: T.Scalar=None,
a_max: T.Scalar=None) -> T.Tensor:
"""
Return a tensor with its values clipped between a_min and a_max.
Args:
tensor: A tensor.
a_min (optional): The desired lower bound on the elements of the tensor.
a_max... | d80d27711f5b257b9b132a313018c74d365d1159 | 3,636,243 |
def remove_objects_from_args(args, # type: Iterable[Any]
kwargs, # type: Dict[str, Any]
pvalue_class # type: Union[Type[T], Tuple[Type[T], ...]]
):
# type: (...) -> Tuple[List[Any], Dict[str, Any], List[T]]
"""For internal use ... | e68d59e00f18357f83817bc49248a0297a869624 | 3,636,244 |
import re
def reminder_validator(input_str):
"""
Allows a string that matches utils.REMINDER_REGEX.
Raises ValidationError otherwise.
"""
match = re.match(REMINDER_REGEX, input_str)
if match or input_str == '.':
return input_str
else:
raise ValidationError('Expected format:... | 3dc1895a19170ec8143ed6b62020d0e4b87f174b | 3,636,245 |
def evaluate_nll(confidences, true_labels, log_input=True, eps=1e-8, reduction="mean"):
"""
Args:
confidences (Array): An array with shape [N, K,].
true_labels (Array): An array with shape [N,].
log_input (bool): Specifies whether confidences are already given as log values.
eps ... | f2694b495f3856269fcdf5c934b3ffabe45a0491 | 3,636,246 |
import re
def parse(features: str) -> AirPlayFlags:
"""Parse an AirPlay feature string and return what is supported.
A feature string have one of the following formats:
- 0x12345678
- 0x12345678,0xabcdef12 => 0xabcdef1212345678
"""
match = re.match(r"^0x([0-9A-Fa-f]{1,8})(?:,0x([0-9A-Fa-f... | ae4e69cb3c03f5c1252067c491a8e05875d642de | 3,636,247 |
def _prefix_with_swift_module(path, resource_info):
"""Prepends a path with the resource info's Swift module, if set.
Args:
path: The path to prepend.
resource_info: The resource info struct.
Returns: The path with the Swift module name prepended if it was set, or just
the path itself if ... | f2a12f59a3c30c09fa20d65b806779ad47f49b90 | 3,636,248 |
from datetime import datetime
def str2datetime(dt, format=None):
"""
convert a string into a datetime object, it can be:
- 2013-05-24 18:49:46
- 2013-05-24 18:49:46.568
@param dt string
@param format format for the conversion, the most complete one is
... | b304eb4b0bdaf87efda333475f879fb64a8f690d | 3,636,249 |
import os
import glob
import nipype.interfaces.io as nio
import nipype.pipeline.engine as pe
def run_func_motion_correct(func_reorient, out_dir=None, run=True):
"""Run the 'func_motion_correct_workflow' function to execute the modular
workflow with the provided inputs.
:type func_reorient: str
:param... | 7d2d2b4fa5f842eef38c42954424cd504cfa7b7f | 3,636,250 |
from ..utils import sampling
def get_zoomin(self, scale=1.0):
"""
Returns a spherical region encompassing maximally refined cells.
Moved from Amr class.
What should it do??
Parameters
----------
scale : float
The radius of the returned sphere is scaled by 'scale'.
"""
im... | 52a4ead516a1b11a0e6fc6c1791488e62bbbe222 | 3,636,251 |
def parse_repeating_time_interval_to_days(date_str):
"""Parsea un string con un intervalo de tiempo con repetición especificado
por la norma ISO 8601 en una cantidad de días que representa ese intervalo.
Devuelve 0 en caso de que el intervalo sea inválido.
"""
intervals = {'Y': 365, 'M': 30, 'W': 7... | c417c0fc971ae0c94f651634ef5fb27f1accff24 | 3,636,252 |
def get_pk_and_validate(model):
"""
:param model:
:return:
"""
hits = []
for field in get_model_fields(model):
extra_attrs = field.field_info.extra
if extra_attrs.get('primary_key'):
hits.append(field)
hit_count = len(hits)
if hit_count != 1:
raise ER... | 3da628de19d9280f3fcacd232bc7de084596bc09 | 3,636,253 |
def lat_to_y(lat):
"""Convert latitude to Web-Mercator
Args:
lat: a latutude value
Returns:
float: a Web-Mercator y coordinate
"""
r = 6_378_137 # radius of the Earth at the equator
return log(tan((90 + lat) * pi / 360)) * r | 142770214f9503653ed8d2c38be39e69730dc4c6 | 3,636,254 |
import os
import platform
import xdg
def find_file(filename):
"""Find a file of given name on the file system.
This function is intended to use in tests and demo applications
to locate data files without resorting to absolute paths. You may
use it for your code as well.
It looks in the following... | 516d0b03f2254b37605a4b04bc8d3401fecb23d0 | 3,636,255 |
def generate_lasso_mask(image, selectedData):
"""
Generates a polygon mask using the given lasso coordinates
:param selectedData: The raw coordinates selected from the data
:return: The polygon mask generated from the given coordinate
"""
height = image.size[1]
y_coords = selectedData["lass... | 10831928275f5799814576e71a8faf3af019b35d | 3,636,256 |
from math import pi
def guitar(C):
"""Triangular wave (pulled guitar string)."""
L = 0.75
x0 = 0.8*L
a = 0.005
freq = 440
wavelength = 2*L
c = freq*wavelength
w = 2*pi*freq
num_periods = 1
T = 2*pi/w*num_periods
# Choose dt the same as the stability limit for Nx=50
dt =... | 0bd0ae7f5a720f330f27b1d16cbdadaea76535fd | 3,636,257 |
def start_threads_dict():
"""
获取指定URL起始THREADS字典
:return: dict-->配置中指定URL起始THREADS字典
"""
temp_dict = dict()
enable_flag = const.CONF.get('Auto_Test.assign_start_threads', 'ENABLE')
if enable_flag and isinstance(enable_flag, str):
if enable_flag.lower() == 'true':
temp_dic... | 45829c774b0b0a539fc9bede8989940dcae7a863 | 3,636,258 |
from typing import Optional
def exists_in_s3(s3_path: str) -> Optional[bool]:
"""Check whether a fully specified s3 path exists.
Args:
s3_path: Full path on s3 in format "s3://<bucket_name>/<obj_path>".
Returns:
Boolean of whether the file exists on s3 (None if there was an error.)
"... | 2f72fcf0f5f56d45e7cc9a63d0b572ef8eb652af | 3,636,259 |
from ethpm.uri import check_if_chain_matches_chain_uri
from typing import List
def validate_single_matching_uri(all_blockchain_uris: List[str], w3: Web3) -> str:
"""
Return a single block URI after validating that it is the *only* URI in
all_blockchain_uris that matches the w3 instance.
"""
match... | efc814456b74f2783de2c1fc214cba11b7b6a9ad | 3,636,260 |
import time
def ListAndWaitForObjects(service, counting_start_time,
expected_set_of_objects, object_prefix):
"""List objects and wait for consistency.
Args:
service: the ObjectStorageServiceBase object to use.
counting_start_time: The start time used to count for the inconsisten... | d2a3c2704cca699c588c4382b16643c23d578553 | 3,636,261 |
from typing import List
def load_mbb_player_boxscore(seasons: List[int]) -> pd.DataFrame:
"""Load men's college basketball player boxscore data
Example:
`mbb_df = sportsdataverse.mbb.load_mbb_player_boxscore(seasons=range(2002,2022))`
Args:
seasons (list): Used to define different season... | 1967c629045b1c7a0bc11e27a37e70ca8c12d8b7 | 3,636,262 |
from datetime import datetime
def countdown(code, input):
""" .countdown <month> <day> <year> - displays a countdown to a given date. """
error = '{red}Please use correct format: %scountdown <month> <day> <year>' % code.prefix
text = input.group(2).strip()
if ' ' in text:
text = text.split()
... | e06aa49396c3348f9641889d2dc58ef19f65a821 | 3,636,263 |
def split_rdd(rdd):
"""
Separate a rdd into two weighted rdds train(70%) and test(30%)
:param rdd
"""
SPLIT_WEIGHT = 0.7
(rdd_train, rdd_test) = rdd.randomSplit([SPLIT_WEIGHT, 1 - SPLIT_WEIGHT])
return rdd_train, rdd_test | 082439fb41108da171610dc3d03ab1f8f9f021c5 | 3,636,264 |
def QuickSort(A, l, r):
"""
Arguments:
A -- total number list
l -- left index of input list
r -- right index of input list
Returns:
ASorted -- sorted list
cpNum -- Number of comparisons
"""
# Number of comparisons
cpNum = r - l
# Base case
if cpNum == 0:
return [A[l]], 0
elif cpNum < 0:
return [], ... | 26092d222d93d8b931ab6f2d5c539ac5c9e00b2f | 3,636,265 |
import os
def get_cache_dir():
"""get directory to store data cached by application
"""
return os.path.join(get_userdata_dir(), CACHE_DIR) | 41aa21bb53e4b534cb251ae980a6b31bc6db1cc1 | 3,636,266 |
from typing import Counter
def checksum(input):
""" Checksum by counting items that have duplicates and/or triplicates and multiplying"""
checksum_twos = 0
checksum_threes = 0
for id in input:
c = [v for k,v in Counter(id).items()]
if 2 in c:
checksum_twos += 1
if ... | 8ba72e795b5868a852ce0c9c234ca35088057538 | 3,636,267 |
def Rescale(UnscaledMatrix, Scales):
"""Forces a matrix of raw (user-supplied) information
(for example, # of House Seats, or DJIA) to conform to
svd-appropriate range.
Practically, this is done by subtracting min and dividing by
scaled-range (which itself is max-min).
"""
# Calulate multi... | 9201078f3395aa11e75529f01f8e6486409c1347 | 3,636,268 |
def winrate_of(node: sgf.Node) -> float:
"""
The winrate of the node/position is defined as winrate of the most visited child.
"""
max_visits = 0
winrate = 0
variations = ([] if node.next == None else [node.next]) + node.variations
for child in variations:
if "B" in child.properties ... | d7893fdd0295f6b43fec258351c201ae8d789f1a | 3,636,269 |
def extract_kernel_version(kernel_img_path):
"""
Extracts the kernel version out of the given image path.
The extraction logic is designed to closely mimick the logic Zipl configuration to BLS
conversion script works, so that it is possible to identify the possible issues with kernel
images.
:... | 2f75b220ff3e68b8c2ae2a046b7c604a786b05b8 | 3,636,270 |
def about(request):
""" About view """
try:
about = About.objects.get().description
except:
about = "No information here yet."
return render(request, 'about_page.html', {'about': about}) | 60ea35c1c50f54c4c54ea207f48cd7805f27571a | 3,636,271 |
def concat_strings(string_list):
"""
Concatenate all the strings in possibly-nested string_list.
@param list[str]|str string_list: a list of strings
@rtype: str
>>> list_ = (["The", "cow", "goes", "moo", "!"])
>>> concat_strings(list_)
'The cow goes moo !'
>>> list_ = (["This", "senten... | bbeb884e2cd4c689ce6e61c147558c993acc5f09 | 3,636,272 |
def produce_grid(tuple_of_limits, grid_spacing):
"""Produce a 2D grid for the simulation system.
The grid is based on the tuple of Cartesian Coordinate limits calculated in
an earlier step.
Parameters
----------
tuple_of_limits : tuple
``x_min, x_max, y_min, y_max``
grid_spacing : ... | 9ce30e74e4740cdbde520eb71156c6ce4799304e | 3,636,273 |
def intensity_histogram_measures(regionmask, intensity):
"""Computes Intensity Distribution features
This functions computes features that describe the distribution characteristic of the instensity.
Args:
regionmask=binary image
intensity= intensity image
"""
feat= Intensity_His... | f1bcb7a3517555d68193c9e526d0016eee81d4b5 | 3,636,274 |
def match(input_character, final_answer):
"""
:param input_character: str, allow users to input a string that will be verified whether
there are any matches with the final answer.
:param final_answer: str, the final answer.
:return: str, return the matching result that could consist of '-' and lette... | 4323cd2eefa00126baad11576cdc9a29fe94ec0b | 3,636,275 |
import os
import json
def read_json(filename, **kwargs):
"""Read JSON.
Parameters
----------
filename : str
**kwargs
Keyword arguments into :meth:`~astropy.cosmology.Cosmology.from_format`
Returns
-------
`~astropy.cosmology.Cosmology` instance
"""
# read
if isins... | c120ba1f231430e3c0ed44130b65f6a67b3facc2 | 3,636,276 |
def render_error(request, status=500, title=_('Oops!'),
err_msg=_('An error occured')):
"""Render any error page with a given error code, title and text body
Title and description are passed through as-is to allow html. Make
sure no user input is contained therein for security reasons. The... | 26c5bc2a6699a1065bc492d8ca8c83d4146dae58 | 3,636,277 |
def affaire_spatial(request):
"""
Get modification affaire by affaire_fille
"""
# Check connected
if not check_connected(request):
raise exc.HTTPForbidden()
results = request.dbsession.query(VAffaire).filter(
VAffaire.date_cloture == None
).filter(
VAffaire.date_envo... | 1f1743765f0c044a1070b5ee3cc7a2328233c24a | 3,636,278 |
def get_cosets(big_galois: GaloisGroup, small_galois: GaloisGroup) -> SetOfCosets:
"""
Given a big group `big_galois` and a subgroup `small_galois`, return the cosets
of small_galois \\ big_galois.
Args:
big_galois: A `GaloisGroup` whose cosets to examine
small_galois: The acting subgro... | b312a490727f860f8e1423cf0ab7e877e8df6ba4 | 3,636,279 |
import argparse
def create_parser(args):
""" Function which add the command line arguments required for the cyclomatic complexity report parser"""
# Create the parser
cyclo_parser = argparse.ArgumentParser(description='cyclomatic complexity gate Parser')
# Add the arguments
cyclo_parser.add_argum... | 46ddafdf458c20d323bc86974525f91320a33ae3 | 3,636,280 |
import calendar
def get_month_day_range(date):
"""
For a date 'date' returns the start and end date for the month of 'date'.
Month with 31 days:
>>> date = datetime.date(2011, 7, 27)
>>> get_month_day_range(date)
(datetime.date(2011, 7, 1), datetime.date(2011, 7, 31))
Month with 28 days:... | 610ff43b0e637afba780119c76181c6ff033a299 | 3,636,281 |
def measure_of_risk_callback(app):
"""
Attaches the callback function for the component
rendered in the measure_of_risk function
Args:
app = the dash app
Returns:
None
"""
component_id = 'measure-risk'
@app.callback(
Output(component_id + 'out', 'children'),
... | 6beabaae619a94db258d41e1f9062de4018fbf68 | 3,636,282 |
from typing import Union
from typing import Optional
from typing import Tuple
from typing import cast
from typing import List
def dot(
a: Union[float, ArrayLike],
b: Union[float, ArrayLike],
*,
dims: Optional[Tuple[int, int]] = None
) -> Union[float, Array]:
"""
Get dot product of simple numbe... | 298f9ea31386eff1dee33aec4fa47a29fd5a6f20 | 3,636,283 |
def read_float64(field: str) -> np.float64:
"""Read a float64."""
return np.float64(field) if field != "" else np.nan | f26da82fa22e79a370facad2d787ce3aee70723a | 3,636,284 |
def write_hypergraph(hgr, colored = False):
"""
Return a string specifying the given hypergraph in DOT Language.
@type hgr: hypergraph
@param hgr: Hypergraph.
@type colored: boolean
@param colored: Whether hyperedges should be colored.
@rtype: string
@return: String specify... | 2e25eecd84ea0d8724c6f4618478e1cd7a7676d6 | 3,636,285 |
def sort_gtf(gtf_path, out_path):
"""Sorts a GTF file based on its chromosome, start position, line number.
:param gtf_path: path to GTF file
:type gtf_path: str
:return: path to sorted GTF file, set of chromosomes in GTF file
:rtype: tuple
"""
logger.info('Sorting {}'.format(gtf_path))
... | 5cb1289b81a0c05a138cac5d2ae6213f46d47110 | 3,636,286 |
def leia_dinheiro(msg):
"""
-> Recebe um valor digitado pelo usuário e verifica se é um
valor númerico válido
:param msg: Mensagem a ser mostrada ao usuário
:return: Retorno o valor digitado pelo usuário caso seja válido
"""
while True:
num = input(msg).strip().replace(',', '.') # S... | aa8e21243009af1fde6d6c5e9cb611acff36369e | 3,636,287 |
from typing import OrderedDict
def format_analyse(parsed_tokens, to_1d_flag=False):
"""
入力
parsed_tokens # list(list(str)) : 変数毎の変数名/インデックスがtokenizedなトークンリスト
出力
res,dic # FormatNode,OrderedDict<str:VariableInformation> : フォーマット情報のノードと変数の情報を保持した辞書を同時に... | 76d42cc83f26c31273ae6aadd42479861c49ff69 | 3,636,288 |
def KAMA(df: pd.DataFrame, window: int = 10, pow1: int = 2, pow2: int = 30) -> pd.DataFrame:
"""
Kaufman's Adaptive Moving Average (KAMA) is an indicator that
indicates both the volatility and trend of the market.
"""
df_with_signal = df.copy()
df_with_signal["signal"] = kama(df["close"], window... | 79f23b1c840a4bc0860d9bc84fceceedb1c1b6b3 | 3,636,289 |
def cast_to_str(obj):
"""Return a string representation of a Seq or SeqRecord.
Args:
obj (str, Seq, SeqRecord): Biopython Seq or SeqRecord
Returns:
str: String representation of the sequence
"""
if isinstance(obj, str):
return obj
if isinstance(obj, Seq):
retu... | cd4100c6ef41b9ff33346349f6c70ac30e9ccd20 | 3,636,290 |
def _octet_bits(o):
"""
Get the bits of an octet.
:param o: The octets.
:return: The bits as a list in LSB-to-MSB order.
:rtype: list
"""
if not isinstance(o, int):
raise TypeError("o should be an int")
if not (0 <= o <= 255):
raise ValueError("o should be between 0 and ... | f472a2ab65702e59439b7693260abf040d4e7742 | 3,636,291 |
from aiida.common.links import LinkType
from aiida.orm.data import Data
from aiida.orm.calculation import Calculation
from aiida.orm.calculation.job import JobCalculation
from aiida.orm.calculation.work import WorkCalculation
from aiida.orm.calculation.inline import InlineCalculation
import hashlib
import os
def _col... | f63a22ee3bcecced6503b27e894288241d8d9d3f | 3,636,292 |
import networkx
def to_graph(l):
"""
Credit: Jochen Ritzel
https://stackoverflow.com/questions/4842613/merge-lists-that-share-common-elements
"""
G = networkx.Graph()
for part in l:
# each sublist is a bunch of nodes
G.add_nodes_from(part)
# it also implies a number of ... | da50880d4b056ffcf538b305dc418cdb11d2f41f | 3,636,293 |
def convert_mcmc_labels(param_keys, unit_labels=False):
"""Returns sequence of formatted MCMC parameter labels
"""
keys = list(param_keys)
for i, key in enumerate(keys):
if 'qb' in key:
label_str = r'$Q_\mathrm{b,' + f'{key[-1]}' + '}$'
elif 'mdot' in key:
label_... | d4059cd0b43f7968d0a59e7f760d9a226c4e6af1 | 3,636,294 |
def superuser_exempt(filter_authorization_verification):
"""Decorator to exempt any superuser from filtering, authorization, or verification functions."""
def superuser_exempt_fun(request, arg):
if request.user.is_superuser:
if isinstance(arg, QuerySet):
return arg
... | 1fa3752971be8ba291fd454c0704673b6687af9d | 3,636,295 |
import os
def relName(path, cwd=None, root=None):
"""Return pathname relative to `cwd`.
If possible, returns a relative pathname for path. The rules are:
1. If the file is in or below `cwd` then a simple relative name is
returned. For example: 'dir/fred.c'.
2. If both the file and `... | 59b096e1e080441177a6a4d72c2e8c7a2e30b3df | 3,636,296 |
def paf_to_lastz(job, paf_file, sort_secondaries=True):
"""
Makes lastz output using paftools.js. Also splits the input paf_file into two files
in the output, one for the primary and the other for secondary.
sort_secondaries bool, if true, will cause fxn to return two files instead of one.
"""... | 3bde7a90c71452bdc189e20bbc1e220179c2d35d | 3,636,297 |
from mindquantum import Circuit
def u1(lambd, q):
"""Openqasm u1 gate."""
return Circuit().rz(lambd, q) | 723035f9e3822e1a7ae385fba5bee51f457936a8 | 3,636,298 |
def get_simple_object(key='slug', model=None, self=None):
"""
get_simple_object() => Retrieve object instance.
params => key, model, self
return => object (instane)
"""
try:
if key == 'id':
id = self.kwargs['id']
instance = model.objects.get(id=id)
else:
... | 218a742e8652b3edebd6be9676e10c7b5dd709ab | 3,636,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.