content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def getImage(matrix):
"""
Convert the 3d numpy array back into an image.
"""
return Image.fromarray(np.uint8(matrix)).convert('RGB') | d57a7f07d468d49d41bf40db7d066a78625e1671 | 3,614,000 |
def _get_additional_sign_content_plan(device_type):
"""
Get AdditionalSignContentPlan instance and set its related models
interfering device_types to universal one.
"""
universal_device_type = get_traffic_control_device_type(
code="123", target_model=None
)
obj = get_additional_sign_... | 3465dd44c11222034ca6f59be2081117f1a4e3b1 | 3,614,001 |
def get_org_link_by_short_link(session, short_link):
"""
Get origin link from short link
:param session: this param is session to connect to database
:param short_link: Short link
"""
origin_link = session.query(models.Url).filter(models.Url.short_link ==
... | 51fc6d0e49e5fe169b571d29207ad0e67a4b8f48 | 3,614,002 |
def _design(n, p, rho, equicorrelated):
"""
Create an equicorrelated or AR(1) design.
"""
if equicorrelated:
X = (np.sqrt(1 - rho) * np.random.standard_normal((n, p)) +
np.sqrt(rho) * np.random.standard_normal(n)[:, None])
def equi(rho, p):
if ('equi', p, rho) no... | 166dbfe8e4dc5c4fc18af5475dd5e5df151b5c08 | 3,614,003 |
def unidades_medida():
"""
Muestra las configuraciones para las unidades de medida
"""
grid = webgrid.WebGrid(crud)
grid.datasource = db(db.unidades_medida).select()
grid.pagesize = 20
#grid.fields = ['db.catmod.id', 'db.catmod.nombre', 'db.catmod.posicion']
#grid.filters = ['db.catmod.c... | 42a9a2c3be35228edba97473c204a689e562c4ac | 3,614,004 |
def unpack_shard(shard):
"""Unpack what pack_shard() did."""
replica = (shard & SHARD_REPLICA_MASK) >> SHARD_REPLICA_SHIFT
writer = (shard & SHARD_WRITER_MASK)
return (replica, writer) | bf07c091794f638c222cae98e7c16ff73edd3188 | 3,614,005 |
import ast
def set_if_chain(tree: ast.AST) -> ast.AST:
"""
Used to create ``if`` chains.
We have a problem, because we cannot tell which situation is happening:
.. code:: python
if some_value:
if other_value:
...
.. code:: python
if some_value:
... | 6508c1fb12f9c63a0995f3084751e31e50f46055 | 3,614,006 |
def poly(n, force_zero=None, **kwargs):
"""Returns a fit function that is a polynomial of degree n
y(x) = a0 + a1 * x + a2 * x^2 + ... + an * x^n
"""
if force_zero is None and len(kwargs) == 0:
# noinspection PyUnusedLocal
def pf(x, params, const_list, const_dict):
return... | 7712c0b07d6026ee9be130eae4881d1d1698ec91 | 3,614,007 |
def symptom_unreasonable_max_token_size():
"""`keystone.conf [DEFAULT] max_token_size` should be adjusted.
This option is intended to protect keystone from unreasonably sized tokens,
where "reasonable" is mostly dependent on the `keystone.conf [token]
provider` that you're using. If you're using one of... | ebbffa326de5d4f8073c12268d075d6dc4b4a58e | 3,614,008 |
def delete_channel(_, slug):
"""Unsubscribe from a channel"""
if models.YoutubeChannel.objects.filter(slug=slug).exists():
channel = models.YoutubeChannel.objects.get(slug=slug)
channel.delete()
return redirect("notifpy:home") | bd099f4ccd313d3337eb308aa9a4a513c4872597 | 3,614,009 |
import multiprocessing
def multisign_archive(archive, cred_dirs_to_output_paths, info_props=None):
""" Given an isign.archive object,
a mapping of credential directories to desired output paths,
optional info.plist properties to overwrite,
produce re-signed versions of the IPA.
I... | c6286b6836147309b25f06e03dfe0454500b6048 | 3,614,010 |
def MakePDBAtomRecord(pdbmol,i):
""" Make string for PDB 'ATOM' record.
:param lst pdbmol: pdbmol data
:param int i: i-th atom
:return: string(str) - PDB 'ATOM' record
"""
blk=' '; fi4='%4d'; fi3='%3d'; fi2='%2d'; fi5='%5d'; ff8='%8.3f'; ff6='%6.2f'
s=blk*80; ires=0
seqnmb=i+1
... | 43907029e99a1612d587bb9dabe764b86c5faf06 | 3,614,011 |
def sliding_window(sequence, window_size, step_size):
"""Converts a sequence into sliding windows. Returns a list of sequences.
- sequence: a string containing only nucleotides.
- window_size: Windows of equal size sequence. Default is 500 bp.
- step_size: overlap required for sliding windows. Default is... | 3af3e5a0fb204fe019971494a8f89272fd5026d3 | 3,614,012 |
import os
def get_wiki_folder(config, lecture_num, course):
"""
Return tuple of (lecture file location, markdown images path)
"""
tri = get_tri_from_course(course, config['courses'])
lecture_path = os.path.join(config['wiki-root'], "Uni", tri.capitalize(), course, "Lectures")
images_path = os.path.join(l... | 0b502c788ebd1db0d417e647ac8d8d990fa16743 | 3,614,013 |
def api_contests_join():
"""
Join/Leave a contest, GET all contests a user is in
"""
if request.method == 'GET':
user = get_queryparam('user')
returnJSON = models.select_joined_contest(
params=('*'),
conditions=('{}=\"{}\"'.format(
settings.DB_... | cd5e745aa5a092dd443e5db62430430ff4b11db1 | 3,614,014 |
import math
def feat_numc_window(cmap, winsize=3, score_threshold=0.2):
""" Get distribution over number of contacts in certain window,
where the window is a 2d field around each contacts.
The distribution is represented as an array of counts for each
number of contacts with in the window (i.e. lengt... | ca52d8df9133dd60efdc955477467c0332e88433 | 3,614,015 |
def expand_item(range_list, onepass=False):
""" Expand a list of plugin:parameters into a list of hosts """
if isinstance(range_list, str):
range_list = [range_list]
# Iterate through our list
newlist = []
found_plugin = False
for item in range_list:
# Is the item a plugin
... | 1df5d27208446b1184adcb12fa9d75459240e108 | 3,614,016 |
def load_csv(filename, sep=None, header=None):
"""Opens and parses provided csv file returning the data and info for all regions
as a list of Region objects. Since no experimental information is provided in the free-form text file,
The experimental properties are set to physically miningless defaults.
T... | 421f3b283caf8c4914dfbb85d75d2480b79da142 | 3,614,017 |
def print_devices(detail_level=0):
"""
Print all platforms and device available, optionall with detailed
device information.
Parameters
----------
details : int
If >0, the function also prints device properties. Higher
levels correspond to more (and less important) detail.
... | 02cbda028126de5f3a358958d96e77dbe6fe1b4e | 3,614,018 |
def create_2dlist():
"""
create 2d list used for gamefield
"""
return [[0 for _ in range(config.NR_COLS)] for _ in range(config.NR_ROWS)] | f5c04c76505594f1942b2477bb9c46aeab1dbe34 | 3,614,019 |
def Huge():
"""
Return the largest positive integer that can be stored (before a long integer
is needed)
"""
if not hasattr(Huge, "_huge"):
# If we haven't yet calculated Huge, calculate it
Huge._huge = 1
while True:
newHuge = Huge._huge * 2
if isinstance(newHuge, int):
Huge... | 5176692c7315063d9c4741709313617e6d05de10 | 3,614,020 |
import curses
def get_next_player_move(state, gui):
"""Uses input to get the next move by a human"""
def is_valid_move(state, x):
if x == '':
return False, '\n'
s = x.split(',')
if len(s) != state.ndim:
return False, 'Not the correct number of dimensions.\n'
... | 4cbcbceeb58d94f84445402505d0b945e9000e1a | 3,614,021 |
import asyncio
import aiohttp
import math
async def dyno_usage(dyno):
"""
Get your account Dyno Usage
"""
await dyno.edit("```Checking dynos โจ```")
await asyncio.sleep(1)
useragent = (
'Mozilla/5.0 (Linux; Android 10; SM-G975F) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
... | 68143df7d3b2c50b75196ad17a01a59276c4d85e | 3,614,022 |
import h5py
import os
def get_kssk(fh5, remove_bragg=False):
"""Retrieve determinant S(k) from HDF5 archive
Args:
fh5 (str): hdf5 archive
remove_bragg (bool, optional): remove Bragg peaks
Return:
(np.array, np.array, np.array): raxes, gvecs, sk0a
reciprocal lattice, integer vectors, twist-res... | 47c7e9c8b70afefb726521933f38c154754c39d5 | 3,614,023 |
def unravel_trimat( raveled, unravelIndices, shape=None ):
"""
Undo's a
Note: if shape = None, M,N are taken to be the maximum values in the matrix, so if there's zero columns
on the right, or zero rows on the bottom, they will be cropped in the returned triangular matrix.
"""
if shape ==... | ab43cb73557f9a69f3266ca730fe88fa66123912 | 3,614,024 |
def index_snps(snpeff_file):
"""indexes the snps"""
success, errors = helpers.bulk(es,_get_snps_document(snpeff_file), stats_only=True, chunk_size=10000)
return success, errors | b02e0812068eefec30c52a6795fad75282c31f1b | 3,614,025 |
def raster_path_shape(raster_path):
"""Return the number of rows and columns in a raster
Args:
raster_path (str): file path of the raster
Returns:
tuple of raster rows and columns
"""
raster_ds = gdal.Open(raster_path, 0)
raster_shape = raster_ds_shape(raster_ds)
raster_ds... | 4730bf5bdb8dc3b31dbba6c9d521334970eec845 | 3,614,026 |
def mongo_to_dict(obj, exclude_fields=list()):
"""
Convert Document of MongoEngine's instance to dictionary type
:param obj: Document of MongoEngine
:param exclude_fields: field names for exclude
"""
exclude_fields.append('_cls')
return_data = {}
if obj is None:
return None
... | e465e8ea7d7af142e88a4032a5ae4c0499bb9a04 | 3,614,027 |
def reconstruct_path(goal, branch, waypoint_fn):
"""
Reconstruct a path from the goal state and branch information
"""
current_node = goal
path = [current_node]
while current_node is not None:
previous_node = branch[waypoint_fn(current_node)]
path.append(previous_node)
cu... | cdc99ebaa5b987785e86a8b277c25638af1a3e71 | 3,614,028 |
def pt_acfg(**kwargs):
""" Architecture Config (PyTorch model origin) """
bn_cfg = kwargs.pop('bn_cfg', None) or get_bn_args_pt()
return {'pad_type': 'LIKE', 'bn_cfg': bn_cfg, **kwargs} | e50f25080ba19ec935850e8668e96836f08b957c | 3,614,029 |
import subprocess
import os
def nvidia_smi_current_gpu(): # pragma: no cover
"""Returns GPU ID used by the process.
(tested locally, cannot be tested on Travis CI bcs no GPU available)
Returns
-------
int
[MiB]
"""
# if theano.config.device=='cpu': ... | 8e7521655af03daa3402c7f434de7180ec20596e | 3,614,030 |
def prw(value):
"""Writer share, PR"""
return calculate_value(value, PRW_SHARE) | 028b8af0c5a3cd4af61056bc19d60efd92040f00 | 3,614,031 |
def get_vehicle_marker(object, header, marker_id=0, is_player=False):
"""
Return a marker msg
:param object: carla agent object (pb2 object (vehicle, pedestrian or traffic light))
:param header: ros header (stamp/frame_id)
:param marker_id: a marker id (int32)
:param is_player: True if player e... | 9069609296d70b468754a44d37828de34308604e | 3,614,032 |
def default_ssl_cacerts():
"""Path to default Certificate Authority certificates"""
return SSL_CACERTS.get() | ecc2662c9bbd2fe58995ae652f266580af902cf8 | 3,614,033 |
def vectornormalization(surface, inputarray, outputarray, iscelldata=False):
"""Add data array with the normalization of a vector field."""
calc = vtk.vtkArrayCalculator()
calc.SetInput(surface)
if iscelldata:
calc.SetAttributeModeToUseCellData()
calc.AddVectorArrayName(inputarray, 0, 1, 2)
... | 048b2c0ae94d65e3b5a7c6a1d665a9e6b1e3de27 | 3,614,034 |
def format_df(df, mhe):
"""Make a weak labels dataframe from strongly labeled (join labels)
Args:
df: pd.DataFrame, the dataframe strongly labeled with onset and offset columns (+ event_label)
mhe: ManyHotEncoder object, the many hot encoder object that can encode the weak labels
Returns:
... | 513f1055aef6dfb0d1382ca4a5f5c990f5567b49 | 3,614,035 |
import operator
def create_judgment_matrix(N,T,layers,v_r=[],actions=[],judgment_type="OPTIMISTIC"):
"""Creates a functionality map for input into the functionality parameter in the indp function.
:param N: An InfrastructureNetwork instance (created in infrastructure.py)
:param T: Number of timesteps to o... | cead11f406918ed290e845b4cd33a955783069f1 | 3,614,036 |
def vertically_partition_data(X, X_test, A_idx, B_idx):
"""
Vertically partition feature for party A
and B
:param X: train feature
:param X_test: test feature
:param A_idx: feature index of party A
:param B_idx: feature index of party B
:return: train data for A, B; test data for A, B
... | 58a9c3869ca9189af7c3e387cdab988cb283e07f | 3,614,037 |
from typing import Type
from typing import Any
def type_instantiate(attr_type: Type, **kwargs) -> Any:
"""
Instantiate a nominated type.
"""
while hasattr(attr_type, "__origin__"):
attr_type = attr_type.__origin__
return attr_type(**kwargs) | a42893824f52ae2bff583014f3e824634e6417e2 | 3,614,038 |
import scipy
def eval_tau(J, r, chieff, q, chi1, chi2, precomputedroots=None):
"""
Period of S as it oscillates from S- to S+ and back to S-.
Call
----
tau = eval_tau(J,r,chieff,q,chi1,chi2,precomputedroots=None)
Parameters
----------
J: float
Magnitude of the total angular m... | 04eea453e8c124c405a9e801bfba88fc691fba16 | 3,614,039 |
def make_change_dep_eval(dep,):
"""Produce an evaluation function that returns True if any change has happened on any occurence of the given dep"""
def change_dep_eval(orig,modif):
s1 = get_pairs(orig, dep)
s2 = get_pairs(modif, dep)
return s1 != s2, bool(s1)
return change_dep_eval | 0f3799832c24ce1d9021727f2917d5bb3e5ed1a9 | 3,614,040 |
from typing import Optional
def get_verse_id(book: Book, chapter: int, verse: int) -> int:
"""
Given the Book enum, chapter number int, and verse number int return the verse id if it exists.
:param book:
:param chapter:
:param verse:
:return: the integer verse id for the given book, chapter, ... | f736a39a640c97473d110be214da534e0fc06010 | 3,614,041 |
def get_fitness(cell_type,cell_neighbour_types,DELTA,game,game_params):
"""returns fitness of single cell"""
return 1+DELTA*game(cell_type,cell_neighbour_types,*game_params) | bfac50ecbe64911c145a9e6cbc9e872add774cbf | 3,614,042 |
def patch_resource(url, body):
"""
Patch resource with the given json body
:returns: http response data
"""
timer = Timer()
response = Bridge_DAO().patchURL(url, PHEADER, body)
log_data = "PATCH %s %s ==status==> %s" % (url, body, response.status)
if not response.status == 200:
... | 0dc2d2f47fc453d2902bed28158bc27be0f40101 | 3,614,043 |
def fetch_core_sketch(X, ss, **kwargs_rg):
"""
:param X: the tensor of dimension N
:param ks: array of size N
:param tensor_proj: True: use tensor random projection,
otherwise, use normal one
:return: [core_sketch:s_n\times s_n ...\times s_n,
list of sketches phis, s_n\times I_n]
"""
... | e197a823757634a5587d2aac21ad73a2be8266bb | 3,614,044 |
def test_simplify():
"""Test simplification of expr according to manual rules"""
h1 = LocalSpace("h1")
a = OperatorSymbol("a", hs=h1)
b = OperatorSymbol("b", hs=h1)
c = OperatorSymbol("c", hs=h1)
d = OperatorSymbol("d", hs=h1)
expr = 2 * (a * b * c - b * c * a)
A_ = wc('A', head=Operat... | 30e128cda58a4173fccc5f6507e6fd9926703373 | 3,614,045 |
import torch
def linear_quantize_callback(
inp: torch.Tensor,
bits: int = 8,
decimal: TensorOrInt = 5,
channel_index: int = 1,
) -> torch.Tensor:
"""quantization function with type signature of [QuantizeCallback][qsparse.common.QuantizeCallback].
Args:
inp (torch.Tensor): input tensor... | 7e40b94c665135b3a95612992280a0902144ec99 | 3,614,046 |
from bs4 import BeautifulSoup
import re
from datetime import datetime
def parse_post(content):
"""
parse response content
:param content: string
:return: Dict
"""
# parse content
soup = BeautifulSoup(content, 'lxml')
# get title
mainTitle = soup.find('div', {'id': 'mainTitle'}) ... | 352407882081cee1dbfd55a41d3beebe3ccb2bfa | 3,614,047 |
from typing import Optional
def get_ocean_token_address(
address_file: str, network: Optional[str] = None, web3: Optional[Web3] = None
) -> str:
"""Returns the Ocean token address for given network or web3 instance
Requires either network name or web3 instance.
"""
addresses = get_contracts_addres... | bf97f5de1e7258a9f8eef9f3c7277bd860f16928 | 3,614,048 |
def _get_relevant_items_by_timestamp(
dataframe,
col_user=DEFAULT_USER_COL,
col_item=DEFAULT_ITEM_COL,
col_rating=DEFAULT_RATING_COL,
col_timestamp=DEFAULT_TIMESTAMP_COL,
col_prediction=PREDICTION_COL,
k=DEFAULT_K
):
"""Get relevant items for each customer def... | 1ee48e1152d53bcf39017a1d667c2492af96599e | 3,614,049 |
def check_encryption(value):
"""
check for the --???-encryption argument
raise an exception if the given encryption is invalid
"""
value = value.lower()
if value not in ['ssl', 'tls', 'starttls', 'none']:
raise ArgumentTypeError(f'{value} is an unknown encryption. Use can use ssl... | bfb6c18de43c7cd8db6529717950231c327b808d | 3,614,050 |
from typing import Union
from typing import Dict
from typing import Any
import typing
def FloatSlider(
continuous_update: bool = True,
description: str = "",
description_tooltip: str = None,
disabled: bool = False,
layout: Union[Dict[str, Any], Element[ipywidgets.widgets.widget_layout.Layout]] = {... | 6533130c79d4a3e108f454c94dd1e203272ce3d3 | 3,614,051 |
def _apply_feature_constraints(feature, min_value, max_value):
"""Constrains `feature` to be between `min_value` and `max_value`."""
if min_value is not None:
feature = tf.math.maximum(feature, min_value)
if max_value is not None:
feature = tf.math.minimum(feature, max_value)
return feature | 85352d537cddf8409b02fdaa97b385dcc8a928c2 | 3,614,052 |
def configure_global_stackwise_virtual(device, domain=None):
""" Enables global stackwise-virtual on target device
Args:
device ('obj'): Device object
domain ('str'): Stackwise-virtual domain
Returns:
None
Raises:
SubCommandFailure
"""
... | 6f37c07ec94a488b29df909cf5fc826741a43b74 | 3,614,053 |
import sys
def get_print_func(io):
"""This is a workaround go get mocking of stdout to work with
both py2 and py3.
"""
if sys.version_info[0] == 2:
return io.write
else:
return io.writelines | 0f9ba032cd701d9bdbac8218b152a6109e0586b7 | 3,614,054 |
import six
import hashlib
def run_server(locker, register=True):
"""Runs tickets server."""
_LOGGER.info('Tickets server starting.')
# no __init__ method.
#
# pylint: disable=W0232
class TicketLockerServer(gssapiprotocol.GSSAPILineServer):
"""Ticket locker server."""
@utils.e... | ed9ee1f0f8c0be63e9476f16c5fb4ecd26d15871 | 3,614,055 |
def verify_incall_state(log, ads, expected_status):
"""Verify phones in incall state or not.
Verify if all phones in the array <ads> are in <expected_status>.
Args:
log: Log object.
ads: Array of Android Device Object. All droid in this array will be tested.
expected_status: If Tru... | a20f88770e92a6f61ac5376e3a7827cf3c82c1f2 | 3,614,056 |
def buildData(all_data, outPickleFile, build_dict=False, word_only=False):
"""
i
"""
n = 0
# now only handle the eds data, to extend for all other formats
eds_data = []
for id, data in all_data.items():
# try to extend this to other frameworks
if 'mrp_eds' in data:
... | 03620984e45a3875495ef23048693edeae739c73 | 3,614,057 |
from typing import Tuple
import math
def euclidean_distance(
point: Tuple[float, float], origin: Tuple[float, float] = None
) -> float:
"""Calculate euclidean distance from the origin"""
if origin is None:
return math.sqrt(sum((p ** 2 for p in point)))
else:
assert len(origin) == len(p... | b248122c6700d90182d68a35a43c7ad47b968667 | 3,614,058 |
def perspective_edit(request, perspective_id, response_format='html'):
"""Perspective edit"""
perspective = get_object_or_404(Perspective, pk=perspective_id)
# Don't let users delete their last perspective
other_perspectives = Perspective.objects.filter(
trash=False).exclude(id=perspective_id)
... | 353dcb3f963cc3aa82e69b42d83fb0f6d901927d | 3,614,059 |
def _extract_key(obj):
"""Convert a handle or Event handle into a Database Event ID."""
if isinstance(obj, Event):
return obj.id
elif isinstance(obj, str):
return obj
raise TypeError('Must provide an Event or Event handle (string)') | 1b4a3fb64d77ddc196238739f483246a7bf67cb1 | 3,614,060 |
def convolve_adjoint_filter(x, y, ndim, input_multi_channel=False,
output_multi_channel=False, mode='full'):
"""Convolution adjoint.
Args:
x (array): input array with shape batch_shape + input_shape
if input_multi_channel=False.
Otherwise with shape ... | ec8e26c0a199600fec21ce0a400f9685054e0032 | 3,614,061 |
def getCompletedJobs(jobs):
"""
Gets all completed jobs
"""
completed_jobs = []
for job in jobs:
if 'result' in job:
completed_jobs.append(job)
return completed_jobs | 7193cae304fb0498f9fe50f0302e50699d7e96e3 | 3,614,062 |
def read_pergene_file(pergene_insertions_file,chrom):
"""Reading the pergene file , the information per gene , related to where it starts and ends in the genome.
Parameters
----------
pergene_insertions_file : str
absolute path of the per gene file location
chrom : str
Name of the ... | e9629c5a9621784be6eb6efbd1e8793f2ac5b67e | 3,614,063 |
import math
def gam_a98rgb(rgb):
"""Convert an array of linear-light a98-rgb in the range 0.0-1.0 to gamma corrected form."""
return [math.copysign(math.pow(abs(val), 256 / 563), val) for val in rgb] | 6d2543dc28ac6533067ffe9b0a265ef093416f9e | 3,614,064 |
import socket
def conflictBetweenIPv4AndIPv6():
"""
Is there a conflict between binding an IPv6 and an IPv4 port? Return True
if there is, False if there isn't.
This is a temporary workaround until maybe Twisted starts setting
C{IPPROTO_IPV6 / IPV6_V6ONLY} on IPv6 sockets.
@return: C{True} ... | bef744d6f066e3aafbe7644662d8d87e4b139abb | 3,614,065 |
import copy
def unlock_layer(wC, uC, noise=0.0):
"""
unlock a layer of a scale invariant MERA
Args:
wC, uC (list): MERA tensors
noise (float): amplitude of noise to be added to the new layer
Returns:
wC, uC (list): new MERA tensors
"""
wC.append(copy.copy(wC[-1]))... | 9bad36a4d31e8411a14fa13d520f13e2d71167b9 | 3,614,066 |
def conformal2geodetic(conformal_lat: "ndarray", ell: Ellipsoid = None, deg: bool = True) -> "ndarray":
"""
converts from conformal latitude to geodetic latitude
like Matlab map.geodesy.ConformalLatitudeConverter.inverse()
Parameters
----------
conformal_lat : "ndarray"
conformal latit... | 5a26f3b1cd8b0b43739db2f936a6b42c79bf6e19 | 3,614,067 |
def get_frame_subframe(sfn_sf):
""" Get the frame and the subframe number from the
received bitstring
"""
sfn_sf_list = []
frame_mask = ~((1<<4) - 1)
frame = (sfn_sf & frame_mask) >> 4
sf_mask = ~(((1<<12) - 1) << 4)
subframe = (sfn_sf & sf_mask)
sfn_sf_list.append(frame)
sf... | d623ef8c1fa97dfbd5b5ef2a99e52e045d5dd205 | 3,614,068 |
def make_renderer(nodes, use_binary_transport=False):
"""Creates the pydeck visualization for rendering"""
view_state = pydeck.ViewState(
offset=[0, 0],
latitude=None,
longitude=None,
bearing=None,
pitch=None,
zoom=10,
)
views = [pydeck.View(type="OrbitVi... | dc6438f4e48d5fc6fcd4eaca46603e1b0d022874 | 3,614,069 |
def get_secret_value(secret_name):
"""
get secret value from AWS Secrets Manager
:param secret_name: name of the secret passed
:return secret_value: value of the secret passed
"""
client = session.client(service_name='secretsmanager')
secret_value = ''
try:
get_secret_value_respo... | 70af6ce869ad816de15e99259868cc020071c217 | 3,614,070 |
import torch
def true_positive_fraction(output, target):
"""True positive fraction of binary segmentation."""
output, target, was_numpy = _convert_to_torch(output, target)
result = _true_positives(output, target) / (torch.sum(output) + torch.sum(target))
return _convert_to_scalar(result, was_numpy) | 5c6a7f7df36213da5383c8105910e59fee539e97 | 3,614,071 |
def backend_parameter(func):
"""Decorator for parameters reading data from the backend.
Errors are handled in a default way.
"""
def _func_wrapper(self: 'VehicleState', *args, **kwargs):
# pylint: disable=protected-access
if self._attributes is None:
raise ValueError('No dat... | c12baada4759e475eb554eafffc0aff620f049ac | 3,614,072 |
import re
def _build_freetext_query(querystring):
"""
Parses the freetext argument 'nyckelord' in the following ways:
'word1 AND word2' => word1 and word2
'"word1"AND"word2"' => word1 and word2
'"word1 word2"' => word1 and word2
'word1 OR word2' => word1 or word2
'"word1"OR"word2"' => word... | 53a717351c85323bf02df47ce87daab8b9497ae4 | 3,614,073 |
def get_course_list(only_active=True, sortedby="name"):
""" Return a list of courses.
By default only active courses.
will be ordered by given field.
[{id:, name:, title:}, ]
"""
clist = []
reload_if_needed()
for course in COURSES:
if only_active:
if COURS... | ef0b4ef4606e9d3cb157efb34decb144caf8e8a7 | 3,614,074 |
def covars_for_custom_models_simple_training_data_4elements():
"""
defines initial covars compatible with custom_models_simple_training_data_4elements above
:return: covars (list of tuple)
"""
covars = [(0.0, -2.0, 2.0)]
return covars | f21cfa472c03811758dfb5196594f93f6e8247c6 | 3,614,075 |
import six
def create(ctxt, name, source_instance_id, description=None):
"""Creates migration.
Raises:
MigrationCreateFailed: If there is error during migration creation.
InstanceNotReadyForMigration: Migrating instance failed
pre-migration validations
... | 25402f56013cc5da7d3483200f0ab94532332624 | 3,614,076 |
def get_asgi_application():
"""
The public interface to Django's ASGI support. Return an ASGI 3 callable.
Avoids making django.core.handlers.ASGIHandler a public API, in case the
internal implementation changes or moves in the future.
"""
django.setup(set_prefix=False)
return ASGIHandler() | 5e3c760f58005ea84a623305661294f5e9724504 | 3,614,077 |
from typing import List
from typing import Dict
from typing import Union
def generate_html(d: List[Dict[str, Union[str, bool]]]) -> str:
"""
Pass in a dict with a list of rows to include in a formatted table. This will return the HTML for the table.
:param d:
:return:
html: HTML formatted tab... | f874c63735443bb3b68355905e59f5efbc5b50af | 3,614,078 |
from typing import List
from typing import Union
def flip_random_flippable(reconstructed_edges: List[Edge],
initial_weight: int) -> Union[int, None]:
"""
Flips a random flippable edge in the provided solution.
Args:
initial_weight: - Initial solution weight.
reco... | 0f7b4ebc5f99487e171d422554871b3d20833f33 | 3,614,079 |
import typing
def _de_bruijn(k: int, n: int) -> typing.List[int]:
"""Generate a De Bruijn sequence.
This is a piece of mathematical heavy machinery needed for O(1) ctz on
integers of bounded size. The algorithm is adapted from chapter 7 of
Frank Ruskey's "Combinatorial Generation".
Args:
... | bbb86a4f0a7ef03bbce29126cc56e4fb3e41e288 | 3,614,080 |
from typing import List
def run_pt_stream(data_map: dict, features: List[str], session: str, feature_column_names: List[str], time_column_name: str, speed: float=1.0, smoothing_factor: float=0.1, title: str=''):
"""Displays an animation of features synchronized across time. Helpful for comparing feature changes over... | 719ef8c8ddf2fdb0ff2783e2debfed648e4ba8cb | 3,614,081 |
def preprocess_data(x):
"""Preprocess data. Ensure x is 2d ndarray, and scale so that the mean absolute
amplitude of each column is one.
:param x: ndarray, shape (n_samples,) or (n_samples, n_features)
:returns: float ndarray, shape (n_samples, n_features)
"""
x = np.array(x, dtype=np.float64)... | 1d696d754db5849c7b092b3a70913ebf164b4df2 | 3,614,082 |
def left_edge_vertical_ids(shape):
"""Link IDs of left edge vertical links.
Parameters
----------
shape : tuple of int
Shape of grid, given as (rows, columns) of nodes.
Returns
-------
ndarray :
Link IDs of left edge vertical links. Length is
(rmg.number_of_rows - 1... | 9ff1e8caa66b27deae5b2086de5b40a03917a8ad | 3,614,083 |
def guess_dim_transition_linebyline(filename):
"""get number of histogram bins from transition matrix file (one line per entry!!!)"""
#print "Reading...", filename
with open(filename,"r") as f:
count = 0
for line in f: # skip lines starting with #
if not line.startswith("#"):
... | f0cb5bb788195c0b2369d588e2e9d8e9caa3c5f1 | 3,614,084 |
from typing import List
from typing import Dict
def deduplicate(new_data: List[Dict]) -> List[Dict]:
""" Checks for duplicates and omits them """
old_data = load_data()
data = []
for new in new_data:
if all(new['tweet_id'] != old[2] for old in old_data):
data.append(new)
return... | b648ea4cfc9a8d14e6eff822e56680fdcb1e17eb | 3,614,085 |
def identify_necessary_covariates(dependents, definitions):
"""Identify covariates necessary to compute `dependents`.
This function can be used if only a specific subset of covariates is necessary and
not all covariates.
See also
--------
respy.likelihood._compute_x_beta_for_type_probability
... | 08f6db315a1c1281ef2ffae4efc1ccda78f3e95e | 3,614,086 |
def delete_event(current_user, event_id):
"""
Deleting a User Event from the database if it exists.
:param current_user:
:param event_id:
:return:
"""
try:
int(event_id)
except ValueError:
return response('failed', 'Please provide a valid Event Id', 400)
user_event = ... | eb4977198c87294eb0980932dfd17e572d950bbf | 3,614,087 |
import os
def _file_name_to_target_times(downsized_3d_file_name):
"""Parses file name for target times.
:param downsized_3d_file_name: See doc for `find_downsized_3d_example_file`.
:return: first_target_time_unix_sec: First target time in file.
:return: last_target_time_unix_sec: Last target time in ... | e5eacd0c9cfdfbd323cf47064a6d5d9124c78970 | 3,614,088 |
def make_meeting():
""" Generate a new dummy meeting and save it. """
meeting = frappe.get_doc({
"doctype": "Meeting",
"title": "Test Meeitng",
"status": "Planned",
"date": "2017-07-20",
"from_time": "09:00",
"to_time": "09:30",
"minutes": [
{
"description": "Test minute 1",
"status": "Open",... | 047c3ed250e5cda64bea859ddcfd0a3c3a7a8b3c | 3,614,089 |
import os
from shutil import copyfile
def get_configuration_file():
"""ensure yml file exist at $HOME and providing file path and name."""
if not os.path.isfile(HOME_CONFIGURATION):
copyfile(DEFAULT_CONFIGURATION, HOME_CONFIGURATION)
return HOME_CONFIGURATION | 2cac26ad96c6301e2e333a89847996f45090ace2 | 3,614,090 |
def test_authorize_scalar_attribute_eq(post_fixtures):
"""Test authorization rules on a relationship with one object equaling another."""
# Object equals another object
Oso.load_str(
"""
allow(actor: test_app2::User, "read", _: test_app2::Post{created_by: actor, access_level: "private"});
... | 0b3727b4bcc4e3f61d53f3b06228f1e05f7287d1 | 3,614,091 |
def load_template(template_file_path):
"""
Load a Jinja2 template and return it
Args:
template_file_path (str): path to the Jinja2 template file
Returns:
Template: contains jinja2 template
"""
return Template(open(template_file_path).read()) | 7841065523262a2c049d783df1c06b27c65b3cf6 | 3,614,092 |
def template_used(response, template_name):
"""Asserts a given template was used (with caveats)
First off, this is a gross simplification of what the Django
assertTemplateUsed() TestCase method does. This does not work as a
context manager and it doesn't handle a lot of the pseudo-response
cases.
... | f8a878d27c5379b0b2f2fac2a08fbeee91607858 | 3,614,093 |
def _sign_trace(s11, s22, s33):
"""Calculate sign of trace. Sign of 0 is set to 1.
Parameters
----------
s11: array_like
Component 11 of 3D tensor.
s22: array_like
Component 22 of 3D tensor.
s33: array_like
Component 33 of 3D tensor.
Returns
-------
numpy.nd... | d0557995bd5662e84939536b2e220acf6e0ce460 | 3,614,094 |
def read2dlv(filename):
"""Read LabView 2D array and return as numpy array.
Big-endian version.
"""
if isinstance(filename, str):
f = open(filename, 'rb')
else:
f = filename
dims = np.fromstring(f.read(8), dtype=np.dtype('>u4'))
ccd_temp = np.fromstring(f.read(), dtype=np.dt... | 911a62eac2b43fca607f95aefdd845d7c67877bb | 3,614,095 |
import click
def ensure_remote(ctx, param, value):
""" Ensure --remote is used. """
# pylint: disable=unused-argument
if value and ctx.params.get('remote') == (None, None):
raise click.BadParameter('Invalid without "-r" / "--remote" option')
return value | d22f8d73e4b5ec57cc18607918775778d09efc67 | 3,614,096 |
def edit_draft_service(draft_id):
"""
Edit a draft service
:param draft_id:
:return:
"""
updater_json = validate_and_return_updater_request()
update_json = validate_and_return_draft_request()
page_questions = get_request_page_questions()
draft = DraftService.query.filter(
D... | db734fb9bf2b3cdaa9f89162e08875215cd4dfad | 3,614,097 |
def is_lisp_like(view):
""" Check for a lisp like file using the current language/syntax setting """
return get_dialect(view) != '' | c6b6f4df062173421b8300bf9e82e1240213f692 | 3,614,098 |
from typing import Callable
import types
import json
def _execute(cls, app_engine: AppKernelEngine, provisioner_method: Callable, model_class: Model):
"""
The main view function for flask routes.
:param app_engine: the app engine instance
:param provisioner_method: the method on our service object whi... | 8b2ffd71bc512afad0657ea5695b7a281cde5f86 | 3,614,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.