content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import socket
def _get_ip():
"""
:return: This computer's default AF_INET IP address as a string
"""
# find ip using answer with 75 votes
# https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib
ip = ''
sock = socket.socket(socket.AF_INET, socket.SOCK_D... | f39c961877a1ec026596a7ced01679411962fca4 | 3,638,912 |
def _get_value(cav, _type):
"""Get value of custom attribute item"""
if _type == 'Map:Person':
return cav["attribute_object"]["id"] \
if cav.get("attribute_object") else None
if _type == 'Checkbox':
return cav["attribute_value"] == '1'
return cav["attribute_value"] | c8210579cf8b2a29dffc1f28a6e204fc9f89f274 | 3,638,913 |
def get_inference(model, vectorizer, topics, text, threshold):
"""
runs inference on text input
paramaters
----------
model: loaded model to use to transform the input
vectorizer: instance of the vectorizer e.g TfidfVectorizer(ngram_range=(2, 3))
topics: the list of topics in the model
... | e48ba018d372de317dd79fb678d69d2c83b4787b | 3,638,914 |
def get_message_id(update: dict, status_update: str) -> int:
"""функция для получения номера сообщения.
Описание - функция получает номер сообщения от пользователя
Parameters
----------
update : dict
новое сообщение от бота
status_update : str
состояние сообщения, изменено или ... | 9b299c94e322ad9cea92fd73cb9e7a55f3364caa | 3,638,915 |
def gmm_clustering_predict(model, X):
"""
X is a (N, 1) array
"""
X = np.clip(X, -2.5, 2.5)
return model.predict(X) | 9dcff9aa68fe008713dbb5142e16702bb68f65a0 | 3,638,916 |
import requests
def http_request(url, method='GET', timeout=2, **kwargs):
"""Generic task to make an http request."""
headers = kwargs.get('headers', {})
params = kwargs.get('params', {})
data = kwargs.get('data', {})
request_kwargs = {}
if headers:
request_kwargs['headers'] = headers
... | f7605d5b88bb7e23a1b541b7103185d229427270 | 3,638,917 |
from typing import Type
def unify_nest(args: Type[MultiNode], kwargs: Type[MultiNode], node_str, mode, axis=0, max_depth=1):
"""
Unify the input nested arguments, which consist of sub-arrays spread across arbitrary nodes, to unified arrays
on the single target node.
:param args: The nested positional... | 392491382b31c566db7eb8b13a98001158d8153a | 3,638,918 |
def ast_for_inv_exp(inv: 'Ast', ctx: 'ReferenceDict'):
"""
invExp ::= atomExpr (atomExpr | invTrailer)*;
"""
assert inv.name is UNameEnum.invExp
atom_expr, *inv_trailers = inv
res = ast_for_atom_expr(atom_expr, ctx)
if len(inv_trailers) is 1:
[each] = inv_trailers
if each.n... | 77de8d7c1fd5dfc4a8fefa04ee6c0a5da17a6bc1 | 3,638,919 |
def create_input_pipeline(files,
batch_size,
n_epochs,
shape,
crop_shape=None,
crop_factor=1.0,
n_threads=2):
"""Creates a pipefile from a list of image files.
... | 17c26de3659cccd7e32d8297ed0e31167ef05c38 | 3,638,920 |
def confirm_email_page():
"""Returns page for users that have not confirmed their
email address"""
if not g.loggedIn:
return redirect(url_for('general.loginPage'))
next = request.args.get('next')
if general_db.is_activated(g.user):
if next is not '':
return make_auth_to... | e37c59e9f1fa1d710d2795257be1cfb8bc9aa3df | 3,638,921 |
from bs4 import BeautifulSoup
def get_movie_names(url_data):
"""Get all the movies from the webpage"""
soup = BeautifulSoup(url_data, 'html.parser')
data = soup.findAll('ul', attrs={'class' : 'ctlg-holder'}) #Get all the lines from HTML that are a part of ul with class = 'ctlg-holder'
movie_list... | 1cae6b0093f0e0ca9e361bdc207be9ea654e7c2b | 3,638,922 |
def message_results():
"""Shows the user their message, with the letters in sorted order."""
message = request.form.get('message')
encrypted_message = sort_letters(message)
return render_template('message_results.html', message=encrypted_message) | 8e0868330c318c958da496a742f630583822bbd0 | 3,638,923 |
def flatten_dict(dicts, keys):
"""
Input is list of dicts. This operation pulls out the key in each dict and combines the values into a new list mapped to the original key. A new dictionary is formed with these key -> list mappings.
"""
return {
key: flatten_n([d[key] for d in dicts])
fo... | ca037e47e2e6287145da693cd55f47719d463115 | 3,638,924 |
def render_url(fullpath, notebook=False): # , prefix="files"):
"""Converts a path relative to the notebook (i.e. kernel) to a URL that
can be served by the notebook server, by prepending the notebook
directory"""
if fullpath.startswith('http://'):
url = fullpath
else:
url = (radiopad... | ee401c4521cf93fe4ec95b2d3c1fb7dbe337ff52 | 3,638,925 |
def register():
"""Register User route."""
email = request.form.get('email')
password = request.form.get('password')
new_user = User.register(email, password)
if new_user:
return jsonify({'message': 'Registration successful.'}), 201
return jsonify({'message': 'Invalid username or passwor... | a6148b514268e36fc28a69737718598fcc355460 | 3,638,926 |
import json
def route_sns_task(event, context):
"""
Gets SNS Message, deserialises the message,
imports the function, calls the function with args
"""
record = event['Records'][0]
message = json.loads(
record['Sns']['Message']
)
return run_message(message) | 1e7c8f774f62cddf633e51d631f74cad3fa1ec8e | 3,638,927 |
def release_dp_mean_absolute_deviation(x, bounds, epsilon):
"""Release the dp mean absolute deviation.
Assumes dataset size len(`x`) is public.
Theorem 27: https://arxiv.org/pdf/2001.02285.pdf
"""
lower, upper = bounds
sensitivity = (upper - lower) * 2. / len(x)
x = np.clip(x, *bounds)
... | da49088e52fcd0ccf8358db072354fcd39de565e | 3,638,928 |
def LoadScores(firstfile, prevfile):
"""Load the first and previous scores. For each peptide, compute a prize
that is -log10(min p-value across all time points). Assumes the scores
are p-values or equivalaent scores in (0, 1]. Do not allow null or missing
scores.
Return: data frame with scores a... | b6a0d9769795937a21aee195d782060db73ec494 | 3,638,930 |
def _gen_find(subseq, generator):
"""Returns the first position of `subseq` in the generator or -1 if there is no such position."""
if isinstance(subseq, bytes):
subseq = bytearray(subseq)
subseq = list(subseq)
pos = 0
saved = []
for c in generator:
saved.append(c)
if le... | ec89e787a61d684e2a7d0c8c2d0fb9c89cf73ada | 3,638,932 |
def all_permits(target_dynamo_table):
"""
Simply return all data from DynamoDb Table
:param target_dynamo_table:
:return:
"""
response = target_dynamo_table.scan()
data = response['Items']
while response.get('LastEvaluatedKey', False):
response = target_dynamo_table.scan(Exclusi... | 8efdaf4ff407d0e2ce8dd592eeac766b0ec2264b | 3,638,934 |
def maximum_difference_sort_value(contributions):
"""
Auxiliary function to sort the contributions for the compare_plot.
Returns the value of the maximum difference between values in contributions[0].
Parameters
----------
contributions: list
list containing 2 elements:
a Numpy.... | cd7f66ec252199fb01b9891440d0f7da370c7b8e | 3,638,935 |
def get_primer_target_sequence(id, svStartChr, svStartPos, svEndChr, svEndPos, svType, svComment, primerTargetSize, primerOffset, blastdbcmd, genomeFile):
"""Get the sequences in which primers will be placed"""
if svType in ["del", "inv3to3", "trans3to3", "trans3to5", "snv", "invRefA", "invAltA"]:
targe... | b8b32319d6a37a2373a620b1be867ab838c54fdc | 3,638,937 |
def human_format(num):
"""
:param num: A number to print in a nice readable way.
:return: A string representing this number in a readable way (e.g. 1000 --> 1K).
"""
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0
return '%.2f%s' % (num, ['', 'K', 'M', 'G... | 41e4f3823f756588c18b0fb926949a5aca9c6942 | 3,638,938 |
from typing import Optional
from typing import Dict
def torchserve(
model_path: str,
management_api: str,
image: str = TORCHX_IMAGE,
params: Optional[Dict[str, object]] = None,
) -> specs.AppDef:
"""Deploys the provided model to the given torchserve management API
endpoint.
>>> from torch... | b90ec26512525e3f23a54034a685be380ef0be96 | 3,638,939 |
def ExpandRange(r,s=1):
"""expand 1-5 to [1..5], step by 1-10/2"""
if REGEX_PATTERNS['step'].search(r):
[r1,s] = r.split('/')
s=int(s)
else:
r1 = r
(start,end) = r1.split('-')
return [i for i in range(int(start),int(end)+1,s)] | 1e8ca3b5b026c36817acfefd1666312b0bcccf23 | 3,638,940 |
def write_file_if_changed(name, data):
""" Write a file if the contents have changed. Returns True if the file was written. """
if path_exists(name):
old_contents = read_file(name)
else:
old_contents = ''
if (data != old_contents):
write_file(name, data)
return True
return False | 42962e9f9159d8cab121826e223bfa10467b8d5c | 3,638,941 |
def _get_preprocessor_loader(plugin_name):
"""Get a class that loads a preprocessor class.
This returns a class with a single class method, ``transform``,
which, when called, finds a plugin and defers to its ``transform``
class method. This is necessary because ``convert()`` is called as
a decorato... | 5b2c1687be92b21f31c0e9e28a3566505831c876 | 3,638,942 |
def preprocess_sample(data, word_dict):
"""
Args:
data (dict)
Returns:
dict
"""
processed = {}
processed['Abstract'] = [sentence_to_indices(sent, word_dict) for sent in data['Abstract'].split('$$$')]
if 'Task 2' in data:
processed['Label'] = label_to_onehot(data['Task... | 0b1b50285be0afa1faf78917024b1e2cd01fb167 | 3,638,943 |
import yaml
import torch
def read_input_file(input_file_path):
"""
read inputs from input_file_path
:param input_file_path:
:return:
"""
cprint('[INFO]', bc.dgreen, "read input file: {}".format(input_file_path))
with open(input_file_path, 'r') as input_file_read:
dl_inputs = yaml.l... | ade3584937997798b496690d5799e23effae1cd1 | 3,638,944 |
def plugin(version: str) -> 'Plugin':
"""Get the application plugin."""
return XPXPlugin | 8211b8b3f2aaedbbfe289184117e6964fad5cce5 | 3,638,946 |
def is_anaconda_5():
"""
anaconda 5 has conda version 4.4.0 or greater... obviously :/
"""
vers = conda_version()
if not vers:
return False
ma = vers['major'] >= 4
mi = vers['minor'] >= 4
return ma and mi | cc4701bb788867a6370c53b48994c166dffa7cd4 | 3,638,947 |
def relay_array_map(c, fn, *array):
"""Implementation of array_map for Relay."""
assert fn.is_constant(Primitive)
fn = fn.value
if fn is P.switch:
rfn = relay.where
else:
rfn = SIMPLE_MAP[fn]
return rfn(*[c.ref(a) for a in array]) | 8d3d89ea131272f987054c198353ec7fc398e4a0 | 3,638,948 |
def get_multi_objects_dict(*args, params=None):
"""Convertir un array de objetos en diccionarios"""
object_group = []
result = {}
for data_object in args:
if params is not None and params['fields']:
fields = params['fields']
else:
fields = [attr for attr in data_o... | 2f4e2bc6e68bc77fedfae89ff4562cdab5fa91fb | 3,638,949 |
from btu.manual_tests import ping_now
def test_function_ping_now_bytes():
"""
Picking the 'ping_now' function and return as bytes.
"""
queue_args = {
"site": frappe.local.site,
"user": frappe.session.user,
"method": ping_now,
"event": None,
"job_name": "ping_now",
"is_async": True, # always true; we... | 0673efa3ff11aa9b55b470c4ac84a35f7878af98 | 3,638,950 |
def post_equals_form(post, json_response):
"""
Checks if the posts object is equal to the json object
"""
if post.title != json_response['title']:
return False
if post.deadline != json_response['deadline']:
return False
if post.details != json_response['details']:
retu... | 965a533c7ebbb70001bcdcb0e143b617708807e3 | 3,638,951 |
def get_shield(plugin: str) -> dict:
"""
Generate shield json for napari plugin.
If the package is not a valid plugin, display 'plugin not found' instead.
:param plugin: name of the plugin
:return: shield json used in shields.io.
"""
shield_schema = {
"color": "#0074B8",
"la... | f1c7dadabd0b5fe6b1b0012188559b4958ca5fd0 | 3,638,952 |
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == expectedUN and password == expectedPW | e19759a1514fad47a085e3dad2180c5b8b49827c | 3,638,953 |
def Lambda(t, y):
"""Original Arnett 1982 dimensionless bolometric light curve expression
Calculates the bolometric light curve due to radioactive decay of 56Ni,
assuming no other energy input.
t: time since explosion in days
y: Arnett 1982 light curve width parameter (typical 0.7 <... | 85752fa09f1189ca7e24a32d821e36c58379572d | 3,638,954 |
from datetime import datetime
def get_utcnow_time(format: str = None) -> str:
"""
Return string with current utc time in chosen format
Args:
format (str): format string. if None "%y%m%d.%H%M%S" will be used.
Returns:
str: formatted utc time string
"""
if format is None:
... | 994e47abde4a4b56bd0f22ccc41d7d91c7b3b8d0 | 3,638,955 |
def repair_branch(cmorph, cut, rmorph, rep, force=False):
"""Attempts to extend cut neurite using intact branch.
Args:
cmorph (treem.Morph): cut morphology.
cut (treem.Node): cut node, from cmorph.
rmorph (treem.Morph): repair morphology.
rep (treem.Node): undamaged branch start... | 1e76ec2619f1b74791c1258c65c649c25261a740 | 3,638,956 |
def us2cycles(us):
"""
Converts microseconds to integer number of tProc clock cycles.
:param cycles: Number of microseconds
:type cycles: float
:return: Number of tProc clock cycles
:rtype: int
"""
return int(us*fs_proc) | 51d405c512c146bdfda0a091470ad84593872819 | 3,638,958 |
from datetime import datetime
def date_range(begin_date, end_date):
"""
获取一个时间区间的list
"""
dates = []
dt = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
date = begin_date[:]
while date <= end_date:
dates.append(date)
dt = dt + datetime.timedelta(1)
date = dt... | a3373ab76752423eaf1484e5d66dc5d6334c4360 | 3,638,959 |
def scalar(name):
"""
Create a scalar variable with the corresponding name. The 'name' will be during code generation, so should match the
variable name used in the C++ code.
"""
tname = name
return symbols(tname) | 8f1f7295d15b136be38383135729fe7717fd71b8 | 3,638,960 |
def add(number1, number2):
"""
This functions adds two numbers
Arguments:
number1 : first number to be passed
number2 : second number to be passed
Returns: number1*number2
the result of two numbers
Examples:
>>> add(0,0)
0
>>> add(1,1)
2
>>> add(1.1,2.2)
... | 5db1a461f65672d5fc1201a82657fada30220743 | 3,638,961 |
def calculate_timeout(start_point, end_point, planner):
"""
Calucaltes the time limit between start_point and end_point considering a fixed speed of 5 km/hr.
Args:
start_point: initial position
end_point: target_position
planner: to get the shortest part between start_point and ... | cb7ae44df9b6a89d2e171046fa0bdfe3f81445c5 | 3,638,962 |
def func_parallel(func, list_inputs, leave_cpu_num=1):
"""
:param func: func(list_inputs[i])
:param list_inputs: each element is the input of func
:param leave_cpu_num: num of cpu that not use
:return: [return_of_func(list_inputs[0]), return_of_func(list_inputs[1]), ...]
"""
cpu_cores = mp.c... | 4642149db87236b444e26515747a18ccbc420e64 | 3,638,964 |
def get_mean(jsondata):
"""Get average of list of items using numpy."""
if len(jsondata['results']) > 1:
return mean([float(price.get('price')) for price in jsondata['results'] if 'price' in price]) # key name from itunes
# [a.get('a') for a in alist if 'a' in a]
else:
return float(... | 63851f6e89bea230549975eba68391421b57f087 | 3,638,965 |
from typing import Dict
import torch
import time
def evaluate_with_trajectory(
sc_dataset: SingleCellDataset,
n_samples: int,
trajectory_type: str,
trajectory_coef: Dict,
types: DeconvolutionDatatypeParametrization,
deconvolution_params: Dict,
n_iters=5_000,
):
"""Evaluate L1_error and... | bb82164f4ec9d79bcc675be1612a61ff5b209752 | 3,638,966 |
def plot_diffraction_1d(result, deg):
"""
Returns this result instance in PlotData1D representation.
:param deg: if False the phase is expressed in radians, if True in degrees.
"""
# Distinguish between the strings "phase in deg" and "phase in rad".
if deg:
phase_string = "Phase in deg"
... | f316e1f02a5b5b295bfed22fc5307bcf908788c2 | 3,638,968 |
import logging
def prepare_go_environ():
"""Returns dict with environment variables to set to use Go toolset.
Installs or updates the toolset and vendored dependencies if necessary.
"""
bootstrap(LAYOUT, logging.INFO)
return get_go_environ(LAYOUT) | cf7d6ee594193317a1201beb127e607139fd367f | 3,638,969 |
def get_subnets(client, name='tag:project', values=[ec2_project_name,], dry=True):
"""
Get VPC(s) by tag (note: create_tags not working via client api, use cidr or object_id instead )
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_subnets
"""
... | 4504a37689bce171d3d62a3cf6f66365c58f56e8 | 3,638,970 |
import requests
def get_object_handler(s3_client, request_context, user_request):
"""
Handler for the GetObject Operation
:param s3_client: s3 client
:param request_context: GetObject request context
:param user_request: user request
:return: WriteGetObjectResponse
"""
# Validate user... | fc98197f99e8751976245902eb4034a5b4930d3b | 3,638,971 |
def decline_agreement(supplier_code):
"""Decline agreement (role=supplier)
---
tags:
- seller edit
parameters:
- name: supplier_code
in: path
type: number
required: true
responses:
200:
description: Agreement declined.
400:
... | fa7f2186af9f7beb2b138eab3347cd34580557f0 | 3,638,974 |
import torch
def load_model(model, model_path):
"""
Load model from saved weights.
"""
if hasattr(model, "module"):
model.module.load_state_dict(torch.load(model_path, map_location="cpu"), strict=False)
else:
model.load_state_dict(torch.load(model_path, map_location="cpu"), strict=... | 0fbf34548474c4af89c25806f05d1e7d3170bbde | 3,638,975 |
def get_file_size(filepath: str):
"""
Not exactly sure how os.stat or os.path.getsize work, but they seem to get the total allocated size of the file and
return that while the file is still copying. What we want, is the actual file size written to disk during copying.
With standard Windows file copyin... | 6936a8227a96e3ebc4b1146f8363f092d232cafd | 3,638,976 |
import json
def get_aws_regions_from_file(region_file):
"""
Return the list of region names read from region_file.
The format of region_file is as follows:
{
"regions": [
"cn-north-1",
"cn-northwest-1"
]
}
"""
with open(region_file) as r_file:
r... | 639da8c6417295f97621f9fd5321d8499652b7b2 | 3,638,977 |
def item_pack():
""" RESTful CRUD controller """
s3db.configure("supply_item_pack",
listadd = False,
)
return s3_rest_controller() | e6bce829b441a08c98dc81fa6ac1ea432ef67c89 | 3,638,978 |
def inv_cipher(rkey, ct, Nk=4):
"""AES decryption cipher."""
assert Nk in {4, 6, 8}
Nr = Nk + 6
rkey = rkey.reshape(4*(Nr+1), 32)
ct = ct.reshape(128)
# first round
state = add_round_key(ct, rkey[4*Nr:4*(Nr+1)])
for i in range(Nr-1, 0, -1):
state = inv_shift_rows(state)
... | 477b32450b4fef060f936952d0af3115ca4b8add | 3,638,979 |
def _ptrarray_to_list(ptrarray):
"""Converts a ptr_array structure from SimpLL into a Python list."""
result = []
for i in range(0, ptrarray.len):
result.append(ptrarray.arr[i])
lib.freePointerArray(ptrarray)
return result | 430c26f15ee41dbf5b4bdf562dd81c0167eead18 | 3,638,981 |
from typing import Callable
def endpoint(path: str) -> Callable[[], Endpoint]:
"""Decorator for creating an
Arguments:
path: The path to the API endpoint (relative to the API's
``base_url``).
Returns:
The wrapper for the endpoint method.
"""
def wrapper(method):
retu... | 1a0b9b836630f1ab4eea902861899c50303aa539 | 3,638,983 |
def from_string_to_bytes(a):
"""
Based on project: https://github.com/chaeplin/dashmnb.
"""
return a if isinstance(a, bytes) else bytes(a, 'utf-8') | e76509f1be8baf8df0bf3b7160615f9a9c04ff86 | 3,638,984 |
def split(x, divider):
"""Split a string.
Parameters
----------
x : any
A str object to be split. Anything else is returned as is.
divider : str
Divider string.
"""
if isinstance(x, str):
return x.split(divider)
return x | e77a162777d9bb13262e4686ba1cb9732ebab221 | 3,638,985 |
def despesa_update(despesa_id):
"""
Editar uma despesa.
Args:
despesa_id (int): ID da despesa a ser editada.
Lógica matemática é chamada de utils.py: adicionar_registro()
Returns:
Template renderizado: despesa.html
Redirecionamento: aplication.transacoes
"""
desp... | bd848eacc19144c40822a7389ceecdae4f5c5532 | 3,638,986 |
def _convert_format(partition):
"""
Converts the format of the python-louvain into a numpy array
Parameters
----------
partition : dict
Standard output from python-louvain package
Returns
-------
partition: np.array
Partition as a numpy array
"""
return np.arra... | 5afffe9745c0083829a2ce88f5842b295583e737 | 3,638,987 |
def settingsdir():
"""In which directory to save to the settings file"""
return module_dir()+"/settings" | ac485b7d947cfa051adc9eeed6f194b9746d8401 | 3,638,988 |
from typing import Dict
from typing import List
import copy
def run_range_mcraptor(
timetable: Timetable,
origin_station: str,
dep_secs_min: int,
dep_secs_max: int,
max_rounds: int,
) -> Dict[str, List[Journey]]:
"""
Perform the McRAPTOR algorithm for a range query
"""
# Get stops... | d09a85fbe5f3e1a8e3081037e195298aed6e5fc8 | 3,638,990 |
def _choose_node_type(w_operator, w_constant, w_input, t):
"""
Choose a random node (from operators, constants and input variables)
:param w_operator: Weighting of choosing an operator
:param w_constant: Weighting of choosing a constant
:param w_input: Weighting of cho... | 7517d347b97bce2748e4ccd45a5f25120e074e9d | 3,638,991 |
def _plat_idx_to_val(idx: int , edge: float = 0.5, FIO_IO_U_PLAT_BITS: int = 6, FIO_IO_U_PLAT_VAL: int = 64) -> float:
""" Taken from fio's stat.c for calculating the latency value of a bin
from that bin's index.
idx : the value of the index into the histogram bins
edge : fractiona... | f992194492e031add3d14f0e145888303a5b4f06 | 3,638,994 |
def is_blank(value):
"""
Returns True if ``value`` is ``None`` or an empty string.
>>> is_blank("")
True
>>> is_blank(0)
False
>>> is_blank([])
False
"""
return value is None or value == "" | 6a30f9f6726701a4b7a9df8957503111a5222558 | 3,638,995 |
def overload_check(data, min_overload_samples=3):
"""Check data for overload
:param data: one or two (time, samples) dimensional array
:param min_overload_samples: number of samples that need to be equal to max
for overload
:return: overload status
"""
if data.n... | 9c59bb2e105828afd93af193949a2ad01a34a32e | 3,638,996 |
import socket
import time
def send_packet_to_capture_last_one():
"""
Since we read packets from stdout of tcpdump, we do not know when a packet is finished
Hence you should send an additional packet after you assume all interesting packets were sent
"""
def send():
conf = get_netconfig()
... | 984848ec685273d97630dd6a95d93c939665969e | 3,638,997 |
from typing import Callable
from pathlib import Path
from typing import Iterable
from typing import Optional
import signal
import random
def diss(
demos: Demos,
to_concept: Identify,
to_chain: MarkovChainFact,
competency: CompetencyEstimator,
lift_path: Callable[[Path], Path] = lambda x: x,
n... | 016af4c38a890426fa148af78e1349b6bacdfa79 | 3,638,998 |
def expand_gelu(expand_info):
"""Gelu expander"""
# get op info.
input_desc = expand_info['input_desc'][0]
graph_builder = builder.GraphBuilder()
# generate a graph.
with graph_builder.graph_scope('main') as graph_scope:
# create tensor input.
input_x = graph_builder.tensor(inp... | 1237d4899ef0411b827efd930fb7e2e0fa5fddde | 3,638,999 |
def cache_mixin(cache, session):
"""CacheMixin factory"""
hook = EventHook([cache], session)
class _Cache(CacheMixinBase):
_hook = hook
_cache_client = cache
_db_session = session
return _Cache | 79368b4cc2680ff95be520c9d877dcca5a6a1eef | 3,639,000 |
def _read_output(path):
"""Read CmdStan output csv file.
Parameters
----------
path : str
Returns
-------
Dict[str, Any]
"""
# Read data
columns, data, comments = _read_output_file(path)
pconf = _process_configuration(comments)
# split dataframe to warmup and draws
... | aba1fe156de9f2fe9f595d5e5e64994b9eab539b | 3,639,001 |
def linear_chance_constraint_noinit(a,M,N,risk,num_gpcpoly,n_states,n_uncert,p):
"""
Pr{a^\Top x + b \leq 0} \geq 1-eps
Converts to SOCP
"""
a_hat = np.kron(a.T,M)
a_dummy = np.zeros((n_states,n_states))
for ii in range(n_states):
a_dummy[ii,ii] = a[ii,0]
#print(a_dummy)
... | 9b6421213f3f2251824a45fc04b69146cfeebbaa | 3,639,002 |
import fastapi
def patroni(response: responses.Response,
session: sqlalchemy.orm.Session = fastapi.Depends(models.patroni.get_session)):
"""
Returns a health check for the reachability of the Patroni database.
"""
return db_health(response, session, 'Patroni') | fabaf09e2754e0e89ff17312e9a3f86d48972dc0 | 3,639,003 |
def authorization_code_grant_step1(request):
"""
Code grant step1 short-cut. This will return url with code.
"""
django_request = oauth2_request_class()(request)
grant = CodeGrant(oauth2_server, django_request)
return grant.authorization() | 5227158127b5313b17c27fb0f351f8294faec840 | 3,639,004 |
async def activity(
guild_id: int,
discord_id: int,
activity_input: DestinyActivityInputModel,
db: AsyncSession = Depends(get_db_session),
):
"""Return information about the user their stats in the supplied activity ids"""
user = await discord_users.get_profile_from_discord_id(discord_id)
... | 25a2eb719648cbdb6161baa2b1de1570e07a42ea | 3,639,005 |
def put_topoverlays(image, rects, alpha=0.3):
"""
a function for drawing some rectangles with random color
Args:
image: an opencv image with format of BGR
rects: a list of opencv rectangle
alpha: a float, blend level
Return:
An opencv image
"""
h, w, _ = image.shape
im = np.ones(shape=image... | 9f6cf0cfd33214503905a16384fade2976bad190 | 3,639,006 |
def extract_next_token(link):
"""Use with paginated endpoints for extracting
token which points to next page of data."""
clean_link = link.split(";")[0].strip("<>")
token = clean_link.split("?token=")[1]
# token is already quoted we have to unqoute so it can be passed to params
return unquote(t... | f0eae72cf8d99e816dfff1c6345f0a9b73abdd21 | 3,639,007 |
import urllib
import json
def get_host_country(host_ip):
"""Gets country of the target's IP"""
country = 'NOT DEFINED'
try:
response_body = urllib.request.urlopen(f'https://ipinfo.io/{host_ip}').read().decode('utf8')
response_data = json.loads(response_body)
country = response_data... | 05df2c54dd275c654631cb188cbfdaa0d8e15ed9 | 3,639,008 |
import traceback
def astng_wrapper(func, modname):
"""wrapper to give to ASTNGManager.project_from_files"""
print 'parsing %s...' % modname
try:
return func(modname)
except ASTNGBuildingException, exc:
print exc
except Exception, exc:
traceback.print_exc() | fbb1b3090bfc7b93258fbbcefea1a8d1463dded2 | 3,639,009 |
def clean(s):
"""Clean text!"""
return patList.do(liblang.fixRepetedVowel(s)) | d81f16dfb35b4f218af5017de1eef8a005d3e7de | 3,639,010 |
def elastic_transform(image, alpha=1000, sigma=30, spline_order=1, mode='nearest', random_state=np.random):
"""Elastic deformation of image as described in [Simard2003]_.
.. [Simard2003] Simard, Steinkraus and Platt, "Best Practices for
Convolutional Neural Networks applied to Visual Document Analysis", ... | ddabb6a15deba901398f799352216b2c89652296 | 3,639,012 |
import json
def format_search_log(json_string):
"""
usage example {{ model_object|format_search_log }}
"""
query_json = json.loads(json_string)
attributes_selected = sorted(query_json.get('_source'))
context = {}
context['attributes_selected'] = attributes_selected
return attributes... | eb5aa21590474acaee7b2b94a1cfdc52c080d017 | 3,639,013 |
def set_variable(value,variable=None):
"""Load some value into session memory by creating a new variable.
If an existing variable is given, load the value into the given variable.
"""
sess = get_session()
if variable is not None:
assign_op = tf.assign(variable,value)
sess.run([assign... | 8256a27c2a446e600e6cfe818c5e4c60e18f1d04 | 3,639,014 |
def matrix ( mtrx , i , j ) :
"""Get i,j element from matrix-like object
>>> mtrx = ...
>>> value = matrix ( m , 1 , 2 )
"""
if isinstance ( mtrx , ROOT.TMatrix ) :
if i < mtrx.GetNrows () and j < mtrx.GetNcols () :
return mtrx ( i , j )
if callable ( mtrx ) :
... | 1101d5bd4bf569f11ec7ee41700171906e58e743 | 3,639,015 |
def check_type(instance, *classes):
"""Check if object is instance of given class"""
for klass in classes:
if type(instance).__name__ == klass:
return True
for T in getmro(type(instance)):
if T.__name__ == klass:
return True
return False | 1761be42fd1a781ef5b6d94b42006fdcb2789e8b | 3,639,016 |
def test_get_earth_imperative_solution(solar_system):
"""
## Imperative Solution
The first example uses flow control statements to define a
[Imperative Solution]( https://en.wikipedia.org/wiki/Imperative_programming). This is a
very common approach to solving problems.
"""
def get_planet... | f966886e3384547803106c404a21e2bb7ecd8fa9 | 3,639,017 |
import glob
import tqdm
def animate(map, time, phase0=0.0, res=75, interval=75):
"""
"""
# Load the SPICE data
ephemFiles = glob.glob('../data/TESS_EPH_PRE_LONG_2018*.bsp')
tlsFile = '../data/tess2018338154046-41240_naif0012.tls'
solarSysFile = '../data/tess2018338154429-41241_de430.bsp'
... | 0fa39a0299a8d8cd75b0475f45e49caa731925a7 | 3,639,019 |
def bresenham(points):
""" Apply Bresenham algorithm for a list points.
More info: https://en.wikipedia.org/wiki/Bresenham's_line_algorithm
# Arguments
points: ndarray. Array of points with shape (N, 2) with N being the number
if points and the second coordinate representing the (x, y)
... | 9c49edd9eda3113855582ec3cc35c4d40d056dd9 | 3,639,021 |
def radialBeamProfile_flatTop(x,y,a):
"""Top hat beam profile
\param[in] x x-position for profile computation
\param[in] y y-position for profile computation
\param[in] a radial extension of flat-top component
\param[in] R 1/e-width of beam profile
\param[ou... | 699d214c499d8cbcf1c0ed26a5d0d00cf2813f3f | 3,639,022 |
def _split_data(x, y, k_idx, k, perm_indices):
"""Randomly and coordinates splits two indexable items.
Splits items in accordiance with k-fold cross-validatoin.
Arguments:
x: [?]
indexable item
y: [?]
indexable item
k_idx: int
index of the k-fold... | 7e53d6a172335b7777887ed493ec41ecb6833461 | 3,639,023 |
from typing import Any
from typing import Optional
def resolve_Log(
parent: Any,
info: gr.ResolveInfo,
id: Optional[int] = None,
uuid: Optional[str] = None,
) -> ENTITY_DICT_TYPE:
"""Resolution function."""
return resolve_entity(Log, info, id, uuid) | eecd46296e9d1c0ce55dc31ee1249b4c3b512b15 | 3,639,025 |
from typing import Union
from pathlib import Path
def _get_path_size(source: Union[Path, ZipInfo]) -> int:
"""
A helper method that returns the file size for the given source
:param source: the source object to get the file size for.
:return: the source's size.
"""
return source.stat().st_siz... | 2981b2b88e776cfd2315785fea8ba1e1ec63c7cf | 3,639,026 |
def get_graph_subsampling_dataset(
prefix, arrays, shuffle_indices, ratio_unlabeled_data_to_labeled_data,
max_nodes, max_edges,
**subsampler_kwargs):
"""Returns tf_dataset for online sampling."""
def generator():
labeled_indices = arrays[f"{prefix}_indices"]
if ratio_unlabeled_data_to_labeled_d... | da31aff7064c3516f95fb5597f2ee757ee35fa25 | 3,639,027 |
def check_comment_exists(comment_id_required=True):
"""
Decorator to check if a given comment exists. If it does not, it returns an
HTTP 400 error. Must be called with (), and may pass the optional argument
of whether the id is required. If the id is passed, it will be checked
against entities of... | 2c2dd4bd1149ee9f0e87b5d426211a3d5bba78c0 | 3,639,028 |
def GeoMoonState(time):
"""Calculates equatorial geocentric position and velocity of the Moon at a given time.
Given a time of observation, calculates the Moon's position and velocity vectors.
The position and velocity are of the Moon's center relative to the Earth's center.
The position (x, y, z) comp... | 50c523a2f838e7730546fac4e4b8ed2a13eefe0a | 3,639,029 |
import platform
def get_machine_name():
"""
Portable way of calling hostname shell-command.
Regarding docker containers:
NOTE: If we are running from inside the docker-dev environment, then $(hostname) will return
the container-id by default.
For now we leave that behaviour.
We ... | ae5a7090846164a97cafd07af4701dcfcc25070e | 3,639,030 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.