content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def conv1d(x, k, out_ch, dilation, init, scope, mask_type=None):
"""
1-dimensional convolution
x: batch_size x length x n_channels
"""
with tf.variable_scope(scope):
in_ch = x.get_shape()[2].value
w_shape = [k, in_ch, out_ch]
strides = [1]
dilation = [dilation]
... | 4c72409997ea5c32b228e44ceb6d3b3b1f1bcaf6 | 65,000 |
def get_memory(isdsAppliance, statistics_duration, check_mode=False, force=False):
"""
Retrieving the Storage Usage Statistics
"""
return isdsAppliance.invoke_get(
"Retrieving the Memory Usage Statistics",
"/analysis/system_memory{0}".format(
tools.create_query_string(
... | aa63aa5029b684960ccb57e6d3730a760ba94c69 | 65,001 |
def start_client(daemon, host, port, **kwargs):
"""Return a socket to an existing "remote" pydevd-handling daemon.
The daemon supports the pydevd client wire protocol, sending
requests and handling responses (and events).
This is a replacement for _pydevd_bundle.pydevd_comm.start_client.
"""
s... | 26b4e5e79a4b8aaf602cb5b713514358b4951fdc | 65,002 |
import requests
def get_specific_device_summary(device_id=DEVICE_ID):
"""Get an Operating System or Application Vulnerability Summary for a specific device."""
url = GET_DEVICE_VULN_SUMMARY.format(HOSTNAME, ORG_KEY, device_id)
return requests.get(url, headers=HEADERS).json() | a15f559194a32ee2bed917f5658f11cb9f187f67 | 65,003 |
def remove_not_allowed_signs(string) -> str:
"""
:returns: String (eg. from object name)
without all signs not allowed in file names and paths.
"""
for s in NOT_ALLOWED_SIGNS:
string = string.replace(s, "")
return string | a639b2965f5a717547a0bba746f0aea5918e4f35 | 65,004 |
from typing import Dict
def event_device(user: User, device: Device, event_type: str = "decommission") -> Dict:
"""Prepare test device decommission event dictionary with user and device data."""
return {
"action": event_type,
"actor": {"id": user.id, "type": "user", "email": user.name},
... | 3a5d880a3f4758609b609ceaf7d4f1cf1ec67daa | 65,005 |
import re
def parentdir(file_path):
"""
Get the parent directory of a file or directory.
Goes by the path alone, so it doesn't follow symlinks.
On Windows, paths must be converted to use / before passing.
This function is not the same as os.path.dirname(); for example,
dirname will not giv... | baec28e9b6f0017566b91cd2b442a9eb783a144f | 65,006 |
from datetime import datetime
def check_params(args):
"""Check/cleanup parameter values in `args` and convert to a `dict`.
"""
params = {}
params.update(args)
input_ = params['input']
camera = False
try:
input_ = int(input_)
camera = True
except ValueError:
ass... | 85812ead40bb169a60e2c3dab41418588ce322e8 | 65,007 |
def calc_freefree_snu_ujy(ne, t, width, elongation, dist, ghz):
"""Calculate a flux density from pure free-free emission.
"""
hz = ghz * 1e9
eta = calc_freefree_eta(ne, t, hz)
kappa = calc_freefree_kappa(ne, t, hz)
snu = calc_snu(eta, kappa, width, elongation, dist)
ujy = snu * cgs.jypercgs... | c595792646629e45dba6d6a6ae2dee586f9f83c9 | 65,008 |
def _Int(s):
"""Try to convert s to an int. If we can't, just return s."""
try:
return int(s)
except ValueError:
assert '.' not in s # dots aren't allowed in individual element names
return s | 8f7fcf70717fe30ba991c8cff63cecefe5c01daf | 65,009 |
def em(m, t, Omega, M):
"""
Trigonometric polynomial basis function.
Parameters
----------
m : int
Order of basis function.
t : numpy.ndarray
Times over which to compute the function.
Omega : float
Bandwidth (in rad/s).
M : int
Trigonometric polynomial or... | 9d95aa622031262a550afbeb5fcab96545249514 | 65,010 |
def strlist_with_or (alist):
"""Return comma separated string, and last entry appended with ' or '."""
if len(alist) > 1:
return "%s or %s" % (", ".join(alist[:-1]), alist[-1])
return ", ".join(alist) | 1202e76d34f84618bb6b310bbc43c835f3c94104 | 65,011 |
def compare_authors_or_editors(db_entry, dqm_entry, datatype): # noqa: C901
"""
Authors and Editors are in a hash with order of 'order' from db and 'authorRank' from dqm. They have to be sorted by the order, and for updates the db 'author_id' is used to patch. Currently we don't want to remove any authors, ... | 01f8256da5728fdc6ab8595d59ab10ebe7e3827d | 65,012 |
import awkward
import vector
import vector._backends.awkward_
import typing
def zip(
arrays: typing.Dict[str, typing.Any], depth_limit: typing.Optional[int] = None
) -> typing.Any:
"""
Constructs an Awkward Array of vectors, whose type is determined by the fields
of the record array (which may be nest... | a04ae0e20dbb3f09ad375dd6229a61d2a5e6565a | 65,013 |
def _tc_invert_ ( c ) :
"""Invert the cut
>>> cut =
>>> new_cut = ~cut
"""
nc = ROOT.TCut ( c .strip() )
tit = nc.GetTitle()
if tit : return ROOT.TCut( '!(%s)' % tit )
##
return ROOT.TCut | c4d44e9f5d99dc8570bd398f9755c81bf3a3dd68 | 65,014 |
def main_covariance_estimation_SR(
data_stack,
cov_est_window_size,
pixel_spacing_slant_rg,
pixel_spacing_az,
incidence_angle_rad,
carrier_frequency_hz,
range_bandwidth_hz,
):
"""Covariance estimation: inputs are in Slant Range radar coordinates
see also main_covariance_estimation_G... | 0c973bb9f0e88628882ecd188d687cbb5f5d0cfd | 65,015 |
from typing import Optional
from typing import Dict
from typing import Type
def ghidra_struct_to_strud(
is_big_endian: bool,
name: str,
length: int,
string_repr: str,
all_struds: Optional[Dict[str, Type[AbStrud]]] = None,
) -> Type[AbStrud]:
"""
Make an strudra internal struct out of a ghi... | 19a2b03ca6d30322e9bc912c5653c125137b7354 | 65,016 |
def program_marketing(request, program_uuid):
"""
Display the program marketing page.
"""
program_data = get_programs(uuid=program_uuid)
if not program_data:
raise Http404
program = ProgramMarketingDataExtender(program_data, request.user).extend()
program['type_slug'] = slugify(pro... | a0cab850aae3a041cc697a5ebc7bf9112890176d | 65,017 |
import torch
def ensure_torch_random_state(random_state: TorchRandomHint) -> torch.Generator:
"""Prepare a random state for PyTorch."""
if random_state is None:
random_state = random_non_negative_int()
logger.warning(f"using automatically assigned random_state={random_state}")
if isinstanc... | 6dccbfc5e66ad792194139eb1f91aa7aa66f5327 | 65,018 |
import re
def parse_jinja_comment(path):
"""
Parses jinja comment
:param path: Path to jinja template
:type path: str
:returns: Jinja comment docstring
:rtype: str
"""
f= open(path, 'r')
contents= f.read()
res=re.match(r"\{\#(.+?)\#\}", contents, flags=re.MULTILINE|re.DOTALL... | bfdfe73c1b7307c6c57e3539697a2f9eeb62d84a | 65,019 |
import numbers
def get_tstats_betsize(probs, N, num_classes=2, eps=1e-4):
"""Translate probability to bettingsize
Args:
probs (array-like)
N (int): The number of estimators used for generating probs
num_classes (int, optional): Defaults to 2
Returns:
array-like: Signals a... | 256b7cdea18c971b053f0614041ea9e881a4c027 | 65,020 |
def normalise(word):
"""Normalises words to lowercase and stems and lemmatizes it."""
word = word.lower()
#word = stemmer.stem_word(word)
#word = lemmatizer.lemmatize(word)
return word | b1b158960bf6fc3a1fcc34d55dd25b9496ff9069 | 65,021 |
import array
def errors(node_influence: array, byzantine_rate=0.0) -> array:
"""
Returns a stake-weighted population of adversarial members,
with `byzantine_rate` being the *percentage* of the total weights.
"""
return node_influence.cumsum() < byzantine_rate | ed7efcae7c50a57b07b49d121002221e411db2ff | 65,022 |
def FISTA(obs, psf, rho, max_iter=500):
"""Wrapper around FISTA :py:func:`FISTA_core` for a set of images
:param obs: 3D set of images to deconvolve.
:param psf: associated 3D set of point spread functions
:param rho: hyperparameter of the augmented lagrangian.
:param max_iter: maximal number o... | f1afec8a295a69d8abdc0184795f1be201697cb0 | 65,023 |
import math
def getAngle(Gy, Gx, height, width):
"""
Computes the edge angle by taking the tan inverse of yGradient/xGradient
:param Gx:
:param Gy:
:param height:
:param width:
:return: integer array representing the edge angle
"""
gradientData = np.empty(shape=(height, width))
... | 0f6cd641d7eb79ee3c793ee7764875993e97d6da | 65,024 |
def featured_sponsor_rotation():
"""
Retrieve featured Sponsors for rotation
"""
# TODO remove this code completely if not necessary
# this templatetag logic was removed by the PR #1667
# the Sponsor model got updated and its previous use was deprecated
# this templated tag is used at https:... | 68908559d1104ed09c93b6948b639ac43eee42b0 | 65,025 |
def generate_gate_swap(
c_sys: "CompositeSystem", is_physicality_required: bool = True
) -> Gate:
"""Return the Gate class for the SWAP gate on the composite system.
Parameters
----------
c_sys: CompositeSystem
is_physicality_required: bool = True
whether the generated object is physic... | fda4f5b3bd2ebf8fc599b949679cd7d8f6bff12f | 65,026 |
def reformatPermissionErrors(function):
"""This function decorator will trap any permission error exceptions and
raise a different exception with a nicer message."""
def new_func(*args, **kwargs):
pass
return new_func | e3482a6e93ea1d759ddb19ac8b8de90be1fd6651 | 65,027 |
def GetStagesToIgnoreForChange(build_root, change):
"""Get a list of stages that the CQ should ignore for a given |change|.
The list of stage name prefixes to ignore for each project is specified in a
config file inside the project, named COMMIT-QUEUE.ini. The file would look
like this:
[GENERAL]
ignore... | d8546642b21c12a87f0dfebd9cbc28912cd9ed0a | 65,028 |
import yaml
import os
def load_descriptor(descriptor):
""" parses descriptor and validate it against requested schema type
Args:
descriptor - yaml descriptor or path to a descriptor to be loaded.
If a path is provided it must be an absolute path. In other case it's
assumed that it is a yaml... | 99cd363dbc07c88e572ff170c6e1995f06280dac | 65,029 |
import re
def split_assignment_options(args):
"""
replace -a=b with -a b and --arg=b with --arg b
:param args:
:return: returns the updated arg list
"""
i = 0
p = re.compile('((-[a-zA-Z]=)|(--[a-zA-Z\-]+=))')
while i < args.__len__():
m = p.match(args[i])
if m:
... | 07d829c20383a0b6e6f27944b9cd7cc21ff420c1 | 65,030 |
def allInstalledPackages(allInstalledPackages):
"""
All installed packages in system
"""
osType = OSCheck.get_os_family()
if OSCheck.is_suse_family():
return _lookUpZypperPackages(
["sudo", "zypper", "--no-gpg-checks", "search", "--installed-only", "--details"],
allInstalledPackages)
elif O... | e00c7aad3b2ce3ca0128bc1c01abe48adae9039c | 65,031 |
def get_contact_emails():
"""
returns email address of each contact
"""
return [contact.email[0].address for contact in contacts] | 6a818d663c17529dc8d384ddf458be00aaa0ac50 | 65,032 |
def is_critical_hit(base_speed, move_crit_rate):
"""
TODO: amping abilities not applied - focus energy etc..
this is bugged in Gen 1 - but we will just ignore it.
"""
prob = base_speed / 512
if move_crit_rate == 1:
prob = base_speed / 64
chance = np.random.rand()
return chan... | f9eba3f3fa4b59bdc394e602529b558b7b84bb0c | 65,033 |
def unique_slug_generator(instance, new_slug=None):
"""Generate new slug if current slug already exists"""
if new_slug is not None:
slug = new_slug
else:
slug = slugify(instance.title)
Klass = instance.__class__
qs_exists = Klass.objects.filter(slug=slug).exists()
if qs_exists:
... | 2101b687e3a1ac59ba5180bae96307b488229fb2 | 65,034 |
def create_update(title:str,time:str,repeat:bool,covid_data:bool,news:bool) -> dict:
"""This method takes elements of an update and formats the update
description shown to the user, and also assesses the update type.
Args:
title (str): Title of update given by user
time (str): Time of updat... | f2ca2df838eb60f59d422b94c4723a68b9ab7197 | 65,035 |
async def what_status(status: str):
"""Checks what `status` the input may be.
`status` subcommands are defined to be `died` and `anchored`.
Args:
status (str): the string to check for `status`
Returns:
str: the correct "status" if successful
None: if invalid
"""
if re... | de8c0ecb76acfa43b7bf143b4914822595d58134 | 65,036 |
def values_dict(items):
"""Given a list of (key, list) values returns a dictionary where
single-element lists have been replaced by their sole value.
"""
return {k: v[0] if len(v) == 1 else v for k, v in items} | 7abcf62ab334cecc6e6996bad73ff10e5eecdf89 | 65,037 |
def filter_data(df, city, month, day):
"""
Filters by month and day if applicable.
Args:
(dataframe) df - the original raw data
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the da... | 8844ee1b057af2cad5d81ad4f6824917487c7e16 | 65,038 |
def splitCubic(t, cubic):
"""Splits a cubic Bezier into two cubic Bezier at the given parameter t.
Uses de Casteljau algorithm."""
a0 = lerp(t, cubic[0], cubic[1])
a1 = lerp(t, cubic[1], cubic[2])
a2 = lerp(t, cubic[2], cubic[3])
b0 = lerp(t, a0, a1)
b1 = lerp(t, a1, a2)
c0 = lerp(t, b0, b1)
return (cubic[0],... | 4d651cc49eea1fc4ec3bb3d5071fe97249016a21 | 65,039 |
from re import T
from datetime import datetime
def rat_tables():
""" Load the RAT Tables when needed """
module = "assess"
# Load the models we depend on
if settings.has_module("cr"):
shelter_id = s3db.shelter_id
if settings.has_module("hrm"):
human_resource_id = s3db.hrm_human_r... | 50056fce94ad339ac90d19c890502942fe732bfe | 65,040 |
def deleteAccount(user):
"""
Deletes the user's account.
"""
try:
# delete the user from Firebase
auth.delete_user(user.firebase_uid)
# clear PII
user.firebase_uid = None
user.email = None
user.phone_number = None
user.service_provider_id = None
# clear preferences
user.em... | 601b3b44078496ff13d5812754b0331e3fec9bea | 65,041 |
from typing import Dict
from typing import Any
from typing import Union
from typing import Callable
def flatten_dict(
data: Dict[str, Any],
key_prefix: Union[str, None] = None,
key_map: Union[Callable[[str], str], None] = str.lower) -> Dict[str, str]:
"""Flatten a dictionary to be one dime... | 6e524abf16ca0717b803a2e8f5686d970d6db4b6 | 65,042 |
def ssd_unsupported_nodes_to_plugin_nodes(ssd_graph, n_classes, input_dims, feature_dims):
"""Makes ssd_graph TensorRT comparible using graphsurgeon.
This function takes ssd_graph, which contains graphsurgeon
DynamicGraph data structure. This structure describes frozen Tensorflow
graph, that can be mod... | 9f8d49ca0e68515ea559e32dfcebaeda05dfc62b | 65,043 |
def fibonacci_iterative(n):
"""
Compute the Fibonacci numbers with given number by iterative method
:param n: given number
:type n: int
:return: the Fibonacci numbers
:rtype: int
"""
if n == 0:
return 0
elif n == 1:
return 1
elif n < 0:
return -1
fn,... | d3fd6a2977c145c2624c1c3fdbd527bab502bfe9 | 65,044 |
def generate_ignore_database_table(ignore_tables, table):
"""
:param ignore_tables: Dictionary
:param table: String
:return: Dictionary
"""
ignore_tables.append('--ignore-table=' + system.config['origin']['db']['name'] + '.' + table)
return ignore_tables | b0f5ca4a7eb32bd93e9566967367ae8366b453ef | 65,045 |
from typing import Tuple
from typing import List
def _make_line_buses(dss: win32com.client.CDispatch) -> Tuple[List[str], List[str]]:
"""
Make the bus names for all of the lines in the circuit.
Parameters
----------
dss : win32com.client.CDispatch
The OpenDSSEngine object.
Returns
... | de2799ec4ea4752518574dbcb51f3f6ffe99b20c | 65,046 |
import random
import string
import time
import os
def make_voevent(candcollection, role='test'):
""" Script to generate a VOEvent file from the CandCollection
Takes Candcollection info and writes a .xml file with relevant inforation
VOEvent format based on Petroff et al. 2017 VOEvent Standard for Fast Ra... | 6b0845a01ef10e8b389241bed47fa1f85c9fea05 | 65,047 |
def getmaskarray(arr):
"""
Return the mask of a masked array, or full boolean array of False.
Return the mask of `arr` as an ndarray if `arr` is a `MaskedArray` and
the mask is not `nomask`, else return a full boolean array of False of
the same shape as `arr`.
Parameters
----------
arr... | bf1075d4e6c0105b699da608d649aba7220d1e99 | 65,048 |
def ghostnet(**kwargs):
"""
Constructs a GhostNet model
"""
cfgs = [
# k, t, c, SE, s
[[3, 16, 16, 0, 1]],
[[3, 72, 24, 0, 1]],
[[3, 88, 24, 0, 1]],
[[3, 96, 24, 0, 2]],
[[3, 240, 40, 0, 1]],
[[3, 240, 40, 1, 1]],
[[3, 120, 40, 1, 1],
... | f4826d83363bac40d6543fa752b69294fcebca75 | 65,049 |
import click
def describe_chute_network_client(ctx, chute, network, client):
"""
Display information about a network client.
CHUTE must be the name of an installed chute. NETWORK must be the
name of one of the chute's configured networks. Typically, this
will be "wifi". CLIENT identifies the ne... | 03c2802c454405c370970829228fcd6f7911817b | 65,050 |
def get_root():
"""
Returns the root folder.
"""
return 'data/simulators/lotka_volterra' | 51351a55f678594707329fcf4fb3aa37e7340b31 | 65,051 |
def transform_to_normal(data_extremes, imin, imax):
"""
Transforming a random distribution to a normal distribution can be done in the following way:
1. Compute the values of the CDF. These values are the percentiles. These are (always) uniformly distributed.
2. Use the percent point function (inverse... | 80775cb8b44188f1602713dc8b4da7410a22fe57 | 65,052 |
from base64 import encodestring
from base64 import encodebytes as encodestring
def uu_encode(binData, width = 64):
""" uu encoding
>>> print(uu_encode(b"12345678"))
MTIzNDU2Nzg=
>>> print(uu_encode("12345678"))
MTIzNDU2Nzg=
"""
if is_python2():
else:
if is_python3():
if is_string(binData):
binData = bi... | b137cc343f45ca5abddb604c0c4de04975e08f22 | 65,053 |
def is_same_function(f1, f2):
"""returns true if f1 and f2 is same function
Use case: sometimes when user defines some virtual function in base class,
it overrides it in a derived one. Sometimes we need to know whether two
member functions is actually same function.
"""
if f1 is f2:
ret... | 713a62b3453f00cffa0eea6d1f42dfe68860b094 | 65,054 |
def sameopenfile(fp1, fp2):
"""Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file."""
return True | c6943dc157d19208e52a201adff563404ae221f7 | 65,055 |
def DetermineServiceFromUrl(url):
"""Takes a DFA service's URL and returns the service name.
Args:
url: string The DFA service's URL.
Returns:
string The name of the service this URL points to.
"""
return url.split('/')[-1] | 213e1a4dbb5eb3ed643e0ace300b4ac5b6c6c745 | 65,056 |
def tshark_read(device, capture_file, packet_details=False, filter_str=None):
"""Read the packets via tshark
:param device: lan or wan...
:type device: Object
:param capture_file: Filename in which the packets were captured
:type capture_file: String
:param packet_details: output of packet tree... | 8585248223410f771d7a90d3c59d2a1fbb3a221b | 65,057 |
def is_prime(number):
"""如果是素数返回True.
>>> is_prime(2)
True
>>> is_prime(42)
False
>>> is_prime(41)
True
"""
# 小数的检查.
if number < 10:
return number in {2, 3, 5, 7}
# 偶数.
if not (number & 1):
return False
# 计算最少的回合数.
k = get_primality_testing_rou... | 8d7a4d27b17ebb12420a00c5771d2239c6a037a1 | 65,058 |
def pad_pkcs7(buf):
"""Appends PKCS7 padding to an input buffer.
Parameters:
buf - buffer to add padding
Returns:
buffer with PKCS7_PADDING
Raises:
No special exception handling
"""
padder = cryptography.hazmat.primitives.padding.PKCS7(
cryptography.hazmat.primiti... | fae4acded6ae37c20d4b1838d9657fe72e1725ff | 65,059 |
def list_detectors(client, aws_region):
"""
Lists the detectors in a given Account/Region
Used to detect if a detector exists already
:param client: GuardDuty client
:param aws_region: AWS Region
:return: Dictionary of AWS_Region: DetectorId
"""
detector_dict = client.list_detectors()
... | 75413860f6974471b3be5cb8155fce76482f7fbe | 65,060 |
import re
def str_simplified(input_str: str) -> str:
"""
Remove leading/trailing whitespaces,
simplify multiple whitespaces,
unify newline characters
Parameters
----------
input_str : str
Returns
-------
str
input_str stripped if it is a string
"""
if not isin... | b9005bf5c3d01c971e3e17176a527eb1a23a1bf4 | 65,061 |
def wrapper(path, wrapped, ns=None, ns_map=None, idx=None):
"""
The function is used to map a class field to an XML element that is contained by a subelement.
:param str path: full path to the `wrapped` element. Element names are separated by slashes
:param wrapped: a wrapped element
:param str ns:... | 59cb0d644ce01dc2858650bf4d47967ffbad2261 | 65,062 |
def Find_2D_uc(Peaks, toll_angle=5, toll=0.10):
"""
Finds the best fitting unit cell for an image
Input :
SeqIma : sequence of images
Output :
- out : array of unit vectors of length : number_of_images_in_sequence*2
"""
unit_vectors = find_all_2vectors(Peaks, toll_angle)
#vecti = s... | d68307fb4447e3f218bcdef4990deeeda6514986 | 65,063 |
def _listify(x):
"""Ensure a scalar/list is returned as a list.
Taken from https://stackoverflow.com/a/1416677/1467820
Copied from the pre-v1 hera_sim.rfi module.
"""
try:
basestring
except NameError:
basestring = (str, bytes)
if isinstance(x, basestring):
return [... | 51b6594af9e54025d1b91d73ff01dd2c6db85d9b | 65,064 |
def open_dta(address):
"""Open any recent version dta file (versions 114, 115, 117) .
Parameters
----------
Address of file, including file name and ".dta".
Returns
-------
Instance of sub-class of Dta, depending on dta file.
"""
with open(address, 'rb') as dta_file:
... | e675ecc5aae8d518c2a7bcff95b70da8c0c51e3c | 65,065 |
def moveaxis(a, source, destination):
"""
Move axes of a tensor to new positions.
Other axes remain in their original order.
Parameters
----------
a : Tensor
The tensor whose axes should be reordered.
source : int or sequence of int
Original positions of the axes to move. T... | cae4202c11f09f5b78290ecb9ab82c17a5cad1ce | 65,066 |
def get_links_by_cve(cve, vul_db):
"""Get external links if they have mitigation info for a cve.
Example:
>>> from cve_links import get_links_by_cve
>>> res = get_links_by_cve('CVE-1999-0002')
[('http://www.securityfocus.com/bid/121', True)]
Args:
cve (string): cve ID
... | c1032bbf02c7c75c6b366c001bc0884e9bee04a2 | 65,067 |
def spark():
"""spark Session factory"""
spark_ = SparkSession \
.builder \
.appName("Detect dictionary and vocabulary") \
.getOrCreate()
return spark_ | 7db051a2e88ebbabe14c8fa4e1a402edf7e4ad78 | 65,068 |
def softmax_crossentropy_with_logits(logits,reference_answers):
"""Bu fonksiyon softmax aktivasyon fonksiyonu ile modelin tahminleri ile olması gereken değerler arasındaki cross entropy'yi hesaplıyor. logits, modelin tahminlerini, reference_answers ise gerçek olması gereken değerleri ifade ediyor"""
logits_for_... | da229dd55605a8d115d9a6bdbc38d89b5216f502 | 65,069 |
def rand_walk(start_point, step_size, num_iters, sigma = 1):
"""
Function to initiate a random walk from a starting point
Inputs
------
start_point : vector(1-D Numpy array)
Vector of the initial point of the walk
step_size : float
Size of random step
num_iters : integer... | 9253dfbf387e150b321ed4703cfcf360a1d235e8 | 65,070 |
def object_to_schema(obj: InDataT, **options) -> InDataT:
"""
Generate a node represents JSON schema object with type annotation added
for given object node.
:param obj: mapping object such like a dict
:param options: Other keyword options such as:
- ac_schema_strict: True if more strict (... | 4d21e84b9b37795799627587d7e9068082802269 | 65,071 |
def read_lut(from_opened_input_file, bytes_of_lut_to_read: int, reverse_byte_ordering=False):
"""
:param from_opened_input_file: file handle to the LUT file, positioned at the beginning of the file
:param bytes_of_lut_to_read: how many bytes to read; this is a product of the number of entries (4 bytes per)
... | 56d8db742ced18127b90e8b38e2819ecf97beb9b | 65,072 |
def calc_verbosity(verbose=False, debug=False):
"""Calculate the verbosity
of the script"""
verbosity = 0
if verbose:
verbosity = 1
if debug:
verbosity = 2
return verbosity | 527aef36cfb3de4f245aa6670d105f58a84926aa | 65,073 |
def approximate_kl(log_prob_new, log_prob_old, mask):
"""Computes the approximate KL divergence between the old and new log-probs.
Args:
log_prob_new: (B, T, C, A) log probs new
log_prob_old: (B, T, C, A) log probs old
mask: (B, T)
Returns:
Approximate KL.
"""
diff = log_prob_old - log_prob_... | 205513d78b4a1482b158bf4239fde838b2d2309d | 65,074 |
import math
def get_sprites(X):
"""Generate a square sprite image with digits.
Tensorflow supports sprite images up to 8192x8192 pixels. Given each of
our digits is 20px*20px, we don't have to scale it down.
"""
width, height = IMAGE_WIDTH, IMAGE_HEIGHT
digits_per_row = int(math.ceil(math.sqrt... | be4253bfbb5966605b7b95b34cf11f644774ced5 | 65,075 |
def plotyy( x1, y1, x2, y2, color1='b', color2='g', fun=None, **kwargs ):
"""
A work-alike of the Matlab (TM) function of the same name. This
places two curves on the same axes using the same x-axis, but
different y-axes.
Call signature::
ax, h1, h2 = plotyy( x1, y2, x2, y2, color1='b', color... | f013e7e647f3eb94f40bb1a49cb7d5fec2bcf04d | 65,076 |
def protected():
"""
A protected endpoint. The auth_required decorator will require a header
containing a valid JWT
.. example::
$ curl http://localhost:5000/api/protected -X GET \
-H "Authorization: Bearer <your_token>"
"""
return {"message": f'protected endpoint (allowed user {... | 4a970dfd726448ab090c3ae36a9b1f5ad5be2cf8 | 65,077 |
import os
import pkg_resources
def get_esst_changelog_path() -> str:
"""
Returns: changelog path
"""
changelog_path = os.path.join(os.path.dirname(__file__), 'CHANGELOG.rst')
if not os.path.exists(changelog_path):
LOGGER.debug('changelog not found, trying from pkg_resource')
chan... | 10297812d8cddaf9a83a619c0c1dcbcde1cd25cf | 65,078 |
def filter_list(list_to_filter, attr, attr_value, list_type):
"""
Utility function to filter a given list based on the whether it has the given
values for the given attributes. Keeps the objects where all the objects have the
given attr_vals for the corresponding attrs.
:param list_to_filter: The li... | 04766fb7d64588c9407783aa9f0c5e055d2a3dbf | 65,079 |
from scapy.libs.winpcapy import (
PCAP_ERRBUF_SIZE,
pcap_open_live,
pcap_compile,
pcap_compile_nopcap,
pcap_close
)
from ctypes import create_string_buffer
def compile_filter(filter_exp, # type: str
iface=None, # type: Optional[Union[str... | 6900d8aced81a1a04fbfc7c0f4dc6309c61419ec | 65,080 |
def rates_nucleus(er, det: Detector, fx: Flux, efficiency=None, f=None, nsip=NSIparameters(), flavor='e',
op=oscillation_parameters(), ffs=formfsquared, q2=False, **kwargs):
"""
calculating scattering rates per nucleus
:param er: recoil energy
:param det: detector
:param fx: flux
... | a6c0ebcd1cab8acdc18a88013f33a07d61686e86 | 65,081 |
def all_3tours(ct, dists):
"""generates all 3-lenght tours from ct -> cities tuple"""
tours = []
NCITIES = len(ct)
for i in range(0, NCITIES):
for j in range(i+1, NCITIES):
for k in range(j+1, NCITIES):
tours.append(tour(ct[i],ct[j],ct[k],dists))
return tours | d57d7491a62d09d9640345068a3987f18715fb1f | 65,082 |
import copy
import torch
def dataProcessing(data_x, data_y, batch_size, training_ratio, validation_ratio,
FM_indices, bool_norm=False):
"""
Data preprocessing.
Parameters:
----------
data_x: 2D Array (nDOF x SampleNum).
The deformation data (x SampleNum) of al... | 6501dfb29d3b922843eb404cee0a2aa6df247dc4 | 65,083 |
import os
def read_init():
""" Read the init and exctracts PyTorch, TensorFlow, SentencePiece and Tokenizers objects. """
with open(os.path.join(PATH_TO_TRANSFORMERS, "__init__.py"), "r", encoding="utf-8") as f:
lines = f.readlines()
line_index = 0
# Find where the SentencePiece imports begin... | aa87b1373a1bf023b3a3f7ebaf462af19931aff9 | 65,084 |
from msrest.serialization import Deserializer
from msrest.exceptions import DeserializationError
def datetime_format(value):
"""Validate the correct format of a datetime string and deserialize."""
try:
datetime_obj = Deserializer.deserialize_iso(value)
except DeserializationError:
message ... | 8f635e60e4b9276cccedb8ee282afaea64c579fd | 65,085 |
async def create_new_task(request):
"""Create a new task."""
required_fields = ["name", "administrators", "owners"]
utils.validate_fields(required_fields, request.json)
txn_key, txn_user_id = await utils.get_transactor_key(request)
task_id = str(uuid4())
batch_list = Task().batch_list(
... | dc8f2a50ade50de9d07bbcac8acf14912f87961a | 65,086 |
def combine(background_img, figure_img):
"""
:param background_img: str, the file path of the original background image.
:param figure_img: str, the file path of the original figure image.
:return: Replace the green background in figure imagine into the background imagine.
"""
bg = background_im... | a444ea43222ed892161edd9c8ddaf0ca1ca0f514 | 65,087 |
def runcommand(cosmology='WMAP5'):
""" Example interface commands """
# Return the WMAP5 cosmology concentration predicted for
# z=0 range of masses
Mi = [1e8, 1e9, 1e10]
zi = 0
print("Concentrations for haloes of mass %s at z=%s" % (Mi, zi))
output = commah.run(cosmology=cosmology, zi=zi, ... | b0854c596218e91f78f84b67b917fa62ea7b4175 | 65,088 |
def do_include_raw(parser, token):
""" Performs a template include without parsing the context, just dumps the template in.
"""
bits = token.split_contents()
if len(bits) != 2:
raise template.TemplateSyntaxError, "%r tag takes one argument: the name of the template to be included" % bits[0]
template_name... | e324a73c33bf8861916a12107f5eb40c8b7cb32c | 65,089 |
import os
import logging
def extract_seq(line):
"""
read input breakpoint file and extract sequence from the genome file
:param line: line read from breakpoint file
:return: a list to two folders
"""
genomeSeq = SeqIO.index(seqIn, 'fasta')
lineL = line.rstrip().split()
seqID, geneID =... | 0e4a9a143acb21a6f95e9adc491dd87ab8aad08f | 65,090 |
def build_dataset(cfg, target, default_args=None):
"""Build a dataset from config dict.
Args:
cfg (dict): Config dict. It should at least contain the key "type".
target (str): Target name. One of : "train", "val", "test".
default_args (dict, optional): Default initialization arguments.
... | 432c9f67e5c740bcf2553c5d4f7cf93880920777 | 65,091 |
def to_json(MLClassifier):
"""
Returns an ML Classifier JSON object
"""
return ml_classifier_schema.dump(MLClassifier).data | 0d4e56c4f0d8f2fe8a992f4acdf6b633ebcd7bdf | 65,092 |
def convert(bsigs, grpkey, bldkey, msg=ffi.NULL, mgrkey=ffi.NULL):
"""
Converts a set of blinded group signatures, in schemes that support it.
Optional parameters may be ignored in some schemes.
Parameters:
bsigs: An array containing the blinded group signatures.
grpkey: The group key.
... | cce4639fa42bff7999c55ac5bc60355712c8e3b6 | 65,093 |
def _tdigest_norm_kstest(digest):
"""TODO
Parameters
----------
digest : tdigest.TDigest
t-digest data structure.
Returns
-------
TODO
"""
normdigest = _tdigest_normalise(digest)
x = np.linspace(-3, 3, 500)
dig_q = np.array([normdigest.cdf(xx) for xx in x])
nor... | cf5c4f3174db604b59c01961f008398c13c48e35 | 65,094 |
def get_colors(hists):
"""
Get colors of plotted objects from draw option
:param hists: histograms
:type hists: list
:return: list of colors
:rtype: list
"""
def get_color(hist):
draw_option = hist.GetDrawOption()
if isinstance(hist, ROOT.TEfficiency):
return ... | e5af47ea7ee5904b42536b2abcb1891ec6d52bc1 | 65,095 |
def _instance_transfer(Xs, Xt, ys, psi, train_selection):
""" Do the instance transfer. """
tol = 1e-10
# ns = 550, nt = 550
ns, _ = Xs.shape
nt, _ = Xt.shape
# neighbor trees
target_tree = BallTree(Xt, leaf_size=16, metric='euclidean')
source_tree = BallTree(Xs, leaf_size=16, metric=... | e58aa739600e6ac692bab993f19f2e2ab79c8434 | 65,096 |
def login_password_invalid(client, user):
"""Yield a function for this step"""
def run_step(last_result):
"""Run the step"""
user.set_password("password1")
user.save()
return assert_api_call(
client,
"psa-login-password",
{
"fl... | 64f58705a164369caa655f2c134978214ff36a5c | 65,097 |
def is_git_configured():
"""Check if user.name and user.email is set globally in git
This will also return false if git is not available at all.
Returns:
bool: True if it is set globally, False otherwise
"""
try:
for attr in ["name", "email"]:
shell.git("config", "--get... | 5a3ee580266c1695f35c20a21fffdb248b56758b | 65,098 |
def join(a, *p):
"""Join two or more pathname components, inserting '/' as needed.
If any component is an absolute path, all previous path components
will be discarded."""
path = a
for b in p:
if b.startswith('/'):
path = b
elif path == '' or path.endswith('/'):
... | 3c9588e6a89918e262e2469721516b88d48df92e | 65,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.