content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def LoadFinalCircuit(Parasitics=False,LoopgainMag=True,LoopgainPhs=True):
"""
Returns the Loop Gain symbolic analysis estimation of the final circuit
Select Parasitcs=True for symbolic estimations considering the parasitics after extraction in Cadence.
"""
#Frequency limits to be plot
f_check_... | 95108e0219381c396e10602bcb467c6ff758ca4f | 53,400 |
def get_conformer(species, name):
"""
Generate a conformer of a species given a new name but with the same
atoms
Arguments:
species (autode.species.Species):
name (str):
Returns:
(autode.conformers.Conformer): Conformer
"""
conformer = Conformer(name=name, atoms=spe... | 25d071d3a48942856edcb7f5156a2b85b1fe8cd4 | 53,401 |
import tempfile
import pathlib
from pathlib import Path
import webbrowser
import platform
import os
import subprocess
def save_tempfile(
text,
filename=None,
encoding='utf-8',
start=True,
browser=False,
): # pylint: disable=too-many-branches, too-many-return-statements
# f... | a1258efd2e546a7cb7f5b7a63f5624896abe042e | 53,402 |
import requests
import json
def _get_stream_with_params_and_return_list_of_ads(filter_params):
"""
This function handles:
http GET request
check that no http error is returned
converting the bytestring in the response to a list of ads
"""
response = requests.get(url_for_stream,... | 3d3c5db65efc05270e3ea24bdac354baa3c80f6d | 53,403 |
import os
def build_logfile_dirpath(gearman_worker):
"""
Build the path for saving the transfer logfile
"""
cruise_dir = os.path.join(gearman_worker.shipboard_data_warehouse_config['shipboardDataWarehouseBaseDir'], gearman_worker.cruise_id)
return os.path.join(cruise_dir, gearman_worker.ovdm.get_... | b456c755657cb4451bb246a8f66ef5ff083e3604 | 53,404 |
import requests
import numpy as np
from requests.exceptions import ReadTimeout
def post_nadlan_sviva_rest(body, only_neighborhoods=True, subject=None,
add_coords=True):
"""take body from request and post to nadlan.gov.il deals REST API,
Sviva=other parameters, demographics, etc,
... | c659b5ac32b6b5317d614460def207fe9fc20820 | 53,405 |
def make_export(objects, exportable_objects=None):
"""Make export"""
query_helper = QueryHelper(objects)
ids_by_type = query_helper.get_ids()
converter = ExportConverter(
ids_by_type=ids_by_type,
exportable_queries=exportable_objects,
)
csv_data = converter.export_csv_data()
object_names = "_"... | 4fdaa37b84371cc6926dcb4eb5a5880e1bb53990 | 53,406 |
from operator import ne
def grad(fld, bnd=True):
"""2nd order centeral diff, 1st order @ boundaries if bnd"""
# vx, vy, vz = fld.component_views()
if bnd:
fld = viscid.extend_boundaries(fld, order=0, crd_order=0)
if fld.iscentered("Cell"):
crdx, crdy, crdz = fld.get_crds_cc(shaped=Tru... | 5196dd3a6d92839ae83ccfd503ddb08a98aad17f | 53,407 |
def profile(request):
"""displays profile page"""
current_user = request.user
user_id = current_user.id
return render(request, 'profile/profile.html', {
'account': get_object_or_404(Account, acc_id=user_id),
'dj_name': current_user.username
}) | 0801d99ebdeae1ff14a449ab1c91f3ddf66828ec | 53,408 |
import numpy
def positions_join(positions_sequence):
"""Return concatenated positions arrays."""
return numpy.concatenate(positions_sequence) | f2743b00ac6b3c19e2c8efe0209e8a3f938389b7 | 53,409 |
def rotate_matrix(matrix, phi, theta, psi):
""" Rotate affine transformation described by the matrix.
The rotation is described by the three euler angles
phi, theta, psi (in degree).
This is untested!
"""
# decompose transformations
t, s, r = decompose_matrix(matrix)
# buil... | 7297a6432239f39116e7ccf03bc2394fb60e2fc4 | 53,410 |
def build_optimizer(model, args):
""" helper to build the optimizer and wrap model
:param model: the model to wrap
:returns: optimizer wrapping model provided
:rtype: nn.Optim
"""
optim_map = {
"rmsprop": optim.RMSprop,
"adam": optim.Adam,
"adadelta": optim.Adadelta,
... | 8f5233a0b3f264d56307550e2c38f445381acbec | 53,411 |
def callback_on_failure():
"""Simple callback on failure"""
return False | 98fcb160561ff4c6c25f49e95610394b56580a04 | 53,412 |
def _reconstitute(cls, dict_, items):
""" Reconstitute an ``OrderingList``.
This is the adjoint to ``OrderingList.__reduce__()``. It is used for
unpickling ``OrderingList``\\s
"""
obj = cls.__new__(cls)
obj.__dict__.update(dict_)
list.extend(obj, items)
return obj | 2fb4d4bafba99da0a4bcdc4348b7e0f75aa78895 | 53,413 |
def id_attributes_map(dataset_path, id_field_names, field_names, **kwargs):
"""Return dictionary mapping of field attribute for each feature ID.
Note:
There is no guarantee that the ID field(s) are unique.
Use ArcPy cursor token names for object IDs and geometry objects/
properties.
... | 8c654542434f81b2b8ac94de54ece3880abd8e34 | 53,414 |
def modify_attack_types(id_, attack_types, user, **kwargs):
"""
Set the Indicator attack type.
:param indicator_id: The ObjectId of the indicator to update.
:type indicator_id: str
:param attack_types: The new indicator attack types.
:type attack_type: list,str
:param user: The user updatin... | 5df8efb8b3f36d70a303a145f28587dec485332e | 53,415 |
def addUpdateCarriers():
"""
Add or Update a carrier
"""
db = DummySession()
newgwid = None
try:
if not session.get('logged_in'):
return redirect(url_for('index'))
if (settings.DEBUG):
debugEndpoint()
db = SessionLoader()
form = stripD... | 71c53804f97baae972363c7b6e18b690ff9d68dc | 53,416 |
def mdotvpw(M, v, w):
"""
M.v + w
"""
return vaddw(mdotv(M, v), w) | c5fbd96c6cbd4f6fe2b93a287b4ef02397464817 | 53,417 |
def get_ip(device):
""" Return first ip on an interface """
cmd = "ip addr show dev %s" % device
for i in execute(cmd):
vals = i.lstrip().split()
if (vals[0] == 'inet'):
return vals[1]
return "" | 87da98e037b74de3686e3e2f3919327a6df8130c | 53,418 |
def index2int(index):
"""Helper function to convert timeindexes to ints"""
return index.view(np.int64).reshape(-1,1) | 6a56d04fc5d43e54262ec804ec538c62f4294a44 | 53,419 |
def fetch_documents_front(document_id):
"""
Obtém o JSON do Document do Kernel com base no parametro 'document_id'
"""
return fetch_data("/documents/%s/front" % (document_id)) | e1fd02859332cc9947b9a14ea2cd4ed4bfdb0de4 | 53,420 |
from typing import List
from typing import Optional
from typing import Any
import glob
def get_positions(
topology: PathLike,
trajectory: List[str],
*,
mask: str = "all",
stride: Optional[int] = None,
) -> NDArray[(Any, ...), Float]:
"""Read a molecular dynamics trajectory and retrieve the coo... | 30b0374187088f56e48b1756b475a55785fde373 | 53,421 |
def snd(pair):
"""Return the second element of pair
"""
return pair[1] | a7893d60324ebdd358a0a0bb86bd2842d2617629 | 53,422 |
def create_swagger_spec():
"""
Swagger API definition.
"""
return jsonify(spec.to_dict()) | 26354017e8403107873e9fc543488e9a4ace98b6 | 53,423 |
def quicksort_hoare(a):
"""Quicksorts a list, using Hoare partitioning."""
def partition(low, high):
swap_center_to_front(low, high)
pivot = a[low]
low -= 1
high += 1
while True:
low += 1
while a[low] < pivot:
low += 1
... | 46b1ce7568b519df932a17a0903ca3814a1e3c7e | 53,424 |
import inspect
def trimArgsKwargs(fn, givenArgs, givenKwargs=None):
""" given function, and tuple and dict of args and kwargs,
trim args to accepted length, and remove all but given kwargs from dict
for use in signals - some functions just need to trigger
on specific signals, while others may need more detail inf... | 02ae5865f519052bc56f178d79626d1145889c75 | 53,425 |
import tempfile
import os
def get_estimator(batch_size=1,
epochs=500,
steps_per_epoch=128,
model_dir=tempfile.mkdtemp(),
path_brats=os.path.join(os.getenv('HOME'), 'fastestimator_data', 'BraTs')):
"""Args:
path_brats: folder path of B... | 533edcf0cde6df44e8bbafc5147cf27be7ed1eaf | 53,426 |
def norm_hue_channel(value):
"""Normalize hex channel."""
return norm_angle(value) | 1612b10e790a1f179ef168501ea83e421eee275a | 53,427 |
import os
def latest_checkpoint(ckpt_dir, prefix='checkpoint_'):
"""Retrieve the path of the latest checkpoint in a directory.
Args:
ckpt_dir: str: directory of checkpoints to restore from.
prefix: str: name prefix of checkpoint files.
Returns:
The latest checkpoint path or None if no checkpoints ... | a60826060fad4a4f7ccbf25b0708ad8079f382f1 | 53,428 |
def _add_common_cc_options(version, **kwargs):
"""Add common C++ defines, compiler and linker options.
This function will add common Xykivo C++ options to the given cc_library
or cc_binary optional arguments.
:param version: The version of the of the C++ target
:param kwargs: Optional C++ target a... | be9dc753106c69a3baf5af4bf51de2846a36b01a | 53,429 |
def ServiceAccountCredentials(email, key_file=None, key_data=None):
"""Configure OAuth2 credentials for a Google Service Account.
Args:
email: The email address of the account for which to configure credentials.
key_file: The path to a file containing the private key associated with
the service acc... | 6e6e30262b065ec279955ba1a3ba89a2217bb068 | 53,430 |
def get_prop_type(value, key=None):
"""
Performs typing and value conversion for the graph_tool PropertyMap class.
If a key is provided, it also ensures the key is in a format that can be
used with the PropertyMap. Returns a tuple, (type name, value, key)
"""
if isinstance(key, unicode):
... | 41805f689d76e0f8103a9ede42eea93b91fea542 | 53,431 |
def get_pb_by_name(xml_parent, name):
"""
Searches for a pb_type with the given name inside a parent pb_type.
Returns either a child or the parent.
The provided parent may be a mode but a pb_type is always returned.
"""
assert xml_parent.tag in ["pb_type", "mode"], xml_parent.tag
# Check t... | aa8a55d0af07ff30ffd9a27556ec50480c6ccde0 | 53,432 |
def getTimeframe(start: date, stop: date) -> str:
"""Given two dates, returns a stringified version of the interval between
the two dates which is used to retrieve data for a specific time frame
from Google Trends.
"""
return f"{start.strftime('%Y-%m-%d')} {stop.strftime('%Y-%m-%d')}" | 3099cc6c3ae19dd737df5d5bac4527e6ef430bb7 | 53,433 |
def set_val(request):
"""AJAX POST for setting arbitrary values to an object."""
user = request.user
msg = "fail"
instance = None
if request.method == 'POST':
cid = request.POST.get('cid')
oid = request.POST.get('oid')
field = request.POST.get('field')
instance_value ... | b18cb0afd01f689f53064ca9e9be1945ddec1200 | 53,434 |
def h3_to_parent(h, res=None):
"""
Get parent of arrays of cells.
Parameters
----------
h : array of H3Cells
res: int or None, optional
The resolution for the parent
If `None`, then `res = resolution(h) - 1`
Returns
-------
array of H3Cells
"""
h = np.array(... | e45316b21a6f90d26ec7bd79d02c44b1b1fd1597 | 53,435 |
import struct
def packFileInfo(file, byte_order='<'):
"""
packs FileInfo object into bytearray b
"""
if file.address is None:
raise ValueError('FileInfo object does not have an address')
if (byte_order != '<') and (byte_order != '>'):
raise ValueError('unknown byte_order: '+str(byte_order))... | 7c18a200f0571470224d7f253014460ce913bf54 | 53,436 |
def contenttype(filename, default='text/plain'):
"""
Returns the Content-Type string matching extension of the given filename.
"""
i = filename.rfind('.')
if i >= 0:
default = CONTENT_TYPE.get(filename[i:].lower(), default)
j = filename.rfind('.', 0, i)
if j >= 0:
... | 7dd27aa87db1197887be4aaa20f489d1b19f7258 | 53,437 |
import pdb
def _validate_mean_cols(df, fix=False):
"""
Validates contents of mean column in a given dataframe
"""
col = 'mean'
if col in df.columns:
# Check if columns are floats
if not df[col].values.dtype == float:
# Check whether values can be interpreted as floats... | 4461a84ca46c38da24064fbbd1d69b88e0c6ba84 | 53,438 |
from datetime import datetime
from typing import List
from typing import Dict
def search_async(start: datetime.datetime,
end: datetime.datetime,
programs: List[str] = None,
platforms: List[str] = None,
instrument_types: List[str] = None,
... | e261774eb3e31461d5ff5ce6c2f82bfe3cdc0859 | 53,439 |
def delete_aip(mets_file):
"""Delete the file"""
mets_instance = METS.query.filter_by(metsfile='%s' % (mets_file)).first()
db.session.delete(mets_instance)
db.session.commit()
return render_template('deletesuccess.html') | 415696d5ba75934de02ea23e3a6c77c3a9a19e45 | 53,440 |
import argparse
def read_commandline_args():
"""Read arguments passed on program execution"""
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbose', action='store_true',
help='print verbose output')
config = vars(parser.parse_args())
if config.get('verb... | b562bdeb91f1bef473b8e271aff90425fce593c7 | 53,441 |
import json
def bel_process_pybel_neighborhood():
"""Process BEL Large Corpus neighborhood and return INDRA Statements."""
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
genes = body.get('genes')
bp = bel.process_pyb... | 2ca33f051d87c65cc8b4e493a555175d1adcda1b | 53,442 |
def _induced_power_cwt(data, sfreq, frequencies, use_fft=True, n_cycles=7,
decim=1, n_jobs=1, zero_mean=False):
"""Compute time induced power and inter-trial phase-locking factor
The time frequency decomposition is done with Morlet wavelets
Parameters
----------
data : array... | 9c847ce3b329fa5710fcc97353ce65075a08b65c | 53,443 |
def clean_tag_text(tag):
""" Convert a tag to a string, with all extra whitespace removed.
"""
if tag is None:
return None
# Get tag text and remove soft hyphens added by Word
text = tag.get_text().replace('\xad', '')
return RE_CLEAN_TEXT.sub(' ', text).strip() | e025101484d03cdb29a39b80863f9f4c802160f7 | 53,444 |
def get_xfmr_pose(pose: str, dim: int, **kwargs) -> nn.Module:
"""
Return position encodings layer
Args:
pose (str): positional encoding type, {abs|rel|xl|conv1d}
"""
if pose not in PosEncodings:
raise ValueError(f"Unsupported pose layer: {pose}")
return PosEncodings[pose](dim, *... | adce1b7369322238d0cbd2fbcc0d4394c89dfbfa | 53,445 |
def base64_middleware():
"""Provide a middleware configured with the Base64Backend."""
return EPDBServe(backend=Base64Backend(), serve_options={"port": 9000}) | 02885892ae4409e743183f0b3a43824d8de53456 | 53,446 |
from numpy import log
def log_mean(T_hi, T_lo, exact=False):
"""
compute the logarithmic mean
"""
if exact:
return (T_hi-T_lo)/log(T_hi/T_lo)
else:
d = T_hi - T_lo
return T_hi - d/2*(1 + d/6/T_hi*(1 + d/2/T_hi)) | dcae1d753c416a117dc2f8502454d18f9413fc36 | 53,447 |
def getheader(header_text, default="ascii"):
"""Decode the specified header"""
headers = decode_header(header_text)
header_sections = [(text.encode(charset or default)).decode() if type(text) == str else text.decode(charset or default)
for text, charset in headers]
return ''.... | 44da35add8dd06899a6d73c104e6606d62ee2360 | 53,448 |
from pathlib import Path
import json
def load_json(fp_in):
"""Loads JSON and returns items
:param fp_in: (str) filepath
:returns: data from JSON
"""
if not Path(fp_in).exists():
log.error('file does not exist: {}'.format(fp_in))
return {}
with open(str(fp_in), 'r') as fp:
data = json.load(fp)
... | e6689b5f5650c34185adf9cb0d0de2e9a75aad71 | 53,449 |
def uniform_glorot(nin, nout, mean=0., gain=1., **kwargs):
"""
Uniform Glorot Initialization
:param nin:
:param nout:
:param mean:
:param gain: float or 'relu'
:return:
"""
if gain == 'relu':
gain = np.sqrt(2)
logger.warn('Uniform Glorot weight with {} fan-in, {} fan-out,... | d3e625c81fae23478e526bdb3b093fc64660ce9a | 53,450 |
def elevate(command, param="", wait=False):
"""
Execute a shell command with elevated rights when the current
user can have the privilge.
Deisgned to be used with Windows Vista, 7 and 8.
It also works on Windows XP although it is not necessary on many
occasions.
It may pops User Access Con... | a3c5131862e7e6baff0e3937f5d004ef7b6515a5 | 53,451 |
import torch
def pearson_corrcoef(preds: Tensor, target: Tensor) -> Tensor:
"""
Computes pearson correlation coefficient.
Args:
preds: estimated scores
target: ground truth scores
Example:
>>> from torchmetrics.functional import pearson_corrcoef
>>> target = torch.ten... | 8de3fea852585d14de6595f411ce15a14df83317 | 53,452 |
def get_local_env_method(method): # pylint:disable=too-many-return-statements
"""get a local environment method based on its name"""
method = method.lower()
if method.lower() == "crystalnn":
# see eq. 15 and 16 in
# https://pubs.acs.org/doi/full/10.1021/acs.inorgchem.0c02996
# for ... | 778f98153c53380b25339f21d0cda123bd642590 | 53,453 |
def name_for(obj):
"""
Get a name for something.
Allows overriding of default names using the `__alias__` attribute.
"""
if isinstance(obj, str):
return obj
cls = obj if isclass(obj) else obj.__class__
if hasattr(cls, "__alias__"):
return underscore(cls.__alias__)
els... | f875cf8233c3bd8443d28c61de9f413b4c82f524 | 53,454 |
def reduceSet(setList):
"""Step through a list of sets and combine sets that overlap.
This will create a unique list of sets, where each set contains the headers
of reads that optical duplicates."""
setList2 = [setList[0]]
for item1 in setList[1:]:
inSetList2 = False
for item2 ... | 4e7e763ae78d5cf97fa122f991b01529e12c86a5 | 53,455 |
def weird_compare(interval, start, end):
"""
This is a function that is used later on in data_upscale, to add a corrective integer (either 1 or 0),
when that function checks whether the image it is working on has reached the border.
This function is not expected to be used anywhere outside data_upscale.... | f4b67c2b740a318ad659d1001bd14d402dad9e21 | 53,456 |
def make_word(letters, beginnings=[], endings=[]):
"""Return word dictionary"""
return {
'word': ''.join(letters),
'letters': letters,
'beginnings': beginnings,
'endings': endings,
} | 0b53fd8e26d2ca80e8c54ffa08f9473fb7b9f902 | 53,457 |
def dependence_vector(iter_vars, iter_slices, source, sink, invariant=None):
"""
Uses ISL for dependence testing and returns the dependence vector.
iter_vars: Iteration variables
iter_slices: Iteration starts, stops and steps; stop is inclusive!
source, sink: Subscript objects
invariant: Loop i... | 015b6959c0b77b0e5bdbc45f6d66df7033fb71e8 | 53,458 |
import importlib
def get_role(classpath):
"""Get a role implementation by its path name."""
return importlib.get_class(classpath, __name__) | 6c124221085f18d08719b74c41e73e17e84c1689 | 53,459 |
import torch
def compute_batch_accuracy(output, target):
"""Computes the accuracy for a batch"""
with torch.no_grad():
batch_size = target.size(0)
_, pred = output.max(1)
correct = pred.eq(target).sum()
return correct * 100.0 / batch_size | b8ac6b891b2b1abc39cd9549c2d2a4a79c129577 | 53,460 |
import psutil
def get_ram_memory(units="Mb"):
"""Get the RAM memory of the current machine.
Args:
units (str): Units [bytes, Kb, Mb, Gb]
Returns:
float: Memory size.
Examples:
>>> num = get_ram_memory("Gb")
>>> num >= 4
True
"""
s_bytes =... | 144a09c631f94d4971b4c329bcd065cff77d16c6 | 53,461 |
def gsl_blas_zswap(*args, **kwargs):
"""gsl_blas_zswap(gsl_vector_complex * X, gsl_vector_complex * Y) -> int"""
return _gslwrap.gsl_blas_zswap(*args, **kwargs) | d069e57bf92b21ceb5d2e7d64b3f4d939599d9b8 | 53,462 |
import json
def create_user():
"""Endpoint to create a user data."""
data = json.loads(request.data)
password = data['password'].encode('utf-8')
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
user = User(username=data['username'], password=hashed.decode('utf-8'), phone=data['phone'],
... | 9edea341aa97107acf7e018761b89d4c0c91f953 | 53,463 |
import hashlib
def valid_proof(last_hash, proof, difficulty):
"""
Validates the Proof: Multi-ouroborus: Do the last six characters of
the hash of the last proof match the first six characters of the proof?
IE: last_hash: ...AE9123456, new hash 123456888...
"""
# TODO: Your code here!
... | f8ed217dc098898ef8d712b26828637218a1af7b | 53,464 |
def set_mon_sites(node: CephAdmin, tiebreaker_node) -> bool:
"""
Adds the mon daemons into the two sites with arbiter node at site 3 as a tie breaker
Args:
node: Cephadm node where the commands need to be executed
tiebreaker_node: name of the monitor to be added as tie breaker( site 3 )
... | b5f6cf9d06bbe8ac9664afc9e5b3d97a5a44aea4 | 53,465 |
import os
def data_together(filepath):
"""
:param filepath: all the csv files with raw data
:return:
"""
csvs = []
dfs = []
for subdir, dirs, files in os.walk(filepath):
for file in files:
filepath = subdir + os.sep + file
if filepath.endswith(".csv"):
... | 79e131cde3760435fc38bd18b692646506db31de | 53,466 |
def conv1d(
ni: int, no: int, ks: int = 1, stride: int = 1, padding: int = 0, bias: bool = False
):
"""Create and initialize a `nn.Conv1d` layer with spectral normalization.
Unmodified from
https://github.com/fastai/fastai/blob/5c51f9eabf76853a89a9bc5741804d2ed4407e49/fastai/layers.py
"""
conv ... | b7f0584c0c6ffe7ef5bd24403125826f6e8225a2 | 53,467 |
def _GetPrincipalQuantumNumber(atNum):
"""
*Internal Use Only*
Get the principal quantum number of atom with atomic
number equal to atNum
Parameters:
atNum: int
Returns:
PrincipalQuantumNumber: int
"""
if atNum <= 2:
return 1
elif atNum <= 10:... | 3176377b74a8ff8dd41b710137c2b2e79b9a1d53 | 53,468 |
import functools
def wrap_single_convertor(convert_single):
"""
Wraps a ``__ua_convert__`` defined for a single element to all elements.
If any of them return ``NotImplemented``, the operation is assumed to be
undefined.
Accepts a signature of (value, type, coerce).
"""
@functools.wraps(... | 9a937f5366b896d95c091db870952b923f5323fe | 53,469 |
def rot(theta):
"""returns a 2D-rotation matrix with rotation angle theta"""
R = np.array(((cos(theta), -sin(theta)),
(sin(theta), cos(theta))))
return R | f67b88a7c29300f88884f5130f1d16c99a00bb1e | 53,470 |
def integrate(params, t, gamma_max, nu_max, phiR, Kd=Kd):
"""
Integrates the system of differential equations, including the dilution
factor and assumes that nutrient concentration is high enough such that
nu ≈ nu_max.
"""
# Unpacking
Mr, Mp, cAA = params
gamma_max, nu_max, phiR = args... | d055c0a11c1dd3501f22ab4a060e4a3652746fbf | 53,471 |
def build_streamflow_cube(nc_files, river_ids=None, consistent_id_order=True):
"""Reads streamflow from several NWM files into a single array.
Reads streamflow from several files into a single array. Each file
from the National Water Model represents a single time step. This
function can be used to rea... | d08149ff7133026d4afc8992f998b11384aa233b | 53,472 |
def mutate(mushroom, i):
""" Randomly flips one bit in a mushroom bit string"""
return mushroom ^ 1 << i | ffac7c56cfe455928fcbb833d363441ef9a2a8a7 | 53,473 |
def avoid_multiple_update(func):
"""Decorator to prevent handlers to update multiple times."""
def wrapper(self, attr, old, new):
if self.in_update:
return
self.in_update = True
func(self, attr, old, new)
self.in_update = False
return wrapper | d35e9add88ddb62d1368ff0fbf94e9637518c249 | 53,474 |
def zeros(shape, dtype=float):
"""
Array of zeros.
Return an array of given shape and type, filled with zeros.
Parameters
----------
shape : {sequence of ints, int}
Shape of the array
dtype : data-type, optional
The desired data-type for the array, default is np.float64.
... | 50cc1bafdc2b1f25f40d5215846ad5cf8b76ec00 | 53,475 |
def node_draw_color(node):
"""given a row of a nodes() dataframe, return the color it should be drawn"""
if 'draw_color' in node.axes[0]:
# if this value has already been calculated
return node.draw_color
color = '#d2d2e6' # (210, 210, 230) #default color
if 'HoursFlooded' in node and... | 42fc4c392d872f94a58c753c1c62569b1302fd0a | 53,476 |
from typing import Callable
def tabulated(dr: Array, spline: Callable[[Array], Array], **unused_kwargs) -> Array:
"""
Tabulated radial potential between particles given a spline function.
Args:
dr: An ndarray of pairwise distances between particles
spline: A function computing the spline ... | 0118cc34a8b8c0e80223aca572a13f10121479ea | 53,477 |
import numpy as np
def create_slice_mask(plane_dict, infile_dims):
"""Create a binary array defining a mask covering the area below a given
plane in the 3D image.
:type plane_dict: dict
:param plane_dict: A dictionary matching z voxel coordinates to
corresponding (x,y) coordina... | ca25e627dc93b3828b7ea49c139e1f9fc5950f6e | 53,478 |
def postprocess_braces(value, **options):
"""Remove any braces from a string value."""
if bibpy.is_string(value):
return "".join([e for e in bibpy.parser.parse_braced_expr(value)
if e not in '{}'])
return value | 78db8d678a9d023394e7e9a59f2cd82d565c0cdf | 53,479 |
def row2dict(row):
"""
Converts a row of SQLAlchemy into a dictionary
:see: http://stackoverflow.com/questions/1958219/convert-sqlalchemy-row-object-to-python-dict
:param row: SQLAlchemy row
:return: dictionary
"""
if row is None:
return None
d = {}
if hasattr(row, '__table_... | f5ccfcc919e79340b668d1f99c52223fa48ea5f8 | 53,480 |
from typing import List
import json
def retrieve_by_index(index_dir_path: str, question: str, top_k: int=1) -> List[str]:
"""
Retrieves the most relevant passages to a question, using the indexed embedding of the passages.
:param index_dir_path: path to the index and texts.
:param question:
:para... | 45a72078bab65b8d1bb56997c839f4f350fcd247 | 53,481 |
def unsigned_to_signed(seq, width):
"""
Convert unsigned integer to signed.
"""
out = []
k = pow(2, width)
for x in seq:
if x >= k/2:
x -= k
out.append(x)
return out | b7b90ff4de576bee2e91af27f6fc3b509608ef34 | 53,482 |
import signal
def ssim(img1, img2, cs_map=False):
"""Return the Structural Similarity Map corresponding to input images img1
and img2 (images are assumed to be uint8)
This function attempts to mimic precisely the functionality of ssim.m a
MATLAB provided by the author's of SSIM
https://ece.... | dbd347bc4cf026cb0e0ffef17812f7783a3aa921 | 53,483 |
def _hash(host, username, password, hasher_params):
"""Performs a hash operation on the given host with the given hasher parameters (hasherWsParams) and returns
a hasherWsResult record with these fields:
- blockFileDataHandler (base64Binary)
- blockFileName (string)
- bytesHashed (long)
- elapse... | d9c7330c1c2df54744c15f42d347fa4fd28254c1 | 53,484 |
def l2_distance(x, y):
"""Computes cosine similarity between all pairs of vectors in x and y."""
x_expanded, y_expanded = x[:, tf.newaxis], y[tf.newaxis, :]
return tf.sqrt(tf.reduce_sum((x_expanded - y_expanded)**2, axis=-1)) | a6fdf06c7facba2f63799786dfa8085602e8c070 | 53,485 |
def per_device_batch_size(batch_size, num_gpus):
"""For multi-gpu, batch-size must be a multiple of the number of GPUs.
Note that this should eventually be handled by DistributionStrategies
directly. Multi-GPU support is currently experimental, however,
so doing the work here until that feature is in place.
... | 5191fb313ba26026cb1bd61173a3f983ca42f5b6 | 53,486 |
def organisation_information_save(request,organisation_id):
"""
:param request:
:param organisation_id:
:return:
"""
# ADD IN PERMISSION CHECKING
# Get the form data
form = OrganisationForm(request.POST)
if not form.is_valid():
return HttpResponseBadRequest(form.errors)
... | e183b2b79064b86d3007b55ca63ce0012c9c63c7 | 53,487 |
from typing import Optional
from typing import List
from typing import Tuple
def _monkey_patch_python_domain_to_resolve_params():
"""Adds support to the Python domain for resolving parameter references."""
PythonDomain = sphinx.domains.python.PythonDomain # pylint: disable=invalid-name
orig_resolve_xref = Pyt... | 408e0fa3e3019b0ea3ebbcc1d0af03e13853fa0e | 53,488 |
def containerhasprefix(obj, prefix):
"""
Returns whether obj's container starts with prefix.
"""
return obj.container.name.startswith(prefix) | dcf4b14cfa1ac15355e7db5110be55b623e35f20 | 53,489 |
def _variance(mean_variance, samples):
"""Perform final variance calculations.
`mean_variance` and `samples` were pre-recorded with
`options.record.reduction._variance`.
This operation only calculates total running variance.
This function is applied on per-recording basis (per layer to be exact).... | 0bcc9705205304d8338843a3c09c8ae1f2314bb6 | 53,490 |
import os
def get_connections_db(ccs_path):
"""Returns path to connections folder"""
conns_path = get_targetDB(ccs_path) + '/' + CONNECTIONS
return os.path.normpath(conns_path) | eb6afd07ce78045a1a5acff01efa6717d49b1ccf | 53,491 |
import tqdm
def trange(*args, **kwargs):
"""
A shortcut for tqdm(xrange(*args), **kwargs).
On Python3+ range is used instead of xrange.
"""
return tqdm(_range(*args), **kwargs) | 991ff44ab461b9c78639b0d4d0621d959f0a0a2b | 53,492 |
from pathlib import Path
import json
def load_event_schema(event_type, suffix=None):
"""Load an Avro schema for a Slack Events API event from the local app
data.
This function is memoized so that repeated calls are fast.
Parameters
----------
event_type : `str`
Name of an event type,... | 7741549c1703ed300a25081274dd42dfc8e59eec | 53,493 |
import six
def choose_part_ranges(content_length, minimum_part_size):
"""
Returns a list of (offset, length) for the parts of a large file.
:param content_length: content length value
:type content_length: int
:param minimum_part_size: a minimum file part size
:type minimum_part_size: int
... | 28acbe2df14d6f54a95ab74c18e410a076354187 | 53,494 |
def line_too_long(editor, item):
""" Pylint line-too-long method """
line_no = item.line_no
error_text = editor.lines[line_no]
new_lines = line_split(error_text, 100)
if not new_lines:
LOGGER.info("Could not split: {0}".format(error_text))
result = (line_no, 0)
else:
asse... | cbd450bcac63e46482fec2248939548bd6931399 | 53,495 |
from typing import Dict
from typing import Any
def __process_input_of_start_premises(premisegroups, db_conclusion: Statement, supportive, db_issue: Issue,
db_user: User) -> Dict[str, Any]:
"""
Inserts premises of groups as new arguments in dependence of the input paramete... | f4c089887520866a84d0db15b67064ff1b2692c6 | 53,496 |
import torch
def sampled_softmax(pre_logits, log_std, samples=10):
"""
Draw samples from gaussian distributed pre-logits and use these to estimate
a mean and aleatoric uncertainty.
"""
# NOTE here as we do not risk dividing by zero should we really be
# predicting log_std or is there another w... | a834cc575ed33729f5778e3b44ead0a04e4b0f9a | 53,497 |
from pathlib import Path
import shutil
import sys
def load_codebook(experiment_fpath: str, metadata: str) -> dict:
"""Function used to load the codebooks. It links the channel to
the codebook pandas dataframe
Args:
experiment_fpath (str): Path to the experiment to process
metadata (dict):... | 8bd59bf23df16f1f4d0b984c9c119abda3834cf8 | 53,498 |
from operator import and_
def remove_actions_that_are_not_wildcard_arn_only(db_session, actions_list):
"""
Given a list of actions, remove the ones that CAN be restricted to ARNs, leaving only the ones that cannot.
:param db_session: SQL Alchemy database session object
:param actions_list: A list of ... | b8d74e56fb0fe305e24ebb1b865066b8fdc68daf | 53,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.