content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_headers_token(security_scopes: SecurityScopes, encoded: str = Depends(get_reusable_oauth2())) -> Token:
"""
This FastAPI dependency *will not* result in an argument added to the OpenAPI spec.
This should generally be used for dependencies involving the access token.
"""
return get_validated... | f7c9794fcd4b95f1e541b98203bfbe4fb1a6ec60 | 33,100 |
def worker_mode(self):
"""
bool: Whether or not all MPI ranks are in worker mode, in which all
worker ranks are listening for calls from the controller rank. If
*True*, all workers are continuously listening for calls made with
:meth:`~_make_call` until set to *False*.
By default, this is *False... | 45d256e47bfeffe9e3878297c6009061801e5d8d | 33,101 |
def _pcolor(text, color, indent=0):
""" Colorized print to standard output """
esc_dict = {
'black':30, 'red':31, 'green':32, 'yellow':33, 'blue':34, 'magenta':35,
'cyan':36, 'white':37, 'none':-1
}
if esc_dict[color] != -1:
return (
'\033[{color_code}m{indent}{text}\... | b156f86b2c73c00b44b8b5fd968499549bc79389 | 33,102 |
def naninterp(X, method='linear'):
"""
---------------------------------------------------------------------
fill 'gaps' in data (marked by NaN) by interpolating
---------------------------------------------------------------------
"""
inan = np.argwhere(np.isnan(X))
if inan.size == 0:
... | 33b95a879ead6ce93fa7cf4826c05c8086194c5f | 33,103 |
def to_op_list(elements: list) -> OperatorList:
"""elements should be a properly written reverse polish notation expression to be made into OperatorLists"""
if len(elements) == 0:
raise InvalidExpressionError()
new_elements = []
for e in elements:
if isinstance(e, Element):
n... | d849d840c4c391559dd85c5135909bc3381ed9cc | 33,104 |
def future(fn):
"""Mark a test as expected to unconditionally fail.
Takes no arguments, omit parens when using as a decorator.
"""
fn_name = fn.__name__
def decorated(*args, **kw):
try:
fn(*args, **kw)
except Exception, ex:
print ("Future test '%s' failed as ... | ae7b5fed9aea4546dcc07fa89a1d37dac89c0a94 | 33,105 |
def prodXTXv(v):
"""
Fast computation function for the product between a vector v, the matrix X and the transpose of the matrix X,
where X is the triangular matrix with only one below the diagonal.
:parameters:
- v : (array-like) the vector v
:return:
- res : the result of the mat... | 0e7526df922518278791c6c67c7233d2f53ca6c8 | 33,106 |
def input_fn(mode, batch_size, data_dir):
"""Input_fn using the contrib.data input pipeline for CIFAR-10 dataset.
Args:
mode: Standard names for model modes (tf.estimators.ModeKeys).
batch_size: The number of samples per batch of input requested.
"""
dataset = record_dataset(filenames(mode, data_di... | 4e59ed0e8a7ff1151a93a457b68cb99d3a47124b | 33,107 |
from typing import Any
from typing import Set
import inspect
from unittest.mock import Mock
def _get_default_arguments(obj: Any) -> Set[str]:
"""Get the names of the default arguments on an object
The default arguments are determined by comparing the object to one constructed
from the object's class's in... | 483fe82dd79aadfe1da387fb0c602beb503f344b | 33,108 |
from typing import Union
from typing import Optional
import logging
def execute_query(
connection: mysql.connector.connection_cext.CMySQLConnection,
sql_query: str,
data: Union[dict, tuple],
commit=True,
) -> Optional[int]:
"""
Execute and commit MySQL query
Parameters
----------
... | 7c7fbeb7880d2b4efd758387af860dc6af05bbfd | 33,109 |
def rpn_targets(anchors, bbox_gt, config):
"""Build the targets for training the RPN
Arguments
---------
anchors: [N, 4]
All potential anchors in the image
bbox_gt: [M, 4]
Ground truth bounding boxes
config: Config
Instance of the Config class that stores the parameters
... | 3775c2c3222911377a85ddaae802a625a181a9d9 | 33,110 |
from datetime import datetime
def add_years(d, years):
"""Return a date that's `years` years after the date (or datetime).
Return the same calendar date (month and day) in the destination year,
if it exists, otherwise use the following day
(thus changing February 29 to February 28).
"""
try:
... | 325085694b92f39e3ed8d22f690b5b520cdcbe5f | 33,111 |
def adj_to_knn(adj, n_neighbors):
"""convert the adjacency matrix of a nearest neighbor graph to the indices
and weights for a knn graph.
Arguments
---------
adj: matrix (`.X`, dtype `float32`)
Adjacency matrix (n x n) of the nearest neighbor graph.
n_neighbors: 'int' (o... | baed2ea35131705bf99fe01f5ffd6924eb689f32 | 33,112 |
def typeck(banana_file):
"""
Type-check the provided BananaFile instance.
If it type check, it returns the associated TypeTable.
:type banana_file: ast.BananaFile
:param banana_file: The file to typecheck.
:rtype: typetbl.TypeTable
:return: Returns the TypeTable for this BananaFile
"""
... | 71516db1fcb34666b35f2f62736e585d46766c5c | 33,113 |
import os
def stylemap(styles, paths=None):
"""Return path to mapfile for a given style.
Searches mapfile in the following locations:
1. templatepath/style/map
2. templatepath/map-style
3. templatepath/map
"""
if paths is None:
paths = templatepath()
elif isinstance(paths, st... | 590e70c594c52a4d018104a2172aed1457e375c7 | 33,114 |
import aiohttp
import async_timeout
async def authenticate(
session: aiohttp.ClientSession, username: str, password: str
) -> str:
"""Authenticate and return a token."""
with async_timeout.timeout(10):
resp = await session.request(
"post",
BASE_URL + "authenticate",
... | 5728503c49e2173f872eda7fbd5152f67f50d6c2 | 33,115 |
async def create_individual_sensors(
hass: HomeAssistantType, sensor_config: dict
) -> list[SensorEntity]:
"""Create entities (power, energy, utility_meters) which track the appliance."""
source_entity = await create_source_entity(sensor_config[CONF_ENTITY_ID], hass)
try:
power_sensor = await ... | 3112b85721fe4692ddec3f15c13ae9e5192dfb55 | 33,116 |
def collatz(number):
"""If number is even (number // 2) else (3 * number + 1)
Args:
number (int): number to collatz
Returns:
int: collatz number
"""
if (number % 2) == 0:
print(number // 2)
return number // 2
print(3 * number + 1)
return 3 * number + 1 | 221fd238bd6d0c40c9cb80be2c58746bb206c17b | 33,117 |
def maximum_clique(adjacency):
"""Maximum clique of an adjacency matrix.
Parameters
----------
adjacency : (M, M) array
Adjacency matrix.
Returns
-------
maximum_clique : list with length = size of maximum clique
Row indices of maximum clique coordinates. Set to False if no... | a8cf5cb67b74f334ea632263f68127b35f8e7816 | 33,118 |
def get_disk_at(board, position):
"""
Return the disk at the given position on the given board.
- None is returned if there is no disk at the given position.
- The function also returns None if no disk can be obtained from the given
board at the given position. This is for instance... | 4b793ce1947b2f71d666b1d1676ca894f43c3b58 | 33,119 |
def incr_key_store(key, amount=1):
"""
increments value of key in store with amount
:param key: key of the data
:param amount: amount to add
:return: new value
"""
if get_use_redis():
return rds.incr(str(key), amount)
else:
if exists_key_store(key):
value = g... | b31d024952c133863f38a6504d4c39e92493f27a | 33,120 |
def firstUniqChar(s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0:
return -1
if len(s) == 1:
return 0
hash_table = {}
for i in s:
if i not in hash_table:
hash_table[i] = 1
else:
hash_table[i] += 1
for i in s:
if hash... | 25148de95099094991339bb0fe6815644e5b94cb | 33,121 |
def sum_of_powers_of_transition_matrix(adj, pow):
"""Computes \sum_{r=1}^{pow) (D^{-1}A)^r.
Parameters
-----
adj: sp.csr_matrix, shape [n_nodes, n_nodes]
Adjacency matrix of the graph
pow: int
Power exponent
Returns
----
sp.csr_matrix
Sum of powers of the transi... | 6b20b6cf8f9bba2d04672a04401f265f751cd5f0 | 33,122 |
from typing import Optional
from typing import Union
from typing import Callable
def get_current_sites(
brand_id: Optional[BrandID] = None, *, include_brands: bool = False
) -> set[Union[Site, SiteWithBrand]]:
"""Return all "current" (i.e. enabled and not archived) sites."""
query = db.session.query(DbSit... | 7bddf17bc2d2b3b5854f6c2bf47089bbac930d0a | 33,123 |
def get_text_editor_for_attr(traits_ui, attr):
""" Grab the Qt QLineEdit for attr off the UI and return its text.
"""
widget = get_widget_for_attr(traits_ui, attr)
return widget.text() | 6691fe0ddc13b379b1edcc5494e6378317df3bdc | 33,124 |
def check_coords(lat, lng):
""" Accepts a list of lat/lng tuples.
returns the list of tuples that are within the bounding box for the US.
NB. THESE ARE NOT NECESSARILY WITHIN THE US BORDERS!
"""
if bottom <= lat <= top and left <= lng <= right:
inside_box = 1
else:
inside... | e9b1678b2d736dbae9c2524df08bc59a3fe1912f | 33,125 |
async def confirm_email(body: ConfirmTokenModel, include_in_schema=False):
"""Mark a user's email as confirmed"""
email = verify_access_token(body.token)
if not email:
logger.info("Error getting email")
return JSONResponse(
status_code=status.HTTP_401_UNAUTHORIZED,
c... | 428ce5b9ed1e23bde91d57f16e5a18f9add3da83 | 33,126 |
def create_config_hyperparameter_search(dataset_name):
"""
Create the config file for the hyper-parameter tuning given a dataset.
"""
hidden_layer_size = [16, 32, 64]
n_hidden_layers = [2, 3, 4]
learning_rate = [0.005, 0.01, 0.02, 0.05]
lr_decay = [0.99, 0.995, 0.999, 1.0]
pytorch_init_... | d8635f42bf66e782c11dd9bc310b2c1ae30deff2 | 33,127 |
def get_genome_set(gids=[], def_name=None):
"""Wrapper for Genome object creation, checks if cache (created through unique option set) exists first and returns that.
returns dict: key = genome_id, value = Genome() object
see: help(Genome)
"""
if not gids:
sys.stderr.write("No ids inputt... | ea3cc9f5094b5ac21c760c3f2dfa2f0072c3ead4 | 33,128 |
def sample_tag(user: User, name: str = "Main course") -> Tag:
"""Create and return a sample name"""
return Tag.objects.create(user=user, name=name) | d0181ae04479661bde1ed4d72c6e871de95a016a | 33,129 |
def update(todo_id, done):
"""Handle request. Delete todo."""
update_todo(username=current_user.id, todo_id=todo_id, done=done)
return redirect(url_for('hello')) | 8cfaca881c3d62dc2941f60e0c95ac1180bee871 | 33,130 |
def trustworthiness(X, X_embedded, n_neighbors=5, precomputed=False):
"""Expresses to what extent the local structure is retained.
The trustworthiness is within [0, 1]. It is defined as
Returns
-------
trustworthiness : float
Trustworthiness of the low-dimensional embedding.
"""
if ... | d5db0a3c8b3ecbdb3375171a9601320bd6628020 | 33,131 |
def compute_logomaker_df(adata, indices, fixed_length: int = None):
"""
The sample names (adata.obs_names) must be strings made of amino acid characters.
The list of allowed characters is stored in the variable aminoacids.
"""
if fixed_length is None:
pos_list = np.arange(max([len(adata.obs_... | 760715143605bb9cc1b632978a10d8bd2d56bd66 | 33,132 |
from typing import Optional
from typing import Tuple
import re
def parse_test_stats_from_output(output: str, fail_type: Optional[str]) -> Tuple[int, int]:
"""Parse tasks output and determine test counts.
Return tuple (number of tests, number of test failures). Default
to the entire task representing a si... | 8ec67d226c2280eb08de3589cba7b6aa0a09024c | 33,133 |
from typing import List
from typing import Tuple
from typing import Dict
def _constraint_items_missing_from_collection(
constraints: List[Tuple], collection: Dict[str, int]
) -> List[str]:
"""
Determine the constrained items that are not specified
in the collection.
"""
constrained_items = se... | 918667f1e8b001637c9adf00ef5323b2e8587775 | 33,134 |
import scipy
def coldpool_edge_shear_direction_split(
tv0100,
ds_profile,
l_smoothing=L_SMOOTHING_DEFUALT,
l_edge=L_EDGE_DEFAULT,
d_theta_v=COLDPOOL_THRESHOLD_DEFAULT,
shear_calc_z_max=SHEAR_DIRECTION_Z_MAX_DEFAULT,
profile_time_tolerance=60.0,
):
"""
Computes a mask for the edge o... | 9a8f97005c1ed638828a9a9ae00ffbbf516606c3 | 33,135 |
import json
def store_audio_tracks():
"""
Store the audio tracks of an event identified after probing the first HLS video segment.
Body:
.. code-block:: python
{
"Name": string,
"Program": string,
"AudioTracks": list
}
Returns:
None
... | 4310bd8bfa7e65b4be113bfac93db74957b4e822 | 33,136 |
import operator
def isqrt(n):
"""
Return the integer part of the square root of the input.
(math.isqrt from Python 3.8)
"""
n = operator.index(n)
if n < 0:
raise ValueError("isqrt() argument must be nonnegative")
if n == 0:
return 0
c = (n.bit_length() - 1) // 2
a =... | b841bc3907c15677ddc97a5c5366b1a0312d12b6 | 33,137 |
import csv
def main(file_in, file_out):
"""
Read in lines, flatten list of lines to list of words,
sort and tally words, write out tallies.
"""
with open(file_in, 'r') as f_in:
word_lists = [line.split() for line in f_in]
# Flatten the list
# http://stackoverflow.com/questions/95... | 225dd5d5b4c2bcb158ee61aa859f78e1e608a5fe | 33,138 |
def check_api_key(current_request):
"""
Check if an API Key for GitHub was provided and
return a 403 if no x-api-key header was sent by the client.
"""
x_api_key = current_request.headers.get('x-api-key', False)
if not x_api_key:
return Response(
body='Missing x-api-key heade... | cb0b76e8b76135fe4498fdc66f34b1f5184441d1 | 33,139 |
def read_mm_stamp(fh, byteorder, dtype, count):
"""Read MM_STAMP tag from file and return as numpy.array."""
return numpy_fromfile(fh, byteorder+'8f8', 1)[0] | f575243ecfa67160bdbd90a476fd9fd3c6b0bed8 | 33,140 |
def Qfromq(q):
""" converts five-element set q of unique Q-tensor elements to the full 3x3 Q-tensor matrix """
return np.array( [ [ q[0], q[1], q[2] ],
[ q[1], q[3], q[4] ],
[ q[2], q[4], -q[0] - q[3] ] ] ) | cebc58a8023588fffd0a504e8894cd2c075cde3a | 33,141 |
def load_atomic(val):
"""
Load a std::atomic<T>'s value.
"""
valty = val.type.template_argument(0)
# XXX This assumes std::atomic<T> has the same layout as a raw T.
return val.address.reinterpret_cast(valty.pointer()).dereference() | 307bcc9d3eae2eede6a8e2275104280a1e7b4b94 | 33,142 |
def sample_trunc_beta(a, b, lower, upper):
"""
Samples from a truncated beta distribution in log space
Parameters
----------
a, b: float
Canonical parameters of the beta distribution
lower, upper: float
Lower and upper truncations of the beta distribution
Returns
------... | 40380436b82c4f5f169e21443aabbe2d30ccf84a | 33,143 |
import torch
def reduce_dict(input_dict, average=True):
# ref: https://github.com/pytorch/vision/blob/3711754a508e429d0049df3c4a410c4cde08e4e6/references/detection/utils.py#L118
"""
Args:
input_dict (dict): all the values will be reduced
average (bool): whether to do average or sum
Red... | 877919878977df23fae0cecddb9042762394d083 | 33,144 |
def dataId_to_dict(dataId):
""" Parse an LSST dataId to a dictionary.
Args:
dataId (dataId): The LSST dataId object.
Returns:
dict: The dictionary version of the dataId.
"""
return dataId.to_simple().dict()["dataId"] | 77b7566492b80a8c6e2becacafff36737c8a7256 | 33,145 |
def norm_max(tab):
"""
Short Summary
-------------
Normalize an array or a list by the maximum.
Parameters
----------
`tab` : {numpy.array}, {list}
input array or list.
Returns
-------
`tab_norm` : {numpy.array}, {list}
Normalized array.
"""
tab_norm = t... | 657f6ed358e81c6635e967d5b995663c05145c57 | 33,146 |
def getHoliday(holidayName):
"""Returns a specific holiday.
Args:
holidayName (str): The name of the holiday to return.
Case-sensitive.
Returns:
HolidayModel: The holiday, as a HolidayModel object, or None if
not found.
"""
print(holidayName)
return None | 15b67fd6ac607d1ff12a216cc3c4baab61305be6 | 33,147 |
def draw_object(obj, bb: "BBLike" = None, ax=None):
"""
Draw easymunk object using matplotlib.
"""
options = DrawOptions(ax or plt.gca(), bb=bb)
options.draw_object(obj)
return ax | 3b7322d12290d22be6eb47ac74d30494a1c091de | 33,148 |
import six
import hashlib
def hash_mod(text, divisor):
"""
returns the module of dividing text md5 hash over given divisor
"""
if isinstance(text, six.text_type):
text = text.encode('utf8')
md5 = hashlib.md5()
md5.update(text)
digest = md5.hexdigest()
return int(digest, 16) % d... | 3f127837bb072df5ee609b3afa80dd04e4f7b794 | 33,149 |
import re
def normalize_mac_address_table(input_string):
"""
:param input_string: cli string has been get from network device by command like "show mac-address table"
:return: {(mac_address', 'vlan'): 'l2_interface'}
"""
res = {}
same_local_mac_address_count: int = 0
mac_address_number: ... | f4c010d440e6e3ea89dd35c967019096fb2269ef | 33,150 |
def _get_exploration_memcache_key(exploration_id):
"""Returns a memcache key for an exploration."""
return 'exploration:%s' % exploration_id | 1400607cc86f84c242201c9c9fe36a7a06cd2357 | 33,151 |
from typing import Optional
from typing import Tuple
def corr_filter(
corrs: np.ndarray,
value_range: Optional[Tuple[float, float]] = None,
k: Optional[int] = None,
) -> Tuple[np.ndarray, np.ndarray]:
"""
Filter correlation values by k and value_range
"""
assert (value_range is None) or (... | bbf84b19edb39ac2b787517ad1e9817bf2a042f5 | 33,152 |
import re
def isValid(text):
"""
Returns True if the input is related to jokes/humor.
Arguments:
text -- user-input, typically transcribed speech
"""
return bool(re.search(r'WATCH|OUT', text, re.IGNORECASE)) | 7d94e30bf9e0da267bd4ccab1ce823aaa315eba2 | 33,153 |
def set_brevet():
"""
sets the brevet distance
"""
app.logger.debug("Got a JSON request");
calculate.brevet = request.args.get('brevet', 0, type=int)
return jsonify(result=calculate.brevet) | 855bc14643be30c96a43b4a4dc7d6ff171688d25 | 33,154 |
def pairs_from_array(a):
"""
Given an array of strings, create a list of pairs of elements from the array
Creates all possible combinations without symmetry (given pair [a,b], it does not create [b,a])
nor repetition (e.g. [a,a])
:param a: Array of strings
:return: list of pairs of strings
"""
pairs = l... | 50c489d660a7e82c18baf4800e599b8a3cd083f0 | 33,155 |
def cleanse_comments(line):
"""Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed.
"""
comment_position = line.find('//')
if comment_position != -1 and not is_cpp_string(line[:comment_pos... | d209b93070ab33d3f85f5a1d5c44ed47cde2fe91 | 33,156 |
def get_next_document_id(request, document_id):
"""Gets the id of the next document, by the current document's id
Gets the id of the next document, by the current document's id
The function is accessible for users with 'read_project' permission of the project and the owner of the project.
Args:
... | c9a098077a4672e27f438dc58ce0fb3c93d528d2 | 33,157 |
def is_merged(request):
"""Makes tests try both merged and closed pull requests."""
return request.param | d621f44b2ac3fe4a8639fd71d11e146fde9ca725 | 33,158 |
from typing import Dict
from typing import cast
def is_table(base_url: str, token: str) -> bool:
"""check if service layer is a table"""
params: Dict[str, str] = init_params(token)
type_layer = cast(Dict[str, str], request(base_url.rstrip('/'), params))['type']
return type_layer.lower() == 'table' | 23c67be574335689ac5e906c748e465d3d6ed0a0 | 33,159 |
def shared_options(option_list):
"""Define decorator for common options."""
def _shared_options(func):
for option in reversed(option_list):
func = option(func)
return func
return _shared_options | 7ef551ea9879b708e6b449ce1155d47b662efd3d | 33,160 |
from typing import Any
def complex_key(c: complex) -> Any:
"""Defines a sorting order for complex numbers."""
return c.real != int(c.real), c.real, c.imag | 55c17b0d4adf8bcfb39b50c66d5bd8133f5bb814 | 33,161 |
def make_raw_query_nlist_test_set(box, points, query_points, mode, r_max,
num_neighbors, exclude_ii):
"""Helper function to test multiple neighbor-finding data structures.
Args:
box (:class:`freud.box.Box`):
Simulation box.
points ((:math:`N_{points... | 2f9b6bd9436f6f416d62e3056b9baf663ed3b209 | 33,162 |
def runs_new_in_exp(exp='xpptut15', procname='pixel_status', verb=0) :
"""Returns list of (4-char str) runs which are found in xtc directory and not yet listed in the log file,
e.g. ['0059', '0060',...]
"""
runs_log = runs_in_log_file(exp, procname)
runs_xtc = runs_in_xtc_dir(exp)
runs_new = ... | 42faf8c27bdea9e979a8b2390a89fd6c3cad72f4 | 33,163 |
def cart_pole():
"""Generate Robot instance of classical CartPole dynamic system."""
#TODO: bring it to the new notation with 0-frame
robo = Robot('CartPole', 2, 2, 2, False)
robo.ant = (-1, 0, 1)
robo.sigma = (0, 1, 0)
robo.alpha = (0, pi/2, pi/2)
robo.d = (0, 0, 0)
robo.theta = (0, pi/... | 4edb03501665f94a0bdb3458189aab68fb45565a | 33,164 |
def get_targets(
initial_positions,
trajectory_target_positions):
"""Returns the averaged particle mobilities from the sampled trajectories.
Args:
initial_positions: the initial positions of the particles with shape
[n_particles, 3].
trajectory_target_positions: the absolute positions of the ... | e9f5bde1f791fe2f0546ba7d5323745b90f1029b | 33,165 |
def get_campaign_goal(campaign, goal_identifier):
"""Returns goal from given campaign and Goal_identifier.
Args:
campaign (dict): The running campaign
goal_identifier (string): Goal identifier
Returns:
dict: Goal corresponding to goal_identifer in respective campaign
"""
i... | 1a8738416ee8187ad2a6a977b36b68f66052bfe8 | 33,166 |
def vox2mm(ijk, affine):
"""
Convert matrix subscripts to coordinates.
.. versionchanged:: 0.0.8
* [ENH] This function was part of `nimare.transforms` in previous versions (0.0.3-0.0.7)
Parameters
----------
ijk : (X, 3) :obj:`numpy.ndarray`
Matrix subscripts for coordinates b... | 9800c53a447e2f7eab85e62ea802c91aaa23aea7 | 33,167 |
def getChanprofIndex(chanprof, profile, chanList):
""" List of indices into the RTTOV chanprof(:) array corresponding to the chanlist.
NB This assumes you've checked the chanlist against chanprof already.
"""
ilo = sum(map(len, chanprof[:profile-1]))
ichanprof = []
for c in chanList:
... | e61e210e8b05fdfbf3a769f4b5b388d765d436b9 | 33,168 |
def _get_blob_size_string(blob_key):
"""Return blob size string."""
blob_size = blobs.get_blob_size(blob_key)
if blob_size is None:
return None
return utils.get_size_string(blob_size) | 5f223101c71d641540aef97bda1b59f3bc7dfa7c | 33,169 |
import argparse
def parse_args():
"""Accepts path arguments for eml or directory."""
outpath = "C:\\Utilities\\Logs"
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", help="Path to EML file",
required=False)
parser.add_argument("-p", "--path", help="Dir... | 61c4fcc5bd4278a2dd3c32aa3fd9a779f0f2ff3e | 33,170 |
def masked_softmax_full(input_layer, n_nodes, batch_size):
"""
A Lambda layer to compute a lower-triangular version of the full adjacency.
Each row must sum up to one. We apply a lower triangular mask of ones
and then add an upper triangular mask of a large negative number.
After that we return the... | d48d48a90cb8ac80614ea54ee3a3f2e56def3a69 | 33,171 |
import collections
import socket
def match_backends_and_tasks(backends, tasks):
"""Returns tuples of matching (backend, task) pairs, as matched by IP and port. Each backend will be listed exactly
once, and each task will be listed once per port. If a backend does not match with a task, (backend, None) will
... | 9fab7e8b8f1a3c7a3cdbfb271fc5a4aac4807b03 | 33,172 |
def _drop_path(x, keep_prob):
"""
Drops out a whole example hiddenstate with
the specified probability.
"""
batch_size = tf.shape(x)[0]
noise_shape = [batch_size, 1, 1, 1]
random_tensor = keep_prob
random_tensor += tf.random_uniform(noise_shape, dtype=tf.float32)
binary_tensor = tf.f... | a91d308a91fbf328c472c2758dd080bab1b3ee4c | 33,173 |
import yaml
def read_pipeline_definition(file_path):
"""Function reads the yaml pipeline definitions.
Function reads the yaml pipeline definitions. We also remove the variables
key as that was only used for yaml placeholders.
Args:
file_path (str): Path to the pipeline definition.
Returns... | ea6ee7e8fcd14ffb30bca48b5f9505bc49657d0c | 33,174 |
import io
def detect_text(path):
"""Detects text in the file."""
client = vision.ImageAnnotatorClient()
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision.types.Image(content=content)
response = client.text_detection(image=image)
texts = response.text... | 22993db37ca8d858a9c4e1fbf866da9deca67528 | 33,175 |
import bisect
def find_dataset_ind(windows_ds, win_ind):
"""Taken from torch.utils.data.dataset.ConcatDataset.
"""
return bisect.bisect_right(windows_ds.cumulative_sizes, win_ind) | 76abcbdf9718cc59f1d2b7ca8daacc062970b253 | 33,176 |
def from_moment(w):
"""Converts a moment representation w to a 3D rotation matrix."""
length = vectorops.norm(w)
if length < 1e-7: return identity()
return rotation(vectorops.mul(w,1.0/length),length) | 3a5adf11665cd32dbebde158fbee5939e5654f18 | 33,177 |
def add_menu(data):
"""
新增
:param data:
:return:
"""
i = SysMenu.insert(data).execute()
return i | 07173c3648bbb3ed957f549420e80bcb1c539f48 | 33,178 |
def compute_distance_matrix(m1: np.ndarray, m2: np.ndarray,
dist_func: np.ndarray, row_wise: bool = False) \
-> np.ndarray:
"""
Function for computing the pair-wise distance matrix between two arrays of
vectors. Both matrices must have the same number ... | d044daaca81e9dc0ec186195493f1182a8209a1a | 33,179 |
from typing import List
from typing import Iterator
from typing import Any
def term_table(
strings: List[str], row_wise: bool = False, filler: str = "~"
) -> Iterator[Any]:
"""
:param strings:
:param row_wise:
:param filler:
:return:
"""
max_str_len = max(len(str) for str in strings) ... | 47fe2d7fc63490b99f03acb57b08eabbe9e1b20c | 33,180 |
def create_pipelines_lingspam():
"""Reproduces the pipelines evaluated in the LingSpam paper.
I. Androutsopoulos, J. Koutsias, K.V. Chandrinos, George Paliouras,
and C.D. Spyropoulos, "An Evaluation of Naive Bayesian Anti-Spam
Filtering". In Potamias, G., Moustakis, V. and van Someren, M. (Eds.),
... | 3d691c869e1b92f16d892e7d87cc59bad055d2a0 | 33,181 |
def band_dos_plain_spin_polarized(
band_folder,
dos_folder,
output='band_dos_plain_sp.png',
up_color='black',
down_color='red',
linewidth=1.25,
up_linestyle='-',
down_linestyle=':',
figsize=(6, 3),
width_ratios=[7, 3],
erange=[-6, 6],
kpath=None,
custom_kpath=None,
... | 8a00300828a0a9672edf025fcf4ca2a7c3264c96 | 33,182 |
def _unsigned16(data, littleEndian=False):
"""return a 16-bit unsigned integer with selectable Endian"""
assert len(data) >= 2
if littleEndian:
b0 = data[1]
b1 = data[0]
else:
b0 = data[0]
b1 = data[1]
val = (b0 << 8) + b1
return val | 22feb074aca7f4ab7d489eacb573c3653cad9272 | 33,183 |
def calculate_term_frequencies(tokens):
"""Given a series of `tokens`, produces a sorted list of tuples in the
format of (term frequency, token).
"""
frequency_dict = {}
for token in tokens:
frequency_dict.setdefault(token, 0)
frequency_dict[token] += 1
tf = []
for token... | b764175cd59fe25c4a87576faee2a76273097c5e | 33,184 |
def max(*l):
"""
Element-wise max of each of the input tensors (with Numpy-style broadcasting support).
Args:
*x (a list of Tensor): List of tensors for max.
Returns:
Tensor, the output
"""
return Max()(*l)[0] | 9467af70178c17d8bfa6404ca4969f6aae22ef2f | 33,185 |
def _edr_peak_trough_mean(ecg: pd.Series, peaks: np.array, troughs: np.array) -> np.array:
"""Estimate respiration signal from ECG based on `peak-trough-mean` method.
The `peak-trough-mean` method is based on computing the mean amplitude between R peaks (`peaks`) and
minima before R peaks (`troughs`).
... | 9f2a5fdbe9d27d0461133757157ef034fe46e2af | 33,186 |
import joblib
def feature_stacking(n_splits=CV, random_state=None, use_proba=False, verbose=False, drop_words=0.):
"""
Args:
n_splits: n_splits for KFold
random_state: random_state for KFlod
use_proba: True to predict probabilities of labels instead of labels
verbose: True to ... | 7af6d07dabd39ff27dcf66dc0d9d41cc30eefb70 | 33,187 |
import traceback
import json
def data(request):
"""
[メソッド概要]
アクション履歴画面の一覧表示
"""
logger.logic_log('LOSI00001', 'none', request=request)
msg = ''
lang = request.user.get_lang_mode()
ita_flg = False
mail_flg = False
servicenow_flg = False
filter_info = {
'tblname' : ... | e5292200699d169693d55e3032a47260258db5bc | 33,188 |
def get_default():
"""Get the configuration from the source code"""
return {name: dict(block()._asdict()) for name, _, block in triples} | 00279671d46b95dd85c307d2d690f5215d9e0a99 | 33,189 |
def npulses(image_number,passno=0):
"""How many X-ray bursts to send to the sample as function of image
number. image_number is 1-based, passno is 0-based.
"""
# When using sample translation the exposure may be boken up
# into several passes.
if passno != None: npulses = npulses_of_pass(image_n... | 485c2b27979a0b25ca4449b538f12554d2f12938 | 33,190 |
import torch
from typing import Optional
def topk__dynamic(ctx,
input: torch.Tensor,
k: int,
dim: Optional[int] = None,
largest: bool = True,
sorted: bool = True):
"""Rewrite `topk` for default backend.
Cast k to tensor... | f01ac53e2b7b5a1cef4ff55b0066bff7e9846f7f | 33,191 |
def GetLocalNodeId() -> int:
"""Returns the current local node id. If none has been set, a default is set and
used."""
global _local_node_id
if _local_node_id is None:
SetLocalNodeId(DEFAULT_LOCAL_NODE_ID)
return _local_node_id | 500c2795eade3e0854f23fbfb99e82796b98c7ef | 33,192 |
def get_dlons_from_case(case: dict):
"""pull list of latitudes from test case"""
dlons = [geo[1] for geo in case["destinations"]]
return dlons | 666ab789761e99749b4852a51f5d38c35c66bd2a | 33,193 |
def account_info(info):
"""Extract user information from IdP response"""
return dict(
user=dict(
email=info['User.email'][0],
profile=dict(
username=info['User.FirstName'][0],
full_name=info['User.FirstName'][0])),
external_id=info['User.em... | 1e3141e4ca84b935af67078d36e035c6c94bcefc | 33,194 |
from typing import Concatenate
def MangoYOLO(inputs, num_anchors, num_classes, **kwargs):
"""Create Tiny YOLO_v3 model CNN body in keras."""
x1 = compose(
DarknetConv2D_BN_Leaky(16, (3,3), **kwargs),
DarknetConv2D_BN_Leaky(16, (3, 3), strides=2, **kwargs),
DarknetConv2D_BN_Leaky(32, (3,3), **kwargs),
Darkne... | b9d1eba1407e5cd5e0037bd968e0d897153e31c0 | 33,195 |
def zone_max_matching(plan_a, plan_b):
"""
Determines the optimal bipartite matching of
districts in plan_a to districts in plan_b
to maximize the total population overlap.
Both plans should have districts indexed from 1 to k,
where k is some positive integer.
Based on the concept of "... | a710b27540ddff5c352374c62e074a2eed9ce39e | 33,196 |
def dyn_sim_feedback_discrete_time(A, Bu, Bd, x0, u, d, t_series, K):
"""
Simulate discrete-time ODE
Args:
A: discrete-time A
Bu: discrete-time B for control
Bd: discrete-time B for disturbance
x0: Initial condition in numpy array nx*1
u: Control signal in numpy array... | 9e77bdd04f03e8b2f20d204188d1d83ca325932c | 33,197 |
import itertools
def cutter_indexes(shape, tile_shape):
"""
Make indexes for cutting.
shape: shape of cutted data
tile_shape: shape of tile
"""
# TODO přepis r1?
# r0 = range(0, shape[0] - tile_shape[0] + 1, tile_shape[0])
# r1 = range(1, shape[1] - tile_shape[1] + 1, tile_shape[1])
... | 7543bd22bbcbd99dc75271de9b49f918273ff5b9 | 33,198 |
import logging
def get_recordings(mysql, symbol_id):
"""
Parameters
----------
mysql : dict
Connection information
symbol_id : int
ID of a symbol on write-math.com
Returns
-------
list :
A list of HandwrittenData objects
"""
connection = pymysql.connect... | c6e64b51353ae210c67adffd372b45a01847342d | 33,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.