content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
from typing import Tuple
def partwise_function(function: str, parts: List[Tuple[str, str]], add_zero_otherwise: bool = True) -> str:
"""
Returns a string representing the definition a part-wise mathematical function.
**Parameters**
- `function`: str
The name of the f... | b2954a9c947add4cf4b4740ac62f4ca16d3e1d70 | 3,630,200 |
def coprime(a, b):
"""0 is coprime only with 1"""
return gcd(a, b) in (0, 1) | e2b6434390f5569bd6b4817271f7b32e0e205193 | 3,630,201 |
def user_picture1(request):
"""A view that is vulnerable to malicious file access."""
filename = request.GET.get('p')
# BAD: This could read any file on the file system
data = open(filename, 'rb').read()
return HttpResponse(data) | 8601c9c23391d6224a0a63e8d19d9054454a3ea4 | 3,630,202 |
import random
import array
def random_array():
"""
089
Create an array which will store a list of integers. Generate five random numbers and store them in
the array. Display the array (showing each item on a separate line).
"""
rand_array, counter = array("i"), 5
while counter:
ran... | fb5f35dadabd4bb9976248f40db2201c2a0f8a8b | 3,630,203 |
def load_seq_ids(fname):
"""Load sequence of IDs from txt file."""
ids = []
with open(fname, "r") as f:
for line in f:
ids.append(int(line.strip()))
ids = np.asarray(ids)
return ids | 1a80dcbedefccc89a3e9944276131f0c7f30bdad | 3,630,204 |
from . import routes
def create_app(config):
"""Initialize the core application."""
app = Flask(__name__, instance_relative_config=False)
app.config.from_object(config)
db.init_app(app)
with app.app_context():
# Include our Routes
# Register Blueprints
# Call factory fun... | dc67754a5eda92edeec7de314e5560cb2fca1d89 | 3,630,205 |
def is_valid_maze(maze):
"""Returns True if the maze is valid, False otherwise."""
# Asserts each constraint and returns False if any are not met.
if not constraint_0(maze):
return(False)
if not constraint_1(maze):
return(False)
if not constraint_2(maze):
return(False)
if... | d6be2ff37899134ae108d299d226423b9c0f0c4e | 3,630,206 |
def spectral_dimension_ui(i):
"""Return a list of widgets whose entries are used in evaluating the dimension
coordinates along the i^th dimension. The widgets includes number of points (count),
spectral width, and reference offset.
Args:
i: An integer with the dimension index.
"""
# cou... | 56deda19f52aed1752c464767ce374cbdab85f31 | 3,630,207 |
def get_params(filename=None, **kwargs):
"""Return all the parameters, retrieved following this order of priority:
* parameters specified as keyword arguments in this function,
* parameters specified in the .PRM file given in `filename`,
* default parameters.
"""
# Extract sample_rate ... | 14514e61cd4083e9d10201273e5f6589710227d6 | 3,630,208 |
def read_restrictions_file(file):
"""
<Purpose>
Reads in the contents of a restrictions file.
<Arguments>
file: name/path of the file to open
<Returns>
A list, where each element is a line in the file
"""
# Get the file object, read mode with universal newlines
fileo = open(file,"rU"... | df7207ea3bab49af47fcfbdaa9cc51f54692bb85 | 3,630,209 |
def argsToParams(args):
"""
"""
if args.explanation_computer == ExplanationComputer.MUS.name:
params = MUSParams()
elif args.explanation_computer == ExplanationComputer.OUS_INCREMENTAL_NAIVE.name:
params = OusIncrNaiveParams()
elif args.explanation_computer == ExplanationComputer.OUS... | a45c75ac4a9df617e76b35226a392c802f7ce6b8 | 3,630,210 |
def randiwishart(sigma, df):
""" Generate an inverse Wishart random matrix in the form consistent with randiwishart.m
:param sigma: covariance matrix (n x n)
:param df: degrees of freedom. Must be greater than n (dimension of sigma)
:type sigma: np.ndarray
:type df: int
:return: sqrtinvx
... | 077c46a878d9a26628def661d186cb79c2ffef03 | 3,630,211 |
def get_pred_metrics(key_filepath, pred_filepath, average="macro"):
""" Gets F1 value out a key and predicted csv files
Files must be formated as
name,target
name1,1
name2,3
...
name948,2
name949,2
"""
key = pd.read_csv(key_filepath)
pred = pd.read_csv(pred_filepath)
asse... | bf89fb8a31b334f2c23f28cef16b60326a3510f2 | 3,630,212 |
def guess_email_class(email: EmailMessage) -> str :
"""
:param email:
:return:
"""
for part in email.walk():
if part.get_content_type() == 'text/calendar':
return 'IPM.Appointment'
else:
return 'IPM.Note' | 5b26ac875e43d9b613215b26b8377187c99b85eb | 3,630,213 |
import os
def slice_generator(image_file, out_dir, new_size=None):
"""
Image generator.
creates slices of a given size for an image and saves them
to disk, to use for c3d.
image_filename: Filename of the image.
out_dir: output directory.
Returns the paths of each of the saved slices.
... | 09e66a6180c4ca64d3f801542d42f42331693d67 | 3,630,214 |
from pathlib import Path
def synctree(a, b):
"""
Copy new and updated files from a to b.
:param a: The seed directory
:param b: The destination directory
:return: `True` if files were copied, `False` otherwise
"""
def sync(cmp):
for name in cmp.left_only + cmp.diff_files:
... | 3832d7136cca3c33c113d4c81c649d83621aea16 | 3,630,215 |
import types
def fqn(o):
"""Returns the fully qualified class name of an object or a class
:param o: object or class
:return: class name
"""
parts = []
if isinstance(o, (str, bytes)):
return o
if not hasattr(o, '__module__'):
raise ValueError('Invalid argument `%s`' % o)
... | bb95cc55c8afb8785dd4daf1cd6d75997794a181 | 3,630,216 |
def get_lane_boundaries_surface(
world: carla.World, # pylint: disable=no-member
pixels_per_meter: int = 5,
scale: float = 1.0,
margin: int = 150,
) -> pygame.Surface:
"""Generates a `PyGame` surface of a CARLA town lane boundaries.
Heavily inspired by the official CARLA `no_rendering_mode.py` exa... | 3f80bff30bb652d4173feb5a62434a0e4be0ffdd | 3,630,217 |
def batch_dq_prod_vector(dqs, V):
"""Apply transforms represented by a dual quaternions to vectors.
Parameters
----------
dqs : array-like, shape (..., 8)
Unit dual quaternions
V : array-like, shape (..., 3)
3d vectors
Returns
-------
W : array, shape (3,)
3d v... | 1db9b9d9c2e2cbc9e11c903dfc2fa6a1bd9da594 | 3,630,218 |
import re
def uniescape(text: str) -> str:
"""
Escapes all non-ASCII printable characters with JavaScript Unicode escapes.
"""
def escape(match):
character = match.group(0)
assert len(character) == 1
code_point = ord(character)
assert code_point <= 0xFFFF
retur... | 0ce57acb1dc8dc88ad366844f323e6527eb655af | 3,630,219 |
from typing import Dict
from typing import List
from typing import Union
def aggregate_collate_fn(insts) -> Dict[str, List[List[Union[int, str, List[int]]]]]:
"""aggregate the instance to the max seq length in batch
Args:
insts: list of sample
Returns:
"""
subtree_spans, children_spans, s... | 5b3cbb71876b9814a9664f0d99396308a218c3aa | 3,630,220 |
def encode_extended(values, value_range):
"""Encode data using Google's "extended" encoding for the most granularity."""
return "".join(num2chars(v, value_range) for v in values) | b5d980f26b77cb9f0ffedcfb9b5cdb7a29afa8ff | 3,630,221 |
import argparse
import sys
import json
def main(argv=None):
"""
The main function of this script. Converts JSON to XML based on the arguments provided.
:param argv: List[str] Arguments to parse (default sys.argv)
:return: int
"""
#Parse arguments
parser = argparse.ArgumentParser(description='Converts JSON to ... | 38fc88929bd1b45d80d7f0520f2ac4f3a978bf0e | 3,630,222 |
import string
def part_b(puzzle_input, workers=5, offset=60):
"""
Calculate the answer for part_b.
Args:
puzzle_input (list): Formatted as the provided input from the website.
Returns:
string: The answer for part_b.
"""
deps = parse_deps(puzzle_input)
finished = []
qu... | b9484aa9c66d425798fa806b84e6bd7c31a4eb1f | 3,630,223 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up a National Weather Service entry."""
latitude = entry.data[CONF_LATITUDE]
longitude = entry.data[CONF_LONGITUDE]
api_key = entry.data[CONF_API_KEY]
station = entry.data[CONF_STATION]
client_session = async_get_clien... | 2a7acda783a3ee29289cec651f530281af52e199 | 3,630,224 |
def cov_hvus(data1,data2,label):
"""
Estimate the covariance of hvus between two classifiers/features based on graph theory
Parameters
----------
data1 : array-like of shape (n_samples,)
samples' value from classifier1
data2 : array-like of shape (n_samples,)
samples' value ... | 4ab273d7a94f85a55fcfe4c67255e8714f04da5f | 3,630,225 |
import re
def clean(s):
"""
remove symbols and lowercase
"""
regex = re.compile('\W+')
s = regex.sub(' ', s).strip()
return s.lower() | f0f71dacac0d792c10480f9eec605bc85bf58be0 | 3,630,226 |
def trueifset(xeval, typematch=False):
"""return True if @xeval is set, otherwise False"""
if typematch:
if not (xeval is False or xeval is None): return True
else: return False
else:
if xeval: return True
else: return False | ff9ab55f869edc0fc784d9a34f55fe46652f22b5 | 3,630,227 |
def _generate_dash_manifest(encoding, output, output_path):
# type: (Encoding, Output, str) -> DashManifestDefault
"""
Creates a DASH default manifest that automatically includes all representations configured in
the encoding.
<p>API endpoint:
https://bitmovin.com/docs/encoding/api-reference/se... | 4a2563b48ac3977b16901f735aaf719bdffe97f9 | 3,630,228 |
def shipping():
"""The webapp's page for viewing the shipping status of work orders.
This allows the employee to review existing work orders and see if they are ready to ship or not."""
# if the current user is not authenticated, redirect the user to the logged out index page
if not current_user.is_authenticated:
... | 25c6a9bb71744b63a102751dc1c675137008a514 | 3,630,229 |
def get_file_content(file: str) -> str:
"""
Get file content.
"""
try:
with open(file, 'r') as f:
content = f.read()
return content
except IOError as e:
print(e)
print('Exiting...')
exit(1) | c10407d73ba2cd2d84eb99c0f131d3895ede460d | 3,630,230 |
import types
def simplify_name_to_string(input_name):
"""
``simplify_name_to_string`` simplifies a templated C++ name with default arguments and returns a string
:param input_name: String or qualified name to be simplified
:type input_name: Union[str, QualifiedName]
:return: simplified name (or original name if... | 218b4289612849d0cc4b24b541882ba7bb9240b9 | 3,630,231 |
def _normalize_index(index, axis_size):
"""Normalizes an index value in the range [-N, N) to the range [0, N)."""
return lax.select(
lax.lt(index, _constant_like(index, 0)),
lax.add(index, _constant_like(index, axis_size)),
index) | e3175d169b2179493125b58ee49b79bb39843e51 | 3,630,232 |
def english_to_french(english_text):
#write the code here
"""class docstring
code to translate english text to french"""
translation = language_translator.translate(
text = english_text, model_id = "en-fr"
).get_result()
french_text = translation["translations"][0]["translation"]
... | a806a9b7d0beb267d02096dd21a4711aba506417 | 3,630,233 |
def get_sampling_distribution(samples):
"""
Get the sampling distribution of all samples of a population.
Parameter: a list of lists containing all possibile samples of a distribution.
Returns: sampling distribution, which is the list of means of all samples given.
"""
sampling_distribution = ... | 2f5bdfe89ed6886c4d858846c6d40b6aa04fc483 | 3,630,234 |
import torch
def compute_loss3D(embeddings, labels, device, temperature=0.7):
"""
embeddings: a B, C, D, H, W array
lables: B, 1 array
device: torch.device instance, either cuda or cpu
"""
# all of them are 3d embeddings, I again need to separate
# them and then do the dot prod... | 53cc363fe8fc9266f5143d4641e63e1f8491f0d1 | 3,630,235 |
def grad_polynomial_bases(X, N):
"""
Compute the gradients of the monomial bases.
Parameters
----------
X : ndarray
contains the points to evaluate the monomials
N : int
the maximum degree of the monomial basis
Returns
-------
dB : ndarray
contains the grad... | 5d2ae8fdbfae187b05ea1b3186e307468cabbb04 | 3,630,236 |
def hor1f(x, z, offset=1):
"""
BROKEN: Haven't quite figured this one out
Calculate the horizon pixel for all x,z
This mimics the algorthim from Dozier 1981 and the
hor1f.c from IPW
Works backwards from the end but looks forwards for
the horizon
xrange stops one index before [stop]
... | 21612c6b9b4243d57ef91c649b593e92babdde90 | 3,630,237 |
def make_multi_class_binomial_deviance(n_class, alpha=2., beta=0.5, cy=25., sim='cosine'):
""" Builder for the Binomial Deviance loss function. Ref:
https://papers.nips.cc/paper/6464-learning-deep-embeddings-with-histogram-loss.pdf
Note that the batch must be built using M exclusive classes and N images pe... | 5a5cae1f6e80060d1c81acc7e7811963f9e11771 | 3,630,238 |
import json
from collections import OrderedDict
def json_to_odict(json_series):
"""
Load a JSON series into OrderedDict
"""
odict = json.loads(js, object_pairs_hook=OrderedDict)
return odict | 20c377fef580660b583f87e2c447ed978821113d | 3,630,239 |
import typing
def sectors_performance(
apikey: str, limit: int = DEFAULT_LIMIT
) -> typing.List[typing.Dict]:
"""
Query FMP /sectors_performance/ API
:param apikey: Your API key.
:param limit: Number of rows to return
:return: A list of dictionaries.
"""
path = f"sectors-performance"
... | 03d8f1ee35f68d93c0c1536aea0d0e9d232f1782 | 3,630,240 |
from datetime import datetime
def _prepTrends(rawReport, startDt, numFiles, countMonth, granularity):
"""
Helper function which reformats data into list of lists with correct data
types. If anything is empty or has incorrect data, then an empty list is
returned.
"""
#load each rawReport into separate list
repo... | 2f416f04fc930d9729d5ef54a901963e33021fba | 3,630,241 |
def drift(ips, tau):
"""Drift operator.
"""
if ips.include_pn_corrections:
return drift_pn(ips, tau)
return drift_n(ips, tau) | 30ea7822ba8cce35e86b82deb3f92154f15d7603 | 3,630,242 |
def F1Score4(pred, groundtruth):
"""
# N A O P
# Normal AF Other Noisy Total
#Normal Nn Na No Np ∑N
# AF An Aa Ao Ap ∑A
#Other On Oa Oo Op ∑O
#Noisy Pn Pa Po Pp ∑P
#Total ∑n ∑a ∑o ∑p
"""
pred_len = len(pred)
re_table =np.zeros([4,4])
for i in range(pred_... | b3019f13939de99bda714e99894947d2de636390 | 3,630,243 |
from datetime import datetime
import tqdm
from functools import cmp_to_key
def get_point_pixel_values(
coords,
start_date: datetime = date.today() - timedelta(days=365),
end_date: datetime = date.today(),
ascending: bool = True,
orbit_number: object = None,
scale: int = 20,
n_jobs: int = 1... | e86fd02e58d23b74f64608071abf8826399c3cd3 | 3,630,244 |
from typing import Union
from typing import Optional
from typing import Tuple
from typing import List
def any(x: Union[ivy.Array, ivy.NativeArray],
axis: Optional[Union[int, Tuple[int], List[int]]] = None,
keepdims: bool = False)\
-> ivy.Array:
"""
Tests whether any input array element... | 2712ba15f571ecbe00e66a6ddb16695017ee6ccf | 3,630,245 |
def _filter_in_wet_days(da: DataArray, dry_day_value: float):
"""
Turns non wet days to NaN.
dry_day_value may be Nan or 0.
"""
precip = convert_units_to(da, "mm/d")
return precip.where(precip > 1, dry_day_value) | 739a210d772a6d124fceb50258d46012cb5b3060 | 3,630,246 |
def codemirror_field_css_assets(*args):
"""
Tag to render CodeMirror CSS assets needed for all given fields.
Example:
::
{% load djangocodemirror_tags %}
{% codemirror_field_css_assets form.myfield1 form.myfield2 %}
"""
manifesto = CodemirrorAssetTagRender()
manifesto.r... | bd127a3974ba9a12568359ed0dc0af99e31aa38f | 3,630,247 |
import json
def request(method, url, **kwargs):
"""
Wrapper around :func:`treq.request` with some added arguments
and validation.
:param str method:
The HTTP method to use when making the request.
:param str url:
The url this request will be made to.
:type data: str, list, t... | e0b70390ce4168f043b6394a4155f3d439945368 | 3,630,248 |
def for_stmt(target, iter_, body, orelse, local_writes):
"""Functional form of a for statement."""
if tf.is_tensor(iter_):
local_writes = [
var for var in local_writes if not py_defaults.is_undefined(var.val)
]
n = _tf_len(iter_)
def for_test(i, *_):
return i < n
def for_body(i... | f47a11ebee4143b0c0f92e8c7fb814ecfd79e91f | 3,630,249 |
def is_running():
"""Return if the main global loop is running."""
global __loop__
return __loop__ is not None and __loop__.is_running() | 6698c224109d8de3f95ba894a18bc420ff7e5734 | 3,630,250 |
from functools import reduce
def build_web_site(resources, site_class=None):
"""Build a Twisted web Site instance for a specified dictionary of
resources.
:param dict resources:
Dictionary of path -> resource class mappings to create the site from.
:type site_class: Sub-class of Twisted's Sit... | 1087fb6550a60e09d515ff12494ba8b7a344a489 | 3,630,251 |
def CheckExpectedOutput(output, expected):
"""Assert that expected content appears in the output.
Arguments:
output: Output from a tool to be searched for matches
expected: An iterable which contains regular expressions, a match for
each of which must appear in 'output'
Returns the nu... | 88023bb5c2884213df192491487c6d8bc909c52d | 3,630,252 |
from functools import reduce
def vector_sum(vectors):
""" sums all corresponding elements """
return reduce(vector_add, vectors) | 54fe814c07c991099b300f56a9995934069d0e5b | 3,630,253 |
async def get_all_consent_documents(environment, access_token, deployment_id):
"""
Function: [get_all_consent_documents]
:param environment: The CARP [environment].
:param access_token: The [access_token].
:param deployment_id: The [deployment_id].
:return: Lists all consents documents by [deplo... | b699a40cd11229555be8cfb07cfdf063f0e895a0 | 3,630,254 |
def convert_to_time_series(dataset, sequence_len, input_dim, output_dim):
"""
Function to convert a sequential `dataset` into time series data
:param dataset: 1-D List containing sequential data
:param sequence_len: Number of time steps in each instance
:param input_dim: Dimension of input at each t... | 87b33ee5e8205229d6804225dd5f4e943b019773 | 3,630,255 |
from typing import Tuple
def get_ip_reputation_score(classification: str) -> Tuple[int, str]:
"""Get DBot score and human readable of score.
:type classification: ``str``
:param classification: classification of ip provided from GreyNoise.
:return: tuple of dbot score and it's readable form.
:rt... | a71ec03b176425040047695e73a8046742878137 | 3,630,256 |
def _cv_input_text(cfg):
"""Configure validation helper for input box (voluptuous)."""
minimum = cfg.get(CONF_MIN)
maximum = cfg.get(CONF_MAX)
if minimum > maximum:
raise vol.Invalid('Max len ({}) is not greater than min len ({})'
.format(minimum, maximum))
state = ... | 53a6a9025e8f10857e0a558e908acf10fa0eb473 | 3,630,257 |
def map_values(e):
"""
:rtype: Column
"""
return col(MapValues(ensure_column(e))) | 6008b81c07c3d7a283b30ba7de493b27a32541eb | 3,630,258 |
from typing import List
from typing import Dict
from typing import Tuple
from typing import Set
def find_connected_pattern(variables: List[str], triples: List[Dict[str, str]]) -> Tuple[Dict[str, str],int, Set[str]]:
"""Find the first pattern in a set of triples pattern connected to a set of variables"""
pos =... | 30e2fc143b0252faad597320eb5a22a4b5ee75e9 | 3,630,259 |
import hmac
def make_secure_val(val):
"""
Creates secure value using secret.
"""
return '%s|%s' % (val, hmac.new(secret, val).hexdigest()) | ce8f1af92e91c99a7cc7dcb6c536dd56403738cb | 3,630,260 |
from .plotting import make_rand_cmap
import os
def make_segm_from_catalog(catalog_star,
bounds, estimate_radius,
mag_name='rmag', mag_limit=22,
obj_name='', band='G',
ext_cat=None, draw=True,
... | 11270fedf8cb376c3180e3c3ad319137fc640254 | 3,630,261 |
import itertools
def get_forced_photometry_mp(table, ra_col_name, dec_col_name, surveys,
bands, apertures, fovs, image_folder_path, n_jobs=5,
auto_download=True,
verbosity=0):
"""Calculate forced photometry in multiprocessing mode.
... | b633c5cb07a555541ae351c8fd0de682f1b506fb | 3,630,262 |
def Any(x):
"""The Any type; can also be used to cast a value to type Any."""
return x | 88abecb27317e5bf16c5bd27c306ce800c7ac760 | 3,630,263 |
def resource_name_for_resource_type(resource_type, row):
"""Return the resource name for the resource type.
Each returned row contains all possible changed fields. This function
returns the resource name of the changed field based on the
resource type. The changed field's parent is also populated but is not us... | 500bc32be1765f1e516f4f7cd386b24c3c4f373f | 3,630,264 |
from re import M
import pprint
def compute_performance_metrics_binary(model, x, y, metric_names):
"""
Given a model (TensorFlow) and (x, y).
Compute accuracy, loss, True Positive, False Negative, False Positive, True Negative, Recall, Precision,
f1 score, Average Precision Recal... | 7f8912b845b1c6e4e8083458d7e79d1eba624c1f | 3,630,265 |
import re
def to_yw7(text):
"""Convert html tags to yWriter 6/7 raw markup.
Return a yw6/7 markup string.
"""
# Clean up polluted HTML code.
text = re.sub('</*font.*?>', '', text)
text = re.sub('</*span.*?>', '', text)
text = re.sub('</*FONT.*?>', '', text)
text = re.sub('</*SPAN.*?... | 59b9b961f7a94d23e2829b9d940f63c32207600b | 3,630,266 |
def decode_labels(mask, num_images=1, num_classes=21):
"""Decode batch of segmentation masks.
Args:
mask: result of inference after taking argmax.
num_images: number of images to decode from the batch.
num_classes: number of classes to predict (including background).
Returns:
A batch with num_im... | 967da7e34e993bf2eb4a2140898309811de79330 | 3,630,267 |
def get_base_url(hostname):
"""
Constructs the GitHub API url with the given hostname.
:param str hostname: Hostname to construct the API endpoint url.
:returns: None
:raises: None
"""
if hostname and hostname.startswith('http'):
return hostname
else:
return "https://{ho... | b0a13d3054fd48a9970c639ea8730d24a67a09ed | 3,630,268 |
import array
def gauss_sqrt_cov_ft(karr: array, width: float = 1.0) -> array:
"""sqrt of FFT of KD Gaussian covariance matrix
Square root of Fourier transform of a covariance matrix that is a Gaussian
function of difference in position
Returns
-------
karr : (L1,L2,...,LK/2+1,1,K)
Ar... | 5b16b19847706b9985855e1d32df3abab95685f3 | 3,630,269 |
def get_qt_lineedit_suffix(gb, suffix):
"""Gets the line edit associated with a tab and suffix.
Args:
gb (QtWidgets.QGroupBox): Group box for the tab.
suffix (str): Text appended to UI element search query.
Returns:
QtWidgets.QLineEdit: LineEdit matching val_{tag}_{suffix}.
"""... | 01443bf3d96a89037fdf9276d8e4bbb57f4e2175 | 3,630,270 |
import logging
def fit_statmech_pseudo_rotors(Tlist, Cvlist, n_vib, n_rot, molecule=None):
"""
Fit `n_vib` harmonic oscillator and `n_rot` hindered internal rotor modes to
the provided dimensionless heat capacities `Cvlist` at temperatures `Tlist`
in K. This method assumes that there are enough heat c... | cd3a45c4964c2ce00ae1fdddded4a75020fb0beb | 3,630,271 |
import logging
def response_to_invalid_request(diameter_request,
origin_host,
origin_realm):
"""
Method used to respond to invalid Diameter request.
We define an invalid Diameter request by comparing its command code
with the ones that w... | da18bd3120e55c7a0b50940e57a83edb9fab4b72 | 3,630,272 |
def lsi_model(tmp_corpus, temp_dict):
""" creates an latent semantic indexing model from
a corpus of words and a dictionary using gensim
Args:
tmp_corpus (list): a list of words from dict
temp_dict (Dictionary): a gensim Dictionary
Returns:
a list of word vectors that comprise ... | a39fa884c9eb4fe08941f1ae1d51b7a6a8403d7f | 3,630,273 |
def kmeanssample(X, k, nsample=0, **kwargs):
""" 2-pass kmeans, fast for large N:
1) kmeans a random sample of nsample ~ sqrt(N) from X
2) full kmeans, starting from those centres
"""
# merge w kmeans ? mttiw
# v large N: sample N^1/2, N^1/2 of that
# seed like sklearn ?
N, dim =... | 3853349e42b2ce29384d202a381ce26a05f49a53 | 3,630,274 |
def get_real_resolution():
"""获取真实的分辨率"""
hDC = win32gui.GetDC(0)
# 横向分辨率
w = win32print.GetDeviceCaps(hDC, win32con.DESKTOPHORZRES)
# 纵向分辨率
h = win32print.GetDeviceCaps(hDC, win32con.DESKTOPVERTRES)
return w, h | d8eac10bc449a3e1e44f983e9b2cf76494ef56e1 | 3,630,275 |
def op_acot(x):
"""Returns the inverse cotangent of this mathematical object."""
return op_inv(op_atan(x)) | 604b989524081078ab7a40e09c36b20ad6c52be3 | 3,630,276 |
import struct
import fcntl
import termios
def terminal_size():
"""
Get terminal size
Will return width and height
"""
if os_windows:
w = 80
h = 25
else:
h, w, hp, wp = struct.unpack(
'HHHH', fcntl.ioctl(0, termios.TIOCGWINSZ,
... | a88d7f869fc0de5a310d3390091a62c2dd44c1ac | 3,630,277 |
import types
from typing import Dict
import numpy
from typing import List
def sdc_pandas_series_groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,
group_keys=True, squeeze=False, observed=False):
"""
Intel Scalable Dataframe Compiler User Guide
*************... | fb33b16b35850839616ba8d9936f1fd19606a1d2 | 3,630,278 |
def get_most_popular():
"""
Helper which retrieves most popular urls based on `redirects`(desc) and
`created_at`(desc)
"""
return Url.objects.order_by('-redirects', '-created_at') | 660714f455e6e425698e4e1a86635b0d12a290f6 | 3,630,279 |
def eval_genomes(genomes, substrate, vd_environment, generation):
"""
The function to evaluate fitness of the entire population against test
visual descriminator environment using the provided substrate
configuration of the descriminatorANN
Arguments:
genomes: The list of genomes in... | 7d03f265820a5ea148c8df81262927a1b6acb578 | 3,630,280 |
def cosine_similarities(a, b, transform):
"""
returns list of cosine similarities between lists of vectors
a and b. The z_score transformation is applied if transform == True
"""
a = numpy.stack(a)
b = numpy.stack(b)
#transform if requested
if transform:
print "transforming"
... | 4164dcce80ba84ceb8b468b4db2d72b2ca8a10f7 | 3,630,281 |
def element_damage_nohitbox(raw_element, sharpness):
"""
Calculate elemental damage to a monster part with the given elemental
attack, the given sharpness, and the given monster elemental weakness.
Note that this is independent of the motion value of the attack.
"""
return (raw_element * Sharpne... | 10d527e1740172e2bba4f4fe9170dfe8f4218a98 | 3,630,282 |
def getTabData(header, index):
"""Get the table data at index from above tables generator.
Expects the header string and the index of the table."""
tabStart = header.index('{', index) + 1 #start of the table, first letter after {.
tabEnd = header.index('}', tabStart) #last of the array.
return header[tabStart:tabE... | 738e6f1532129043e67e1e639a66d12e43d1e9a6 | 3,630,283 |
def get_default_input_id():
"""gets default input device number
pygame.midi.get_default_input_id(): return default_id
Return the default device ID or -1 if there are no devices.
The result can be passed to the Input()/Ouput() class.
On the PC, the user can specify a default device by
setting ... | 482a02501343d365ea05bda825bc2d8560a687b3 | 3,630,284 |
from contextlib import contextmanager
from wurlitzer import sys_pipes
def notebook_system_output():
"""Capture system-level stdout/stderr within a Jupyter Notebook shell.
Get a context manager that attempts to use `wurlitzer
<https://github.com/minrk/wurlitzer>`__ to capture system-level
stdout/stder... | 4085d83003a1b9e31ee48867d8261732508e1195 | 3,630,285 |
def dict_merged(d, _filter=None, **kw):
"""Update dictionary d with the items passed as kw if the value passes _filter."""
def f(s):
if _filter:
return _filter(s)
return s is not None
d = d or {}
for k, v in kw.items():
if f(v):
d[k] = v
return d | 03df2c26975f114db1b6f258a4324d0d12109126 | 3,630,286 |
def check_latest_deploy(package, region, requirements_hash):
"""
Args:
package: Name of package to query
region: region to query for
requirements_hash: hash of requirements.txt file
returns:
Boolean: False if requirements hash matches latest deployhed version (doesn't need de... | 0f74fc73e7cb01d9c0f2e466246feba44021cb3f | 3,630,287 |
def docker_images(docker_url, query):
"""Looking for local images.
:param docker_url: Docker base url
:param query: image name lookup
:type docker_url: str
:type query: str
:returns: all matching images
:rtype: set
"""
cli = Client(base_url=docker_url)
results = set()
images... | 1e9dc9f9048985503ea53f90fbb1290ba3d7be38 | 3,630,288 |
from typing import List
from typing import Dict
from typing import Optional
import logging
def _generate_pathfinding_environment(
object_bounds_list: List[List[Dict[str, float]]],
source: Dict[str, float] = None,
target: Dict[str, float] = None,
save_path_plot_with_name: str = None
) -> Optional[Envir... | ee35dd84dbdd88e65f50a38ed5dbe4b9476e55b1 | 3,630,289 |
def keyword_confirm(request, name=None):
"""."""
q_objects = Q()
q_objects.add(Q(target_species__icontains=name), Q.OR)
confirm_proteins = Association.objects.filter(q_objects)
confirm_proteins = _sorted_nicely(confirm_proteins, sort_key="name")
return render(
request,
"associat... | e1d97020e2267ff96c2f5d2c37315254621aaae4 | 3,630,290 |
from typing import Union
from typing import Optional
from typing import Callable
def day_dropdown_widget(
data: Union["LogData", pd.DataFrame], callback: Optional[Callable] = None
) -> "ipywidgets.Dropdown":
"""Create dropdown widget to filter log data by a specific day.
Parameters
----------
dat... | 87f0e7d527d74de0ccec98c42ac2127fcf1143b3 | 3,630,291 |
def is_node_valid(node: dict) -> bool:
"""
Returns True if the provided node contains a directive and token.
"""
result = False
if node:
if DIR in node and TOK in node:
result = True
return result | b99329e3a76705172f88fe62ecc6aee640aa1736 | 3,630,292 |
import os
def is_crawler(client_ip):
"""
:return: crawler or not
"""
data_dir = os.path.join(os.path.dirname(__file__), 'data')
udger = Udger(data_dir)
return True if udger.parse_ip(client_ip)['ip_classification_code'] == 'crawler' else False | 240d5681c26ceb5bdcd39a08ee1be96d9c07df49 | 3,630,293 |
import pytz
def pytz_version():
"""Return the version of pytz as a tuple."""
year, month = pytz.__version__.split('.')
return int(year), int(month) | 0d28f0dcceb629168a997f01a5d07b89231e0894 | 3,630,294 |
from typing import List
from typing import Any
from typing import Tuple
def fixup_partition_table(partitions: List[Any], sector_size=512) -> Tuple[List[Any], int]:
"""
Return fixed partition table so it can be really written to disk.
Also return total size of partition.
"""
start_offset = 0
if... | ac3023ac021c41d95a4274b0ec82449c9d70d1ad | 3,630,295 |
def topological_sort(self):
"""
Returns:
List(int): Topological sort of vertices of a graph.
"""
topo_order = self.depth_first_search()[1]
position = [-1] * len(self.v)
for i, v in enumerate(topo_order):
position[v] = i
for u, v in self.e:
if positi... | ccd21c7486c3b32da1203015e77c24530d1f5e56 | 3,630,296 |
def construct_start_stop_intervals(intron_intervals, d):
"""Splits a iterable of intervals into two parallel tuples of 2d bp intervals representing their start and stop"""
left_intervals = []
right_intervals = []
for i in intron_intervals:
left_intervals.append(ChromosomeInterval(i.chromosome, i... | ee46c343d0a465a3b67b9f4990ebcc9d44cef669 | 3,630,297 |
def region_growing(image,coordinate,number):
"""Give coordinate and size,return a region."""
# tmp_image store marks and rg_image store new image after region grow
nt = number
tmp_image = np.zeros_like(image)
rg_image = np.zeros_like(image)
image_shape = image.shape
x = coordinate[0]
y ... | ee495848e6d9afd4f29bc97663f8804092b51559 | 3,630,298 |
def mock_subprocess(case_tuple):
"""We perform several subprocess.check_output calls, but we want to only mock
one of them at a time. This function helps us do that.
:type case_tuple: tuple of SubprocessMock
:param case_tuple: See docstring for SubprocessMock
"""
def fn(inputs, **kwargs):
... | 0c98028464633c01808108145a462c64ce7015bd | 3,630,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.