content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def run(factory, method: str, **kwargs):
"""hook to call event list factory
call any function
Args:
factory: :obj:`design_db_manager.events.EventManager` or :obj:`str`
method (str): 取得の仕方. 'get' or 'get_all'
kwargs (dict): kwargs for method selected by args
date or (yea... | c865787f3b85175e83307a347ac18be32312d6ba | 3,621,265 |
def arr_2_tio_image(arr):
"""
ScalarImage(shape: (c, w, h, d))
dtype: torch.DoubleTensor
"""
arr = arr.swapaxes(0,3)
return tio.ScalarImage(tensor=arr) | b4338c5ce507bf065bd6bd09a8ea55b193682ded | 3,621,266 |
def get_data_type(name):
"""Extract the data type name from an ABC(...) type name."""
return name.split('(', 1)[0] | 7565b30e1e2469de929b377fde1f186d28080f94 | 3,621,268 |
from typing import Tuple
import math
def rytz_axis_construction(d1: Vec3, d2: Vec3) -> Tuple[Vec3, Vec3, float]:
"""The Rytz’s axis construction is a basic method of descriptive Geometry
to find the axes, the semi-major axis and semi-minor axis, starting from two
conjugated half-diameters.
Source: `W... | 4256b510f5cf62e6a54d34aefd719d8ee0eee241 | 3,621,269 |
def moving_average(time_series, window_size=20, fwd_fill_to_end=0):
"""
Computes a Simple Moving Average (SMA) function on a time series
:param time_series: a pandas time series input containing numerical values
:param window_size: a window size used to compute the SMA
:param fwd_fill_to_end: index ... | d71931867c419f306824e8b240a9b1bb3fff2fdd | 3,621,270 |
def format_timestamp(df):
"""
Reformat timestamps to ISO 8601
Args:
df: input dataframe
Return:
input dataframe with timestamps formatted as ISO 8601
"""
return df.withColumn(
"timestamp",
F.date_format(
F.to_timestamp("timestamp"), "yyyy-MM-dd'T'HH:m... | fd9efdc2b563a90aafdc0204e339cd8735423b2d | 3,621,271 |
def FE(obs, mod, axis=None):
""" Fractional Error (%)"""
return (old_div(np.ma.abs(mod - obs), (mod + obs))).mean(axis=axis) * 2. * 100. | 86442208d49a13dd7f51c5c719fb406e7821fb28 | 3,621,272 |
def run_query(db_config_file, query, columns, **kwargs):
"""
General function to run a query against MLWH.
Parameters
----------
db_config_file : str
Path to MySQL config file.
query : str
SQL query.
columns : list of str
Column names for output.
**kwargs
... | 70571921d4cf6ad5a2f32d2774ffabadecb97782 | 3,621,273 |
import time
def compute_distribution_shift(index, df_wgt, Y, X, method, hist_len, freq=None, tic=0):
""" Y:target (unobserved), X:data (observed) """
N = Y.shape[1]
p = _normalize_distribution(Y)
q = _normalize_distribution(X)
if method.lower() in ['kl', 'kl-divergence']:
eps_ratio = (1-... | da8dda9fd66f9b7bb7b537282f08915e3ff65d54 | 3,621,274 |
from pathlib import Path
from typing import Sequence
def load_input(path: Path) -> Sequence[int]:
"""Loads the input data for the puzzle."""
with open(path, "r") as f:
depths = tuple(int(d) for d in f.readlines())
return depths | 35472eadcd2deefbbae332b3811be7d731cb2478 | 3,621,275 |
def create_user(email, password):
"""Create and return a new user."""
user = User(email=email, password=password)
db.session.add(user)
db.session.commit()
return user | 6f7d2a7ee8de6481dc0b7ab7e9e4ea2f0650d1b2 | 3,621,276 |
def forgiving_state_copy(target_net, source_net):
"""
Handle partial loading when some tensors don't match up in size.
Because we want to use models that were trained off a different
number of classes.
"""
net_state_dict = target_net.state_dict()
loaded_dict = source_net.state_dict()
new... | cea46fdc0fd123517ea2a678968d19e8716ccbdf | 3,621,277 |
def _get_query_results(job, splunk_client, limit):
""" Get results from a complete Splunk query """
# Get the results and display them
response = splunk_client.get_results(job, limit)
# Replace "null" with ""
if response:
response = remove_nulls(response)
return response | cfa85de524620cebd52f4654fa8839e94e12706d | 3,621,278 |
import asyncio
def patched_auth_failed_open_connection(auth_failed_prepared_stream_reader, event_loop):
"""Return a tuple of patched stream_reader and stream_writer."""
stream_writer = MagicMock()
if asyncio.iscoroutinefunction(stream_writer):
# Python 3.8.2 and later
return_value = (auth_... | 9dd44bb9178c4967c6c3fded392abf94b4710fd0 | 3,621,279 |
def has_permissions(**perms):
"""
A decorator that checks if the author has the required permissions.
Examples
--------
::
@has_permissions(administrator=True)
async def setup(ctx):
print("Success")
"""
async def predicate(ctx):
"""
Parameters
... | b0a579f61aca6a3ec24dbfc5cc474cdee8e8bb9d | 3,621,280 |
def warning(text, render=1):
""" display a warning
Args:
text (str): warning message
render (bool, optional): Defaults to True. render or return settings
Returns:
str: setting value if render=False, None otherwise
"""
color = 'yellow'
s = "[Warning] %s" % text
writ... | 58b298d5ef3b72da60e6c10a18246a82295ed98d | 3,621,282 |
def _ratio_enum(anchor, ratios):
""" Enumerate a set of anchors for each aspect ratio wrt an anchor."""
w, h, x_ctr, y_ctr = _whctrs(anchor)
size = w * h
size_ratios = size / ratios
ws = np.round(np.sqrt(size_ratios))
hw = np.round(ws * ratios)
anchors = _mkanchors(ws, hs, x_ctr, y_ctr)
... | d40a6f24485b10347ea84059b6f922e3fa8a8be9 | 3,621,283 |
def dummy_filefield_as_sequence(toformat_name):
"""Simple helper method to fill a models.FileField"""
return factory.Sequence(lambda n: get_dummy_uploaded_image(toformat_name % n)) | 2f570f76f7ada1c87bc1e59885909c5dc2c74220 | 3,621,284 |
import logging
def intersect(bed, truth, chromosome, prefix):
"""
Perform bed intersection at chromosome level
:param bed: str
Bed file path
:param truth: str
Truth vcf path
:param chromosome: str
Chromosome
:param prefix: str
Prefix of the output file
... | b5fb39f001e974b1fa2ff7ceee3956d6ae316334 | 3,621,285 |
def read_model(hdf5_file_name):
"""Reads model from HDF5 file.
:param hdf5_file_name: Path to input file.
"""
return keras.models.load_model(hdf5_file_name) | 5c82b28ea06253f21bb8121c720972b58f8d7c81 | 3,621,286 |
from io import StringIO
def image(server, hash_string):
"""Handle image, use redis to cache image."""
image_url = 'https://{0}.zhimg.com/{1}'.format(server, hash_string)
cached = Config.redis_server.get(image_url)
if cached:
buffer_image = StringIO(cached)
buffer_image.seek(0)
else... | d90ad5740d8f2e4c4ac52c41a8c1b24fef04c5d9 | 3,621,287 |
def address(interface):
"""
Get the IPv4 address assigned to an interface.
Example::
import fabtools
# Print all configured IP addresses
for interface in fabtools.network.interfaces():
print(fabtools.network.address(interface))
"""
with settings(hide('running'... | c365992939efc1d452292e46d9b9fd235a5aa47f | 3,621,288 |
def nearest_griddata(x, y, z, xi, yi):
"""
Nearest Neighbor Interpolation Method.
Nearest-neighbor interpolation (also known as proximal interpolation or, in some contexts, point sampling) is a simple method of multivariate interpolation in one or more dimensions.<br/>
Interpolation is the problem of ... | 57d5d8c1caa8e23515bce3c2e796725dc5122233 | 3,621,289 |
def clean_invite_embed(line):
"""Makes invites not embed"""
return line.replace("discord.gg/", "discord.gg/\u200b") | 05b73197150e892ed2284d9c6ac8b0eebeb492b1 | 3,621,291 |
def invalid_name(statement):
"""Identifies invalid identifiers when a name begins with a number"""
first = statement.prev_token
second = statement.bad_token
# New in Python 3.10
if (
statement.highlighted_tokens is not None
and len(statement.highlighted_tokens) > 1
):
fir... | 714c54f95cf5cdcd3b58746e0bc18e75aca5d723 | 3,621,292 |
def bbox_iou(bboxes1, bboxes2):
"""
@param bboxes1: (a, b, ..., 4)
@param bboxes2: (A, B, ..., 4)
x:X is 1:n or n:n or n:1
@return (max(a,A), max(b,B), ...)
ex) (4,):(3,4) -> (3,)
(2,1,4):(2,3,4) -> (2,3)
"""
bboxes1_area = bboxes1[..., 2] * bboxes1[..., 3]
bboxes2_area =... | c5e4a437fc25836c6f6bd41dcc3293245fcce6d1 | 3,621,293 |
import tqdm
def get_album_audio_analysis(sp, album_name, album_name_dict, album_info_path):
"""Get audio analysis data for all albums for the given artists and pickle the data-frames
:param sp: Spotify object
:type sp: object
:param album_name: List of album names
:type album_name: list
:para... | 2e21e16ec4d5f544ff14baa3bec3515dad8ca2f3 | 3,621,294 |
def fit_and_sample(lagged_zvalues:[[float]],num:int, copula=None, fig_file=None, labels=None ):
""" Example of fitting a copula function, and sampling
lagged_zvalues: [ [z1,z2,z3] ] Data with roughly N(0,1) margins
copula :
returns: [ [z1, z2, z3] ] representative sample
... | 5e4cc13b305fa333b355a634d63068b4e8dea2cb | 3,621,295 |
from typing import Dict
from typing import List
from typing import cast
def set_errors_to_event(event_uuid: str, errors: Dict[str, List[str]]) -> bool:
"""Adds the list of errors provided into the event.
Arguments:
event_uuid {str} -- The UUID for the event to add errors to.
errors {List[str]... | f93d698a4ad97edf788745ee2988989296659285 | 3,621,296 |
def createQueryFilters(filters):
"""
Takes in filters from the frontend and creates a query that elasticsearch can use
Args: filters with the fields below
verified - if the user is verified
topics - list of topics we want to see
pov - point of view
lang - the langauge the tw... | ed1238f3f72a556eae3a1bc0d1afadef3bf67abb | 3,621,297 |
import torch
def compute_dual_subgradient(weights, dual_vars, lbs, ubs, l_preacts, u_preacts):
"""
Given the network layers, post- and pre-activation bounds as lists of
tensors, and dual variables (and functions thereof) as DualVars, compute the subgradient of the dual objective.
:return: DualVars ins... | a5b11272af838d5f6713fa8b06429627cc3ae266 | 3,621,298 |
import torch
def plot_surface_density_profile(model: astro_dynamo.model.DynamicalModel,
ax: SubplotBase = None,
target_values: torch.Tensor = None) -> SubplotBase:
"""Plots the azimuthally averaged surface density of a model.
The model must con... | ebf142b63256632ebefd558da66ce8e6aecd64ab | 3,621,299 |
import hashlib
import zlib
def calc_hash_crc(filename):
"""Calculate hash and crc32 of selected file"""
data = open(filename, 'rb').read()
fhash = hashlib.sha256(data).hexdigest()
fcrc = zlib.crc32(data)
return {'sha256': fhash, 'crc32' : fcrc} | e36d004b41cd9a9d92cd9f41584fa90fb67b7631 | 3,621,300 |
def deny_request(request, cast: Cast, username: str):
"""
Denies a cast membership request
"""
user = get_object_or_404(User, username=username)
try:
cast.remove_member_request(user.profile)
except ValueError as exc:
messages.error(request, str(exc))
else:
notify.send... | aa9f6aea542e6e6e32bba1804e441d27062711ae | 3,621,301 |
async def create_user_service_call(request: web.Request) -> web.Response:
""" Register User """
user_host = request.app["config"].user_service.host
user_port = request.app["config"].user_service.port
user_path = request.app["config"].user_service.path
user_url = URL(f"http://{user_host}:{user_port}... | ffa2a26d90b1410a0e3a96b6ecf9ed162b058f13 | 3,621,302 |
def compareDocDecorator(f):
"""Decorator that updates doc strings for comparison methods.
Similar to :func:`serpentTools.plot.magicPlotDocDecorator`
but for comparison functions
"""
f.__doc__ = compareDocReplacer(f.__doc__)
return f | 6296efaee08caa6eda94d63a72b5756f902379c7 | 3,621,303 |
def unet2D(input_tensor, use_upsampling=False,
n_out=1, dropout=0.2, print_summary = False, return_model=False):
"""
2D U-Net
"""
print("2D U-Net Segmentation")
inputs = K.layers.Input(shape=input_tensor, name="Images")
# Convolution parameters
params = dict(kernel_size=(3, 3),... | 59117313d328091c32768a1e8cfb2f83f58075f2 | 3,621,304 |
def set_accuracy_83(num):
"""Reduce floating point accuracy to 8.3 (xxxxx.xxx).
:param float num: input number
:returns: float with specified accuracy
"""
return float("{:8.3f}".format(num)) | fd1818a81ea7a78c296a85adc3621ab77fbad230 | 3,621,306 |
def get_hexes_at_radius(centre_col, centre_row, radius):
"""
Function that get a list of all hexes at a certain radius from
a centre hex
"""
if radius == 0:
hex_list = [[centre_col, centre_row]]
return hex_list
if radius == 1:
hex_list = [[centre_col, centre_row - 2],
... | de4b0fd70bcca0978a02ec55f645f600eaca7947 | 3,621,307 |
import ast
def get_dependency_network(filepath):
"""
Given a directory, collects all Python and IPython files and
uses the Python AST to create a dictionary of dependencies from them.
Returns the dependencies converted into a NetworkX graph.
"""
files = get_files(filepath)
dependencies = {... | bd2e9b03af160afc24778850ce130c0d231578f5 | 3,621,308 |
import requests
def get_user(user_name):
"""
Fetches a github developer (user). Receives an username/login. E.g.
'h3nnn4n'
"""
auth = get_auth()
result = requests.get(
f'https://api.github.com/users/{user_name}',
auth=auth
)
rate_limit_update(result.headers)
check... | 1660d987a53bbe5a5cc88bc1330f9def7609bfb8 | 3,621,309 |
def ellipsecoords(pars,npoints=100):
""" Create coordinates of an ellipse."""
# [x,y,asemi,bsemi,theta]
# copied from ellipsecoords.pro
xc = pars[0]
yc = pars[1]
asemi = pars[2]
bsemi = pars[3]
pos_ang = pars[4]
phi = 2*np.pi*(np.arange(npoints,dtype=float)/(npoints-1)) # Divide ci... | 855312fdcea3bc5aca335ecbe4b316a01bf7ca74 | 3,621,311 |
from typing import Tuple
from typing import Union
def crop_images_scan_manual(images: Tuple[Image], ids: Union[list, DF],
x_sizes: Union[list, DF], y_sizes: Union[list, DF]) -> Tuple[Image]:
""" Read data from dataframe ids, series x_sizes and y_sizes and crop images """
x_sizes = ... | 9b274eb9d05347eeb2749ef4286efea3756f33d5 | 3,621,312 |
def number_vars(expr):
"""
returns the number of variables in expr
"""
m = PBA.get_var_map(expr)
return len(m) | 6fc81c00d06d1e710978005d2662e9eff190a2ef | 3,621,313 |
def get_staticmethod_func(cm):
"""
Returns the function wrapped by the #staticmethod *cm*.
"""
if hasattr(cm, '__func__'):
return cm.__func__
else:
return cm.__get__(int) | 7f8992db0b90abdb64a82e74c53199b3490792c7 | 3,621,314 |
def like_hood_data_individual(l_values, decision_mat, state_mat):
"""
generates the individual likelihood contribution based on the model.
Parameters
----------
l_values : np.array
the raw log likelihood per state.
decision_mat : numpy.array
see :ref:`decision_mat`
state_mat... | b3113e52c7dd084c2227c85c7ea64bc948253936 | 3,621,315 |
def new_extractor_obj():
"""
Gera um objeto News_extractor novo para cada teste.
"""
return News_extractor() | bdf85519efe3b97b17edf54118eee28f98191e72 | 3,621,316 |
from pathlib import Path
from typing import Optional
def render_jinja2_template(
template_path: Path,
package: Optional[Package] = None,
service_name: Optional[ServiceName] = None,
) -> str:
"""
Render Jinja2 template to a string.
Arguments:
template_path -- Relative path to template ... | b82409fe5ebb5e4d36c6878ebab308b113864b38 | 3,621,317 |
def fault_wtd_avg_params(slipmodel):
"""
###
# fault_wtd_avg_params: Generate default format for fault parameters from a given slip model for RW
###
"""
num_faults = int(np.max(slipmodel[:, 0]) + 1)
faults = np.zeros((num_faults, 6))
sub_fault_pot = np.zeros((len(slipmodel), 2))
... | 857f9082e47c9d17152a3f4af97ab8633c7ceb23 | 3,621,318 |
import uuid
async def get_task(request):
"""
Returns a task
:Example: curl -X GET http://localhost:8082/foglamp/task/{task_id}?name=xxx&state=xxx
"""
try:
task_id = request.match_info.get('task_id', None)
if not task_id:
raise web.HTTPBadRequest(reason='Task ID is r... | 1a937deb10bfff6231cae79acfa44e89773cc18d | 3,621,319 |
def endtext(update, context):
"""Returns `ConversationHandler.END`, which tells the
ConversationHandler that the conversation is over"""
try:
BOT.delete_message(
chat_id=update.message.chat.id,
message_id=context.user_data['message_id']
)
except:
pass
... | f04471abe0ee8ca4f15f8c544710c80a0698d15c | 3,621,320 |
def taq_initial_data():
"""Takes the initial values for the analysis
:return: None -- The function prints the message and does not return a
value.
"""
print()
print('#################################################')
print('Average Response Functions Physical Time Analysis')
print('#... | 226a4cfdfd11c56861e74d09c52b57266b5e6a59 | 3,621,321 |
from typing import Callable
def make_series_filter(
user: str = None, sys_name: str = None, newer_than: dt.datetime = None,
older_than: dt.datetime = None, complete: bool = False,
incomplete: bool = False) -> Callable[[SeriesInfo], bool]:
"""Generate a filter for using with dir_db function... | 50b6038c24c294cfdfb61a5cfac68a2e8f5c49dd | 3,621,322 |
def users(*logins):
""" Decorate a method to execute it once for each given user. """
@decorator
def wrapper(func, *args, **kwargs):
self = args[0]
old_uid = self.uid
try:
# retrieve users
Users = self.env['res.users'].with_context(active_test=False)
... | 941501b0a15122fb5919085c4ecd2c07cd113fe7 | 3,621,323 |
def laplace_mech(eps, delta, k=1, prob=1.0):
"""
Calibrate the scale parameter b of the Laplace mechanism
:param eps: prescribed eps
:param delta: prescribed delta
:param k: (optional) number of times to run this mechanism.
:return: the parameter structure for this randomized algorithm
"""
... | 69828a078d28c76d6bfd6a51af70de123445888f | 3,621,324 |
import platform
def is_mac():
"""
Checks if we are running on Mac OSX.
:returns: **bool** to indicate if we're on a Mac
"""
return platform.system() == 'Darwin' | 9991bfd017bf9948a75d99d5a1dfeadfd291c803 | 3,621,325 |
import math
def log(x, base=None):
""" log(x, base=e)
Logarithmic function.
"""
_math = infer_math(x)
if base is None:
return _math.log(x)
elif _math == math:
return _math.log(x, base)
else:
# numpy has no option to set a base
return _math.log(x) / _math.log... | 1abade0ced30ac8853fbe947ffff957c021fb49e | 3,621,326 |
def air_to_vacuum(wair, units):
"""Convert wavelengths in air to wavelengths in vacuum.
**Algorithm:** Convert input air wavelengths to Angstroms. Convert
air wavelengths greater than 1999.3520267833621 Angstroms to vacuum
wavelengths using the following formulae, which is used by VALD3:
.. math::... | cccd774cb1fffe593e64a93e854276e321b5df98 | 3,621,327 |
def tf_spost(A):
"""Superoperator on the right of matrix A."""
Id = Id_like(A)
return tf_kron(Id, tf.linalg.matrix_transpose(A)) | 8a2fcbbdf77b4bb909798f3832ea0eb01757492a | 3,621,328 |
def element_to_toc_item(element):
"""Convert an element to a TOC item, recursively converting children.
Args:
element (dict) - tree element represented as a dict.
"""
sub_items = []
if "members" in element:
# Group members by type, then alphabetically.
element["members"].sort... | 541fedd247fc8fa3aecc570999db0a43675b4826 | 3,621,329 |
import six
def _get_opd_info(self, opd=None, HDUL_to_OTELM=True):
"""
Parse out OPD information for a given OPD, which can be a
file name, tuple (file,slice), HDUList, or OTE Linear Model.
Returns dictionary of some relevant information for logging purposes.
The dictionary has an OPD version as ... | 536cc9ac7d522442d9eb3c19b0ed5e19653014a0 | 3,621,332 |
def latlon(sec3, npoints):
"""Computes latitudes and longitudes of grid points.
Parameters
----------
sec3 : bytes
Section 3 of GRIB2 message.
npoints : int
Number of points in grid.
Returns
-------
lon, lat : tuple
Longitudes and latitudes of grid point... | 40fbd01d5994866184e17a23ab818d88a26e5125 | 3,621,333 |
def load_file(path):
"""Loads file and return its content as list.
Args:
path: Path to file.
Returns:
list: Content splited by linebreak.
"""
with open(path, 'r') as arq:
text = arq.read().split('\n')
return text | 348d57ab3050c12181c03c61a4134f2d43cd93cd | 3,621,334 |
def mean_autocorrelation(x):
"""
Calculates the average autocorrelation (Compare to http://en.wikipedia.org/wiki/Autocorrelation#Estimation),
taken over different all possible lags (1 to length of x)
.. math::
\\frac{1}{n} \\sum_{l=1,\ldots, n} \\frac{1}{(n-l)\sigma^{2}} \\sum_{t=1}^{n-l}(X_{t... | 8ee1eea6dd1c3c7faba690fd82f8429ce1677401 | 3,621,335 |
def LF_screw(c):
"""
Checking if a screw is mentioned
"""
return ABNORMAL_VAL if "screw" in c.report_text.text.lower() else ABSTAIN_VAL | ef73a286f0d0eb5e5bd40b993a66aba7e366e9ac | 3,621,336 |
from typing import Type
import enum
def _enum_help(msg: str, e: Type[enum.Enum]) -> str:
"""
Render a `--help`-style string for the given enumeration.
"""
return f"{msg} (choices: {', '.join(str(v) for v in e)})" | e53762798e0ecb324143ee4a05c4152eaf756aad | 3,621,337 |
def distance_numpy_einsum(ps, p1):
""" Distance calculation using numpy einstein sum """
flat_units = (item for sublist in ps for item in sublist)
units_np = np.fromiter(flat_units, dtype=float, count=2 * len(ps)).reshape((-1, 2))
point_np = np.fromiter(p1, dtype=float, count=2).reshape((-1, 2))
del... | 3a5fcedb882004f8440d7a512853002f7773f83c | 3,621,338 |
def without_keywords(url,API_KEY):
"""
:type url: string
:param url: url of the website
:type API_KEY: string
:param API_KEY: google news api API Key
This method returns two types of dictionary
if the algorithm manages to find relevent articlesit returns a dictionary with keys
sta... | 9451af37425e5fc764060f89a28120405e4e2613 | 3,621,339 |
def orient_az_diff(err):
"""Differences between two azimuthal angles wraps around the circle and
should be centered about the subtractend (reference direction).
Parameters
----------
diff
Returns
-------
reoriented_diff
"""
return ((err + np.pi) % (2 * np.pi)) - np.pi | ce0be97eb179b74699339aff44f93e1c5703553b | 3,621,340 |
def volume_fraction(pvms):
"""
Computes the :abbr:`ICV (intracranial volume)` fractions
corresponding to the (partial volume maps).
:param list pvms: list of :code:`numpy.ndarray` of partial volume maps.
"""
tissue_vfs = {}
total = 0
for k, lid in list(FSL_FAST_LABELS.items()):
... | 36a7e058cc8348d6452bdb735ef71c2414846846 | 3,621,341 |
def to_timestamp(arg, format_str, timezone=None):
"""
Parses a string and returns a timestamp.
Parameters
----------
format_str : A format string potentially of the type '%Y-%m-%d'
timezone : An optional string indicating the timezone,
i.e. 'America/New_York'
Examples
--------
... | d9f7d6bff2bebedbf197dc25789e3ef5680ac36b | 3,621,342 |
import calendar
def get_timestamp(node):
"""
Return a dokuwiki-Compatible Unix int timestamp for a mediawiki API page/image/revision
"""
dt = simplemediawiki.MediaWiki.parse_date(node['timestamp'])
return int(calendar.timegm(dt.utctimetuple())) | 4215bd502ce2158387b9ac7b3d2b7d8b966fe1a8 | 3,621,343 |
from operator import mod
def FOM(t0,dM,P,step=None,**kwargs):
"""
Plot the figure of merit
"""
if step is None:
step = np.nanmax(dM.data)
Pcad = int(round(P/lc))
dMW = tfind.XWrap(dM,Pcad,fill_value=np.nan)
dMW = ma.masked_invalid(dMW)
dMW.fill_value=np.nan
res = tfind.e... | b6632531f098d3aa81c8929d5d7a853fbbe76454 | 3,621,344 |
from typing import OrderedDict
def array_remove_duplicates(s):
"""removes any duplicated elements in a string array."""
return list(OrderedDict.fromkeys(s)) | ea5a0d620139e691db99f364c38827abe39a16f5 | 3,621,345 |
from typing import Optional
def get_scholia_iri(prefix: str, identifier: str) -> Optional[str]:
"""Get a Scholia IRI, if possible.
:param prefix: The prefix in the CURIE
:param identifier: The identifier in the CURIE
:return: A link to the Scholia page
>>> get_scholia_iri("pubmed", "1234")
'... | ed240f6acb526eb2b94768028e932bbafdc01ab2 | 3,621,346 |
def timestamp_of_last_action(user, grid):
"""
Template filter implementing `time_of_last_action` from
models/place.py.
"""
if not user.is_authenticated:
return 0
return time_of_last_action(user, grid).timestamp() | 82067cab3c6e66a46737ab4db6c8dfd4de0d824d | 3,621,347 |
def kullback_leibler_divergence(weights=1.0, name='KullbackLeiberDivergence', scope=None,
collect=False):
"""Adds a Kullback leiber diverenge loss to the training procedure.
Args:
name: name of the op.
scope: The scope for the operations performed in computing t... | 286601088582b707dc216130cddfe1f26709f8ce | 3,621,348 |
def get_gateway_counts(bpmn_graph):
"""
Returns the count of the different types of gateways
in the BPMNDiagramGraph instance.
:param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model.
:return: count of the different types of gateways in the BPMNDiagramGraph instance
"""
... | 28851c8be421f286d3848f9d3ce44d4f64c8a62c | 3,621,349 |
def build_5_cycle_graph():
"""Builds a 5-cycle graph, C5.
Ref: http://mathworld.wolfram.com/CycleGraph.html"""
graph = build_cycle_graph(5)
return graph | 4b61c4fa3d366eebc52b79de5b757d2594ad253a | 3,621,350 |
from typing import Optional
from typing import List
def get_git_log_command(
verbose: bool,
from_commit: Optional[str] = None,
to_commit: Optional[str] = None,
is_helm_chart: bool = True,
) -> List[str]:
"""
Get git command to run for the current repo from the current folder (which is the pack... | e196afeeac77c997beb26ce8b2631c371db52ecc | 3,621,351 |
import logging
def xcorr(a, b, ds):
"""
:param a: x1
:param b: x2
:param ds: sampling rate
:return: corrs, lags
"""
S = len(a)
a_norm = (a - np.mean(a)) / np.std(a)
b_norm = (b - np.mean(b)) / np.std(b)
corrs = np.correlate(a_norm, b_norm / S, 'full')
lags_half = np.arang... | 43664681d36c8a72cad8381fb86584d30466c995 | 3,621,352 |
def gt_comparison():
""">: Greater than operator."""
class _Comparable:
def __gt__(self, other):
return 'big' in other
return _Comparable() > 'big' and "masperpiece" | 76009a61f47fac7e5abc838bf2fa427ec7268d03 | 3,621,353 |
def internal_server_error(error):
""" Handles unexpected server error with 500_SERVER_ERROR """
message = str(error)
app.logger.error(message)
return (
jsonify(
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
error="Internal Server Error",
message=message,
... | b896799fb9e00993b88bffe7d08f553fb8db9105 | 3,621,354 |
def minimum_separation(lon1, lat1, lon2, lat2, unit='deg'):
"""Compute minimum distance of each (lon1, lat1) to any (lon2, lat2).
Parameters
----------
lon1, lat1 : array_like
Primary coordinates of interest
lon2, lat2 : array_like
Counterpart coordinate array
unit : {'deg', 'ra... | d8b74ca19684e0914d595ed0058d3b68b32ef547 | 3,621,355 |
def tau_references_json():
"""Show the modifiers of the Tau protein."""
rows = get_tau_references(graph)
return jsonify([
dict(zip(('type', 'reference'), row))
for row in rows
]) | 7d04c08d60074bfb64a6d18b9b68bdc4b73819fc | 3,621,356 |
import types
def _attempt_nocopy_reshape(context, builder, aryty, ary, newnd, newshape,
newstrides):
"""
Call into Numba_attempt_nocopy_reshape() for the given array type
and instance, and the specified new shape. The array pointed to
by *newstrides* will be filled up if s... | 5816abf342654608911c6d4f0ab064faefd582fd | 3,621,359 |
def get_aim_matrix(origin, target, up_vector=om.MGlobal.upAxis()):
"""Return the aim matrix aiming from the origin to the target.
The aim vector will be the Y Axis
Args:
origin(om.MPoint): origin point
target(om.MPoint): target point
"""
aim_vector = om.MVector(target - origin).nor... | 18991fbc7a5e61ea8002353b17981e0898cecb94 | 3,621,360 |
def new_event_loop():
"""Return a new event loop."""
return Loop() | dab78c79145de789a56649269fddcc90f0c68f13 | 3,621,361 |
import math
def execCopySourceTarget(TargetSkinCluster, SourceSkinCluster, TargetSelection, SourceSelection, smoothValue=1, progressBar=None):
""" copy skincluster information from one vertex group to another based on closest proximity
:param TargetSkinCluster: the skincluster to gather information from
... | 774ad6fb8cae0d1dc709ddfd67f2abc2511915e9 | 3,621,362 |
import socket
def get_ipv4_for_hostname(hostname, static_mappings={}):
"""Translate a host name to IPv4 address format.
The IPv4 address is returned as a string, such as '100.50.200.5'.
If the host name is an IPv4 address itself it is returned unchanged.
You can provide a dictionnary with static map... | fd28106380c6a6d2c353c0e8103f15df264117ef | 3,621,363 |
def handler(event, context):
"""
Gets credentials by email address or domain.
:param event: object containing 'email' or 'domain' string but not both
:return: a list of credentials in the form "<email address>:<password>"
"""
domain: str = event.get('domain')
email: str = event.get('email'... | c77c2eabb8981ee8b120c167e14f032e801be7c9 | 3,621,364 |
def create_subgraph_for_op(input_shape: tuple, op_string: str) -> tf.Graph:
"""
Create and return the TensorFlow session graph for a single Op.
A well known input named "aimet_input" and a well known output named "aimet_identity" are used
along with the Op for the purposes of traversing the graph for th... | e6039895f3a1b8a8fdb68a4f048e7b0307aa3372 | 3,621,365 |
def configure_audit_decorator(graph):
"""
Configure the audit decorator.
Example Usage:
@graph.audit
def login(username, password):
...
"""
include_request_body = int(graph.config.audit.include_request_body)
include_response_body = int(graph.config.audit.include_res... | 4f1744073a3c4a71db6cd1ea36d77ff0bbb9efed | 3,621,366 |
def read_geopackage(file_path, layer):
"""Read file as GeoDataFrame."""
src = fiona.open(file_path, "r", layer=layer)
rows = []
columns = list(src.schema["properties"].keys()) + ["geometry"]
dtypes = normalize_fiona_schema(src.schema)["properties"]
crs = src.crs
for feature in src:
#... | 773e0cb202ce426410b05e0cf993b4904ad90fb7 | 3,621,367 |
from io import StringIO
def getpalette(data):
"""
Helper to transform a StringIO object into a palette
"""
palette = []
string = StringIO(data)
while True:
try:
palette.append(unpack("<4B", string.read(4)))
except StructError:
break
return palette | f9db54d6005af2acc7013aad2e2c14d9b6d64b03 | 3,621,368 |
def parse_privs(privs, db):
"""
Parse privilege string to determine permissions for database db.
Format:
privileges[/privileges/...]
Where:
privileges := DATABASE_PRIVILEGES[,DATABASE_PRIVILEGES,...] |
TABLE_NAME:TABLE_PRIVILEGES[,TABLE_PRIVILEGES,...]
"""
if privs... | c34b85bcb721d6e94a40eace8fe0f84fd8886f1c | 3,621,369 |
def season_ts(ds, var, season):
""" calculate timeseries of seasonal averages
Args: ds (xarray.Dataset): dataset
var (str): variable to calculate
season (str): 'DJF', 'MAM', 'JJA', 'SON'
"""
## set months outside of season to nan
ds_season = ds.where(ds['time.season'] == season)... | 6d5b0ddc39762ceca42de6b9228c38f4bf365cd0 | 3,621,370 |
def _create_sub_sequences(sequence, th=1):
""" create list of perfect subsequence """
out = []
if not sequence:
return out
sub_sequence = [sequence[0]]
sequence = sequence[1:]
while sequence:
p1 = sub_sequence[-1]
_next = None
for i, p2 in enumerate(sequence):
... | 73f79e7bf77da3cfcbacb3f77635266197976220 | 3,621,371 |
import numpy
import scipy
def interpolate_contour(
points: numpy.array, interval: float, method: str = 'linear'
) -> numpy.array:
"""
Calculate a set of points along an arbitrary polygon to enforce a regular interval between particles.
:param points: array of x and y values of starting polygon
:p... | dab87e3d1332b910ec211f85f77531551f54a37c | 3,621,372 |
from typing import Union
from typing import Callable
import codecs
import tqdm
def augment_train_data_with_replacement(train_data: pd.DataFrame,
replace_entity: str,
synonym_func: Union[str, Callable],
... | 4b18df3d3adecf318a85dde8af216891d4fbf0b3 | 3,621,373 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.