content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import csv
def buildUsageAndRatingByCityJs():
"""Builds several strings defining variables used for visualization.
Reads a CSV file containing the usage-by-city data and uses it
to build a JavaScript string defining a DataTable containing the data.
Returns:
{string} of the form <var_name>=<json>, where ... | 4869a64c8ef91fd2ce3940ce5d4ab28ed8278092 | 3,621,900 |
import argparse
def add_subparser(parser):
"""Add the subparser that needs to be used for this command"""
test_db_parser = parser.add_parser(
"test", help=SHORT_DESCRIPTION, description=SHORT_DESCRIPTION
)
test_db_parser.add_argument(
"-c",
"--config",
type=argparse.Fi... | 1ab6cf13e29879ca18b0d0ff174d7950adc2095d | 3,621,901 |
def _get_Abc(c, c0=0, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None,
x0=None, undo=[]):
"""
Given a linear programming problem of the form:
Minimize::
c @ x
Subject to::
A_ub @ x <= b_ub
A_eq @ x == b_eq
lb <= x <= ub
where ``lb = 0`` and ... | c177b919626f13d2d0b5cddeecb2c7678af23d6d | 3,621,902 |
def obj2np(obj):
"""Wraps an object into an np.array."""
ar = np.zeros((1,), dtype=np.object_)
ar[0] = obj
return ar | e35be1f05a0bb62a573592802c86ba823f727530 | 3,621,903 |
def masking(tokens, p = 0.1, mask='[MASK]'):
"""
Returns a new list by replacing elements in `tokens` by `mask` with probability `p`.
Args:
tokens (list): list of tokens or token ids.
p (float): probability to mask each element in `tokens`.
Returns:
A new list by replacing eleme... | da19ca09fb76557c58c96a77986276a98feaac86 | 3,621,904 |
import string
from typing import Counter
def singlebyte_xor_cipher(hex):
"""
Takes a hex string and finds the best xor key
and returns (ResultString, Confidence)
"""
common = ['n', 'i', 'o', 't', 'e', ' ']
ret = None
score = 0
key=0
if not isinstance(hex, bytearray):
hex = hex.decode('hex')
hex = bytearr... | 1611372d05bfa7753d77cc389e58420a2efb0c99 | 3,621,905 |
def absolute_url(context, route, *args, **kwargs):
"""The absolute url for a request and a route"""
return context.request.build_absolute_uri(reverse(route, args=args, kwargs=kwargs)) | cfaff5366b115bdc318168669efb753c4164ca53 | 3,621,906 |
def get_Kernels(test_vectors,img_width):
"""
Creates 3x3 kernel which is operated by the conv2d
Parameters
----------
test_vectors : numpy array
Generated test vectors 3x1.
img_width : integer
with of test matrix.
Returns
-------
Kernel : numpy array
Kernel t... | f9da65a87fd497ec3f4ef851fa7acb1ad8101405 | 3,621,907 |
def get_solc_version() -> Version:
"""
Get the version of the active `solc` binary.
Returns
-------
Version
solc version
"""
solc_binary = get_executable()
return wrapper._get_solc_version(solc_binary) | 680d72cbeb2ceef5453722afde0dc238dbba3376 | 3,621,908 |
def epoch2dt64(ep_time):
"""
Convert from epoch time (seconds since 1/1/1970 00:00:00) to
numpy.datetime64 array
Parameters
----------
ep_time : xarray.DataArray
Time coordinate data-array or single time element
Returns
-------
time : numpy.datetime64
The converted... | 9fe7734d36a44cf4c4d63823190e7bab83b8a2f5 | 3,621,909 |
import requests
import tarfile
def get_file_from_recipe_url(url):
"""Downloads file at url and returns tarball"""
r = requests.get(url, timeout=MULLED_SOCKET_TIMEOUT)
return tarfile.open(mode="r:bz2", fileobj=BytesIO(r.content)) | 1bda8c89560c1af0da8ff0a6d8eb3a70281ae66a | 3,621,910 |
def df_to_dict_single(df, curation_id=None):
"""
Purpose:
Convert a single entry pandas DataFrame into a dictionary and strip out
indexing information
:param df: pandas DataFrame with single entry (e.g., use df.loc[] to filter)
:param curation_id: integer providing the curation_id. Default: ... | 5a63e4cb56f8492adfae48cfd0c54f0fa6f6e104 | 3,621,911 |
def check_lines_valid(left_line, right_line, last_left_line=None, last_right_line=None):
"""
Checks validity of two given lines based on there geometry and optionally based on the deviation to the previous
detected lines. Also calculates the Mean Absolute error and the Mean Squared Error of the x values bet... | 5b9bb2369d6eccb4c2c1ba4288b5939f6c290574 | 3,621,912 |
import requests
def get_the_manifest(filter_string, api_url, manifest_file, max_files=None):
"""
This function takes a JSON filter string and uses it to download a manifest from GDC
"""
#
# 1) When putting the size and "return_type" : "manifest" args inside a POST document, the result comes
#... | 04fd2006b42bf5478c7c5b6ee6a87da128ce7131 | 3,621,913 |
def imageseg(Cont_Image):
"""imageseg('Image Name')
This program takes an image that has been pre-proccessed by an edge finding script as its sole input, segments it, and spits out a segmented image file and a pandas dataframe of individual particle positions.
This function works by creating a binary of a... | 7d786863cb668c7ba1d7cc643180fe33bcb1d318 | 3,621,914 |
import re
def getSisters(tree, t="g"):
"""Some nasty regex to get pairs of sister taxa
(only at terminal branches)"""
if t == "s":
l = re.findall("\(([1-9][0-9]|\d),([1-9][0-9]|\d)\)", tree)
else:
l = re.findall(
"\(([1-9][0-9]|\d):\d\.\d\d\d,([1-9][0-9]|\d):\d\.\d\d\d\)", ... | b5c3d26b406847bfd0858181bd3becb90fccb878 | 3,621,915 |
from typing import Optional
import warnings
def cluster_ensembles(
labels: np.ndarray,
nclass: Optional[int] = None,
solver: str = 'hbgf',
random_state: Optional[int] = None,
verbose: bool = False) -> np.ndarray:
"""Generate a single consensus clustering label by using base... | 2d996860fd05418f676b22d2fd795a1478266dc6 | 3,621,916 |
def ReadFromXMLStream (istream,
options = XML_STRICT_HDR | XML_LOAD_DROP_TOP_LEVEL | XML_LOAD_EVAL_CONTENT, # best option for invertibility
array_disposition = ARRAYDISPOSITION_AS_NUMERIC_WRAPPER,
prepend_char=XML_PREPEND_CHAR) :
"""Read XML from... | 757caaf44bb50a0391e8561b9c08209469f40aa0 | 3,621,917 |
def AngleRA (angle,unit=units.hourangle,raise_errors=False):
"""
An object which represents a right ascension angle
see `astropy.coordinates.RA` for more extensive documentation
The primary difference with astropy is that if the call to coordinates.RA
errors you have the option to ignore it an... | 01d2d5d7aedfb73f2189fba2bb7ef0d5076d49a2 | 3,621,918 |
def k_euclidean_neighbors(k, x1, x2, exclude_identity=False, identities=None):
""" For each row vector in x1 the k-nearest neighbors in x2.
:param k:
:param x1: M x Feat-dim
:param x2: N x Feat-dim
:param exclude_identity:
:param identities:
:return: M x k
"""
all_cross_pairwise_dist... | 746b6100eb0e6724178633093b02725a30022ec9 | 3,621,919 |
def get_train_feed_dict(model, reviews, win_reviews, batch_length, ote_labels, ts_labels, opn_labels, stm_lm_labels, lr, dropout_rate=1.0, train_flag=True):
"""Construct feed dictionary."""
feed_dict = dict()
feed_dict.update({model.reviews: reviews})
feed_dict.update({model.win_reviews: win_reviews})
... | d1abf917a6fc0db66102aebda61ce431a508988f | 3,621,920 |
def pass_through_third_point(marking_points, i, j, thresh):
"""See whether the line between two points pass through a third point."""
x_1 = marking_points[i][1][0]
y_1 = marking_points[i][1][1]
x_2 = marking_points[j][1][0]
y_2 = marking_points[j][1][1]
for point_idx, point in enumerate(marking_... | fbd38906e1266e8e4690e3c1eae99825009a6fab | 3,621,921 |
def increment_ctr(ctr):
"""
Increments one the counter.
Parameters
----------
ctr : string
Counter
Returns
-------
incremented_counter : string
Incremented Counter
"""
ctr_inc_int = int.from_bytes(bytes.fromhex(ctr), byteorder="big") + 1
return bytes.hex(c... | 0ef04e10283f02b6b7df46cf196493a3ad4a95c8 | 3,621,922 |
from typing import Any
def _instantiate(config: Any, *args: Any, **kwargs: Any) -> Any:
"""
:param config: An config object describing what to call and what params to use.
In addition to the parameters, the config must contain:
_target_ : target class or callable name (st... | 82527dbf49f5af837435ef0498a2c74785806594 | 3,621,923 |
import json
import torch
from re import T
import time
import math
def test_emb(
opt,
batch_size=16,
img_size=(1088, 608),
print_interval=40, ):
"""
:param opt:
:param batch_size:
:param img_size:
:param print_interval:
:return:
"""
data_cfg = opt.data_cf... | a2931c824ca69701611ab078770a46ca3167196a | 3,621,924 |
def is_supported(value, check_all=False, filters=None, iterate=True):
"""Return True if the value is supported, False otherwise"""
assert filters is not None
if not is_editable_type(value):
return False
elif not isinstance(value, filters):
return False
elif iterate:
if isinst... | b9f557b779121fa36f88e79318357d36849a3186 | 3,621,925 |
import os
def read(*paths):
"""read files"""
with open(os.path.join(*paths)) as filename:
return filename.read() | 5264d458658ed406b77f94fbe4e4eac0da2bbd4a | 3,621,926 |
def box_net(images,
level,
num_anchors,
num_filters,
is_training,
act_type,
repeats=4,
separable_conv=True,
survival_prob=None):
"""Box regression network."""
for i in range(repeats):
orig_images = images
... | 4541b6498fe821fc113b22b7b5d7142a2c24e4b1 | 3,621,927 |
def process_folder(repo_path, folder):
"""Find files and send for processing."""
folder_path = repo_path + folder + "\\"
vars()[folder] = dict()
json_queries = enum_json(folder_path)
vars()[folder].update(json_queries)
yaml_queries = enum_yaml(folder_path)
vars()[folder].update(yaml_queries... | d84434ed931c61ac94f1a53467c86da5e4d85ebc | 3,621,928 |
def img_to_array(img, data_format=None, dtype=None):
"""Converts a PIL Image instance to a Numpy array.
# Arguments
img: PIL Image instance.
data_format: Image data format, either "channels_first" or "channels_last".
If omitted (`None`), then `backend.image_data_format()` is used.
... | 0e297731b9f069995bf7faa350ea556e343274d8 | 3,621,929 |
import array
def C3(theta):
"""
Parameters
----------
theta : float
Angle 'theta' to be rotated around the X axis in rad.
Returns
-------
array
Cossine matix (3X3) of a 'theta' rotation around the Z axis.
"""
return array([[cos(theta), sin(theta), 0],
... | 6a0249a4e4ee3517809a22b7587a12ebc3522a56 | 3,621,930 |
import math
import random
def deal_hand(n):
"""
Returns a random hand containing n lowercase letters.
ceil(n/3) letters in the hand should be VOWELS (note,
ceil(n/3) means the smallest integer not less than n/3).
Hands are represented as dictionaries. The keys are
letters and the values are t... | 42606fe48be3100ac9aba4d8089163ef1b227600 | 3,621,931 |
import base64
import os
def gen_random(prefix):
"""
:param prefix: string to prefix random key with
:return: prefix plus 16 char alphanumeric (lowercase) random string
"""
# TODO move to utils
p_len = len(prefix)
assert p_len < 5, p_len
return prefix + '-' + base64.b32encode(os.urandom... | b6f50f9c0161e70e2fb3869998c1d978bf31cab4 | 3,621,932 |
def fit_jigsaw( x, y, grid_size, jigsaw_grid, tiles ):
"""
This function recursively tries to find the solution to the jigsaw puzzle.
*** Heavily inspired by reddit user: u/Fuzzy-Age6814 ***
TODO: Cleanup and improve code readability.
"""
if len( tiles ) == 0:
return jigsaw_grid
... | 04d8fea2928043e72f329e9ade902ede801ccae1 | 3,621,933 |
def open_url(filename, basepath=None):
"""Opens and reads a certain file from a web or remote location.
Opens and reads a certain file from a web or remote location. This
function utilizes the urllib2 module, which means that it is
restricted to the types of remote locations supported by urllib2.
... | 346bdbe1a508458dc216c95e582d2854bd9470e1 | 3,621,934 |
import argparse
def parse_options(description, example_usage, args):
"""Parse training options user can specify in command line.
Parameters
----------
description : str
the description of the script using this parser
example_usage : str
an example of the runner script being used
... | 9c92fb7f2283b73f8381cc1a66f66ad2ffa335ad | 3,621,935 |
def build_login():
""" Construye la ventana del inicio de sesion del usuario"""
layout =[[sg.T("Usuario", size=(8,1)), sg.InputText(key='-USER-')],
[sg.T("Contraseña", size=(8,1)), sg.InputText(key='-PASS-')],
[sg.Submit("LogIn", size=(15,1), pad=(0,15))],
[sg.T("No estas r... | 7b8a6acc2891d82b745323f7605856e63653d8f5 | 3,621,936 |
def get_tif_image_layer_count(file_name):
"""
:param file_name:
:return:
"""
with tifffile.TiffFile(file_name) as tif:
return len(tif.pages) | 945118d8849dbe3af8f4d7b8db1cd59d08ded774 | 3,621,937 |
def sonify_chromagram_with_signal(chroma_data, x, frame_rate, Fs, fading_msec=5, stereo=True):
"""Sonify the chroma features from a chromagram together with a corresponding signal
Parameters
----------
chroma_data : NumPy Array
A chromagram (e.g. gathered from a list of note events by list_to_c... | e05151412a8f0e8f7a23bcaaad37a9c283234a27 | 3,621,938 |
def ensure_binary(s, encoding='utf-8', errors='strict'):
"""Coerce **s** to six.binary_type.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> encoded to `bytes`
- `bytes` -> `bytes`
"""
if isinstance(s, text_type):
return s.encode(encoding, errors)
... | e4890c18b918bc0939a594eb0de19767a73e9898 | 3,621,939 |
import asyncio
def pytest_pyfunc_call(pyfuncitem):
"""Run coroutines in an event loop instead of a normal function call."""
if asyncio.iscoroutinefunction(pyfuncitem.function):
existing_loop = pyfuncitem.funcargs.get('loop', None)
with _passthrough_loop_context(existing_loop) as _loop:
... | a78518681acd2c9d3e8ed8f015573d4f42c135c2 | 3,621,940 |
import re
from datetime import datetime
def get_forecast_times(forecast_length, forecast_date=None,
forecast_time=None):
"""
Generate a list of python datetime objects specifying the desired forecast
times. This list will be created from input specifications if provided.
Otherwi... | 9fe3c8a58b4dabb1513419d9e082e3a6bbf023be | 3,621,941 |
from typing import Tuple
from typing import Union
from typing import Dict
import os
import logging
import time
def _extract_entities_and_relations(
config: dict
) -> Tuple[Union[Dict[str, list], list], Union[Dict[str, list], list]]:
"""
Read matched triples and create sets for all existing subjects, r... | 02423d2b6459db82bd8c38a804d6a78b2196562a | 3,621,942 |
import requests
def human_output():
"""Get request with human output params"""
response = requests.request("GET", BASE_URL, params=querystring)
return response | c15c07baaba60dc469aaf71443a3bad57b310180 | 3,621,943 |
def multiset(left, right, pairwise):
"""
Calculate the multiset distance between two vectors.
:arg array_like left, right: Vector.
:arg function pairwise: A pairwise distance function.
:return: The multiset distance between `left` and `right`.
:rtype: float
Note that `function` must be ve... | bbeb929963e92ebd371fcb52153763c1519b06d2 | 3,621,944 |
def json_response(func):
"""
A decorator thats takes a view response and turns it
into json. If a callback is added through GET or POST
the response is JSONP.
"""
def decorator(request, *args, **kwargs):
objects = func(request, *args, **kwargs)
if isinstance(objects, HttpResponse... | 1b49343e2f583bc9ba05092d4203177d7e23db3f | 3,621,945 |
def sample_CRP(N, alpha,d =0):
"""
sample from a Pitman-Yor process via the Chinese Restaraunt process, default
value of d=0 samples from a Dirichlet process
Parameters
-----------
N : scalar, integer
number of samples to return
alpha : scalar > -d
concentration parameter
... | be809c64c54b18c28554fadbfc351bc1d7f55d3f | 3,621,946 |
def iotest(fh, eof, blocksize=512, t=10):
"""io test"""
io_num = 0
start_ts = time.time()
while time.time() < start_ts+t:
io_num += 1
# freebsd8: need 512B sector alignment and at least one whole block left
pos = random.randint(0, eof - blocksize) & ~0x1ff
fh.seek(pos)
... | a205b9cf30d171df4b0c51c1a136c907b3db23af | 3,621,947 |
import os
def decentralized_registration(raster, win_num=1, reg_block_num=1, iter_num=4):
"""
Decentralized registration
Input: raster plot (poisson denoised)
Output: displacement estimate
"""
D, T = raster.shape
# get windows
window_list = []
if win_num == 1:
window_... | 725095959c0d1e456a301b68894ac3f63aa1ad1b | 3,621,948 |
def calc_info_frames(site_results_filtered, remove_multiple=None):
"""Return the info frames for the input."""
dat, conf_both, conf_any = get_pipeline_stats(site_results_filtered, log=False)
df_all = get_conf_dfs(conf_any)
if remove_multiple:
url_by_leak = df_all.groupby(["browser", "url"])[["me... | efcf4360febc44bb6d413b84bb2bb7f704eedb02 | 3,621,949 |
def _cleaner( vbo ):
"""Construct a mapped-array cleaner function to unmap vbo.target"""
def clean( ref ):
try:
_cleaners.pop( vbo )
except Exception as err:
pass
else:
vbo.implementation.glUnmapBuffer( vbo.target )
return clean | f478025165cc9ea1bfbc8f5980df8cf752b575ab | 3,621,950 |
def winrate_match(timebox, size, map_category):
""" Returns civs with winrate data based on matches. """
sql = QUERIES["win_rates_match"].format(*timebox, filters(map_category, size))
civs = CivDict(WinrateCivilization, size, map_category, "match")
bottom_civs = CivDict(BottomWinrateCivilization, size, ... | ef1924be54d462f362467cfb297220924d9f7dd6 | 3,621,951 |
def powerLaw(t, m, a, b):
"""
Model for the shower dominated part of a ratescan
"""
return m*np.power(t, a)+b | b0aaa838bc523d40322b621d4e4cae526cdaeb88 | 3,621,952 |
def update_unified_dataset(
session: Session, project: SchemaMappingProject
) -> Operation:
"""Apply changes to the unified dataset and wait for the operation to complete
Args:
project: Tamr Schema Mapping project
"""
unified_dataset = unified.from_project(session, project)
op = unified... | e9e628d9fb4e6da9331f7b0f2198db220123084c | 3,621,953 |
def make_v_spacer() -> QSpacerItem:
"""Make vertical QSpacerItem."""
widget = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Expanding)
return widget | 11216ae878058593e05a6542f3b14be91ef7c1e2 | 3,621,954 |
def combine_measurements(values):
"""Combines a np.array of measurements into one ufloat"""
return ufloat(mean(values), stdDevOfMean(values)) | 1e6df9fa79dbcab5d7476cc7f4b59b6c82c37584 | 3,621,955 |
def rename_guided(expr, resolution_guide):
"""
resolution_guide is a dictionary whose keys are expressions
and values are tuples (previous_pred, new_pred) that guide
the renaming.
"""
replacements = resolution_guide.get(expr, [])
for prev_pred, new_pred in replacements:
expr = expr.r... | d12a8ab0968e07b47f429ce8fbf7d3a6f8e1c02b | 3,621,956 |
def get_base_required_fields_uframe():
""" Get required fields for base asset in uframe.
"""
base_required_fields = [
'assetId',
'assetType',
'@class',
'dataSource'
'de... | 233e9c8985b82335d32765daab3cc29ae5959354 | 3,621,957 |
def get_comparative_forms(tokens):
"""Identify, color and count comparatives and superlatives"""
# find comp. forms of adjectives
comparatives = [t for t in tokens if t.full_pos in ['ADJA', 'ADJD'] and t.mo.comp == 'Comp']
superlatives = [t for t in tokens if t.full_pos in ['ADJA', 'ADJD'] and t.mo... | 020ce0f3a4959a2525698bfac4c45ac497e5cc67 | 3,621,958 |
from typing import Tuple
from typing import Dict
from typing import Any
def code_phase_difference(dset: "Dataset") -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""Calculate code-phase difference based on code and phase observations
Args:
dset: Dataset
Returns:
Tuple with code-phase diffe... | 36065d5aa5089ebaaf10292c02ce8290a029567d | 3,621,959 |
from typing import Optional
def fit_hypsometric_bins_poly(hypsometric_bins: pd.DataFrame, value_column: str = "value", degree: int = 3,
iterations: int = 1, count_threshold: Optional[int] = None) -> pd.Series:
"""
Fit a polynomial to the hypsometric bins.
:param hypsometric_... | d54d03cff1f65aa13a5b8678626e5a3000ad755a | 3,621,960 |
def get_nvidia_model(summary=True):
"""
Get the keras Model corresponding to the NVIDIA architecture described in:
Bojarski, Mariusz, et al. "End to end learning for self-driving cars."
The paper describes the network architecture but doesn't go into details for some aspects.
Input normalization, a... | 3195f7880f3deaa4f7b4f4919579252597feea84 | 3,621,961 |
def templateXcorr(datastream, template):
"""
Normalized cross correlation of short template trace against longer data stream
Based off matlab function coralTemplateXcorr.m by Justin Sweet
Args:
datastream: obspy trace of longer time period to search for template matches
template: obspy ... | bae76c7bd4cc7b40e533acb868a2a2c3215ce60a | 3,621,962 |
from datetime import datetime
def _load_dates():
"""Return a dict with the dates from the start_date to the current date.
Returns
-------
dates : dict
Dictionary containing dates and indicies.
"""
dates = {}
end_date = datetime.datetime.now()
curr_date = datetime.datetime(... | 8fe0bffefe46ef57d857ccd13caaec14db003fbf | 3,621,963 |
import functools
def _has_arg(fn, arg_name):
"""Returns True if `arg_name` might be a valid parameter for `fn`.
Specifically, this means that `fn` either has a parameter named
`arg_name`, or has a `**kwargs` parameter.
Args:
fn: The function to check.
arg_name: The name fo the parameter.
Returns:... | 6a26cd24818f753642e53d641a93dfe816f4022a | 3,621,964 |
def logout(request):
"""
Allows a non-SAML 2.0 URL to log out the user and
returns a standard logged-out page. (SalesForce and others use this method,
though it's technically not SAML 2.0).
"""
auth.logout(request)
tv = {}
return render('saml2idp/logged_out.html', tv) | ae27ed4caaeacb31bb003b683a485eff8963b7dd | 3,621,965 |
def auto_norm(data_set):
"""
Get the minimum values of each column
and place in min_vals. max_vals, too.
data_set.min(0) allows you to take the minimums
from the columns, not the rows.
Then calculate the range of possible
values seen in our data.
To get the normalized values,
you sub... | 7d3018f8053ebddb19d85ea1712bcec168fa1853 | 3,621,966 |
from typing import Callable
from typing import Any
def middleware(type: MiddlewareType) -> Callable[[CoroFunc[Any]], Middleware]:
"""
A decorator that returns a :class:`~subway.objects.Middleware` object.
Parameters
----------
type: :class:`~subway.objects.MiddlewareType`
The type of midd... | d004a1260c6ffeb1861e6b43b38ea08eb199cd3a | 3,621,967 |
import copy
def add_sorting_info_to_spike_info(original_spike_info, sorted_spike_info, tsne_filename=None, save_to_file=None):
"""
Adds the information in a spike_info dataframe that results after manual sorting (through a t-sne for example)
into the main spike_info. The original_spike_info is the large s... | 995bf4a4c1595c2b0b3b1c9ee2d882f0f872775f | 3,621,968 |
def XXX(self, s):
"""
:type s: str
:rtype: int
"""
left, right = 0, 0
while right < len(s):
right += 1
if len(set(s[left:right])) != right-left:
left += 1
return right-left | 26e08dc0b82985fef73b0b13669c74f3d9f9acef | 3,621,969 |
def people():
"""
View root page function that returns the index page and its data
"""
posts = Post.query.filter_by(category="People").all()
form = SubscriberForm()
if form.validate_on_submit():
email = form.email.data
new_subscriber=Subscriber(email=email)
new_subscribe... | 5891270d777f9a7e26f75535fd3fa59ae0884b53 | 3,621,970 |
def networkDrawSVG(request, networkKey):
"""
A view called when a user wants to draw the potential energy surface for
a given Network in SVG format.
"""
networkModel = get_object_or_404(Network, pk=networkKey)
networkModel.load()
# Run CanTherm! This may take some time...
networ... | 71976acd92f982fb01df4604d9ac812843832357 | 3,621,971 |
def transform_dict_to_count_df(item_dict):
"""Given a dictionary, where each element of the dictionary is a list,
return the data frame with columns all the elements that occur in any of
the lists (union of the lists) and rows the keys of the dictionary. Each
entry is the number of times that the item o... | 90a98d067d131e34239d147edd7dc57667bae030 | 3,621,972 |
import re
def parse_cmscan_tblout(filename):
"""
SNORA74 RF00090 URS00007E391B_9796 - cm 103 201 1 99 + 5' 2 0.49 0.0 97.9 3.2e-26 ! Small nucleolar RNA SNORA74
"""
data = defaultdict(list)
with open(filename, 'r') as f:
for line in ... | 11a07252136604dad87b52cd38981484032572ca | 3,621,973 |
def himmelblauConstraintOne(solution):
"""First restriction
Args:
solution (Solution): Candidate solution
Returns:
bool: True if it meets the constraint, False otherwise
"""
return (26 - (solution[0] - 5) ** 2 - solution[1] ** 2) >= 0 | f5878d2573559b78fee3b434d537a380abb5e2c8 | 3,621,974 |
from unittest.mock import patch
def patch_try_disk(return_value):
"""
Mocks the InsightsUploadConf.try_disk method so it returns the given parsed file contents.
"""
def decorator(old_function):
patcher = patch("insights.client.collection_rules.InsightsUploadConf.try_disk", return_value=return_... | 95ed09006e0a17bc58e5f320f1ae5dfb203300dd | 3,621,975 |
import re
def lyric_wikia_capitalize(string, noupper = True):
"""
lyrics.wikia.com page name rules:
- Uppercase All Words
- No all-uppercase WORDS allowed in song titles (but in artist names)
- Keep StrANgeLy cased words
See http://lyrics.wikia.com/wiki/LyricWiki:Page_... | b3d5aefff0715a7ff1e7298b9bdb492bd461c217 | 3,621,976 |
def create_ip_list(addr0, n_addrs):
"""Creates list of IP multicast subscription addresses.
Args:
addr0 (str): first IP address in the list.
n_addrs (int): number of consecutive IP addresses for subscription.
Returns:
addr_list (list): list of IP addresses for subscription.
"""... | e29b5c4b9f9ec0dc46916977e4a54bb77a9e74a6 | 3,621,977 |
def _classify_samples(indexfile, ssparser):
"""Given an ssparser object, go through all samples and decide sample types."""
sample_table = dict()
index_dict_tenX = parse_10X_indexes(indexfile['tenX'])
index_dict_smartseq = parse_smartseq_indexes(indexfile['smartseq'])
for sample in ssparser.data:
... | 954c3f5ceff6da6eddaa603ae310b83f849e3191 | 3,621,978 |
import logging
def debounce_failures(failed_builds, current_builds_successful, build_db):
"""Using trigger information in build_db, make sure we don't double-fire."""
@contextmanager
def save_build_failures(master_url, builder, buildnum, section_hash,
unsatisfied):
yield
build... | cde733e25d3fdad44af7eb552b8efb98646c0b13 | 3,621,979 |
def get_common_incident_details(static_attributes: dict, editable_attributes: dict, args) -> dict:
"""
Parses the needed incident details into context paths
:param static_attributes: The static attributes of the incident
:param editable_attributes: The editable attributes of the incident
:param args... | 6d88792e2139cd3c57a50d3d148fa01cad44c152 | 3,621,980 |
def win_prob_to_odds(prob, odds_style="a"):
"""
:param prob: Float. Implied winning % of a given wager
:param odds_style: Integer (American), Float(Decimal), String or Fraction Class (Fractional)
:return: The stated odds of a bet in a given style
"""
try:
if odds_style.lower() == "americ... | 49b13a28526c2d18df0d022d0ee51a71ab4b3447 | 3,621,981 |
def from_pil(pil_image):
"""
Construct Image from supplied PIL image object.
:param pil_image: PIL image object
:type pil_image: PIL.Image.Image
:raises RuntimeError: If the PIL Image provided is not in a recognized
mode.
:returns: New Image instance using the given image's pixels.
:r... | 64f74048ab98c9dd9dd933397a09b806b22af95f | 3,621,982 |
import random
def cxBlend(var1, var2, alpha=0.5):
"""Executes a blend crossover that modify in-place the input individuals.
The blend crossover expects :term:`sequence` individuals of floating point
numbers.
:param var1: The first variable participating in the crossover.
:param var2: The second v... | 11b7339f388ec228f855d1af87d86034cab7166a | 3,621,983 |
import sys
def CheckForBlacklistedCommand(args, blacklist, warn=True, die=False):
"""Blacklist certain subcommands, and warn the user.
Args:
args: the command line arguments, including the 0th argument which is
the program name.
blacklist: a map of blacklisted commands to the messages that should b... | 005285b3b544306baa58a732ef0a3a06f4daee97 | 3,621,984 |
import decimal
def decimal_to_num(obj):
"""
Helper function to convert all decimal valued inputs to the real representation of the value (int or float.)
This function is recursive.
Parameters:
obj (obj): An object to parse for decimals.
Returns:
obj: The passed in object with any transfo... | 395bb2c1c03d2c41e552b405df4bceb4172fe7aa | 3,621,985 |
import os
def find_rap_file_any_grid(
top_directory_name, init_time_unix_sec, lead_time_hours,
raise_error_if_missing=True):
"""Finds RAP (Rapid Refresh) file on any grid.
:param top_directory_name: See doc for `find_ruc_file_any_grid`.
:param init_time_unix_sec: Same.
:param lead_tim... | 1dff47cc5dbb46afcc8d96645afaca0762aae1c2 | 3,621,986 |
def compute_consistency_score(returns_test, preds):
"""
Compute Bayesian consistency score.
Parameters
----------
returns_test : pd.Series
Observed cumulative returns.
preds : numpy.array
Multiple (simulated) cumulative returns.
Returns
-------
Consistency score
... | d6d16583bdf72b2e26e18b427857aacce88db363 | 3,621,987 |
def check_if_sums_are_close(uvd1, uvd2, redgrps, array='data'):
"""
Check whether the sum of the data, flags, or nsamples in two UVData objects
is the same within each redgrp.
"""
close = []
for i, grp in enumerate(redgrps):
sum_uvd1 = np.sum(get_data_redgrp(uvd1, grp, array... | ae674bf28fb50d5d2c2b5ba16f0d7516ddd56c20 | 3,621,988 |
from datetime import datetime
def stats(update, context):
""" Show help info about all secret admins commands """
user = User.get_user(update, context)
if not user.is_admin:
return
text = f"""
*Users*: {User.objects.count()}
*24h active*: {User.objects.filter(modified__gte=now() - datetime.ti... | 18ca3b406d8750ab7e15894407b601118cacefdc | 3,621,989 |
def load_blacklist():
"""Return blacklist to be used."""
if blacklistfile:
return get_filebased_blacklist()
return get_threecommas_blacklist() | 19b2ef2d710c7065822f396c2ad93698b4bc0d74 | 3,621,990 |
def is_valid_mx(value: str):
"""Check if mx record is valid."""
for line in value.splitlines():
try:
priority, hostname = line.split(" ")
except ValueError:
raise ValidationError(
"Each line must be in the following format: [priority] [hostname]"
... | 5db5a24e6a4b4d6140d9953f059a83f6bae4baf0 | 3,621,991 |
import os
def get_index_path(yaml_data):
"""Find the index path."""
for index_root in yaml_data['index_roots']:
if os.path.exists(os.path.join(index_root, yaml_data['index_path'])):
index_path = os.path.join(index_root, yaml_data['index_path'])
break
return index_path | 28aaa73b69205fc88b98110a83534ff24a4c6f00 | 3,621,992 |
def count_accuracy_raw(pred_corpus, target_corpus):
"""
Test accuracy, Raw accuracy
"""
count_accu = 0
total = 0
pred_sents = pred_corpus.split('.')
target_sents = target_corpus.split('.')
for pred_sent, target_sent in zip(pred_sents, target_sents):
pred_list = pred_sent.split(' ... | 6935fd0bba49d0529be382c3c78f937618f28647 | 3,621,993 |
def _handle_class_a_table(table, record_children, debug):
"""Handle tables with the table headers across the top row."""
table_data = list()
keys = [item.text for item in table.find_all('tr')[0].find_all('th')]
_debug(debug, 'Found {} keys:\n{}'.format(len(keys), keys))
_debug(debug, 'Found {} rows'... | 3e24786d62e21400fef9dc3565395d78bc4e56d4 | 3,621,994 |
def f(random_state, dfnum, dfden, size=None, chunk_size=None, gpu=None, dtype=None):
"""
Draw samples from an F distribution.
Samples are drawn from an F distribution with specified parameters,
`dfnum` (degrees of freedom in numerator) and `dfden` (degrees of
freedom in denominator), where both par... | d2d4a9113a7b26c1fb79b0a54fea8a4515350c44 | 3,621,995 |
def get_callers_info(callers_file, callers_package, callers, res_dir):
"""
Tries to create a map between the top callers and its associated file, using a best effort approach, by parsing the
package declaration, in case this is need. If a file matches to a caller in the dataset, it retrieves any required
... | 37fa8fcc47ba455e6bc47243f8334f2ab26e3962 | 3,621,996 |
from typing import Union
from typing import Dict
from typing import Any
import json
def _get_connection_options(data: Union[str, Dict[str, Any]]) -> Dict[str, ConnectionOptions]:
"""Create per-platform ConnectionOptions objects from configuration dict
Args:
data (str|dict): Connection options in dict... | 08420d1785a596d8f4d7cf512e54203009901a55 | 3,621,997 |
def plyify(r, t, ply_thickness, reverse=False):
"""Fill thickness distribution using plies."""
active = []
done = []
np = len(r)
for i in range(np):
while t[i] > len(active) * ply_thickness:
active.append([r[i], -1])
while t[i] <= (len(active) - 1) * ply_thickness:
... | f8fbfa256fd1cc7b83007a631f244162d8534b4e | 3,621,998 |
import os
def info(repo=False):
"""List all installed packages with their respective port origin."""
pkg_info = env.flags["chroot"] + "/usr/local/sbin/pkg"
if not os.path.isfile(pkg_info):
return False
if repo:
return ("pkg", "rquery", "%n-%v:%o")
else:
return ("pkg", "quer... | f5600c0c61c5fad3a23743c8eb9d8760f00f6910 | 3,621,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.