content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import math
def sequential_clustering(singleton_list, num_clusters):
"""
Take a data table and create a list of clusters
by partitioning the table into clusters based on its ordering
Note that method may return num_clusters or num_clusters + 1 final clusters
"""
cluster_list = []
... | 5239dae52107ba60ae3053d0b90b139d8bffa9e7 | 51,120 |
def normalize_point_cloud(inputs):
"""
input: pc [N, P, 3]
output: pc, centroid, furthest_distance
"""
#print("shape",input.shape)
C = inputs.shape[-1]
pc = inputs[:,:,:3]
if C > 3:
nor = inputs[:,:,3:]
centroid = np.mean(pc, axis=1, keepdims=True)
pc = inputs[:,:,:3] - ... | 02be80ca8287af82140cdf9f68a0d48c70441d76 | 51,122 |
import click
def info(country_name):
"""Brief information about a country."""
country = return_country(country_data, country_name)
currency = return_country(currency_data, country_name)
calling_code = return_country(country_calling_code, country_name)
if currency is None and country is None and ... | c5c8e41c9c79f60592f8e35c3cebdfe220881b8a | 51,123 |
def aCoulomb(r, t=0, charge=-1):
"""
Coulomb acceleration calculation.
Input: r, t --Spatiotemporal coordinates.
charge --Coulomb charge. (Default: -1)
Output: aCoulomb --Acceleration vector.
"""
return(r*charge/blas.dznrm2(r)**3) | 00f5db2dd6dcd42d4704096583399cedc498e6f6 | 51,124 |
def get_finite(arr):
"""
Select only finite elements of an array.
"""
return arr[np.isfinite(arr)] | 09016626ec77c1e8b3cb2255b0ecac366c7f9a2d | 51,125 |
def get_x_from_index(index: int) -> int:
"""Compute the x-coordinate with the provided x index.
This method compute the x coordinate associated with the
given x index. The returned value has the same dimension as
the constants provided in _constants.py.
Parameters:
index (int): The circuit... | eca24874f91098900de34d29351c27341dab4204 | 51,127 |
import awkward1.highlevel
import numbers
import numpy
from typing import Iterable
def to_numpy(array, allow_missing=True):
"""
Converts `array` (many types supported, including all Awkward Arrays and
Records) into a NumPy array, if possible.
If the data are numerical and regular (nested lists have eq... | 52a0e0425bcded9b6dd5afe7be543a844728de7f | 51,128 |
def coeff_generator(style, func):
"""Make a Coefficient"""
if func == "f":
base = f
else:
base = g
if style == "func":
return coefficient(base, args=args)
if style == "array":
return coefficient(base(tlist, **args), tlist=tlist)
if style == "arraylog":
re... | 6aec6c0a1044e711390649002410d5dadc8d36f7 | 51,131 |
def load_imagenet_meta(meta_path):
"""It reads ImageNEt metadata from ILSVRC 2012 dev tool file
Args:
meta_path: path to ImageNet metadata file
Returns:
wnids: list of ImageNet labels(as strings)
words: list of words(a... | c96ec911c7fdadfa975a774a77177decb090dcd3 | 51,132 |
def _static_folder_path(static_url, static_folder, static_asset, prefix=''):
"""
Returns a path to a file based on the static folder, and not on the
filesystem holding the file.
Returns a path relative to static_url for static_asset
"""
# first get the asset path relative to the static folder... | 2b160faadd8ef8c9f436452542810de9a6701b34 | 51,133 |
def get_df_by_month(df, month):
"""Return ."""
cols = get_column_by_month(df, month)
basic = ['uid', 'age', 'sex', 'active_date', 'limit']
dates_col = [ACTIVE_MONTH, ACTIVE_YEAR, ACTIVE_DOW]
# this get sum of loans of 8,9,10,11
cols_12_cum = get_column_by_month(df, '12')
cols_12_cum.remove('... | b3f74dd934038932b991fd850c9d80eb397100f7 | 51,134 |
def mock_protocol_engine(decoy: Decoy) -> ProtocolEngine:
"""Get a mock EngineStore interface."""
return decoy.mock(cls=ProtocolEngine) | 83ff94a15d104551bcbfa5b98ed3f10de79519cd | 51,135 |
def wrap_render_to_string(f):
""" decorator for django.template.loader.render_to_string """
@wraps(f)
def wrapper(template_name, context=None, request=None, *args, **kwargs):
if request is not None and has_variant(request):
template_name = get_templates(template_name, get_variant(reques... | 8ea8801755f7a6d6486f952c13d75cbebad032da | 51,136 |
import json
def dumps(dict_):
"""
Converts dictionaries to indented JSON for readability.
Args:
dict_ (dict): The dictionary to be JSON encoded.
Returns:
str: JSON encoded dictionary.
"""
string = json.dumps(dict_, indent=4, sort_keys=True)
return string | c2f3eabe0b473def6233476018d8c3a3918beb70 | 51,137 |
def camel_case_to_snake_case(name):
"""
HelloWorld -> hello_world
"""
s1 = _FIRST_CAP_RE.sub(r'\1_\2', name)
return _ALL_CAP_RE.sub(r'\1_\2', s1).lower() | 2cf136866815cc63f5335d2fe1d68586b1ece88e | 51,138 |
def num_nets_provisioned(context, project_id):
"""Returns number of networks for a given tennat.
:param project_id: globally unique neutron tenant identifier
"""
return context.session.query(db_models.AristaProvisionedNets). \
filter_by(project_id=project_id).count() | 8d848fe77c76370318142d020fe5a551a6a0f6b2 | 51,139 |
def csundir_vect(time_in):
"""
Calculate the direction of the sun.
Parameters
----------
time_in: list of float
Time array.
Returns
-------
gst: list of float
Greenwich mean sideral time (radians).
slong: list of float
Longitude along ecliptic (radians).
... | 8a0973af076690922f6be55e552a61cb10ee75d2 | 51,140 |
def process_image(img,skip_dilate=False):
"""Uses a blurring function, adaptive thresholding and dilation to expose the main features of an image."""
# Gaussian blur with a kernal size (height, width) of 9.
# Note that kernal sizes must be positive and odd and the kernel must be square.
proc = cv2.Gaus... | a83996f96d4c473cdbd9dfe3fab7a16da7fe6c15 | 51,142 |
from datetime import datetime
def sample_game(**params):
"""Create and return a sample game"""
defaults = {
'igdb_id': 1,
'name': 'Mass Effect',
'summary': 'best game ever',
'rating': 90,
'first_release_date': datetime.datetime.fromtimestamp(1317945600)
}
defaul... | bfb4ef5e0fb93b9ab49d921e7509b2681bff3ac1 | 51,143 |
def minkowski_distance(dataset=None, x=None, y=None, p_value=None):
"""generalization of the euclidean and manhattan distances.
:param dataset: two object dataset with numeric attributes
:param x: list of first object's numeric attributes
:param y: list of second object's numeric attributes
:return:... | 4cc9ec7efbc16ad1cfde9f39135a42168e996f3c | 51,144 |
def most_symmetric_integer_factorization(N):
"""
Calculates the "most symmetric" integer factorization of N. This is the closest two integer factors of N. If N is
a square number, the integer factorization is "symmetric" and (sqrt(N), sqrt(N)) is the most "symmetric"
factorization.
Args:
N:... | bd633302c4ba9baf97e3da2abd27b5eb915ba240 | 51,145 |
import inspect
def alias_version(func):
"""Wrapper function to support aliasing of SPICE body names or codes.
"""
if hasattr(func, 'alias'):
return func.alias
if not hasattr(func, 'ALIAS_ARGS'):
alias_args = {}
for k in range(len(func.ARGNAMES)):
sig = func.SIGNAT... | 2d98fee83368ccb1e8aa1e020b8179477b275654 | 51,146 |
from typing import List
def count_nucleotides(lines: List[str]) -> str:
"""
:param lines: A line, in a list representing DNA sequence
:return: Four numbers separated by spaces - respective number of A, C, G and T nucleotides in input
"""
# only one sequence is expected
dna_sequence, = lines
... | d6d7e2a9c229ba1e006f39b05f54d12523cf088c | 51,147 |
def parsedir(directory, parsed, files, blocked, exts=('.torrent',),
return_metainfo=False, errfunc=_errfunc):
"""Parse bencoded files in a directory structure.
Parameters
str - path of directory
{str: {str: *}}
- dictionary, keyed by sha hash of encoded info dic... | 7674f5e0280d151062d36a305f85ec97535184b7 | 51,148 |
def jpeg_linqual(quality):
"""
See int jpeg_quality_scaling(int quality)
in libjpeg-turbo source (file ijg/jcparam.c).
Convert quality rating to percentage scaling factor
used to scale the quantization table.
"""
quality = max(quality, 1)
quality = min(quality, 100)
if quality < 50:
... | a35157416fd4d95dddfe6cf8408a99e6247703ba | 51,150 |
def pytest_funcarg__content(request):
"""
The content for the test document as string.
By default, the content is taken from the argument of the ``with_content``
marker. If no such marker exists, the content is build from the id
returned by the ``issue_id`` funcargby prepending a dash before the i... | e357042566ce22557ba5c8f83b14f56cb8025dca | 51,151 |
def _apply_weighting(F, loss, weight=None, sample_weight=None):
"""Apply weighting to loss.
Parameters
----------
loss : Symbol
The loss to be weighted.
weight : float or None
Global scalar weight for loss.
sample_weight : Symbol or None
Per sample weighting. Must be bro... | e7d73368c1194f98c44861137d23231c565a415a | 51,155 |
def split_s3_path(s3_path):
"""
Splits the complete s3 path to a bucket name and a key name,
this is useful in cases where and api requires two seperate entries (bucket and key)
Arguments:
s3_path {string} -- An S3 uri path
Returns:
bucket {string} - The bucket name
key {... | 81efc5fc125c62d4dcde577b3424029acb4a536f | 51,156 |
def build_reference_wcs(inputs, sciname='sci'):
"""Create the reference WCS based on all the inputs for a field"""
# start by creating a composite field-of-view for all inputs
wcslist = []
for img in inputs:
nsci = countExtn(img)
for num in range(nsci):
extname = (sciname, nu... | 63d792275898bc2d6b4d8187d7f7d799ae22dc33 | 51,157 |
def get_q_rq_H(region, R_type):
"""単位面積当たりの必要暖房能力
Args:
region(int): 省エネルギー地域区分
R_type(string): 居室の形式
Returns:
float: 単位面積当たりの必要暖房能力
"""
if R_type == '主たる居室':
return get_table_m_2()[0][region - 1]
elif R_type == 'その他の居室':
return get_table_m_2()[1][region - 1]... | ac3196e6583d2bfc24555c66f0b575971937bab9 | 51,160 |
import zipfile
def createZip(zip_name, src):
"""
parameter:- zip file name , folder path
This will create zip file
"""
zipf = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED)
for file in src:
zipf.write(file)
zipf.close()
print("--------zip file created --------")
... | 325f8a6b63f4a8c2d46b8d07bfc3b3e938d50836 | 51,161 |
def dash(*txts):
"""Join non-empty txts by a dash."""
return " -- ".join([t for t in txts if t != ""]) | 53566f49991f8d7930a63f7d2d22c125d9d25073 | 51,162 |
def quarter(month):
"""
:int month: Any month, as an int.
:return: The quarter of the year during which that month occurs (1-4)
"""
return int(ceil(float(month) / 3)) | 76d4e58e3b68870d9fc2f9697580fdef6624cc13 | 51,163 |
import asyncio
import functools
def call_later(delay, fn, *args, **kwargs) -> asyncio.Handle:
"""
Call a function after a delay (in seconds).
"""
loop = asyncio.get_event_loop()
callback = functools.partial(fn, *args, **kwargs)
handle = loop.call_later(delay, callback)
return handle | 86d157ed0f5f8dc7f806af9871a71057dc36222c | 51,164 |
from typing import Tuple
def build_blacklist_status(blacklist_status: str) -> Tuple[str, str, str]:
"""Build the blacklist_status
@type blacklist_status: str
@param blacklist_status: The blacklist status from command line
@returns Tuple[str, str, str]: The builded blacklist status
"""
blackli... | 10f0c3a77169a0e9b9136d454e6d17efdd4760f6 | 51,165 |
import spwd
import grp
def isuser(username, domain, password=None):
"""Check if user exists and if he is a member of the group 'domain'."""
try:
spwd.getspnam(username)
return username in grp.getgrnam(domain)[3]
except KeyError:
return False
except PermissionError:
prin... | 70e920c0fe3212c3e2588bc429c745fe134653e7 | 51,166 |
from typing import Match
def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
"""Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to... | f02e9ea980b2d68e2e03207209d14ab5e2f3f236 | 51,168 |
def dataclassAsDict(obj) -> dict:
"""
Return dataclass values as ``dict``.
This is a non-recursive variant of ``dataclasses.asdict``.
"""
if not is_dataclass(obj):
raise TypeError(f'Object {obj} is not a dataclass')
return {field.name: getattr(obj, field.name) for field in fields(obj)} | 0b026e4442f7ce06ef4afec026c6d5cef40d3180 | 51,169 |
async def server_error(request, exc):
"""
Return an HTTP 500 page.
"""
response = "Server error"
return PlainTextResponse(response) | 4bff48761e456261b95f825f5d38317918390e0d | 51,170 |
def _check_substituted_domains(patchset, search_regex):
"""Returns True if the patchset contains substituted domains; False otherwise"""
for patchedfile in patchset:
for hunk in patchedfile:
if not search_regex.search(str(hunk)) is None:
return True
return False | e3fdeaa1ede7f041bb6080d4647c8d969b41f73d | 51,171 |
def build(
requirements, # type: Iterable[InstallRequirement]
wheel_cache, # type: WheelCache
build_options, # type: List[str]
global_options, # type: List[str]
):
# type: (...) -> BuildResult
"""Build wheels.
:return: The list of InstallRequirement that succeeded to build and
t... | 7f174ec0b7aa6ea2ee73c192d68c33353bb37e3e | 51,172 |
import re
def prepareReposToJson(json_repos):
"""
Convert information about repo to proper format
:param json_repos:
:return: dictionary
"""
columns = ["created_on", "description", "fork_policy", "full_name", "has_issues", "has_wiki", "is_private",
"language", "links", "mainbran... | 40eaa03779b0161f78250a174e19b77041d511e8 | 51,175 |
def notifications(context):
"""
This renders the actual box where popup notifications get displayed on screen
"""
return render_to_string('notifications/display.html', {}, context) | 88a48f14f6557c75951ae5d514807f35d39f12e9 | 51,176 |
from typing import Optional
def draw_self_loop(
point: np.array,
ax: Optional[plt.Axes] = None,
padding: float = 1.5,
width: float = 0.3,
plot_size: int = 10,
linewidth: float = 0.2,
color: str = "pink",
) -> plt.Axes:
"""Draw a loop from `point` to itself
!Important! By "center" ... | 4f33d750d3228b16302cea8819bf102051345fa9 | 51,180 |
def verify_arguments(target, method_name, args, kwargs):
"""Verifies that the provided arguments match the signature of the provided method.
:param Target target: A ``Target`` object containing the object with the method to double.
:param str method_name: The name of the method to double.
:param tuple ... | f9975e11d21834664ce31e0d0b0d924b271c6db4 | 51,181 |
def _get_routine_reference(self, routine_id):
"""Constructs a RoutineReference.
Args:
routine_id (str): the ID of the routine.
Returns:
google.cloud.bigquery.routine.RoutineReference:
A RoutineReference for a routine in this dataset.
"""
return RoutineReference.from_api... | 740b26d21676289f55688ee834017b62ad8324b6 | 51,183 |
def file(file_path: str) -> File:
"""
Returns a File object for a specified file path.
:param file_path:
:return File: a ReadableFile or ConvertibleFile object.
"""
if not is_found(file_path):
raise FileNotFoundError(file_path)
elif check_ext(file_path, Extensions.HISTOGRAM) and is... | f17dd501b92bd7cc3e40d64aaebd92c943a19826 | 51,184 |
from re import T
def get_bias_offset(nnet):
"""
returns the offset to balance the polynomial parameters possible by the bias
terms of the network.
"""
offset = 0
L = len(nnet.trainable_layers)
for l in range(L-1):
layer = nnet.trainable_layers[l]
if layer.b is not None:
... | 79b44c65c7a8b533a4c474977edc8eb6e63b0b9e | 51,185 |
def export_liaison(request):
"""导出所有联系人信息"""
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="liaison.xls"'
# 创建一个workbook,设置编码
wb = xlwt.Workbook(encoding='utf-8')
# 创建一个worksheet,对应excel中的sheet,表名称
ws = wb.add_sheet('liai... | f66b2a0e412bbfac8c201523c77554f3a2c4e31a | 51,186 |
def get_percentage(df, filename=None, dropna=True):
"""
Normalise results to be plotted
"""
if len(df.columns) > 1 and len(df.index) > 1:
by_row, by_col = True, False
else:
by_row, by_col = True, True
if dropna is True:
# get nan Percentage
# 'Percentage NaN'
... | 9488848f41b693695ab9c21cf59d9aa4057efb04 | 51,187 |
def third_octaves(p, fs, density=False,
frequencies=NOMINAL_THIRD_OCTAVE_CENTER_FREQUENCIES,
ref=REFERENCE_PRESSURE):
"""Calculate level per 1/3-octave in frequency domain using the FFT.
:param x: Instantaneous signal :math:`x(t)`.
:param fs: Sample frequency.
:param... | 3d6abc7d30181300205fc7d4aa0cb429cf032a9a | 51,188 |
import torch
def convert_to_one_hot(
targets: torch.Tensor,
num_class: int,
label_smooth: float = 0.0,
) -> torch.Tensor:
"""
This function converts target class indices to one-hot vectors, given the number of classes.
Args:
targets (torch.Tensor): Index labels to be converted.
... | 344d527e9d799c03e710c07ea9229e0a0f34599c | 51,189 |
def flow_schema(dps):
"""Return schema used in config flow."""
return {
vol.Optional(CONF_FAN_SPEED_CONTROL): vol.In(dps),
vol.Optional(CONF_FAN_OSCILLATING_CONTROL): vol.In(dps),
vol.Optional(CONF_FAN_DIRECTION): vol.In(dps),
vol.Optional(CONF_FAN_DIRECTION_FWD, default="forward... | 94513cd2fe1302f022fb214231a18630c6e2accc | 51,191 |
from typing import Tuple
import torch
def fast_rcnn_inference_single_image(
boxes,
scores,
image_shape: Tuple[int, int],
score_thresh: float,
nms_thresh: float,
topk_per_image: int,
aps_thresh: float,
):
"""
Single-image inference. Return bounding-box detection results by threshold... | 17d2893d6fdfb7d1e03759352cba46508f2b2f5c | 51,192 |
def StrSubstr(start_idx, count, initial_string):
"""
Create a concrete version of the substring
:param start_idx : starting index of the substring
:param end_idx : last index of the substring
:param initial_string
:return : a concrete version of the substring
"""
new_value = initial_str... | 88b0c077ec38fec1d0a5baa247114f472944c424 | 51,194 |
def delete_segment(seq, start, end):
"""Return the sequence with deleted segment from ``start`` to ``end``."""
return seq[:start] + seq[end:] | 1eba39d373ac2ab28ea1ea414f708a508bdf48d2 | 51,195 |
def placeNodesInLevels(nodes, edge_function):
"""Given a node "N" and an edge function, divide nodes into a sequence of groups
so that nodes never flow into their own group or an ealier group. Throw
if this has a cycle
"""
all_nodes = findAllNodes(nodes, edge_function)
reverse_edges = {c: set()... | e61b90bcc3bf384254a444f0da6c53c301cd3ae3 | 51,196 |
from typing import List
def voronoi_coloring(
points: List[complex],
centers: List[complex],
colors: List[Color]) -> Frame:
"""Convert the list of complex points to color output frame.
Args:
points (List[complex]): Input "image".
centers (List[complex]): Region centers... | 5a5376f8f033583caf5f58ae62f121854ebdb377 | 51,197 |
def get_directions(i0, i1, i2, i3):
""" get list of directions in a certain sequence """
return [directions_list[i0], directions_list[i1], directions_list[i2], directions_list[i3]] | e28cc069071807df3d892fc2f0e2b0d7ecbe8e4f | 51,198 |
def press_valve_route(action):
"""Route for press valve
Arguments:
action {string} -- Define the state change for the LOX and FUEL
Returns:
string -- Returns the valve controllers message
"""
if ser.is_open == True:
if action == 'FUEL-PRESS-OPEN':
ser.write(b'O1\n')
message = ser... | 5307fdb775e982f61af73b521ae04642067077cd | 51,199 |
import math
def triangleSum(n):
"""
Finding the sum of 1+2+...+n
:param n: the last interger to be added
:return: the sum
"""
n = math.floor(n)
if n > 1 :
return n+triangleSum(n-1)
return 1 | 4bffb8d8d758730b161a572fad447e5420c30490 | 51,200 |
def replace_database_in_url(db_url: str, db_name: str) -> str:
"""
replaces the database portion of a database connection URL with db_name
@param db_name database name to replace with
"""
db_url_parsed = urlparse(db_url)
db_url_parsed = db_url_parsed._replace(path=f"/{db_name}")
return db... | de8d2303b84e9172fc28f02d1650afd5f4f8148e | 51,201 |
import re
def detect_arxiv(txt):
"""
Extract an arXiv ID from text data
"""
regex = r'arXiv:[0-9]{4,4}\.[0-9]{5,5}(v[0-9]+)?'
m = re.search(regex, txt)
if m is not None:
return m.group(0)
else:
return None | a855497b6eb1f027085a301096735e860e76fbe7 | 51,203 |
from operator import and_
async def get_contributor_by_username(
*,
username: str,
session: Session = Depends(dal.get_session)
) -> contributor_schemas.Details:
""" Get contributor record from DB """
conditions = and_(
User.username == username,
)
db_contributor = contributor_ops... | b220cac092f3daf384ffb574a8cdd8142ecfef90 | 51,204 |
def display(image, title=' ', resolution=(960, 540)):
"""Uses cv2 to display an image then wait for a button press
pts is either None or an integer specifying the number of point
and click events you'd like to capture"""
cv2.namedWindow(title, cv2.WINDOW_KEEPRATIO)
cv2.resizeWindow(title, *... | a6ab9b462b1d253a99c303f9bfab20250a3a04a4 | 51,205 |
def get_narrative_cell_counts(wsadmin, narrative_ref):
"""
Gets the number of App Cells and Code Cells in the narrative
See documentation for WS administer here
https://github.com/kbase/workspace_deluxe/blob/02217e4d63da8442d9eed6611aaa790f173de58e/docsource/administrationinterface.rst
"""
app_c... | d00bd855459fbd9ea5a7824ae85462c9df2e2a13 | 51,207 |
def calculate_emotions(labeled_emotions, labeled_intensities):
"""
Calculate the emotions that are present in each sentence taking into consideration the values given
by the different annotators.
Args:
labeled_emotions (np.ndarray): Emotions labeled as list of string numbers.
labeled_int... | 0e872ee65af6a5a48fc6a6afb7e71314b16d603d | 51,208 |
from typing import Tuple
def xiang_dsp_kernel(X: ndarray, y: ndarray) -> Tuple[ndarray, ndarray, ndarray, ndarray]:
"""dsp algorihtm based on paper[1].
Parameters
----------
X : ndarray
EEG data assuming removing mean, shape (n_trials, n_channels, n_samples)
y : ndarray
labels, sh... | 35b7a449cb1493645bd6e0ab2137bdcbe13d62c3 | 51,209 |
from typing import List
def get_free_remote_ports(count: int, node: Node) -> List[int]:
"""Returns several free remote ports.
See :func:`.get_free_remote_port`.
:param count: Free port count.
:param node: Node to find a port on.
"""
result = {get_free_remote_port(node=node) fo... | 727766eb04aa1c709ded7a003c7e2afc5a5e0369 | 51,210 |
def precipitation():
"""Return dictionary using date as the key and prcp as the value."""
# Create our session (link) from Python to the database
session = Session(engine)
# Query all prcp and dates
results = session.query(Measurement.prcp, Measurement.date).all()
# Close out our link
sessio... | c1d6577e8d783a8744636a85a36dd7d55e0d1554 | 51,211 |
def canonical_source(spec, filter_multimethods=True, source=None):
"""Get canonical source for a spec's package.py by unparsing its AST.
Arguments:
filter_multimethods (bool): By default, filter multimethods out of the
AST if they are known statically to be unused. Supply False to disable.
... | 557e24ae26ec54b72825bd80957647b6647f872b | 51,212 |
def pointsEqual(a, b):
"""
checks if 2 [x, y] points are equal
"""
for i in range(0, len(a)):
if a[i] != b[i]:
return False
return True | 7341c1aa417ef8979662c1ef3e67cad1e902422e | 51,213 |
from operator import add
def move(directions):
"""Meh
>>> move(parse_directions(EXAMPLE))
[100 10] [10 1]
[100 10] [10 4]
[170 38] [10 4]
[170 38] [ 4 -10]
[214 -72] [ 4 -10]
286
"""
wpt = np.array((10, 1), dtype=int)
pos = np.array((0, 0), dtype=int)
for where... | f089443ad3848fdc622af7e90ed396e85118a6ee | 51,214 |
def _choose_convolve(z_i, ds):
"""Choose between _dense_convolve and _sparse_convolve with a heuristic
on the sparsity of z_i, and perform the convolution.
z_i : array, shape(n_atoms, n_times_valid)
Activations
ds : array, shape(n_atoms, n_times_atom)
Dictionary
"""
assert z_i.s... | efced323dfbaca84b3b1a9500f30f3752e5e943f | 51,215 |
from pathlib import Path
from typing import Sequence
from typing import Optional
def find_and_test_all(root_dir: Path, file_templates: Sequence,
timeout: Optional[float] = None) -> bool:
"""Run standard sanity tests on all files.
Args:
root_dir: Find all files that satisfy the t... | 6a85ca729b95fedb22fd24f2f9b2cac0b5fd4441 | 51,216 |
import requests
def healthy2_check_in(token, custom_id, post_dict):
"""
第二类健康打卡
:param token: 用户令牌
:param custom_id: 健康打卡id
:param post_dict: 健康打卡数据
:return:
"""
if not post_dict.get("whereabouts"):
errmsg = f"完美校园第二类健康打卡方式错误,请选第一类健康打卡"
log.warning(errmsg)
retur... | ad4b78ac1d433ad244fbde569407f3c3a95ce27a | 51,217 |
from dtale_desktop import app
def app(monkeypatch, tmpdir):
"""
Sets environment variables before importing the app.
"""
monkeypatch.setenv("DTALEDESKTOP_ROOT_DIR", tmpdir.strpath)
return app | a3d7d1074e399360fa902edac2f3e9dccb7f2ea1 | 51,218 |
def allowed_file(filename):
"""
Return true if a file is allowed.
Args:
filename: (str): write your description
"""
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS | 4d576787e9761b08a89baa1ca42939bc0f1bd29b | 51,220 |
def refine(window_priors, window_info, null_variance=0.42 ** 2, cs_val=0.95,
cs_merge_buffer=200000, cov_df=None, jac_cutoff=0.8):
"""
Refines a set of windows given their prior probability and effect size estimates
Inputs:
window_priors : dict of windows with prior probabilities
... | 64708f1e450de974f3fb5c023cbac51aa683af2d | 51,221 |
def get_google_client(credentials_file):
"""
Return this module's Google API client, creating a connection is one
does not already exist.
"""
global _client
if not _client:
# Connecting to google's API
logger.info("Connecting to Google API using credentials file {}".format(creden... | 224220752e64c32a78d72cfe38acb3e23d52221a | 51,223 |
def cut_sentences(text):
"""
将文本切成句子
:param text: 待切分文本
:return: 句子列表
"""
text = text.translate(str.maketrans('!?!?\r\n', '。。。。 '))
return [sen for sen in text.split('。') if len(sen.strip()) > 1] | 06e8b503c2c6e3ea73901bb19f2b4fba2f443e19 | 51,224 |
def _setup_conduction_constants(rr, ht_consts):
"""Set up numpy arrays to accelerate conduction calculation
Notes
-----
Creates dictionary attribute "_cond" which has keys "adj"
and "const". Usage is as follows:
dT_conduction = (self._cond['const']
* (self.temp['coolant_in... | 2876bd7e877f0b799f24508858802134c52cd7dd | 51,225 |
def full_justify(*args, **kwargs):
"""
Usage: $full_justify(<text>)
Returns <text> filling up screen width by adding extra space.
"""
if args:
return base_justify(args[0], align='f')
return "" | c5766245eca848e135a7987422e46d10750b0d24 | 51,226 |
def translation(translation):
""" Construct a homogeneous 2D translation matrix.
# Arguments
translation: the translation 2D vector
# Returns
the translation matrix as 3 by 3 numpy array
"""
return np.array([
[1, 0, translation[0]],
[0, 1, translation[1]],
[0,... | e397417c1d8b91c280386f005250be06b0337845 | 51,228 |
import itertools
def get_pairs(self, data, linked_clusters):
"""
Return pairs of linked clusters and establish which can be merged and which
cannot
"""
_linked_clusters = [_cluster.antecessor for _cluster in linked_clusters]
pairs = [pair for pair in itertools.combinations(_linked_clusters, ... | 1de2f8db3bd05665b05849fcbf09794f7fe843d9 | 51,229 |
import glob
def list_files(directory, reverse_sort=False, smart_sort=None, relative=False,
extension=None):
"""
Returns all the files from a directory.
Can set the filetype using extension.
Parameters
----------
directory : str
Filepath pointing to the dir... | 6dfc966eb58438be779d06d2220c46d9482d2718 | 51,230 |
def SubjectArgs(*args, **kwargs):
"""
Decorator that overrides the default arguments to the subject
initialiser.
:param args: The positional arguments to the subject initialiser.
:param kwargs: The keyword arguments to the subject initialiser.
"""
def applicator(method):
... | 66a972775d45d5668b4f2af49dc3a4b05aa17a25 | 51,231 |
def convert_words_to_chars(tokens: list) -> list:
"""
:param tokens:
:return:
"""
return list(set(chain.from_iterable(tokens))) | 1712f186aeaecc9f25bd1afcce4b078deea81aec | 51,232 |
def handler_supports_service(handler, service=None):
""" Convenience method to check whether or not a handler supports a service.
"""
if isinstance(handler.service, basestring):
return handler.service.upper() == service
else:
return service in handler.service | 5b256aae85b51ec3e676cc9f65d79a426e141729 | 51,233 |
from functools import reduce
def solution(input_str):
""" Solution to the problem """
inputstr = str(input_str)
rotated = inputstr+inputstr[0]
result = reduce(reducer, zip(rotated, rotated[1:]), 0)
return result | 9a4d2f3de42c804b610c510499698209337faf02 | 51,234 |
def get_persona_page(persona):
"""Obtains the html of the page for `peronsa`."""
# using firefox-geckodriver
driver = webdriver.Firefox()
# Persona 5 Royal Fusion Calculator website
driver.get(
"https://chinhodado.github.io/persona5_calculator/indexRoyal.html#/list")
searchbox = driver.f... | 1e9f702160517c56c44d958b89cef883fca7a909 | 51,236 |
def parse_signature_file(sig_file):
"""
Parses signatures from a file of signatures
:param sig_file: file-like object to pares
:return: list of signatures
"""
res = []
part_sig = ""
for signature in sig_file:
signature = part_sig + signature
part_sig = ""
if not s... | a41ed0bb65c67573f444da37c83018dea80a2a87 | 51,237 |
import functools
def single_format(func):
"""Manage format of dhcp response
"""
@functools.wraps(func)
def formatter(*args, **kwargs):
iface = args[0]
ans = func(*args, **kwargs)
#scapy stores all sequence of requests
#so ans[0][1] would be response to first request
... | 39ee3a135d0cecb87625be57a9c9bce0a95badc0 | 51,238 |
def to_literal(typ, always_tuple=False):
"""Convert a typestruct item to a simplified form for ease of use."""
def expand(params):
return (to_literal(x) for x in params)
def union(params):
ret = tuple(sorted(expand(params), key=str))
if len(ret) == 1 and not always_tuple:
ret, = ret # pylint:... | a628676073a09042689f64ab1aa4d12a2a87c463 | 51,239 |
def powmod(a, b, m):
""" Returns the power a**b % m """
# a^(2b) = (a^b)^2
# a^(2b+1) = a * (a^b)^2
if b==0:
return 1
return ((a if b%2==1 else 1) * powmod(a, b//2, m)**2) % m | 33b4cadc1d23423f32e147718e3f08b04bd2fd17 | 51,240 |
def test_module(client: Client) -> str:
"""
If a client was made then an accesses token was successfully reached,
therefore the username and password are valid and a connection was made
additionally, checks if not using all the optional quota
:param client: the client object with an access token
... | 977f6d2ba3e37ca428c90b63666b509ba92f1447 | 51,241 |
import numpy as np
def str_to_array(s):
"""
Simplistic converter of strings from repr to float NumPy arrays.
If the repr representation has ellipsis in it, then this will fail.
Parameters
----------
s : str
The repr version of a NumPy array.
Examples
--------
>>> s = "ar... | 858491f8c7279630951b1244a3ea630d932eb7c6 | 51,242 |
def check_cores(func):
"""
Checks how many cores the search has been configured to
use and then returns None instead of calling the pool
creation function in the case that only one core has
been set.
Parameters
----------
func
A function that creates a pool
Returns
----... | 5ecba37910e024cbf213adb04d2ed4fd7f5479c0 | 51,243 |
def get_potential_versions(servicename, **_):
"""
List the different versions of a service stored in the system
Variables:
servicename => Name of the service to get the versions
Arguments:
None
Data Block:
None
Result example:
['3.1.0', '3.2.0', '3.3.0', '4.0.0', ...] ... | b972908777bb07d40c4a25da34e05405c1c6f72b | 51,244 |
import functools
def generate_decorator(exception):
"""Ddecorator generator"""
def expected_error(test):
@functools.wraps(test)
def inner(*args, **kwargs):
try:
test(*args, **kwargs)
except exception:
assert True
else:
... | 7089aabfb4ad9ce51b08ec43ada1c27d6fe529f0 | 51,245 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.