content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
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 extract_addresses_from_txlist(tx_hashes_tx, _getrawtransaction_batch):
"""
helper for extract_addresses, seperated so we can pass in a mocked _getrawtransaction_batch for test purposes
"""
logger.debug('extract_addresses_from_txlist, txs: %d' % (len(tx_hashes_tx.keys()), ))
tx_hashes_addresses ... | 269e7c51c614be173a1489ebca4bc56828f4af78 | 3,621,305 |
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 |
import pandas
def sift(*args):
"""Filters rows of the data that meet input criteria.
Giving multiple arguments to sift is equivalent to a logical "and".
In: df >> sift(X.carat > 4, X.cut == "Premium")
# Out:
# carat cut color clarity depth table price x ...
# 4.01 Premium I I1 ... | 688e28eea89275b7056dea41b6a5078cbcfd48a5 | 3,621,310 |
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 os
def read_ground_truth(img_path):
"""
Summary.
Read ground truth from txt path corresponding to image path
Args:
img_path(string): image path.
Returns:
list, [YAW,PITCH,ROLL], key point list, bool value(is ground truth valid).
"""
txt_path = ""
if img_path.e... | f3d82065c12d2f58ad14b08995f12f62ba04c985 | 3,621,330 |
import os
def check_file_access(file_path, file_label, file_rwx='r', use_logger=False,
warn_only=False, exit_val=exitvals['startup']['num']):
"""
Check if a file is accessible.
For purposes of this function, 'file' includes directories,
symlinks, etc.
If the file doesn't e... | cbe4f21a3e198e05110a500f599110b3f6fdc1d5 | 3,621,331 |
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 subprocess
def get_version_name(args, version_hash):
"""
Returns current version name based on the git commit history.
"""
if BRANCH != get_branch(args):
return "non-main-branch"
output = subprocess.check_output("git log --pretty=oneline", shell=True).decode().strip()
list_git_... | f544bfba4fcef71122cf75332d7d3c2cf7ccb473 | 3,621,357 |
import uuid
import hashlib
import os
import pickle
import requests
def createWallet(password, blockHash, remoteNode):
"""
CREATES NEW WALLET AND SENDS IT TO FULL NODE
Returns:
Wallet address
"""
# Create wallet ID
uid = uuid.uuid4().hex
hsh = hashlib.sha3_224((password+uid).encode... | 83c0b1c50922cf65c4c3243d706b5d66d2597c8f | 3,621,358 |
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 |
def tile_images(img_nhwc):
"""
Tile N images into one big PxQ image.
(P,Q) are chosen to be as close as possible, and if N
is square, then P=Q.
Parameters
----------
img_nhwc: list or array of images, ndim=4 once turned into array
n = batch index, h = height, w = width, c = chann... | 14bcb0629070bda20a093476c3e399cc87fa4a5d | 3,621,374 |
from typing import List
from typing import Dict
def get_top_menu(user: AbstractUser, admin_site: str = "admin") -> List[Dict]:
"""
Produce the menu for the top nav bar
"""
options = get_settings()
menu = make_menu(user, options.get("topmenu_links", []), options, admin_site=admin_site)
children... | 6a59b9f59021a473657da56601521cd6c3df8f30 | 3,621,375 |
def _calculate_share_known_cases(df):
"""Calculate the share of known cases from detected and undetected cases.
Args:
df (pandas.DataFrame): Dataframe with columns "date", "type" and "count".
Each date and type is a row.
Returns:
share_known_cases (pandas.Series):
s... | 75b1a33a98a8a2fcd59905e29ee1efe4dcf91384 | 3,621,376 |
def device_get_all_by_filters(filters):
"""Returns Compute devices filtered by name of the field."""
return IMPL.device_get_all_by_filters(filters) | 2ff170a2df5eace277ae7109ef9a97271b4b95c0 | 3,621,377 |
def fv_creator(lamp, lams, lamda_c, int_fwm, betas, M, P_p,P_s, Df_band=1):
"""
Cretes 7 split frequency grid set up around the waves from degenerate
FWM. The central freuency of the bands is determined by the non-depleted
pump approximation and is power dependent. The wideness of these bands
is det... | 301d9c57ab64b2e78d15400905d418304a35f3ce | 3,621,378 |
def read_select_def(line: str):
"""Attempt to read SELECT definition line"""
select_match = FRegex.SELECT.match(line)
select_desc = None
select_binding = None
if select_match is None:
select_type_match = FRegex.SELECT_TYPE.match(line)
if select_type_match is None:
select_... | 5895f6e04aac2827ededc6986e27f9aaa71b967a | 3,621,379 |
def getSubString(string, firstChar, secondChar,start=0):
"""
Gives the substring of string between firstChar and secondChar. Starts looking from start. If it is unable to find a substring returns an empty string.
"""
front = string.find(firstChar,start)
back = string.find(secondChar,front+1)
if ... | c845c3c31abce7ed8064cfd16e455c27f1aac806 | 3,621,380 |
def slopePythonPlane(inBlock, outBlock, inXSize, inYSize, A_mat, z_vec, winSize=3, zScale=1):
""" Calculate slope using Python.
Algorithm fits plane to a window of data and calculated the slope
from this - slope than the standard algorithm but can deal with
noisy data batter.
The ... | 89fcc8385f894cbb1c8387097ae5a064844cc137 | 3,621,381 |
def decTimeToDeg(sign_sym, deg, min, sec):
"""Convert dec sign, degrees, minutes, seconds into a signed angle in degrees.
sign_sym may represent negative as either '-' or numeric -1."""
if sign_sym == -1 or sign_sym == '-':
sign = -1
else:
sign = 1
return dmsToDeg(sign, deg, min, ... | b2ecc2d449617560069193623a8b9aa98d1ea78c | 3,621,382 |
import sys
import traceback
def return_task_from_stack(tb) -> dict:
"""
Function returns task information from stack trace if available
Used to tag
:param tb: traceback
:return return_task: dict
"""
return_task = {}
if not tb:
tb = sys.exc_info()[2]
while 1:
if not ... | 2a259480c7478feafec08ff07f9818d5926bef2f | 3,621,383 |
from typing import Counter
def new_lanternfish(puzzle_input: list, days: int) -> int:
"""
Extract the list of fish ages from the puzzle input.
Rather than add to the existing list with new numbers, instead create a new
dictionary where each key is the days left (0 to 8) and the value
is the total ... | 50cbdecd45dd8c391b37d71fe67a0ac592cc6e45 | 3,621,384 |
def clone(
model,
input_tensors=None,
layer_fn=to_monotonic,
input_dim=-1,
dc_decomp=False,
convex_domain={},
mode="backward",
slope_backward=V_slope.name,
IBP=True,
forward=True,
finetune=False,
):
"""
:param model: Keras model
:param input_tensors: List of input... | f6450b13ca26a72692b77aecbcbe310753c0a824 | 3,621,385 |
def OddCore(G):
"""
Subgraph of vertices and edges that participate in odd cycles.
Aka, the union of nonbipartite biconnected components.
"""
return Graphs.union(*[C for C in BiconnectedComponents(G) if not isBipartite(C)]) | 94818dfce0590b900272b2926fc45b052464228f | 3,621,386 |
def pv(td1,p1,df1):
"""
returns the vapour partial pressure for given dew-frost point at pressure
:param td1: known dew-frost point
:param p1: known total pressure
:param df1: calculate over dew(1) or frost (0)
:return: vapour partial pressure (Pa)
"""
return vp(td1, df1)*ef(td1, p1, df... | edfc31cdd7e9cbaf49e575fd408ebd7bac81296d | 3,621,387 |
def FExist(filedisk, err):
"""
Test if FITS file exists
returns True or False
* file = File name
* disk = disk number, 0->CWD
* err = Python Obit Error/message stack,
"""
################################################################
# Checks
if err.isErr:
... | 5fa0b07b17ae18eb8b43e0cb3997265eb26f0710 | 3,621,388 |
def _estimate_gaussian_covariances_diag(resp, X, nk, means, reg_covar):
"""Estimate the diagonal covariance vectors.
Parameters
----------
responsibilities : array-like of shape (n_samples, n_components)
X : array-like of shape (n_samples, n_features)
nk : array-like of shape (n_components,)
... | 9031123eba89e79aca939290fd9d2234f9da03bb | 3,621,389 |
def mediation_covariates(intervention, run, mediation_year, num_mediators):
"""Build the causal dataset."""
# Just use all of the states at the moment of treatment assignment
confounders = run[intervention.time].values()
mediators = run[mediation_year].values()[:num_mediators]
return np.concatenate(... | eaa70942b0ebff820e5007ea47ee7d10bb802339 | 3,621,390 |
import os
def get_hepmass_data(train_test_split=True, decorrelate=False, normalize=False, return_dequantize_scale=True, remove_outliers=True, whiten=True, retrieve_files=['1000_train', '1000_test'], data_folder='/tmp/hepmass/'):
# language=rst
"""
Load the HEPMASS dataset.
:param data_folder: Where t... | 2cfcdd2768ecaa240702d76b33872e9e2e56ab80 | 3,621,391 |
def get_azimuth(inclination: float, launchpad_latitude: float) -> float:
"""Gets the required Azimuth of the launch in order to satisfy the orbit inclination.
The azimuth changes in function of the targeted orbit as well as the position of the launchpad.
Args:
inclination (float): inclination (in d... | 12ccfa58da65754bdbb185e11128e11aa97844c0 | 3,621,392 |
from io import StringIO
def create_wsgi_request(event_info, server_name='zappa', script_name=None,
trailing_slash=True):
"""
Given some event_info,
create and return a valid WSGI request environ.
"""
method = event_info['httpMethod']
params = ev... | 7b95db4c0f501bfa5ffdeb21c6166b24b4bc13ed | 3,621,393 |
def knapsack_polynomial_estimation(W, weights, costs, eps):
"""Полиномиальное приближение задачи о рюкзаке.
W - вместимость рюкзака
weights - веса предметов
costs - стоимости предметов
eps - точность приближения (должна быть 0 < eps < 1) """
assert W >= 0
assert weights.shape == costs.shape... | 15beebcca875c61f9e077c24c0a170e383f95242 | 3,621,394 |
def extract_watermark(fileName, base=2) -> str:
"""
从STL文件中提取水印
fileName: 文件名
base: 返回水印的进制,默认为二进制
"""
solid = Solid(fileName)
__ref = __get_ref(solid)
__ord = __ord2S(__ref) # 一个参数标识提取水印
__ord = __ord[:128] # 除去后缀0
if base == 2:
return __ord
elif base =... | c2a8d23b37926ea4a5c007175cb19ad95c3aacae | 3,621,395 |
def make_figure84():
"""
Returns initial conditions for a 4-body system in a 8-shaped orbit.
"""
ps = ParticleSystem(4)
ps.mass[...] = [1.0, 1.0, 1.0, 1.0]
ps.rx[...] = [+1.382857, 0.0, -1.382857, 0.0]
ps.ry[...] = [0.0, +0.157030, 0.0, -0.157030]
ps.rz[...] = [0.0, 0.0, 0.0, 0.0]
... | 7df73bbf9588df6e6599baaf9a14b535f1077c23 | 3,621,396 |
def pca(data,k=5,frac=0.99,whiten=0):
"""Computes a PCA and a whitening. The number of
components can be specified either directly or as a fraction
of the total sum of the eigenvalues. The function returns
the transformed data, the mean, the eigenvalues, and
the eigenvectors."""
n,d = data.sh... | fc752af6cd3c6296a607dcf801d1d273879278b8 | 3,621,397 |
import multiprocessing
import threading
def isatty(file):
"""
Returns `True` if `file` is a tty.
Most built-in Python file-like objects have an `isatty` member,
but some user-defined types may not, so this assumes those are not
ttys.
"""
if (multiprocessing.current_process().name != 'Main... | 07de93799f67becd927c392f65b25a335d14fc9a | 3,621,398 |
def update_networkipv6(networkv6, user):
"""Updates a NetworkIPv6."""
netv6_obj = get_networkipv6_by_id(networkv6.get('id'))
netv6_obj.update_v3(networkv6)
return netv6_obj | 57ca37be83bbee77a24b99f42c4dc7c60efaf806 | 3,621,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.