content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def retrieve_tensors(logdir, groups=["train", "valid"]):
"""
Grab all tensorboard tensors and put them in one loss dataframe
Parameters
----------
logdir : str
Directory containing summary log of loss for tensorboard
groups : list, optional
groups containing tensors ... | e8a7d7a6d0626a66682c61a25bb7fb79b62cc186 | 32,800 |
def get_page_index(obj, amongst_live_pages=True):
"""
Get oage's index (a number) within its siblings.
:param obj:
Wagtail page object
:param amongst_live_pages:
Get index amongst live pages if True or all pages if False.
:return:
Index of a page if found or None if page d... | fd1950533a398019ab0d3e208a1587f86b134a13 | 32,801 |
import requests
def contact_ocsp_server(certs):
"""Sends an OCSP request to the responding server for a certificate chain"""
chain = convert_to_oscrypto(certs)
req = create_ocsp_request(chain[0], chain[1])
URI = extract_ocsp_uri(certs[0])
data = requests.post(URI, data=req, stream=True, headers={'... | 15c32e72d41e6db275f5ef1d91ee7ccf05eb8cde | 32,802 |
import warnings
def reset_index_inplace(df: pd.DataFrame, *args, **kwargs) -> pd.DataFrame:
"""
Return the dataframe with an inplace resetting of the index.
This method mutates the original DataFrame.
Compared to non-inplace resetting, this avoids data copying, thus
providing a potential speedup... | 6c10d67ffdaf195c0a9eea3ae473bb0e93e6e9ef | 32,803 |
import errno
import os
def load_mapping():
"""Load the mapping from the disk.
If the configuration directory files do not exist (probably because it is
the user's first time executing a dtags command), create them.
:return: the mapping object loaded from the disk
"""
try:
# Parse and... | a81189c9ed01df8970888bf9f3292cd10a9247b5 | 32,804 |
def get_current_user():
"""Get the current logged in user, or None."""
if environment.is_local_development():
return User('user@localhost')
current_request = request_cache.get_current_request()
if local_config.AuthConfig().get('enable_loas'):
loas_user = current_request.headers.get('X-AppEngine-LOAS-Pe... | 3b80285c87358dc33595ca97ecee3cf38cf96034 | 32,805 |
import calendar
import time
def genericGetCreationDate(page):
"""
Go to each date position and attempt to get date
"""
randSleep()
allDates = []
signaturePositions = findSignatures(page)
for p in signaturePositions:
timestamp = getTimestampFromSERP(p, page)
# print('times... | 3d3f6e9a0b1ce9b49f887ba4d1d99493b75d2f9e | 32,806 |
def depth(data):
"""
For each event, it finds the deepest layer in which the shower has
deposited some E.
"""
maxdepth = 2 * (data[2].sum(axis=(1, 2)) != 0)
maxdepth[maxdepth == 0] = 1 * (
data[1][maxdepth == 0].sum(axis=(1, 2)) != 0
)
return maxdepth | aa48c88c516382aebe2a8b761b21f650afea82b1 | 32,807 |
import sys
def python_obj_size(obj, humanize=True):
""" 获取一个python对象的大小,默认返回人可读的形式 """
if humanize:
return humanize_bytes(sys.getsizeof(obj))
else:
return sys.getsizeof(obj) | 39da1f8148247828b279486c25c80cd45f46a2db | 32,808 |
def transform_user_extensions(user_extension_json):
"""
Transforms the raw extensions JSON from the API into a list of extensions mapped to users
:param user_extension_json: The JSON text blob returned from the CRXcavator API
:return: Tuple containing unique users list, unique extension list, and exten... | 89d91781028eb4335fff2c9bca446f50b5e91a3f | 32,809 |
def shower_array_rot(shower_array, alt, az):
"""
Given a series of point on the Z axis, perform a rotation of alt around Y and az around Z
Parameters
----------
shower_array: numpy array of shape (N,3) giving N points coordinates
alt: altitude shower direction - float
az: azimuth shower dir... | d98a6a4589b8945e8dff1272608307915f499fd6 | 32,810 |
from typing import Optional
def get_dscp_configuration(dscp_configuration_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDscpConfigurationResult:
"""
Use this data source t... | 80e0a388581cd7028c7a8351737808e578778611 | 32,811 |
def aggregate_returns(df_daily_rets, convert_to):
"""
Aggregates returns by week, month, or year.
Parameters
----------
df_daily_rets : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet (returns).
convert_to : str
... | 7ccf2763420df055a59f15b679ba2c8265744a41 | 32,812 |
import argparse
def parse_args(args):
"""Parse the command line arguments."""
parser = argparse.ArgumentParser(
description='STOMP client for Network Rail\'s public data.'
)
subparsers = parser.add_subparsers()
# Creation of new configuration files
create_parser = subparsers.add_parser... | 632b3702f6a3b3837b58ca39b7290081e7a3fb94 | 32,813 |
import random
def impute(x,nu):
"""
Impute to missing values: for each row of x this function find the nearest row in eucledian distance
in a sample of nu rows of x and replace the missing value of the former row
with the corrisponding values of the... | e13562e28eaafcfaa7848eae9cca7ac9d435d1f4 | 32,814 |
def get_data_splits(comment_type_str=None, ignore_ast=False):
"""Retrieves train/validation/test sets for the given comment_type_str.
comment_type_str -- Return, Param, Summary, or None (if None, uses all comment types)
ignore_ast -- Skip loading ASTs (they take a long time)"""
dataset, high_level... | b9451c5539c7ce235b7bb7f3251e3caa8e4b77c7 | 32,815 |
from typing import Tuple
def get_slide_roi_masks(slide_path, halo_roi_path, annotation_name, slide_id:str=None,
output_dir:str=None) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""get roi masks from slides
Given a slide, halo annotation xml file, generate labels from xml polygons,
then crop ... | b79e9b8d93416c404110b56582b4ae1e9030bd7c | 32,816 |
def generate_stop_enex_nb(entries: tp.Array2d,
ts: tp.Array,
stop: tp.MaybeArray[float],
trailing: tp.MaybeArray[bool],
entry_wait: int,
exit_wait: int,
pick_first:... | a34108bd324498e70155f5dcc8c8c4364982c43f | 32,817 |
def mangle_type(typ):
"""
Mangle Numba type
"""
if typ in N2C:
typename = N2C[typ]
else:
typename = str(typ)
return mangle_type_c(typename) | 944952e184d1d33f9424c9e1118920f69f757e86 | 32,818 |
def lorentz(sample_len=1000, sigma=10, rho=28, beta=8 / 3, step=0.01):
"""This function generates a Lorentz time series of length sample_len,
with standard parameters sigma, rho and beta.
"""
x = np.zeros([sample_len])
y = np.zeros([sample_len])
z = np.zeros([sample_len])
# Initial conditi... | c8dc9de84dde15453fe99ed8fb55eddcdd628648 | 32,819 |
def draw_lane_lines_on_all_images(images, cols=2, rows=3, figsize=(15, 13)):
"""
This method calls draw_windows_and_fitted_lines Fn for each image and then show the grid of output images.
"""
no_of_images = len(images)
fig, axes = plt.subplots(rows, cols, figsize=figsize)
indexes = range(cols * r... | 27975a95836b784fece0547375b4d79868bbd3b6 | 32,820 |
import re
def get_field_order(address, latin=False):
"""
Returns expected order of address form fields as a list of lists.
Example for PL:
>>> get_field_order({'country_code': 'PL'})
[[u'name'], [u'company_name'], [u'street_address'], [u'postal_code', u'city']]
"""
rules = get_validation_r... | d86c36ab1026fdad6e0b66288708786d8d2cb906 | 32,821 |
def env_start():
""" returns numpy array """
global maze, current_position
current_position = 500
return current_position | ed377adedc48159607a4bb08ea6e3624575ec723 | 32,822 |
def bootstrap_acceleration(d):
""" Bootstrap (BCA) acceleration term.
Args:
d : Jackknife differences
Returns:
a : Acceleration
"""
return np.sum(d**3) / np.sum(d**2)**(3.0/2.0) / 6.0 | fbd9a05934d4c822863df0ba0b138db840f34955 | 32,823 |
def normalize_map(x):
"""
normalize map input
:param x: map input (H, W, ch)
:return np.ndarray: normalized map (H, W, ch)
"""
# rescale to [0, 2], later zero padding will produce equivalent obstacle
return x * (2.0/255.0) | f750df26c8e6f39553ada82e247e21b2e3d6aabd | 32,824 |
def today():
"""Get the today of int date
:return: int date of today
"""
the_day = date.today()
return to_int_date(the_day) | 81c497cdf33050b6e8de31b0098d10acfb555444 | 32,825 |
from datetime import datetime
def contact(request):
"""Renders the contact page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/contact.html',
{
'title':'联系我们',
'message':'你可以通过以下方式和我们取得联系',
'year':datetime.now().year,
... | 65056534556a8503d897b38468b43da968d4223d | 32,826 |
import math
def plagdet_score(rec, prec, gran):
"""Combines recall, precision, and granularity to a allow for ranking."""
if (rec == 0 and prec == 0) or prec < 0 or rec < 0 or gran < 1:
return 0
return ((2 * rec * prec) / (rec + prec)) / math.log(1 + gran, 2) | f8debf876d55296c3945d0d41c7701588a1869b6 | 32,827 |
def continuum(spec,bin=50,perc=60,norder=4):
""" Derive the continuum of a spectrum."""
nx = len(spec)
x = np.arange(nx)
# Loop over bins and find the maximum
nbins = nx//bin
xbin1 = np.zeros(nbins,float)
ybin1 = np.zeros(nbins,float)
for i in range(nbins):
xbin1[i] = np.mean(x[i... | 42709c9361707ef8b614030906e9db5ea38087b3 | 32,828 |
def mean_IoU(Y_true, Y_pred):
"""
Calculate the mean IoU score between two lists of labeled masks.
:param Y_true: a list of labeled masks (numpy arrays) - the ground truth
:param Y_pred: a list labeled predicted masks (numpy arrays) for images with the original dimensions
:return: mean IoU score for... | 79581b1015512653f428a93c0e61cd5d451f031e | 32,829 |
def get_matrix_header(filename):
"""
Returns the entries, rows, and cols of a matrix market file.
"""
with open(filename) as f:
entries = 0
rows = 0
cols = 0
for line in f.readlines():
if line.startswith('%'):
continue
line = line.s... | 66200661715cb9a67522ced7b13d4140a3905c28 | 32,830 |
def get_slot_names(slotted_instance):
"""Get all slot names in a class with slots."""
# thanks: https://stackoverflow.com/a/6720815/782170
return slotted_instance.__slots__ | bd0f5b58964444396ceae7facb916012a4fb7c8a | 32,831 |
def make_standard_fisher_regularizer(make_logits, scope, should_regularize,
perturbation, differentiate_probability):
"""Creates per-example logits and the per-example standard Fisher-Rao norm.
This function assumes the model of a categorical distribution generated by a
softm... | b8edc41ccce39511e147fdfeb919c30ad65e8a85 | 32,832 |
def objective(y_objective, sim_param, curve_param):
"""
Calculates the objective function (RMS-VIF) given the control point y-values of a given particle
:param y_objective: control point y-values of the particle
:param sim_param: Instance of sim_param
:param curve_param: Instance of curve_param
... | 8191aa0cc346ea596c88d3cdff86c3a3abc3ccca | 32,833 |
def form_poisson_equation_impl(height, width, alpha, normals, depth_weight, depth):
"""
Creates a Poisson equation given the normals and depth at every pixel in image.
The solution to Poisson equation is the estimated depth.
When the mode, is 'depth' in 'combine.py', the equation should return the actua... | 56b94e106f6035af94489a9e40a2c17ef40ab7d8 | 32,834 |
def shortest_first_name(names):
"""Returns the shortest first name (str)"""
names = dedup_and_title_case_names(names)
name_dict = []
for i in names:
i = i.split()
name_dict.append({'name':i[0], 'surname': i[1]})
short_name_sort = sorted(name_dict, key=lambda k: len(k['name']))
re... | 868d5d977d4ef3aa4264fa1644ca5f142920bbe4 | 32,835 |
def timezone_validator(self, response):
"""Match timezone code in libraries/timezone.
Arguments
---------
response: "String containing current answer"
Raises
------
ValidationError: "Display a short description with available formats"
Returns
-------
boolean: True
... | 080e56256a72a254e1c5940d16a5a89b693a3ad6 | 32,836 |
def reset_clb_srv(req):
"""
Service when reset of state planner
:param req:
:return:
"""
global reset_pose, pose_msgs , goal_sub, global_offset
rospy.loginfo_once("reset pose")
resp = TriggerResponse()
resp.success = True
resp.message = "Reset pose: True"
reset_pose = pose... | 14deae77fd35fa256760164978eacf7cee1421ad | 32,837 |
import tkinter
def Calcola():
"""Calcolate point of task!"""
esci=False
while esci is False:
try:
check=False
while check is False:
DeadLine=input("inserisci la deadline in giorni ")
try:
DeadLine = int(DeadLine)
... | 7f9d03a2c45a3dd06172368213000c38ffa6532d | 32,838 |
import six
def disabled(name):
"""
Ensure an Apache module is disabled.
.. versionadded:: 2016.3.0
name
Name of the Apache module
"""
ret = {"name": name, "result": True, "comment": "", "changes": {}}
is_enabled = __salt__["apache.check_mod_enabled"](name)
if is_enabled:
... | edc69d3ad8b03c739a01e28d50aacbf00db54d9c | 32,839 |
def get_stops_in_polygon(feed, polygon, geo_stops=None):
"""
Return the slice of ``feed.stops`` that contains all stops that lie
within the given Shapely Polygon object that is specified in
WGS84 coordinates.
Parameters
----------
feed : Feed
polygon : Shapely Polygon
Specified ... | cf42652a1a00f9f70f51d5bc9597733ca9d89cf6 | 32,840 |
def define_stkvar(*args):
"""
define_stkvar(pfn, name, off, flags, ti, nbytes) -> bool
Define/redefine a stack variable.
@param pfn: pointer to function (C++: func_t *)
@param name: variable name, NULL means autogenerate a name (C++: const
char *)
@param off: offset of the stack variabl... | bbd52e35a92dcd84afe990e0519a2a5e26abe5b8 | 32,841 |
def spherical_polar_area(r, lon, lat):
"""Calculates the area bounding an array of latitude and longitude points.
Parameters
----------
r : float
Radius of sphere.
lon : 1d array
Longitude points. [Degrees]
lat : 1d array
Longitude points. [Degrees]
Returns
----... | a07b73f6e04ee64b06d1e663dfff7ff971d00bf5 | 32,842 |
def row_plays(hand, row):
"""Return the set of legal plays in the specified row.
A row play is a (start, 'WORD') pair,
"""
results = set()
# for each anchor and for each legal prefix, add all legal suffixes and save any valid words in results
for (i, square) in enumerate(row[1: -1], start=1):
... | 5b98f30fb8a932f31bc9bc0b22f21480880c3302 | 32,843 |
def nearest_pillar(grid, xy, ref_k0 = 0, kp = 0):
"""Returns the (j0, i0) indices of the primary pillar with point closest in x,y plane to point xy."""
# note: currently works with unmasked data and using primary pillars only
pe_i = grid.extent_kji[2] + 1
sum_dxy2 = grid.pillar_distances_sqr(xy, ref_k0... | 2338698963cb6bddca8d9702e000e5be125e6e86 | 32,844 |
def read_state(file, statename):
""" read and select state from file
Args:
file (str): path to state shapefile
statename (str): name of state (i.e. California)
"""
all = gpd.read_file("../data/states.shp")
state = all[all['STATE_NAME'] == statename]
return state | 0732d01dfb466ac00622964dfd3a9d0655367fbf | 32,845 |
def get_random_state(seed):
"""
Get a random number from the whole range of large integer values.
"""
np.random.seed(seed)
return np.random.randint(MAX_INT) | abf99c5547d146bfc9e6e1d33e7970d7090ba6d2 | 32,846 |
def get_start_and_end_time(file_or_file_object):
"""
Returns the start and end time of a MiniSEED file or file-like object.
:type file_or_file_object: str or file
:param file_or_file_object: MiniSEED file name or open file-like object
containing a MiniSEED record.
:return: tuple (start time... | 4c094a8fb1d9e186a0bbcbff25b7af8ac5461131 | 32,847 |
from typing import Optional
import json
import asyncio
async def send_message(msg: str) -> Optional[str]:
"""
Send a message to the websocket and return the response
Args:
msg: The message to be sent
Returns:
The response message or None if it was not defined
"""
if not (WS a... | d6395c3f74baf1900d99f605a08b77990637be8e | 32,848 |
def _getname(storefile):
"""returns the filename"""
if storefile is None:
raise ValueError("This method cannot magically produce a filename when given None as input.")
if not isinstance(storefile, basestring):
if not hasattr(storefile, "name"):
storefilename = _getdummyname(store... | fa423102a3ff8355af4784eaa39b2a065da80ec4 | 32,849 |
def flow_lines(sol, nlines, time_length, scale=0.5):
"""
compute the flow lines of the solution
Parameters
----------
sol : :py:class:`Simulation<pylbm.simulation.Simulation>`
the solution given by pylbm
nlines : int (number of flow lines)
time_length : double (time during which we ... | fea6667aa8b3012918a66ae3f6e94b9b0a4439ad | 32,850 |
def minOperations(n):
""" finds min. operations to reach and string """
if type(n) != int or n <= 1:
return 0
res = 0
i = 2
while(i <= n + 1):
if (n % i == 0):
res += i
n /= i
else:
i += 1
return res | c26cbd71c6e675adea79938b6e7248a4c093e63f | 32,851 |
def matrix2dictionary(matrix):
"""
convert matrix to dictionary of comparisons
"""
pw = {}
for line in matrix:
line = line.strip().split('\t')
if line[0].startswith('#'):
names = line[1:]
continue
a = line[0]
for i, pident in enumerate(line[1:]... | fd53dc4f80ff45d4eb41939af54be1d712ee2fa4 | 32,852 |
def combine_fastq_output_files(files_to_combine, out_prefix, remove_temp_output):
""" Combines fastq output created by BMTagger/bowtie2 on multiple databases and
returns a list of output files. Also updates the log file with read counts for the
input and output files.
"""
# print out the read... | 1421878edf7e44b46b386d7d4465090cc22acfa4 | 32,853 |
import json
def deliver_dap():
"""
Endpoint for submissions only intended for DAP. POST request requires the submission JSON to be uploaded
as "submission" and the filename passed in the query parameters.
"""
logger.info('Processing DAP submission')
filename = request.args.get("filename")
... | e7c2753319f512eaa1328fcb3cc808a17a5933b8 | 32,854 |
def api_run_delete(run_id):
"""Delete the given run and corresponding entities."""
data = current_app.config["data"] # type: DataStorage
RunFacade(data).delete_run(run_id)
return "DELETED run %s" % run_id | c2a07caa95d9177eb8fe4b6f27caf368d1a9fbdd | 32,855 |
import numpy
def gfalternate_createdataandstatsdict(ldt_tower,data_tower,attr_tower,alternate_info):
"""
Purpose:
Creates the data_dict and stat_dict to hold data and statistics during gap filling from
alternate data sources.
Usage:
Side effects:
Called by:
Calls:
Author: PRI
... | a1690fb9e53abcd6b23e33046d82c10a2ca7abc0 | 32,856 |
import re
def doGeneMapping(model):
"""
Function that maps enzymes and genes to reactions
This function works only if the GPR associations are defined
as follows: (g1 and g2 and g6) or ((g3 or g10) and g12)
- *model* Pysces model
- *GPRdict* dictionary with ... | d2e12f7161aca69afa28f7bb0d528d9b922b25b4 | 32,857 |
def delay_to_midnight():
"""Calculates the delay between the current time and midnight"""
current_time = get_current_time()
delay = time_conversions.hhmm_to_seconds("24:00") - time_conversions.hhmm_to_seconds(current_time)
return delay | 14b33591e58975cd5a4f95d3602e6a1494131267 | 32,858 |
def predict(model, imgs):
"""
Predict the labels of a set of images using the VGG16 model.
Args:
imgs (ndarray) : An array of N images (size: N x width x height x channels).
Returns:
preds (np.array) : Highest confidence value of the predictio... | 0f992412a9067608e99a6976c6ef65b466ef7572 | 32,859 |
def get_last_query_records_count(connection: psycopg2_connection):
"""
Returns the number of rows that were loaded by the last COPY command run in the current session.
"""
# TODO: handle array extraction of rows num , handle NONE
result_set = redshift_query(connection, COPY_ROWS_COUNT_QUERY)
if ... | 65ea989fef25be6e0ba6b275eec1315b258ea618 | 32,860 |
def _endmsg(rd) -> str:
"""
Returns an end message with elapsed time
"""
msg = ""
s = ""
if rd.hours > 0:
if rd.hours > 1:
s = "s"
msg += colors.bold(str(rd.hours)) + " hour" + s + " "
s = ""
if rd.minutes > 0:
if rd.minutes > 1:
s = "s"
... | 635792c4ebf772926f492e5976ee4ac7caf92cca | 32,861 |
import bz2
import zlib
import lzma
def decompress(fcn):
"""Decorator that decompresses returned data.
libmagic is used to identify the MIME type of the data and the function
will keep decompressing until no supported compression format is identified.
"""
def wrapper(cls, raw=False, *args, **kw):
... | ba5d1540da70c4f92604888f5fd10b879bd62371 | 32,862 |
def get_satellite_params(platform=None):
"""
Helper function to generate Landsat or Sentinel query information
for quick use during NRT cube creation or sync only.
Parameters
----------
platform: str
Name of a satellite platform, Landsat or Sentinel only.
params
"""
... | 2298c100eed431a48a9531bc3038c5ab8565025d | 32,863 |
import random
def generate_random_token(length = 64):
""" Generates a random token of specified length.
"""
lrange = 16 ** length
hexval = "%0{}x".format(length)
return hexval % (random.randrange(lrange)) | 5140dc2a07cb336387fd3e71b3b1edc746cccb44 | 32,864 |
import os
import http
async def process_file(path, request_headers):
"""Serves a file when doing a GET request with a valid path."""
sever_root="/opt/vosk-server/websocket/web"
MIME_TYPES = {
"html": "text/html",
"js": "text/javascript",
"css": "text/css"
}
if "Upgrade" in... | d51d2ff1ec27185c31fc4eff3dfed8243e6d1764 | 32,865 |
from typing import Optional
from typing import Union
from typing import Tuple
def permute_sse_metric(
name: str,
ref: np.ndarray,
est: np.ndarray,
compute_permutation: bool = False,
fs: Optional[int] = None) -> Union[float, Tuple[float, list]]:
"""
Computation of SiSNR/... | 4e6398852231fa74b8999158dc5f20833f53643b | 32,866 |
import os
def get_tids_from_directory(audio_dir):
"""Get track IDs from the mp3s in a directory.
Parameters
----------
audio_dir : str
Path to the directory where the audio files are stored.
Returns
-------
A list of track IDs.
"""
tids = []
for _, dirnames, files... | 46c1e0b753392f7098c43afb58a24f6272bd432d | 32,867 |
from datetime import datetime
import os
def coverage_qc_report(institute_id, case_name):
"""Display coverage and qc report."""
_, case_obj = institute_and_case(store, institute_id, case_name)
data = controllers.multiqc(store, institute_id, case_name)
if data["case"].get("coverage_qc_report") is None:
... | 097fd405b01e4c0976cb0973cc01a6fe7bb7f5a3 | 32,868 |
import os
def get(name, decode=True):
"""
Get a resource from the trimesh/resources folder.
Parameters
-------------
name : str
File path relative to `trimesh/resources`
decode : bool
Whether or not to decode result as UTF-8
Returns
-------------
resource : str or byt... | 191c03dd5c7ebd62b521a7669411090807105a66 | 32,869 |
from typing import Literal
def test_if() -> None:
"""if-elif-else."""
PositiveOrNegative = Literal[-1, 0, 1]
def positive_negative(number: int) -> PositiveOrNegative:
"""Return -1 for negative numbers, 1 for positive numbers, and 0 for 0."""
result: PositiveOrNegative
if number < ... | 771c5e5375b161d5eed0efc00db1094a7996169a | 32,870 |
def ba2str(ba):
"""Convert Bluetooth address to string"""
string = []
for b in ba.b:
string.append('{:02X}'.format(b))
string.reverse()
return ':'.join(string).upper() | 765fc9dbbea5afdd32c6d09c18f428e3693e20bf | 32,871 |
import numpy as np
from accessory import get_iterable
import logging
import sys
def calc_variance(img, omit=[]):
"""
calculate variance of pixel values in image
:param img: 2D array of pixel values
:param omit: pixel values to omit from calculation
:return: variance
"""
if np.ndim(img) >... | 1506ede8136b1f67ccfb905427e4487c2fe32127 | 32,872 |
import requests
def delete_user(client: Client, user_id: str) -> bool:
"""Deletes disabled user account via the `/users/{user_id}` endpoint.
:param client: Client object
:param user_id: The ID of the user account
:return: `True` if succeeded, `False` otherwise
"""
params = {'version': get_use... | f385ca6e1108f95c00e28dbd99ffa640fefed761 | 32,873 |
import requests
def get_token(corp_id: str, corp_secret: str):
"""获取access_token
https://open.work.weixin.qq.com/api/doc/90000/90135/91039
"""
req = requests.get(
f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={corp_secret}'
)
return req.json().get('access_t... | 9a9c3fcdb74312b5d2d7c62588aea3cf78796ec9 | 32,874 |
def _update_run_op(beta1, beta2, eps, global_step, lr, weight_decay, param, m, v, gradient, decay_flag, optim_filter):
"""
Update parameters.
Args:
beta1 (Tensor): The exponential decay rate for the 1st moment estimations. Should be in range (0.0, 1.0).
beta2 (Tensor): The exponential decay... | 292f493ff83aba5e95a7b4ddce6b454ce4600e2c | 32,875 |
def make_initial_ledger(toodir=None):
"""Set up the initial ToO ledger with one ersatz observation.
Parameters
----------
toodir : :class:`str`, optional, defaults to ``None``
The directory to treat as the Targets of Opportunity I/O directory.
If ``None`` then look up from the $TOO_DIR ... | 9f377c54b65973bd26b868a3a7ca11dd96a7e1e6 | 32,876 |
def trace_sqrt_product_tf(cov1, cov2):
""" This function calculates trace(sqrt(cov1 * cov2))
This code is inspired from:
https://github.com/tensorflow/tensorflow/blob/r1.10/tensorflow/contrib/gan/python/eval/python/classifier_metrics_impl.py
:param cov1:
:param cov2:
:return:
"""
sqrt_... | f685080ce644a889aff633fb44cccf452746c5e9 | 32,877 |
from typing import Any
from typing import Optional
import json
def opennem_serialize(obj: Any, indent: Optional[int] = None) -> str:
"""Use custom OpenNEM serializer which supports custom types and GeoJSON"""
obj_deserialized = None
if not obj_deserialized:
obj_deserialized = json.dumps(obj, cls=... | 77bcb41130b5d8d95f5460cc45f4e78b9ef8bdf5 | 32,878 |
def min_vector(first_atom, second_atom, cell=None):
"""Helper to find mimimum image criterion distance."""
if cell is None:
cell = first_atom._parent.cell.cell
return min_vect(first_atom.pos,
first_atom.fractional,
second_atom.pos,
second_a... | aa159ff5379b8087f05c8b4c88e3ee71a5d2765f | 32,879 |
def dice_coeff_2label(pred, target):
"""This definition generalize to real valued pred and target vector.
This should be differentiable.
pred: tensor with first dimension as batch
target: tensor with first dimension as batch
"""
target = target.data.cpu()
# pred = torch.sigmoid(pred)
# ... | 553f3cdc76f4061512dea27a482f177948f87063 | 32,880 |
def cost_arrhenius(p, T, rate):
"""
Sum of absolute deviations of obs and arrhenius function.
Parameters
----------
p : iterable of floats
`p[0]` is activation energy [J]
x : float or array_like of floats
independent variable
y : float or array_like of floats
depende... | f69a98e06e79774e2fa7eef2709f0bdd6adbe3e1 | 32,881 |
def get_ou_accounts_by_ou_name(ou_name, accounts_list=None, parent=None):
"""
Returns the account of an OU by itsname
Args:
ou_name: name of the OU
accounts_list: list of accounts from a previous call due to the recursive
next_token: the token for the call in case a recursive occurs
... | 6a8d638b18de08937208de45665fd3586dff8c76 | 32,882 |
def split_result_of_axis_func_pandas(axis, num_splits, result, length_list=None):
"""Split the Pandas result evenly based on the provided number of splits.
Args:
axis: The axis to split across.
num_splits: The number of even splits to create.
result: The result of the computation. This ... | bd136350147db12ed165129310fd5ee22f55b40e | 32,883 |
def is_icypaw_scalar_type_annotation(obj):
"""Return if the object is usable as an icypaw scalar type annotation."""
if isinstance(obj, type) and issubclass(obj, IcypawScalarType):
return True
return False | 7c3095ff03183a1dce33062b18dac94ee2528170 | 32,884 |
from typing import List
import os
def gcs_batched_data(request, gcs_bucket, dest_dataset,
dest_table) -> List[storage.blob.Blob]:
"""
upload two batches of data
"""
data_objs = []
for batch in ["batch0", "batch1"]:
for test_file in ["part-m-00000", "part-m-00001", "_SUCCES... | 99475abcc92bbbb921964e21dbfe90f35d2a902f | 32,885 |
def pair_is_inward(read, regionlength):
"""Determine if pair is pointing inward"""
return read_is_inward(read, regionlength) and mate_is_inward(read, regionlength) | 4d67b7824093df1cd5d2e020d88894a0877d5d71 | 32,886 |
import requests
import html
import re
import json
import os
def lambda_handler(event, context):
"""
Call the main function
"""
print(event)
# check if it's the original invokation or not.
if is_the_original_invokation(event):
# original invocation. Go on as usual
ugetter = Urls... | f136021588ab75c391167affd6f25c4d74732cb9 | 32,887 |
import logging
import requests
def send_request(url, payload):
"""
Send http request.
:param url: The url to access.
:param payload: The payload to send.
:return: None if request failed, Response content if request ok.
"""
logging.debug(f'Request {url} with payload:\n{payload}')
retr... | 7f608575548ea99b4ca1f0fbeb524aaeee806b10 | 32,888 |
def sort_by_game(game_walker, from_locale, pack):
"""Sort a pack by the order in which strings appears in the game files.
This is one of the slowest sorting method. If the pack contains strings
that are not present in the game, they are sorted alphabetically at the
end and a message is logged."""
... | 97cebe8db744aef876c7dd0018c49593e7c22888 | 32,889 |
from ..base.util.worker_thread import stop_all_threads
from typing import Sequence
import threading
def main(args: Sequence[str]) -> int:
"""
Entry for the program.
"""
try:
user_args = parse_args(args)
bus = bootstrap_petronia(user_args)
return run_petronia(bus, user_args)
... | 099c0ab97569028a6ca8af3bc97103c1490c54ff | 32,890 |
def to_query_str(params):
"""Converts a dict of params to a query string.
Args:
params (dict): A dictionary of parameters, where each key is a
parameter name, and each value is either a string or
something that can be converted into a string. If `params`
is a list, i... | 11b27e17525cf05dabf0d36e1709be749e829264 | 32,891 |
def histogram(backend, qureg):
"""
Make a measurement outcome probability histogram for the given qubits.
Args:
backend (BasicEngine): A ProjectQ backend
qureg (list of qubits and/or quregs): The qubits,
for which to make the histogram
Returns:
A tuple (fig, axes, p... | 77227d1db0f90420134c18737248989481d384c1 | 32,892 |
import bisect
def crop(sequence, minimum, maximum, key=None, extend=False):
"""
Calculates crop indices for given sequence and range. Optionally the range
can be extended by adding additional adjacent points to each side. Such
extension might be useful to display zoomed lines etc. Note that this metho... | af761dbdbcb40270a4aaf7c55921497e1872f8c1 | 32,893 |
def reverse_dict(dict_obj):
"""Reverse a dict, so each value in it maps to a sorted list of its keys.
Parameters
----------
dict_obj : dict
A key-value dict.
Returns
-------
dict
A dict where each value maps to a sorted list of all the unique keys
that mapped to it.... | 94ff638e67de94a37754cfae7fd9d2605835b946 | 32,894 |
def remote_error_known():
"""Return a remote "error" code."""
return {"errorType": 1} | bd848143531a9f8e997af8ef64f2d1ee4ad3670b | 32,895 |
import re
def get_throttling_plan(js: str):
"""Extract the "throttling plan".
The "throttling plan" is a list of tuples used for calling functions
in the c array. The first element of the tuple is the index of the
function to call, and any remaining elements of the tuple are arguments
to pass to ... | c53eba9d018a6e3308f07031c4c8f26101f853dd | 32,896 |
def list_agg(object_list, func):
"""Aggregation function for a list of objects."""
ret = []
for elm in object_list:
ret.append(func(elm))
return ret | b2d8eef9c795e4700d111a3949922df940435809 | 32,897 |
from typing import Callable
def job_metadata_api(**kwargs: dict) -> Callable[[dict], str]:
"""
Job Metadata API route.
Arguments:
kwargs: required keyword arguments
Returns:
JSON response
"""
return job_resource.job_metadata_api(**kwargs) | 4641930a6c18066eac3dbaaaed99bfbd59560722 | 32,898 |
def parse_word(word: str) -> str:
"""Compile a word of uppercase letters as numeric digits. Non-uppercase letter words are returned unchanged."""
if not word.isupper():
return word
compiled_word = " + ".join([letter + "*" + str(10**index) for index, letter in enumerate(word[:: -1])])
return "(" ... | aa246c7d5e92035f14476327f5b2b694b383f7e1 | 32,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.