content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def SecureBytesEqual( a, b ):
"""Returns the equivalent of 'a == b', but avoids content based short
circuiting to reduce the vulnerability to timing attacks."""
# Consistent timing matters more here than data type flexibility
# We do NOT want to support py2's str type because iterating over them
# (below) pro... | 1ba46089d94f544b53a47e09dbbcf95dd5b594a0 | 3,651,200 |
import base64
import pickle
def encode(something):
"""
We encode all messages as base64-encoded pickle objects in case
later on, we want to persist them or send them to another system.
This is extraneous for now.
"""
return base64.b64encode(pickle.dumps(something)) | 89c9c855b8b66aadc55c1602e133906d3220691a | 3,651,201 |
def scrape_proposal_page(browser, proposal_url):
"""
Navigates to the page giving details about a piece of legislation, scrapes
that data, and adds a model to the database session. Returns the new DB
model.
"""
browser.get(proposal_url)
file_number = int(extract_text(browser.find_element_by... | a15b01721e9fea658d07a0a878df2f2ac58fa2f7 | 3,651,202 |
def installRecommendation(install, uninstall, working_set=working_set, tuples=False):
"""Human Readable advice on which modules have to be installed on
current Working Set.
"""
installList = []
for i in install:
is_in = False
for p in working_set:
if i[0] == p.key and i[1... | bf3083d4bcb50bdc27c382ccd9ea1dfc7b8cdb71 | 3,651,203 |
def obsangle(thetas, phis, alpha_obs):
"""
Return the cosine of the observer angle for the different shockwave segments and and
and observer at and angle alpha_obs with respect to the jet axis
(contained in yz plane)
"""
#u_obs_x, u_obs_y, u_obs_z = 0., sin(alpha_obs), co... | 6fc03a386a97f63d3ad10d291d1528bf7fb45720 | 3,651,204 |
def _image_tensor_input_placeholder(input_shape=None):
"""Returns input placeholder and a 4-D uint8 image tensor."""
if input_shape is None:
input_shape = (None, None, None, 3)
input_tensor = tf.placeholder(
dtype=tf.uint8, shape=input_shape, name='image_tensor')
return input_tensor, inp... | bd3c339da4b8f0eea482687cecf28a4625d3f84c | 3,651,205 |
def _load_top_bonds(f, topology, **kwargs):
"""Take a mol2 file section with the heading '@<TRIPOS>BOND' and save to the topology.bonds attribute."""
while True:
line = f.readline()
if _is_end_of_rti(line):
line = line.split()
bond = Bond(
connection_membe... | e6605428a99720ff0d773a1db2a8363d61e38ca3 | 3,651,206 |
def timelength_to_phrase(
timelength: spec.Timelength,
from_representation: spec.TimelengthRepresentation = None,
) -> spec.TimelengthPhrase:
"""convert Timelength to TimelengthPhrase
## Inputs
- timelength: Timelength
- from_representation: str representation name of input timelength
## R... | a840b69625c968cda4a1e686a61298e2809ffde0 | 3,651,207 |
def order_columns(self: DataFrame, order: str = "asc", by_dtypes: bool = False):
"""
Rearrange the columns in alphabetical order.
An option of rearrangement by dtypes is possible.
:param self:
:param by_dtypes: boolean to rearrange by dtypes first
"""
if order not in ['asc', 'desc']:
... | c05f4b13b26b041c86816c15a375943713a6dcdb | 3,651,208 |
import sys
from sys import version
import os
def main():
""" do main work """
cmdArgs = sys.argv[1:]
if not cmdArgs:
msg = "There is no version in args. Current version: "
msg += version.current()
print(msg)
if GIT_EXE:
print("Result of 'git describe': ")
... | b6110be510bb9a8bdddbc076ada7c51eb2ad8427 | 3,651,209 |
import random
def reorderWithinGroup(players_by_wins):
"""Shuffle players with the same score.
Args:
players_by_wins: a dictionary returned by splitByScore().
Returns a list of the re-ordered player ids.
"""
for score in players_by_wins.keys():
random.shuffle(players_by_win... | bd0afe4db36bf815ab7861e53cd674bd49e81775 | 3,651,210 |
def selection(population, method):
"""Apply selection method of a given population.
Args:
population: (list of) plans to apply the selection on.
method: (str) selection method:
- rws (Roulette Wheel Selection)
- sus (Stochastic Universal Selection)
- ts (Tou... | e5b05c62530babfd48b5061152b9f88e4a463456 | 3,651,211 |
def PSL_prefix(row, cols):
"""Returns the prefix a domain (www.images for www.images.example.com)"""
psl_data = psl.search_tree(row[cols[0]])
if psl_data:
return(psl_data[1], psl_data[0])
return (None, None) | e5e7809acae3be60eca9f0cd65aec7a93ac087de | 3,651,212 |
def build_model(sess,t,Y,model='sde',sf0=1.0,ell0=[2,2],sfg0=1.0,ellg0=[1e5],
W=6,ktype="id",whiten=True,
fix_ell=False,fix_sf=False,fix_Z=False,fix_U=False,fix_sn=False,
fix_ellg=False,fix_sfg=False,fix_Zg=True,fix_Ug=False):
"""
Args:
sess: TensowFlow session ne... | f5d691aca815df25d1c34ae9c7fa9810c3aae1ab | 3,651,213 |
import re
def paginatedUrls(pattern, view, kwargs=None, name=None):
"""
Takes a group of url tuples and adds paginated urls.
Extends a url tuple to include paginated urls.
Currently doesn't handle url() compiled patterns.
"""
results = [(pattern, view, kwargs, name)]
tail = ''
mtail ... | 2102309434e02e0df49888978d41ffce2de0e2dc | 3,651,214 |
from typing import Tuple
def _to_intraday_trix(date: pd.Timestamp, provider: providers.DataProvider,
period: int)-> Tuple[nd.NDArray, nd.NDArray]:
"""
Returns an ndarray containing the TRIX for a given +data+ and +provider+,
averaged across a given +period+.
"""
# First, get ... | 14c621afa6128fb3b33058b357e2ca79723a42f9 | 3,651,215 |
def _decode(integer):
"""
Decode the given 32-bit integer into a MAX_LENGTH character string according
to the scheme in the specification. Returns a string.
"""
if integer.bit_length() > 32:
raise ValueError("Can only decode 32-bit integers.")
decoded_int = 0
# Since each byte has ... | 156b75e8907bbcf6ae69f0a3429fb29777651f8e | 3,651,216 |
def register(name):
"""Registers a new data loader function under the given name."""
def add_to_dict(func):
_LOADERS[name] = func
return func
return add_to_dict | ea672cdf3c8d34f090d98e2498b77ea929aee6e6 | 3,651,217 |
def get_api_host(staging):
"""If 'staging' is truthy, return staging API host instead of prod."""
return STAGING_API_HOST if staging else PROD_API_HOST | d2b0003669422ef4481ffe4db76497de1485d0f7 | 3,651,218 |
import requests
import os
def get(path, params={}):
"""Make an authenticated GET request to the GitHub API."""
return requests.get(
os.path.join("https://api.github.com/", path),
auth=(USER, PASS),
params=params
).json() | b35d416f762a7d42a97169133d686b33dac74a59 | 3,651,219 |
def delete_user(auth, client):
"""
Delete a user
:auth: dict
:client: users_client object
"""
log("What user you want to delete?")
user_to_delete = find_user_by_username(auth, client)
if user_to_delete is False:
log("Could not find user.", serv="ERROR")
return False
... | db51c7d7d9f5fbd164bde010f3887f43e998fbef | 3,651,220 |
from datetime import datetime
import requests
def get_buildbot_stats(time_window : datetime.datetime) -> BuildStats:
"""Get the statistics for the all builders."""
print('getting list of builders...')
stats = BuildStats()
for builder in requests.get(BASE_URL).json().keys():
# TODO: maybe filte... | dc27d0672b9c03967575bef2ccbc95791502a8ab | 3,651,221 |
def remove_empty(s):
"""\
Remove empty strings from a list.
>>> a = ['a', 2, '', 'b', '']
>>> remove_empty(a)
[{u}'a', 2, {u}'b']
"""
while True:
try:
s.remove('')
except ValueError:
break
return s | 98778e4cc90f11b9b74ac6d26b203cbfc958fd7b | 3,651,222 |
import math
from typing import Tuple
from typing import Any
import itertools
def quantum_ia(nb_stick: int, past: list, backend_sim: Aer) -> list:
"""Quantum IA.
Args:
nb_stick: nb of stick left
past: past turn
backend_sim: backend for quantum
Return: Prediction to use
... | 7e13f554e6eb901ec43ec80bf346005f17ec55d5 | 3,651,223 |
def construct_model_cnn_gram(num_classes, input_shape):
"""
construct model architecture
:param num_classes: number of output classes of the model [int]
:return: model - Keras model object
"""
model = Sequential()
model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_unifo... | ddffb66efe6b4f94a9c2a0ccc976206eebb503a6 | 3,651,224 |
def get_basic_data(match_info, event):
"""input: dictionary | output: dictionary updated"""
match_info['status'] = event['status']['type']['name']
match_info['start_time'] = event['date']
match_info['match_id'] = event['id']
match_info['time'] = event['status']['displayClock']
match_info['period... | fae755e195b5bbf12c9fccf20b9ba2c2f9e700c6 | 3,651,225 |
import os
import subprocess
def handle_solution(f, problem_id, user, lang):
"""
When user uploads the solution, this function takes care of it.
It runs the grader, saves the running time and output and saves
the submission info to database.
:param f: submission file (program)
... | 6373e5d55c8135ede8e401cc8f2c9b1464bda1bf | 3,651,226 |
def convert_blockgrad(node, **kwargs):
""" Skip operator """
return create_basic_op_node('Identity', node, kwargs) | 12803d387a30884da08779b878e9cdf3e06226a7 | 3,651,227 |
def is_complete(node):
"""
all children of a sum node have same scope as the parent
"""
assert node is not None
for sum_node in reversed(get_nodes_by_type(node, Sum)):
nscope = set(sum_node.scope)
if len(sum_node.children) == 0:
return False, "Sum node %s has no childr... | a92741f4770757518e91a44e757e4d8037958066 | 3,651,228 |
import torch
def step_inplace(Ts, ae, target, weight, depth, intrinsics, lm=.0001, ep=10.0):
""" dense gauss newton update with computing similiarity matrix """
pts = pops.inv_project(depth, intrinsics)
pts = pts.permute(0,3,1,2).contiguous()
# tensor representation of SE3
se3 = Ts.data.perm... | 9f1fc6911d1fb11bc6956d63dda8f59b8f6654cd | 3,651,229 |
def _compute_extent_axis(axis_range, grid_steps):
"""Compute extent for matplotlib.pyplot.imshow() along one axis.
:param axis_range: 1D numpy float array with 2 elements; axis range for plotting
:param grid_steps: positive integer, number of grid steps in each dimension
:return: 1D numpy float array w... | e83a251b4055639435342d19960d1e75a6d33ba8 | 3,651,230 |
import pathlib
import os
def normalize_path(filepath, expand_vars=False):
""" Fully normalizes a given filepath to an absolute path.
:param str filepath: The filepath to normalize
:param bool expand_vars: Expands embedded environment variables if True
:returns: The fully noralized filepath
:rtype... | d408d6c1cd86072473a52f626821fcebd380c29d | 3,651,231 |
import os
def _make_relative_path(base_path, full_path):
"""
Strip out the base_path from full_path and make it relative.
"""
flask.current_app.logger.debug(
'got base_path: %s and full_path: %s' % (base_path, full_path))
if base_path in full_path:
# Get the common prefix
c... | c40252232bf02aa51411f4a9a50d9d71d5447348 | 3,651,232 |
import hashlib
def md5_hash_file(fh):
"""Return the md5 hash of the given file-object"""
md5 = hashlib.md5()
while True:
data = fh.read(8192)
if not data:
break
md5.update(data)
return md5.hexdigest() | f572ec27add8024e5fa8b9a82b5d694905e4d0f8 | 3,651,233 |
def rule(request):
"""Administration rule content"""
if request.user.is_authenticated():
return helpers.render_page('rule.html', show_descriptions=True)
else:
return redirect('ahmia.views_admin.login') | 514f767235660b812126c5cfc2dabeec40a7b22a | 3,651,234 |
def get_tenant_info(schema_name):
"""
get_tenant_info return the first tenant object by schema_name
"""
with schema_context(schema_name):
return Pharmacy.objects.filter(schema_name=schema_name).first() | 388d51c50fec60a331822bd157da1d53c88cc170 | 3,651,235 |
def get_lr(curr_epoch, hparams, iteration=None):
"""Returns the learning rate during training based on the current epoch."""
assert iteration is not None
batches_per_epoch = int(hparams.train_size / hparams.batch_size)
if 'svhn' in hparams.dataset and 'wrn' in hparams.model_name:
lr = step_lr(hp... | 42df4a185dd41d0eb02845d78dbd061f4658fba8 | 3,651,236 |
import glob
import os
def delete_map():
"""
Delete all maps
Returns
-------
(response, status_code): (dict, int)
The response is a dictionary with the keys -> status, message and
result.
The status is a bool that says if the operation was successful.
... | 0a4b8ef8975f33e37ecde4b50324d98c45f8a691 | 3,651,237 |
def delete_page(shortname):
"""Delete page from the database."""
# Check page existency
if get_page(shortname) is None:
abort(404)
if shortname is None:
flash("No parameters for page deletion!")
return redirect(url_for("admin"))
else:
query_db("DELETE FROM pages WHER... | b1bb9526832209e1cddf1c86851aeef7c6701d3d | 3,651,238 |
def has_property(name, match=None):
"""Matches if object has a property with a given name whose value satisfies
a given matcher.
:param name: The name of the property.
:param match: Optional matcher to satisfy.
This matcher determines if the evaluated object has a property with a given
name. I... | a5c562b1f5a36fc2c591d700d84b5ee9ca54ccde | 3,651,239 |
import glob
def gain_stability_task(run, det_name, fe55_files):
"""
This task fits the Fe55 clusters to the cluster data from each frame
sequence and writes a pickle file with the gains as a function of
sequence number and MJD-OBS.
Parameters
----------
run: str
Run number.
de... | a285879fc963342ed51b61ec9fae8ac08c089bc6 | 3,651,240 |
from datetime import datetime
def get_datetime(timestamp):
"""Parse several representations of time into a datetime object"""
if isinstance(timestamp, datetime.datetime):
# Timestamp is already a datetime object.
return timestamp
elif isinstance(timestamp, (int, float)):
try:
... | d8277a1de3876106de02b9d75e02369061261996 | 3,651,241 |
def conda_installed_files(prefix, exclude_self_build=False):
"""
Return the set of files which have been installed (using conda) into
a given prefix.
"""
res = set()
for dist in install.linked(prefix):
meta = install.is_linked(prefix, dist)
if exclude_self_build and 'file_hash' i... | e81051e19f7829bf149c71f0533bd51c80c7e2a1 | 3,651,242 |
def computeStarsItembased(corated, target_bid, model):
"""
corated - {bid: star, ...}
"""
if corated == None:
return None
corated.pop(target_bid, None)
bid_cor = list(corated.keys())
collect = []
for b in bid_cor:
pair = None
if b < target_bid:
pair = ... | 7b3cd5bd103d35fe09477be96b5cbcc378927c65 | 3,651,243 |
import psutil
import re
def beacon(config):
"""
Monitor the memory usage of the minion
Specify thresholds for percent used and only emit a beacon
if it is exceeded.
.. code-block:: yaml
beacons:
memusage:
- percent: 63%
"""
ret = []
_config = {}
li... | ac10e85d47fef403148ad2e00c4e10ced2cc226c | 3,651,244 |
def get_surrounding_points(search_values, point_set):
"""
#for each value p[i] in search_values, returns a pair of surrounding points from point_set
the surrounding points are a tuplet of the form (lb[i], ub[i]) where
- lb[i] < p[i] < ub[i] if p[i] is not in point_set, and p[i] is within range
- lb[... | d4ec055946c19b999ed9523aa260d7bd28ffd269 | 3,651,245 |
def _scriptable_get(obj, name):
""" The getter for a scriptable trait. """
global _outermost_call
saved_outermost = _outermost_call
_outermost_call = False
try:
result = getattr(obj, '_' + name, None)
if result is None:
result = obj.trait(name).default
finally:
... | 53da00cb49d73065281306c90a51a95e1670e14e | 3,651,246 |
def Iq(q, intercept, slope):
"""
:param q: Input q-value
:param intercept: Intrecept in linear model
:param slope: Slope in linear model
:return: Calculated Intensity
"""
inten = intercept + slope*q
return inten | af3e580e6061089b431ef25f1f08def6f29c8ef6 | 3,651,247 |
import os
import logging
import math
import numpy
import audioop
def read_sph(input_file_name, mode='p'):
"""
Read a SPHERE audio file
:param input_file_name: name of the file to read
:param mode: specifies the following (\* =default)
.. note::
- Scaling:
- ... | 4d06b14fffc8203c2ac0ec0a3c1086cc0904d193 | 3,651,248 |
import os
import pathlib
import yaml
def unpack(path, catalog_name):
"""
Place a catalog configuration file in the user configuration area.
Parameters
----------
path: Path
Path to output from pack
catalog_name: Str
A unique name for the catalog
Returns
-------
co... | ae40f5d9f9521e6df34b598c034d657b8239a389 | 3,651,249 |
def psi4ToStrain(mp_psi4, f0):
"""
Convert the input mp_psi4 data to the strain of the gravitational wave
mp_psi4 = Weyl scalar result from simulation
f0 = cutoff frequency
return = strain (h) of the gravitational wave
"""
#TODO: Check for uniform spacing in time
t0 = mp_psi4[:, 0]
list_len = len(t0)
comple... | 4ab3320a44bd10403e73015e4a215142529b8029 | 3,651,250 |
def get_optimizer(library, solver):
"""Constructs Optimizer given and optimization library and optimization
solver specification"""
options = {
'maxiter': 100
}
if library == 'scipy':
optimizer = optimize.ScipyOptimizer(method=solver, options=options)
elif library == 'ipopt':
... | be72fc9115abf0d087049debe470139b248ef47f | 3,651,251 |
def _cast_query(query, col):
"""
ALlow different query types (e.g. numerical, list, str)
"""
query = query.strip()
if col in {"t", "d"}:
return query
if query.startswith("[") and query.endswith("]"):
if "," in query:
query = ",".split(query[1:-1])
return [... | 4b6cfc823f8b2e78f343e73683b418112e66f43d | 3,651,252 |
import torch
def binary_loss(pred_raw,
label_raw,
loss_func,
weight=None,
class_weight=None,
class_weight_norm=False,
reduction='mean',
avg_factor=None,
smooth=1.0):
"""
:param pred:... | 9154c8e46a48485e643de496554d302f9db294ac | 3,651,253 |
import os
import uuid
def picture_upload_to(instance, filename):
"""
Returns a unique filename for picture which is hard to guess.
Will use uuid.uuid4() the chances of collision are very very very low.
"""
ext = os.path.splitext(filename)[1].strip('.')
if not ext:
ext = 'jpg'
filen... | 0bdaa002105cdbc85c68019eebe1c6f54ab9173f | 3,651,254 |
def showerActivityModel(sol, flux_max, b, sol_max):
""" Activity model taken from: Jenniskens, P. (1994). Meteor stream activity I. The annual streams.
Astronomy and Astrophysics, 287., equation 8.
Arguments:
sol: [float] Solar longitude for which the activity is computed (radians).
... | 0a4cc6d8c490b36412140cfeeca0c30464c11577 | 3,651,255 |
import os
def create_directories(directory_name):
"""
Create directories
"""
# Create directory
try:
# Create target Directory
os.mkdir(directory_name)
logger.info("Directory %s Created", directory_name)
except FileExistsError:
logger.info("Directory %s already... | 453399c5e5b4200478c14d414efdd7a4cf8ced1f | 3,651,256 |
import json
def request_slow_log(db_cluster_id, start_datetime, end_datetime, page_number, page_size):
"""
请求慢SQL日志
:param db_cluster_id:
:param start_datetime:
:param end_datetime:
:param page_number:
:param page_size:
:return:
"""
request = DescribeSlowLogRecordsRequest()
... | e49a006e59f04067eb43f72dfcd29fd71def4fb1 | 3,651,257 |
def pad_omni_image(image, pad_size, image_dims=None):
"""Pad an omni-directional image with the correct image wrapping at the edges.
Parameters
----------
image
Image to perform the padding on *[batch_shape,h,w,d]*
pad_size
Number of pixels to pad.
image_dims
Image dimen... | e54d732508bea3f969eb2a78ec3238e88e33a30f | 3,651,258 |
from typing import Any
def add_film(
film: FilmCreate,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
) -> Any:
"""
Add new film
"""
if not user.role.can_add_films:
raise ForbiddenAction
db_film = db.query(Film).filter(Film.name == film.name).first()
... | 510f80969570e186233a6313277093b6d939a9ea | 3,651,259 |
def load_cube_file(lines, target_mode=None, cls=ImageFilter.Color3DLUT):
"""Loads 3D lookup table from .cube file format.
:param lines: Filename or iterable list of strings with file content.
:param target_mode: Image mode which should be after color transformation.
The default is No... | bf87c0e686b689a429297bae4ec84402dd12dc3d | 3,651,260 |
import torch
def vector_to_Hermitian(vec):
"""Construct a Hermitian matrix from a vector of N**2 independent
real-valued elements.
Args:
vec (torch.Tensor): (..., N ** 2)
Returns:
mat (ComplexTensor): (..., N, N)
""" # noqa: H405, D205, D400
N = int(np.sqrt(vec.shape[-1]))
... | 8bd32d93e9865305a8f75711d72990beaea5d897 | 3,651,261 |
import os
import yaml
import plistlib
def new_recipe(argv):
"""Makes a new recipe template"""
verb = argv[1]
parser = gen_common_parser()
parser.set_usage(
f"Usage: %prog {verb} [options] recipe_pathname\n" "Make a new template recipe."
)
# Parse arguments
parser.add_option("-i",... | 598577761487497a65f2bb6bdd16c308859af278 | 3,651,262 |
def view_payment(request):
""" A view that renders the payment page template """
user = request.user
# Check if user has already paid and redirect them to definitions app.
if user.has_perm('definitionssoftware.access_paid_definitions_app'):
return redirect(reverse('view_definitionssoftware'))
... | fc86a79c759bc4e4005d634b5c9a204473a3a3a7 | 3,651,263 |
def augment_bag(store, bag, username=None):
"""
Augment a bag object with information about it's policy type.
"""
if not bag.store:
bag = store.get(bag)
if not username:
username = bag.policy.owner
policy_type = determine_tank_type(bag, username)
bag.icon = POLICY_ICONS[polic... | 1fbda85f3db346e46e52b86d2d4b5784f8c4d2ab | 3,651,264 |
from typing import Dict
def province_id_to_home_sc_power() -> Dict[utils.ProvinceID, int]:
"""Which power is this a home sc for?"""
content = get_mdf_content(MapMDF.STANDARD_MAP)
home_sc_line = content.splitlines()[2]
tag_to_id = _tag_to_id(get_mdf_content(MapMDF.STANDARD_MAP))
# Assume powers are ordered ... | f87081ce053e3a50bb48deaae28b0e919e224216 | 3,651,265 |
def evaluate_cubic_spline(x, y, r, t):
"""Evaluate cubic spline at points.
Parameters:
x : rank-1 np.array of np.float64
data x coordinates
y : rank-1 np.array of np.float64
data y coordinates
r : rank-1 np.array of np.float64
output of solve_coeffs()... | 52d6c4ac0440da88ee908bc0a6cfa2b755ca606f | 3,651,266 |
def get_username(host, meta_host, config):
"""Find username from sources db/metadata/config."""
username = host.username or meta_host.get("username")
if is_windows_host(meta_host):
username = username or "Administrator"
default_user = get_config_value(config["users"], meta_host["os"])
usern... | 4e220816442e64d43f1da15aa0bd19508e186f19 | 3,651,267 |
def get_all_tests():
"""
Collect all tests and return them
:return: A test suite as returned by xunitparser with all the tests
available in the w3af framework source code, without any selectors.
"""
return _get_tests('all.xml') | 11acff501fb717ac5c9bdc16343742f124f2a120 | 3,651,268 |
def main():
"""Builds OSS-Fuzz project's fuzzers for CI tools.
Note: The resulting fuzz target binaries of this build are placed in
the directory: ${GITHUB_WORKSPACE}/out
Returns:
0 on success or nonzero on failure.
"""
return build_fuzzers_entrypoint() | cd7c386c2a5d126c0abc1504a1cb3dfe6026173c | 3,651,269 |
def find_first_img_dim(import_gen):
"""
Loads in the first image in a provided data set and returns its dimensions
Intentionally returns on first iteration of the loop
:param import_gen: PyTorch DataLoader utilizing ImageFolderWithPaths for its dataset
:return: dimensions of image
"""
for x,... | 3ccaccdfb20d7b2ca4d339adacd3c706a460fdef | 3,651,270 |
def restaurantJSON():
""" Returns all restaurants by JSON call """
restaurants = session.query(Restaurant)
return jsonify(Restaurants=[r.serialize for r in restaurants]) | 350df909de7798da9567a7fe0a972d660c40ff8c | 3,651,271 |
def _to_histogram_plotgroup(use_spec, plotgroup_id, plot_id, read_type, bincounts, output_dir, png_name):
"""
Create a histogram of length distribution.
"""
plot_spec = use_spec.get_plot_spec(plotgroup_id, plot_id)
png_file = op.join(output_dir, png_name)
png, thumb = plot_read_lengths_binned(bi... | 18ae412af24800098ec2c01c9ba5c456455540f5 | 3,651,272 |
def prepare_string(x, max_length=None):
""" Converts a string from LaTeX escapes to UTF8 and truncates it to max_length """
# data = latex2text(x, tolerant_parsing=True)
try:
data = latex_to_unicode(filter_using_re(x))
if max_length is not None:
data = (data[:max_length-5] + '[..... | 043d0d063e22ef18943459a7ba0a8928244bca12 | 3,651,273 |
import math
def q_b(m0, m1, m2, n0, n1, n2):
"""Stretch"""
return math.sqrt((m0 - n0)**2 + (m1 - n1)**2 + (m2 - n2)**2) | 61cf1b5eec6c89be7f822cbdbc03564b805a1920 | 3,651,274 |
def poly_union(poly_det, poly_gt):
"""Calculate the union area between two polygon.
Args:
poly_det (Polygon): A polygon predicted by detector.
poly_gt (Polygon): A gt polygon.
Returns:
union_area (float): The union area between two polygons.
"""
assert isinstance(poly_det, ... | fbd13a9b1ef4acee27fac7d04b00fc1cfc46ca08 | 3,651,275 |
def get_stoich(geom_i, geom_j):
""" get the overall combined stoichiometry
"""
form_i = automol.geom.formula(geom_i)
form_j = automol.geom.formula(geom_j)
form = automol.formula.join(form_i, form_j)
stoich = ''
for key, val in form.items():
stoich += key + str(val)
return stoic... | eaba89508d7c913a77ebf91097d620dc6fdff5a6 | 3,651,276 |
import requests
from bs4 import BeautifulSoup
def get_all_text(url):
"""Retrieves all text in paragraphs.
:param str url: The URL to scrap.
:rtype: str :return: Text in the URL.
"""
try:
response = requests.get(url)
# If the response was successful, no Exception will be raised
... | 364150aee7c1c093367d3d95bc5c0836dde978db | 3,651,277 |
from typing import List
def metadata_partitioner(rx_txt: str) -> List[str]:
"""Extract Relax program and metadata section.
Parameters
----------
rx_txt : str
The input relax text.
Returns
-------
output : List[str]
The result list of partitioned text, the first element
... | dd09aff9ea517813d43ff307fb9fc425b7338943 | 3,651,278 |
def make_aware(value, timezone):
"""
Makes a naive datetime.datetime in a given time zone aware.
"""
if hasattr(timezone, 'localize'):
# available for pytz time zones
return timezone.localize(value, is_dst=None)
else:
# may be wrong around DST changes
return value.rep... | b466b4fda2daf54b7aa5e8f00ad7b10397e61c7b | 3,651,279 |
def to_dict(funs):
"""Convert an object to a dict using a dictionary of functions.
to_dict(funs)(an_object) => a dictionary with keys calculated from functions on an_object
Note the dictionary is copied, not modified in-place.
If you want to modify a dictionary in-place, do adict.update(to_dict(funs)... | d22bbcb3c1913361c3906fd2e7f3d254dc67de28 | 3,651,280 |
import re
def parse_duration_string_ms(duration):
"""Parses a duration string of the form 1h2h3m4s5.6ms4.5us7.8ns into milliseconds."""
pattern = r'(?P<value>[0-9]+\.?[0-9]*?)(?P<units>\D+)'
matches = list(re.finditer(pattern, duration))
assert matches, 'Failed to parse duration string %s' % duration
times... | da2981590d70f32ee3514873602621a77b70cbe2 | 3,651,281 |
def fin(activity):
"""Return the end time of the activity. """
return activity.finish | ed5b1d1e0f29f403cfee357a264d05d5cc88093e | 3,651,282 |
def unfreeze_map(obj):
"""
Unfreezes all elements of mappables
"""
return {key: unfreeze(value) for key, value in obj.items()} | 2ba48f6cf89f44001b7940076c4763dc820d9aa1 | 3,651,283 |
from typing import Optional
from typing import Union
from datetime import datetime
def get_date(
value: Optional[Union[date, datetime, str]],
raise_error=False
) -> Optional[date]:
"""
Convert a given value to a date.
Args:
raise_error: flag to raise error if return is None or not
... | 501b2363aa2d40f16f6144995db8d840e62f750a | 3,651,284 |
import os.path, os
def make_working_directories ():
""" Creates directories that we will be working in.
In particular, we will have DOC_ROOT/stage-PID and
DOC_ROOT/packages-PID """
global doc_root
stage_dir = os.path.join (doc_root, "stage-" + str (os.getpid ()))
package_dir = os.path.join (d... | e92fb9f27c5c7b13d1666175ea89705c473d8323 | 3,651,285 |
def k_param(kguess, s):
"""
Finds the root of the maximum likelihood estimator
for k using Newton's method. Routines for using Newton's method
exist within the scipy package but they were not explored. This
function is sufficiently well behaved such that we should not
have problems solving for k... | 24df48746d53fd4573db10093065e7b49d5c7bfe | 3,651,286 |
def hex_to_bin(value: hex) -> bin:
"""
convert a hexadecimal to binary
0xf -> '0b1111'
"""
return bin(value) | b82c4fea08fc258a3b50be9a5e77b3d076a33459 | 3,651,287 |
def four_oneports_2_twoport(s11: Network, s12: Network, s21: Network, s22: Network, *args, **kwargs) -> Network:
"""
Builds a 2-port Network from list of four 1-ports
Parameters
----------
s11 : one-port :class:`Network`
s11
s12 : one-port :class:`Network`
s12
s21 : one-port... | 2f8b365b2ccb06c252337630f6e34b794a3a3eba | 3,651,288 |
def find_xml_command(rvt_version, xml_path):
"""
Finds name index src path and group of Commands in RevitPythonShell.xml configuration.
:param rvt_version: rvt version to find the appropriate RevitPythonShell.xml.
:param xml_path: path where RevitPythonShell.xml resides.
:return: Commands dictionary... | 1effc1b313d93e92b25deef1d62fc65c8f3e6975 | 3,651,289 |
import mimetypes
def put_data_to_s3(data, bucket, key, acl=None):
"""data is bytes not string"""
content_type = mimetypes.guess_type(key)[0]
if content_type is None:
content_type = 'binary/octet-stream'
put_object_args = {'Bucket': bucket, 'Key': key, 'Body': data,
'Cont... | 042fc8eea230559efdc60ca9f18db2e9d1766286 | 3,651,290 |
from pathlib import Path
def join_analysis_json_path(data_path: Path, analysis_id: str, sample_id: str) -> Path:
"""
Join the path to an analysis JSON file for the given sample-analysis ID combination.
Analysis JSON files are created when the analysis data is too large for a MongoDB document.
:param... | 5ae25e5c0df4801b23a34cdac09db709733844ca | 3,651,291 |
def user_profile(uname=None):
"""
Frontend gets user's profile by user name or modify user profile (to do).
Return user's complete profile and the recommendations for him (brief events).
:param uname: user's name, a string
:return: a json structured as {'user': [(0, 'who', 'password', 'email@student... | b43ab64b0d44e7d19342a90da261bf96489fed3a | 3,651,292 |
def circuit_status(self, handle: ResultHandle) -> CircuitStatus:
"""
Return a CircuitStatus reporting the status of the circuit execution
corresponding to the ResultHandle
"""
if handle in self._cache:
return CircuitStatus(StatusEnum.COMPLETED)
raise CircuitNotRunError(handle) | 7de17e03e3177f7b7c2de31650a0c341ab7e4fa6 | 3,651,293 |
import os
import json
def run_pyfunnel(test_dir):
"""Run pyfunnel compareAndReport function.
The test is run:
* with the parameters, reference and test values from the test directory
passed as argument;
* from current directory (to which output directory path is relative).
Args:
... | ef88e40aad9be05dbfdb4f281b9cb1c5b934d49e | 3,651,294 |
def get_portfolio() -> pd.DataFrame:
"""
Get complete user portfolio
Returns:
pd.DataFrame: complete portfolio
"""
portfolio = get_simple_portfolio()
full_portfolio = pd.DataFrame()
for ticket in portfolio.index:
full_portfolio = full_portfolio.append(
_clea... | c04df5cf88e936cab9bd7f30a63ab3e695efd771 | 3,651,295 |
def findZeros( vec, tol = 0.00001 ):
"""Given a vector of a data, finds all the zeros
returns a Nx2 array of data
each row is a zero, first column is the time of the zero, second column indicates increasing
or decreasing (+1 or -1 respectively)"""
zeros = []
for i in range( vec.size - ... | 173f734c9b3abf876b48d194e691b517fd0ec816 | 3,651,296 |
from typing import List
def get_index(square_num: int) -> List[int]:
"""
Gets the indices of a square given the square number
:param square_num: An integer representing a square
:return: Returns a union with 2 indices
"""
for i in range(4):
for j in range(4):
if puzzle_st... | e9896ba58b76ea43069b408a445720f0b418488d | 3,651,297 |
def _ResolveName(item):
"""Apply custom name info if provided by metadata"""
# ----------------------------------------------------------------------
def IsValidName(value):
return bool(value)
# ----------------------------------------------------------------------
if Attributes.UNIVERSAL... | 0d303cb4577503b4e39f14da699cf77c9adf462f | 3,651,298 |
import re
def extract_errno(errstr):
"""
Given an error response from a proxyfs RPC, extracts the error number
from it, or None if the error isn't in the usual format.
"""
# A proxyfs error response looks like "errno: 18"
m = re.match(PFS_ERRNO_RE, errstr)
if m:
return int(m.group(... | adff11595d391a1bb4403c3c93a0bb4ab182254a | 3,651,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.