content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def can_login(email, password):
"""Validation login parameter(email, password) with rules.
return validation result True/False.
"""
login_user = User.find_by_email(email)
return login_user is not None and argon2.verify(password, login_user.password_hash) | 41908f753efa1075d6583ee8a6159011bd8af661 | 14,300 |
def toPlanar(arr: np.ndarray, shape: tuple = None) -> np.ndarray:
"""
Converts interleaved frame into planar
Args:
arr (numpy.ndarray): Interleaved frame
shape (tuple, optional): If provided, the interleaved frame will be scaled to specified shape before converting into planar
Returns:... | 0f54b14b72a05fe0b20bdfd14c31084aa9c917ca | 14,301 |
import os
import subprocess
def _convert_client_cert():
"""
Convert the client certificate pfx to crt/rsa required by nginx.
If the certificate does not exist then no action is taken.
"""
cert_file = os.path.join(SECRETS, 'streams-certs', 'client.pfx')
if not os.path.exists(cert_file):
... | 55856e92d018e506999d519913a7aed58a8d3d33 | 14,302 |
def downsample_grid(
xg: np.ndarray, yg: np.ndarray, distance: float, mask: np.ndarray = None
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Downsample grid locations to approximate spacing provided by 'distance'.
Notes
-----
This implementation is more efficient than the 'downsample_xy' f... | 6ba36486bc081b85670918c63b8c1f183c284503 | 14,303 |
def convert_12bit_to_type(image, desired_type=np.uint8):
"""
Converts the 12-bit tiff from a 6X sensor to a numpy compatible form
:param desired_type: The desired type
:return: The converted image in numpy.array format
"""
image = image / MAX_VAL_12BIT # Scale to 0-1
image = np.iinfo(desire... | 6a3287946d1f56f57c6a44fc3f797753ebcd251a | 14,304 |
def dm_hdu(hdu):
""" Compute DM HDU from the actual FITS file HDU."""
if lsst.afw.__version__.startswith('12.0'):
return hdu + 1
return hdu | 87d93549f3d45ae060ced0f103065b6221e343db | 14,305 |
def get_hdf_filepaths(hdf_dir):
"""Get a list of downloaded HDF files which is be used for iterating through hdf file conversion."""
print "Building list of downloaded HDF files..."
hdf_filename_list = []
hdf_filepath_list = []
for dir in hdf_dir:
for dir_path, subdir, files in os.walk(dir):... | a64aa83d06b218a0faf3372e09c2ac337ce106aa | 14,306 |
def mask_depth_image(depth_image, min_depth, max_depth):
""" mask out-of-range pixel to zero """
ret, depth_image = cv2.threshold(
depth_image, min_depth, 100000, cv2.THRESH_TOZERO)
ret, depth_image = cv2.threshold(
depth_image, max_depth, 100000, cv2.THRESH_TOZERO_INV)
depth_image = np.... | 39fde62083666a9bb4a546c29aa736a23724e25f | 14,307 |
import copy
import os
def database_exists(url):
"""Check if a database exists.
:param url: A SQLAlchemy engine URL.
Performs backend-specific testing to quickly determine if a database
exists on the server. ::
database_exists('postgres://postgres@localhost/name') #=> False
create_d... | c04fe11fc9a8bf1e8cce767bcb2326eafdcd3c3a | 14,308 |
def prompt_for_password(prompt=None):
"""Fake prompt function that just returns a constant string"""
return 'promptpass' | 49499970c7698b08f38078c557637907edef3223 | 14,309 |
def heading(start, end):
"""
Find how to get from the point on a planet specified as a tuple start
to a point specified in the tuple end
"""
start = ( radians(start[0]), radians(start[1]))
end = ( radians(end[0]), radians(end[1]))
delta_lon = end[1] - start[1]
delta_lat = log(tan(pi/4 +... | 97bd69fc308bdf1a484901ad25b415def20f25ee | 14,310 |
def get_frame_list(video, jump_size = 6, **kwargs):
"""
Returns list of frame numbers including first and last frame.
"""
frame_numbers =\
[frame_number for frame_number in range(0, video.frame_count, jump_size)]
last_frame_number = video.frame_count - 1;
if frame_numbers[-1] != last_... | 786de04b4edf224045216de226ac61fdd42b0d7b | 14,311 |
def build_xlsx_response(wb, title="report"):
""" Take a workbook and return a xlsx file response """
title = generate_filename(title, '.xlsx')
myfile = BytesIO()
myfile.write(save_virtual_workbook(wb))
response = HttpResponse(
myfile.getvalue(),
content_type='application/vnd.openxmlf... | c9990c818b45fc68646ff28d39ea0b914e362db1 | 14,312 |
def top_k(*args, **kwargs):
""" See https://www.tensorflow.org/api_docs/python/tf/nn/top_k .
"""
return tensorflow.nn.top_k(*args, **kwargs) | 0b0a9f250a466f439301d840af2213f6b2758656 | 14,313 |
def determine_d_atoms_without_connectivity(zmat, coords, a_atoms, n):
"""
A helper function to determine d_atoms without connectivity information.
Args:
zmat (dict): The zmat.
coords (list, tuple): Just the 'coords' part of the xyz dict.
a_atoms (list): The determined a_atoms.
... | 8b2a60f6092e24b9bc6f71e4ad8753e06c2e6373 | 14,314 |
def all_of_them():
"""
Return page with all products with given name from API.
"""
if 'username' in session:
return render_template('productsearch.html', username=escape(session['username']), vars=lyst)
else:
return "Your are not logged in" | cee22ba57e108edaedc9330c21caa9cb60968aa5 | 14,315 |
def is_blank(line):
"""Determines if a selected line consists entirely of whitespace."""
return whitespace_re.match(line) is not None | 1120d7a70ce5c08eb5f179cd3d2a258af5cd3bc2 | 14,316 |
import re
import collections
import urllib
def _gff_line_map(line, params):
"""Map part of Map-Reduce; parses a line of GFF into a dictionary.
Given an input line from a GFF file, this:
- decides if the file passes our filtering limits
- if so:
- breaks it into component elements
- de... | 555ca7d4ce455563e7230d4b85f4f4404fa839bc | 14,317 |
def smoothEvolve(problem, orig_point, first_ref, second_ref):
"""Evolves using RVEA with abrupt change of reference vectors."""
pop = Population(problem, assign_type="empty", plotting=False)
try:
pop.evolve(slowRVEA, {"generations_per_iteration": 200, "iterations": 15})
except IndexError:
... | fd7f7e82e8b029597affd63ec04da3d40c049c98 | 14,318 |
def combine_color_channels(discrete_rgb_images):
"""
Combine discrete r,g,b images to RGB iamges.
:param discrete_rgb_images:
:return:
"""
color_imgs = []
for r, g, b in zip(*discrete_rgb_images):
# pca output is float64, positive and negative. normalize the images to [0, 255] rgb
... | 246653a698c997faffade25405b1dfafb8236510 | 14,319 |
def decohere_earlier_link(tA, tB, wA, wB, T_coh):
"""Applies decoherence to the earlier generated of the two links.
Parameters
----------
tA : float
Waiting time of one of the links.
wA : float
Corresponding fidelity
tB : float
Waiting time of the other link.
wB : fl... | 0ec19f50d1673f69211ac7af21ab942612fe8a67 | 14,320 |
import torch
def train(
network: RNN,
data: np.ndarray,
epochs: int = 10,
_n_seqs: int = 10,
_n_steps: int = 50,
lr: int = 0.001,
clip: int = 5,
val_frac: int = 0.2,
cuda: bool = True,
print_every: int = 10,
):
"""Train RNN."""
network.train()
opt = torch.optim.Adam... | 97c642c0b2849cb530121d914c586bc6ee76a26b | 14,321 |
def simple_lunar_phase(jd):
"""
This just does a quick-and-dirty estimate of the Moon's phase given the date.
"""
lunations = (jd - 2451550.1) / LUNAR_PERIOD
percent = lunations - int(lunations)
phase_angle = percent * 360.
delta_t = phase_angle * LUNAR_PERIOD / 360.
moon_day = int(delt... | 539d407241a0390b140fad4b67e2173ff1dee66c | 14,322 |
def fetch_traj(data, sample_index, colum_index):
""" Returns the state sequence. It also deletes the middle index, which is
the transition point from history to future.
"""
# data shape: [sample_index, time, feature]
traj = np.delete(data[sample_index, :, colum_index:colum_index+1], history_len-... | da373d3890f2c89754e36f78b78fb582b429109d | 14,323 |
from datetime import datetime
def validate_date(period: str, start: bool = False) -> pd.Timestamp:
"""Validate the format of date passed as a string.
:param period: Date in string. If None, date of today is assigned.
:type period: str
:param start: Whether argument passed is a starting date or an end... | 99c76ee2e23beaff92a8ad67bf38b26c5f33f4bd | 14,324 |
import copy
def rec_module_mic(echograms, mic_specs):
"""
Apply microphone directivity gains to a set of given echograms.
Parameters
----------
echograms : ndarray, dtype = Echogram
Target echograms. Dimension = (nSrc, nRec)
mic_specs : ndarray
Microphone directions and direct... | 91abe86095cab7ccb7d3f2f001892df4a809106b | 14,325 |
def is_string_like(obj): # from John Hunter, types-free version
"""Check if obj is string."""
try:
obj + ''
except (TypeError, ValueError):
return False
return True | cb7682f91009794011c7c663f98e539d8543c8fd | 14,326 |
import platform
def get_firefox_start_cmd():
"""Return the command to start firefox."""
start_cmd = ""
if platform.system() == "Darwin":
start_cmd = ("/Applications/Firefox.app/Contents/MacOS/firefox-bin")
elif platform.system() == "Windows":
start_cmd = _find_exe_in_registry() or _def... | 8a1dd5fea8e1197c16f4a8c26e9029265e9b83c5 | 14,327 |
def divide():
"""Handles division, returns a string of the answer"""
a = int(request.args["a"])
b = int(request.args["b"])
quotient = str(int(operations.div(a, b)))
return quotient | 50c48f9802b3f11e3322b88a45068cad7e354637 | 14,328 |
def ax2cu(ax):
"""Axis angle pair to cubochoric vector."""
return Rotation.ho2cu(Rotation.ax2ho(ax)) | 6f1c6e181d1e25a2bf28605f01d66fa6a8ffcd45 | 14,329 |
from typing import Optional
import urllib
from typing import Dict
import logging
import requests
import os
import shutil
def download_and_store(
feed_url: Text,
ignore_file: Optional[Text],
storage_path: Text,
proxy_string: Optional[Text],
link: urllib.parse.ParseResult) -> Dic... | dd5a87dcdae78f036cd1c1a86efd49b5b63066b4 | 14,330 |
def define_genom_loc(current_loc, pstart, p_center, pend, hit_start, hit_end, hit_strand, ovl_range):
""" [Local] Returns location label to be given to the annotated peak, if upstream/downstream or overlapping one edge of feature."""
all_pos = ["start", "end"]
closest_pos, dmin = distance_to_peak_center(
... | 87f89a1d392935a008b7997930bf16dda96cf36b | 14,331 |
from typing import List
import re
import argparse
def define_macro(preprocessor: Preprocessor, name: str, args: List[str], text: str) -> None:
"""Defines a macro.
Inputs:
- preprocessor - the object to which the macro is added
- name: str - the name of the new macro
- args: List[str] - List or arguments name
- ... | 56ff5bc64b733d6cadfee3252ca3a7b8a06233c5 | 14,332 |
import torch
def actp(Gij, X0, jacobian=False):
""" action on point cloud """
X1 = Gij[:,:,None,None] * X0
if jacobian:
X, Y, Z, d = X1.unbind(dim=-1)
o = torch.zeros_like(d)
B, N, H, W = d.shape
if isinstance(Gij, SE3):
Ja = torch.stack([
... | 87f85a713b72de65064224086d9c4715f704d800 | 14,333 |
def isPalindrome(s):
"""Assumes s is a str
Returns True if s is a palindrome; False otherwise.
Punctuation marks, blanks, and capitalization are ignored."""
def toChars(s):
s = s.lower()
letters = ''
for c in s:
if c in 'abcdefghijklmnopqrstuvwxyz':
letters =... | 496f5fa92088a5ecb1b99be811e68501513ee3a4 | 14,334 |
import os
def find_make_workdir(subdir, despike, spm, logger=None):
""" generates realign directory to query based on flags
and if it exists and create new workdir
"""
rlgn_dir = utils.defaults['realign_ants']
if spm:
rlgn_dir = utils.defaults['realign_spm']
if despike:
rlgn_di... | a306745583555e1488e77fea11d90e45630d7f5e | 14,335 |
import logging
def compute_irs(ground_truth_data,
representation_function,
random_state,
diff_quantile=0.99,
num_train=gin.REQUIRED,
batch_size=gin.REQUIRED):
"""Computes the Interventional Robustness Score.
Args:
ground_truth_da... | 0ff37699367946fa099f4a5a48cbc66d89af8a29 | 14,336 |
def Grab_Pareto_Min_Max(ref_set_array, objective_values, num_objs, num_dec_vars, objectives_names=[],
create_txt_file='No'):
"""
Purposes: Identifies the operating policies producing the best and worst performance in each objective.
Gets called automatically by processing_reference... | 882ba260576550d2c9de20e950594d5369410187 | 14,337 |
def edist(x, y):
""" Compute the Euclidean distance between two samples x, y \in R^d."""
try:
dist = np.sqrt(np.sum((x-y)**2))
except ValueError:
print 'Dimensionality of samples must match!'
else:
return dist | e0b0e586b49bf3e19eafa2cbf271fb3b1ddc2b99 | 14,338 |
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import six
def figure(fnum=None, pnum=(1, 1, 1), title=None, figtitle=None, doclf=False,
docla=False, projection=None, **kwargs):
"""
http://matplotlib.org/users/gridspec.html
Args:
fnum (int): fignum = figure numbe... | a37e688a12713b2f4770708e34084601e2c308bb | 14,339 |
def allsec_preorder(h):
"""
Alternative to using h.allsec(). This returns all sections in order from
the root. Traverses the topology each neuron in "pre-order"
"""
#Iterate over all sections, find roots
roots = root_sections(h)
# Build list of all sections
sec_list = []
for r in ro... | 0407bd37c3f975ba91a51b3058d6c619813f2526 | 14,340 |
def get_func_bytes(*args):
"""get_func_bytes(func_t pfn) -> int"""
return _idaapi.get_func_bytes(*args) | 56000602c9d1d98fb1b76c809cce6c3458a3f426 | 14,341 |
def balanced_accuracy(y_true, y_score):
"""Compute accuracy using one-hot representaitons."""
if isinstance(y_true, list) and isinstance(y_score, list):
# Online scenario
if y_true[0].ndim == 2 and y_score[0].ndim == 2:
# Flatten to single (very long prediction)
y_true = ... | 9745769ac047863b902f0e74f17680f9ccee5a53 | 14,342 |
import json
from dateutil import tz
from datetime import datetime
async def get_weather(weather):
""" For .weather command, gets the current weather of a city. """
if not OWM_API:
await weather.reply(
f"`{JAVES_NNAME}:` **Get an API key from** https://openweathermap.org/ `first.`")
... | b93c21eadefa2b4504708ae2663bfdcbf0555668 | 14,343 |
def read_table(source, columns=None, nthreads=1, metadata=None,
use_pandas_metadata=False):
"""
Read a Table from Parquet format
Parameters
----------
source: str or pyarrow.io.NativeFile
Location of Parquet dataset. If a string passed, can be a single file
name or di... | 0d0e4990e88c39920e380cca315332f7c36f6ee8 | 14,344 |
def preprocess_img(image, segnet_stream='fstream'):
"""Preprocess the image to adapt it to network requirements
Args:
Image we want to input the network in (W,H,3) or (W,H,4) numpy array
Returns:
Image ready to input to the network of (1,W,H,3) or (1,W,H,4) shape
Note:
This is re... | a3371b69179fb5f53583fb39a3ac458b9c9bbe5d | 14,345 |
def _export_cert_from_task_keystore(
task, keystore_path, alias, password=KEYSTORE_PASS):
"""
Retrieves certificate from the keystore with given alias by executing
a keytool in context of running container and loads the certificate to
memory.
Args:
task (str): Task id of container t... | 8ae8a0e1d46f121597d70aff35a26ce15c448399 | 14,346 |
def eta_expand(
path: qlast.Path,
stype: s_types.Type,
*,
ctx: context.ContextLevel,
) -> qlast.Expr:
"""η-expansion of an AST path"""
if not ALWAYS_EXPAND and not stype.contains_object(ctx.env.schema):
# This isn't strictly right from a "fully η expanding" perspective,
# but for... | 294e9b0e2aa158dc4e8d57917031986f824fd55d | 14,347 |
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
import timeit
def NBAccuracy(features_train, labels_train, features_test, labels_test):
""" compute the accuracy of your Naive Bayes classifier """
# create classifier
clf = GaussianNB()
# fit the classifier on the... | c4c6d5a37341a811023bb0040616ebeb1c44be13 | 14,348 |
import json
def verify(body): # noqa: E501
"""verify
Verifies user with given user id. # noqa: E501
:param body: User id that is required for verification.
:type body: dict | bytes
:rtype: UserVerificationResponse
"""
if connexion.request.is_json:
body = VerifyUser.from_dict(co... | 76b2ad631dffbf59b1c2ffeb12069983d0540b51 | 14,349 |
def load_interface(interface_name, data):
"""
Load an interface
:param interface_name: a string representing the name of the interface
:param data: a dictionary of arguments to be used for initializing the interface
:return: an Interface object of the appropriate type
"""
if interface_name n... | e57e0710d5ad5080b2da1f734581d1b205aedc77 | 14,350 |
def as_observation_matrix(cnarr, variants=None):
"""Extract HMM fitting values from `cnarr`.
For each chromosome arm, extract log2 ratios as a numpy array.
Future: If VCF of variants is given, or 'baf' column has already been
added to `cnarr` from the same, then the BAF values are a second row/column
... | 74def8f4ecf398c389a6b2a857096a599ef05a15 | 14,351 |
def get_full_word(*args):
"""get_full_word(ea_t ea) -> ulonglong"""
return _idaapi.get_full_word(*args) | 8eb45586888fc836146441bb00bc3c3096ea2c5e | 14,352 |
def full_setup(battery_chemistry):
"""This function gets the baseline vehicle and creates modifications for different
configurations, as well as the mission and analyses to go with those configurations."""
# Collect baseline vehicle data and changes when using different configuration settings
vehicle ... | 9335521ad5a238ab0a566c80d1443cc5c052a37a | 14,353 |
def sph_yn_exact(n, z):
"""Return the value of y_n computed using the exact formula.
The expression used is http://dlmf.nist.gov/10.49.E4 .
"""
zm = mpmathify(z)
s1 = sum((-1)**k*_a(2*k, n)/zm**(2*k+1) for k in xrange(0, int(n/2) + 1))
s2 = sum((-1)**k*_a(2*k+1, n)/zm**(2*k+2) for k in xrange(... | 490c31a3311fb922f5d33337aaeb70f167b25772 | 14,354 |
def f_bis(n1 : float, n2 : float, n3 : float) -> str:
""" ... cf ci-dessus ...
"""
if n1 < n2:
if n2 < n3:
return 'cas 1'
elif n1 < n3:
return 'cas 2'
else:
return 'cas 5'
elif n1 < n3:
return 'cas 3'
elif n2 < n3:
return 'c... | e46c147a5baef02878700e546b11b7ae44b8909a | 14,355 |
def calc_B_effective(*B_phasors):
"""It calculates the effective value of the magnetic induction field B
(microTesla) in a given point, considering the magnetic induction of
all the cables provided.
Firstly, the function computes the resulting real and imaginary parts
of the x and y magnetic induc... | a24ae9330018f9dc24ebbba66ccc4bc4bd79a7cb | 14,356 |
def elision_count(l):
"""Returns the number of elisions in a given line
Args:
l (a bs4 <line>): The line
Returns:
(int): The number of elisions
"""
return sum([(1 if _has_elision(w) else 0) for w in l("word")]) | c031765089a030328d68718577872a6d2f70b88d | 14,357 |
def get_final_df(model, data):
"""
This function takes the `model` and `data` dict to
construct a final dataframe that includes the features along
with true and predicted prices of the testing dataset
"""
# if predicted future price is higher than the current,
# then calculate the true futur... | e28f19c5072693872bf17a89cf39cc6afa74517b | 14,358 |
def read_fragment_groups(input_string,natoms,num_channels):
""" read in the fragment groups for each channel
"""
inp_line = _get_integer_line(input_string,'FragmentGroups',natoms)
assert inp_line is not None
out=' '.join(inp_line)
return out | 81ae922add4d0c1680bbeb5223ad85a265ac3040 | 14,359 |
import os
import warnings
import sys
import pickle
def save(program, model_path, protocol=4, **configs):
"""
:api_attr: Static Graph
This function save parameters, optimizer information and network description to model_path.
The parameters contains all the trainable Tensor, will save to a file with ... | 4352e700fee3b24652ae51adf6108a72866f9a26 | 14,360 |
def pad_tile_on_edge(tile, tile_row, tile_col, tile_size, ROI):
""" add the padding to the tile on the edges. If the tile's center is
outside of ROI, move it back to the edge
Args:
tile: tile value
tile_row: row number of the tile relative to its ROI
tile_col: col number of the tile relative to its... | bf829ead79f6347423dae8f4c534352d648a3845 | 14,361 |
def calc_kfold_score(model, df, y, n_splits=3, shuffle=True):
"""
Calculate crossvalidation score for the given model and data. Uses sklearn's KFold with shuffle=True.
:param model: an instance of sklearn-model
:param df: the dataframe with training data
:param y: dependent value
:param n_... | 09e646d40b245be543c5183b8c964fe8ee4f699f | 14,362 |
def obter_forca (unidade):
"""Esta funcao devolve a forca de ataque da unidade dada como argumento"""
return unidade[2] | 34fe4acac8e0e3f1964faf8e4b26fa31148cf2a6 | 14,363 |
from typing import Dict
def get_default_configuration(cookiecutter_json: CookiecutterJson) -> Dict[str, str]:
"""
Get the default values for the cookiecutter configuration.
"""
default_options = dict()
for key, value in cookiecutter_json.items():
if isinstance(value, str) and "{{" not in v... | 8a8e3a9b80d3440f1e6031498c210b7b5577aa03 | 14,364 |
def random_nodes_generator(num_nodes, seed=20):
"""
:param int num_nodes: An Integer denoting the number of nodes
:param int seed: (Optional) Integer specifying the seed for controlled randomization.
:return: A dictionary containing the coordinates.
:rtype: dict
"""
np.random.seed(seed)
... | 5fa08ccc2cd3a4c34962a29ca9a7566ca5e64592 | 14,365 |
def OpenDocumentTextMaster():
""" Creates a text master document """
doc = OpenDocument('application/vnd.oasis.opendocument.text-master')
doc.text = Text()
doc.body.addElement(doc.text)
return doc | 6813f527ced0f1cd89e0824ac10aeb78d06799a4 | 14,366 |
def get_visible_desktops():
"""
Returns a list of visible desktops.
The first desktop is on Xinerama screen 0, the second is on Xinerama
screen 1, etc.
:return: A list of visible desktops.
:rtype: util.PropertyCookie (CARDINAL[]/32)
"""
return util.PropertyCookie(util.ge... | 9fba922a5c83ed4635391f6ed5319fcfe4fd424d | 14,367 |
import os
def get_env_string(env_key, fallback):
"""
reads boolean literal from environment. (does not use literal compilation
as far as env returns always a string value
Please note that 0, [], {}, '' treats as False
:param str env_key: key to read
:param str fallback: fallback value
:r... | af136c32b22b1cad30a65e517828dfaf01cb597d | 14,368 |
def spherical_noise(
gridData=None, order_max=8, kind="complex", spherical_harmonic_bases=None
):
"""Returns order-limited random weights on a spherical surface.
Parameters
----------
gridData : io.SphericalGrid
SphericalGrid containing azimuth and colatitude
order_max : int, optional
... | 82ef238ef0d72100435306267bf8248f82b70fd8 | 14,369 |
def rollback_command():
"""Command to perform a rollback fo the repo."""
return Command().command(_rollback_command).require_clean().require_migration().with_database() | abfed20ff8cfa08af084fc8c956ebb8d312c985f | 14,370 |
import numpy
def circumcenter(vertices):
"""
Compute the circumcenter of a triangle (the center of the circle which passes through all the vertices of the
triangle).
:param vertices: The triangle vertices (3 by n matrix with the vertices as rows (where n is the dimension of the
space)).
:... | 314e7650b6fec6c82880541de32c1378e720c8c8 | 14,371 |
import subprocess
def testing_submodules_repo(testing_workdir, request):
"""Initialize a new git directory with two submodules."""
subprocess.check_call(['git', 'init'])
# adding a commit for a readme since git diff behaves weird if
# submodules are the first ever commit
subprocess.check_call(['t... | 3a09e30447d7ebdb041ff1d4ad7f28c8483db41a | 14,372 |
def get_ROC_curve_naive(values, classes):
""" Naive implementation of a ROC curve generator that iterates over a number of thresholds.
"""
# get number of positives and negatives:
n_values = len(values);
totalP = len(np.where(classes > 0)[0]);
totalN = n_values - totalP;
min_v... | 5950c207746c39c4787b3a472c83fbca5599d654 | 14,373 |
import re
def worker(path, opt):
"""Worker for each process.
Args:
path (str): Image path.
opt (dict): Configuration dict. It contains:
crop_size (int): Crop size.
step (int): Step for overlapped sliding window.
thresh_size (int): Threshold size. Patches wh... | 68b43995cb147bedad7b94c6f4960cef2646ed87 | 14,374 |
def RobotNet(images,dropout):
"""
Build the model for Robot where it will be used as RobotNet.
Args:
images: 4-D tensor with shape [batch_size, height, width, channals].
dropout: A Python float. The probability that each element is kept.
Returns:
Output tensor with the computed ... | 9bab69a9a0a01436c9b4225ec882231dc561c204 | 14,375 |
def cvReleaseMemStorage(*args):
"""cvReleaseMemStorage(PyObject obj)"""
return _cv.cvReleaseMemStorage(*args) | a11985f756672ab7b7c5ed58336daad1a975c0d2 | 14,376 |
import os
from sys import path
def run_config_filename(conf_filename):
""" Runs xNormal using the path to a configuration file. """
retcode = os.system("\"%s\" %s" % (path, conf_filename))
return retcode | a68fdbefc4e6d4459073243996d0706111ec4a36 | 14,377 |
import typing
def GetCommitsInOrder(
repo: git.Repo,
head_ref: str = "HEAD",
tail_ref: typing.Optional[str] = None) -> typing.List[git.Commit]:
"""Get a list of all commits, in chronological order from old to new.
Args:
repo: The repo to list the commits of.
head_ref: The starting point for i... | 57db975d44af80a5c6a8e251842182f6a0f572af | 14,378 |
def sell():
"""Sell shares of stock"""
# return apology("TODO")
if request.method == 'GET':
return render_template('sell_stock.html')
else:
symbol = request.form['symbol']
shares = int(request.form['shares'])
return sell_stock(Symbol=symbol, Shares=shares, id=session['use... | 66e53465f1c7fc9bb695f2b63867f24a9429018f | 14,379 |
def return_sw_checked(softwareversion, osversion):
"""
Check software existence, return boolean.
:param softwareversion: Software release version.
:type softwareversion: str
:param osversion: OS version.
:type osversion: str
"""
if softwareversion is None:
serv = bbconstants.SE... | 9f7efb06150468e553ac6a066b2c7750fd233d4c | 14,380 |
from re import A
import copy
def apply(
f: tp.Callable[..., None],
obj: A,
*rest: A,
inplace: bool = False,
_top_inplace: tp.Optional[bool] = None,
_top_level: bool = True,
) -> A:
"""
Applies a function to all `to.Tree`s in a Pytree. Works very similar to `jax.tree_map`,
but its v... | 9a4d29546eb47ba4838fccb58f78495411c99e1c | 14,381 |
import requests
def imageSearch(query, top=10):
"""Returns the decoded json response content
:param query: query for search
:param top: number of search result
"""
# set search url
query = '%27' + parse.quote_plus(query) + '%27'
# web result only base url
base_url = 'https://api.datam... | 4c731b0ead57e5ec4ab290c9afc67d6066cce093 | 14,382 |
def pack_inputs(inputs):
"""Pack a list of `inputs` tensors to a tuple.
Args:
inputs: a list of tensors.
Returns:
a tuple of tensors. if any input is None, replace it with a special constant
tensor.
"""
inputs = tf.nest.flatten(inputs)
outputs = []
for x in inputs:
if x is None... | 2801929a1109cd3c416d8b3229399a0a9b73a38f | 14,383 |
def entries_as_dict(month_index):
"""Convert index xml list to list of dictionaries."""
# Search path
findentrylist = etree.ETXPath("//section[@id='month-index']/ul/li")
# Extract data
entries_xml = findentrylist(month_index)
entries = [to_entry_dict(entry_index_xml)
for entry_ind... | 2fba6699457ca9726d4ce93b480e722bb6c8223d | 14,384 |
def resnet50():
"""Constructs a ResNet-50 model.
"""
return Bottleneck, [3, 4, 6, 3] | 197dc833c966146226721e56315d3f12d9c13398 | 14,385 |
def build_service_job_mapping(client, configured_jobs):
"""
:param client: A Chronos client used for getting the list of running jobs
:param configured_jobs: A list of jobs configured in Paasta, i.e. jobs we
expect to be able to find
:returns: A dict of {(service, instance): last_chronos_job}
... | 58cdf0a7f7561d1383f8f4c4e4cdd0f46ccfad0c | 14,386 |
def _validate_labels(labels, lon=True):
"""
Convert labels argument to length-4 boolean array.
"""
if labels is None:
return [None] * 4
which = 'lon' if lon else 'lat'
if isinstance(labels, str):
labels = (labels,)
array = np.atleast_1d(labels).tolist()
if all(isinstance(... | 6b4f4870692b3c89f2c51f920892852eeecc418d | 14,387 |
def celsius_to_fahrenheit(temperature_C):
""" converts C -> F """
return temperature_C * 9.0 / 5.0 + 32.0 | 47c789c560c5b7d035252418bd7fb0819b7631a4 | 14,388 |
import re
from datetime import datetime
def _parse_date_time(date):
"""Parse time string.
This matches 17:29:43.
Args:
date (str): the date string to be parsed.
Returns:
A tuple of the format (date_time, nsec), where date_time is a
datetime.time object and nsec is 0.
Ra... | 2d7f4b067d1215623c2e8e4217c98591a1794481 | 14,389 |
def parsed_user(request, institute_obj):
"""Return user info"""
user_info = {
'email': 'john@doe.com',
'name': 'John Doe',
'location': 'here',
'institutes': [institute_obj['internal_id']],
'roles': ['admin']
}
return user_info | 773363dc41f599abe27a5913434f88d1a20c131d | 14,390 |
def lastFromUT1(ut1, longitude):
"""Convert from universal time (MJD)
to local apparent sidereal time (deg).
Inputs:
- ut1 UT1 MJD
- longitude longitude east (deg)
Returns:
- last local apparent sideral time (deg)
History:
2002-08-05 ROwen First version, loosely base... | 0ba587125c0c422349acf7bb9753b09956fd9bed | 14,391 |
import os
import torch
def get_dataset(opts):
""" Dataset And Augmentation
"""
train_transform = transform.Compose([
transform.RandomResizedCrop(opts.crop_size, (0.5, 2.0)),
transform.RandomHorizontalFlip(),
transform.ToTensor(),
transform.Normalize(mean=[0.485, 0.456, 0.40... | 610d656f356ec710e7873998e8566685da262ab9 | 14,392 |
import itertools
def strip_translations_header(translations: str) -> str:
"""
Strip header from translations generated by ``xgettext``.
Header consists of multiple lines separated from the body by an empty line.
"""
return "\n".join(itertools.dropwhile(len, translations.splitlines())) | b96c964502724008306d627d785224be08bddb86 | 14,393 |
import random
def sample_targets_and_primes(targets, primes, n_rounds,
already_sampled_targets=None, already_sampled_primes=None):
"""
Sample targets `targets` and primes `primes` for `n_rounds` number of rounds. Omit already sampled targets
or primes which can be passed as s... | 6b73cdadf3016f1dc248deb2625eae1dd620553b | 14,394 |
def getsign(num):
"""input the raw num string, return a tuple (sign_num, num_abs).
"""
sign_num = ''
if num.startswith('±'):
sign_num = plus_minus
num_abs = num.lstrip('±+-')
if not islegal(num_abs):
return sign_num, ''
else:
try:
temp = float(... | 46fc5a7ac8e366479c40e2ccc1a33f57a736b343 | 14,395 |
from typing import Mapping
from typing import Union
def _convert_actions_to_commands(
subvol: Subvol,
build_appliance: Subvol,
action_to_names_or_rpms: Mapping[RpmAction, Union[str, _LocalRpm]],
) -> Mapping[YumDnfCommand, Union[str, _LocalRpm]]:
"""
Go through the list of RPMs to install and chan... | 519d09754b18bcabef405f3d39a959b1296d3c6c | 14,396 |
def fit_DBscan (image_X,
eps,
eps_grain_boundary,
min_sample,
min_sample_grain_boundary,
filter_boundary,
remove_large_clusters,
remove_small_clusters,
binarize_bdr_coord,
b... | b32218e6d45dc766d749af9247ee1d343236fef0 | 14,397 |
def get_today_timestring():
"""Docen."""
return pd.Timestamp.today().strftime('%Y-%m-%d') | f749a5a63f7c55053918eb3f95bb56c2325f4362 | 14,398 |
from pathlib import Path
import json
def load_json(filepath):
"""
Load a json file
:param filepath: path to json file
"""
fp = Path(filepath)
if not fp.exists():
raise ValueError("Unrecognized file path: {}".format(filepath))
with open(filepath) as f:
data = json.load(f)
... | 657509a50961f7b9c83536a8973884eef5bbed5e | 14,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.