content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import math
def __calc_entropy_passphrase(word_count, word_bank_size, pad_length, pad_bank_size):
"""
Approximates the minimum entropy of the passphrase with its possible deviation
:param word_count: Number of words in passphrase
:param word_bank_size: Total number of words in the word bank
:param... | c3597b8d8fc35387638e1e0e4923316c2b99aaa8 | 50,400 |
def masked_softmax(X, valid_lens):
"""通过在最后一个轴上掩蔽元素来执行 softmax 操作"""
if valid_lens is None:
return ops.Softmax(-1)(X)
else:
shape = X.shape
if valid_lens.ndim == 1:
valid_lens = mnp.repeat(valid_lens, shape[1])
else:
valid_lens = valid_lens.reshape(-1)... | 6895ac2da748167f469e317d27c1eb814be20d79 | 50,401 |
from nexinfosys.command_generators import Issue, IType
def any_error_issue(issues):
"""
Just iterate through a list of Issues (of the three types) to check if there is any error
:param issues:
:return:
"""
any_error = False
for i in issues:
if isinstance(i, dict):
if i... | de308851af2d7a8a8e64a11f298517d328d45370 | 50,402 |
def join_string(list_string, join_string):
"""
Join string based on join_string
Parameters
----------
list_string : string list
list of string to be join
join_string : string
characters used for the joining
Returns
-------
string joined : string
a string whe... | bcb55fb72b9579dd5ab548b737a0ffd85cbc7f43 | 50,403 |
def value_from_example(example, feature_name):
"""Returns the feature as a Python list."""
feature = example.features.feature[feature_name]
feature_type = feature.WhichOneof('kind')
return getattr(feature, feature_type).value[:] | 8c73b2ecec80255de219911b0628fc89359a220a | 50,404 |
def apply_control(sys, u_opt):
""" evaluates the controlled system trajectory """
states = sys.states
# if not MPC:
timesteps = sys.timesteps
x_new = np.zeros([states, timesteps])
x_new[:, 0] = sys.state
cost = 0
for t in range(timesteps - 1):
u = u_opt[:, t]
# retur... | 201e6ba6a23c9d00b1cce8ccc1d74d91ce9cb3bf | 50,405 |
import warnings
def xfl_domshape_to_svg(domshape, mask=False):
"""Convert the XFL <DOMShape> element to SVG <path> elements.
Args:
domshape: An XFL <DOMShape> element
mask: If True, all fill colors will be set to #FFFFFF. This ensures
that the resulting mask is fully transparent... | d6123a72270def300f0cbc1e7ba627940ee6a0cc | 50,406 |
async def chained_filter_repositories_labels(
client, headers, account_id, date_from, date_to, exclude_inactive, repos, timezone,
):
"""Chain the request to get filtered repos and labels."""
filtered_repositories, fr_datapoint = await filter_repositories(
client,
headers,
int(account... | 34268f4824c29e65d457c79a1503bc875cb06f1d | 50,407 |
from typing import Any
def return_value_from_dict_extended(some_dict: dict,
path_string: str) -> Any:
"""
Возвращает значение ключа в словаре по пути ключа "key.subkey.subsubkey"
:param some_dict:
:param path_string:
:return:
"""
check = access_dot_path(some_dict... | e23f4c5ded43f78e92b026f4bf2f892235da428c | 50,408 |
import requests
def search(term, country='UA', media='music', entity=None, attribute=None, limit=50):
"""
Returns the result of the search of the specified term in an array of result_item(s)
:param term: String. The URL-encoded text string you want to search for. Example: Steven Wilson.
T... | c577ca67a3f0c73ef92bd251deda30c75145eb55 | 50,409 |
def returnFiles(path):
"""Collects a list of files within a file
:rtype: list
"""
if path:
onlyFiles = [join(path, f) for f in listdir(path) if isfile(join(path, f))]
# print("onlyFiles: ", onlyFiles)
return onlyFiles
# print("Path: ", listdir(path))
return None | 88b49aff59941cfafeca62cc08578b318dc4c55d | 50,410 |
import os
def maybe_download_and_extract_bz2(root, file_name, data_url):
"""Downloads file from given URL and extracts if bz2
Args:
root (str): The root directory
file_name (str): File name to download to
data_url (str): Url of data
"""
if not os.path.exists(root):
os.... | 2af6f1a9ec273e02a330d14edc1c615ecb119881 | 50,411 |
from typing import Tuple
def minus(a: Tuple[int], b: Tuple[int]) -> Tuple[int]:
"""
Vektor a minus Vektor b.
:param a: Von den Werten in dieser Liste wird subtrahiert.
:param b: Diese Werte werden subtrahiert.
:return: Elementweise Differenz.
"""
assert len(a) == len(b)
return tuple(ax... | 1cfbbb98fd2ac0eb422ef5d5e27fa9871f0272d0 | 50,412 |
from typing import get_args
def ccds():
"""
Returns list of Consensus CDS IDs by query paramaters
---
tags:
- Query functions
parameters:
- name: ccdsid
in: query
type: string
required: false
description: 'Consensus CDS ID'
default: 'CCDS1357... | ea55fa1fe705a3a3696181cfee3d2bc5118c6e7b | 50,413 |
from datetime import datetime
def today_w_time():
"""
Returns today in format 'Y-m-d H:i:s'
"""
today = datetime.datetime.now()
today = today.replace(microsecond=0)
return today.isoformat(' ') | 4084b1f5b387c92a38e705267f76c03a6863a8f2 | 50,414 |
from datetime import datetime
def GetLast7DaysYesterday():
"""
Set date range as 7 days before yesteday up to yesterday
Returns
startDate: date object. Start of period.
endDate: date object. End of period.
countOfDays: integer. Number of days between start and end date
""... | 3f8dc77e1d795e7fdd4c2498552c5c116c1262a5 | 50,415 |
def top_level_nodes(ig_service):
"""test fixture gets the top level navigation nodes"""
response = ig_service.fetch_top_level_navigation_nodes()
return response["nodes"] | 323a88402a2790d672273001826d0ae3d25c017d | 50,416 |
def softmax_loss_vectorized(W, X, y, reg):
"""
Softmax loss function, vectorized version.
Inputs and outputs are the same as softmax_loss_naive.
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
num_classes = W.shape[1]
num_train = X.shape[0]
num_d... | ec52b1f44abc049e8b3298b68a69296bc0316a71 | 50,417 |
import logging
def _default_handlers(stream, logging_level):
"""Return a list of the default logging handlers to use.
Args:
stream: See the configure_logging() docstring.
"""
# Create the filter.
def should_log(record):
"""Return whether a logging.LogRecord should be logged."""
... | d2473a3176f3f292bfd6ab4bb2528d0ba6cd6b50 | 50,418 |
import logging
def ldap_add_memberuid(email, member_id):
"""
Update an existing LDAP account by adding another memberUid to it.
"""
logger = logging.getLogger('membership.utils.ldap_add_memberuid')
conn = settings.LDAP_CONN
cn = f'cn={email},{settings.LDAP_DOMAIN_CONTROLLER}'
changes = {'... | f0111103aba95e5bc91fb368977866ee0b7bf1a3 | 50,419 |
def read_pb2(filename, binary=True):
""" Convert a Protobuf Message file into mb.Compound
Parameters
---------
filename : str
binary: bool, default True
If True, will print a binary file
If False, will print to a text file
Todo: This could be more elegantly detected
Re... | 43306677671c3ee8f85ee3d64e35aa1e8fba4f1a | 50,420 |
def is_unique_bloom_filter(bloom_filter, item):
"""
Converts Redis results to boolean representing if item was unique (aka not found).
Keyword arguments:
bloom_filter -- the bloom filter
item -- the item to check
Returns:
boolean -- True if unique (aka not found)
Throws:
Assertion... | 1a42f43a4eb058c2861ca0f9e20f95e74e42acff | 50,421 |
import psutil
def get_avain_instance_count():
""" Return the number of currently active AVAIN processes """
instance_count = 0
for proc in psutil.process_iter():
try:
for elem in proc.cmdline():
if elem.endswith("/avain.py") or elem == "/usr/local/bin/avain":
... | 9fdb90c5ec7b273b5652d0702a59ef850cd83895 | 50,422 |
import math
def incidence_rate_ci(events, time, alpha=0.05):
"""Calculate two-sided (1-alpha)% Wald Confidence interval of Incidence Rate
Returns (incidence rate, lower CL, upper CL, SE)
events:
-number of events/outcomes that occurred
time:
-total person-time contributed in this gro... | 7287eefa4f087ece3702ffa95be71a771bc69db8 | 50,423 |
def make_costate_rates(ham, states, costate_names, derivative_fn):
"""Make costates."""
costates = [SymVar({'name': lam, 'eom':derivative_fn(-1*(ham), s)})
for s, lam in zip(states, costate_names)]
return costates | 2c1a40d215866e5cd4622c1afab21c1ec5273aea | 50,424 |
from re import T
def projection():
""" RESTful CRUD controller """
if deployment_settings.get_security_map() and not s3_has_role("MapAdmin"):
unauthorised()
tablename = module + "_" + resourcename
table = db[tablename]
# CRUD Strings
ADD_PROJECTION = T("Add Projection")
LIST_PR... | 3fe952cb86efcfa30b0ff54c512b191ccd03c49c | 50,425 |
def parse_segments(segments_str):
"""
Parse segments stored as a string.
:param vertices: "v1,v2,v3,..."
:param return: [(v1,v2), (v3, v4), (v5, v6), ... ]
"""
s = [int(t) for t in segments_str.split(',')]
return zip(s[::2], s[1::2]) | 4adfaff824ceb12772e33480a73f52f0054f6f5d | 50,426 |
def GetFirstWord(buff, sep=None):#{{{
"""
Get the first word string delimited by the supplied separator
"""
try:
return buff.split(sep, 1)[0]
except IndexError:
return "" | ce01a470ff5ba08f21e37e75ac46d5a8f498a76a | 50,427 |
from typing import Optional
def get_table(id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetTableResult:
"""
Resource Type definition for AWS::DynamoDB::Table
"""
__args__ = dict()
__args__['id'] = id
if opts is None:
opts = pulumi.Invo... | ef564eeac0443cb99bceddb4959e1abb137570c3 | 50,428 |
def load_perezfornos2012(shuffle=False, subjects=None, figures=None,
random_state=0):
"""Load data from [PerezFornos2012]_
Load the brightness associated with joystick position data described in
[PerezFornos2012]_.
Datapoints were extracted from Figures 3-7 of the paper.
... | 5edd2826e8fa3a0b5a44bf57bfc12104c0899d66 | 50,429 |
from typing import Set
from typing import List
def filter_tests(tests: Set[str], exclude_tests: List[str]) -> Set[str]:
"""
Exclude tests which have been denylisted.
:param tests: Set of tests to filter.
:param exclude_tests: Tests to filter out.
:return: Set of tests with exclude_tests filtered ... | 6e1233c840fc4263252cc172958c75eb0819f526 | 50,430 |
def setup_Component_with_parameters():
"""
Sets up a Component with parameters and all options used.
"""
comp = setup_Component_all_keywords()
comp._unfreeze()
# Need to set up attribute parameters
comp.new_par1 = 1.5
comp.new_par2 = 3
comp.new_par3 = None
comp.this_par = "test... | 8e99f241617a8857593da7dc203af5ffe09beb7c | 50,431 |
def dpuSetTaskPriority(task, priority):
"""
Set the priority of one DPU task. Priority range is 0 to 15, 0 has the highest priority.
The priority of the task when it was created defaults to 15.
"""
return pyc_libn2cube.pyc_dpuSetTaskPriority(task, c_int(priority)) | fca91a76d7a36bc09e69153a69ff694b80a39767 | 50,432 |
def find_std(arr):
"""
This function determines the standard deviation of the given array.
Args:
arr = numpy array for which the standard deviation and means are to be determined
Returns:
std = standard deviation of the given array
mean = mean value of the given array
Usage... | 3b6d4962ee3ff31eafb4cd194f2302675c5643de | 50,433 |
import math
def process(frame: np.ndarray, mask: np.ndarray = None, hsv: np.ndarray = None, *,
lower=(20, 100, 100), upper=(35, 255, 255),
min_area_prop=1/64, focal_length=208.5):
"""Find cubes using our vision algorithm.
Args
----
frame: the image to process
mask: optiona... | 7c173299676ad7665b0a9e62ab5aa9be8530552b | 50,434 |
def required_daemons(instance):
"""
Return which daemon types are required by the instance
"""
daemons = [DaemonType.SENSOR]
if isinstance(instance.scheduler, DagsterDaemonScheduler):
daemons.append(DaemonType.SCHEDULER)
if isinstance(instance.run_coordinator, QueuedRunCoordinator):
... | 8c0c016ced926e0bc2db86ca447f4cd7beef7b64 | 50,435 |
import six
def SplitDictOfTensors(t_dict, num_splits):
"""Splits tensors in `t_dict` evenly into `num_splits` along the 1st dimenion.
Args:
t_dict: A dictionary of tensors. Each tensor's 1st dimension is the same
size.
num_splits: A python integer.
Returns:
A list of dictionaries of tensors,... | 53d4ec0b5d1a5222dc6d3e3c5fa115f43aef6260 | 50,436 |
def add_gradient_noise(t, stddev=1e-3, name=None):
"""
Adds gradient noise as described in http://arxiv.org/abs/1511.06807 [2].
The input Tensor `t` should be a gradient.
The output will be `t` + gaussian noise.
0.001 was said to be a good fixed value for memory networks [2].
"""
with tf.name_scope(values... | 7991459fc70ccbffcd19af238265023ab58ca6f6 | 50,437 |
import csv
def _read_csv(
reader,
header=True,
skiprows=0,
numeric=True,
columns=None,
index=None,
index_col=None,
):
"""
Reads a file in as a DataFrame.
:param reader: A file handle or filename.
:param headers: True if headers are on the first line of data, false otherwis... | 84817e96b18a543ec55e11d09e07636f28108deb | 50,438 |
from typing import Any
def find_entering_variable(
tableau: npt.NDArray, pivot_row_index: int, non_basic_variables: set
) -> Any:
"""
Finds the non-basic variable which becomes basic after pivoting
Parameters
----------
tableau : array
A tableau corresponding to a vertex of a Polytope... | 70d4641bef7f92d82c6a7f8b141fd5b463005ccd | 50,439 |
def activity_final(self):
"""Find or create a final node in a Activity
Note that while UML allows multiple final nodes, use of this routine assumes a single is sufficient.
:return: FinalNode for Activity
"""
final = [a for a in self.nodes if isinstance(a, FinalNode)]
if not final:
self.... | 9fe7b2041600c8478f13a3a2f1985e72bc22ed2c | 50,440 |
def contar_caracteres(s):
"""
FUNÇÃO QUE CONTA OS CARACTERES DE UMA STRING
:param s: string a ser contada
"""
num_of_caracteres = {}
for caracter in s:
num_of_caracteres[caracter] = (num_of_caracteres.get(caracter, 0) + 1)
return num_of_caracteres | afad48efc5f2f22f5c8e4622836516d3229266c8 | 50,441 |
def parse_symmetric_morlet_single_scale_parameters( parameter_map ):
"""
Parses parameters for the single scale, symmetric Morlet wavelet generator.
Takes a dictionary of (key, string value)'s and casts the values to the
types expected by get_symmetric_morlet_single_scale_transform().
The following... | 4698ee7d36187d5716ceed968cbe05cbe0985b94 | 50,442 |
from typing import Union
from typing import Iterator
from typing import Optional
from typing import List
def keep_protein_class(data: Union[pd.DataFrame, PandasTextFileReader, Iterator], protein_data: pd.DataFrame,
classes: Optional[Union[dict, List[dict]]] = [{'l2': 'Kinase'}, {'l5': 'Adenosin... | 6d0ecc9e6a7fd05b323fe5bc19565b263594e02b | 50,443 |
import types
def load_embeddings(env_config):
"""Attempt to loads user and movie embeddings from a json or pickle file.
Args:
env_config: `EnvConfig` class from movie_lens_simulator.py
Returns:
embedding_dict containing embeddings for movies and users
"""
path = env_config.embeddings_path
embedd... | 1a10a4995d517d591ce6cbbd1a180acc17f31731 | 50,444 |
def find_one_file(directory, pattern):
"""
Use :func:`find_files()` to find a file and make sure a single file is matched.
:param directory: The pathname of the directory to be searched (a string).
:param pattern: The filename pattern to match (a string).
:returns: The matched pathname (a string).
... | 2d3e6fdbcd650af1685b2f05a0098b9d463900ef | 50,445 |
def image_hosting():
"""
图床
"""
# from app.util import file_list_qiniu
# imgs = file_list_qiniu()
page = request.args.get('page',1, type=int)
imgs = Picture.query.order_by(Picture.id.desc()). \
paginate(page, per_page=20, error_out=False)
return render_template('admin/image_hosti... | fb513bba18a492312ad084b84c86ed9380b43156 | 50,446 |
def get_domain_ip(domain):
"""
Get the IP for the domain. Any IP that responded is good enough.
"""
if domain.canonical.ip is not None:
return domain.canonical.ip
if domain.https.ip is not None:
return domain.https.ip
if domain.httpswww.ip is not None:
return domain.http... | 5f16fe7716561059d00ae33c631ae1df711ecc0e | 50,447 |
def create_frame(i):
"""Helper function to create snapshot objects."""
snap = gsd.hoomd.Snapshot()
snap.configuration.step = i + 1
return snap | 395c830fc3121a6292ac08eea7e963445e0f9a58 | 50,448 |
import torch
def BPR_Loss(positive : torch.Tensor, negative : torch.Tensor) -> torch.Tensor:
"""
Given postive and negative examples, compute Bayesian Personalized ranking loss
"""
distances = positive - negative
loss = - torch.sum(torch.log(torch.sigmoid(distances)), 0, keepdim=True)
return ... | 868df180dc0166b47256d64c60928e9759b80e5f | 50,449 |
def gen_segment(curr_img, curr_predictor,
try_bools = [False, False],
out_trk = None):
"""Apply different methods (see try_bools) iteratively to try to segment
a single shot (non-ALC) image. Because image source is not a mosaic,
extent jittering (zooming in and out) is ... | 84e5ef2e270c9c09faafe1d5e51ce7d0a446dc61 | 50,450 |
import urllib
def query(url):
"""Send the query url and return the DOM
Exception is raised if there is errors"""
u = urllib.FancyURLopener(HTTP_PROXY)
usock = u.open(url)
dom = minidom.parse(usock)
usock.close()
errors = dom.getElementsByTagName('Error')
if errors:
e = buildException(errors)
raise e
r... | e12c7e608aa9beba17b5d6a9bfaba39f73b33547 | 50,451 |
import os
def expandFilename(filename):
"""Get the actual file name.
Parameters
----------
filename: str
A file or directory name.
Returns
-------
full_file_name: str
The real directory name.
"""
fname = filename
done = False
count = 0
while not done:... | 0e2a901298e52b0f349fc06b5d353d4af674c960 | 50,452 |
def reshape_img(image):
"""
Reshape an image into the form (height, width, channels).
:param image (np.array): Loaded image
:return: reshaped (np.array): Reshaped image
"""
img = []
for i in range(3):
img_c = np.reshape(image[channel * i:channel * (i + 1)], (image_size, image_size)... | 7c2da20262ed84c8dffc6135a0f6638e0ba89a43 | 50,453 |
import os
from datetime import datetime
def RetArquivo(dir: str= '.',
prefix_data:bool= True,
radical_arquivo:str= 'arq',
dig_serial: int= 5,
extensao: str= 'dat',
incArq: int= 0,
) -> str:
"""... | 9a3a259b28fc5043bcc727ee855431843f8a3041 | 50,454 |
def set_levels(lst_all, lst_chiln, lng_level):
"""Top down recursive setting of nesting levels"""
lng_next = lng_level + 1
for id_child in lst_chiln:
dct_child = lst_all[id_child]
dct_child[ATT_LEVEL] = lng_level
lst_next = dct_child[ATT_CHILN]
if lst_next:
set_levels(lst_all, lst_next, lng_next)
return... | b3f6f586d5db9aa5458c639234e55f9baeb1e807 | 50,455 |
from tests.test_plugins.threads_plugin import ThreadPlugin
def ThreadPlugin():
"""
:return: thread plugin class
"""
return ThreadPlugin | 79e59657484db2c894ff9cae58af5c933d7a6df7 | 50,456 |
import math
def get_distance(pos_1, pos_2):
"""Get the distance between two point
Args:
pos_1, pos_2: Coordinate tuples for both points.
"""
x1, y1 = pos_1
x2, y2 = pos_2
dx = x1 - x2
dy = y1 - y2
return math.hypot(dx, dy) | 457827af4625c493537c8501c66ebba73d9ce1a1 | 50,457 |
import re
def jsonContentCategories():
"""
Parses the Google Cloud content categories from a local txt file and returns a nested dictionary (ugly, but effective).
Returns:
Dictionary -- Nested dictionary of content categories.
"""
f = open("google_content_categories.txt", "r")
catArr... | 720ddf12e0b3bd443f2b119c9565d516798555f8 | 50,458 |
def makeFigure():
"""
Makes figure 5.
"""
# Get list of axis objects
ax, f = getSetup((10, 10), (4, 3))
figureMaker(ax, *commonAnalyze(list_of_populations, 2), num_lineages=num_lineages)
subplotLabel(ax)
return f | 3880ab2afb3d93c716774742691833c4eaf88170 | 50,459 |
def gauss2D_FIT(xy, x0, y0, sigma_x, sigma_y):
"""Version of gauss2D used for fitting (1 x_data input (xy)
and flattened output). Returns the value of a gaussian at a 2D set of points for the given
standard deviation with maximum normalized to 1.
The Gaussian axes are assumed to be 90 degrees from each ... | 42dc8fb01de967fa0243372ccae4eeaa22e37571 | 50,460 |
def insert_many(sql, *args):
"""
执行SQL语句
:param sql: insert的SQL语句,可含?
:param args: insert的SQL语句所对应的值
:return: 最后插入行的主键ID
"""
return _insert(sql, True, *args) | 311132a144df8da3e74119331eaadc86cd1cfc30 | 50,461 |
def _sub_matches_cl(subs, state_expr, state):
""" Checks whether any of the substitutions in subs will be applied to
state_expr
Arguments:
subs: substitutions in tuple format
state_expr: target symbolic expressions in which substitutions will
be applied
state: target symboli... | 7ceba9a6c0a83251289dec8f27ccbf1558e47dac | 50,462 |
import time
def get_full_json(job_id: str = None,
textract_api: Textract_API = Textract_API.DETECT,
boto3_textract_client=None,
job_done_polling_interval=1) -> dict:
"""returns full json for call, even when response is chunked"""
logger.debug(f"get_full_js... | 4550f05d0926e5c991c251faa2505668c2316b77 | 50,463 |
import os
import re
import time
from datetime import datetime
def get_time_from_filename(file_name, date_extraction_pattern, date_pattern):
"""
@param file_name name of the file
@param date_extraction_pattern regular expression describing how the date is represented in the filename
@param date_pattern... | da9c576267f4c2b1ab029ecbf3275793b3f1ffa3 | 50,464 |
import sys
def calc_sense_prob(x, S):
"""
This function calculates the probabilities for x (can be a lemma or a key)
from S (can be a Semantic Class or a Wordnet Synset)
"""
if isinstance(S, Semantic_Class):
pass
elif isinstance(S, nltk.corpus.reader.wordnet.Synset):
... | cdc386e9c939cf3c202035874f5ead8b532258c4 | 50,465 |
def find_fxn(tu, fxn, call_graph):
"""
Looks up the dictionary associated with the function.
:param tu: The translation unit in which to look for locals functions
:param fxn: The function name
:param call_graph: a object used to store information about each function
:return: the dictionary for t... | e73783b2eddadcbbc9e9eff39073805fc158c34e | 50,466 |
def _prepare_embeddings(h, m):
"""
Combine FCN outputs with segmentation masks to build a batch of
mask-pooled hidden vectors. Represents the calculation of h_{m}
in the first equation in Henaff et al's paper
:h: batch of embeddings; (N,w,h,d)
:m: batch of NORMALIZED segmentation tensors; ... | 9a8f8f77fa4fdaf340978b6c0320a755b5c4b8a7 | 50,467 |
def estimate_mode_width(distribution):
"""Estimate mode and width-at-half-maximum for a 1D distribution.
Parameters
----------
distribution : array of int or float
The input distribution. ``plt.plot(distribution)`` should look
like a histogram.
Returns
-------
mode : int
... | 6ed4370391fa227d31f4330d9afbabb2795fc9d0 | 50,468 |
def agent_hostname_by_id(agent_id):
"""Given a agent_id provides the agent ip"""
for agent in __get_all_agents():
if agent['id'] == agent_id:
return agent['hostname']
return None | 62fc3510790b8b47a17e98f6394b984628f0073b | 50,469 |
def parse_tile_name(name: str):
""" Parse the tile """
match = reTILE.match(name)
if match is None:
return None
groups = match.groupdict() # type: Dict[str, Any]
groups['tile'] = int(groups['tile'])
return groups | 3bd2219fbefb828bfaea77ac6cd1be3947bb9c63 | 50,470 |
import os
def save_format(file):
"""Return 'mat' or 'py' based on file name extension."""
ext = os.path.splitext(file)[1]
return ext[-(len(ext) - 1):] | a52b05a368034b54ce6d362b714369d7952a3786 | 50,471 |
import urllib3
import re
import urllib
import json
import time
def query_object_elasticsearch(query_string, item_type="tor"):
"""Return a dict of Elasticsearch results."""
# make an http request to elasticsearch
#pool = urllib3.HTTPSConnectionPool(settings.ELASTICSEARCH_HOST,
# settings.ELASTIC... | b3b75deaaf4e4f393d4374f6f329009035bfe26d | 50,472 |
from typing import List
def article_to_frequency(article: str) -> List[int]:
"""Convert an article or article description to a list of numbers.
:param article: The article or article description
:return: A list of numbers corresponding to the words
"""
numbers: List[int] = [0] * len(common_words)... | 26f2036a3e3e2bf5dedeef6a068b77f33b559108 | 50,473 |
import os
def track_requests(fn):
""" Decorator to log 21 sell request data.
Args:
fn: function to wrap
"""
@wraps(fn)
def decorator(*args, **kwargs):
service_name = os.environ["SERVICE"]
url = request.url
host = request.headers["Host"]
endpoint = url.st... | 49102bcdf936fa73be1cd7d2c9dd1621f08569f0 | 50,474 |
def Date(default=None, validator=None, repr=False, eq=True, order=True, # NOQA
converter=None, label=None, help=None,): # NOQA
"""
A date attribute. It always serializes to an ISO date string.
Behavior is TBD and for now this is exactly a string.
"""
return String(
default=defau... | ed814cdb67953c05eeb066c008c40f6dffaca49e | 50,475 |
def compute_confuse_matrix_batch(y_targetlabel_list,y_logits_array,label_dict,name='default'):
"""
compute confuse matrix for a batch
:param y_targetlabel_list: a list; each element is a mulit-hot,e.g. [1,0,0,1,...]
:param y_logits_array: a 2-d array. [batch_size,num_class]
:param label_dict:{label:... | 70b4a238a4f64d5a2d97f1ca9e5e0c4c6c7cf14b | 50,476 |
def jsonify_item(category_id, item_id):
"""Return an item information of a category in JSON"""
try:
item = db.session.query(Item).filter_by(
category_id=category_id, id=item_id).one()
return jsonify(Item=item.serialize)
except Exception as e:
abort(404) | 6fd07ff2dfab3bccdbdb29a019f95060d7896370 | 50,477 |
from typing import Union
from typing import Tuple
def parse(source: Union[str, bytes], fnam: str = None, errors: Errors = None,
pyversion: Tuple[int, int] = defaults.PYTHON3_VERSION,
custom_typing_module: str = None) -> MypyFile:
"""Parse a source file, without doing any semantic analysis.
... | 34b7c9d4d868d442c3c92bba98f8cf3bca3c2cf8 | 50,478 |
def encode_multipart_formdata(fields, files):
#http://code.activestate.com/recipes/146306/
"""
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return (content_type, body) ready for httplib.HTTP instance... | 4f4ab117f922bc38b512794f63abfc2c0355921b | 50,479 |
import re
def ParseMaxRevision(revision_list):
"""Returns the max revision from a list of url@revision string."""
revision_re = re.compile(r'.*@(\d+)')
def RevisionKey(revision):
return revision_re.match(revision).group(1)
max_revision = max(revision_list.split(), key=RevisionKey)
return max_revision.... | e40b1faaf10f0c0b7b0d6118bccd7c0de8d1c030 | 50,480 |
from typing import List
def get_resolv_conf_namservers() -> List[str]:
"""Return list of namserver IPs in /etc/resolv.conf."""
result = []
with open("/etc/resolv.conf") as f:
for line in f:
parts = line.lower().split()
if len(parts) >= 2 and parts[0] == 'nameserver':
... | 859b5811d92778458896dc6fdca4043b6072457a | 50,481 |
import csv
import codecs
def import_gloss_csv(request):
"""
Check which objects exist and which not. Then show the user a list of glosses that will be added if user confirms.
Store the glosses to be added into sessions.
"""
glosses_new = []
glosses_exists = []
# Make sure that the session ... | bb8fb5118832178d56dde8a7c7ad2dfed422f076 | 50,482 |
import os
import torch
def transfer_cnn_weights(model, source_path, split, selection="best_balanced_accuracy", cnn_index=None):
"""
Set the weights of the model according to the CNN at source path.
:param model: (Module) the model which must be initialized
:param source_path: (str) path to the source ... | 8f6e1c0a05a3a8f173bcb5211fdfec23f9ab519d | 50,483 |
import numpy
def vis_timeslices(vis: Visibility, timeslice='auto') -> int:
""" Calculate number of time slices in a visibility
:param vis: Visibility
:param timeslice: 'auto' or float (seconds)
:return: Number of slices
"""
assert isinstance(vis, Visibility) or isinstance(vis, BlockVisibility... | d9cf407f5a9e8456c7371cb2d3de05a7404e8e86 | 50,484 |
import torch
def alexnet_metapoison(widths=[16, 32, 32, 64, 64], in_channels=3, num_classes=10, batchnorm=False):
"""AlexNet variant as used in MetaPoison."""
def convblock(width_in, width_out):
if batchnorm:
bn = torch.nn.BatchNorm2d(width_out)
else:
bn = torch.nn.Iden... | 40f84a7d434cd68b9f824ee847ea045e4479f5be | 50,485 |
import subprocess
def find_paths_with_suid_sgid(root_path):
"""Finds all paths/files which have an suid/sgid bit enabled.
Starting with the root_path, this will recursively find all paths which
have an suid or sgid bit set.
"""
cmd = ['find', root_path, '-perm', '-4000', '-o', '-perm', '-2000',
... | af6ce23d72b0c56b681abf01e4c0c19c585190c2 | 50,486 |
def checksum(message):
"""
Calculate the GDB server protocol checksum of the message.
The GDB server protocol uses a simple modulo 256 sum.
"""
check = 0
for c in message:
check += ord(c)
return check % 256 | bfba144414f26d3b65dc0c102cb7eaa903de780a | 50,487 |
import torch
def sds_bmm_torch(s_t1, d_t2):
"""
bmm (Batch Matrix Matrix) for sparse x dense -> sparse. This function doesn't support gradient.
And sparse tensors cannot accept gradient due to the limitation of torch implementation.
with s_t1.shape = (b, x, s), d_t2.shape = (b, s, y), the output shape... | a17daf9b000d808ab3a3cf18590373480de2d543 | 50,488 |
def calc_fires(mappability_filename, cooler_filenames, bin_size, neighborhood_region, perc_threshold=.25, avg_mappability_threshold=0.9):
"""Perform FIREcaller algorithm.
Parameters:
----------
mappability_filename : str
Path to mappability file
cooler_filenames : str
List of paths ... | 6d221fe4a9110b7480dee221b23036dd0748cedb | 50,489 |
def parse_report_filter_values(request, reports):
"""Given a dictionary of GET query parameters, return a dictionary mapping
report names to a dictionary of filter values.
Report filter parameters contain a | in the name. For example, request.GET
might be
{
"crash_report|operating_... | 217a7bfdeb65952637774ebefb6ae0ea7a0d991c | 50,490 |
def generate_jwt(payload):
"""Encode given payload to jwt, return encoded jwt, private key, public key
Args:
payload (dict): the payload to be encoded in the jwt
Returns:
Encoded jwt(json), private key (str) used to encode the payload, public key(str) used to encode the payload
"""
... | 17fec33ea1f8c912740d2833132a26921d052578 | 50,491 |
def advantage_returns(rewards, values, gamma, lam):
"""Compute the advantage and returns from rewards and values."""
# GAE-Lambda advantage calculation.
deltas = rewards[:-1] + gamma * values[1:] - values[:-1]
advantages = discount(deltas, gamma * lam)
# Compute rewards-to-go (targets for the value ... | 1cca149bf6a583fd3932ce4cfaad7ef66d6682f6 | 50,492 |
import itertools
def iter_extend(iterable, length, obj=None):
"""Ensure that iterable is the specified length by extending with obj"""
return itertools.islice(itertools.chain(iterable, itertools.repeat(obj)), length) | 1e6a2bdd36b8bcb3202c4472c9e7621eef9edcf1 | 50,493 |
def _ldap_search(cnx, filter_str, attributes, non_unique='raise'):
"""Helper function to perform the actual LDAP search
@param cnx: The LDAP connection object
@param filter_str: The LDAP filter string
@param attributes: The LDAP attributes to fetch. This *must* include self.ldap_username
@param non... | 4153b6f35f8281a2e41f74200d254f468d8bba0b | 50,494 |
import yaml
def read_yaml(filename:str) -> dict:
"""
Return dic from yaml.
Args:
filename: Output file name.
Returns:
dict: Dictionary object.
"""
with open(filename, 'r') as f:
dic = yaml.load(f, Loader=Loader)
return dic | 9260e1640e1ebfeebb2fb14aeebc3abd87f0d919 | 50,495 |
import hashlib
def download(id):
"""Serve the pickle file"""
passwd = hashlib.sha256(ID.encode()).hexdigest()
if id == passwd:
return send_file("model.pickle", as_attachment=True) | 823b3d53b627b7890dd69e36c6e7daeb4f74f650 | 50,496 |
def get_common_prefix(string_1, string_2):
"""Find the largest common prefix of two strings.
Args:
string_1: A string.
string_2: Another string.
Returns:
The longest common prefix of string_1 and string_2.
"""
# If either string_1 or string_2 is the empty string, the common
... | 1b9d0ba5742c30dff4b06ea02cc4a71a228d82a0 | 50,497 |
def get_user_limit(session: Session, group: Group, modifier: int) -> bool:
"""
Comparing number of free seats and number of users in group and
subgroups with parent groups.
:return: False if space is exhausted.
"""
max_seats = get_num_seats(session, group)
num_users = get_num_users(session,... | 0ce0d460f621355cdbfd61cd9f98f0ec2869103e | 50,498 |
def test_get_annotations_no_data(
pandas_series, coordination_args, monkeypatch
):
"""Test coordination of annotation retrieval when no data retrieved for a given protein."""
def mock_get_anno(*args, **kwargs):
protein_data = []
return protein_data
monkeypatch.setattr(get_genbank_annot... | edb05ace156c0852bd2952615bd195caa12610a2 | 50,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.