content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_ordered_patterns(order, patterns):
"""
Place the sites in the pattern dictionary into the order that they were
added.
Input:
order: a list of pattern ids providing the order
patterns: a dictionary of patterns
Output: Nested array with columns for sites, their order, and ampl... | b3622fa9b3330923da819cd923582db13199f86a | 27,629 |
def extract_pphour(file, fecha, llat, llon):
"""
"""
l_lat = llat
l_lon = np.array(llon) % 360
i_lat, i_lon, lat, lon = get_index_lat(fecha, file, llat, llon)
tiempos = get_index_time(file, fecha)
di = tiempos[1]
di_f = (di + dt.timedelta(days=8)).replace(hour=0)
i_t1 = [i for i in r... | e5e2a2271e85a6d5a9f6fc4a189b1119f62d471b | 27,630 |
def bubble_sort2(array):
"""冒泡排序的经典实现"""
n = len(array)
stop = False
#子过程运行闭区间的右端点标记定义为i,范围[n-1,1],转换为适合while惯用区间为[n-1,0)
i = n-1
while i > 0 and not stop:
stop = True
#子过程交换位置标记定义为j,范围为[0,i-1],转换为适合while惯用区间为[0,i)
#子过程运行区间为[0,i]
j = 0
while j < i:
if array[j] > array[j+1]:
array[j],array[j+1] =... | c95706b40c6e328e321f68de117ee20faa5c1c31 | 27,631 |
def encriptar(texto):
"""função que recebe um texto e retorna o mesmo criptografado"""
#1. Filtro de entrada para evitar erros
#1.1 Verifica se texto é uma string
#1.1 Se texto é vazio, retorna texto
#2. remove os espaços em branco do texto
texto = texto.replace(" ","")
#3. sobre ... | 63afaf6bae94a7a9c43b3fea39bdd5df2916b195 | 27,632 |
from enum import Enum
def extend_enum(*inherited_enums: type[Enum]):
"""EXPERIMENTAL
Join multiple enums into one.
Modified version from: https://stackoverflow.com/a/64045773/14748231
"""
# All members from all enums which injected in result enum
joined_members = {}
def _add_item_if_not_... | 4ec9e36fdd584555e5c201d3a1899007fa9adb85 | 27,634 |
import requests
import csv
import io
def tsv_reader():
""" read register-like data from government-form-data TSV"""
resp = requests.get(url=url)
resp.raise_for_status()
return csv.DictReader(io.StringIO(resp.text), delimiter=sep) | 2487f44f516afc8727d1d0fd8b253578aaaef026 | 27,635 |
import time
def GetMonotime():
"""Older tornado doesn't have monotime(); stay compatible."""
if hasattr(tornado.util, 'monotime_impl'):
return tornado.util.monotime_impl
else:
return time.time | e0ea587512213b2a830b4912ae67928cb8515b98 | 27,636 |
def test_multiplica():
"""
Target function returns the sum of the multilica of two given vector.
Expect output as np.float object.
"""
dict_1 = file_read.read_file('../../data/10mM_2,7-AQDS_1M_KOH_25mVs_0.5step_2.txt')
data = file_read.data_frame(dict_1, 1)
col_x1, col_x2 = baseline.split(da... | 7334a9500da86df959e6d6056a044d240dfbec95 | 27,637 |
def last_name_first(n):
"""Returns: copy of n in form 'last-name, first-name'
Precondition: n string in form 'first-name last-name
n has only space, separating first and last."""
assert type(n) == str, str(n) + " is not a string"
assert is_two_words(n), n+' has the wrong form'
# Compute the va... | 448b23cc70294a28b82d36af95c2dab772b30e9d | 27,638 |
import logging
def by_count(logger: logging.Logger, once_every: int) -> logging.Logger:
"""
The returned logger will only permit at most one print every `once_every` logging calls from the code
line this function was called from.
Usage example::
for i in range(100):
log_throttlin... | 9c67c84a4e4371a25e5947f6fcb92b860cc12e9e | 27,639 |
def load_ps_label(frame_id):
"""
:param frame_id: file name of pseudo label
:return gt_box: loaded gt boxes (N, 9) [x, y, z, w, l, h, ry, label, scores]
"""
if frame_id in PSEUDO_LABELS:
gt_box = PSEUDO_LABELS[frame_id]['gt_boxes']
else:
raise ValueError('Cannot find pseudo label... | 53b73ddfe4a51676f7e81f9e266724ccc5e494fa | 27,641 |
import json
async def execute(
url_path: str,
body: dict,
codef,
service_type: ServiceType,
) -> dict:
"""
API 요청 실행 함수.
실제 사용자에게 제공되는 함수 내부에서 이 함수를 호출해서 사용할 것을 권장한다.
:param url_path: 요청 URL 경로
:param body: post 요청 바디
:param codef: codef 인스턴스
:param service_... | e0c55b38697121e3fa671fc7585fe477c977c724 | 27,642 |
def main() -> int:
""" Execute all tasks.
"""
get_googletest()
return 0 | c2850f781245cacd77b3707881b337a113dcb048 | 27,643 |
import asyncio
async def async_unload_entry(
hass: HomeAssistantType,
config_entry: config_entries.ConfigEntry,
) -> bool:
"""Unload Energosbyt Plus entry"""
log_prefix = _make_log_prefix(config_entry, "setup")
entry_id = config_entry.entry_id
update_delegators: UpdateDelegatorsDataType = has... | c3e7a928c801f65b4ca997fb8b3734059b95e210 | 27,644 |
def euler_vec(z, y, x, n):
"""
Return (n,3,3) tensor with each (3,3) block containing an
Euler rotation with angles z, y, x. Optionally each of z, y, x
can be a vector of length n.
"""
L = np.zeros((n, 3, 3), "d")
cosx, sinx = np.cos(x), np.sin(x)
L[:, 0, 0] = 1
L[:, 1, 1] = L[:, 2, ... | 799dd414ff8fc1aa405072bb2d5d155751ad86a4 | 27,645 |
def ReadBenderEllipse( filename, dataFrame=False, headerLine=None, useDefaultColumnNames=True ):
"""Read in an ellipse fit generated by Bender/Saglia code and store it
in a dictionary (or, optionally, a ListDataFrame object). Columns are
converted to 1-D numpy arrays.
headerLine indicates which lin... | 8d8f816f2ac7375bcc6814c34fd69a11e352255b | 27,646 |
def getQuote(symbolStringCSV, detailFlag = 'ALL' ):
"""
Returns the live quote of a single or many companies
symbolStringCSV <str> is a comma separated value of tickers
detailFlag <'ALL' or 'INTRADAY'> specifies whether all data is returned or just a subset with intraday
sample usage:
getQuote('TVIX, GOOG'... | b40489c5d0680126abf58d32f7e487332599ea8b | 27,647 |
def get_user_resources_permissions_dict(user, request, resource_types=None, resource_ids=None,
inherit_groups_permissions=True, resolve_groups_permissions=False):
# type: (models.User, Request, Optional[List[Str]], Optional[List[int]], bool, bool) -> ResourcePermissionMap
... | 6c3c647f304167328282505f118633654b9422a2 | 27,648 |
import json
import requests
def create_new_index(index_name: str):
"""
Алгоритм внутри по шагам
:param index_name: str: название текущей версии индекса
:return: new_index_name: str: название обновленного индекса
"""
print("*" * 10)
# получаем новое имя индекса
new_index_name = up_inde... | 797a1f2fa556f640588837c644bfbbf2b425daab | 27,649 |
def _parse_slice_str(slice_str):
"""Parses the given string as a multidimensional array slice and returns a
list of slice objects and integer indices."""
is_valid = False
if len(slice_str) > 2:
is_valid = slice_str[0] == "[" and slice_str[-1] == "]"
sliced_inds = []
if is_valid:
slice_str_list = ... | 6eb7a6b5d1dc2ee57e878b37be70e1e75d7d6ecc | 27,650 |
def AverageZComparison(x, y):
""" Take the average of second and third element in an array and compare
which is bigger. To be used in conjunction with the sort function. """
xsum = x[1]+x[2]
ysum = y[1]+y[2]
if xsum < ysum:
return -1
if xsum > ysum:
return 1
return 0 | 84c9e7b92df4b3e4914c769293f71790def5e4dd | 27,651 |
def convblock(in_channels, out_channels, kernel_size, stride=1, padding=0, use_bn=True):
"""
Returns convolution block
"""
if use_bn:
return [
nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding),
nn.BatchNorm2d(out_channels),
nn.ReLU(True)
... | 157cc5a88e0f1e0d0f4f3afc228fd25d1a67d058 | 27,652 |
def get_caffe_op_type(layer, input_channels=1, output_channels=1):
"""
Gets the relevant Toolkit Enum for the corresponding Caffe layer stage type.
:param layer:
The particular layer field of the caffe Net msg that we want to discover the type.
:return: StageType Enum
"""
if isConvolutio... | e912014862643e3724fad8f10c0b8ee7133c77e1 | 27,653 |
def comp_volumes(self):
"""Compute the Lamination volumes (Vlam, Vvent, Vslot, Vwind)
Parameters
----------
self : LamSlotWind
A LamSlotWind object
Returns
-------
V_dict: dict
Lamination volume dictionnary (Vlam, Vvent, Vslot, Vwind) [m**3]
"""
V_dict = LamSlot.c... | 4b9444b9ac7c78e6a7719ab73dfa5cabcd78debf | 27,654 |
def elliptical_orbit():
"""Draw an example of a planet with an elliptical orbit around its star."""
fig, axes = plt.subplots(1, 1)
orbit = Ellipse(xy=(0, 0), width=2, height=1.5, facecolor='lightblue')
axes.add_artist(orbit)
axes.plot([-1, 0], [0, 0])
axes.annotate(
'semi-major axis',... | ccb12b80111009a59cacff522a35cd41a6e73ad4 | 27,655 |
from datetime import datetime
def get_date_range_for_date(date_str, interval):
"""
Given a date string, parse it and derive a range based on the given
interval. The interval is inclusive on the lower end, and exclusve on the
higher end. For example, given a date str of 2019-03-10 and a 'month'
int... | 4b2d1f47d4984fbd9fe590e2698b288560aa0162 | 27,656 |
def sigmaStarDFA(sigma=None):
"""
Given a alphabet S returns the minimal DFA for S*
:param sigma: set of symbols
:return: DFA
.. versionadded:: 1.2"""
if sigma is None:
raise
d = DFA()
d.setSigma(sigma)
i = d.addState()
d.setInitial(i)
d.addFinal(i)
for a in d.S... | 51ab7fa365b356f03aab57b777bd245163ba6b02 | 27,657 |
from datetime import datetime
def timestamp_to_datetime(seconds, tz=None):
"""Returns a datetime.datetime of `seconds` in UTC
:param seconds: timestamp relative to the epoch
:param tz: timezone of the timestamp
"""
if tz is None:
tz = timezone.utc
dt = datetime.fromtimestamp(seconds, ... | 2b53d69aeb2c7e5f88602af47d2d7b1ee40e0730 | 27,659 |
import re
def initialize(plugins, exclude_regex=None, rootdir='.'):
"""Scans the entire codebase for high entropy strings, and returns a
SecretsCollection object.
:type plugins: tuple of detect_secrets.plugins.base.BasePlugin
:param plugins: rules to initialize the SecretsCollection with.
:type ... | 80c262041736c58f79a4356781b3ab831b6f1daa | 27,660 |
def decompose_job_id(job_id):
"""Thin wrapper around generic decompose_job_id to use our local SPACER."""
return utils_decompose_job_id(job_id, spacer=SPACER) | f41553a6864940816da53982746a9f06220347e6 | 27,661 |
from re import U
from re import T
def build(P , word_size , first_hidden_size , encoding_size) :
"""
create entity and relation encoding
"""
P["W_word_left_input"] = U.initial_weights(2*word_size , first_hidden_size)
P["W_word_right_input"] = U.initial_weights(2*word_size , first_hidden_size)
... | 9c465b9033b23aa938ea600326bc5add1000edb5 | 27,662 |
def validate_path_for_get_public_key(path: list, slip44_id: int) -> bool:
"""
Checks if path has at least three hardened items and slip44 id matches.
The path is allowed to have more than three items, but all the following
items have to be non-hardened.
"""
length = len(path)
if length < 3 o... | 1e0ef325283a2cfc6aceba748c18fa2dbc9a34c0 | 27,664 |
import base64
from datetime import datetime
def generate_result(pic_type, img_path, predicted_breed=''):
"""
Generate a result of predicted dog breed for display in Jupyter Notebook.
Args:
pic_type (str): Type of picture, either 'dog', 'human' or 'error'
img_path (str): Path to the image p... | 345db6c17e0ec2a3d65963ba403200c1bde3229c | 27,665 |
def concatSeriesMovies(dataFrame1, dataFrame2):
"""
Join, concat two dataFrames
Parameters:
dataFrame1: string
The name of the dataFrame the user wants to concat.
dataFrame2: string
The name of the dataFrame the user wants to concat.
Returns:
a new ... | cb063ca82dac809f05a60a920f77d7a53ed5d3af | 27,666 |
def Pattern7(s):
""" Compute the correlator for this pattern:
↓ ○
↑ ↑
and symmetry-equivalent patterns
"""
res = 0.0
s = np.pad(s, ((0, 0), (2, 2), (2, 2)))
L = s.shape[-1]
for i in range(L-2):
for j in range(L-2):
res += s[0, i, j] * s[0, i+1... | 2dea3f7cae06cec65f9ee416b61367320d9893cc | 27,667 |
def list_camera_ports():
"""
Test the ports and returns a tuple with the available ports and the ones that are working
"""
non_working_ports = []
working_ports = []
available_ports = []
dev_port = 0
while len(non_working_ports) <= 3: # If there are more than 3 non working ports stop the ... | 192cdb62807f89a05a67f7efbbc267bcc1b1f305 | 27,668 |
from pathlib import Path
def parse_taxid_names(file_path):
"""
Parse the names.dmp file and output a dictionary mapping names to taxids
(multiple different keys) and taxids to scientific names.
Parameters
----------
file_path : str
The path to the names.dmp file.
Returns
----... | 1d136f73a56ac8d3c02fd53c6e7928a39440e27a | 27,669 |
def dn_outfunc(e1, e2, W, V1=None, V2=None, b=None):
"""Applies a bilinear function based on given parameters.
This is a building block of Neural Tensor Network (see the reference paper
below). It takes two input variables and one or four parameters, and
outputs one variable.
To be precise, denote... | f1c642b7fcaf91d49df993177b76715774fc17bf | 27,672 |
def action_can_be_queued(action_type):
"""
test the action_type whether can be queued
Inputs: action_type, int
Outputs: true or false
"""
need_args = actions.RAW_FUNCTIONS[action_type].args
result = False
for arg in need_args:
if arg.name == 'queued':
result = True
... | e05f56b047d5c14bc2bcb27e82e789a41b12e090 | 27,673 |
def bench4(x):
"""A benchmark function for test purposes.
f(x) = float(x) ** 2
where x is a string. It has a single minima with f(x*) = 0 at x* = "0".
This benchmark is used for checking support of categorical variables.
"""
return float(x[0]) ** 2 | 2c7bf171f917b599db6f7553b2a959cb8c691c93 | 27,674 |
def drop_columns_from_dataframe_if_all_elements_are_nan(df, elements_list=['', '']):
""" Takes two parameters:
df: Dataframe
elements_list: By default it will identify np.nan. If you want to add additional elements, as an example, you can do this ['', ' ']
"""
m = df.applymap(lambda i:... | 5f66e8c33a918872e2cfeabff2116a43fda9095f | 27,675 |
def drop_db(code, confirm_by_typing_db_code_again=None):
"""
Delete a history database.
Parameters
----------
code : str, required
the database code
confirm_by_typing_db_code_again : str, required
enter the db code again to confirm you want to drop the database, its config,
... | a135ad9e3abdecb891b0ef5b6a1754d01a85fda8 | 27,676 |
def _nex_group(seq, core, spatial, c_num=4, s_num=4):
"""Build spatial stream index"""
# step 1
ant_num = c_num * s_num
seq_diff = np.diff(seq)
offset = np.where(seq_diff != 0)[0]
offset = np.r_[0, offset + 1]
count = np.diff(np.r_[offset, len(seq)])
offset = offset[count == ant_num]
... | 2c9ff96b965c48aa0a0aace2cfab2e5d8b1d3a9e | 27,677 |
import asyncio
async def test_async_init_timeout(circuit):
"""Test the async initialization time_out."""
async def w3():
await asyncio.sleep(0.1)
return 3
logger = TimeLogger('logger')
out = edzed.ValuePoll(
'out',
func=w3,
interval=10, # don't ca... | 1915a66e8e82987f878f05a4a9016037e25c7da0 | 27,678 |
def compute_diffraction(
bundle,
key,
s,
eta,
L,
nlebedev=74,
nomega=12,
mode="xray",
form="raw",
anisotropy="cos2",
print_level=False,
):
"""Compute the I(s, eta) elastic scattering signal for a Bundle.
See aimsprop/notes/ued for details on this property.
... | 380043d47e6a5786ab2907a4b1bd11495784f052 | 27,679 |
def convert_dict_id_values_to_strings(dict_list):
"""This function ensures that the ``id`` keys in a list of dictionaries use string values.
:param dict_list: List (or tuple) of dictionaries (or a single dictionary) containing API object data
:type dict_list: list, tuple, dict, None
:returns: A new dic... | 7d1348910e5802c928b94bc74d71f3ce35770215 | 27,680 |
def delete_images(request):
"""
Deletes images which are passed via HTTP query.
"""
Image.objects.filter(pk__in=request.POST.getlist("images")).delete()
return HttpResponseRedirect(reverse("lfs_manage_global_images")) | 29e2e3be3730a2a3552bc78feb8e8817e594dab5 | 27,681 |
import fnmatch
def is_requirements_file(location):
"""
Return True if the ``location`` is likely for a pip requirements file.
For example::
>>> is_requirements_file('dev-requirements.txt')
True
>>> is_requirements_file('requirements.txt')
True
>>> is_requirements_file('requirements.in... | 2577595ef6d2bcb553a0354623c40589f96a5fb3 | 27,682 |
def bisect_steps_remaining():
"""Estimate of remaining steps, including the current one.
This is an approximation."""
# https://github.com/git/git/blob/566a1439f6f56c2171b8853ddbca0ad3f5098770/bisect.c#L1043
return floor(log(bisect_revisions(), 2)) | ded51395ead2c7ea76aa4ff3c2cf7d6195f81537 | 27,683 |
def create_lstm_model(fingerprint_input, model_settings, model_size_info,
is_training):
"""Builds a model with a lstm layer (with output projection layer and
peep-hole connections)
Based on model described in https://arxiv.org/abs/1705.02411
model_size_info: [projection size, memo... | d050e3b984f2aff1b0466b5cab73d262243d6cc9 | 27,684 |
def tile(x: Tensor, count: int, dim=0) -> Tensor:
"""
Tiles x on dimension dim count times. From OpenNMT. Used for beam search.
:param x: tensor to tile
:param count: number of tiles
:param dim: dimension along which the tensor is tiled
:return: tiled tensor
"""
if isinstance(x, tuple):... | 04b0e507e1600f3cb3185b170ee72286c2d20a7f | 27,685 |
from typing import Callable
from typing import Coroutine
from typing import Any
from typing import Optional
import asyncio
def cancellable_request(handler: Callable[..., Coroutine[Any, Any, Optional[Any]]]):
"""this decorator periodically checks if the client disconnected and then will cancel the request and retu... | 10e50a565f45c0e4babf68386b244557e1727bc2 | 27,686 |
import time
def add_central_server_member_delete_global_error_cert(case,
client, ss2_host,
ss2_username, ss2_password):
"""
Restores security server after member being deleted in central server
:p... | 77ea9a9de677947285f7bda233520bc43df84e18 | 27,687 |
def get_country_models(model):
"""
Get all valid domain-specific models for a given model.
:param str model:
:return:
"""
domains = get_domain_for(model, country=None)
return ['{}{}-K9'.format(model, domain) for domain in domains] | 48e171e304e75216ac0dd2d70613996b8ae5f9e7 | 27,688 |
def _cprint_bad_contrast3(fgcolor, bgcolor, bold, underlined):
"""Returns 1 if one of the conditions of poor contrast is matched """
# black on black with LIGHT BG
_c1 = (fgcolor == 8) and (bgcolor == 0) and (CPRINT_PAR["light_background"])
if _c1:
return 1
else:
return 0 | 89d74cfe47fecd3fd21fc3d7f47a5674df80b669 | 27,690 |
def download_from_mongo(context, sel_filter, projection):
"""
Download panda DataFrame from a mongoDB server
:param context: execution context
:param sel_filter: a SON object specifying elements which must be present for a document to be included in the
result set
:param proj... | 863a0fdc7761de38d578039c764052ecac2e57f8 | 27,691 |
def create_group(current_session, groupname, description):
"""
Creates a group and returns it
"""
return gp.create_group(current_session, groupname, description) | 0a5adea7b0a57ec3f44d260da250b06c09eca939 | 27,692 |
import requests
def call_api(endpoint):
"""
Build the API URL and request data
:param str endpoint: specific api endpoint to hit
:return response: server's reponse to the request
"""
url = BASE_URL + endpoint
try: # try to get json data
response = requests.get(url).json()
exce... | 6f2527c6eb777c2cd0ab80636865d7adda032506 | 27,693 |
import inspect
def test_callable_args(func, args):
"""
Return True when this function can be called with the given arguments.
"""
assert isinstance(args, (list, tuple))
signature = getattr(inspect, 'signature', None)
if signature is not None:
# For Python 3, use inspect.signature.
... | 704697253a88009394297a4688a9b3179b976f0d | 27,694 |
def get_kde_caseduration_json(df, parameters=None):
"""
Gets the estimation of KDE density for the case durations calculated on the log/dataframe
(expressed as JSON)
Parameters
--------------
df
Pandas dataframe
parameters
Possible parameters of the algorithm, including:
... | 54262948216c43e0bbd44ec9ed2ed691903d9a9d | 27,695 |
def render_text(name: str,
data: str,
font_size: int = 10,
fig_width_per_char: float = 0.1,
fig_height: float = 0.4,
img_height: int = None,
img_width: int = None,
**kwargs):
"""Render a text string.
... | d956b8dc885f1f582c2a54147bd42623f2a796c4 | 27,696 |
def index_closed(client, index_name):
"""Return True if index is closed"""
try:
# 1.0 params
index_metadata = client.cluster.state(
index=index_name,
metric='metadata',
)
except TypeError:
# 0.90 params:
index_metadata = client.cluster.state(
... | 9da234b5ef4b6f6c2835f3adf67aac804cc92919 | 27,697 |
def get_contributions_with_user_as_submitter(event, user):
"""Get a list of contributions in which the `user` has submission rights"""
return (_query_contributions_with_user_as_submitter(event, user)
.options(joinedload('acl_entries'))
.order_by(db.func.lower(Contribution.title))
... | ae30ded175f52aed5d50e629d5e260577bffe0f3 | 27,699 |
def rewrite_string(
searcher: AbstractSearcher,
source: Text,
path: Text,
max_iterations=1,
) -> Text:
"""Applies any replacements to the input source, and returns the result."""
return formatting.apply_substitutions(
source, find_iter(
searcher,
source,
path,
... | 2de75ca2511ff2496f29674ff762c7a48531c51b | 27,700 |
def build_path_result_tests(name):
"""
Build a test for API commands that respond with ``Err`` and
``Mountpoint`` fields.
:param unicode command_name: The command in the schema to validate.
:return: ``TestCase``.
"""
return build_schema_test(
name=str(name + "Tests"),
schem... | 32491f1eb10d9f175522b7ea55f91a2c1e6aeb27 | 27,701 |
def get_mpls_autobw_template_detail_rpc(self, api_timeout=''):
"""
This is an auto-generated method for the PySwitchLib.
**Supported Versions**:
* SLXOS: 17r.1.01a, 17r.2.00, 17s.1.02
:type api_timeout: long or tuple(long, long)
:param api_timeout: Timeout for connection and response ... | 97e0d7ef9a43ef2335fefc6c62ad34286dbf7efb | 27,702 |
def empty(a):
"""Test whether the slice is empty."""
return a is None or volume(a)==0 | c1de4cfbf3bcc569b4b3cde02d518aabf32ff6fd | 27,703 |
def nnPredict(w1, w2, data):
"""% nnPredict predicts the label of data given the parameter w1, w2 of Neural
% Network.
% Input:
% w1: matrix of weights of connections from input layer to hidden layers.
% w1(i, j) represents the weight of connection from unit i in input
% layer to unit ... | 564e3db0c659713de9dbfda7c279381d50d490e3 | 27,705 |
from typing import List
def count_pairs(array: List[int], difference: int) -> int:
"""
Given an array of integers, count the number of unique pairs of integers that have a given difference.
These pairs are stored in a set in order to remove duplicates.
Time complexity: O(n^2).
:param array: is th... | e027e8885f4c4531da9b7dab7de8e84a7004c913 | 27,706 |
def decompress_deltas_18bit(buffer):
"""Parse packet deltas from 18-byte compression format."""
if bad_data_size(buffer, 18, "18-byte compressed packet"):
raise ValueError("Bad input size for byte conversion.")
deltas = np.zeros((2, 4))
# Sample 1 - Channel 1
minibuf = [(buffer[0] >> 6),
... | 65fc1b7cc12c0d9f0a082c7df57bbae81fb1ec13 | 27,707 |
import re
def password_validate(password):
"""It validates password using regular expression
:param password: contains the users password
:returns: Boolean
:raises: ValidationError
"""
if re.match(
r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$",
passw... | 57cec9fd1ae1f4f2b4df887d98e65ea9f6191595 | 27,708 |
def get_emr_cluster_status(cluster_id: str, detail: bool = False):
"""
Provides cluster-level details including status, cluster_id, cluster_name and so on.
Args:
cluster_id: string, EMR cluster id
detail: bool, provided additional detail about cluster like ec2 attributes
Returns:
... | 48da66c5aa45f0697b71924a31ea6d942bb5ce19 | 27,709 |
def get_keypair() -> KeyPairInfo:
"""Returns current keypair (ec2.KeyPairInfo)
https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#keypairinfo
"""
return get_keypair_dict()[get_keypair_name()] | 95cba4f8a81858578e831b0bdbae359791399841 | 27,710 |
def char_vectorizer(char,
custom_alphabet=False):
"""
Vectorize given nucleotide character. Convert to uppercase before
vectorizing.
>>> char_vectorizer("C")
[0, 1, 0, 0]
>>> char_vectorizer("g")
[0, 0, 1, 0]
>>> char_vectorizer("M", ['E', 'H', 'I', 'M', 'S'])
[0... | 53c306d814807299b7bac7801f4b7d2a663b6f99 | 27,711 |
def orbit_from_name(name):
"""Return :py:class:`~poliastro.twobody.orbit.Orbit` given a name.
Retrieve info from JPL DASTCOM5 database.
Parameters
----------
name : str
NEO name.
Returns
-------
orbit : list (~poliastro.twobody.orbit.Orbit)
NEO orbits.
"""
rec... | 145c1ef503743e9066ecf8e2f5e06c0526f8ab62 | 27,712 |
def make_snowflake(timestamp_ms, datacenter_id, worker_id, sequence_id, twepoch=twepoch):
"""generate a twitter-snowflake id, based on
https://github.com/twitter/snowflake/blob/master/src/main/scala/com/twitter/service/snowflake/IdWorker.scala
:param: timestamp_ms time since UNIX epoch in milliseconds"""
... | 473d97589dbe90949cb69ecdbeba719cbea5c2ee | 27,713 |
from typing import Sequence
def compute_committee(indices: Sequence[ValidatorIndex],
seed: Bytes32,
index: uint64,
count: uint64) -> Sequence[ValidatorIndex]:
"""
Return the committee corresponding to ``indices``, ``seed``, ``index``, and commi... | 168fc69ef7d4962c089cd6e497cd94ccad062c73 | 27,714 |
def get_default_graph():
""" Setting graphviz graph global options """
graph = Digraph('AWS', engine='dot')
graph.body.append('splines=line')
graph.body.append('rankdir=LR')
graph.body.append('outputorder=edgesfirst')
graph.node_attr.update(shape='rectangle', style='filled', color='black')
r... | 25ae7376b31d280722fb2791dbf9478a6b4cb2d1 | 27,715 |
from json import dumps
def GetJson(data):
"""
将对象转换为JSON
@data 被转换的对象(dict/list/str/int...)
"""
if data == bytes: data = data.decode('utf-8')
return dumps(data) | 372b501f5ada7254efab10447dcbdc91c8799408 | 27,716 |
def binary_tail(n: int) -> int:
""" The last 1 digit and the following 0s of a binary representation, as a number """
return ((n ^ (n - 1)) + 1) >> 1 | 63460cef7b39b7e7ee2ec880810ff71d82be01e9 | 27,717 |
from datetime import datetime
def time_left(expire_date):
"""Return remaining days before feature expiration or 0 if expired."""
today_dt = datetime.today()
expire_dt = datetime.strptime(expire_date, "%d-%b-%Y")
# Calculate remaining days before expiration
days_left_td = expire_dt - today_dt
... | 652acd27b0d4fa9b21321df4ff8ce6ce15b97ed6 | 27,718 |
import yaml
def load_config():
"""
importer_config.yaml must be in the current working directory
"""
with open(_PATH) as fd:
config = yaml.safe_load(fd)
# Remove trailing slashes from URLs
config['kbase_endpoint'] = config['kbase_endpoint'].strip('/')
return config | 0137c59cd2ea7b5b8ba57a82fb2997e6e7330751 | 27,719 |
def get_package_version():
"""Return the Review Board version as a Python package version string.
Returns:
unicode:
The Review Board package version.
"""
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2] or VERSION[3]:
version = '%s.%s' % (version, VERSION[2])
... | 418eef843dd3647cffdeb879781e3599487cd885 | 27,720 |
def fit(x, y, sigy=None, error=False):
""" Perform a linear fit on a range of x and y values.
This function fits a set of data points x, y with individual standard
deviations sigy for the y values to a straight line y = a + bx by
minimizing chi-square.
If the 'error' parameter is False the functio... | f02db36a6e7395d3f955cafc6f506e3a42984abf | 27,722 |
def eval_metrics_offline(cfg,
pred_folder,
palette,
metrics=['mFscoreCD', 'mFscore']
):
"""Calculate evaluation metrics from offline GT and prediction images, maily use the evaluate of dataset class
Args:
... | 7d5e44a1cda8d7bbb92a56cedf18e940c51663e5 | 27,723 |
def zero_pad_and_crop(img, amount=4):
"""Zero pad by `amount` zero pixels on each side then take a random crop.
Args:
img: numpy image that will be zero padded and cropped.
amount: amount of zeros to pad `img` with horizontally and verically.
Returns:
The cropped zero padded img. The returned numpy ... | 63ac80cb9759fd06032afd97f03e0057aed86784 | 27,724 |
def video_id(video_id_or_url):
"""
Returns video id from given video id or url
Parameters:
-----------
video_id_or_url: str - either a video id or url
Returns:
--------
the video id
"""
if 'watch?v=' in video_id_or_url:
return video_id_or_url.split('watch?v=')[1]
e... | 9f680ac621e1f5c6314a6a3e97093d786fa7ea33 | 27,725 |
def check_permission(resource: Resource, permission_name: str) -> dict:
"""
Check if requester has sufficient permissions to do something on specific resource.
Raises if not.
"""
base_permission_policy = resource.get_guest_authorization()
if (authorization_header := resource.request.headers.get... | b632fbb5f3429c1540da35c3b82e6fa562b81c87 | 27,726 |
from datetime import datetime
import json
def makePalRecordsConsistent(pal_records, low_frequency, high_frequency,
user_id, fcc_channel_id="1",
start_date=None, end_date=None):
"""Make Pal object consistent with the inputs
Args:
pal_records: (list... | 3029ee761afb17428a6a2b0b1e85c0f2f3fdc6d6 | 27,727 |
import yaml
def read_config():
"""Read from rotest.yml config elrados segment."""
config_path = search_config_file()
if config_path is not None:
with open(config_path, "r") as config_file:
configuration_content = config_file.read()
yaml_configuration = yaml.load(configuration_... | 5fb81ef5609074c029203021895ba55654760a60 | 27,728 |
import typing
def cast_to_str(some_value: typing.Any, from_type: typing.Any) -> typing.Any:
"""Just helper for creating suitable test assets."""
if from_type == bytes:
return some_value.decode()
return str(some_value) | 9157873a74d0d02b919d047710c1d4ccee4121a6 | 27,729 |
def downsample_by_group(df,min_distance=1.,message_callback=print):
"""Group and down-sample a DataFrame of xrsd records.
Parameters
----------
df : pandas.DataFrame
dataframe containing xrsd samples
min_distance : float
the minimum allowed nearest-neighbor distance
... | bbcdbab6c1bf5e42554e102bda8d245263a47bfd | 27,730 |
from typing import Union
def get_pure_ratings(
ratings: Union[str, pd.Series, pd.DataFrame]
) -> Union[str, pd.Series, pd.DataFrame]:
"""Removes rating watches/outlooks.
Parameters
----------
ratings : str, pd.Series, or pd.DataFrame
Rating may contain watch, such as `AA- *+`, `BBB+ (CwNe... | a834b3f33f12d8d3b6c109021a4d075c32160544 | 27,731 |
def export_grid(outname,resh,ignore=[255,0]):
"""[Exports given grid to a point cloud]
Args:
outname ([str]): [Output file name]
resh ([np.array]): [3D Volume in grid representation]
ignore (list, optional): [values to ignore]. Defaults to [255,0].
Returns:
Grid as a point c... | 27fd06c37d57f0eb320d0d81908efc1acf6bc8ee | 27,732 |
def sum_errors(dic):
"""Helper function to sum up number of failed jobs per host.
Assumes that dic is in the form
:param dict dic: {"error_code1":count1, "error_code2":count2, etc.}
:return int: Sum of all values in dic
"""
return sum(value for key, value in dic.iteritems()) | 0d2bc9df58e5bf9639a331d64061de4c0a5aa4ed | 27,733 |
def checkFriends(new_user, usernameOfFriend):
""" Check if users are friends or not"""
# Check if users are friends first
viewF = viewFriends(new_user, usernameOfFriend)
# Check if users have any pending requests
viewP = searchPendingRequests(new_user, usernameOfFriend)
# Logic
if viewF:
... | 6268d180a768ad858d5e1c5c69c92837a027f07f | 27,734 |
def update(instance, **data):
"""Update instance with data directly by using ``update()``
skipping calling ``save()`` method.
Usage: ``instance = update(instance, some_field=some_value)``
"""
instance.__class__.objects.filter(pk=instance.pk).update(**data)
return refresh(instance) | 8462d5459ba02d11ef3edd0c1d3c152d4b682634 | 27,735 |
def cast_distance_matrix_to_optimal_integer_type(D_X):
"""
Cast distance matrix to smallest signed integer type, sufficient
to hold all its distances.
Parameters
-----------
D_X: np.array (|X|×|X|)
Distance matrix of a compact metric space X with integer
distances.
Returns
... | 01c8e43259d5edc7282a9c01269277f34495ff9d | 27,736 |
def getObject(name):
"""Get reference to single Rhino object, checking for failure"""
rc, obRef = Rhino.Input.RhinoGet.GetOneObject("Select " + name, True, Rhino.DocObjects.ObjectType.AnyObject)
if rc != Rhino.Commands.Result.Success or not obRef : raise NameError(rc)
return obRef | 20d562dd90dec82a479bdedabef62f17129cecf0 | 27,737 |
def get_falsecolor(input):
"""
picks false color bands from the 12 Sentinel bands (for visual interpretation of vegetation)
:param input: 12-band image tensor
:return: 3-band NIR-RED-GREEN tensor
"""
rgb_band_idxs = [bands.index(b) for b in ["S2B8", "S2B4", "S2B3"]]
return input[rgb_band_idx... | a4e80bb61211456794b34c99ec0ad92f1b1f567d | 27,738 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.