content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import types
def parse_container_args(field_type: type) -> types.Union[ParamType, types.Tuple[ParamType]]:
"""Parses the arguments inside a container type (lists, tuples and so on).
Args:
field_type (type): pydantic field type
Returns:
types.Union[ParamType, types.Tuple[ParamType]]: sing... | 925ceab7886f47c41ed5b3189693db2a28c37db1 | 12,200 |
def decrypt_from_base64(ciphertext_bs64, decrypt_key: str , iv : str) -> str:
"""From base64 ciphertext decrypt to string.
"""
aes: AES_Turbe = AES_Turbe(decrypt_key,iv)
content_str = aes.decrypt_from_base64(ciphertext_bs64)
return content_str | 67c4e1bb610b4a28d6fc563b910e86554779f1f2 | 12,201 |
def _resize_data(image, mask):
"""Resizes images to smaller dimensions."""
image = tf.image.resize_images(image, [480, 640])
mask = tf.image.resize_images(mask, [480, 640])
return image, mask | 47961541bf903c8b84066766529bf28d268eaa36 | 12,202 |
def dist_Mpc_to_geo(dist):
"""convert distance from Mpc to geometric units (i.e., metres)"""
return dist * Mpc | d023b80da73420f5499be0eb14f4d2e515e54627 | 12,203 |
def upload_to_bucket(file_path, filename):
"""
Upload file to S3 bucket
"""
s3_client = boto3.client('s3')
success = False
try:
response = s3_client.upload_file(file_path, AWS_S3_BUCKET_NAME, filename)
success = True
except ClientError as e:
logger.error('Error at %s'... | 630937591307d9ec55fe606b2e199b1219139bcb | 12,204 |
import os
def osqueryd_log_parser(osqueryd_logdir=None,
backuplogdir=None,
maxlogfilesizethreshold=None,
logfilethresholdinbytes=None,
backuplogfilescount=None,
enablediskstatslogging=False,
... | 96428f3984b688b3a55c5d5b37087fcec97c12f4 | 12,205 |
import os
def get_filenames(data_dir, mode, valid_id, pred_id, overlap_step, patch_size):
"""Returns a list of filenames."""
if mode == 'train':
train_files = [
os.path.join(data_dir, 'subject-%d.tfrecords' % i)
for i in range(1, 11)
if i != valid_id
]
for f in train_files:
assert os.path.isfile(... | 255a89254c860d7bbd7941da017e7e015406cf8d | 12,206 |
def downsample_data( data, factor, hdr ):
"""Resample data and update the header appropriately
If factor < 1, this is *upsampling*.
Use this function to just return the data and hdr parts in case you want to do further operations prior to saving.
order=3 appears to crash Python 64-bit on ... | 889e698531255b862fe407d5ce64a3ed54b44c44 | 12,207 |
def check_if_present(driver: webdriver.Firefox, selector: str):
""" Checks if element is present on page by css selector """
return bool(driver.find_elements_by_css_selector(selector)) | 9cc4ebf92908ed8ef392cc20697734d553eb6db0 | 12,208 |
import glob
import os
def list_pdf_paths(pdf_folder):
"""
list of pdf paths in pdf folder
"""
return glob(os.path.join(pdf_folder, '*', '*', '*.pdf')) | 793629d3fbbc9c072f1b1bedbd374e10a1d88781 | 12,209 |
def cmi(x, y, z, k=3, base=2):
"""Mutual information of x and y, conditioned on z
x,y,z should be a list of vectors, e.g. x = [[1.3], [3.7], [5.1], [2.4]]
if x is a one-dimensional scalar and we have four samples
"""
assert len(x)==len(y), 'Lists should have same length.'
assert k <= len(x) - 1, 'Set k smal... | b79a39dbe98202fedf4f572148cdce81c6608e3c | 12,210 |
def connected_plate():
"""Detects which plate from the PMA is connected to the device.
Returns:
FirmwareDeviceID: device ID of the connected plate. None if not detected
"""
for plate_id in (
FirmwareDeviceID.pt4_foundation_plate,
FirmwareDeviceID.pt4_expansion_plate,
):
... | 4db471df81d63aa3c60f24b50fc25cef452db2d7 | 12,211 |
def islogin(_a=None):
"""
是否已经登录,如果已经登录返回token,否则False
"""
if _a is None:
global a
else:
a = _a
x=a.get(DOMAIN+"/apps/files/desktop/own",o=True)
t=a.b.find("input",{"id":"request_token"})
if t is None:
t = a.b.find("input",{"id":"oc_requesttoken"})
if t is Non... | 235a4662ecca8c496b83aec5bc0408bbd8ae45ec | 12,212 |
def discrete_coons_patch(ab, bc, dc, ad):
"""Creates a coons patch from a set of four or three boundary
polylines (ab, bc, dc, ad).
Parameters
----------
ab : list[[float, float, float] | :class:`~compas.geometry.Point`]
The XYZ coordinates of the vertices of the first polyline.
bc : li... | 19393f8eea5164e0f6cf89463dd3d68329c395d5 | 12,213 |
def w(shape, stddev=0.01):
"""
@return A weight layer with the given shape and standard deviation. Initialized with a
truncated normal distribution.
"""
return tf.Variable(tf.truncated_normal(shape, stddev=stddev)) | fd3d0bb6fb5565ce4ff5b4aafb80eccf711072db | 12,214 |
def lr_mult(alpha):
"""Decreases the learning rate update by a factor of alpha."""
@tf.custom_gradient
def _lr_mult(x):
def grad(dy):
return dy * alpha * tf.ones_like(x)
return x, grad
return _lr_mult | b5ab1c2b01025aee74c5f4c92b81eabf08c20de1 | 12,215 |
import PIL
import io
def get_png_string(mask_array):
"""Builds PNG string from mask array.
Args:
mask_array (HxW): Mask array to generate PNG string from.
Returns: String of mask encoded as a PNG.
"""
# Convert the new mask back to an image.
image = PIL.Image.fromarray(mask_array.ast... | f44dd5417cb5250587926da939b5923921c62ead | 12,216 |
def rotate90ccw(v):
"""Rotate 2d vector 90 degrees counter clockwise
"""
return (-(v[1]), v[0]) | cde43efd01e9fff3002623437f99e521790e33f2 | 12,217 |
def GetListOfCellTestPointsNearestListOfPointsV5(inInputFilter, pointList):
"""for each point in the list, find the cell test point (e.g. center of
cell bounding box) which is nearest the test point. Use MPI to work
in parallel"""
thisProcessNearestCellPointList, thisProcDistSqrdList = \
GetCellsClo... | c4dc0fcdb9d85dbc2ce1654743284400ca11e3d6 | 12,218 |
def _BuildBaseMTTCmd(args, host):
"""Build base MTT cmd."""
remote_mtt_binary = _REMOTE_MTT_BINARY_FORMAT % host.context.user
remote_cmd = [remote_mtt_binary]
if args.very_verbose:
remote_cmd += ['-vv']
elif args.verbose:
remote_cmd += ['-v']
# We copy the mtt binary inside mtt_lab to remote host,
... | 7506a39b79c81bc3b279280e69820ccdbb8ed664 | 12,219 |
def get_service(credentials=get_credentials()):
"""Gets GMail service, given credentials"""
return apiclient.discovery.build("gmail", "v1", credentials=credentials) | 7f344f07cc2d78014381bd449d6655658f2e4881 | 12,220 |
def edb_client_server_info(edb: ElectrolyteDB) -> dict:
"""
Perform an operation that ensures that the `edb` fixture has a client that:
- Is able to connect to the server (non-mock), or
- Is a "convincing fake" (mock), so that test functions using `edb` can expect a realistic behavior
Additiona... | 83e9d4bb7bf76e7ed5a73c69a4a2a617227526f8 | 12,221 |
def convert_to_int_list(dataframe: pd.Series) -> "list[list[int]]":
"""
Takes a dataframe with a string representation of a list of ints
and converts that into a list of lists of ints
"""
result_list = []
for row in dataframe:
result_list.append([int(x) for x in row[1:-1].split(", ")])
... | 0d0ed69db3af04a21a65d472c53580d8f88f50f0 | 12,222 |
def get_prism_daily_single(variable,
date,
return_path=False,
**kwargs):
"""Download data for a single day
Parameters
----------
variable : str
Either tmean, tmax, tmin, or ppt
date : str
The d... | 5fe14da937452e040e2fcf7d38d04d1068f2bff8 | 12,223 |
import base64
import io
def handle_filestreams(list_of_contents, list_of_names):
"""
Args:
list_of_contents:
list_of_names:
"""
if len(list_of_contents) == 1:
content = list_of_contents[0]
filename = list_of_names[0]
else:
raise Exception("Multiple files not... | 3ab582bbf6d709d0ebcdb6f71825734f43e8bc86 | 12,224 |
def grid_count(grid, shape=None, interpolation='linear', bound='zero',
extrapolate=False):
"""Splatting weights with respect to a deformation field (pull adjoint).
Notes
-----
{interpolation}
{bound}
Parameters
----------
grid : ([batch], *inshape, dim) tensor
T... | 620713f2e234d1a2195fdebba5215a2c1f2493a3 | 12,225 |
def check_spf_record(lookup, spf_record):
"""
Check that all parts of lookup appear somewhere in the given SPF record, resolving
include: directives recursively
"""
not_found_lookup_parts = set(lookup.split(" "))
_check_spf_record(not_found_lookup_parts, spf_record, 0)
return not not_found_l... | 831c6d07a91484ce6b96bdc507a8f31034193590 | 12,226 |
import pytz
def local_tz2() -> pytz.BaseTzInfo:
"""
Second timezone for the second user
"""
return pytz.timezone("America/Los_Angeles") | d841f3ea06334540b8dca6fd2c2a2e823227fa37 | 12,227 |
def get_chemistry_info(sam_header, input_filenames, fail_on_missing=False):
"""Get chemistry triple information for movies referenced in a SAM
header.
Args:
sam_header: a pysam.Samfile.header, which is a multi-level dictionary.
Movie names are read from RG tags in this header.
... | 4bfdd7f09061650c0e010f71cd00cbd44481c40f | 12,228 |
import warnings
import http
def json_catalog(request, domain='djangojs', packages=None):
"""
Return the selected language catalog as a JSON object.
Receives the same parameters as javascript_catalog(), but returns
a response with a JSON object of the following format:
{
"catalog"... | f2ac449d11299471184f0ddaeac87d543e90b7a3 | 12,229 |
from typing import Dict
from typing import Any
def read_global_config() -> Dict[Text, Any]:
"""Read global Rasa configuration."""
# noinspection PyBroadException
try:
return rasa.utils.io.read_yaml_file(GLOBAL_USER_CONFIG_PATH)
except Exception:
# if things go south we pretend there is... | 0287aa03a07b7ce5218f56237cd49d9ea18f8d5f | 12,230 |
def get_uuid_hex(digest_size: int = 10) -> str:
"""Generate hex of uuid4 with the defined size."""
return blake2b(uuid4().bytes, digest_size=digest_size).hexdigest() | 4ec853740b7f17bbf7cb90fd5e25c9d7719440c8 | 12,231 |
def crc16(data):
"""CRC-16-CCITT computation with LSB-first and inversion."""
crc = 0xffff
for byte in data:
crc ^= byte
for bits in range(8):
if crc & 1:
crc = (crc >> 1) ^ 0x8408
else:
crc >>= 1
return crc ^ 0xffff | 2560f53c1f2b597d556a0b63462ef56f0c972db2 | 12,232 |
def _unlink_f(filename):
""" Call os.unlink, but don't die if the file isn't there. This is the main
difference between "rm -f" and plain "rm". """
try:
os.unlink(filename)
return True
except OSError, e:
if e.errno not in (errno.ENOENT, errno.EPERM, errno.EACCES,errno.EROFS):... | f0014e7ab0dfb6db519198f1eb052d930542a63f | 12,233 |
def get_member_expr_fullname(expr: MemberExpr) -> str:
"""Return the qualified name representation of a member expression.
Return a string of form foo.bar, foo.bar.baz, or similar, or None if the
argument cannot be represented in this form.
"""
if isinstance(expr.expr, NameExpr):
initial = ... | 2859751a977f028f0984e86422f31f388314414a | 12,234 |
def _read_dino_waterlvl_metadata(f, line):
"""read dino waterlevel metadata
Parameters
----------
f : text wrapper
line : str
line with meta dictionary keys
meta_dic : dict (optional)
dictionary with metadata
Returns
-------
meta : dict
dictionary with metad... | 949535f4fc677a7d0afc70a76e377ccefcc8943f | 12,235 |
def async_get_url(
hass: HomeAssistant,
*,
require_ssl: bool = False,
require_standard_port: bool = False,
allow_internal: bool = True,
allow_external: bool = True,
allow_cloud: bool = True,
allow_ip: bool = True,
prefer_external: bool = False,
prefer_cloud: bool = False,
) -> st... | 1d4e13a8fa5d26bbc9132e85937a24d320136112 | 12,236 |
import os
def validate_local_model(models_path: str, model_id: str) -> bool:
"""Validate local model by id.
Args:
models_path: Path to the models folder.
model_id: Model id.
"""
model_correct = True
model_path = os.path.join(models_path, model_id)
if not os.path.exists(model_p... | 9e081b5175ceb46d2caac57d0342f4660946d18e | 12,237 |
def strip(prefix: Seq, seq: Seq, partial=False, cmp=NOT_GIVEN) -> Iter:
"""
If seq starts with the same elements as in prefix, remove them from
result.
Args:
prefix:
Prefix sequence to possibly removed from seq.
seq:
Sequence of input elements.
partial:
... | 8d2a9a62157e3b55adcc976d5c7693cb67513c92 | 12,238 |
def _read_unicode_table(instream, separator, startseq, encoding):
"""Read the Unicode table in a PSF2 file."""
raw_table = instream.read()
entries = raw_table.split(separator)[:-1]
table = []
for point, entry in enumerate(entries):
split = entry.split(startseq)
code_points = [_seq.de... | e27e59b57d10cb20dd4ddc832c65cb8802984d44 | 12,239 |
from click.testing import CliRunner
def runner():
"""Provides a command-line test runner."""
return CliRunner() | 82b75c8dcaa0105c623a1caea5b459c97e3e18fd | 12,240 |
def matsubara_exponents(coup_strength, bath_broad, bath_freq, beta, N_exp):
"""
Calculates the exponentials for the correlation function for matsubara
terms. (t>=0)
Parameters
----------
coup_strength: float
The coupling strength parameter.
bath_broad: float
A parameter cha... | 4d6a1691234f12a5cbdec13b2520891c0f30eb77 | 12,241 |
def reverse(array):
"""Return `array` in reverse order.
Args:
array (list|string): Object to process.
Returns:
list|string: Reverse of object.
Example:
>>> reverse([1, 2, 3, 4])
[4, 3, 2, 1]
.. versionadded:: 2.2.0
"""
# NOTE: Using this method to reverse... | 5eb096d043d051d4456e08fae91fb52048686992 | 12,242 |
def compute_segregation_profile(gdf,
groups=None,
distances=None,
network=None,
decay='linear',
function='triangular',
precomput... | 3598d7c72660860330847758fc744fcd1b1f40ce | 12,243 |
def calculate_lbp_pixel(image, x, y):
"""Perform the LBP operator on a given pixel.
Order and format:
32 | 64 | 128
----+-----+-----
16 | 0 | 1
----+-----+-----
8 | 4 | 2
:param image: Input image
:type: numpy.ndarray
:param x: ... | 14f6bd557355a71379b638e52f21d72ccd30a7cb | 12,244 |
def test_gradient_sparse_var():
"""
https://www.tensorflow.org/beta/guide/effective_tf2
"""
target = tf.constant([[1., 0., 0.], [1., 0., 0.]])
v = tf.Variable([0.5, 0.5])
x = tx.Lambda([],
fn=lambda _: tf.SparseTensor([[0, 0], [1, 1]], v, [2, 3]),
n_units=3,... | e43a84a052313fecd11eca60a027f00385cd252f | 12,245 |
def get_setup_and_moves(sgf_game, board=None):
"""Return the initial setup and the following moves from an Sgf_game.
Returns a pair (board, plays)
board -- boards.Board
plays -- list of pairs (colour, move)
moves are (row, col), or None for a pass.
The board represents the posi... | a933c067baa49d8e6c7309f7762298244a192d2e | 12,246 |
def help_text_metadata(label=None, description=None, example=None):
"""
Standard interface to help specify the required metadata fields for helptext to
work correctly for a model.
:param str label: Alternative name for the model.
:param str description: Long description of the model.
:param exa... | a1fb9c9a9419fe7ce60ed77bc6fadc97ed4523f8 | 12,247 |
def conv1d_stack(sequences, filters, activations, name=None):
"""Convolve a jagged batch of sequences with a stack of filters.
This is equivalent to running several `conv1d`s on each `sequences[i]` and
reassembling the results as a `Jagged`. The padding is always 'SAME'.
Args:
sequences: 4-D `Jagged` ten... | 33248627280ea0c127d710128790e58e0ca5bb9a | 12,248 |
def dh_mnthOfYear(value, pattern):
"""
Helper for decoding a single integer value.
The value should be >=1000, no conversion,
no rounding (used in month of the year)
"""
return dh_noConv(value, pattern, _formatLimit_MonthOfYear[0]) | 5dd1027a0713cb93ea6e3504f1a07517f228a037 | 12,249 |
from typing import Counter
def build_team(datafile, salary_col, position_col, prediction_col, cap=60000, legal_teams=None):
"""
Construct teams from a set of prediction data
:param str datafile: saved prediction data (pickle file)
:param str salary_col: name of salary column
:param str position_col: name of... | c1ac67fe72926e2f97268e753d3d97d9f8169840 | 12,250 |
import traceback
import six
def serialize_remote_exception(failure_info):
"""Prepares exception data to be sent over rpc.
Failure_info should be a sys.exc_info() tuple.
"""
tb = traceback.format_exception(*failure_info)
failure = failure_info[1]
kwargs = {}
if hasattr(failure, 'kwargs'... | 549b996afc2b07b9e72f69cd2c6ddaee4010f5af | 12,251 |
def build_eval_graph(features, model):
"""
builds evaluation graph
"""
_params = {}
logger.debug("building evaluation graph: %s.", _params)
with tf.variable_scope("loss"):
loss = tf.losses.sigmoid_cross_entropy(multi_class_labels=tf.expand_dims(features["sentiment"], axis=1),
... | a63f88d30c817dfc648f6b774acfb78efd6db42c | 12,252 |
import pprint
def in_common(routes):
"""routes is a list of lists, each containing a route to a peer."""
r = []
branch = False
for n in izip_any(*routes): #itertools.izip(*routes):
# strip dead nodes
f = [i for i in n if i != '*']
# ignore all dead nodes
if len(f) == ... | 82858ea2abb2e8fd1ffaaefef3d07c9aeb29c61a | 12,253 |
def process_polygon(coordinates):
"""Pass list of co-ordinates to Shapely Polygon function and get polygon object"""
return Polygon(coordinates) | fe644dc41e7951a030df511bb7e76b2e74883cae | 12,254 |
def split_function(vector, column, value):
"""
Split function
"""
return vector[column] >= value | c6129422fd5bf0b16229e6346adde5f50b203e7b | 12,255 |
def blackwell(Sv, theta, phi, r,
r0=10, r1=1000,
tSv=-75, ttheta=702, tphi=282,
wtheta=28 , wphi=52):
"""
Detects and mask seabed using the split-beam angle and Sv, based in
"Blackwell et al (2019), Aliased seabed detection in fisheries acoustic
data". Comple... | a4a8a925feaabad0002c36bc945aa74a99e30ade | 12,256 |
def _excitation_operator( # pylint: disable=invalid-name
edge_list: np.ndarray, p: int, q: int, h1_pq: float
) -> SparsePauliOp:
"""Map an excitation operator to a Pauli operator.
Args:
edge_list: representation of graph specifying neighboring qubits.
p: First Fermionic-mode index.
q: Se... | 0ae0ace12884c507977cf2e555a354c80f83e7ad | 12,257 |
def send_message( message, node, username, password, resource, max_attempts=1 ):
""" broadcast this message thru lvalert """
tmpfilename = "tmpfile.json"
tmpfile = open(tmpfilename, "w")
tmpfile.write( message )
tmpfile.close()
cmd = "lvalert_send -a %s -b %s -r %s -n %s -m %d --file %s"%(user... | 5ebec2f3487b431a6d1131b11c8ab2d672308b48 | 12,258 |
def create_bcs(field_to_subspace, Lx, Ly, solutes,
V_boundary,
enable_NS, enable_PF, enable_EC,
**namespace):
""" The boundary conditions are defined in terms of field. """
boundaries = dict(wall=[Wall()])
bcs = dict(
wall=dict()
)
bcs_pointwise... | d1e72d30404ee68b877c6761a6309884e3054b6c | 12,259 |
def get_response_rows(response, template):
"""
Take in a list of responses and covert them to SSE.Rows based on the column type specified in template
The template should be a list of the form: ["str", "num", "dual", ...]
For string values use: "str"
For numeric values use: "num"
For dual values:... | c3c3e4bf53929895959948836a77893b2f961221 | 12,260 |
def stations_within_radius(stations, centre, r):
"""function that returns a list of all stations (type MonitoringStation)
within radius r of a geographic coordinate x."""
close_stations = []
for station in stations:
if haversine(station.coord, centre) < float(r):
close_stations.appe... | 9877020f56f25435d1dad6fae32ebbae0e7cfdaf | 12,261 |
import os
import json
def get_pack_display_name(pack_id: str) -> str:
"""
Gets the display name of the pack from the pack ID.
:param pack_id: ID of the pack.
:return: Name found in the pack metadata, otherwise an empty string.
"""
metadata_path = os.path.join(PACKS_FULL_PATH, pack_id, PACK_ME... | feac51303f2a2b99dd2890cfc9fade74b45324db | 12,262 |
import os
import tqdm
def tflite_conversion(model, tflite_path, conversion_type="fp32"):
"""Performs tflite conversion (fp32, int8)."""
# Prepare model for inference
model = prepare_model_for_inference(model)
create_directories([os.path.dirname(tflite_path)])
converter = tf.lite.TFLiteConverter.f... | 9764243cfd037424a19bda35c2d20dff472851cf | 12,263 |
import torch
def jacobian(model, x, output_class):
"""
Compute the output_class'th row of a Jacobian matrix. In other words,
compute the gradient wrt to the output_class.
:param model: forward pass function.
:param x: input tensor.
:param output_class: the output_fz class we want to compute t... | 07364b8cc58d3ba51431d07e6bf5d164da7ab380 | 12,264 |
def render_face_orthographic(mesh, background=None):
"""
mesh location should be normalized
:param mesh:
:param background:
:return:
"""
mesh.visual.face_colors = np.array([0.05, 0.1, 0.2, 1])
mesh = pyrender.Mesh.from_trimesh(mesh, smooth=False)
# mesh = pyrender.Mesh.from_trimesh(... | 21cc7adaaebec7d8114f8192ccdc133075a19bc3 | 12,265 |
def check_and_join(phrase, symbols=None, filter=None):
"""
Joins characters of ``phrase`` and if ``symbols`` is given, raises
an error if any character in ``phrase`` is not in ``symbols``.
Parameters
==========
phrase
String or list of strings to be returned as a string.
symbols
... | 64ddcedf19ecba17b169e4bc3a3c205fe3192eb7 | 12,266 |
from typing import Optional
from typing import Set
def rigs_from_file(filepath: str, sensor_ids: Optional[Set[str]] = None) -> kapture.Rigs:
"""
Reads rigs from CSV file.
:param filepath: input file path
:param sensor_ids: input set of valid sensor ids.
If a rig id collides on... | c7fffcf28df54fb345b2638c02d79f40256cbb78 | 12,267 |
def drawLaneOnImage(img):
"""
Find and draw the lane lines on the image `img`.
"""
left_fit, right_fit, left_fit_m, right_fit_m, _, _, _, _, _ = findLines(img)
output = drawLine(img, left_fit, right_fit)
return cv2.cvtColor( output, cv2.COLOR_BGR2RGB ) | aa42679c7ff8f90b906d8cf74af9207edeadc430 | 12,268 |
def enthalpy_diff(SA, CT, p_shallow, p_deep):
"""
Calculates the difference of the specific enthalpy of seawater between
two different pressures, p_deep (the deeper pressure) and p_shallow (the
shallower pressure), at the same values of SA and CT. This function uses
the computationally-efficient 48... | 4a7251f41b073127cf1a2882614986987f085c30 | 12,269 |
import numpy
def ss(a, axis=0):
### taken from SciPy
"""Squares each value in the passed array, adds these squares, and
returns the result.
Parameters
----------
a : array
axis : int or None
Returns
-------
The sum along the given axis for (a*a).
"""
a, axis = _chk_asarray(a, axis)
return numpy.sum(a... | 75569fa96fd866f20b57c5f5c52a38e1b9663968 | 12,270 |
def Journaling_TypeInfo():
"""Journaling_TypeInfo() -> RTTI"""
return _DataModel.Journaling_TypeInfo() | 24cdb273b6463874e71668a304af3a13305fff24 | 12,271 |
def _maven_artifact(
group,
artifact,
version,
ownership_tag = None,
packaging = None,
classifier = None,
exclusions = None,
neverlink = None,
testonly = None,
tags = None,
flatten_transitive_deps = None,
aliases = None):
... | 9f97cd8cadfc3ad1365cb6d291634a9362fea4e8 | 12,272 |
import sys
def docmdnf(cmd):
"""Execute a command."""
if flag_echo:
sys.stderr.write("executing: " + cmd + "\n")
if flag_dryrun:
return 0
return u.docmdnf(cmd) | c21d06c34a913d62995447392dd62d2524b1253e | 12,273 |
def get_anchors(n):
"""Get a list of NumPy arrays, each of them is an anchor node set"""
m = int(np.log2(n))
anchor_set_id = []
for i in range(m):
anchor_size = int(n / np.exp2(i + 1))
for _ in range(m):
anchor_set_id.append(np.random.choice(n, size=anchor_size, replace=False... | 4adbaa291740ab3d9cb0a3d6b48c39665d8d5b06 | 12,274 |
def diag_gaussian_log_likelihood(z, mu=0.0, logvar=0.0):
"""Log-likelihood under a Gaussian distribution with diagonal covariance.
Returns the log-likelihood for each dimension. One should sum the
results for the log-likelihood under the full multidimensional model.
Args:
z: The value to compute the l... | 7265103ddfc5c521fd9612524413cd15e237be9b | 12,275 |
def _filter_option_to_config_setting(flt, setting):
"""
Encapsulates the logic for associating a filter database option with the filter setting from relay_config
:param flt: the filter
:param setting: the option deserialized from the database
:return: the option as viewed from relay_config
"""
... | 41694d340285b722daf91fb0badeb1ec33eb0587 | 12,276 |
def get_svg(accession, **kwargs):
"""
Returns a HMM sequence logo in SVG format.
Parameters
----------
accession : str
Pfam accession for desired HMM.
**kwargs :
Additional arguments are passed to :class:`LogoPlot`.
"""
logoplot = plot.LogoPlot(accession, **kwargs)
... | 952c6afa4d63f46be579cd70a4e2756b061b9f9b | 12,277 |
def wl_to_en( l ):
"""
Converts a wavelength, given in nm, to an energy in eV.
:param l: The wavelength to convert, in nm.
:returns: The corresponding energy in eV.
"""
a = phys.physical_constants[ 'electron volt-joule relationship' ][ 0 ] # J
return phys.Planck* phys.c/( a* l* 1e-9 ) | a9d428d7aed3a6c88a1906e026649ee74f700c81 | 12,278 |
from typing import Optional
def get_local_address_reaching(dest_ip: IPv4Address) -> Optional[IPv4Address]:
"""Get address of a local interface within same subnet as provided address."""
for iface in netifaces.interfaces():
for addr in netifaces.ifaddresses(iface).get(netifaces.AF_INET, []):
... | ee7061633d72c3b0ac578baf6119e5437395ce17 | 12,279 |
def atSendCmdTest(cmd_name: 'str', params: 'list'):
""" 发送测试命令,方便调试 ATCore
"""
func_name = 'atSendCmdTest'
atserial.ATraderCmdTest_send(cmd_name, params)
res = recv_serial(func_name)
atReturnChecker(func_name, res.result)
return res.listResult | 4cbe127ea7291893d64d8554c5a405c24085320a | 12,280 |
def unlabeled_balls_in_unlabeled_boxes(balls, box_sizes):
"""
OVERVIEW
This function returns a generator that produces all distinct distributions of
indistinguishable balls among indistinguishable boxes, with specified box
sizes (capacities). This is a generalization of the most common formulation
o... | 13743a7207f1d4fd2635f35c9eaef0a9acf53fa0 | 12,281 |
def get_version():
"""Extract current version from __init__.py."""
with open("morphocell/__init__.py", encoding="utf-8") as fid:
for line in fid:
if line.startswith("__version__"):
VERSION = line.strip().split()[-1][1:-1]
break
return VERSION | 69a00c2e5544dfd8d86cdab8be53c17b73764aca | 12,282 |
def get_neighbor_v4_by_id(obj_id):
"""Return an NeighborV4 by id.
Args:
obj_id: Id of NeighborV4
"""
try:
obj = NeighborV4.get_by_pk(id=obj_id)
except NeighborV4NotFoundError as e:
raise NeighborV4DoesNotExistException(str(e))
return obj | 30b00e2fb1f954299a331ce6b198f1e5465122e5 | 12,283 |
from typing import Dict
def get_resources_json_obj(resource_name: str) -> Dict:
"""
Get a JSON object of a specified resource.
:param resource_name: The name of the resource.
:returns: The JSON object (in the form of a dictionary).
:raises Exception: An exception is raised if the specified reso... | ce625ecbaad0ec4cea93da78c9c213e37ffef3ed | 12,284 |
def skip_if(predicate, reason=None):
"""Skip a test if predicate is true."""
reason = reason or predicate.__name__
def decorate(fn):
fn_name = fn.__name__
def maybe(*args, **kw):
if predicate():
msg = "'%s' skipped: %s" % (fn_name, reason)
raise ... | 56089515f8cae4f977b1eac96a8de6c6ee59e711 | 12,285 |
from pyrap.measures import measures
from pyrap.quanta import quantity as q
def synthesized_uvw(ants, time, phase_dir, auto_correlations):
"""
Synthesizes new UVW coordinates based on time according to
NRAO CASA convention (same as in fixvis)
User should check these UVW coordinates carefully:
if ti... | f3261545f85981d353a05acf3176bf0317ea4c86 | 12,286 |
from datetime import datetime
def execute_pso_strategy(df, options, topology, retrain_params, commission, data_name, s_test, e_test, iters=100, normalization='exponential'):
"""
Execute particle swarm optimization strategy on data history contained in df
:param df: dataframe with historical data
:para... | a9a4fffe335ab34ca584a4fe1d3b6116a2a7866c | 12,287 |
def env_get(d, key, default, decoders=decoders, required=None):
"""
Look up ``key`` in ``d`` and decode it, or return ``default``.
"""
if required is None:
required = isinstance(default, type)
try:
value = d[key]
except KeyError:
if required:
raise
re... | 844c6ac9931af97bdc92da6d5014659c3600d50e | 12,288 |
from sympy.functions.elementary.complexes import re, im
from .add import Add
from re import S
def get_integer_part(expr: 'Expr', no: int, options: OPT_DICT, return_ints=False) -> \
tUnion[TMP_RES, tTuple[int, int]]:
"""
With no = 1, computes ceiling(expr)
With no = -1, computes floor(expr)
No... | 6e00897786581134480a6d7fd16b559760a1a4e7 | 12,289 |
def inv_last_roundf(ns):
"""
ns -> States of nibbles
Predict the states of nibbles after passing through the inverse last round
of SomeCipher. Refer to `last_roundf()` for more details.
"""
return inv_shift_row(ns) | 12561f9815ecad4cd08909be1e0c77dd61500cce | 12,290 |
def get_screen(name, layer=None):
"""
:doc: screens
Returns the ScreenDisplayable with the given `name` on layer. `name`
is first interpreted as a tag name, and then a screen name. If the
screen is not showing, returns None.
This can also take a list of names, in which case the first screen
... | a6496e453a80f1ad286bbe5201aba92fa922794b | 12,291 |
import random
import csv
def generate_address_full(chance=None, variation=False, format=1):
"""
Function to generate the full address of the profile.
Args:
chance: Integer between 1-100 used for realistic variation. (not required)
variation: Boolean value indicating whether variation is requested. (optional)... | 364cbe0f033d0500014583c550beb36a6cb6db55 | 12,292 |
import urllib
def binder_url(repo, branch="master", filepath=None):
"""
Build a binder url. If filepath is provided, the url will be for
the specific file.
Parameters
----------
repo: str
The repository in the form "username/reponame"
branch: str, optional
The branch, defa... | f9ac9e28a1cc6b88bce788e63668f1e4a4b45f61 | 12,293 |
def _create_group_hub_without_avatar(_khoros_object, _api_url, _payload):
"""This function creates a group hub with only a JSON payload and no avatar image.
.. versionadded:: 2.6.0
:param _khoros_object: The core :py:class:`khoros.Khoros` object
:type _khoros_object: class[khoros.Khoros]
:param _a... | 43222666b5a5f5dcec91a4fa1025278f84275e9c | 12,294 |
def ulstrip(text):
"""
Strip Unicode extended whitespace from the left side of a string
"""
return text.lstrip(unicode_extended_whitespace) | 191e0654cdab79778c64ec874bbc9b945b0ed4a3 | 12,295 |
def clone_dcm_meta(dcm):
"""
Copy an existing pydicom Dataset as a basis for saving
another image
:param dcm: the pydicom dataset to be copied
:return:
"""
newdcm = pydi.Dataset()
for k, v in dcm.items():
newdcm[k] = v
newdcm.file_meta = mk_file_meta()
newdcm.is_little_en... | e208ee11241b4194bb0d02357e625d0ee4f52d2e | 12,296 |
import toml
import itertools
from pathlib import Path
def load_plate(toml_path):
"""\
Parse a TOML-formatted configuration file defining how each well in a
particular plate should be interpreted.
Below is a list of the keys that are understood in the configuration file:
'xlsx_path' [string]... | cc92a9dae783de915628984979119ca9d2b591a2 | 12,297 |
def reduce_entropy(X, axis=-1):
"""
calculate the entropy over axis and reduce that axis
:param X:
:param axis:
:return:
"""
return -1 * np.sum(X * np.log(X+1E-12), axis=axis) | 68a7d86bf0ad204d989fddceee9e4f75c77a4cb5 | 12,298 |
def compile_pbt(lr: float = 5e-3, value_weight: float = 0.5):
"""
my default: 5e-3
# SAI: 1e-4
# KataGo: per-sample learning rate of 6e-5, except 2e-5 for the first 5mm samples
"""
input_shape = (N, N, dual_net.get_features_planes())
model = dual_net.build_model(input_shape)
opt = keras.... | e625915c55a44a8c128431ae220401c451ee69a5 | 12,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.