content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _login(client, user, users):
"""Login user and return url."""
login_user_via_session(client, user=User.query.get(user.id))
return user | 079136eb777957caf09c51c75ae5148ab2eea836 | 4,500 |
def search(request):
"""renders search page"""
queryset_list = Listing.objects.order_by('-list_date')
if 'keywords' in request.GET:
keywords = request.GET['keywords']
# Checking if its none
if keywords:
queryset_list = queryset_list.filter(
description__... | a25d6e112d4054dfaf505aff5c4c36f07a95d989 | 4,501 |
def generate_cutout(butler, skymap, ra, dec, band='N708', data_type='deepCoadd',
half_size=10.0 * u.arcsec, psf=True, verbose=False):
"""Generate a single cutout image.
"""
if not isinstance(half_size, u.Quantity):
# Assume that this is in pixel
half_size_pix = int(half_s... | fdc42ad0dd0f357d53804a1f6fa43c93e86d2c0e | 4,502 |
def get_arraytypes ():
"""pygame.sndarray.get_arraytypes (): return tuple
Gets the array system types currently supported.
Checks, which array system types are available and returns them as a
tuple of strings. The values of the tuple can be used directly in
the use_arraytype () method.
If no ... | 192cb215fdc651543ac6ed4ce2f9cac2b0d3b4f4 | 4,503 |
def is_request_authentic(request, secret_token: bytes = conf.WEBHOOK_SECRET_TOKEN):
"""
Examine the given request object to determine if it was sent by an authorized source.
:param request: Request object to examine for authenticity
:type request: :class:`~chalice.app.Request`
:param secret_token: ... | 1ffceea3aebc0c038384c003edc93358e6faa9ed | 4,504 |
def circular_mask_string(centre_ra_dec_posns, aperture_radius="1arcmin"):
"""Get a mask string representing circular apertures about (x,y) tuples"""
mask = ''
if centre_ra_dec_posns is None:
return mask
for coords in centre_ra_dec_posns:
mask += 'circle [ [ {x} , {y}] , {r} ]\n'.format(
... | 04e66d160eb908f543990adf896e494226674c71 | 4,505 |
def dataset_hdf5(dataset, tmp_path):
"""Make an HDF5 dataset and write it to disk."""
path = str(tmp_path / 'test.h5')
dataset.write_hdf5(path, object_id_itemsize=10)
return path | 4a7920adf7715797561513fbb87593abf95f0bca | 4,506 |
def _make_indexable(iterable):
"""Ensure iterable supports indexing or convert to an indexable variant.
Convert sparse matrices to csr and other non-indexable iterable to arrays.
Let `None` and indexable objects (e.g. pandas dataframes) pass unchanged.
Parameters
----------
iterable : {list, d... | 94be904009adfd3bf15de0f258b94a196a9612df | 4,507 |
import sys
import abc
def get_all_readers():
"""Get all the readers from the module."""
readers = []
for _, name in getmembers(sys.modules[__name__]):
if isinstance(name, abc.ABCMeta) and name.__name__ != 'Reader':
readers.append(name)
return readers | 50d8451ce70c2a2b5a4561952911f960c3667d02 | 4,508 |
def fib_for(n):
"""
Compute Fibonnaci sequence using a for loop
Parameters
----------
n : integer
the nth Fibonnaci number in the sequence
Returns
-------
the nth Fibonnaci number in the sequence
"""
res = [0, 1]
for i in range(n-1):
res.append(res[i] + res... | 1609a2d52f5308a6a9d496f13c1de3f7eee6332d | 4,509 |
import pickle
def command_factory(command):
"""A factory which returns functions for direct daemon communication.
This factory will create a function which sends a payload to the daemon
and returns the unpickled object which is returned by the daemon.
Args:
command (string): The type of payl... | ec84d6ab611d4edaf55ba0c365ed8526250c7ce1 | 4,510 |
def load_prepare_saif_data(threshold=0.25):
"""
Loads and prepares saif's data.
Parameters
----------
threshold : float
Only data with intensities equal to or
above this threshold will be kept (range 0-1).
Returns
-------
DataFrame : pd.DataFrame
Concatenated t... | b2087d0558473069cf5985bd7e2b063162157df5 | 4,511 |
def nonmax_suppression(harris_resp, halfwidth=2):
"""
Takes a Harris response from an image, performs nonmax suppression, and outputs the x,y values
of the corners in the image.
:param harris_resp: Harris response for an image which is an array of the same shape as the original image.
:param half... | b980ac9045728c8231749e7a43aa2f06d958d80c | 4,512 |
import uuid
from datetime import datetime
import pytz
def create_credit_request(course_key, provider_id, username):
"""
Initiate a request for credit from a credit provider.
This will return the parameters that the user's browser will need to POST
to the credit provider. It does NOT calculate the si... | 8c9e763d1f10f9187c102746911dc242385100e8 | 4,513 |
import pathlib
def is_valid_project_root(project_root: pathlib.Path) -> bool:
"""Check if the project root is a valid trestle project root."""
if project_root is None or project_root == '' or len(project_root.parts) <= 0:
return False
trestle_dir = pathlib.Path.joinpath(project_root, const.TRESTL... | f35d63373d96ee34592e84f21296eadb3ebc6c98 | 4,514 |
def make_2D_predictions_into_one_hot_4D(prediction_2D, dim):
"""
This method gets 2D prediction of shape (#batch, #kpts)
and then returns 4D one_hot maps of shape
(#batch, #kpts, #dim, #dim)
"""
# getting one_hot maps of predicted locations
# one_hot_maps is of shape (#batch, #kpts, #dim * ... | 507d2fa9c52d5f8a1674e695f55928783a179082 | 4,515 |
import bisect
def display_code_marginal_densities(codes, num_hist_bins, log_prob=False,
ignore_vals=[], lines=True, overlaid=False, plot_title=""):
"""
Estimates the marginal density of coefficients of a code over some dataset
Parameters
----------
codes : ndarray(float32, size=(D, s))
The codes ... | 2085e007c25b855dda78fa910c2c93dc4c2b0767 | 4,516 |
def distance(a, b):
"""
"""
dimensions = len(a)
_sum = 0
for dimension in range(dimensions):
difference_sq = (a[dimension] - b[dimension]) ** 2
_sum += difference_sq
return sqrt(_sum) | 20acd50d7e3ab7f512f3e9ab9920f76b805043a9 | 4,517 |
def is_block(modules):
"""Check if is ResNet building block."""
if isinstance(modules, (BasicBlock, Bottleneck)):
return True
return False | 8c6b5f59797646b27301a25a40d753b6c404b418 | 4,518 |
def playlist_500_fixture():
"""Load payload for playlist 500 and return it."""
return load_fixture("plex/playlist_500.xml") | 834efe057419f56b626c40430b68860fd5e0db1e | 4,519 |
def strip_output(nb):
"""strip the outputs from a notebook object"""
nb.metadata.pop('signature', None)
for cell in nb.cells:
if 'outputs' in cell:
cell['outputs'] = []
if 'prompt_number' in cell:
cell['prompt_number'] = None
return nb | 6339100f6897951bad4f91f8b8d86d1e5a68f459 | 4,520 |
def get_neighbors_general(status: CachingDataStructure, key: tuple) -> list:
"""
Returns a list of tuples of all coordinates that are direct neighbors,
meaning the index is valid and they are not KNOWN
"""
coords = []
for key in get_direct_neighbour_coords_general(key):
if status.valid_i... | 46a2b3aa91e424122982011ccaa684c2d9cf83f2 | 4,521 |
def transit_params(time):
"""
Dummy transit parameters for time series simulations
Parameters
----------
time: sequence
The time axis of the transit observation
Returns
-------
batman.transitmodel.TransitModel
The transit model
"""
params = batman.TransitParams(... | 5e74a32ef4077a990d44edb15d66e56e00925666 | 4,522 |
def actions(__INPUT):
"""
Regresamos una lista de los posibles movimientos de la matriz
"""
MOVIMIENTOS = []
m = eval(__INPUT)
i = 0
while 0 not in m[i]:
i += 1
# Espacio en blanco (#0)
j = m[i].index(0);
if i > 0:
#ACCION MOVER ARRIBA
m[i][j], m[i-1][j] = m[i-... | 46875f83d7f50bbd107be8ad5d926397960ca513 | 4,523 |
def get_massif_geom(massif: str) -> WKBElement:
"""process to get the massifs geometries:
* go on the meteofrance bra website
* then get the html "area" element
* then convert it to fake GeoJSON (wrong coordinates)
* then open it in qgis.
* Select *all* the geom of the layer.
* rotate -90°... | 194ef4274dfd240af65b61781f39464e0cde4b3d | 4,524 |
def _to_arrow(x):
"""Move data to arrow format"""
if isinstance(x, cudf.DataFrame):
return x.to_arrow()
else:
return pa.Table.from_pandas(x, preserve_index=False) | c88c40d2d35f681ff268347c36e2cae4a52576d0 | 4,525 |
def painel(request):
""" Exibe o painel do usuário. """
return render(request, "lancamentos/painel.html") | ff40db732402077eb6678f8586582877d96e3ede | 4,526 |
from shutil import which as shwhich
import os
def which(program, mode=os.F_OK | os.X_OK, path=None):
"""
Mimics the Unix utility which.
For python3.3+, shutil.which provides all of the required functionality.
An implementation is provided in case shutil.which does
not exist.
:param program: (... | fbba58ba489db2c2813e4aadf9781c35d6955f0f | 4,527 |
def q_statistic(y, c1, c2):
""" Q-Statistic.
Parameters
----------
y : numpy.array
Target sample.
c1 : numpy.array
Output of the first classifier.
c2 : numpy.array
Output of the second classifier.
Returns
-------
float
Return the Q-Statistic measur... | 83f83bffcb469ff45c22a1f35efc6e60ccdd0d2d | 4,528 |
def nan_helper(y):
"""Helper to handle indices and logical indices of NaNs.
Input:
- y, 1d numpy array with possible NaNs
Output:
- nans, logical indices of NaNs
- index, a function, with signature indices= index(logical_indices),
to convert logical indices of NaNs to 'equ... | b6bd981369403a5542f8bcefb3e8a68315fb697f | 4,529 |
import sys
def lid_mle_amsaleg(knn_distances):
"""
Local intrinsic dimension (LID) estimators from the papers,
1. Amsaleg, Laurent, et al. "Estimating local intrinsic dimensionality." Proceedings of the 21th ACM SIGKDD
International Conference on Knowledge Discovery and Data Mining. ACM, 2015.
2.... | 2936489035f76a4825a3cb0a64e22febeaf6f541 | 4,530 |
def _rebase_bv(bv: BinaryView, dbg: DebugAdapter.DebugAdapter) -> BinaryView:
"""Get a rebased BinaryView for support of ASLR compatible binaries."""
new_base = dbg.target_base()
if core_ui_enabled() and new_base != bv.start:
dbg.quit()
raise Exception('[!] Can\'t do necessary rebase in GUI,... | f02c031d65ab0758c63536f30dd9229f495b4014 | 4,531 |
import re
def convert_parameters(child, text=False, tail=False, **kwargs):
"""
Get child text or tail
:param child:
:param text:
:param tail:
:return:
"""
p = re.compile(r'\S')
# Remove empty info
child_text = child.text if child.text else ''
child_tail = child.tail if chil... | 2421e515491f1256c56eb9ac6935a3c0c1de64be | 4,532 |
def Get_Country_Name_From_ISO3_Extended(countryISO):
"""
Creates a subset of the quick chart data for a specific country. The subset includes all those rows containing
the given country either as the origin or as the country of asylum.
"""
countryName = ""
# June-22 - This function has been u... | d6e5b34223582f3a5a5ca20fd798ef5cfb1b1e8d | 4,533 |
import sys
def to_cpu(x):
""" Move cupy arrays (or dicts/lists of arrays) to CPU """
if len(sys.argv) > 1:
if type(x) == dict:
return {k:to_cpu(a) for (k, a) in x.items()}
elif type(x) == list:
return [to_cpu(a) for a in x]
else:
return cp.asnumpy(x)
else:
return x | 60ddb9774b5447862d8f5d1f605e9027c3f7c471 | 4,534 |
import re
import os
def parse_mapfile(map_file_path):
"""Parse the '.map' file"""
def parse_keyboard_function(f, line):
"""Parse keyboard-functions in the '.map' file"""
search = re.search(r'(0x\S+)\s+(0x\S+)', next(f))
position = int( search.group(1), 16 )
length = int( search.group(2), 16 )
search = ... | c84b10e95a212f7cc878d9d6a555a0b3ffc67728 | 4,535 |
def thetaG(t,t1,t2):
"""
Return a Gaussian pulse.
Arguments:
t -- time of the pulse
t1 -- initial time
t2 -- final time
Return:
theta -- Scalar or vector with the dimensions of t,
"""
tau = (t2-t1)/5
to = t1 + (t2-t1)/2
thet... | 9e05358bfbf5f11b30f2a6b44504214ab4db4ea5 | 4,536 |
def choose_string(g1, g2):
"""Function used by merge_similar_guesses to choose between 2 possible
properties when they are strings.
If the 2 strings are similar, or one is contained in the other, the latter is returned
with an increased confidence.
If the 2 strings are dissimilar, the one with the... | e39a66c9f3f941b12225dde879bc92956694d2d0 | 4,537 |
def update_alert_command(client: MsClient, args: dict):
"""Updates properties of existing Alert.
Returns:
(str, dict, dict). Human readable, context, raw response
"""
alert_id = args.get('alert_id')
assigned_to = args.get('assigned_to')
status = args.get('status')
classification = a... | 237aa63f449dc6395390a26007b15123d5763874 | 4,538 |
def create_payment(context: SagaContext) -> SagaContext:
"""For testing purposes."""
context["payment"] = "payment"
return context | e96db6e57996d8f704e453bf14b8e4a3c63da1a6 | 4,539 |
import asyncio
async def TwitterAuthURLAPI(
request: Request,
current_user: User = Depends(User.getCurrentUser),
):
"""
Twitter アカウントと連携するための認証 URL を取得する。<br>
認証 URL をブラウザで開くとアプリ連携の許可を求められ、ユーザーが許可すると /api/twitter/callback に戻ってくる。
JWT エンコードされたアクセストークンがリクエストの Authorization: Bearer に設定されていないとアクセ... | 2245c3b2d842c455fa9cb36390c84c8470c3b8e1 | 4,540 |
import random
def post_sunday(request):
"""Post Sunday Details, due on the date from the form"""
date_form = SelectDate(request.POST or None)
if request.method == 'POST':
if date_form.is_valid():
groups = DetailGroup.objects.filter(semester=get_semester())
details = settin... | 84787109d0981920bbced7a734d0b67c84d4a9a7 | 4,541 |
from typing import Dict
from typing import List
def reconstruct(lvl: Level, flow_dict: Dict[int, Dict[int, int]], info: Dict[int, NodeInfo]) -> List[List[int]]:
"""Reconstruct agent paths from the given flow and node information"""
paths: List[List[int]] = [[]] * len(lvl.scenario.agents)
start_flows = flo... | d792ed6b937f49177ac85609ada3edb2089e2642 | 4,542 |
import traceback
def arch_explain_instruction(bv, instruction, lifted_il_instrs):
""" Returns the explanation string from explanations_en.json, formatted with the preprocessed instruction token list """
if instruction is None:
return False, []
parsed = parse_instruction(bv, instruction, lifted_il_... | 57c6146ac06317df8a9e9b846a279fa950a970bc | 4,543 |
from lpot.ux.utils.workload.workload import Workload
from typing import Dict
from typing import Any
import os
import json
def execute_tuning(data: Dict[str, Any]) -> dict:
"""Get configuration."""
if not str(data.get("id", "")):
message = "Missing request id."
mq.post_error(
"tuni... | 370630145325b2166030c6402ed17bce2cf9ed70 | 4,544 |
def get_subnet_mask(subnet: int, v6: bool) -> int:
"""Get the subnet mask given a CIDR prefix 'subnet'."""
if v6:
return bit_not((1 << (128 - subnet)) - 1, 128)
else:
return bit_not((1 << (32 - subnet)) - 1, 32) | 57c8de0bff70b0939dd8c646da0840be7c2839e1 | 4,545 |
import argparse
def get_parser():
"""Return base parser for scripts.
"""
parser = argparse.ArgumentParser()
parser.add_argument('config', help='Tuning configuration file (examples: configs/tuning)')
return parser | 6f394f836fae278b659a0612a088f53563c8f34b | 4,546 |
def home(request):
"""return HttpResponse('<h1>Hello, Welcome to this test</h1>')"""
"""Le chemin des templates est renseigne dans "DIRS" de "TEMPLATES" dans settings.py
DONC PAS BESOIN DE RENSEIGNER LE CHEMIN ABSOLU"""
return render(request, "index.html") | 04a671daa9425ea76841b491f8eefd133b6e2c67 | 4,547 |
import os
def cd(path):
"""Context manager to switch working directory"""
def normpath(path):
"""Normalize UNIX path to a native path."""
normalized = os.path.join(*path.split('/'))
if os.path.isabs(path):
return os.path.abspath('/') + normalized
return normalized
path = normpath(path)
c... | f1664765e26e3ff4ec8a70d16d6beca5a23f4d68 | 4,548 |
def extract_commands(data, *commands):
"""Input function to find commands output in the "data" text"""
ret = ""
hostname = _ttp_["variable"]["gethostname"](data, "input find_command function")
if hostname:
for command in commands:
regex = r"{}[#>] *{} *\n([\S\s]+?)(?={}[#>]|$)".forma... | 6fcbf9584f5a2f799839c9964a5ae6235f4e8b50 | 4,549 |
def get_version() -> str:
"""
Returns the version string for the ufotest project. The version scheme of ufotest loosely follows the
technique of `Semantic Versioning <https://semver.org/>`_. Where a minor version change may introduce backward
incompatible changes, due to the project still being in activ... | b34eac3aef7661b65408c60ce606cd24a06ae0ee | 4,550 |
async def clear_pending_revocations(request: web.BaseRequest):
"""
Request handler for clearing pending revocations.
Args:
request: aiohttp request object
Returns:
Credential revocation ids still pending revocation by revocation registry id.
"""
context: AdminRequestContext = ... | 98db34266f3afbe9ecfeddcf802c1441ae7ea58b | 4,551 |
from datetime import datetime
def add_filter(field, bind, criteria):
"""Generate a filter."""
if 'values' in criteria:
return '{0}=any(:{1})'.format(field, bind), criteria['values']
if 'date' in criteria:
return '{0}::date=:{1}'.format(field, bind), datetime.strptime(criteria['date'], '%Y-... | 2358cab297b2a2cbc42af02b3b6d14ac134c8b71 | 4,552 |
def ireject(predicate, iterable):
"""Reject all items from the sequence for which the predicate is true.
ireject(function or None, sequence) --> iterator
:param predicate:
Predicate function. If ``None``, reject all truthy items.
:param iterable:
Iterable to filter through.
:yields:
A ... | 98f9416ac1db1f2909d1d895ee0c0bc70c8b2249 | 4,553 |
def construct_config_error_msg(config, errors):
"""Construct an error message for an invalid configuration setup
Parameters
----------
config: Dict[str, Any]
Merged dictionary of configuration options from CLI, user configfile and
default configfile
errors: Dict[str, Any]
Di... | 02954620115308d7d50ca28b23b98a2ba410489f | 4,554 |
def isMSAADebugLoggingEnabled():
""" Whether the user has configured NVDA to log extra information about MSAA events. """
return config.conf["debugLog"]["MSAA"] | 8bd9359b73b643534933b90a5fb0810668ca440c | 4,555 |
def _haversine_GC_distance(φ1, φ2, λ1, λ2):
"""
Haversine formula for great circle distance. Suffers from rounding errors for
antipodal points.
Parameters
----------
φ1, φ2 : :class:`numpy.ndarray`
Numpy arrays wih latitudes.
λ1, λ2 : :class:`numpy.ndarray`
Numpy arrays wih ... | bb57ddeacd761abead5ee499610ead8c9ba38a9f | 4,556 |
def differentiate_branch(branch, suffix="deriv"):
"""calculates difference between each entry and the previous
first entry in the new branch is difference between first and last entries in the input"""
def bud(manager):
return {add_suffix(branch,suffix):manager[branch]-np.roll(manager[branch],1)}
return bud | 298b19b1e151e04df9c040f0c48e4799bcc3f3d2 | 4,557 |
import typing
def etf_holders(apikey: str, symbol: str) -> typing.Optional[typing.List[typing.Dict]]:
"""
Query FMP /etf-holder/ API.
:param apikey: Your API key.
:param symbol: Company ticker.
:return: A list of dictionaries.
"""
path = f"etf-holder/{symbol}"
query_vars = {"apikey": ... | f405fa92296c28a8ba8ca87b6edac27392ec1f85 | 4,558 |
def clean_visibility_flags(horizon_dataframe: pd.DataFrame) -> pd.DataFrame:
"""
assign names to unlabeled 'visibility flag' columns -- solar presence,
lunar/interfering body presence, is-target-on-near-side-of-parent-body,
is-target-illuminated; drop then if empty
"""
flag_mapping = {
u... | 906432120babffacb709b1d45e7c4dd86c60775d | 4,559 |
def calib(phase, k, axis=1):
"""Phase calibration
Args:
phase (ndarray): Unwrapped phase of CSI.
k (ndarray): Subcarriers index
axis (int): Axis along which is subcarrier. Default: 1
Returns:
ndarray: Phase calibrated
ref:
[Enabling Contactless Detection of Mov... | 5e1f59c0a13440ad8e1304523976c2fbe6562d5a | 4,560 |
def rescale_as_int(
s: pd.Series, min_value: float = None, max_value: float = None, dtype=np.int16
) -> pd.Series:
"""Cannot be converted to njit because np.clip is unsupported."""
valid_dtypes = {np.int8, np.int16, np.int32}
if dtype not in valid_dtypes:
raise ValueError(f"dtype: expecting [{va... | 31772759c67d33f20b89fd87aa91c9249ae2bb9a | 4,561 |
def format_headers(headers):
"""Formats the headers of a :class:`Request`.
:param headers: the headers to be formatted.
:type headers: :class:`dict`.
:return: the headers in lower case format.
:rtype: :class:`dict`.
"""
dictionary = {}
for k, v in headers.items():
if isinstanc... | 0a0890c10378d9f8e20f353b1b9383e728f0a4f7 | 4,562 |
def decode_field(value):
"""Decodes a field as defined in the 'Field Specification' of the actions
man page: http://www.openvswitch.org/support/dist-docs/ovs-actions.7.txt
"""
parts = value.strip("]\n\r").split("[")
result = {
"field": parts[0],
}
if len(parts) > 1 and parts[1]:
... | 1a1659e69127ddd3c63eb7d4118ceb4e53a28ca0 | 4,563 |
import tqdm
def compute_norm(x_train, in_ch):
"""Returns image-wise mean and standard deviation per channel."""
mean = np.zeros((1, 1, 1, in_ch))
std = np.zeros((1, 1, 1, in_ch))
n = np.zeros((1, 1, 1, in_ch))
# Compute mean.
for x in tqdm(x_train, desc='Compute mean'):
mean += np.sum... | e49012075adfa03b33bb6308d1d50f4c22c1cc2c | 4,564 |
def _nonempty_line_count(src: str) -> int:
"""Count the number of non-empty lines present in the provided source string."""
return sum(1 for line in src.splitlines() if line.strip()) | ad2ac0723f9b3e1f36b331175dc32a8591c67893 | 4,565 |
import json
def geom_to_xml_element(geom):
"""Transform a GEOS or OGR geometry object into an lxml Element
for the GML geometry."""
if geom.srs.srid != 4326:
raise NotImplementedError("Only WGS 84 lat/long geometries (SRID 4326) are supported.")
# GeoJSON output is far more standard than GML, ... | a2702e8ac4e3cb24f787513f820df60ad973e305 | 4,566 |
import os
def _validate_source(source):
"""
Check that the entered data source paths are valid
"""
# acceptable inputs (for now) are a single file or directory
assert type(source) == str, "You must enter your input as a string."
assert (
os.path.isdir(source) == True or os.path.isfile... | 45e1f88f6c246713f85d83cf6a9753ec67799774 | 4,567 |
def precision(y_true, y_pred):
"""Precision metric.
Only computes a batch-wise average of precision.
Computes the precision, a metric for multi-label classification of
how many selected items are relevant.
Parameters
----------
y_true : numpy array
an array of true labels
y_pred... | d57f1d782628e312b2e52098658be81e32351f3d | 4,568 |
def get_validators(setting):
"""
:type setting: dict
"""
if 'validate' not in setting:
return []
validators = []
for validator_name in setting['validate'].keys():
loader_module = load_module(
'spreadsheetconverter.loader.validator.{}',
validator_name)
... | db3b5594122685f3190cdae053ab7a385065d17e | 4,569 |
def _check_found(py_exe, version_text, log_invalid=True):
"""Check the Python and pip version text found.
Args:
py_exe (str or None): Python executable path found, if any.
version_text (str or None): Pip version found, if any.
log_invalid (bool): Whether to log messages if found invalid... | 5262c3e5db5384e7b4addb6288018f23100e7115 | 4,570 |
def worker(remote, parent_remote, env_fn_wrapper):
""" worker func to execute vec_env commands
"""
def step_env(env, action):
ob, reward, done, info = env.step(action)
if done:
ob = env.reset()
return ob, reward, done, info
parent_remote.close()
envs = [env_fn_w... | aaf5a16a72e97ec46e3a1ae4676c4591bc7f0183 | 4,571 |
from functools import reduce
def greedysplit_general(n, k, sigma, combine=lambda a,
b: a + b, key=lambda a: a):
""" Do a greedy split """
splits = [n]
s = sigma(0, n)
def score(splits, sigma):
splits = sorted(splits)
return key(reduce(combine, (sigma(a, b)
... | 6480db8f613f37704e7bf6552407e5b0f851ab47 | 4,572 |
def public_assignment_get(assignment_id: str):
"""
Get a specific assignment spec
:param assignment_id:
:return:
"""
return success_response({
'assignment': get_assignment_data(current_user.id, assignment_id)
}) | 2f3d828975c0d7db663556da5f0dc590124075b2 | 4,573 |
def recursion_detected(frame, keys):
"""Detect if we have a recursion by finding if we have already seen a
call to this function with the same locals. Comparison is done
only for the provided set of keys.
"""
current = frame
current_filename = current.f_code.co_filename
current_function = c... | ebf30e715d2901169095bc920e8af6c715f2a1de | 4,574 |
import argparse
def arg_parser(cmd_line=None, config=None):
"""
Parse the command line or the parameter to pass to the rest of the workflow
:param cmd_line: A string containing a command line (mainly used for
testing)
:return: An args object with overrides for the configuration
"""
default... | 6d04361584f0aaf5743e3db70410c443e5cf9b5f | 4,575 |
def pars_to_blocks(pars):
""" this simulates one of the phases the markdown library goes through when parsing text and returns the paragraphs grouped as blocks, as markdown handles them
"""
pars = list(pars)
m = markdown.Markdown()
bp = markdown.blockprocessors.build_block_parser(m)
root = mark... | f71d4460847ec4b69ad53470aba26c145d296388 | 4,576 |
from bs4 import BeautifulSoup
def extract_intersections_from_osm_xml(osm_xml):
"""
Extract the GPS coordinates of the roads intersections
Return a list of gps tuples
"""
soup = BeautifulSoup(osm_xml)
retval = []
segments_by_extremities = {}
Roads = []
RoadRefs = []
Coordinat... | 6cff1fe39891eb4a6c595196eabfd4569af2fd8e | 4,577 |
def spark_session(request):
"""Fixture for creating a spark context."""
spark = (SparkSession
.builder
.master('local[2]')
.config('spark.jars.packages', 'com.databricks:spark-avro_2.11:3.0.1')
.appName('pytest-pyspark-local-testing')
.enableHive... | e7a95ad7ebea876976923c6dd16c7a761116427d | 4,578 |
import yaml
def _load_model_from_config(config_path, hparam_overrides, vocab_file, mode):
"""Loads model from a configuration file"""
with gfile.GFile(config_path) as config_file:
config = yaml.load(config_file)
model_cls = locate(config["model"]) or getattr(models, config["model"])
model_params = config[... | 97af7dc919de5af96332c8445e162990006079f4 | 4,579 |
import ast
def _get_assignment_node_from_call_frame(frame):
"""
Helper to get the Assign or AnnAssign AST node for a call frame.
The call frame will point to a specific file and line number, and we use the
source index to retrieve the AST nodes for that line.
"""
filename = frame.f_code.co_filename
# Go... | edb7f2425d170721e12dc4c1e2427e9584aeed8c | 4,580 |
def check_existing_user(username):
"""
a function that is used to check and return all exissting accounts
"""
return User.user_exist(username) | 573e9a8a6c0e504812d3b90eb4a27b15edec35ab | 4,581 |
def createevent():
""" An event is a (immediate) change of the world. It has no
duration, contrary to a StaticSituation that has a non-null duration.
This function creates and returns such a instantaneous situation.
:sees: situations.py for a set of standard events types
"""
sit = Situation(... | 998f0a473c47828435d7e5310de29ade1fbd7810 | 4,582 |
def _dump_multipoint(obj, fmt):
"""
Dump a GeoJSON-like MultiPoint object to WKT.
Input parameters and return value are the MULTIPOINT equivalent to
:func:`_dump_point`.
"""
coords = obj['coordinates']
mp = 'MULTIPOINT (%s)'
points = (' '.join(fmt % c for c in pt) for pt in coords)
... | cdea05b91c251b655e08650807e3f74d3bb5e77b | 4,583 |
def do_inference(engine, pics_1, h_input_1, d_input_1, h_output, d_output, stream, batch_size, height, width):
"""
This is the function to run the inference
Args:
engine : Path to the TensorRT engine
pics_1 : Input images to the model.
h_input_1: Input in the host
... | e9e452e96d42167bf17bc6bef8dc014fa31dbe8f | 4,584 |
import ast
def make_import():
"""Import(alias* names)"""
return ast.Import(names=[make_alias()]) | e9085ee9b4b0438857b50b891fbee0b88d256f8b | 4,585 |
from typing import Union
from typing import List
def preprocess(
image: Union[np.ndarray, Image.Image],
threshold: int = None,
resize: int = 64,
quantiles: List[float] = [.01, .05, 0.1,
0.25, 0.5, 0.75, 0.9, 0.95, 0.99],
reduction: Union[str, L... | afa36739309ada2e97e18e63ae65362546b1b52c | 4,586 |
def binary_distance(label1, label2):
"""Simple equality test.
0.0 if the labels are identical, 1.0 if they are different.
>>> from nltk.metrics import binary_distance
>>> binary_distance(1,1)
0.0
>>> binary_distance(1,3)
1.0
"""
return 0.0 if label1 == label2 else 1.0 | 2c4eaebda2d6955a5012cc513857aed66df60194 | 4,587 |
def fetch_collections_info(data):
"""Connect to solr_cloud status page and and return JSON object"""
url = "{0}/admin/collections?action=CLUSTERSTATUS&wt=json".format(data["base_url"])
get_data = _api_call(url, data["opener"])
solr_cloud = {}
if get_data is None:
collectd.error("solr_collec... | cfb3e4dda7986f4f13fd24b5e26a12ae96ceb6e6 | 4,588 |
def calc_commission_futures_global(trade_cnt, price):
"""
国际期货:差别很大,最好外部自定义自己的计算方法,这里只简单按照0.002计算
:param trade_cnt: 交易的股数(int)
:param price: 每股的价格(美元)
:return: 计算结果手续费
"""
cost = trade_cnt * price
# 国际期货各个券商以及代理方式差别很大,最好外部自定义计算方法,这里只简单按照0.002计算
commission = cost * 0.002
return co... | ddd2c4571abfcdf7021a28b6cc78fe6441da2bd3 | 4,589 |
def is_section_command(row):
"""CSV rows are cosidered new section commands if they start with
<SECTION> and consist of at least two columns column.
>>> is_section_command('<SECTION>\tSection name'.split('\t'))
True
>>> is_section_command('<other>\tSection name'.split('\t'))
False
>>> is_... | 7942625e119c4a0d3707fd5884ade6e48b2dfb1a | 4,590 |
import os
def download(auth, url, headers, output_path, size, overwrite,
f_name=None,
ext=None,
block_size=4096,
callback=None):
"""
Call GET for a file stream.
:Args:
- auth (:class:`.Credentials`): The session credentials object.
- url... | 46566124cc1a5425217655239c976fcf9ab378e8 | 4,591 |
def to_int(matrix):
"""
Funciton to convert the eact element of the matrix to int
"""
for row in range(rows(matrix)):
for col in range(cols(matrix)):
for j in range(3):
matrix[row][col][j] = int(matrix[row][col][j])
return matrix | 9f277ab0c0fe7df145e8a4c0da36fba25a523756 | 4,592 |
def create_tastypie_resource(class_inst):
"""
Usage: url(r'^api/', include(create_tastypie_resource(UfsObjFileMapping).urls)),
Access url: api/ufs_obj_file_mapping/?format=json
:param class_inst:
:return:
"""
return create_tastypie_resource_class(class_inst)() | cba76e51073612124c5cd968c9360e9c4748d604 | 4,593 |
def make_collector(entries):
""" Creates a function that collects the location data from openLCA. """
def fn(loc):
entry = [loc.getCode(), loc.getName(), loc.getRefId()]
entries.append(entry)
return fn | 83fb167c38626fde79262a32f500b33a72ab8308 | 4,594 |
def apiname(funcname):
""" Define what name the API uses, the short or the gl version.
"""
if funcname.startswith('gl'):
return funcname
else:
if funcname.startswith('_'):
return '_gl' + funcname[1].upper() + funcname[2:]
else:
return 'gl' + funcname[0].up... | 06575fce76ac02990c973a6dd17ff177ae5e3ddc | 4,595 |
def add_numeric_gene_pos(gene_info):
"""
Add numeric gene (start) genomic position to a gene_info dataframe
"""
gene_chr_numeric = gene_info['chr']
gene_chr_numeric = ['23' if x == 'X' else x for x in gene_chr_numeric]
gene_chr_numeric = ['24' if x == 'Y' else x for x in gene_chr_numeric]
ge... | ab77e6c3a1f6e8d780f5b83a3beb4d94eaf8198b | 4,596 |
import pathlib
def read_list_from_file(filename: str) -> set:
"""Build a set from a simple multiline text file.
Args:
filename: name of the text file
Returns:
a set of the unique lines from the file
"""
filepath = pathlib.Path(__file__).parent.joinpath(filename)
lines = filep... | c6fd5f80e05cc74bad600a7af21e36b5bd672b63 | 4,597 |
def parseAnswerA(answer, index, data):
"""
parseAnswerA(data): Grab our IP address from an answer to an A query
"""
retval = {}
text = (str(answer[0]) + "." + str(answer[1])
+ "." + str(answer[2]) + "." + str(answer[3]))
retval["ip"] = text
#
# TODO: There may be pointers even for A responses. Will have ... | 6cf1f01b6584219644093d7f0a1a730262b03b32 | 4,598 |
import os
def _get_files(data_path, modality, img_or_label):
"""Gets files for the specified data type and dataset split.
Args:
data: String, desired data ('image' or 'label').
dataset_split: String, dataset split ('train', 'val', 'test')
Returns:
A list of sorted file names or None when getting lab... | 99687ddb26bed76d2c609848ba79d4ad795b6827 | 4,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.