content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def value_iteration(p, reward, discount, eps=1e-3):
"""
Basic value-iteration algorithm to solve the given MDP.
Args:
p: The transition probabilities of the MDP as table
`[from: Integer, to: Integer, action: Integer] -> probability: Float`
specifying the probability of a tra... | 82382a8c8fecc578333654a6823463a3d609d300 | 64,600 |
def _ui_device_family_plist_value(ctx):
"""Returns the value to use for `UIDeviceFamily` in an info.plist.
This function returns the array of value to use or None if there should be
no plist entry (currently, only macOS doesn't use UIDeviceFamily).
Args:
ctx: The Skylark context.
Returns:
A list of ... | 831f93e497e8c7e98b66d457b57cffae75942013 | 64,601 |
def extract(input_data: str) -> list:
"""take input data and return the appropriate data structure"""
entries = []
for line in input_data.split('\n'):
instruction = (line[0], int(line[1:]))
entries.append(instruction)
return entries | a201917fd0c0d08e8c6c035d603480c01b0e76de | 64,602 |
def pylsp_completion_item_resolve(completion_item, document):
"""Resolve formatted completion for given non-resolved completion"""
shared_data = document.shared_data['LAST_JEDI_COMPLETIONS'].get(completion_item['label'])
if shared_data:
completion, data = shared_data
return _resolve_completi... | cf7b61e576ec4c3dc01df2528c625b604a902e6e | 64,603 |
def python_2_unicode_compatible(cls):
"""
A decorator that defines __unicode__ and __str__ methods under Python
2. Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__
method returning unicode text and apply this decorator to the class.
The im... | 963de9e2759a58e2e6138490f62609299b656ed7 | 64,604 |
import requests
def get_B1020(
APIKey='AP8DA23',
StartDate='2021-01-01',
EndDate='2021-01-02',
StartTime='00:00:00',
EndTime='23:59:59',
ServiceType='csv',
endpoint='https://api.bmreports.com/BMRS/B1020/v1'
):
"""Changes In Actual Availability In The Transmission Grid
"""
... | 255589966d5f0ced1a1b0c3e19625ec401b287d3 | 64,605 |
def _injectCompanionData(data, delta, param):
"""
Inject analytically a companion defined as 'param' in the 'data' using
'delta'. 'delta' contains the corresponding V2 for T3 and CP first order
calculations.
data and delta have same length
"""
global CONFIG
bi = _modelObservables(data,... | 16cd1d1473f1b5f9d1c12d392ff53f66fc640b70 | 64,606 |
def adjust_hue(img, hue_factor):
"""PRIVATE METHOD. Adjust hue of an image.
.. warning::
Module ``transforms.functional_pil`` is private and should not be used in user application.
Please, consider instead using methods from `transforms.functional` module.
The image hue is adjusted by con... | 32ab5f172f06220b0e1b819efa5e3e902023500a | 64,607 |
def countSimulation(fsFeatures, ssFeatures, npts, fieldFS, fieldSS, idFieldFS, Global = True):
""" Simulates point counts, proportionally, within higher geography (ZIP CODES), matches lower geography (BLOCKS)
to the higher geography by centroid locations, and simulates point counts, proportionally, within ... | 4ef39a4ad841b4aab17f171a8df11a21fffbba0a | 64,608 |
from typing import Optional
def send_slack_message(
message_type: MessageType,
project_name: str,
project_id: Optional[str],
details: str = "no details provided",
):
"""Initialize slack client with values provided in environment."""
if SLACK_TOKEN is None or SLACK_CHANNEL is None:
logg... | bc7dd3256d5120e8bdaf9b1fb5f7d53e456905e4 | 64,609 |
def pairwise_link_collision(body1, link1, body2, link2=BASE_LINK, max_distance=MAX_DISTANCE, distance_threshold=0.0):
"""check pairwise collision between bodies
See getClosestPoints in <pybullet documentation `https://docs.google.com/document/d/10sXEhzFRSnvFcl3XxNGhnD4N2SedqwdAvK3dsihxVUA/edit?usp=sharing`>_
... | 2860ff4e6327bee7ad29dd0073c3b6ecf979fd2c | 64,610 |
from typing import Optional
from typing import Deque
def build_tree(values: list[Optional[int]]) -> Optional[Node]:
"""Builds tree out of given values"""
if len(values) == 0:
return None
if values[0] is None:
return None
root = Node(values[0])
queue: Deque[Node] = deque()
cu... | fd0bf9a5b0bae057851c89a662c8224f768a5840 | 64,611 |
def sim(embed1, embed2, metric='inner', normalize=False, csls_k=0):
"""
Compute pairwise similarity between the two collections of embeddings.
Parameters
----------
embed1 : matrix_like
An embedding matrix of size n1*d, where n1 is the number of embeddings and d is the dimension.
embed2... | 9055c26372758e447c594cc6afd04b2c2aaeada3 | 64,612 |
def lambda_context():
"""Generates An Context"""
class Context:
@staticmethod
def get_remaining_time_in_millis():
return 200000
return Context() | f86f0846ca3317284e11b7b8ec110805b6533e4d | 64,613 |
def find_piece_size(total_size):
""" Determine the ideal piece size for a torrent based on the total
size of the data being shared.
:param total_size: Total torrent size
:type total_size: int
:return: Piece size (KB)
:rtype: int
"""
if total_size <= 2 ** 19:
return 512
elif ... | 532adc41448ce5dfb11f02699c987936e1abda0a | 64,614 |
from typing import Type
def format_type(typ: Type, verbosity: int = 0) -> str:
"""
Convert a type to a relatively short string suitable for error messages.
`verbosity` is a coarse grained control on the verbosity of the type
This function returns a string appropriate for unmodified use in error
... | 884fc9167999c9f83b82d716a3cc69d08515cac7 | 64,615 |
def __parse_string_literal_expression_tokens(tokens: list[Token]) -> (StringLiteralExpression, int):
"""Parse a StringLiteralExpression from a list of tokens."""
if tokens[0].kind != TokenKind.STRING_LITERAL:
raise UnexpectedTokenError(TokenKind.STRING_LITERAL, tokens[0].kind)
return StringLiteralE... | 4a22a153c054ccb5ec92016fbb909d8890ffcbe9 | 64,616 |
import os
import re
def get_recipes(working_directory):
"""Returns the paths to recipes and expectation file directories.
Args:
working_directory (str): absolute path to the directory where the recipes
are located.
Returns:
latest_recipes (str[]): paths to all unbranched reci... | 61c4824c3f8acf10cd160c76d3970a786bcef470 | 64,617 |
def build_material_head(cfg, input_shape):
"""
Build a material head defined by `cfg.MODEL.ROI_MATERIAL_HEAD.NAME`.
"""
name = cfg.MODEL.ROI_MATERIAL_HEAD.NAME
# TODO changed this:
return ROI_MASK_HEAD_REGISTRY.get(name)(cfg, input_shape) | 28f895315c7575f8fb0f68a1d27fa4bef9c79b18 | 64,618 |
def camel_case_split(s):
"""Converts a CamelCase name to be split by spaces.
e.g. "CovertHTMLToText" -> "Convert HTML To Text"
"""
def convert(match):
content = match.group()
if match.start() == 0:
return content
else:
return " %s" % content
return ... | cb0bd8007d804e69f45b8e1e8b791acd6dd423c0 | 64,619 |
def add_ranking(survey_df):
"""
adds a rank between (1, #of entries / day) to every report
:param survey_df: df with a column "submitted_at"
:returns: a df that has a new column "rankings"
"""
survey_df.submitted_at = pd.to_datetime(survey_df.submitted_at)
survey_df["submitted_at_day"] = sur... | 8d4ae088d6df9189c67ee5cabd7903ae1d18eaaa | 64,620 |
from typing import Literal
def estimate_corr_inverse_params(copula, data: np.ndarray, type_: Literal['itau', 'irho']):
"""
Fits the copula with the inversion of Spearman's rho or Kendall's tau Estimator
Parameters
----------
copula
Copula whose parameters are to be estimated
data
... | 8d66dbb83e38565f2941a3859122cceb5f874b66 | 64,621 |
def fake_file(filename, content="mock content"):
"""
For testing I sometimes want specific file request to return
specific content. This is to make creation easier
"""
return {"filename": filename, "content": content} | 5b342edf9dec65987223fbbc8b670402513ae4ed | 64,622 |
from typing import Type
from typing import Union
def command(command_name: str) -> Type[Union[SimpleCommand, ComplexCommand]]:
"""
Registers a class as a command. If the class' parent is SimpleCommand, then it will use the abstracted methods.
If the class' parent is ComplexCommand, then any method decorat... | 9e1b9585d8f4e94fdf1260013086512f2dc98237 | 64,623 |
import hashlib
def sha256d(data):
"""Hash sha256 twice"""
return hashlib.sha256(hashlib.sha256(data)) | 30a19b18e81b6fd55de48f3e60d76f56d24ecdf7 | 64,624 |
def _convert_string(key):
"""Convert OEIS String to Integer."""
if isinstance(key, str):
key = int(key.strip().upper().strip("A"))
return key | b99a93089f655d4a8941fc1939211acc5645ef80 | 64,625 |
from typing import Union
from typing import Any
def in_context(
result: Union[_Value_co, Err, None], **contexts: Any
) -> Union[_Value_co, Err, None]:
"""
Adds context to an error contained in a result type (when applicable)
This function has different signatures depending on the argument types.
... | 03ae292c035f4859bff7f45e05202d3f412b2db2 | 64,626 |
def rot(img, angle, xc=False, yc=False,
dx=0, dy=0, xmargin=0, ymargin=0, missing=0):
"""
Rotate the input image.
Parameters
----------
img : `~numpy.ndarray`
2 dimensional array of image.
angle : `float`
Roation angle in 'radian' unit.
xc : (optional) `float`
... | cb448261535b402702686aa3e238fb813bc7eaea | 64,627 |
def find_note_chapter(connection, note_id, title):
"""
搜索章节信息的字典
:param connection:
:param note_id:
:param title:
:return: 章节信息字典
"""
with connection.cursor() as cursor:
sql = "select * from chapter where note_id=%s and title=%s "
cursor.execute(sql, (note_id, title))
... | 49c9c51efcd266c18d37441a536e81f7605dbb93 | 64,628 |
def concurrent_exec(func, iterable, num_threads):
"""
Executes a function on a list of inputs in parallel by dividing the work
among multiple threads.
Parameters
----------
func : ...
function to execute
iterable : list
list of arguments to map the function to
num_thread... | a555650d3b27d744a8912cc5a44bbf05eeba6297 | 64,629 |
def register_skim_access_variable(
column_name, variable_to_summarize, impedance_measure,
distance, skims_table, agg=np.sum, log=False):
"""
Register skim-based accessibility variable with orca.
Parameters
----------
column_name : str
Name of the orca column to register this ... | 2d2d1f4a49fe56654ded3a34bf178a08f5abc6c9 | 64,630 |
def run_async(coro_obj):
"""异步运行协程对象。协程中依然可以调用 PyWebIO 交互函数。 仅能在 :ref:`基于协程 <coroutine_based_session>` 的会话上下文中调用
:param coro_obj: 协程对象
:return: `TaskHandle <pywebio.session.coroutinebased.TaskHandle>` 实例。 通过 TaskHandle 可以查询协程运行状态和关闭协程。
参见::ref:`协程会话的并发 <coroutine_based_concurrency>`
"""
return... | 335b6d2d765af06f30940d7b34f7935a1fb4f990 | 64,631 |
from .py3AES import encryptData
from .py3PBKDF2 import hashPasswordTuple
import base64
def dataEncrypt(data, password, keyLength=32, hashIterations=10000):
"""
Module function to encrypt a password.
@param data data to encrypt (bytes)
@param password password to be used for encryption (string)
@k... | a26e081c9f2646afc29f0976bc2c16573464fa1a | 64,632 |
def get_version_from_build_id(domain, build_id):
"""
fast lookup of app version number given build_id
implemented as simple caching around _get_version_from_build_id
"""
if not build_id:
return None
try:
build = get_app(domain, build_id)
except (ResourceNotFound, Http404):... | f22f80c67aacc5b86fc1bc79b9b20f316bc12b26 | 64,633 |
def _get_create_kwargs(
skip_translate=None,
ignore_collisions=False,
validate_ip_addrs=True,
client_args=None,
**kwargs
):
"""
Take input kwargs and return a kwargs dict to pass to docker-py's
create_container() function.
"""
networks = kwargs.pop("networks", {})
if kwargs.... | 4fd3245c02e2743e5cc86a49858d8c4d65594a44 | 64,634 |
def flatten(sequence):
"""Given a sequence possibly containing nested lists or tuples,
flatten the sequence to a single non-nested list of primitives.
>>> flatten((('META.INSTRUMENT.DETECTOR', 'META.SUBARRAY.NAME'), ('META.OBSERVATION.DATE', 'META.OBSERVATION.TIME')))
['META.INSTRUMENT.DETECTOR', 'META... | 6ca3fe470757dc4081c4387d917d5e285c2a3f06 | 64,635 |
from skimage.transform import rescale
def impreprocess(rimg,**kwargs):
"""
return a [nchan,ncols,nrows] image which has been rotated to fill its
nonzero bounding box and filtered
"""
rotate = kwargs.pop('rotate',False)
scale = kwargs.pop('scale',1.0)
crop = kwargs.pop('crop',True)
int... | 0bf57c0a6ea1f8973c908d3ba7bea67365a7e60d | 64,636 |
def relevant_rule(rule):
"""Returns true if a given rule is relevant when generating a podspec."""
return (
# cc_library only (ignore cc_test, cc_binary)
rule.type == "cc_library" and
# ignore empty rule
(rule.hdrs + rule.textual_hdrs + rule.srcs) and
# ignore test-only rule
not ... | 3e1a45d222128e0065eb585135806a0f8bb787d9 | 64,637 |
def schedule_elemwise(outs):
"""Schedule for element wise op.
Parameters
----------
outs: Array of Tensor
The computation graph description of reduce in the format
of an array of tensors.
Returns
-------
sch: Schedule
The computation schedule for the op.
"""... | 26fd0ac5494f469b8c14b560fdb2c6ab565268a0 | 64,638 |
from typing import List
def get_neighbors(row: int, column: int, seats: List[str]):
"""
Returns the eight (or fewer) neighbor cells of a given cell
"""
return "".join(
get_seat(r, c, seats)
for r in range(row - 1, row + 2)
for c in range(column - 1, column + 2)
if r != ... | cadbbd73669db21b06c35fd59a437885fbe9aaac | 64,639 |
import tqdm
import yaml
def ensure_fairsharing(force_download: bool = False, use_tqdm: bool = True, **kwargs):
"""Get the FAIRsharing registry."""
if PATH.exists() and not force_download:
return PATH
client = FairsharingClient(**kwargs)
# As of 2021-12-13, there are a bit less than 4k records... | 2d5c85edf692861f16c27f0b71096314bb865c7d | 64,640 |
def get_resampled_df(df, y_col, count, strategy='max'):
"""Resampling dataframe for imbalanced dataset.
count: The number used by strategy for sampling
strategy:
min - oversamples minority below the count for respective y
max - undersamples majority over the count for respective y
# TODO: fixed ... | 859db98d1e3904272d1821f6a3e04226ccbe7106 | 64,641 |
import csv
def getProblemNumber(metadir, pid, lang):
"""
Get number of accepted solutions of a required problem
Parameters:
- metadir -- path to directory with metadata
- pid -- problem id
- lang -- language
"""
problem_data_fn = makeFilePath(metadir, pid + ".csv",
... | 6a45c33a347b72adda4de398bf108da67297c9af | 64,642 |
def IsMergeAllowed(merge_into_issue, mr, services):
"""Check to see if user has permission to merge with specified issue."""
merge_into_project = services.project.GetProjectByName(
mr.cnxn, merge_into_issue.project_name)
merge_into_config = services.config.GetProjectConfig(
mr.cnxn, merge_into_project... | a1acca8a889c872c792181cf3b8624f9b4f30715 | 64,643 |
import os
import subprocess
def _download_ensembl_gff(build):
"""Given build details, download and extract the relevant ensembl GFF.
"""
fname = build.fbase + ".gtf.gz"
dl_url = "/".join([base_ftp, build.taxname, fname]).format(release=ensembl_release)
out_file = os.path.splitext(os.path.basename(... | 1646f136c0ca498bf139350ade8a786c474b41cd | 64,644 |
from typing import Tuple
async def get_gain_correct(
mass: MusicAssistant, player_id: str, item_id: str, provider_id: str
) -> Tuple[float, float]:
"""Get gain correction for given player / track combination."""
player_conf = mass.config.get_player_config(player_id)
if not player_conf["volume_normalis... | 28d1666a7fa9440e62d5ec2ccb3b876121123b4c | 64,645 |
from typing import Optional
import logging
async def issuer_create_and_store_credential_def(wallet_handle: int,
issuer_did: str,
schema_json: str,
tag: str,
... | 3769c23d8b67b12b4816ab9b0c36106706e802d2 | 64,646 |
import glob
import tqdm
def load_patch_files(start_date: str, end_date: str, run_freq: str, patch_dir: str, input_variables: list,
output_variables: list, meta_variables: list,
patch_radius=None, mask=False) -> tuple:
"""
Iterate through all patch files and load the i... | e5ed677cb1069d7b1d5a7f921c06544ded1a7f74 | 64,647 |
import re
def is_contest(tweet):
"""
Guess if a tweet is a legit RT-to-win contest.
"""
# Throw away "manual retweets" that match "RT @username"
manual_retweet = re.compile('^RT:? ?@\S', re.IGNORECASE)
if manual_retweet.match(tweet.text) is not None:
return (False, 'manual RT')
# ... | 94b44e8efc283ae59932004b6b27a798cb6ff5b4 | 64,648 |
def ancestors(pfunc, *orignodes):
"""
Returns the common ancestors of a and b that are furthest from a
root (as measured by longest path).
pfunc must return a list of parent vertices for a given vertex.
"""
def deepest(nodes):
interesting = {}
count = max(nodes) + 1
dept... | 511452ac5ef6327341a54bb91dd920b40fb1c35f | 64,649 |
def tpm3_exon1_exon8_offset():
"""Create test fixture for TPM3."""
params = {
"chr": "NC_000001.11",
"gene": "TPM3",
"start": 154192132,
"exon_start": 1,
"exon_start_offset": 3,
"end": 154170404,
"exon_end": 8,
"exon_end_offset": -5,
"trans... | 4bb9b81e58e01ad45dd713408fba3cad5421b092 | 64,650 |
def a(value):
"""
Толщина проушины
Returns: толщина проушины
"""
return force / (bolt_diameter() * value * sigma) | 47fce4d2ab51762287e0003a4858236ae17b97b2 | 64,651 |
def layernorm(x, scope, epsilon=1e-5, relu=False):
"""
normalize state vector to be zero mean / unit variance + learned scale/shift
"""
n_state = shape_list(x)[-1]
with tf.variable_scope(scope):
gain = tf.get_variable('gain', [n_state], initializer=tf.constant_initializer(1))
bias = ... | 7d334d67da5ed1dae6349595a5b23a69c5505752 | 64,652 |
def mark_outside_black(img, mask):
"""
Mark white background as black
@Param @mandatory img image input
@Param @mandatory mask mask to use
@Return image, mask
"""
# Mark the outside of the house as black
contours, _ = cv2.findContours(~img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
... | ae311e7bd1d5e47d54c27e35aa511e83c4b24c3f | 64,653 |
def get_channel_id_and_message_id(message):
"""
Gets the message's channel's and it's own identifier.
Parameters
----------
message : ``Message``, ``MessageRepr``, ``MessageReference``, `tuple` (`int`, `int`)
The message or it' representation.
Returns
-------
channel_id... | ba6c17e954e57baa7706fc6216e23a6bc792df69 | 64,654 |
import scipy.special
def detectSignalToNoiseThresholdToNoisePd(ThresholdToNoise, pD):
""" Solve for the signal to noise ratio, given the threshold to noise ratio and
probability of detection.
Using the theory of matched filter design, calculate the
signal to noise ratio, to achieve a required probabi... | b654e2429f2a5501857aa37b1a65754c54a9916f | 64,655 |
import os
import hashlib
def get_hash256(fname_or_bdata, start_addr=None, end_addr=None):
""" calculate SHA 256
It calculates hash256 32 bytes either from a binary file or from binary data in bytes/bytearray
If fname_or_bdata is a file, default from offset 0 to the end of file.
Input start, end address if on... | a6907d3ec7fa20745b23119b767ae2f54ad3fd34 | 64,656 |
def order_by_line_nos(objs, line_nos):
"""Orders the set of `objs` by `line_nos`
"""
ordering = sorted(range(len(line_nos)), key=line_nos.__getitem__)
return [objs[i] for i in ordering] | 6ae7a31a4ecad19cb0efb059ed43eddcf952c15e | 64,657 |
def _decrement_version(lambda_config):
"""Decrement the Lambda version, if possible.
Args:
lambda_config (dict): Lambda function config with 'current_version'
Returns:
True if the version was changed, False otherwise
"""
current_version = lambda_config['current_version']
if cur... | a06ed14e0abaa68a809bdb49c2d4f2cc59ce6db2 | 64,658 |
import torch
def idxst(x, expk, buf, out):
"""compute inverse discrete sine transformation
This is different from ordinary formulation for IDCT III
yk = Im { \sum_{n=0}^{N-1} xn exp(j*pi/(2N)*n*(2k+1)) }
"""
if x.is_cuda:
dct_cuda.idxst(x.view([-1, x.size(-1)]), expk, buf, out)
else:
... | d35bf321830cc50cb2b109e6e82f8fcd47d150a5 | 64,659 |
def is_valid(number):
"""Check if the number is valid. This checks the length, format and check
digit."""
try:
return bool(validate(number))
except ValidationError:
return False | 98397aacb84eb60b30e2e98af0ccca14b4dcfedf | 64,660 |
import json
def get_alarm_source(request, cc_biz_id, source_type, source_id):
"""
获取告警源的配置信息
"""
try:
alarm_app = AlarmApplication.objects.get(id=source_id, )
except Exception:
result = {'result': False, 'message': _(u"告警源[id:%s]不存在") % source_id}
return HttpResponse(json.d... | 0dac8e8095e2f9a82d59987e5d1bf344107d640b | 64,661 |
def input():
"""
Mocks the 'input()' function.
If arguments is not None, it resets the arguments used.
"""
return list_of_inputs.pop(0) | b02b11058d944393114e8b61a22a28dbc5429871 | 64,662 |
def std_norm(a):
"""Normalize to +-4 sigma on the range 0 to 1"""
mean = a.mean()
std = a.std()
o = (( a - mean) / std).clip(-4,4) # Def of z-score
o += 4
o /= 8
try:
o.set_fill_value(0)
except AttributeError:
# If it isn't a masked array
pass
... | f6d3bb35a51f7f695176fe4fb5a3bfcff5ffbc03 | 64,663 |
from datetime import datetime
def about(request):
"""Renders the about page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/about.html',
context_instance = RequestContext(request,
{
'title': 'About',
'message': 'Your applicat... | 0ac00d53a04da373b56d4078df527c951522be90 | 64,664 |
import pathlib
from datetime import datetime
def all_possible_urls(end_date):
"""Returns urls and saving path for all possible files to download
:param end_date:
:return:
"""
# This is the base url and the file extension
url = AlgoSettings().fxcm_data_path()
store_path = pathlib.Path(Algo... | 836f4110209946286384ff7cec59c5f1d192e8f2 | 64,665 |
from datetime import datetime
import calendar
def GetBannerTime(timestamp):
"""Converts a timestamp into EZT-ready data so it can appear in the banner.
Args:
timestamp: timestamp expressed in the following format:
[year,month,day,hour,minute,second]
e.g. [2009,3,20,21,45,50] represents Marc... | 8cd76259e206316486d171418a60acf0629c8643 | 64,666 |
def project_biases(tf_features, n_features):
"""
Projects the biases from the feature space to calculate bias per actor
:param tf_features:
:param n_features:
:return:
"""
tf_feature_biases = tf.Variable(tf.zeros([n_features, 1]))
# The reduce sum is to perform a rank reduction
tf_p... | 71db9d76792cf1c6a49cd10b135fa15ee1a7f371 | 64,667 |
def parse(text):
""" Top-level function for parsing user's text to an ObserverExpression.
Parameters
----------
text : str
Text to be parsed.
Returns
-------
expression : ObserverExpression
"""
tree = _LARK_PARSER.parse(text)
return _handle_tree(tree) | e679c05ad73c9670deabe2bb43bf60c5bf3bf613 | 64,668 |
def detailsAuction(username, leilaoId):
"""Consultar os detalhes de um determinado leilão"""
try:
valid = utils.validateTypes([leilaoId], [int])
if not valid:
return jsonify({'erro': 404})
details = db.detailsAuction(leilaoId)
db.connection.commit()
if details... | 18afecb8c07fe084252931c114ca701f1ace2270 | 64,669 |
import numpy
def saccade_detection(x, y, time, missing=0.0, minlen=5, maxvel=40, maxacc=340):
"""Detects saccades, defined as consecutive samples with an inter-sample
velocity of over a velocity threshold or an acceleration threshold
arguments
x - numpy array of x positions
y - numpy array of y positions
... | 8eb205402bdaa69d4e10fdf590c98ca3b386684c | 64,670 |
import copy
def create_assert_data(expected_data):
"""Update EXPECTED_STUB-like structure with appropriate data
Args:
cavs_data: {ind: {key:value, }, }.
ind - indexes of EXPECTED_STUB list (0,1) to update,
key - fields to be updated in stub,
value - values for appropriate fields.
... | 0082ea84b0f35ea1be69ea6090a7ff1a5c75cb76 | 64,671 |
import numpy
def tile_raster_images(X, img_shape, tile_shape, tile_spacing=(0, 0),
scale_rows_to_unit_interval=True,
output_pixel_vals=True):
"""
Transform an array with one flattened image per row, into an array in
which images are reshaped and layed out like tiles... | af9428a18fb39b6b33dd349339a99918604188f0 | 64,672 |
def add_role_member(session, role_id, payload):
"""Create a proposal for adding a role member
Args:
session:
object: current session object
role_id:
str: id of role that is to be added to
payload:
dictionary: in the format of
{
... | ec938d13076c1a15829bdd58fc5db9f283bf5d61 | 64,673 |
def scale_image(input_image, image_size, scale, interpolation=Image.BICUBIC):
"""Scale a PIL Image and return the output image and size."""
input_image.thumbnail((int(image_size.x * scale), int(image_size.y * scale)),
interpolation)
image_size = utils.XY(*input_image.size)
return input_i... | 739debdc5ddc259e47e31593b83e26fd10f6d626 | 64,674 |
from typing import Tuple
import pathlib
from datetime import datetime
def get_new_report_name_and_path() -> Tuple[str, pathlib.PurePath]:
"""Get the name and path of a report which is being created.
Returns:
Tuple[str, pathlib.PurePath] -- filename and path of report being created
"""
report_... | 70720c698d7b7872e40c62b2dda9aaf37ec8b666 | 64,675 |
from s3 import S3DateFilter, S3OptionsFilter, S3TextFilter
from re import T
from datetime import datetime
def due_followups():
""" RESTful Controller for Due Follow-ups """
# CRUD Strings
s3.crud_strings["po_household_followup"] = Storage(
title_display = T("Follow-up Details"),
title_lis... | 19fa17e7361f5a8eeaa2624dc777bcce6171659d | 64,676 |
import collections
def rollout(env, agent, max_steps):
"""Collects a single rollout of experience.
Args:
env: The environment to interact with (adheres to gym interface).
agent: The agent acting in the environment.
max_steps: The max number of steps to take in the environment.
Re... | eb9a9f41b9c37e1c5f8ebdbbec13650dd7665622 | 64,677 |
def generate_derivatives(ts: [list, np.array], verbose=False) -> pd.DataFrame:
"""
if ts is a time series, returns a pandas dataframe with the following
format:
Index Values derivative1 derivative2
... ... ... ...
:param ts: list of the time series th... | 487c877907cd44159367012af3f5fd05ee3ab2bb | 64,678 |
def py_get_ask_form(*args):
"""
py_get_ask_form() -> size_t
"""
return _ida_kernwin.py_get_ask_form(*args) | b1aaa18d33168092399aa5ce77a087102d593db7 | 64,679 |
def run_simulation_TD(args):
"""
args
rx_location: Recevier location (x, y, z)
src_location: Source location (x, y, z)
topo: Topographic location (x, y, z)
hz: Thickeness of the vertical layers
time: Time (s)
field_type: 'secondary'
rx_type:
s... | 02c212d96e5c0e90bc3f5d46c420e298365de740 | 64,680 |
import time
def stat_tuple_to_seconds(t):
"""
Return a float number representing the local time associated with
the six-element tuple `t`.
"""
assert len(t) == 6, \
"need a six-element tuple (year, month, day, hour, min, sec)"
# Do _not_ apply `time.mktime` to the `EPOCH` value be... | 18ecf62fdd1f598490d2c6eccd464ee5fcb823e7 | 64,681 |
import torch
def word_seq_collate_fn(data):
""" collate function for loading word sequences in variable lengths """
# sort a list by sequence length (descending order) to use pack_padded_sequence
data.sort(key=lambda x: len(x[0]), reverse=True)
# separate source and target sequences
_, word_seq, ... | 9643e83f568ae7c22851c83ca50f472b2327dddc | 64,682 |
def tms_mpsse(bits):
"""convert a tms bit sequence to an mpsee (len, bits) tuple"""
n = len(bits)
assert (n > 0) and (n <= 7)
x = 0
# tms is shifted lsb first
for i in range(n - 1, -1, -1):
x = (x << 1) + bits[i]
# only bits 0 thru 6 are shifted on tms - tdi is set to bit 7 (and is l... | 25d2dc3b1edd5494e82295fe50889565246c2ae5 | 64,683 |
def optuna_objective(trial, list_train_dataset, list_valid_dataset, study_name):
"""Define hyperparameters choices"""
model_config_fixed = {
"objective": "binary",
"n_estimators": 1000,
"metrics": "binary_logloss",
"random_state": 0,
"verbose": -1,
}
model_confi... | e1649e6c8b28e9bb786a80b9b18b93780b87b44e | 64,684 |
def _aggregate(query, func, by=None):
"""
Wrap a query in an aggregation clause.
Use this convenience function if the aggregation parameters are coming from
user input so that they can be validated.
Args:
query (str): Query string to wrap.
func (str): Aggregation function of choice. Valid choices ar... | e26aa715fadc5a58f5f87cee297fc3e6500120e1 | 64,685 |
import string
def setup(es_domain):
"""
Sets up an ElasticSearch domain.
"""
aws_info = boto3.client('sts').get_caller_identity()
region = boto3.session.Session().region_name
# Generate the policy from policy.json, filling in the blanks.
with open(getpath('policy.json'), 'r') as ES_ACCESS... | 97287b2f418aa948c12eb35d966d91dfe1b2349e | 64,686 |
from typing import Any
def accept(message: Any) -> bool:
"""
Prompts the user to enter "yes" or "no". Returns True if the
response was "yes", otherwise False. Ctrl-c counts as "no".
"""
message = f"[pretf] {message} [yes/no]: "
response = ""
while response not in ("yes", "no"):
t... | 884bf321462ef37f02a69925ece012e108fad861 | 64,687 |
def _inner_prune_update_upward(prune_df, prune_idx):
"""
progate upwards (through parents) updates of |T_t| and R(T_t) values
as well as g1 values assoicated with these updates
Arguments:
----------
prune_df : pd.DataFrame
data frame with information about each node (before any pruning ... | 7ec0ac355936673aeb457972da6d65f52bf3363d | 64,688 |
async def get_histograms_prs(
client,
headers,
account_id,
date_from,
date_to,
exclude_inactive,
repos,
contributors,
labels,
timezone,
):
"""Get the historam metrics for the PRs filetered with the provided params."""
url = "https://api.athenian.co/v1/histograms/pull_requ... | d8d5e829a5dace262ce3a5f161de3252966ca8d8 | 64,689 |
def add_border(im, border_width, value):
"""Add color border around an image. The resulting image size is not changed.
Args:
im: numpy array with shape [3, im_h, im_w]
border_width: scalar, measured in pixel
value: scalar, or numpy array with shape [3]; the color of the border
Return... | 5ecb4f6fe8fb7f7011908d55df8182c83ebf06f8 | 64,690 |
def GetEventTid():
"""
Get type ID for debug event
@return: type ID
"""
ev = idaapi.get_debug_event()
assert ev, "Could not retrieve debug event"
return ev.tid | 321ac8023148fee90ae1d3a30b373c7237a913d0 | 64,691 |
def data_preprocess_counterfactuals(
encoder_model, dataset, patient_id, timestep, treatment_options, fold, split, static_mode, time_mode
):
"""Preprocess the dataset for obtaining counterfactual predictions for sequences of future treatments.
Args:
- encoder_model: trained encoder model for initia... | ebbe2acfdf0f86e076e36a1e74422c92a8a732d8 | 64,692 |
def SumOfWeights(id_to_mask=None, has_weights=False):
"""Returns a layer to compute sum of weights of all non-masked elements."""
multiply_by_weights = cb.Multiply() if has_weights else []
return cb.Serial(
cb.Drop(), # Drop inputs.
_ElementMask(id_to_mask=id_to_mask),
multiply_by_weights,
... | e8abae05e28609202c6f1006bba1ddbb962189d1 | 64,693 |
import torch
from typing import Union
def pairwise_corrcoef(
x: torch.Tensor,
y: torch.Tensor = None,
return_diagonal: bool = True,
device: Union[torch.device, str] = None,
batch_size: int = None, # TODO implement batching
) -> torch.Tensor:
"""Compute the pairwise correlation between columns... | e603e292bb980fe0a0fc7c854d8dcfa70fd62bd2 | 64,694 |
def calc_fee(asset: Asset, operation: str, amount: Decimal) -> Decimal:
"""Calculates fees for an operation with a given asset and amount."""
if operation == settings.OPERATION_WITHDRAWAL:
fee_percent = asset.withdrawal_fee_percent
fee_fixed = asset.withdrawal_fee_fixed
else:
fee_per... | 890c90ae0c071576c094f371fb11737fe33f4a8c | 64,695 |
def manual_stepping(global_step, boundaries, rates, warmup=False):
"""Manually stepped learning rate schedule.
This function provides fine grained control over learning rates. One must
specify a sequence of learning rates as well as a set of integer steps
at which the current learning rate must transi... | aa748b2b081052a011e07ec48102e464461dcf6e | 64,696 |
def PGetIOList (inTab):
""" Return the InfoList from a Table's IO member
returns InfoList from IO member (disk resident version)
if the IO member is not defined a None is returned.
For most reliable results, this routine should be called when
the table is opened with Write allowed.
inTab ... | 4c778b638dc2b520cbe5fdba055e7f2c312faa35 | 64,697 |
def format_seconds(total_seconds: int) -> str:
"""Format a count of seconds to get a [H:]M:SS string."""
prefix = '-' if total_seconds < 0 else ''
hours, rem = divmod(abs(round(total_seconds)), 3600)
minutes, seconds = divmod(rem, 60)
chunks = []
if hours:
chunks.append(str(hours))
... | c0f79b7f45c32589537b5dbf51a95b4811c50417 | 64,698 |
from math import factorial
def combinations(n, k):
"""
nCk
>>> combinations(52, 2)
1326
"""
return permutations(n, k) // factorial(k) | 8ead280e3a542cdf09ea2e2d863b99ed4c1c0201 | 64,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.