content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def imei_parse_nibble(nibble):
"""Parse one nibble of an IMEI and return its ASCII representation."""
if nibble < 10:
return chr(nibble + ord('0'))
if nibble == 0xa:
return '*'
if nibble == 0xb:
return '#'
if nibble == 0xc:
return 'C'
if nibble == 0xd:
ret... | 837445a7679bc5355978d7d4e69c5c9fa166cb3f | 3,628,100 |
def check_command_succeeded(reply):
"""
Return true if command succeeded, print reason and return false if command
rejected
param reply: BinaryReply
return: boolean
"""
if reply.command_number == 255: # 255 is the binary error response code.
print ("Danger! Command reject... | a320b5000f59790e314108398339b9a66dbf6520 | 3,628,101 |
def format_interval(seconds):
""" Format an integer number of seconds to a human readable string."""
units = [
(('week', 'weeks'), 604800),
(('day', 'days'), 86400),
(('hour', 'hours'), 3600),
(('minute', 'minutes'), 60),
#(('second', 'seconds'), 1)
]
result = []
... | 8deae4627807f4c5e0cc1844499ebb39f658f2d0 | 3,628,102 |
def make_arguments_parser():
"""Build and return a command line agument parser."""
parser = ArgumentParser(description=__doc__, epilog="""CSS-HTML-JS-Minify:
Takes a file or folder full path string and process all CSS/HTML/JS found.
If argument is not file/folder will fail. Check Updates works on Python... | 5acdc6c18edaad874f9a0f3328545c57028ceaa4 | 3,628,103 |
def split_on_comma(tokens):
"""Split a list of tokens on commas, ie ``,`` DELIM tokens.
Only "top-level" comma tokens are splitting points, not commas inside a
function or other :class:`ContainerToken`.
:param tokens:
An iterable of :class:`~.token_data.Token` or
:class:`~.token_data.C... | 8b89dc6857a7b3e9bcc02f3a291e0ff0cd8d5f20 | 3,628,104 |
def filter_grps(grps, rcs, irr_col, low, high, **kwargs):
"""
Apply irradiance filter around passsed reporting irradiances to groupby.
For each group in the grps argument the irradiance is filtered by a
percentage around the reporting irradiance provided in rcs.
Parameters
----------
grps ... | 772600b5d6f9d35c4751db6a566b4d886b2790de | 3,628,105 |
from readDB import query_plug_set
async def get_weapon_plug_hashes(perk_socket_set: SocketSet) -> list[PerkColumn]:
"""
get perks for all random and origin perk sockets
:param perk_socket_set: weapon's perk sockets
:return: weapon perks as List of PerkColumn
"""
plug_sets: list[PlugSet] = []
... | 9a66c742ce3ff1cf027585bcd6c360536da7d1c2 | 3,628,106 |
def export_inventory_information():
"""export the inventory search result to cvs, html or excel format."""
db_session = DBSession()
export_results_form = ExportInventoryInformationForm(request.form)
export_data = dict()
export_data['export_format'] = export_results_form.export_format.data
expor... | 5b517f9a195e595ef04410bb4aa11384b2c73729 | 3,628,107 |
from typing import Set
def decide_unsat(K: Set[CNFClause]) -> bool:
"""
Returns if given set of clauses is in CNF, or not
:param K: Set of Clauses in CNF
:return: bool, whether this formula is undecidable or not
"""
R: set[CNFClause] = set()
S: set[CNFClause] = K
while R != S:
... | 6a479d4f2017f7e60f03e9ef85064940bff6581a | 3,628,108 |
def find(db, user):
"""
find the notelist
:param db:
:param user:
:return:
"""
document = db.notelist.find_one({"_id": user})
return document | 04c6ad64e9b8ff2f5cd5462cebb9d37127b6d176 | 3,628,109 |
def clip(x, xmin, xmax, dtype=None):
"""
Clips (limits) the values in an array.
Given an interval, values outside the interval are clipped to the interval edges.
For example, if an interval of :math:`[0, 1]` is specified, values smaller than 0 become 0,
and values larger than 1 become 1.
Note:... | c99ba428593c589e6844cfd5e355d27cb36c5904 | 3,628,110 |
import math
def jump(distance, delta_piece_y):
"""
跳跃一定的距离
"""
# 计算程序长度与截图测得的距离的比例
scale = 0.945 * 2 / head_diameter
actual_distance = distance * scale * (math.sqrt(6) / 2)
press_time = (-945 + math.sqrt(945 ** 2 + 4 * 105 *
36 * actual_distance)) / (2 * ... | 45c7ade5213d7997a6742373fc92026ab56280b3 | 3,628,111 |
def get_mean_hourly_sleep_mr_df(sleep_profile, colnames):
"""
Creates summary df for mean hourly sleeping metabolic rate for each fly.
Exported as sheet to excel.
"""
mr_hourly = sleep_profile.iloc[:,1::3]
# sleep profile is split into top half: day; bottom half: night
night_bool_list = [x >... | 167c58bba7bc8e3a5e456a9c20d4a7a55ba722d0 | 3,628,112 |
import os
import fnmatch
def get_files_in_traverse_dir(a_dir, patterns):
# type: (str, str) -> List[str]
""" return list of all files in directory which matches 'patterns'
support Unix filename pattern matching ('*', '?', [seq], [!seq])
and multiple option in 'patterns' (space delimetered) """
re... | 6f2f1e16975019f90ee4a127fd5ea6614bc1942b | 3,628,113 |
def characters(probabilities):
"""Turn a 1-hot encoding or a probability distribution over the possible
characters back into its (most likely) character representation."""
return [id2char(c) for c in np.argmax(probabilities, 1)] | 7b516b63df60953519fb6ba4b529039b10944947 | 3,628,114 |
def system(t, state, u):
"""
differential system equation
:param t: time
:param state: current state
:param u: input
:return: derivative of the current state
"""
x = state[0]
y = state[1]
result = np.array([3 * x + 5 * y - 2 * x * y + 3 * x ** 2 - 0.5 * y ** 2,
... | 03a61dc8e1447c4ca636aaabd43dc95b63e5c031 | 3,628,115 |
import torch
def LR_classifier(train_set, train_labels, test_set, test_labels, n_way):
""" Wrapper function which trains a logistic regression on train_set/train_labels and return the accuracy on test_set.
Parameters:
train_set -- torch.tensor (n_sample, n_feature), contains training data
trai... | 30ee4a2e5b3585f086a69304564a3e288166e17f | 3,628,116 |
import logging
def json_file_content_check(package_info):
"""Check the content of json file."""
if package_info['category'] == '':
logging.warning('The category of ' + package_info['name'] + ' package is lost.')
return False
if 'enable' not in package_info or package_info['enable'] == ''... | b700af7ecf7ee8f4c98f62915b969a4e10358a28 | 3,628,117 |
def debug(msg):
"""This is a function for debugging statements in jinja2 templates"""
if args.DEBUG:
return msg
return "" | a94949e4d7e8cb3fe4acb7469945885fb266c4bf | 3,628,118 |
import numpy
def preprocess_image(x, mode='caffe'):
""" Preprocess an image by subtracting the ImageNet mean.
Args
x: numpy.array of shape (None, None, 3) or (3, None, None).
mode: One of "caffe" or "tf".
- caffe: will zero-center each color channel with
respect to ... | a5fe2fe24e9dcef65a7f704a17ab14d4ddb72f97 | 3,628,119 |
def calculate_metric(threshold, args):
"""
给定阈值得到预测类别后,计算precision和recall,其中precision是avg_sample(hit_cnt/pred_cnt), recall是avg_sample(hit_cnt/label_cnt),在当前场景下label_cnt恒等于1
"""
# 格式:label:pred_cls,pred_score;pred_cls,pred_score;
# 78089261739417600:78089261739417600,0.995399;
# 获取label_list... | 97bb7a81e9731a3f0c48000f98669d03f1d48ca4 | 3,628,120 |
import os
import csv
import random
def load_data():
"""Load data from the Quora dataset."""
# Partition off part of the train data for evaluation
with open(os.path.join('data', 'quora', 'train.csv'), 'r') as train_file:
train_data = [row for row in csv.reader(train_file, delimiter=',', quotechar='... | 98d1b5241785cdb2f229fa076f64128aa4aaee29 | 3,628,121 |
from datetime import datetime
def current_time() -> datetime:
"""Return timezone-aware current time as datetime."""
return datetime.now().astimezone() | 2b7237f4c5a0d88ab7643dfdd3b1f8c524683884 | 3,628,122 |
def test_metamodel_callable_must_return_a_metamodel():
"""
Test that meta-model callable must return an instance of TextXMetaModel.
"""
def invalid_metamodel_callable():
return 42
clear_language_registrations()
register_language('test-lang',
pattern='*.test',
... | 8d639c0a0abedb1ad80dc8aa4bbc4f46bc3499a7 | 3,628,123 |
def Reynold(V, D):
""" Calculate Reynold number
Parameters
----------
V : float
velocity
D : float
diameter
Returns
-------
Re : float
Reynold number
"""
nu = 1.004e-6 # kinematic viscosity [m^2/s]
Re = np.abs(V*D/nu)
return Re | c36280eb501ea792ecce7057973d3837d862f05a | 3,628,124 |
def compile(self):
"""Compile AssignNode."""
global register_index
register_type = ""
if '"' not in self.children[1].compile():
register_type = "$N"
else:
register_type = "$S"
byte_code = register_type + "%s = " % register_index
byte_code += self.children[1].compile() + "\... | f0458e66d8245bba69c8f456e9b21785c7f7bee6 | 3,628,125 |
def create_client(*args):
"""
Create an EC2 client for downstream use. Must have a valid AWS configuration for boto3 to use.
:param args: optional profile name for the AWS shared config file.
:return: returns a boto3 EC2 client.
"""
try:
if len(args) == 0:
client = boto3.Ses... | 41ce3acc7e3e443058d3ab01ef05c6b7399da63f | 3,628,126 |
def Uint32ToUint8(z, lsb_first=True):
"""
Example:
np.all(Uint32ToUint8([0x01020304, 0x05060708]) == np.array([4,3,2,1,8,7,6,5], 'uint8'))
"""
return BinToUint8(Uint32ToBin(z, lsb_first)) | 6cb775731c6ec967f02da6b69a48b533e2f3ce3e | 3,628,127 |
from typing import List
def _decode(encoding: Encoding, decoder: Decoder) -> List[int]:
"""Generic decoder using subcalsses to decode different formats.
It works by nitializing a list of timestamps and the decoder with the
initial timestamp from the encoding data structure. The stateful decoder
is t... | 594833d1d518a6dc055ed4769027bd36a44f8038 | 3,628,128 |
import shutil
import os
def _load_python(test_dir, ctxs):
"""Loads the Python library and samples for the given APIs.
Args:
test_dir: The parent directory.
ctxs: The list of Contexts to load.
Returns:
list: A list of Commands to run samples.
"""
sample_cmds = {}
for c... | 97b896b1025d16ea8f74e00fb16215b42786d78e | 3,628,129 |
def merge_diff(
initial_config=None,
initial_path=None,
merge_config=None,
merge_path=None,
saltenv="base",
):
"""
Return the merge diff, as text, after merging the merge config into the
initial config.
initial_config
The initial configuration sent as text. This argument is ... | bd61a70cfb9c4ebb2ff4399fe7825ea2abcac2e8 | 3,628,130 |
def make_label(label_text):
"""
returns a label object
conforming to api specs
given a name
"""
return {
'messageListVisibility': 'show',
'name': label_text,
'labelListVisibility': 'labelShow'
} | 8c388d138136af4f01ec02db1565d66049b38cf1 | 3,628,131 |
import socket
def ip_to_str(address):
"""Print out an IP address given a string
Args:
address (inet struct): inet network address
Returns:
str: Printable/readable IP address
"""
return socket.inet_ntop(socket.AF_INET, address) | e62099babab38dc16a16f431512741ee532db4e1 | 3,628,132 |
import torch
def _empty_memory(memory_dim):
"""Get a empty memory, assuming the memory is a row vector
"""
return torch.zeros(1, memory_dim) | b7454e52bbc3c20061d53716c2e805603eb041ff | 3,628,133 |
def label_to_roi(label, expansion_mm=[0, 0, 0], return_as_list=False):
"""Generates a region of interest (ROI), defined by a starting index (z,y,x)
and size (s_z, s_y, s_x). This can be used to crop images/labels.
Args:
label (sitk.Image | list): Binary label image/mask/structure to define to ROI
... | efc2278019f8a27c4e792ad71ee8d7dbda2dbc68 | 3,628,134 |
def get_topk_correct(outputs, targets, ks=(1,)):
"""
Computes the precision@K for the specified values of K
"""
maxk = max(ks)
_, pred = outputs.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(targets.view(1, -1).expand_as(pred))
res = []
for k in ks:
correct_k =... | f657e850cff85ede7040f1b46123fc0cc1cadf7e | 3,628,135 |
def _create_spectrogram(signal: np.ndarray,
should_graph: bool = False) -> np.ndarray:
"""Creates spectrogram for signal, and returns it.
Shows graph for the signal with a Gaussian filter overlayed, the
filtered signal, and the FFT of the signal.
"""
n = len(signal) # 128
... | 7e82cf45c1f5be2dbde929293b48110da61a43b6 | 3,628,136 |
import scipy.stats
def test_reblocking():
"""
Tests reblocking against known distribution.
"""
def corr_data(N, L):
"""
Creates correlated data. Taken from
https://pyblock.readthedocs.io/en/latest/tutorial.html.
"""
return np.convolve(np.random.randn(2 ** N), n... | c9caa94e57a38d80d5a599546a00415abb4fdedd | 3,628,137 |
def get_rproj_czdisp(galaxyra, galaxydec, galaxycz, galaxygrpid, HUBBLE_CONST=70.):
"""
Compute the observational projected radius, in Mpc/h, and the observational
velocity dispersion, in km/s, for a galaxy group catalog. Input should match
the # of galaxies, and the output will as well. Based on FoF4 c... | 558e6b5acb6363ba23dc1b95b0628b951eea6138 | 3,628,138 |
def colormap_to_ev_blocks_equidistant(colormap, stops):
"""
For a given number of stops, the colormap is divided into equal length segments. The colors are sampled at the
start and end of these segments. They are then used to create "blocks", a constant color for a range between two
exposure values.
... | 21b69ffae9e867c2326eded9efe797369087a429 | 3,628,139 |
import copy
def turn_acs_into_acsK(actions_taken_so_far, all_samples, K, N, horizon):
"""
start with array, where each entry is (a_t)
end with array, where each entry is (a_{t-(K-1)}..., a_{t-1}, a_{t})
"""
#this will become [K-1, acDim]
past_Kminus1_actions = actions_taken_so_far[-(K - 1):]... | 28d5bda4155f6610361f328c16486e43c0beb472 | 3,628,140 |
from typing import Dict
from typing import Any
import os
from typing import List
def parse_scripting_log(script_type: str) -> Dict[str, Any]:
"""Parse a log to run to create a sequence of XEM commands."""
file_name = f"xem_{script_type}.txt"
relative_path = os.path.join("src", "xem_scripts", file_name)
... | 122e215aed3b8543b3981a00043daaff7fd24e2a | 3,628,141 |
def fetch_top_chapter_checkins():
"""
Show checkin count of chapters in this week
"""
re = frappe.db.sql(
"""
SELECT sc.parent_chapter, c.sub_chapter, COUNT(*) AS checkin_count
FROM `tabCheckin` c
JOIN `tabSub Chapter` sc ON c.sub_chapter=sc.name
WHERE c.creation ... | 1b725c0199d28acedf1e941938e924b79c835bc1 | 3,628,142 |
from bitcodin import api_base
def get_api_base():
"""
Get the api base url
:return: string
"""
return api_base | f909de3dae62ce73ad03d813c325801e5a69a9b1 | 3,628,143 |
def simple_reduce_error(
filename,
conservative,
precision,
target_error,
convergence_rate_scale_factor,
):
"""Determine points to add (first) or extend (second) to meet target error.
FILENAME is the data file containing lambda, dhdl_average, and error_est.
"""
points = np.loadtxt(f... | 697f6a100b246ebc783dd0fb7f8e712b989e42da | 3,628,144 |
def read_artist_albums(id, name):
"""get lists of albums for artist
"""
list_a = [(x.name, str(x.release_year), str(x.id))
for x in dmla.list_albums_by_artist('', id, 'Jaar')]
list_c = [(x['album'], x['year']) for x in dmlc.list_albums(DB_C, name)]
return list_a, list_c | f4bdcb3cb7a65bd765fce2c960560367e3be2e9f | 3,628,145 |
def client_add(request):
""" Add new client and see the list of clients """
success_message, error_message = None, None
form = ClientForm
clients = Client.objects.all()
enquiry_form = EnquiryClientForm
enquiry_clients = EnquiryClient.objects.all()
if request.metho... | 4c1023656e307b135e8e9c5b9f1d5875194c0304 | 3,628,146 |
def mult(A, B):
"""
Function to multiply two values A and B, use as "mult(A, B)"
"""
return A * B | 586c9077303dd8a36ae6007ff74756f77ec8fb3b | 3,628,147 |
def remove_stopwords(sentence):
"""
Transforms a given text to its lemmatized form. Assumes clean text separated by spaces.
:param sentence: the text to be lemmatized
:type: string
:return: lemmatized text
:type: string
"""
return ' '.join([w for w in word_tokenize(sentence) if not w in ... | 52b8fd43a710b02b825779ff4d93cb6d988e512d | 3,628,148 |
import re
def fileparse(*args):
"""Split a path into basename, dirpath, and (optional) suffixes.
Translated from perl File::Basename for unix, plus annotations"""
fullname = args[0]
suffixes = args[1:]
if fullname is None:
raise Die("fileparse(): need a valid pathname")
fullname = str(... | cbc2a6b09b9c04647de2d6f65b71bc93f0f92051 | 3,628,149 |
def lfnToEOS( path ):
"""Converts LFN to EOS.
If path is not an LFN in the first place, return path.
??? shouldn't we raise an exception?"""
if isLFN(path):
pfn = 'root://eoscms.cern.ch//eos/cms/' + path
return pfn.replace('//store','/store')
else:
return path | b41b0f42a707f1868776412d1c2f7a6a2fde3a47 | 3,628,150 |
def get_link_href(result_object, link_relation):
"""
Given a result_object (returned by a previous API call), return
the link href for a link relation.
'result_object' a JSON object returned by a previous API call. May not
be None.
'link_relation' the link relation for which href is required.
... | 400cd38d1b29ea71bf974d8aa16c1b3adf104428 | 3,628,151 |
from typing import Callable
from typing import Any
from typing import Sequence
def scanr(
fun: Callable[[Any, Any], Any], acc: Any, trav: Sequence[Any]
) -> Sequence[Any]:
"""Implementation of scanr in Python3.
This is an implementation of the right-handed
scan function from functional programming.
... | 4ef7c43aa4b4b9490efe955ef810a1eab38a6064 | 3,628,152 |
import sys
def _are_we_frozen():
"""Returns whether we are frozen via py2exe.
This will affect how we find out where we are located."""
return hasattr(sys, "frozen") | a9e55631ce9f8d60351e41d257c225f859e39a05 | 3,628,153 |
def argtopk_aggregate(a_plus_idx, k, axis, keepdims):
""" Final aggregation function of argtopk
Invoke argtopk one final time, sort the results internally, drop the data
and return the index only.
"""
assert keepdims is True
a, idx = argtopk(a_plus_idx, k, axis, keepdims)
axis = axis[0]
... | bb9c113112dcbd64bd833a390721a042a0cbbc56 | 3,628,154 |
def eht():
"""Make an empty bst size of 10."""
return HashTable(10) | 7197f5c5846a8b369e5c1284b40b990035fb447b | 3,628,155 |
import re
def rx_filter(objs: list, attr: str, prompt: str) -> list:
"""
Filter a list of dicts based on user-entered regex match to one of their values.
"""
while True:
search_term = input(prompt+" ")
# Prefer exact match first -- otherwise can never select an item that's a substri... | f0c6dd5609020054da7895e577483c911d9aaea3 | 3,628,156 |
import logging
import glob
def _get_morphotactics_rules(morphotactics_dir: str) -> _RewriteRuleSet:
"""Parses morphotactics model into valid rewrite rules.
Args:
morphotactics_dir: path to the directory that contains the text files that
define rules of morphotactics FST. All files that have the ".txt... | 56da73c4a6623dcf9e2f3d8cc136f9aab3409c84 | 3,628,157 |
def _get_usb_hub_map(device_info_list):
"""Creates a map of usb hub addresses to device_infos by port.
Args:
device_info_list (list): list of known usb_connections dicts.
Returns:
dict: map of usb hub addresses to device_infos by port
"""
map_usb_hub_ports = {}
for device_info in device_info_li... | eaadc4713a41fdf38cea4fce35806d1d8772df27 | 3,628,158 |
def gaussian_smoothing(eem_df, sigma, truncate):
"""Performs gaussian smooothing on the excitation-emission matrix from the input
sigma and truncation sigma.
Args:
eem_df (pandas.DataFrame): An excitation-emission matrix.
sig (int): Sigma of the gaussian distribution weight for the data smo... | e3e81ba47b2dd2c7a6015f092b151c65f1236bb9 | 3,628,159 |
import os
import subprocess
def get_current_commit(srcdir):
"""Return information about git commit checked out in the given directory.
:param srcdir: source code directory
:type srcdir: str
:return: commit information composed of brief SHA1 and subject
:rtype: str
"""
os.chdir(srcdir)
... | 3b3601303135bfdfe66cb069ef7d4ed1f413af8b | 3,628,160 |
import re
def parse_pgsql_logs(data):
"""
Parse the pgsql benchmark data from ripsaw and return
the data in list format
Args:
data (str): log data from pgsql bench run
Returns:
list_data (list): data digestable by scripts with below format
e.g.:
[
... | 5bd5cd43432b17be6bd52004b151b32a0f574980 | 3,628,161 |
from django.utils.encoding import force_text
from django.core.mail import EmailMultiAlternatives
from mailer.models import Message, PRIORITY_MAPPING
def send_html_mail(subject, message, message_html, from_email, recipient_list, priority="medium", fail_silently=False,
auth_user=None, auth_password=N... | c77b7cd475fb42891310c2de5cdf0ceb599f637b | 3,628,162 |
import sys
def compute_tDCF(bonafide_score_cm, spoof_score_cm, Pfa_asv, Pmiss_asv, Pmiss_spoof_asv, cost_model, print_cost):
"""
Compute Tandem Detection Cost Function (t-DCF) [1] for a fixed ASV system.
In brief, t-DCF returns a detection cost of a cascaded system of this form,
Speech waveform -> ... | 9245e7d3975ae4c6f910a32afdad20ab4fdbc7d9 | 3,628,163 |
def jd2gdate(myjd):
"""Julian date to Gregorian calendar date and time of day.
The input and output are for the proleptic Gregorian calendar.
Parameters
----------
myjd:
julian date (float).
Returns
-------
y, m, d, f : int, int, int, float
Four element tuple containing... | f43a299fd8627804893eb5b6266d6a016c191d72 | 3,628,164 |
def donation_journal_history_for_a_voter(voter_we_vote_id):
"""
:param voter_we_vote_id:
:return:
"""
donation_manager = DonationManager()
donation_journal_results = donation_manager.retrieve_donation_journal_list(voter_we_vote_id)
refund_days = get_environment_variable("STRIPE_REFUND_DAYS"... | 41b6a63d2893a7104fd15686e31090ee058438cd | 3,628,165 |
from matplotlib import pyplot
import numpy
def imshow(
subplot,
data,
title=None,
sharex=None,
sharey=None,
vmin=-2.5,
vmax=0.0,
cmap=None,
interpolation='lanczos',
**kwargs,
):
"""Log-plot image using matplotlib.pyplot. Return plot axis and plot.
Mirror symmetry is ap... | 33a090c95de533d90690eb3cb635b805634ac12a | 3,628,166 |
import math
def sigmoid_1(x):
""" sigmoid at x """
return math.log(x / (1 - x)) | a7ec76035e4f3b33613e7176e00dff7e243a695a | 3,628,167 |
from typing import Tuple
from typing import List
def initialize_device_settings(use_cuda: bool,
local_rank: int=-1,
multi_gpu: bool=True) -> Tuple[List[str], int]:
"""
Returns a list of available devices.
:param use_cuda: Whether to make use o... | c84f1dcc13ea90b2539b5027324382466372a77d | 3,628,168 |
def get_action_td_zero(exploration_mode, current_state, Q, epsilon, temperature, exploration_degree, actions,
nextStates):
"""
choose action based on temporal difference learning
@param exploration_mode:
@param current_state:
@param Q:
@param epsilon:
@param temperatur... | ad5045f21f5048853371f4b12e9a08a6af50036d | 3,628,169 |
def get_policy_targets(context, presentation):
"""
Returns our target node templates and groups if we have them.
"""
node_templates = []
groups = []
our_targets = presentation.targets
if our_targets:
all_node_templates = \
context.presentation.get('service_template', 't... | f483b9749c25b7d56c0e0a02a6787d936782e470 | 3,628,170 |
def check_for_messages(folder, message_data, pst_name, folder_name):
"""
The check_for_messages function reads folder messages if
present and passes them to the report function
:param folder: pypff.Folder object
:param message_data: list to pass and extend with message info
:param pst_name: A st... | 0022536bbd6b0d0f723c6e6daf9a96e83afcd18d | 3,628,171 |
import socket
def __get_host_ip():
"""
获取本地IP地址
:return:
"""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
finally:
s.close()
return ip | a73d4c02618a0729501dafe12702287195123f2c | 3,628,172 |
def uv_renew(u, s, v, X, gamma1, gamma2):
"""
This function will return the updated u, v and the corresponding lambdas.
Only for internal use for the SSVD function.
"""
n,d = X.shape
u = u.reshape((n,1))
v = v.reshape((d,1))
SSTO = np.sum(X**2)
## first, update v
#... | cb3eef48dc3cac9fd8bae8f2d010d7883eed2a56 | 3,628,173 |
def merge_df(df1, df2):
""" Genera un dataframe seleccionant les columnes que ens
interessen dels dos dataframes, eliminant valors NA, i actualitza
les notes de '538 Grade' simplificant-les.
Keyword arguments:
df1 -- dataframe que conté les dades de les entrevistes.
df2 -- dataframe que conté l... | 955569ebbbbcf141eedd64ca3ee9b9b89f7922be | 3,628,174 |
def OpInfo_CONV(
conv_ps: conv.Conv2DParams, s_id: str, vin_id: str, vout_id: str
) -> OpInfo:
""" OpInfo for a CONV operation """
rd_a = (
"{{ {SID}[oh,ow] -> {VID}[id,ih,iw] "
": 0 <= oh < {OH} "
"and 0 <= ow < {OW} "
"and 0 <= id < {ID} "
"and oh <= i... | 6f4292a79b9905a9a9c1ce79607ab854b3e97d81 | 3,628,175 |
def mean_period(data):
"""Return mean-period of signal."""
peaks = len(find_peaks(data, height=0)[0])
return len(data) / peaks if peaks > 0 else len(data) | 627be25f610f81e45c2387f2c0e778e0b5ce8c20 | 3,628,176 |
def rvsi_vi(imgData, wave, mask=0, bands=[-1,-1,-1]):
"""
Function that calculates the Red-edge Vegetation Stress Index.
This functions uses bands 714, 733, and 752 nm. The closest bands to these values will be used.
Citation: Merton, R. and Huntington, J. 1999. Early simulation results of the ARIES-1 ... | ddf08ac67979b5bff879faaac139bb25fdc660cb | 3,628,177 |
def usb_pitop_peripherals():
"""Returns a list with the status of USB pi-top peripherals.
Returns:
list: list of dictionaries with the status of USB peripherals
"""
return [
{"name": "pi-top Touchscreen", "connected": touchscreen_is_connected()},
{"name": "pi-top Keyboard", "con... | 5fa9100fdfa03bbfaebe3a053a036bc50b52dd59 | 3,628,178 |
import torch
def isPD(B):
"""Check whether a matrix is positive definite.
Args:
B ([torch.Tensor]): [Input matrix.]
Returns:
[bool]: [Returns True if matrix is positive definite, otherwise False.]
"""
try:
_ = torch.cholesky(B)
return True
except RuntimeError:... | c51dc4f6f48ac7417f49ef41b81f3b04816b9279 | 3,628,179 |
def convert_TriMap_to_SelectedLEDs( best_led_config ):
""" Returns a lookup dict of the selected LEDs.
"""
d = {}
for tri_num in best_led_config:
for led_num in best_led_config[tri_num]:
d[led_num] = True
return d | 521a1be0d11cb8198944e437d20d4ac0349c8856 | 3,628,180 |
import os
def get_stimulus_response(src_dir, src_dataset, stim_id, boundary=0,
if_get_stim=True):
"""Get stimulus-response data for all datasets.
Args :
src_dir : Location of all joint embedding datasets.
src_dataset : Dataset corresponding of a specific stimulus.
stim_id : ... | 695ac3dbbea4753d0722e9168f59b85b22776de3 | 3,628,181 |
import argparse
import sys
import logging
def parse_cli():
"""This function parses all the arguments, validates them and then stores them
in a dictionary that is used throughout the script."""
usage = \
'''%(prog)s [--debug] -u username -k pkey -c cert \\
(-H hostname | -F hostfile) [-... | 3bcd60045225d5049e9c7c150667c1664ebc3e50 | 3,628,182 |
def get_by_id(id_estudiante, id_asignatura, edicion):
"""
Obtiene la tupla de la relación Estudiantes con el identificador
:param id_estudiante: El identificador del estudiante
:type id_estudiante: str
:param id_asignatura: El identificadir de la asignatura
:type id... | 04fa8447359917896210c1252b92ce82dc40f511 | 3,628,183 |
def keyword(tokens, expected):
"""Case-insensitive keyword match."""
try:
token = next(iter(tokens))
except StopIteration:
return
if token and token.name == "symbol" and token.value.lower() == expected:
return TokenMatch(None, token.value, (token,)) | 2ae106158e4a17258283abdd3ddcf77c670957c4 | 3,628,184 |
def milestone_container(request):
"""milestone container"""
template = loader.get_template('project_management/milestone_container.html')
context = {}
return HttpResponse(template.render(context, request)) | 5461448dccdc5a5a3a7d56cc324dbaff5b3dbcc2 | 3,628,185 |
def _run_symbolic_method(op_name, symbolic_fn, args):
"""
This trampoline function gets invoked for every symbolic method
call from C++.
"""
try:
return symbolic_fn(*args)
except TypeError as e:
# Handle the specific case where we didn't successfully dispatch
# to symboli... | c95f8d18e4b3a0ed7a06ccc6bdf178a820537d08 | 3,628,186 |
import csv
def load_input_source(input_source):
"""Load data from an arbitrary input source. Currently supported:
JSON, JSON-String, CSV, CSV-String. Returns an empty list if no data
is available."""
input_data = []
try:
input_data = load_json_from_file(input_source)
except ValueError as e:
... | 82ea97978a39a93a8d42e024cef9890cf2535dbe | 3,628,187 |
def total_intensity(field):
"""Calculates total intensity of the field.
Computes intesity and sums over pixels."""
i = field2intensity(field)
return i.sum(tuple(range(i.ndim))[-2:]) | 89a26b8d53c7520aff99ef54800cab5fcb0937bb | 3,628,188 |
import array
def g_function_bernier(Fo, rba):
"""
Bernier (2001) approximation of Ingersol et al. (1954) G-function of
the cylindrical heat source problem.
Fo = Fourier number
rba = ratio of the radius where the temperature is calculated over the
external radius of the borehole.
Re... | 58226463d498b5af839d7ffd3c1042e4a0a4b5ee | 3,628,189 |
def clear_item_updates(api_key: str, item_id: str, *args, **kwargs):
"""Clear an item's updates.
Parameters
api_key : `str`
The monday.com v2 API user key.
item_id : `str`
The item's unique identifier.
args : `tuple`
... | fc487f8fb27d179df5823601179fbcbb858dd69c | 3,628,190 |
import torch
def compute_aucs(pred, targ):
"""
Computes Area Under the Curve (AUC) from prediction scores.
Args:
targ: Pytorch tensor on GPU, shape = [n_samples, n_classes]
true binary labels.
pred: Pytorch tensor on GPU, shape = [n_samples, n_classes]
can either be pro... | 2b2b00eb55421ee1005534998f0519c96ed70696 | 3,628,191 |
def minhash(features):
# type: (List[int]) -> List[int]
"""
Calculate a 64 dimensional minhash integer vector.
:param List[int] features: List of integer features
:return: Minhash vector
:rtype: List[int]
"""
return [
min([(((a * f + b) & MAXI64) % MPRIME) & MAXH for f in featur... | c0bb534f4433fd517a7910647260f947c136111a | 3,628,192 |
def get_gauss_beams(fwhm=7, nside=512, lmax=None):
"""the fwhm of 143GHz is 7.27,
test fwhm: 7, 6, 5, 4
"""
if lmax is None:
lmax = 3*nside + 50
bl = hp.gauss_beam(fwhm*np.pi/10800., lmax=lmax)
return bl | 85a4edd2389afa49c166488089ad70433a4683bd | 3,628,193 |
def create_long_model(model_specified, attention_window, max_pos):
"""Starting from the `roberta-base` (or similar) checkpoint, the following function converts it into an instance of `RobertaLong`.
It makes the following changes:
1)extend the position embeddings from `512` positions to `max_pos`. In Lo... | ff7dc0f6f008ff03f834389f9dc02ccbdabceece | 3,628,194 |
def api_redirect():
"""Redirects the user to the API documentation page."""
return flask.redirect(flask.url_for("api_ns.api")) | 471dcc20b64da5299572783af7345bf2b3effd29 | 3,628,195 |
from rasa.nlu import utils as nlu_utils
import aiohttp
async def download_file_from_url(url: Text) -> Text:
"""Download a story file from a url and persists it into a temp file.
Returns the file path of the temp file that contains the
downloaded content."""
if not nlu_utils.is_url(url):
rais... | 373ca5e8a0726baeeb868a98b827110ca46e541b | 3,628,196 |
import binascii
def _decode_pem_private(lines, passphrase):
"""Decode a PEM format private key"""
pem_name, headers, data, end = _decode_pem(lines, b'PRIVATE KEY')
if pem_name == b'OPENSSH':
return _decode_openssh_private(data, passphrase), end
if headers.get(b'Proc-Type') == b'4,ENCRYPTED'... | 64db7a54a1c35b35d435f64b45353c94029ab6c6 | 3,628,197 |
def kBtu_h2kW(x):
"""kBtu/h -> kW"""
return Btu_h2kW(kBtu_h2Btu_h(x)) | e528827fc9527dfbfa421741aea7c719979c7eb9 | 3,628,198 |
def plot_hist_centers(output, *args, **kwargs):
"""Plot 1-dimensinal output using pyplot.plot
executes pyplot.plot(x, y, *args, **kwargs) with first two arguments overridden
all other arguments are passed as is.
Options:
scale=float or 'width' - multiply bin by a scale or divide by bin width
... | be0d7e2cf5f3b5229d3c781c3f675291c9a9d4ba | 3,628,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.