content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def nonsingular_concat(X, vector):
"""Appends vector to matrix X iff the resulting matrix is nonsingular.
Args:
X (np.array): NxM Matrix to be appended to
vector (np.array): Nx1 vector to be appended to X
Returns:
new_X (np.array): Nx(M+1) Matrix or None
"""
# Cast vector to matrix
... | 68a1f6f8b0ea5e14fbbcacc618f2d19b07814813 | 3,652,432 |
from typing import Union
def get_oxidation_state(element: Union[str, Element]) -> int:
"""Get a typical oxidation state
If it doesn't exist in the database, 0 is returned.
Args:
element (str/ Element): Input element
Return:
Oxidation state of the element.
"""
try:
... | 24187bd8eb5c6d5794f1e287c676b0f16c170d55 | 3,652,433 |
from typing import Callable
def __quality_indexes(
graph: nx.Graph,
communities: object,
scoring_function: Callable[[object, object], float],
summary: bool = True,
) -> object:
"""
:param graph: NetworkX/igraph graph
:param communities: NodeClustering object
:param summary: boolean. I... | a328ec08bef43248c6e8fd7a0f11901801b0e2a5 | 3,652,434 |
def readFromDB_DSC_authorityKey(authorityKey: bytes, connection: Connection) -> DocumentSignerCertificate:
"""Reading from database"""
try:
logger.info("Reading DSC object from database with authority key.")
return connection.getSession().query(DocumentSignerCertificateStorage).filter(DocumentSi... | 34cff097201af92d337568094b8d48577f7e440f | 3,652,436 |
def history_report(history, config=None, html=True):
"""
Test a model and save a history report.
Parameters
----------
history : memote.HistoryManager
The manager grants access to previous results.
config : dict, optional
The final test report configuration.
html : bool, opt... | 8ba956c959b72f37b570b91ea4f01287eb8783c6 | 3,652,437 |
def derive_from_dem(dem):
"""derive slope and flow direction from a DEM.
Results are returned in a dictionary that contains references to
ArcPy Raster objects stored in the "in_memory" (temporary) workspace
"""
# set the snap raster for subsequent operations
env.snapRaster = dem
# ... | 4563e4ccd6695865c05c7a945dcc6244fb8af012 | 3,652,438 |
from typing import Optional
def from_error_details(error: str, message: str, stacktrace: Optional[str]) -> BidiException:
"""Create specific WebDriver BiDi exception class from error details.
Defaults to ``UnknownErrorException`` if `error` is unknown.
"""
cls = get(error)
return cls(error, messa... | 238566bcf1092b685deebcadcf60c1905e585cb9 | 3,652,439 |
def tangential_proj(u, n):
"""
See for instance:
https://link.springer.com/content/pdf/10.1023/A:1022235512626.pdf
"""
return (ufl.Identity(u.ufl_shape[0]) - ufl.outer(n, n)) * u | 92c8eafa222418221b2fb0e1b242dbd76696407d | 3,652,440 |
def _RemoveEdges(tris, match):
"""tris is list of triangles.
er is as returned from _MaxMatch or _GreedyMatch.
Return list of (A,D,B,C) resulting from deleting edge (A,B) causing a merge
of two triangles; append to that list the remaining unmatched triangles."""
ans = []
triset = set(tris)
... | d2415f7275652254ca87a7621e483a29816a8083 | 3,652,441 |
def get_course_authoring_url(course_locator):
"""
Gets course authoring microfrontend URL
"""
return configuration_helpers.get_value_for_org(
course_locator.org,
'COURSE_AUTHORING_MICROFRONTEND_URL',
settings.COURSE_AUTHORING_MICROFRONTEND_URL
) | cea917ca211be1fdd1b4cf028652101392fd80ab | 3,652,442 |
def sumDwellStateSub(params):
"""Threaded, sums dwell times with 1 day seeing no change & accounting for fractional days"""
(dfIn,dwellTime,weight) = params
dfOut = dfIn.copy(deep=True)
while dwellTime > 1:
if dwellTime > 2:
increment = 1
else:
increment = dwellT... | 47ab530bfad9a321bf349e7542f279aae0958a9b | 3,652,443 |
def launch_attacker_view():
"""
Accepts a JSON payload with the following structure:
{
"target": "nlb-something.fqdn.com",
"attacker": "1.2.3.4"
}
If the payload parses correctly, then launch a reverse shell listener using pexpect.spawn
then spawn the auto-sploit.sh tool and ente... | 2c987a2b552fa5cfc6e85240c71d496fe43785c3 | 3,652,444 |
import copy
def stretch(alignment, factor):
"""Time-stretch the alignment by a constant factor"""
# Get phoneme durations
durations = [factor * p.duration() for p in alignment.phonemes()]
alignment = copy.deepcopy(alignment)
alignment.update(durations=durations)
return alignment | 1ea58c32509365d503379df616edd00718cfca19 | 3,652,445 |
def _read_node( data, pos, md_total ):
"""
2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2
The quantity of child nodes.
The quantity of metadata entries.
Zero or more child nodes (as specified in the header).
"""
child_count = data[ pos ]
pos += 1
md_count = data[ pos ]
pos += 1
for i in range( child_count ):
pos, m... | 768036031ab75b532d667769477f8d3144129ac8 | 3,652,450 |
def _large_flag_fit(x, yDat, yFit, initz, speciesDict, minSize, errBound):
"""
Attempts to more robustly fit saturated lyman alpha regions that have
not converged to satisfactory fits using the standard tools.
Uses a preselected sample of a wide range of initial parameter guesses
designed to fit sa... | c065e9e1500977dfa1a522ebd238d2e71e188c6a | 3,652,451 |
from typing import Type
def mse_large_arrays_masked(dataA: 'LargeArray', dataB: 'LargeArray', mask: 'LargeArray',
dtype: Type, batchSizeFlat=1e8):
"""
Compute MSE between two HDF datasets, considering elements where the mask is set to true (one).
Computation is performed in bat... | 27636fc32d208d544b0b2f9790015e6f3d86a69d | 3,652,452 |
import copy
def xml_elem_or_str_to_text(elem_or_xmlstr, default_return=""):
"""
Return string with all tags stripped out from either etree element or xml marked up string
If string is empty or None, return the default_return
>>> root = etree.fromstring(test_xml)
>>> xml_elem_or_str_to_text(t... | 1e13c74d3d7d69fdd1ce8011384e1ee564f366f1 | 3,652,453 |
def sequence_equals(sequence1, sequence2):
"""
Inspired by django's self.assertSequenceEquals
Useful for comparing lists with querysets and similar situations where
simple == fails because of different type.
"""
assert len(sequence1) == len(sequence2), (len(sequence1), len(sequence2))
for i... | 38016a347caf79458bb2a872d0fd80d6b813ba33 | 3,652,454 |
def statistical_features(ds, exclude_col_names: list = [],
feature_names=['mean', 'median', 'stddev', 'variance', 'max', 'min', 'skew',
'kurt', 'sqr']):
"""
Compute statistical features.
Args:
ds (DataStream): Windowed/grouped DataStr... | 544b32b3f909c8f98ae18ae43006719105627a85 | 3,652,455 |
def second_order_difference(t, y):
""" Calculate the second order difference.
Args:
t: ndarray, the list of the three independent variables
y: ndarray, three values of the function at every t
Returns:
double: the second order difference of given points
"""
# claculate the f... | 40e37d2b34104772966afc34e41c1ebc742c9adf | 3,652,456 |
def timeDelay( gpsTime, rightAscension, declination, unit, det1, det2 ):
"""
timeDelay( gpsTime, rightAscension, declination, unit, det1, det2 )
Calculates the time delay in seconds between the detectors
'det1' and 'det2' (e.g. 'H1') for a sky location at (rightAscension
and declination) which must be give... | eb0f444ad2a2be0cf10d62fdbe8b41c8d924c798 | 3,652,457 |
def RngBinStr(n):
"""
Takes a int which represents the length of the final binary number.
Returns a string which represents a number in binary where each char was randomly generated and has lenght n.
"""
num = ""
for i in range(n):
if rng.random() < 0.5:
num += "0"
el... | cf063532425b51243f3ba95f90df892bda121363 | 3,652,458 |
def get_bdbox_from_heatmap(heatmap, threshold=0.2, smooth_radius=20):
"""
Function to extract bounding boxes of objects in heatmap
Input :
Heatmap : matrix extracted with GradCAM.
threshold : value defining the values we consider , increasing it increases the size of bounding boxes.
... | 0a7397263cf2b8b238679f3cd54b8bcb67553387 | 3,652,459 |
def get_request(request_id, to_json=False, session=None):
"""
Get a request or raise a NoObject exception.
:param request_id: The id of the request.
:param to_json: return json format.
:param session: The database session in use.
:raises NoObject: If no request is founded.
:returns: Requ... | 41d34057b859a88818866a03392ec6f96d2b4983 | 3,652,460 |
def gen_multi_correlated(N, n, c_mat, p_arr, use_zscc=False, verify=False, test_sat=False, pack_output=True, print_stat=False):
"""Generate a set of bitstreams that are correlated according to the supplied correlation matrix"""
#Test if the desired parameters are satisfiable
sat_result = corr_sat(N, n, c_m... | 0b1cf206e92363910877b0202b9fb94d377358a3 | 3,652,461 |
def rxzero_traj_eval_grad(parms, t_idx):
"""
Analytical gradient for evaluated trajectory with respect to the log-normal parameters
It is expected to boost the optimization performance when the parameters are high-dimensional...
"""
v_amp_array = np.array([rxzero_vel_amp_eval(parm, t_idx) for parm i... | 47aa04aa2096f472dd0f5612c95903fd638cb1d0 | 3,652,462 |
import traceback
def exec_geoprocessing_model():
"""算法模型试运行测试
根据算法模型的guid标识,算法模型的输入参数,运行算法模型
---
tags:
- system_manage_api/geoprocessing_model
parameters:
- in: string
name: guid
type: string
required: true
description: 流程模型的guid
- in: array
... | 8cfcc56117747c78d8b2c4fc10dc29fa8115aa67 | 3,652,463 |
import requests
def perform_extra_url_query(url):
"""Performs a request to the URL supplied
Arguments:
url {string} -- A URL directing to another page of results from the NASA API
Returns:
Response object -- The response received from the NASA API
"""
response = requests.request... | 7d5fe2d6467d90e1f7e85d2fc51187a36f62305d | 3,652,464 |
from org.optaplanner.optapy import PythonWrapperGenerator # noqa
from org.optaplanner.core.api.domain.solution import \
def problem_fact_property(fact_type: Type) -> Callable[[Callable[[], List]],
Callable[[], List]]:
"""Specifies that a property on a @plann... | 068cdbc1a8dab95b5a742740195b4fdaf595de2a | 3,652,465 |
def _load_method_arguments(name, argtypes, args):
"""Preload argument values to avoid freeing any intermediate data."""
if not argtypes:
return args
if len(args) != len(argtypes):
raise ValueError(f"{name}: Arguments length does not match argtypes length")
return [
arg if hasattr... | 0eb6a16c2e4c1cd46a114923f81e93af331c3d6e | 3,652,466 |
import json
def crash_document_add(key=None):
"""
POST: api/vX/crash/<application_key>
add a crash document by web service
"""
if 'Content-Type' not in request.headers or request.headers['Content-Type'].find('multipart/form-data') < 0:
return jsonify({ 'success': False, 'message': 'input e... | 669c30141d5fb50128b3c60577433938daec5a2a | 3,652,467 |
def log_data(model, action, before, after, instance):
"""Logs mutation signals for Favourite and Category models
Args:
model(str): the target class of the audit-log: favourite or category
action(str): the type of mutation to be logged: create, update, delete
before(dict): the previous v... | f23ef8d2a759130ac55d3dc55f4497099776414f | 3,652,468 |
import requests
def download(url, local_filename, chunk_size=1024 * 10):
"""Download `url` into `local_filename'.
:param url: The URL to download from.
:type url: str
:param local_filename: The local filename to save into.
:type local_filename: str
:param chunk_size: The size to download chun... | 0a86b8600e72e349a4e1344d2ce1ad2bb00b889d | 3,652,469 |
def tokenize(data, tok="space", lang="en"):
"""Tokenize text data.
There are 5 tokenizers supported:
- "space": split along whitespaces
- "char": split in characters
- "13a": Official WMT tokenization
- "zh": Chinese tokenization (See ``sacrebleu`` doc)
- "moses": Moses tokenizer (you can ... | 0974edc3a4d66b90add101002fbcc1486c21e5ce | 3,652,471 |
def ift2(x, dim=(-2, -1)):
"""
Process the inverse 2D fast fourier transform and swaps the axis to get correct results using ftAxis
Parameters
----------
x: (ndarray) the array on which the FFT should be done
dim: the axis (or a tuple of axes) over which is done the FFT (default is the last of t... | 50377bb81fa17c152f8b8053cdae1502dbc791ad | 3,652,472 |
def chi2_test_independence(prediction_files: list, confidence_level: float):
"""Given a list of prediction files and a required confidence level,
return whether the sentiment probability is independent on which prediction
file it comes from.
Returns True if the sentiment probability is independent of s... | 870a91afa202b19398c620756492bd5297c4eb69 | 3,652,473 |
import json
async def insert(cls:"PhaazeDatabase", WebRequest:Request, DBReq:DBRequest) -> Response:
""" Used to insert a new entry into a existing container """
# prepare request for a valid insert
try:
DBInsertRequest:InsertRequest = InsertRequest(DBReq)
return await performInsert(cls, DBInsertRequest)
ex... | 20772f847137422a1da227da38946c9b1a01106a | 3,652,476 |
def eulerAngleXYZ(t123, unit=np.pi/180., dtype=np.float32):
"""
::
In [14]: eulerAngleXYZ([45,0,0])
Out[14]:
array([[ 1. , 0. , 0. , 0. ],
[-0. , 0.7071, 0.7071, 0. ],
[ 0. , -0.7071, 0.7071, 0. ],
[ 0. , ... | a0e6f0b58c1510aa27cb5064ddebd40b3688de37 | 3,652,477 |
def is_on_cooldown(data):
""" Checks to see if user is on cooldown. Based on Castorr91's Gamble"""
# check if command is on cooldown
cooldown = Parent.IsOnCooldown(ScriptName, CGSettings.Command)
user_cool_down = Parent.IsOnUserCooldown(ScriptName, CGSettings.Command, data.User)
caster = Parent.HasP... | b15180c7e890298cc1949ddfb199b42156ee66d9 | 3,652,478 |
def human_readable_size(num):
"""
To show size as 100K, 100M, 10G instead of
showing in bytes.
"""
for s in reversed(SYMBOLS):
power = SYMBOLS.index(s)+1
if num >= 1024**power:
value = float(num) / (1024**power)
return '%.1f%s' % (value, s)
# if size less... | 3c4ad148bc717b7058e90b3abf5efd67f6d92651 | 3,652,479 |
def sum_2_level_dict(two_level_dict):
"""Sum all entries in a two level dict
Parameters
----------
two_level_dict : dict
Nested dict
Returns
-------
tot_sum : float
Number of all entries in nested dict
"""
'''tot_sum = 0
for i in two_level_dict:
for j in... | 6b5be015fb84fa20006c11e9a3e0f094a6761e74 | 3,652,480 |
def q_values_from_q_func(q_func, num_grid_cells, state_bounds, action_n):
"""Computes q value tensor from a q value function
Args:
q_func (funct): function from state to q value
num_grid_cells (int): number of grid_cells for resulting q value tensor
state_bounds (list of tuples): state bounds for... | 2378f2021e16678b75622a23c9e57ba6b2f6d1d7 | 3,652,482 |
import re
def check_ip(ip):
"""
Check whether the IP is valid or not.
Args:
IP (str): IP to check
Raises:
None
Returns:
bool: True if valid, else False
"""
ip = ip.strip()
if re.match(r'^(?:(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])'
'... | 2ff9a9262e46546fcb8854edee4b3b18ae1e2cc4 | 3,652,484 |
from typing import Iterator
from typing import Optional
def _stream_lines(blob: bytes) -> Iterator[bytes]:
"""
Split bytes into lines (newline (\\n) character) on demand.
>>> iter = _stream_lines(b"foo\\nbar\\n")
>>> next(iter)
b'foo'
>>> next(iter)
b'bar'
>>> next(iter)
Traceback... | 8a166af1f765ca9eb70728d4c4bb21c00d7ddbf8 | 3,652,485 |
from typing import Dict
async def fetch_all_organizations(session: ClientSession) -> Dict:
"""Fetch all organizations from organization-catalog."""
url = f"{Config.org_cat_uri()}/organizations"
org_list = await fetch_json_data(url, None, session)
return {org["organizationId"]: org for org in org_list}... | bf033ed85671214d9282acba3361fbdc1e6d4f6e | 3,652,486 |
from typing import Optional
import tqdm
def create_splits_random(df: pd.DataFrame, val_frac: float,
test_frac: float = 0.,
test_split: Optional[set[tuple[str, str]]] = None,
) -> dict[str, list[tuple[str, str]]]:
"""
Args:
df: ... | b8410d8672d11c8133b7d6d8dcdead46e668b3aa | 3,652,487 |
def ha_close(close,high,low,open, n=2, fillna=False):
"""Relative Strength Index (RSI)
Compares the magnitude of recent gains and losses over a specified time
period to measure speed and change of price movements of a security. It is
primarily used to attempt to identify overbought or oversold condit... | 655ce9be20f56a22cbe32ed0eaf7615d2b891577 | 3,652,488 |
def PLUGIN_ENTRY():
"""
Required plugin entry point for IDAPython Plugins.
"""
return funcref_t() | 5c669321d8fc890b8b352e4041dc75773d191664 | 3,652,489 |
def chao1_var_no_doubletons(singles, chao1):
"""Calculates chao1 variance in absence of doubletons.
From EstimateS manual, equation 7.
chao1 is the estimate of the mean of Chao1 from the same dataset.
"""
s = float(singles)
return s*(s-1)/2 + s*(2*s-1)**2/4 - s**4/(4*chao1) | 6b93743a35c70c9ed5b9f3fc9bece1e9363c5802 | 3,652,490 |
def inBarrel(chain, index):
"""
Establish if the outer hit of a muon is in the barrel region.
"""
if abs(chain.muon_outerPositionz[index]) < 108:
return True | 9cbc5dad868d6e0ca221524ef8fc5ed5501adaa4 | 3,652,491 |
from typing import Union
from typing import Callable
from typing import Optional
from typing import Any
def text(message: Text,
default: Text = "",
validate: Union[Validator,
Callable[[Text], bool],
None] = None, # noqa
qmark: Text = DEFAUL... | 74a79a0ce10503cf10841e8370de870c7e42f8e9 | 3,652,493 |
def nav_bar(context):
"""
Define an active tab for the navigation bar
"""
home_active = ''
about_active = ''
detail_active = ''
list_active = ''
logout_active = ''
signup_active = ''
login_active = ''
friends_active = ''
snippets_active = ''
request = context['reque... | 77b5a8bb367228cc31a0f2454e494d97a5e2b411 | 3,652,494 |
def setup_models(basedir, name, lc=True):
"""
Setup model container for simulation
Parameters
----------
basedir : string
Base directory
name : string
Name of source component
Returns
-------
models : `~gammalib.GModels()`
Model container
"""
# Initi... | 8b8db045d5c7b669f579a8f3b74abe204c82c285 | 3,652,495 |
def create_csm(image):
"""
Given an image file create a Community Sensor Model.
Parameters
----------
image : str
The image filename to create a CSM for
Returns
-------
model : object
A CSM sensor model (or None if no associated model is available.)
"""
... | 681c3b5886346e793b26d2e7c801b924ca82b546 | 3,652,496 |
def walk(obj, path='', skiphidden=True):
"""Returns a recursive iterator over all Nodes starting from
findnode(obj, path).
If skiphidden is True (the default) then structure branches starting with
an underscore will be ignored.
"""
node = findnode(obj, path)
return walknode(node, s... | efd3e10329d7e8832fa33c9425974ea2cd80938c | 3,652,497 |
def to_string(class_name):
"""
Magic method that is used by the Metaclass created for Itop object.
"""
string = "%s : { " % type(class_name)
for attribute, value in class_name.__dict__.iteritems():
string += "%s : %s, " % (attribute, value)
string += "}"
return string | a7e155c92c4e62c1f070a474905a7e0c654f45ff | 3,652,499 |
def molefraction_2_pptv(n):
"""Convert mixing ratio units from mole fraction to parts per
thousand by volume (pptv)
INPUTS
n: mole fraction (moles per mole air)
OUTPUTS
q: mixing ratio in parts per trillion by volume (pptv)
"""
# - start with COS mixing ratio n as mole fraction:
# ... | a6a26267f45fb70c346e86421c427bd155bfa65a | 3,652,501 |
import warnings
def is_valid_y(y, warning=False, throw=False, name=None):
"""
"""
y = np.asarray(y, order='c')
valid = True
try:
if len(y.shape) != 1:
if name:
raise ValueError(('Condensed distance matrix \'%s\' must '
'have sha... | 6c3f56c8b931b325d521805902b526054f21e22d | 3,652,502 |
import json
import yaml
def yaml_parse(yamlstr):
"""Parse a yaml string"""
try:
# PyYAML doesn't support json as well as it should, so if the input
# is actually just json it is better to parse it with the standard
# json parser.
return json.loads(yamlstr)
except ValueError... | 8586e1e39ae9f0933b6552531d72cb3a6516f615 | 3,652,503 |
import collections
def csl_item_from_pubmed_article(article):
"""
article is a PubmedArticle xml element tree
https://github.com/citation-style-language/schema/blob/master/csl-data.json
"""
csl_item = collections.OrderedDict()
if not article.find("MedlineCitation/Article"):
raise Not... | 889bb8bbbafd85607936db7caeb33140c4e356fb | 3,652,504 |
def unphase_uvw(ra, dec, uvw):
"""
Calculate unphased uvws/positions from phased ones in an icrs or gcrs frame.
This code expects phased uvws or positions in the same frame that ra/dec
are in (e.g. icrs or gcrs) and returns unphased ones in the same frame.
Parameters
----------
ra : float
... | a6e3d1371ed612bd1ece08fc6fabd4ee77241603 | 3,652,506 |
import uuid
def sender_msg_to_array(msg):
"""
Parse a list argument as returned by L{array_to_msg} function of this
module, and returns the numpy array contained in the message body.
@param msg: a list as returned by L{array_to_msg} function
@rtype: numpy.ndarray
@return: The numpy array conta... | c959a535a4f47c86f9520167fa59dc8eecc70071 | 3,652,507 |
def find_shortest_path(node):
"""Finds shortest path from node to it's neighbors"""
next_node,next_min_cost=node.get_min_cost_neighbor()
if str(next_node)!=str(node):
return find_shortest_path(next_node)
else:
return node | 4fa3979ff665b5cf8df423ff9b3fbaa880d62a73 | 3,652,508 |
from .features import Sequence, get_nested_type
def cast_array_to_feature(array: pa.Array, feature: "FeatureType", allow_number_to_str=True):
"""Cast an array to the arrow type that corresponds to the requested feature type.
For custom features like Audio or Image, it takes into account the "cast_storage" met... | 28c3275445a79e869b8dfe5ec49522ff10ca6842 | 3,652,509 |
def check_key_match(config_name):
"""
Check key matches
@param config_name: Name of WG interface
@type config_name: str
@return: Return dictionary with status
"""
data = request.get_json()
private_key = data['private_key']
public_key = data['public_key']
return jsonify(f_check_k... | 00a3e78e403a54b16558e21e2c6d095560f272d0 | 3,652,510 |
def delete_user_group(request, group_id, *args, **kwargs):
"""This one is not really deleting the group object, rather setting the active status
to False (delete) which can be later restored (undelete) )"""
try:
hydroshare.set_group_active_status(request.user, group_id, False)
messages.succe... | acad59484befdc5448031343aad47989e9c67d64 | 3,652,511 |
from typing import List
def _generate_room_square(dungen: DungeonGenerator, room_data: RoomConceptData) -> RoomConcept:
"""
Generate a square-shaped room.
"""
map_width = dungen.map_data.width
map_height = dungen.map_data.height
# ensure not bigger than the map
room_width = min(dungen.rng... | d147f64aed8491ce9b4714f61b64f971683d913e | 3,652,512 |
def str_is_float(value):
"""Test if a string can be parsed into a float.
:returns: True or False
"""
try:
_ = float(value)
return True
except ValueError:
return False | 08f2e30f134479137052fd821e53e050375cd11e | 3,652,514 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Ruckus Unleashed from a config entry."""
try:
ruckus = await hass.async_add_executor_job(
Ruckus,
entry.data[CONF_HOST],
entry.data[CONF_USERNAME],
entry.data[CONF_PASS... | 567af55b3f46c2b5e2ef5204dbe85fabb87c9a74 | 3,652,516 |
def get_user_plugins_grouped(get_allowed_plugin_uids_func,
get_registered_plugins_grouped_func,
registry,
user,
sort_items=True):
"""Get user plugins grouped.
:param callable get_allowed_plugin_u... | f355738b99f503568a35945e1008f84145569b62 | 3,652,517 |
def calc_randnm7(reg_dict, mlx75027):
"""
Calculate the RANDMN7 register value
Parameters
----------
reg_dict : dict
The dictionary that contains all the register information
mlx75027 : bool
Set to True if using the MLX75027 sensor, False
if using the MLX75026 sensor.... | 898c4662f045fbcbe655870a8d5642de92debcaf | 3,652,518 |
def get_orientation(pose, ori):
"""Generate an orientation vector from yaw/pitch/roll angles in radians."""
yaw, pitch, roll = pose
c1 = np.cos(-yaw)
s1 = np.sin(-yaw)
c2 = np.cos(-pitch)
s2 = np.sin(-pitch)
c3 = np.cos(-roll)
s3 = np.sin(-roll)
Ryaw = np.array([[c1, s1, 0], [-s1, c1... | d00cc9befde7afd28b66c572116fb1234e109367 | 3,652,519 |
import copy
def draw_deformation(source_image, grid, grid_size = 12):
"""
source_image: PIL image object
sample_grid: the sampling grid
grid_size: the size of drawing grid
"""
im = copy.deepcopy(source_image)
d = ImageDraw.Draw(im)
H,W = source_image.size
dist =int(H/grid_size)
... | ec9c6b90e89221789ecba55e2c2360ccd24f9c8c | 3,652,520 |
def dial_socket(host='localhost', port):
"""
Connect to the socket created by the
server instance on specified host and port
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
return sock | 555c90f05cdf0feda97d5db160dd048542e03376 | 3,652,521 |
def analyseClassificationCoefficients(X: pd.DataFrame,
y: pd.Series,
D_learning_results: pd.DataFrame,
outputPath: str) -> dict:
"""
This function evaluates the importance coefficients of the input ... | 2e6a1e4e05d505ab5e43c638810fc23a6b11a228 | 3,652,522 |
def centerfreq_to_bandnum(center_freq, norm_freq, nth_oct):
"""Returns band number from given center frequency."""
return nth_oct * np.log2(center_freq / norm_freq) | 857b9b2598981ba608c958c8acce35a1e71d021f | 3,652,523 |
from typing import Union
from typing import Sequence
from typing import Optional
def crossval_model(
estimator: BaseEstimator,
X: pd.DataFrame,
y: Union[pd.Series, pd.DataFrame],
evaluators: Sequence[Evaluator],
cv: Optional[
Union[int, BaseCrossValidator]
] = None, # defaults to KFol... | 49c95241ed04c248221c6366cde717e575f5f7c1 | 3,652,524 |
import time
def measure_dist(positions,weights,v_ref,side = False):
"""
Will plot the mouse and allow me to click and measure with two clicks
side is false (so top view)
but can be True, then it's cut though the major axis of hte mouse (determined by v_reference)
"""
# simplest trick is to jus... | 4d67344b0df64d3721d87803772c8aad15936fd9 | 3,652,525 |
def _get_draft_comments(request, issue, preview=False):
"""Helper to return objects to put() and a list of draft comments.
If preview is True, the list of objects to put() is empty to avoid changes
to the datastore.
Args:
request: Django Request object.
issue: Issue instance.
preview: Preview flag... | affea5c09e42283057d70d7d1ce9f931d373d90d | 3,652,526 |
def activate_model(cfg):
"""Activate the dynamic parts."""
cfg["fake"] = cfg["fake"]()
return cfg | df8b0a23dc683435c1379e57bc9fd98149876d9d | 3,652,527 |
def convert_to_number(string):
"""
Tries to cast input into an integer number, returning the
number if successful and returning False otherwise.
"""
try:
number = int(string)
return number
except:
return False | 30110377077357d3e7d45cac4c106f5dc9349edd | 3,652,528 |
def _ts_value(position, counts, exposure, background, kernel, norm, flux_estimator):
"""Compute TS value at a given pixel position.
Uses approach described in Stewart (2009).
Parameters
----------
position : tuple (i, j)
Pixel position.
counts : `~numpy.ndarray`
Counts image
... | 5a53a408205e5aecf0b2035efbc3feb33097e46c | 3,652,529 |
from typing import List
def mean(nums: List) -> float:
"""
Find mean of a list of numbers.
Wiki: https://en.wikipedia.org/wiki/Mean
>>> mean([3, 6, 9, 12, 15, 18, 21])
12.0
>>> mean([5, 10, 15, 20, 25, 30, 35])
20.0
>>> mean([1, 2, 3, 4, 5, 6, 7, 8])
4.5
>>> mean([])
Trace... | 3c802b4967f646b6338e52b4ce12977274054c15 | 3,652,530 |
import scipy
def post_3d(post_paths, labels, colours, linestyles, contour_levels_sig, x_label=None, y_label=None, z_label=None,
x_lims=None, y_lims=None, z_lims=None, smooth_xy=None, smooth_xz=None, smooth_yz=None, smooth_x=None,
smooth_y=None, smooth_z=None, print_areas=False, save_path=None)... | 5e25de6f69a7d281e59ac1423b6be4b27080a689 | 3,652,531 |
def det(m1: ndarray) -> float:
"""
Compute the determinant of a double precision 3x3 matrix.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/det_c.html
:param m1: Matrix whose determinant is to be found.
:return: The determinant of the matrix.
"""
m1 = stypes.to_double_matrix(m1)
... | aa0a6629536df22ea016bb81a8e62769c7b3ab9e | 3,652,532 |
def path_to_xy(path: PointList) -> XYList:
"""Convert PointList to XYList"""
return [p.xy() for p in path] | ea8cc222ab2b8ce6634e9bb1ea7d456bfa451782 | 3,652,533 |
def is_gzip(name):
"""Return True if the name indicates that the file is compressed with
gzip."""
return name.endswith(".gz") | a6ea06f04808a07c4b26338f87273986eda86ef1 | 3,652,535 |
def possible_sums_of(numbers: list) -> list:
"""Compute all possible sums of numbers excluding self."""
possible_sums = []
for idx, nr_0 in enumerate(numbers[:-1]):
for nr_1 in numbers[idx + 1:]:
possible_sums.append(nr_0 + nr_1)
return possible_sums | 39ebe3e48c45a9c30f16b43e6c34778c5e813940 | 3,652,537 |
def normalize_norms(X, scale_factor=1, axis=0, by='sum'):
""" wrapper of `normalize_colsum` and `normalize_rowsum`
Parameters
----------
X:
a (sparse) matrix
scale_factor: numeric, None
if None, use the median of sum level as the scaling factor.
axis: int, {0, 1}
if axis... | 7c491245fc83b2b48c21cb91f79915af7261f5ba | 3,652,538 |
def full_solution(combined, prob_dists):
"""
combined: (w, n-1->n-w, 3, 3)
prob_dists: (n, 3, total_reads)
p[v,g,k] = prob of observing k of total_reads on ref if gneotype ig on varaint v
"""
N = len(combined[0])+1
best_idx, best_score = np.empty(N), -np.inf*np.ones(N)
for j, counts in e... | 2732c57e44aa0c17bd652b01226053c095d9fdb3 | 3,652,539 |
def ycbcr2bgr(img):
"""Convert a YCbCr image to BGR image.
The bgr version of ycbcr2rgb.
It implements the ITU-R BT.601 conversion for standard-definition
television. See more details in
https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.
It differs from a similar function in cv2.cvtCol... | e5e5c408e40645ae4844635fd0fbf065746f187d | 3,652,540 |
from datetime import datetime
def tensorize_fg_coeffs(
data,
wgts,
fg_model_comps,
notebook_progressbar=False,
verbose=False,
):
"""Initialize foreground coefficient tensors from uvdata and modeling component dictionaries.
Parameters
----------
data: list
list of tf.Tenso... | dbff52b154326df6a324ef454887c65bfe528044 | 3,652,541 |
def receive_incoming_bets():
"""
Sends fixtures to the front-end
"""
return fixtures.fixtures_information | 2ab61c0bc15bb9c8c4359bb8ca7e8b1287b1d182 | 3,652,542 |
def fibonacci(n):
"""
object: fibonacci(n) returns the first n Fibonacci numbers in a list
input: n- the number used to calculate the fibonacci list
return: retList- the fibonacci list
"""
if type(n) != int:
print(n)
print(":input not an integer")
return False
if... | ac37d952eecae57b33fb3768f1c8097d76769534 | 3,652,543 |
def psnr_batch(_mse_batch_val):
"""
:param _mse_val_each: ndarray
:return: ndarray
Usage:
1) The Bath is deal with channel.
Thus, it is recommended to call mse_batch function before the psnr_batch function.
2) cumsum_psnr_rgb += (metric_.psnr_batch(_mse_batch_val=... | c33eaa3e04fbd7d9749ad8989a15ea198ff4d806 | 3,652,544 |
def get_u0(u0_type, num_features):
"""return a polyhedral definition for U^0, B_mat and b_vec"""
assert u0_type in ["box", "positive_normed"]
if u0_type == "box":
B_mat, b_vec = U0_box(num_features)
if u0_type == "positive_normed":
B_mat, b_vec = U0_positive_normed(num_features)
r... | bb6856284067ac3d5b39ca50d30c5745a7ee5e07 | 3,652,545 |
def funcparser_callable_search_list(*args, caller=None, access="control", **kwargs):
"""
Usage: $objlist(#123)
Legacy alias for search with a return_list=True kwarg preset.
"""
return funcparser_callable_search(*args, caller=caller, access=access,
return_list=... | 511bff6803ba9b088fa94d32e9cb3f85c4823b94 | 3,652,546 |
def upcoming_movie_name(soup):
"""
Extracts the list of movies from BeautifulSoup object.
:param soup: BeautifulSoup object containing the html content.
:return: list of movie names
"""
movie_names = []
movie_name_tag = soup.find_all('h4')
for _movie in movie_name_tag:
_movie_result = _movie.find_all('a')
t... | 6bac06375109ec103492a079746e2c0364bfac17 | 3,652,547 |
def options(*args, **kw):
"""Mark the decorated function as a handler for OPTIONS requests."""
return _make_handler_decorator('OPTIONS', *args, **kw) | 21e6f830e054a84cd16e5cdfbb63c2202ff70d7b | 3,652,548 |
import codecs
import json
def lookup_vendor_name(mac_address):
"""
Translates the returned mac-address to a vendor
"""
url = "http://macvendors.co/api/%s" % mac_address
request = urllib2.Request(url, headers={'User-Agent': "API Browser"})
try:
response = urllib2.urlopen(request)
... | ad854390256c87c537b1d8e4e8906b3b3d0b10bd | 3,652,549 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.