content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
from typing import Tuple
def count_per_domain_statistics(
domain_idxs: torch.Tensor
) -> Tuple[np.ndarray, np.ndarray]:
"""
Args:
- domain_idxs: Pytorch tensor of shape (N,) showing assignment
of each example to each particular domain
Returns:
-... | 4e900e1f611e942a07efc17481462e025bfa4e10 | 52,000 |
def handler500(request):
"""
This is a Django handler function for the 500 server error page. Because a server error can imply an serious issue
such as corrupted database, a nice render of the 500 page may be impossible. So the server first attemps to nicely
render the page with all the dynamic element,... | 5e818aa9ab9d3ebaef2d843e8b32cfd3da90941c | 52,001 |
def featurenet_backbone(input_tensor=None, input_shape=None,
n_filters=32, **kwargs):
"""Construct the deepcell backbone with five convolutional units
Args:
input_tensor (tensor): Input tensor to specify input size
n_filters (int): Defaults to 32. Number of filters for
... | 653646aa594c174ea3f0050401dbca176315fc49 | 52,002 |
from typing import Optional
def call_somewhat_forgivingly(
func, args, kwargs, enforce_sig: Optional[SignatureAble] = None
):
"""Call function on given args and kwargs, but with controllable argument leniency.
By default, the function will only pick from args and kwargs what matches it's
signature, ig... | c2c32cd0b1e8cedc3bcdf030e81d90777a303a54 | 52,003 |
import os
import jinja2
def generate_formula_with_template() -> str:
"""Generate a brew formula by using a template"""
template_path = os.path.join(os.path.dirname(__file__), TEMPLATE_FILE_NAME)
with open(template_path, mode='r') as template:
template_content = template.read()
template = jinj... | 7761b49c1cd44225d0036461f6ca95a05e4a664e | 52,004 |
from typing import List
def _get_list_of_layers(
input_dim: int, hidden_dim: int, output_dim: int, num_layers: int
) -> List[nn.Module]:
"""Utility function to get a list of layers. This assumes all the hidden
layers are using the same dimensionality.
Args:
input_dim (int): input dimension.
... | 9d30258aa06c39e76ddb1b9d96fb699d85b48d22 | 52,005 |
import scipy
import numpy
def LagrangeMultiplierMethod(H, f):
"""
LEXMIN Solve the multi-objective minimization problem:
min {E1(x), E2(x), ... , Ek(x)}
x
where
Ei = 0.5 * x.T * H[i] * x + x.T * f[i]
and Ei is deemed "more important" than Ei+1 (lexicographical ordering):
... | 6a557dc153e3b291eb8b2c9f1c85e3baf1eff091 | 52,006 |
def rescale_to_11bits(im_float):
"""Rescale a float image in [0, 1] to integers in [0, 2047].
This operation makes rank filtering much faster.
Parameters
----------
im_float : array of float in [0, 1]
The float image. The range and type are *not* checked prior to
conversion!
R... | ec15a3599b03184ee520f61e29f40bb0cbb24581 | 52,007 |
import re
def get_data(session_id, n_intervals):
"""Query Database and prepare data as DataFrame.
Parameters
----------
session_id : str
unique session id hex used for caching.
interval : int
update interval from counter used for updating data.
Returns
-------
df : pa... | c84253c0e6838b68454e228395f6a7bca578d282 | 52,008 |
def multi_dict_unpacking(lst):
"""
Receive a list of dictionaries, join them into one big dictionary
"""
result = {}
for d in lst:
for key, val in d.items():
result[key] = val
return result | 530947224d682cffb809e83f308a97a108002080 | 52,009 |
import math
def dist(a: list, b: list) -> float:
"""Calculate the distancie between 2 points
Args:
a (list): point a
b (list): point b
Returns:
float: Distance between a and b
"""
return math.sqrt((a[0]-b[0])**2+(a[1]-b[1])**2) | 7ad6d2f36c0bccee106c7b54a4abebd246c4a3fa | 52,010 |
def is_array_like(item):
"""Check if item is an array-like object."""
return isinstance(item, (list, set, tuple, np.ndarray)) | 7176330220ca903a38d28710053aee6c4edf9df5 | 52,011 |
async def verifyGroupPath(h5path):
""" create any groups along the path that doesn't exist
"""
#print("current task: ", asyncio.Task.current_task())
client = globals["client"]
domain = globals["domain"]
h5path_cache = globals["h5path_cache"]
params = {"host": domain}
parent_group = h5pat... | 5c5c5bc4984b1e58e7008142aa5a0d42ba280921 | 52,012 |
import os
def start_args():
"""
Prepare the things required for Brick Start and Returns the Proc
object required to start Brick Process.
"""
brick_device = os.environ.get("BRICK_DEVICE", None)
brick_path = os.environ["BRICK_PATH"]
if brick_device is not None and brick_device != "":
... | 73c1f09420d76821b65fc5cde903e0309679c567 | 52,013 |
import re
import os
import glob
from typing import OrderedDict
def getVIIRSfilesbygranule(basedir, scenelist=[]):
"""
Returns a dictionary that parses a list of scene directories where each
name YYYY_MM_DD_JJJ_hhmm refers to an overpass timestamp and contains
multiple granules and individual desaggreg... | 27e44b0063ffd5588cd10ea8d90629d90bb6c38c | 52,014 |
def coord(x, y, integer=False):
"""
Convert world coordinates to pixel coordinates. Setting 'integer' to
True will return integer coordinates.
"""
xs = (DRAW_OFFSET[0] + DRAW_SCALE*x)
ys = (DRAW_OFFSET[1] - DRAW_SCALE*y)
if integer:
return int(round(xs)), int(round(ys))
else:
... | 7962dcf2dcbf16dfaaa7fd553ce99530f096106a | 52,015 |
def handle_match(match, url):
"""Should there be a match, format a message and send a notification."""
if match:
message = "Match found at {}:\n{}".format(url, match)
return __send_notification(url, message)
else:
return 'Missing match at: {}'.format(url) | bd019baa184df41a209b19549074b38127ba29b6 | 52,016 |
import requests
import io
def call_model(model_type="mosaic", file_path="tests/flowers.jpg"):
"""helper function"""
model_endpoint = 'http://localhost:5000/model/predict?model=' + model_type
with open(file_path, 'rb') as file:
file_form = {'image': (file_path, file, 'image/jpeg')}
r = re... | 47a5038de6f56c4ae6c099803b8cffc9482ed9f4 | 52,017 |
from bs4 import BeautifulSoup
def get_soup(url):
"""Gets BS object from the given URL"""
# - Get Data
html = get_data(url)
# - Get Soup
soup = BeautifulSoup(html, 'html.parser')
if soup is None:
raise Exception("No data from URL")
return soup | 00b0ef5379e470b5603da54e93aa0d878132d41a | 52,018 |
def node_wise_2_sample(latent, node_ind):
"""Get dcorr t stat for a single node"""
node_latent_pop1 = np.squeeze(latent[:n_graphs, node_ind, :])
node_latent_pop2 = np.squeeze(latent[n_graphs:, node_ind, :])
t_stat = compute_t_stat(node_latent_pop1, node_latent_pop2)
return t_stat | a1939f474d7407c92aea0eb4b0a6fdb30cf60045 | 52,019 |
import urllib
import sys
def upload_single_file(application, file_path, version, override,
stable, scope, force=False, initial_visibility=None, no_wait=False):
"""
:return: exit code
:rtype: int
"""
app_info = read_jar_file(file_path)
if not force and override and not (s... | 6622b3117ffacfbb2c4fbe7986fea52144a5543c | 52,020 |
def create(sender, recipients=None, cc=None, bcc=None, subject='', message='',
html_message='', scheduled_time=None, headers=None,
template=None, priority=None, commit=True,
backend=''):
"""
Creates an email from supplied keyword arguments. If template is
specified, email su... | 4bfe19949c0c07b34d9a5443c5aee8afb785dcca | 52,021 |
from typing import Dict
from typing import Union
from typing import Set
def get_fields_eligible_for_pagination(
schema_info: QueryPlanningSchemaInfo,
types: Dict[VertexPath, Union[GraphQLObjectType, GraphQLInterfaceType]],
single_field_filters: Dict[PropertyPath, Set[FilterInfo]],
fold_scope_roots: Di... | a9b606bb5f44fcb8ae3cfdbe2678f359e83e3a45 | 52,022 |
import re
def _parse_commit_position(commit_message):
"""Parses a commit message for the commit position.
Args:
commit_message: The commit message as a string.
Returns:
An int if there is a commit position, or None otherwise."""
match = re.search(
'^Cr-Commit-Position: [a-z/]... | 7f4d93f8fc88a18276570f2d33ff2fbb75673025 | 52,023 |
from typing import Any
def convert_simple_type(value: Any, json_definition: dict) -> Any:
"""
:param value: Can be of any JSON type except list or dict.
:param json_definition: OpenAPI definition of the value (format used to parse it).
"""
if isinstance(value, str):
field_format = json_def... | 0d83275efa3cc2320d21ed8fb848ee3b2931aa91 | 52,024 |
import torch
def block_diag(m):
"""
Make a block diagonal matrix along dim=-3
EXAMPLE:
block_diag(torch.ones(4,3,2))
should give a 12 x 8 matrix with blocks of 3 x 2 ones.
Prepend batch dimensions if needed.
You can also give a list of matrices.
:type m: torch.Tensor, list
:rtype: ... | c814118d08b34a168e0e9a1ade047c3be26ae5e6 | 52,025 |
def _twoByteStringToNum(bytestring, numberOfDecimals=0, signed=False):
"""Convert a two-byte string to a numerical value, possibly scaling it.
Args:
* bytestring (str): A string of length 2.
* numberOfDecimals (int): The number of decimals. Defaults to 0.
* signed (bol): Whether large p... | 246bff7ec138778718ac8aa47c6348e240a5051b | 52,026 |
def smape(y_true, y_pred):
"""
Calculates the symmetric mean absolute percentage error of the predicted
values to the true values. `y_true`, `y_pred` should be of the same
type and shape.
The SMAPE is calculated as:
2 * mean(|y_pred - y_true| / (|y_pred| + |y_true|))
Therefore, it is ... | ea109400eebf0768b485e434cef992f58e9e3b22 | 52,027 |
def _api_rss_now(name, output, kwargs):
""" API: accepts output """
# Run RSS scan async, because it can take a long time
scheduler.force_rss()
return report(output) | 72e74532fcd2cd4b5c41f9273ce6ebd00c5b566a | 52,028 |
def get_middle_opt(string: str) -> str:
"""Get middle value of a string (efficient).
Examples:
>>> assert get_middle_opt('middle') == 'dd'
"""
return (
string[int(len(string) // 2) - 1 : int(len(string) // 2) + 1]
if not len(string) % 2
else string[int(len(string) // 2)]... | 1636f39e22bacc4f571de876dd71add690e940e6 | 52,029 |
import csv
def vmess_IO(class_):
"""
获取可用订阅链接并刷新存储池
class_: ssr ; v2ray
"""
def refresh_log(dataFlow):
with open(SYS_AIRPORT_INFO_PATH, 'w', encoding='utf-8', newline='') as fp:
writer = csv.writer(fp)
writer.writerows(dataFlow)
try:
with open(SYS_AIRP... | 6e99847f5b3b1ff09b74a1e669a9bb18ee0e5bfa | 52,030 |
from typing import Optional
def get_anonymous_current_user(locale: Optional[str]) -> CurrentUser:
"""Return an anonymous current user object."""
return CurrentUser(
id=ANONYMOUS_USER_ID,
screen_name=None,
suspended=False,
deleted=False,
locale=locale,
avatar_url... | 3c503154f986cfd420751ce331943a8d5854b60a | 52,031 |
def cut_sites_with_region(df_sites, df_region):
"""Find peak interval the crosslinks belong to."""
df_p = df_sites[df_sites['strand'] == '+'].copy()
df_m = df_sites[df_sites['strand'] == '-'].copy()
df_region_p = df_region[df_region['strand'] == '+'].copy()
df_region_m = df_region[df_region['stran... | df40f8fc522e9be65d146b30a17c587899749957 | 52,032 |
def check_inplane_vector(vector, normal):
"""
Determines if a vector is in plane with the current element
:param vector: Test vector
:param normal: Normal of element
:return:
"""
checkdot = np.dot(normal, vector)
err = 1e-9
if -err < checkdot < err:
return True
else:
... | e535dd30d6f03b1ca9048958e769ec02b70e0ba2 | 52,033 |
def parse_temp_data(json_graph):
"""Parse the temp data"""
temp_list = list(filter(lambda x: '100kHz' in x['label'], json_graph['graph_kind_1008']))
if len(temp_list) == 0:
return None
return clean_data(temp_list[0]['data']) | dff2ee90c7312a713815860668551619dceaba97 | 52,034 |
from typing import List
def brl_out(offset: int, data: List[int]) -> bytes:
"""send data to braille display
@param offset: Must be positive.
"""
d2 = len(data)+7
ret = bytearray([
STX,
ord(b'S')
])
ret.extend(offset.to_bytes(2, "big", signed=False))
ret.extend(d2.to_bytes(2, "big", signed=False))
ret.ex... | c761dd0eadd4a59264c1dcca6d2dfed6323f0078 | 52,035 |
def degree_as_dm7(degree):
"""
Given a degree, return the equivalent dm7. Does not perform range validation.
Performs integer conversion of the result.
"""
return int(round(_DM7_PER_DEGREE * degree)) | 1bdd862e32942175ba06f54987d89646e43dae4d | 52,036 |
def duration(duration):
"""Filter that converts a duration in seconds to something like 01:54:01
"""
if duration is None:
return ''
duration = int(duration)
seconds = duration % 60
minutes = (duration // 60) % 60
hours = (duration // 60) // 60
s = '%02d' % (seconds)
m = '%0... | 7cd89654a84c2e3e41d96cb1b13688833ee54387 | 52,037 |
def test_log_dtypes(dtypes, capsys, test_df):
"""Test logging of dtypes can be switched on and off"""
@log_step(dtypes=dtypes)
def do_nothing(df, *args, **kwargs):
return df
test_df.pipe(do_nothing)
captured = capsys.readouterr()
assert ("dtypes=" in captured.out) == dtypes
if d... | 735b1479304dcc15bff10a95c37af9417da79ce7 | 52,038 |
def lookup_embedding_func(
id_tensors, max_ids, embedding_dim,
):
"""
Args:
id_layers: dict, the key is a string and
the value is tf.keras.Input.
standardized_tensor:
input_tensors: dict, the key is a string and the value
is a tensor outputed by the transform ... | 2666832656bf9d98a933b068215c3076328f3a3d | 52,039 |
import types
def name(function):
"""
Retrieve a pretty name for the function
:param function: function to get name from
:return: pretty name
"""
if isinstance(function, types.FunctionType):
return function.__name__
else:
return str(function) | 4002d7a945c3b3e3e4d957c0b10ff202f2cf0246 | 52,040 |
def loading_effects_decorator(func):
"""
Decorator for creating an loading cursor.
>>> @loading_effects_decorator
>>> def do_lengthy_process():
>>> # DO something
>>> pass
Parameters
----------
func: function
Returns
-------
new_function: object
"""
d... | 28c495d0c5b31e124173184ccb2d00dd90986376 | 52,041 |
import requests
def get_response_json(url: str):
"""
Function get response json dictionary from url.
:param url: url address to get response json
:type url: str
:return: dictionary data
:rtype: json
:usage:
function calling
.. code:: python
get_response_json... | dd209b1dba7f4320cd91addb1e49fa98bab0ae2b | 52,042 |
def JobPostingDetails(request, pk):
"""
Retrieve, update or delete a job posting.
"""
try:
job_posting = JobPosting.objects.get(pk=pk)
except JobPosting.DoesNotExist:
return HttpResponse(status=500)
if request.method == "GET":
serializer = JobPostingSerializer(job_postin... | 1f1cc4be467fd64cf87bbab01fcae68a19905969 | 52,043 |
import sys
def create_enclave_signup_data():
"""
Create enclave signup data
"""
try:
enclave_signup_data = \
enclave_helper.EnclaveHelper.create_enclave_signup_data()
except Exception as e:
logger.error("failed to create enclave signup data; %s", str(e))
sys.exi... | 0ab9059e0a1539d033b882c4ce221d131efb523c | 52,044 |
import ast
import re
def strip_typehints(source):
"""Strip the type hints from a function"""
if black:
source = black.format_str(source, line_length=82)
# parse the source code into an AST
parsed_source = ast.parse(source)
# remove all type annotations, function return type definitions
... | 46df36fcffd38b6657df041fb366f001c410ece6 | 52,045 |
def upconv(x, channels, kernel=3, stride=2, pad=1, use_bias=True, sn=False, scope='upconv_0'):
"""
upsampling + conv
"""
with tf.variable_scope(scope):
x = up_sample(x, scale_factor=stride)
x = conv(x, channels=channels, kernel=kernel, stride=1, pad=1, use_bias=use_bias, sn=sn, scope=sco... | 6e3e13e6143757afb549a42632a877b9cb7089a9 | 52,046 |
import copy
def create_temporary_copy(directory_path: str, target_directory_prefix: str = "") -> str:
"""Creates a copy of a directory in a temporary directory and returns its path"""
copy_path = get_temporary_directory_path(target_directory_prefix)
copy(directory_path, copy_path)
return copy_path | b835724145ee64cc52d9193cc73b2b25eb33ec2a | 52,047 |
import pickle
def dumps_content(content):
"""
pickle 序列化响应对象
:param content: 响应对象
:return: 序列化内容
"""
return pickle.dumps(content) | f88159b9d016a6e39744e7af09a76705c9f4e76f | 52,048 |
import os
def get_info(request, tut):
"""Get information about the tutorial from the 'info.ini' file.
:request: Pyramid request
:tutorial: Tutorial name
"""
cfg = SafeConfigParser()
cfg.optionxform = str # case-sensitive keys
cfg.read(os.path.join(get_tutorialdir(request, tut), 'info.ini... | 03edfa34b2257f7b712606ec42c6c356042758ea | 52,049 |
def hide_solution(key, tpl_dict = latex_doc.tpl_dict):
"""Hide solutions by default"""
return """
{%- if cell.metadata.solution_first or cell.metadata.solution2_first or cell.solution_first or cell.solution2_first -%}
{# exercise #}
{%- elif cell.metadata.solution == 'hidden' or cell.metadata... | 836e6bb8009d5626b08ef339145758f7f3ce4214 | 52,050 |
def midpoint(f, a, b, N):
"""Zusammengesetzte Mittelpunktsregel in 1d.
Input:
f : Funktion f(x) welche integiert werden soll.
a, b : untere/obere Grenze des Integrals.
N : Anzahl Teilintervalle in der zusammengesetzten Regel.
"""
x, h = np.linspace(a, b, N+1, retstep=True)... | 0c07c51a8f9c917c1b22ebfebb8c8904fa4dccba | 52,051 |
import argparse
def create_arg_parser():
""" Create an argument parser
return: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser()
# Read in the input file
parser = argparse.ArgumentParser(
description="Create metrics plots in a batch mode")
parser.add_argument(dest=... | 1f8c1e1723f9feaa26519e42662ab7f98d0726c4 | 52,052 |
def content_disposition_filename(filename):
"""
Sanitize a file name to be used in the Content-Disposition HTTP
header.
Even if the standard is quite permissive in terms of
characters, there are a lot of edge cases that are not supported by
different browsers.
See http://greenbytes.de/tech... | dd60cddee1ccb08344e41a2ffbd4bb68b599d5da | 52,053 |
import os
import json
def orgs_v3_p1():
"""
Returns raw orgs from API v3
"""
with open(os.path.join(HERE, 'fixtures', 'orgs_v3_p1.json')) as f:
return json.loads(f.read()) | 05591545231f96d7fcf7178b2b53b35379ee659c | 52,054 |
from datetime import datetime
def fmt_datetime(object_: datetime) -> str:
"""Parse datetime into pydantic's JSON encoded datetime string"""
return object_.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") | 2e39b9d6a262aaa0297f50af8c1fbf9069ac5f4b | 52,055 |
def _gen_setup_file(project_name: str) -> str:
"""
Generate setup.py module content.
"""
content = """\
from setuptools import setup, find_packages
setup(
name='%s',
description='App description.',
version='1.0',
packages=find_packages(),
# package_data={'package': ['subfolder/*']}... | 293003969f52cec6d5314d703848b4ed16853ba4 | 52,056 |
import subprocess
def generate_manifest_in_from_git():
"""Generate MANIFEST.in from 'git ls-files'"""
cmd = r'''git ls-files | sed 's/\(.*\)/include \1/g' > MANIFEST.in'''
return subprocess.call(cmd, shell=True) | bf346f109a79d07dfd66c02d61bfa886e994d9a2 | 52,057 |
import json
def get_table_list(transaction_executor):
"""
Connect to a given ledger using default settings.
"""
statement = "SELECT name FROM information_schema.user_tables"
cursor = transaction_executor.execute_statement(statement)
try:
table_list = {}
i = 0
for r... | c4d50798c0b6340ebe064e087664cfaca5f28a49 | 52,058 |
def _apply_conv_mode(ret, s1, s2, mode, axes):
"""Calculate the convolution result shape based on the `mode` argument.
Returns the result sliced to the correct size for the given mode.
Parameters
----------
ret : array
The result array, with the appropriate shape for the 'full' mode.
s... | 873f5529da5e88a52278fb5c90537c7751b50845 | 52,059 |
def submit_local(filename: str, cmd_line_arguments: str, debug: bool = True):
"""Create a local job & submit it based on provided file to execute."""
cmd = f"{PYTHON_EXECUTABLE} {filename} {cmd_line_arguments}"
proc = submit_subprocess(cmd, debug)
return proc | 50e359096ce158af0ad3056d750ee5bb29b11c50 | 52,060 |
def format_time(ogtime):
"""Increase readability of given catalog times."""
return pd.Timestamp(' '.join(ogtime.split('T'))[:-1]) | 93207ba2b09c3f25c15f5aa2fcf8030950f530f3 | 52,061 |
import time
def train(loss_fn):
"""使用损失函数loss_fn训练回归"""
print("Training;loss function:" + loss_fn.__name__)
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
def loss_for_example(x, y):
return loss_fn(y, prediction(x))
# `grad_fn(x_i, y_i)` returns (1) the value of `loss... | 20de6a0bf6245efc4351e0339b942fbf80e0b9b2 | 52,062 |
def estimator(data):
"""
Takes input data and returns it in a
specified format.
"""
# get days
days = timeEstimateDays(data["periodType"], data["timeToElapse"])
# Challenge 1
# Currently infected estimates
currentlyInfectedImpact = int(data["reportedCases"] * 10)
curren... | 1b7e6bd6772aae1b2b1d76fec083ec601515f7f8 | 52,063 |
def run(method):
"""Run method."""
switcher = {
"construct": lambda: construct(),
"execute": lambda: execute()
}
return switcher.get(method)() | 602cf4765144bbb838fab3f8733cf953216a6d06 | 52,064 |
def unicode_parm(cap, *parms):
"""Return the result of ``tparm(tigetstr())`` except as Unicode."""
return tparm(tigetstr(cap), *parms).decode('utf-8') | cdab15341bf9e7597728bc9552f998118e9a4751 | 52,065 |
def lmtd(tci, tco, thi, tho, counterflow=True):
"""log mean temperature difference
tci = cold inlet
tco = cold outlet
thi = hot inlet
tho = hot outlet
"""
if counterflow:
itd = thi - tco
otd = tho - tci
else:
itd = thi - tci
otd = tho - tco
return lmd(itd, otd) | fef77a7d31ecb7cf00f689d315398643c6df5c5c | 52,066 |
def haversine_distances(X, Y=None):
"""Compute the Haversine distance between samples in X and Y
The Haversine (or great circle) distance is the angular distance between
two points on the surface of a sphere. The first distance of each point is
assumed to be the latitude, the second is the longitude, g... | fa62a8b6f39625aef2a7223c3c23ec7c6705054c | 52,067 |
def rotateRight(self, head: ListNode, k: int) -> ListNode:
"""
72ms 36.76%
13MB 95.80%
:param self:
:param head:
:param k:
:return:
"""
if not head or not head.next:
return head
old_tail = head
length = 1
while old_tail.next:
old_tail = old_tail.next
... | b77ceb294655bf88c41b99366ea6054c6ee29f3a | 52,068 |
def calculate(frame,shares_outstanding):
"""
calculate daily RV/BV/Diff price/volume values from minute price data frame
:param frame: pandas dataframe object from minute price data
:param shares_outstanding: company shares outstanding for volume normalization
:return: the new frame constructed fro... | 75726d2e2fed89bd0c1dfb9a5cb7ac9e17a175b7 | 52,069 |
import numpy
def mgc(piece_u, piece_v, relation):
"""
Computes the final mahalanobis gradient compatibility
:param piece_u: One of the puzzle pieces
:type piece_u: numpy.ndarray
:param piece_v: The other one of the puzzle pieces
:type piece_v: numpy.ndarray
:param relation: The connect... | 3da85a5937715310a524b0f0e5d443b8458dcc3c | 52,070 |
def mock_query_object(LCClient):
"""
Creating a Query Response object and prefilling it with some information
"""
# Creating a Query Response Object
start = '2016/1/1'
end = '2016/1/2'
obj = {
'TimeRange': TimeRange(parse_time(start), parse_time(end)),
'Time_start': parse_tim... | 4ef04e98eb4623763a6ac9cf52d6a5f0489c094f | 52,071 |
def determine_edge_sigmoid_params(laplacian_image: itk.Image) \
-> tuple[float, float]:
"""
This function determines the appropriate alpha and beta
for a sigmoid function. This sigmoid function should map
regions of constant intensity to 1.0, while mapping regions
with high intensity gradien... | 80fc6067fead5a4023abc59535c8d5f8bea58c8c | 52,072 |
def getRandomPopulation(popSize, numItems):
"""
Creates a population of random chromosomes
:param popSize: Population size
:param numItems: Chromosome size
:return: list
"""
return [getRandomChromosome(numItems)
for x in range(popSize)] | 097ef584d48ef2a65e8b47d68f351c9563492387 | 52,073 |
def multi_synonym(w2v_model, multi_syns, n, pooling):
"""Given list of synonyms that represents crossword clue, return aggregate ranking
Args:
w2v_model : standard Word2Vec 'KeyedVectors' data structure
multi_syns : nested list containing lists of each synonym present in a clue
n : ... | bc08827397011f576648ae6a4469d067c890eab5 | 52,074 |
def handleCookbookError(r):
"""Deals with errors when updating cookbook"""
if(r.status_code == 404):
print ""
print "Error Notifying Cookbook of new Gist. Is this URL correct?"
print cookbookURL
print ""
print "If not, update cookbookURL in uploadGists.py in devtools to c... | e17cdb4cbe7e6144365369a27b74a4b50f05d7ae | 52,075 |
import json
def check_cross_account(policy_text, allowed_accounts):
"""Find cross account access policy grant not explicitly allowed
"""
if isinstance(policy_text, basestring):
policy = json.loads(policy_text)
else:
policy = policy_text
violations = []
for s in policy['Stateme... | fadc76cbd37b4d821d9143a7a4804e4725e807ca | 52,076 |
def stokes_ellipsometry(tanpsi, Delta):
"""
Stokes vector using ellipsometer parameters.
This creates a Stokes vector for the specific set of ellipsometry
parameters tanpsi and Delta. See Fujiwara table 3.1 for example.
Args:
tanpsi: abs(E_x/E_y) [-]
Delta: angle(E_x) ... | 12f06c0416d05e001b5805465c43653c59c01c43 | 52,077 |
def gen_psd(q):
"""
Random PSD matrix of size (q,q)
from Wishart distribution
"""
G = np.random.randn(q,q)
G = G @ G.T * (1/q)
return G | 73b3d0bab80a8a266fd58d80c7fced2c4aacd648 | 52,078 |
def strictwwid(wwid):
"""Validity checks WWID for invalid format using strict rules - must be Brocade format"""
if len(wwid) != 23: # WWPN must be 23 characters long
print("WWID has invalid length " + wwid)
return None
# Colon separators must be in the correct place
if wwid[2:3] != ":" ... | 539d9e0ef9f1f9f6d24dbc4a1a514d9a07229388 | 52,079 |
from datetime import datetime
import logging
def GetPlistDateValue(key, secure=False, plist=None, str_format=None):
"""Returns the UTC datetime of a given plist date key, or None if not found.
Args:
key: string key to get from the plist.
secure: boolean; True = munki secure plist, False = munki regular p... | 5cab183096909175ef17857a8b21fcb38edf13e6 | 52,080 |
def get_research_data_by_dev(sn):
"""Return the research data by device
"""
dev = Instrument.query.filter_by(sn=sn).first_or_404()
# Choose model
model = dev._get_data_model()
data = _collection(model, model.query.filter_by(instr_sn=dev.sn),
name='data', sn=dev.sn, researche... | 54c3e00770951ed9d2921264c9da1f6e0a6968ec | 52,081 |
def gethub():
"""
:return: an initialized instance of the github utility.
"""
# Thanks, I'll be here all week.
return Github(base_url=GITHUB_API_URL, login_or_token=GITHUB_ACCESS_TOKEN) | e031cb97abf2316116b1ef1dd17313846ab8ef21 | 52,082 |
def get_verification_link(request):
"""
Computes the verification link
"""
verification = create_verification(request)
if type(verification) is not models.VerificationModel:
return None
else:
return "%s/%s/verify-link/?u=%s&c=%s" %(request.META["HTTP_HOST"], settings.AC... | 6d75c0025c0079aa46d66d3ed117739c4149c559 | 52,083 |
def mrp_shadow(mrpset):
"""return the shadow set of a given modified rodrigues parameter
set
:param mrpset: modified rodrigues parameter set
:return: shadow set of the given MRP set
"""
return np.array([-s/(np.linalg.norm(mrpset)**2) for s in mrpset]) | a7cee1e83c75e252e7cbf955859050dd8c658eae | 52,084 |
def upper_char(c):
"""Return the uppercase version of the character in the current locale."""
return chr(_toupper(ord(c))) | 6e800b61bf19d6cf7987c9f75166e1435c6bdced | 52,085 |
def _create_fig(n_cols, n_rows, figname, wrap_col=5, w_plot=5, h_plot=3):
"""Create a figure with subplots
Parameters
----------
n_cols, n_rows: int, number of rows and column in the plot
figname: str, name of the figure window
wrap_col: int, if only 1 row is present, wrap the columns
w_plo... | 88dad78018869bee4f275f30d481b49ad5f361a6 | 52,086 |
import os
def ipat(pat):
"""Convert glob pattern to case insensitive form."""
(dirname, pat) = os.path.split(pat)
# Convert '/path/to/test.fpt' => '/path/to/[Tt][Ee][Ss][Tt].[]'
newpat = ''
for c in pat:
if c.isalpha:
u = c.upper()
l = c.lower()
if u !... | 54beee120463f10a8950326c512839c18ca063a6 | 52,087 |
def incomplete_mat_mult_bsr(*args):
"""
incomplete_mat_mult_bsr(int Ap, int Aj, float Ax, int Bp, int Bj, float Bx,
int Sp, int Sj, float Sx, int n_brow, int n_bcol,
int brow_A, int bcol_A, int bcol_B)
incomplete_mat_mult_bsr(int Ap, int Aj, double Ax, int Bp, int Bj, double Bx,
int... | 3bc561d7dfc9be68ad9610ea8daf0ab944bef6b8 | 52,088 |
def write_sorted_dca_scores(file_name, sorted_DI, metadata=None, score_type = None):
"""Writes sorted direct information to file.
Parameters
----------
file_name : str
Path to file where DCA data is going to be saved.
sorted_DI : list
A list containing site pair
... | ce9c368c63a96f7b3f36d34f27db9937aa7b7a3d | 52,089 |
import os
def get_fit_entries(path, model_type, num_best):
"""Get entries to insert into the Fit() table, describing the fitted models of a certain model type."""
data = []
for idx in range(num_best):
df = pd.read_csv(os.path.join(path, path_args.fname_best_csv))
run_no = int(df.iloc[idx][... | 4f7a858991c0e606deec87db3cab24cf16aadab1 | 52,090 |
def RemoveIssuerCertsFromKeychain(issuer_cn, keychain=login_keychain, gui=False,
password=None):
"""Removes all certificates issued from a given CN from the keychain.
DeleteCert tries to raise privileges to allow deletions from the System
keychain, so we try and log if it fails.... | fe3e56046aae2c3abef41f6a73546fc9cd2cf84e | 52,091 |
def GetMonthList():
"""
Get a list of the defined month names.
rtype: `list`
"""
monthlist = []
for i in range(13):
name = Month[i]
if name is not None:
monthlist.append(name)
return monthlist | bba7530335d4e4f4a5e7c5029ff7ebac6d07326f | 52,092 |
def get_absolute_url(url, endpoint=None):
"""
Returns the absolute url based on the url and endpoint
Args:
url (str): base url with domain (e.g. https://domain.com)
endpoint (str): link to convert to an absolute url (e.g. /image.png)
"""
endpoint = endpoint.replace('%... | d6b1334dd24d66a1168427a3cfefc35cfe375594 | 52,093 |
import time
async def do_task() -> Response:
"""Run a task with celery workers
Returns:
A response with the results in the payload
"""
s = time()
job = group(tasks.send_task('add.two',args=[i,i]) for i in range(100))
result = job.apply_async()
# result.ready()
res = resu... | cd7bb1fc9244b7f915a08a29d72f1f4a98af6ba2 | 52,094 |
from re import A
def get_validation_augmentation():
"""Add paddings to make image shape divisible by 32"""
test_transform = [
A.PadIfNeeded(384, 160)
]
return A.Compose(test_transform) | 87f3a284ba2ccafc4e8d112fafad94cc0de092a7 | 52,095 |
def lnlike_0(ts, ys, yivars, deltanu, nupeak, K, numax, Lambda0, H, Gamma):
"""Log Likelihood for a comb of K frequencies centered on nupeak and separated by deltanu (solves for the amplitudes)"""
assert len(ts) == len(ys)
halfK = (K - 1) // 2
thisK = 2 * halfK + 1
M = np.zeros((len(t... | 611d473d7d80c5a463c9f0dd0cb386a8b3147709 | 52,096 |
def find_dpid_port_by_ip(ip):
"""
finds dpid and port in which IP is located
"""
p = [(x['dpid'],x['port']) for x in core.discovery.gmat if x['ip'] == ip]
if not p:
return (None, None)
else:
return p.pop() | 6454b725a386412334a73a2c9facfc28ed5c3395 | 52,097 |
import torch
def model_summarize(model, show_weights=True, show_parameters=True):
"""Summarizes torch model by showing trainable parameters and weights."""
tmpstr = model.__class__.__name__ + ' (\n'
params_num = 0
for key, module in model._modules.items():
# if it contains layers let call it r... | 080b9ece46d0769c62b236ae7c1863a42a0aeabb | 52,098 |
def gamedvr_record(console):
"""
Default to record last 60 seconds
Adjust with start/end query parameter
(delta time in seconds)
"""
try:
start_delta = request.args.get('start', -60)
end_delta = request.args.get('end', 0)
console.dvr_record(int(start_delta), int(end_delta... | 58114dd64aae01b30bcaee6cf3298283a3777ebf | 52,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.