content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def max_pool(x: Tensor, kernel_size: tuple, stride: tuple=None, padding: tuple=(0, 0)):
"""
Performs max pooling.
## Parameters
x: `Tensor` - input tensor
kernel_size: `tuple` - shape of the kernel
stride: `tuple` - stride, if not set default shape is same as kernel_size
padding: `tuple`... | ed87b5902341f7ec9caff1b7e94e125fd899ff63 | 3,602,913 |
def create(holmes, user=None):
"""# Create BoletoHolmes
Send a list of BoletoHolmes objects for creation in the Stark Bank API
## Parameters (required):
- holmes [list of BoletoHolmes objects]: list of BoletoHolmes objects to be created in the API
## Parameters (optional):
- user [Organization/P... | abc5c51f6ab05195340f5bbbcb4d88270043e1e6 | 3,602,914 |
import re
def generate_history_diff(collection, identifier=None):
"""
Returns a list of revisions for a record, showing fields that changed in each revision.
collection: a list of Version objects (django-reversion)
identifier: optional description of the object being edited (e.g. 'Geoexchange Driller... | 8915c76c6b7eee7c027dc83ba0e37ad3083c414e | 3,602,916 |
def modules():
"""Entry point for getting the pyxll modules.
Returns a list of module names."""
return [
__name__
] | 2f53cd00387c7533404b8e97a8da34fb3c5811e9 | 3,602,918 |
def render_new_card(self, h, comp, *args):
"""Render card creator minified"""
h << h.a(h.strong('+'), h.span(_('Add a card')),
class_='link-small').action(comp.becomes, model='add')
if self.needs_refresh:
h << h.script('increase_version();')
self.toggle_refresh()
return h.ro... | 5ba03707e47e51a79c8fd51489d4224e35437a05 | 3,602,919 |
def gamma_corr(clip, gamma):
""" Gamma-correction of a video clip """
def fl(im):
corrected = 255 * (1.0 * im / 255) ** gamma
return corrected.astype("uint8")
return clip.fl_image(fl) | d98d411c63d932b068d80bef63d42289cb0d8468 | 3,602,920 |
def _segment_labels(Yi):
"""Segmenting the labels for segmental edit score
"""
idxs = [0] + (np.nonzero(np.diff(Yi))[0]+1).tolist() + [len(Yi)]
Yi_split = np.array([Yi[idxs[i]] for i in range(len(idxs)-1)])
return Yi_split | 902f187be828f649f99a53cfa72ccf79016f9630 | 3,602,921 |
def connected_components(graph):
"""
Given an undirected graph (a 2d array of indices), return a set of
connected components, each connected component being an (arbitrarily
ordered) array of indices which are connected either directly or indirectly.
"""
def add_neighbors(el, seen=[]):
''... | e8299cc024dd27414a287ee0afa302ea64c18b68 | 3,602,922 |
def remove_reference_syntax(definition):
"""
Definitions in English may contain references to Chinese words. The reference syntax contains
vertical bar-separated Han characters as well as a pronunciation enclosed in brackets,
as in "Jiajiang county in Leshan 樂山|乐山[Le4 shan1]".
Remove the reference ... | 91f973a17558881cdaa2da96239cd8c87e103807 | 3,602,923 |
from datetime import datetime
def library():
"""
Create a 4-column, 6-row dataset with numbers and text.
"""
ds = xport.Dataset(
data={
'VIT_STAT': ['ALIVE'] * 3 + ['DEAD'] * 3,
'ECON': ['POOR', 'NOT', 'UNK'] * 2,
'COUNT': [1216, 1761, 2517, 254, 60, 137],
... | 46ca6c05a83c0c8cf03063c1a19f155698f1f589 | 3,602,924 |
def get_segment_point_intersect(seg, pt):
"""Returns the intersection of a segment and point.
Parameters
----------
seg : libpysal.cg.LineSegment
A segment to check for an intersection.
pt : libpysal.cg.Point
A point to check ``seg`` for an intersection.
Returns
-------
... | 9f5c030ab7b995416c3918b853206eb64ebb11c4 | 3,602,925 |
import torch
def log_like_internal(pt_sum_compressed, data, x_m_ary, x_m_sum):
""" Non-Poissonian likelihood for single template, given x_m and x_m_sum
"""
k_max = torch.max(data) + 1
npixROI = int(pt_sum_compressed.size(0))
f0_ary = -(pt_sum_compressed + x_m_sum)
f1_ary = pt_sum_compressed ... | 939fbc1ed070ee0183150cfc01d92d77b1a09fc7 | 3,602,926 |
def generateCards(numberOfSymb):
"""
Source: https://fr.wikipedia.org/wiki/Dobble
"""
nbSymByCard = numberOfSymb
nbCards = (nbSymByCard ** 2) - nbSymByCard + 1
cards = []
n = nbSymByCard - 1
t = []
t.append([[(i + 1) + (j * n) for i in range(n)] for j in range(n)])
for ti in range(n... | 5cf56864675668213f593395978fa511d0ed3784 | 3,602,927 |
def keep_exit_with_descr(descr, router, guard):
"""Checks that the router is not a bad exit, is not down, is stable,
is valid, does not run an old TOR's version, has an available ed25519
identity key and has an 'accept' exit policy
:param descr: descriptor of the exit candidate.
:params router: the ... | 4766bb038499d6bd45e71bd98122514936bd8da0 | 3,602,928 |
def _GetAndroidGnOutputLocale(line):
"""Check a GN list, and return its Android locale if it is an output .xml"""
m = _RE_GN_VALUES_LIST_LINE.match(line)
if not m:
return None
if m.group(1): # First group is optional and contains group 2.
return m.group(2)
return resource_utils.ToAndroidLocaleName(... | 2d784b2c8bb9e548b61d3d7a106c572f1bbe80fe | 3,602,929 |
def get_final_sorted_cavs(dict_all_info, filtered_cavities):
"""
Uses dict_all_info to rank cavities for further exploitation (FP, export as PDB...)
and exclude few more cavities
"""
# scores will contain the scores of filtered cavities
scores = []
# ori_order will contain the original indices of the cavities
... | 01513b4e5c55c7f9ec1e48274103044d92ed2fd5 | 3,602,931 |
def create_model_four_conv(input_shape):
"""
CNN Keras model with 4 convolutions.
:param input_shape: input shape, generally X_train.shape[1:]
:return: Keras model, RMS prop optimizer
"""
model = Sequential()
model.add(Conv2D(32, (3, 3), padding="same", input_shape=input_shape))
model.ad... | 81bcca89d130f6b5e42493b8a73ea0332e951bc9 | 3,602,933 |
def svn_repos_fs_revision_proplist(*args):
"""
svn_repos_fs_revision_proplist(svn_repos_t repos, svn_revnum_t rev, svn_repos_authz_func_t authz_read_func,
apr_pool_t pool) -> svn_error_t
"""
return _repos.svn_repos_fs_revision_proplist(*args) | 7eb893741c4bf83f8caee0974e9e663d6d07644e | 3,602,934 |
import math
import torch
def loglinspace(a, b, n=100, **kwargs):
"""Like :meth:`torch.linspace`, but spread the values out in log space,
instead of linear space. Different from :meth:`torch.logspace`"""
return math.e**torch.linspace(math.log(a), math.log(b), n, **kwargs) | ea456462a0d029f1ada1c4a9e40c9377b86e815d | 3,602,936 |
import types
from typing import Optional
def get_data_view_uri(examples: types.Artifact) -> Optional[str]:
"""Returns the URI to the DataView attached to an Examples artifact.
Or None, if not attached.
Args:
examples: an Examples artifact.
Returns:
The URI to the DataView or None.
"""
assert exa... | c2e0303f42268c5b5e2da8ff4e334e6f7d1663d7 | 3,602,938 |
def infer_spaces(s):
"""Uses dynamic programming to infer the location of spaces in a string
without spaces."""
## Find the best match for the i first characters, assuming cost has
## been built for the i-1 first characters.
## Returns a pair (match_cost, match_length).
words = open("./../data/w... | fca5fb8311d29d3256e03e3462277cf8baac9337 | 3,602,939 |
def get_largest_sample_size(path_to_audio_files):
"""Recursively searches folder and find the largest sample size"""
largest_sample_size = 0
for wav_file in recursively_find_files(path_to_audio_files, '*.wav'):
loader = essentia.standard.MonoLoader(filename=wav_file)
audio = loader()
... | fb3e708541d9bf4b05e7e33e513f3555f38f4d72 | 3,602,940 |
def test_change_logs_on_call(mocker):
"""
Tests if the decorator works on every call
"""
mock = mocker.Mock()
@change(new=mock.new, on_call=mock.log)
def old_sum(a, b):
"""
Sample wrong sum
"""
return a + b + 1
result = old_sum(1, 2)
mock.log.assert_cal... | 354778055df87863d2a5977f9e7cd9ec298284c5 | 3,602,941 |
def fetch_restaurants(data_home=None):
"""Returns a stream containing the data from the Kaggle Recruit Restaurants challenge.
The data is ordered by data and then by store ID.
Parameters:
data_home (str): The directory where you wish to store the data.
Yields:
tuple: A pair (``x``, ``... | 6c8c9b9556128932cfaa5920277ee322c77898d5 | 3,602,942 |
import requests
from bs4 import BeautifulSoup
def get_author_work(url):
""" Get the complete list of work by an author.
Params
------
url(str): The Ideas url of the author.
Returns
-------
pd.DataFrame
"""
url = f'https://ideas.repec.org{url}'
resp = requests.get(url... | 0b6ed0b371c53d84cf7e9ae848038ecdfd173246 | 3,602,943 |
from typing import Optional
from typing import Dict
from typing import Set
import six
def compute_subclass_sets(
schema: GraphQLSchema, type_equivalence_hints: Optional[TypeEquivalenceHintsType] = None
) -> Dict[str, Set[str]]:
"""Return a dict mapping class names to the set of its subclass names.
A clas... | ce3d169fcb97e627916ff073ad317d2f40f1d0bb | 3,602,944 |
def optional_function(func):
"""Only apply function if input value is not None.
Function must be unary.
"""
def wrapper(x, *args, **kwargs):
if x is None:
return None
return func(x, *args, **kwargs)
return wrapper | 3db42719579fc6160b282af4e637f72f9df4781e | 3,602,945 |
def battery_converter(result):
"""
Converts a voltage reading result with battery charge state and level.
"""
voltage = result.get("value", None)
ret = {
"_type": "bat",
"level": battery_util.charge_percentage_for(voltage, nominal_voltage=context["battery"]["nominal_voltage"]),
... | 44efe538ee1a511f9b63fd6e83c46e5f106f3c14 | 3,602,948 |
def put_kernels_on_grid (kernel, pad = 1):
"""Visualize conv. features as an image (mostly for the 1st layer).
Place kernel into a grid, with some paddings between adjacent filters.
Args:
kernel: tensor of shape [Y, X, NumChannels, NumKernels]
(grid_Y, grid_X): shape of the grid. Re... | d7db3ed046e31be45e97c7dfe17c0df149d47ed8 | 3,602,949 |
def _is_sub_scope(scope, parent_scope):
"""
Returns True if the given scope is a subset of the permissions
defined in the parent scope.
"""
return not any (
frozenset(permissions_grant).difference(chain.from_iterable(
parent_permissions_grant
for parent_model_grant, p... | a470cd80337826ca18372c65beaf87860dbaf855 | 3,602,950 |
from typing import Union
from pathlib import Path
from typing import Any
import yaml
def read_yaml(fname: Union[str, Path]) -> Any:
"""Read the given file using YAML.
Parameters
----------
fname : str
the file name.
Returns
-------
content : Any
the object returned by YAM... | d0ee4cea6ef04da699d41f03144f36bff4a61914 | 3,602,951 |
def butter_bandpass_filter(rate, data, freqLowCutoff, freqHighCutoff, order=5):
"""Butterworth band pass filter"""
nyq = 0.5 * rate
low = freqLowCutoff / nyq
high = freqHighCutoff / nyq
b, a = butter(order, [low, high], btype='band')
y = lfilter(b, a, data)
return y | 675a62ca3773ea73018ae34b63f4c760a9f1f5c7 | 3,602,952 |
def co2_ppmfrommgCO2pm3(c_mgpm3,T,p):
"""
Convert CO2 concentration units of mgCO2/m3 to umol/mol (ppm)
Usage:
CO2_ppm = co2_ppmfrommgCO2pm3(CO2_mgpm3, T, p)
where
CO2_mgpm3 (input) - CO2 concentration, mgCO2/m3
T (input) - air temperature, C
p (input) - air... | dc1883a479fa79389255d1edf70deba7e1392f4a | 3,602,953 |
def parse_downsample(arg_list):
"""Parse a list of downsampling policies into a dict usable by specificrulevalue."""
def parse_one(arg):
"""
Parse a single downsampling policy.
A downsampling policy consists of a system type (per parse_systemtype), a colon, and a limit or retention prob... | d4a2d7a68ce98f037acea6f248baa274595ce142 | 3,602,954 |
def top_ten_ports_in_network_events():
"""
get top ten repeated ports in network events
Returns:
JSON/Dict top ten repeated ports in network events
"""
date = fix_date(
get_value_from_request("date")
)
country_ip_dest = get_value_from_request("country_ip_dest")
top_ports... | 843d4bbafe5972116a83ec0ca494622006b6e88d | 3,602,955 |
def plt_transfer_ellipse(a: float, focus: VEC, **kwargs) -> Ellipse:
"""Create a transfer ellipse
Parameters:
-----------
a : float
Semi-major axis of the ellipse (Lambert's problem).
focus : `VEC` (numpy.ndarray)
2D vector to vacant focus. The other focus is assumed to lie at the
... | 2a76c9a6ef084c5ba87b4e1a2190362b5352d934 | 3,602,956 |
import tokenize
def tag_and_stem(text):
"""
Returns a list of (stem, tag, token) triples:
- stem: the word's uninflected form
- tag: the word's part of speech
- token: the original word, so we can reconstruct it later
"""
tokens = tokenize(text)
tagged = nltk.pos_tag(tokens)
out =... | ebcd366bbf0c6b285151b6ad065b55a8b2997636 | 3,602,957 |
def temp_biasadj_HH2015(ref_temp, ref_elev, gcm_temp, dates_table_ref, dates_table):
"""
Huss and Hock (2015) temperature bias correction based on mean and interannual variability
Note: the mean over the reference period will only equal the mean of the gcm for the same time period when the GCM
time... | b24c1329a1c18e3928752117566705dfb51e8933 | 3,602,958 |
def _interpolate_missing_data(X, val=255):
"""Replaces all pixels whose value is val with a weighted
average of neighboring pixels.
"""
assert(X.ndim==2)
Xout = np.array(X, copy=True)
rows, cols = np.nonzero(Xout==val)
for ii in range(len(rows)):
row = rows[ii]; col = cols[ii]
... | 4cb00a9c6259006bac69c440460b903394ff0d8d | 3,602,959 |
from ..baseobjs.resourceallocation import ResourceAllocation as _ResourceAllocation
def distribute_for_dot(a_shape, b_shape, comm):
"""
Prepares for one or muliple distributed dot products given the dimensions to be dotted.
The returned values should be passed as `loc_slices` to :func:`mpidot`.
Para... | 73bb88f0df2cec116650b7f0a9aa903427c20402 | 3,602,961 |
def resolve(oferta: list, demanda: (list, "matriz"), geral=False) -> "matriz":
"""Função que resolve tanto para um ou mais clientes passado."""
resultado_parcial = []
if not geral:
resultado_parcial.append(oferta_demanda(oferta, demanda))
else:
for i in range(len(demanda)):
... | 72098911a7a6e4a2a14fa589a8c065622ef9f6ad | 3,602,962 |
def home():
"""Home page - play with it if you must!"""
return redirect(url_for('dashboard')) | 2a7559a0c93c3af356fe84af04de6526950c54ec | 3,602,963 |
def compute_precision(Y_pred, Y_true):
"""
Compute precision = True positives / Total Number of Predicted Positives
= True positives / (True Positives + False Positives)
NOTE: This method applies to binary classification only!
Arguments:
Y_pred -- predictions, numpy array of... | f262e8964ea3835852fe85c8fa8b254bcf90139a | 3,602,964 |
def purchaseQuantity_perDate_month(data):
"""
DOCSTRING: Creates a 'Purchase Quantity per Day' column based on 'Purchase Date' and 'Purchase Quantity' columns, to assist future aggregations and plotting computations. Another new column 'Purchase Quantity per Month' gets created based on 'Month' and 'Purchase Qu... | 9a4605e801ca7921065580059ef0309d312c8543 | 3,602,965 |
def get(identifier):
"""Returns an optimizer function from a string. Returns its input if it
is callable (already a :class:`torch.optim.Optimizer` for example).
Args:
identifier (str or Callable): the optimizer identifier.
Returns:
:class:`torch.optim.Optimizer` or None
"""
if ... | cd42cbe3e8aefa1f2140eca76378002c4b1bb957 | 3,602,966 |
def deactivate_app():
"""
When multiple application instances are used, this method allows you to activate
the previously activated app by deactivating the current one.
(This method is meant for advanced users and should not be needed for most)
"""
global APP_STACK, APPS, APP
if len(APP_STA... | 50f0a4c7b3f5896a089dd9904a68bf293b975a5f | 3,602,967 |
import email
def parsemail(raw_message):
"""Parse message headers, then remove BCC header."""
message = email.parser.Parser().parsestr(raw_message)
# Detect encoding
detected = chardet.detect(bytearray(raw_message, "utf-8"))
encoding = detected["encoding"]
print(">>> encoding {}".format(encod... | 83609450cbd03657107646a0872fdbcff169f2bf | 3,602,970 |
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import RandomizedSearchCV
def randomsearch_crossval(training_set, training_labels):
"""[summary]
Args:
training_set ([type]): [description]
training_labels ([typ... | 621a51e46c3148b6c74efb41fe36e28e858a0413 | 3,602,971 |
def to_rdfbyid(request,model,id):
"""
take a model name + object id reference to an instance and apply any RDF serialisers defined for this
"""
try:
return _tordf(request,model,id,None)
except Exception as e:
return HttpResponse("Model not serialisable to RDF: %s" % e, status=5... | ac623cbb5b412e4083d3f1e92b1dedde9665a9a8 | 3,602,972 |
def HomePage ():
"""List all available api routes."""
return(
f"Available Routes are: <br/>"
f"<a href='/api/v1.0/precipitation'>Precipitation data</a><br/>"
f"<a href='/api/v1.0/stations'>List of all the stations</a><br/>"
f"<a href='/api/v1.0/tobs'>Last year's temperature for t... | 6edc00ae7b85e1d885a27c99d248f7f0551fdfd7 | 3,602,973 |
def win_sel(win_str, win_size):
"""
Function returns a window vector based on window name.
Note class can only use windows found in scipy.signal library.
"""
if (win_str == 'blackmanharris'):
win = sig.blackmanharris(win_size)
elif (win_str == 'blackman'):
win = sig.black... | bddf602b90d8a8b8afb7a9b41d7c0e7eff381428 | 3,602,974 |
def report_card_perf_overview(plan: pd.DataFrame):
"""Display performance overview diagrams.
Display a dropdown widget to choose between diagrams showing various
characteristics of the plan's convolution layers."""
layer_types = group_count(plan.df, 'type')
count_per_layer_type = partial(
p... | 74dde6220d7100b0dfd4f4d2bc82b6ed9dd78367 | 3,602,975 |
from typing import List
from typing import Dict
def get_beam_sections_map(model: BDF,
bar_beam_eids: List[int]) -> Dict[int, List[int]]:
"""gets the beams sorted by property_id that can be represented as 3d elements"""
bar_pid_to_eids = defaultdict(list)
int_offts = []
for ei... | fecee4714ff36783755ba2351fce548e6ff37db6 | 3,602,976 |
import inspect
def _instantiate_backend_from_name(name, options):
"""
Instantiate an event tracker backend from the full module path to
the backend class. Useful when setting backends from configuration
files.
"""
# Parse backend name
try:
parts = name.split('.')
module_n... | 7a17f038a5ae6549c749b55487f557d83d142135 | 3,602,977 |
def _start_offset_and_length(range_header):
"""
Returns a tuple of the start offset and the length.
If the range header doesn't exist, defaults to (0, -1). If parsing fails, returns (None, None).
"""
start_offset, length = 0, -1
if range_header is not None:
# Parse the header.
f... | ee93447068eb384c9e2f745b6621089c394939a5 | 3,602,978 |
import uuid
async def trigger_clone(request):
"""
Triggers a clone job on a sourcerepository.
---
description: Triggers a clone job on a sourcerepository.
tags:
- Builds
consumes:
- application/x-www-form-urlencoded
parameters:
- name: repository_id
in: p... | c241c7049ed79bb375665ffb3cdeeeddbc8a6b81 | 3,602,979 |
def requirements():
"""Returns the requirement list."""
with open('requirements.txt', 'r') as f:
return [line.strip() for line in f.readlines()] | e40af4819eac602c4af4845e2f59233dc3fa8a62 | 3,602,980 |
from pathlib import Path
def build_outpath(b:Build)->Path:
""" Return the output path of the realization being built. Output path is a
path to valid temporary folder where user may put various build artifacts.
Later this folder becomes a realization. """
paths=build_outpaths(b)
assert len(paths)==1, f"Build... | 3e6648bcad55dc8c55bd2f5b8cd93c09f7b3c7ed | 3,602,981 |
import dateutil
def parse(path, lang='ENG'):
"""
Get the isotherm and sample data from a BEL Japan .csv file.
Parameters
----------
path : str
Path to the file to be read.
Returns
-------
dataDF
"""
# set encoding
if lang == 'ENG':
encoding = 'ISO-8859-1'
... | 0d918c46b6257fc1b0ab8a44d1ffdacc1d3ed62b | 3,602,982 |
def _query_pkey(query, args):
"""Append 'query' and 'args' into a string for use as a primary key
to represent the query. No risk of SQL injection as memo_dict will
simply store memo_dict['malicious_query'] = None.
"""
return query + '.' + str(args) | d524697af247879f6aca5fa3918d80199b6148d5 | 3,602,983 |
from typing import Optional
import requests
def delete_package_holder(connection: Connection, id: str, project_id: Optional[str] = None,
prefer: str = 'respond-async',
error_msg: Optional[str] = None) -> requests.Response:
"""Delete the in-memory metadata packag... | 9ed5e71c7734bf720f27f6c39a7b7fe351025c54 | 3,602,984 |
def _gen_properties(**kwargs):
"""Creates a TaskProperties."""
args = {
u'cipd_input': _gen_cipd_input(),
u'command': [u'command1', u'arg1'],
u'dimensions': {
u'OS': [u'Windows-3.1.1'],
u'hostname': [u'localhost'],
u'pool': [u'default'],
},
u'env': {u'foo': u'bar', u'joe': u'2'... | f3c381902fa31cb95746326481a0a36de6930981 | 3,602,985 |
from typing import List
from typing import Tuple
def color_map_generate(
colors: List[Tuple[int, int, int]], add_black_if_not_exist: bool = False
) -> List[Tuple[int, Tuple[int, int, int]]]:
"""
컬러 리스트에서 [(id, 컬러)] 리스트를 생성합니다.
단, `(0, 0, 0)`이 있을 경우, 검은색의 id는 0으로 할당됩니다.
`add_black_if_not_exist` 옵션... | 38175b00d3f0bd5ba232cfcfd4b2e4bdb5ee7440 | 3,602,986 |
def get_innovation_message(ulog: ULog, topic: str = 'innovation') -> str:
"""
return the name of the innovation message (old: ekf2_innovations; new: estimator_innovations)
:param ulog:
:return: str
"""
if topic == 'innovation':
for elem in ulog.data_list:
if elem.name == "ek... | 03c01fb9352102216758c50654e8be626ee9d70f | 3,602,988 |
def collate_question(query, template, slot):
"""
Collate a question based on template and slot
"""
T1 = "select one to refine your search"
T2 = "what (do you want | would you like) to know about (.+)?"
T3 = "(which | what) (.+) do you mean?"
T4 = "(what | which) (.+) are you looking for?"
... | 1d615aa6b9b923b0f4c5dff0f01b9e04e45c41f5 | 3,602,990 |
import re
def paragraph_newline(paragraphs):
"""Format newlines for paragraphing"""
# Put new paragraphs here; will be joined on ''
newlined_ps = ['']
first_footnote = True
line = re.compile('\(\d\d*\)')
poet_line = re.compile('/\n')
footnote_line = re.compile('\[\^\d\d*\]:')
for i,... | d43ef0de1f95945a747d44957bb86128e1281c5c | 3,602,991 |
def phasemap_cm(m=256):
"""
Colormap periodic/circular data (phase).
"""
theta = 2 * np.pi * np.arange(0, m) / m
circ = np.exp(1j * theta)
# Vertices of colour triangle.
vred, vgreen, vblue = -2, 1 - np.sqrt(3) * 1j, 1 + np.sqrt(3) * 1j
vredc = vred - circ
vgreenc = vgreen - circ... | 78d942fd0f64a4199fc73e5267e2df6fc2744f27 | 3,602,992 |
def convert_coord(coord, name='none', original_image=None, converted_image=None):
"""
:param coord: coord = [label_index, center_x, center_y, width, height]
:param name:
1) rot_90
2) rev_rot_90
3) rev_flip_1 (flip code = -1)
4) flip_1 (flip code = 1)
5) flip_0 (flip code = 0)
---- i... | 32e41fba349dfa32d4b2b8c28e62515ed21d2832 | 3,602,993 |
def build_model(vocab_size: int, batch_size: int, store: BaseConfig) -> tf.keras.Sequential:
"""
Utilizing tf.keras.Sequential model
"""
model = None
if store.dp:
model = build_dp_model(store, batch_size, vocab_size)
else:
model = build_default_model(store, batch_size, vocab_siz... | 0828280c92411aebbae0b00b7a9de43a750e40b4 | 3,602,994 |
import hashlib
def login():
"""
" user login based on [email] and [password]
"""
data = request.json
if data is None:
return response_error(MESSAGE.INVALID_PARAMETER, CODE.INVALID_PARAMETER)
email = data['email']
password = data['password']
if is_valid_email(email) == False... | a3d6de620dd6f28b43e270d3f088ee627f832eea | 3,602,995 |
def data_split_with_processing():
"""
:return: preprocessed data as X input variables y output variable
"""
data = pd.read_csv("C:\\Users\\jackc\\OneDrive\Desktop\\jjp068\\final_data.csv", index_col=[0])
X = data.iloc[:, :-1]
y = data['winner']
rus = RandomUnderSampler()
X, y = rus.fit_... | 07792ed77c8b7c095cd4f8e01bab66cbc795ac33 | 3,602,996 |
def invert_transforms(ts: transforms.Compose) -> transforms.Compose:
"""
Inverts Normalize and ToTensor transforms in a transformation sequence defined via torchvision.transforms.Compose.
:param ts: transforms.Compose object with the list of transforms to be inverted
:return: a torchvision.transforms.Co... | 30da1bd8c0896d523a86dd1567811623a3ca16a3 | 3,602,997 |
from sympy.concrete.summations import Sum
from sympy.calculus.util import AccumulationBounds
from re import S
def limit_seq(expr, n=None, trials=5):
"""Finds the limit of a sequence as index n tends to infinity.
Parameters
==========
expr : Expr
SymPy expression for the n-th term of the sequ... | 23f32c5617c66fd16a2e4548ff187a76c3143945 | 3,602,999 |
from typing import Dict
def alias(alias: str) -> Dict[str, str]:
"""Select a single alias."""
return {"alias": alias} | 9321f00118658dc74fbc9704f1ea0e4a33e1f7aa | 3,603,000 |
def motion_store(
mock_labware_store: MagicMock,
mock_pipette_store: MagicMock,
mock_geometry_store: MagicMock,
) -> MotionStore:
"""Get a MotionStore with its dependecies mocked out."""
return MotionStore(
labware_store=mock_labware_store,
pipette_store=mock_pipette_store,
g... | 00fdd9bf0763061487ff3356e145d90ed7ddbede | 3,603,001 |
def check_validity(geojson_object):
"""
Checks if geojson is valid, throws exception otherwise.
:param geojson_object: geojson object
:return: will return the geo
"""
if geojson_object.is_valid:
return geojson_object
else:
raise api_exceptions.InvalidUsage(status_code=400, er... | 62d25b3b5b409850f6d5b4d15ed33604790c7ec9 | 3,603,002 |
def ErrorCalcsL2(R_vals = [3, 4, 5], n_vals = [200, 400, 600], alphaTrue = 1, betaTrue = 1, gammaTrue = 1, n_iter = 100, dataAlpha = 2, alphaMax = 5, gammaMax = 4, step = 0.1):
"""
Function for simulation of inferring alpha, beta, and gamma. Iterates over each (R, n) pair an equal amount of times
INPUTS:
... | 06ca8663052036458be669bbabd06b4d55185470 | 3,603,004 |
import ipdb
def ipdb(element):
""" Usage: {{ template_var|pdb }}
then inspect 'element' from pdb
"""
ipdb.set_trace()
return element | f393c285b75028d0efd818e0cd7bf3340b1d53cd | 3,603,005 |
def _apply_filter(kspace, filt):
"""Apply filter to kspace
Args:
kspace (np.ndarray) -- raw preprocesed kspace, excluding reference scans
shape : [rcvrs, time, slice, seg, phase, read]
filt (np.ndarray) -- filter to be applied after FFT in RO dimension
shape : [r... | 42c9b843eddbf9b1eb2894a88afce58f6f00d4d9 | 3,603,006 |
def get_member(src: str, member_name: str, fc: context.FunctionContext):
"""
Src has to be a stack symbolic register with a value of type s
RETURNS a stack symbolic register with a value of type m same as the type of s.member_name
"""
dest = fc.scope_man.new_tmp_var_name("member")
fc.types[des... | c4afcf8910cd57cbf0d15b401561db2822a5d010 | 3,603,007 |
def _lz_ema_spre_init(adj:np.ndarray, n_emp=10, rho=0.05)->dict:
""" Le-Zhong state initialization
:param adj: n_dim x n_dim adjacency matrix
:param n_emp: number of observations before switching from emp to moving avg cov
:param rho: importance of most recent observation
:return:
"""
... | 6d28b80771bc20851c61ba11291541bd306dcefa | 3,603,009 |
def connect_to_host(conf_vars):
"""Open a transport connection and authentificate.
Return a reference to the open connection.
"""
port = _DEFAULT_SSH_PORT
host = conf_vars['storer']['remotehostname']
username = conf_vars['storer']['remoteusername']
sock = open_socket(host, port)
t = pa... | 4ab264ed2f43dd451c428ecb7e1d7aa0e9b18269 | 3,603,010 |
def declare_variable(processor, composer, searcher):
# type: (Parser, Compiler, scanner.Scanner) -> Tuple[Parser, Compiler]
"""Record the existence of local variable in the compiler."""
if composer.scope_depth == 0:
return processor, composer
token = processor.previous
for i in range(compo... | 999e9596c5d830f7a4a3b6d3510172b719c67e75 | 3,603,011 |
from registry.get_service import run as _get_service
from registry.register_service import run as _register_service
from admin.handler import MissingFunctionError
def registry_functions(function, args):
"""This function routes calls to sub-functions, thereby allowing
a single registry function to stay hot ... | 56c7fc3f244bd3fcfcff248d5ea740ea2585b75b | 3,603,013 |
def conv1x1(in_channels,
out_channels,
stride=1,
groups=1, dilation=1,
bias=False):
"""
Convolution 1x1 layer.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
str... | f96b2b1aa0375895f7fc080fd47858292df5892c | 3,603,014 |
def _setup_entities(hass: HomeAssistant, device_ids: list):
"""Set up Tuya Switch device."""
device_manager = hass.data[DOMAIN][TUYA_DEVICE_MANAGER]
entities = []
for device_id in device_ids:
device = device_manager.device_map[device_id]
if device is None:
continue
i... | 8654c53f52134003484c293dfa5b66c696273385 | 3,603,015 |
from IPython.display import HTML
from IPython.display import display as iDisplay
def animate_centroids(
lcf,
fig=None,
frames=None,
num_obs_per_frame=240,
interval=250,
use_relative_time=False,
time_range=None,
accumulative=True,
c=None,
display=True,
):
"""
Animate cen... | 237db91a1fdf4f6f83ef7a1bf2e1bba79ff58a39 | 3,603,016 |
async def async_discovery(session):
"""Find bridges allowing gateway discovery."""
bridges = []
json_dict = await async_request(session.get, URL_DISCOVER)
if json_dict:
for bridge in json_dict:
bridges.append({'bridgeid': bridge['id'],
'host': bridge['inte... | 8647b2af8fdac987052fff6f1706cb1914c0f235 | 3,603,018 |
def layerZofHit(hit):
""" Get layerZ from hit """
return ecal_layerZs[layer(hit)] | 6dd3c4df468fb2652ab61feb929bbfa1869dc634 | 3,603,019 |
def camera_from_ngl_state(state_d, zoom_factor=300.0):
"""define a vtk camera from a neuroglancer state dictionary
Parameters
----------
state_d: dict
an neuroglancer state dictionary
zoom_factor: float
how much to multiply zoom by to get camera backoff distance
default = 30... | e904f4defa3341e7002a80579e9374b6ad6d6b34 | 3,603,020 |
def fix_hardmix():
"""Fixture for a hard mixture"""
return {
"background": {"markov:rmin_500_rmax_1000_thresh_0.8_priceVarEst_1e9": 1},
"hft": {"noop": 1},
} | dee9b13b6b7f14ae334a6e1eda6c1fd2a362ba32 | 3,603,022 |
def max_digits(x):
"""
Return the maximum integer that has at most ``x`` digits:
>>> max_digits(4)
9999
>>> max_digits(0)
0
"""
return (10 ** x) - 1 | 3f0ffdfbbb3fdaec8e77889b3bfa14c9b9829b2e | 3,603,023 |
def crear_sprite(dir_sabana, dimensiones, columnas, filas=1, opcion=None):
"""
Funcion para recorte de sprites
sabana: imagen con los graficos
dimensiones: [ancho,alto] del recorte
columnas: cantidad de columnas que tiene la sabana
filas: filas de la sabana (default 1)
opcion: optiene una ma... | 0eb87ee318a709f543bf7213ee102506a1c9d8c3 | 3,603,024 |
def add_intercept_feature_col(X: np.ndarray) -> np.ndarray:
"""Add an intercept column to a (n_examples, n_features) data matrix.
Args:
X: The input array, of shape (n_examples, n_features)
Returns:
X, but with a column of ones prepended, so that it is of shape
(n_examples, n_featu... | d8127b07974a4f0a51efc02e8d81887e05a5825c | 3,603,026 |
def upload_request(self, upload_data, custom_opts=None):
"""Uploads the given generic data and returns the response object."""
opts = default_upload_options()
opts.update(self.custom_opts)
if custom_opts is not None:
opts.update(custom_opts)
# Upload as a directory if the dirname is set, e... | 7bb3bbcbf8e123b0df8c20b5c6cefee2fa5d3b8e | 3,603,027 |
def index():
""" Homepage, point visitors to project page """
theme = themes[DEFAULT_THEME]
return render_template('index.html', theme=theme) | 9ac091b90e3f2bf4f5b2b04ce737afbed78a10c9 | 3,603,028 |
def to_numpy(t):
"""
If t is a Tensor, convert it to a NumPy array; otherwise do nothing
"""
try:
return t.numpy()
except:
return t | 3ac3ef0efd9851959f602d42e7f38bdd7e5da21a | 3,603,029 |
def _hamiltonian_expected(cells, periodic, sites_per_cell,
freedom):
"""Expected Hamiltonian for the simple 1D lattice model"""
# Within the cell, adjacent sites hop to each other, and it's always
# non-periodic.
cell = qutip.qdiags([-np.ones(sites_per_cell - 1)]*2, [1, -1])
... | 19c0ad8d71eb6b8c13556c22b27453725c0cb153 | 3,603,031 |
import torch
import test
def train(args, model, train_loader, test_loader, loss_func, optimizer, device):
"""Function to train a torch model
Args:
args: command line parsed arguments containing training parameters like epochs, log interval
model (torch model): a pytorch model (can... | 91bd7536284bcb2df65fffedf96feed8fdfd45e6 | 3,603,032 |
def printStateStringLatex(n, l, j, s=None):
"""
Returns latex code for spectroscopic label for numeric :math:`n`,
:math:`l`, :math:`j` label of the state.
Args:
n (int): principal quantum number
l (int): orbital angular momentum
j (float): total angular m... | 8a95c6441d3396602223efabb5da2385a1f3a4a0 | 3,603,033 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.