content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def list_rbd_volumes(pool):
"""List volumes names for given ceph pool.
:param pool: ceph pool name
"""
try:
out, err = _run_rbd('rbd', '-p', pool, 'ls')
except processutils.ProcessExecutionError:
# No problem when no volume in rbd pool
return []
return [line.strip() for... | 4c80b6c952a19834a79622c31453af62db12e740 | 27,600 |
from typing import Optional
from datetime import datetime
def parse_date(string: Optional[str]) -> Optional[date]:
"""
Parse a string to a date.
"""
if not string or not isinstance(string, str):
return None
try:
return isoparse(string[:10]).date()
except ValueError:
pas... | f29bb415a0f8d08dbcefe8ae95b5d08f898eecfb | 27,601 |
def butter_bandpass(lowcut, highcut, fs, order=5):
"""
Taken from
https://scipy-cookbook.readthedocs.io/items/ButterworthBandpass.html
Creates a butterworth bandpass filter of order 'order', over frequency
band [lowcut, highcut].
:param lowcut: Lowcut frequency in Hz
:param highcut: Highcut... | 148f581e36a0d1a53f931b5ce2301db8dd2cde17 | 27,602 |
import subprocess
def get_current_SSID():
"""Helper function to find the WiFi SSID name.
Returns:
str: Wifi SSID name("" on Exception).
"""
try:
p = subprocess.Popen(["iwgetid", "-r"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return ou... | f88021770d292cf21d7de7221efc4c0aef0099b5 | 27,603 |
def get_archives_to_prune(archives, hook_data):
"""Return list of keys to delete."""
files_to_skip = []
for i in ['current_archive_filename', 'old_archive_filename']:
if hook_data.get(i):
files_to_skip.append(hook_data[i])
archives.sort(key=itemgetter('LastModified'),
... | 7701e7b145ea28148b77eb63475d7b0e9127d2f0 | 27,604 |
def tf_pad(tensor, paddings, mode):
"""
Pads a tensor according to paddings.
mode can be 'ZERO' or 'EDGE' (Just use tf.pad for other modes).
'EDGE' padding is equivalent to repeatedly doing symmetric padding with all
pads at most 1.
Args:
tensor (Tensor).
paddings (list of lis... | e2e1e9ac2cbef63c4b12bdf35eb35090973d744a | 27,605 |
def compute_reference_gradient_siemens(duration_ms, bandwidth, csa=0):
"""
Description: computes the reference gradient for exporting RF files
to SIEMENS format, assuming the gradient level curGrad is desired.
Theory: the reference gradient is defined as that gradient for which
a 1 cm slice is... | 65cf8bd8e805e37e5966170daeae90594e45595e | 27,606 |
def schedule_conv2d_NHWC_quantized_native(cfg, outs):
""" Interface for native schedule_conv2d_NHWC_quantized"""
return _schedule_conv2d_NHWC_quantized(cfg, outs, False) | 450b6fb914c8b0c971604319417d56c7148b5737 | 27,607 |
def calc_square_dist(a, b, norm=True):
"""
Calculating square distance between a and b
a: [bs, npoint, c]
b: [bs, ndataset, c]
"""
a = tf.expand_dims(a, axis=2) # [bs, npoint, 1, c]
b = tf.expand_dims(b, axis=1) # [bs, 1, ndataset, c]
a_square = tf.reduce_sum(tf.square(a), axis=-1) # [bs... | d855e438d4bcca4eb43a61fa6761a1cd5afd7731 | 27,608 |
def read_config(lines):
"""Read the config into a dictionary"""
d = {}
current_section = None
for i, line in enumerate(lines):
line = line.strip()
if len(line) == 0 or line.startswith(";"):
continue
if line.startswith("[") and line.endswith("]"):
current_s... | 613ed9291ab6546700b991fc9a5fc301c55ae497 | 27,609 |
def get_cert_subject_hash(cert):
"""
Get the hash value of the cert's subject DN
:param cert: the certificate to get subject from
:return: The hash value of the cert's subject DN
"""
try:
public_bytes = cert.public_bytes(encoding=serialization.Encoding.PEM)
cert_c = crypto.load_... | 070284984018ba08f568541a4d7ba815d72bd025 | 27,610 |
import requests
def icon_from_url(url: str):
"""
A very simple attempt at matching up a game URL with its representing icon.
We attempt to parse the URL and return the favicon. If that fails, return
a pre-determined image based on the URL.
"""
if not url:
return
# Allow the user ... | 85f8a539cacbc86e58cf4e3815babdc744352626 | 27,611 |
import numpy
def extract_spikes(hd5_file, neuron_num=0):
"""Extracts the spiking data from the hdf5 file. Returns an array of
spike times.
Keyword arguments:
neuron_num -- the index of the neuron you would like to access.
"""
with h5py.File(hd5_file, "r+") as f:
neuron_list = f['NF'][... | 85df1525595c0141dd885d041b54b02aa5dc1283 | 27,612 |
def problem_kinked(x):
"""Return function with kink."""
return np.sqrt(np.abs(x)) | 12897b83fa4c42cfbe608add92cf5ef0736463ef | 27,613 |
def read_dicom(filename):
"""Read DICOM file and convert it to a decent quality uint8 image.
Parameters
----------
filename: str
Existing DICOM file filename.
"""
try:
data = dicom.read_file(filename)
img = np.frombuffer(data.PixelData, dtype=np.uint16).copy()
i... | e8b621dfb7348e12e1fe8d00ae02009789205e86 | 27,614 |
import logging
def _filter_all_warnings(record) -> bool:
"""Filter out credential error messages."""
if record.name.startswith("azure.identity") and record.levelno == logging.WARNING:
message = record.getMessage()
if ".get_token" in message:
return not message
return True | f16490ef39f9e3a63c791bddcba1c31176b925b7 | 27,615 |
import copy
def _to_minor_allele_frequency(genotype):
"""
Use at your own risk
"""
g_ = copy.deepcopy(genotype)
m_ = g_.metadata
clause_ = m_.allele_1_frequency > 0.5
F = MetadataTF
m_.loc[clause_,[F.K_ALLELE_0, F.K_ALLELE_1]] = m_.loc[clause_,[F.K_ALLELE_1, F.K_ALLELE_0]].values
m_.lo... | 424bf40e29f103abea3dd30ee662c3c695545a10 | 27,616 |
def ioka(z=0, slope=950, std=None, spread_dist='normal'):
"""Calculate the contribution of the igm to the dispersion measure.
Follows Ioka (2003) and Inoue (2004), with default slope value falling
in between the Cordes and Petroff reviews.
Args:
z (array): Redshifts.
slope (float): Slo... | 422f0e7d6a7c88b8ea6666e192271db81d966743 | 27,617 |
def nn_policy(state_input, policy_arch, dim_action, **kwargs):
"""
Fully-connected agent policy network
"""
with tf.variable_scope('policy_net', reuse=tf.AUTO_REUSE):
for i, h in enumerate(policy_arch):
state_input = layer.Dense(h, activation='tanh', # dtype='float64',
... | 8513ba88fe77076711c9aaf6bb148df8d9f18c1a | 27,618 |
def _check_geom(geom):
"""Check if a geometry is loaded in.
Returns the geometry if it's a shapely geometry object. If it's a wkt
string or a list of coordinates, convert to a shapely geometry.
"""
if isinstance(geom, BaseGeometry):
return geom
elif isinstance(geom, str): # assume it's ... | 5f7e1cc405ab6c67cb6f8342e23698d1e330d49c | 27,619 |
from typing import List
import glob
def read_csvs_of_program(program: str) -> List[pd.DataFrame]:
"""
Given the name of an algorithm program, collects the list of CVS benchmarks recorded
for that particular program.
:param program: name of the program which benchmarks should be retrieved
:return: ... | de763b5f790150f0340c58fc9d3d53f16d530f34 | 27,620 |
from typing import List
from typing import Tuple
def print_best_metric_found(
tuning_status: TuningStatus,
metric_names: List[str],
mode: str
) -> Tuple[int, float]:
"""
Prints trial status summary and the best metric found.
:param tuning_status:
:param metric_names:
:param... | e91c3222e66ded7ce3ab4ddcf52a7ae77fe84e9f | 27,621 |
def get_svn_revision(path = '.', branch = 'HEAD'):
""" Returns the SVN revision associated with the specified path and git
branch/tag/hash. """
svn_rev = "None"
cmd = "git log --grep=^git-svn-id: -n 1 %s" % (branch)
result = exec_cmd(cmd, path)
if result['err'] == '':
for line in result['out'].split... | 76d94aca9453e1d949bf70fc6bff4b77bb519479 | 27,622 |
def coerce_str_to_bool(val: t.Union[str, int, bool, None], strict: bool = False) -> bool:
"""
Converts a given string ``val`` into a boolean.
:param val: any string representation of boolean
:param strict: raise ``ValueError`` if ``val`` does not look like a boolean-like object
:return: ``True`` if... | 5ff88bee44b07fb1bd34d1734ba72485a2412b0c | 27,623 |
import csv
def print_labels_from_csv(request):
"""
Generates a PDF with labels from a CSV.
"""
if request.FILES:
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=labels-from-csv.pdf'
canvas = Canvas(response, pagesi... | 1674d136f5ed183913961fe2f7ce23d4b245f3d7 | 27,624 |
def get_ucs_node_list():
"""
Get UCS nodes
"""
nodeList = []
api_data = fit_common.rackhdapi('/api/2.0/nodes')
for node in api_data['json']:
if node["obms"] != [] and node["obms"][0]["service"] == "ucs-obm-service":
nodeList.append(node)
return nodeList | 4fc81f7e71a33be3670d99916828a2348b0e63cd | 27,625 |
import itertools
import platform
def grid_search(fn, grd, fmin=True, nproc=None):
"""Grid search for optimal parameters of a specified function.
Perform a grid search for optimal parameters of a specified
function. In the simplest case the function returns a float value,
and a single optimum value a... | 2c0cb9abde9d6e1abb152af14d361a87d1e7ee5f | 27,626 |
def wysiwyg_form_fields(context):
"""Returns activity data as in field/value pair"""
app = context['app_title']
model = context['entity_title']
try:
return wysiwyg_config(app, model)
except (KeyError, AttributeError):
return None | 86abca4a8711c3d5eec425975ee00055d0e78ae2 | 27,627 |
def thetagrids(angles=None, labels=None, fmt=None, **kwargs):
"""
Get or set the theta gridlines on the current polar plot.
Call signatures::
lines, labels = thetagrids()
lines, labels = thetagrids(angles, labels=None, fmt=None, **kwargs)
When called with no arguments, `.thetagrids` simply ... | a595c4f0ff5af7dae7e20b261d11c6f690344db1 | 27,628 |
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 typing import Union
from typing import IO
import os
from typing import Optional
from typing import List
from typing import Type
from typing import Dict
def load_spn_json(f: Union[IO, os.PathLike, str], leaves: Optional[List[Type[Leaf]]] = None) -> Node:
"""
Load SPN from file by using the JSON format.
... | 05ba2aaf73fbb918d0290ed1f01aa08579d0082d | 27,633 |
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 |
import os
import subprocess
import platform
def has_new_code(is_git):
"""Tests if there are any newer versions of files on the server.
Args:
- is_git: True if we are working in a git repository.
"""
os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
if not is_git:
result... | 90da67be202a717962a8a87e74c7d66148d2703b | 27,640 |
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 |
def feature_engineer(train, test, bureau, bureau_balance, credit_card_balance,
installments_payments, pos_cash_balance, previous_application):
"""
This function read all the data from the competition and do manual feature engineer to it.
:param train:
:param test:
:param bureau:... | f240c60c56503e93f3fb0792b8387a97389cfa70 | 27,658 |
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 resample_to_wet_dry_medians(ds, wet_month=None, dry_month=None, inplace=True):
"""
Takes a xarray dataset/array and a list of wet, dry months which
to resample to. An annualised wet and dry season median image for
given wet, dry months will be created. For example: one wet, one
dry image for ... | 4c04f63064c4ad3556f717123a8cd3f10dfd975b | 27,663 |
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 spec_to_in_spec_list(spec: np.array):
"""
Split full spectrogram song into list of sub-spectrograms, each of length 400ms
:param spec:
spec (np.array): 2D input numpy array spectrogram of given song (512 frequency bins x length of song (in 10ms)
:return:
in_spec_list (list): List of... | 5702da704c67b431e413d414628cdeeab2e8399d | 27,670 |
import os
def cache_trial_timing_bins(trials, trials_timing, bin_dur=.010, data_path='.'):
"""
todo: reinclude a check for bilaterals?
"""
cpath = os.path.join(data_path, 'caches', 'density')
tt = trials_timing
tt = add_uid(tt)
ttgb = tt.groupby('uid')
# load already cached tria... | b5d210dca88455e05ceedadc4087c86dbfad28a8 | 27,671 |
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 |
import os
def FileExtensionMatch(filePath, supportedFileTypeList):
"""
Check whether the file extension matches any of the supported file types.
Parameters
----------
filePath : string
File path
supportedFileTypeList : list
List of supported file extensions
"""
return (os.path.splite... | bdab68917ead387269f52a51465f500a581967f6 | 27,689 |
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 |
import os
def calculate_partial_volume(dirname, label, _isAccumulated=True):
"""
This function...
:param dirname:
:param label:
:param _isAccumulated:
:return:
"""
label = label.upper()
maskSum = 0.0
if _isAccumulated:
fileDir = _config.get("Results", "accumulated")
... | 43827a3880c8b197cb4432776d37bcf7e3f24624 | 27,698 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.