content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def create_task_dialog(request):
"""called when creating tasks
"""
return data_dialog(request, mode='create', entity_type='Task') | 6712048914a8417792b0dc8a1ab60c081886d4fa | 19,279 |
def raw_rearrange(da, pattern, **kwargs):
"""Crudely wrap `einops.rearrange <https://einops.rocks/api/rearrange/>`_.
Wrapper around einops.rearrange with a very similar syntax.
Spaces, parenthesis ``()`` and `->` are not allowed in dimension names.
Parameters
----------
da : xarray.DataArray
... | a16c8e439882acba930fa143e9d2428d38d1ca70 | 19,280 |
from typing import Tuple
def get_users() -> Tuple[int, ...]:
"""Count user ids in db."""
db = get_database_connection()
user_searches = db.keys(pattern=f'{DB_SEARCH_PREFIX}*')
user_ids = [
int(user_search.decode('utf-8').lstrip(DB_SEARCH_PREFIX))
for user_search in user_searches
]
... | 2eaded42444fe4ad5395387ddd45022a9e8736ce | 19,281 |
from typing import Optional
async def login(
email: str,
password: str,
session: Optional[ClientSession] = None,
*,
conf_update_interval: Optional[timedelta] = None,
device_set_debounce: Optional[timedelta] = None,
):
"""Login using email and password."""
if session:
response =... | 274f0785eb0e2fb3b73cfc4c2810df03df52d7b1 | 19,282 |
def rcomp_prediction(system, rcomp, predargs, init_cond):
""" Make a prediction with the given system
Parameters:
system (str): Name of the system to predict
rcomp (ResComp): Trained reservoir computer
predargs (variable length arguments): Passed directly into rcomp.predict
init_... | fb4eb3e710335788333a12abcd494015f4784a78 | 19,283 |
def get_best_model(X ,y):
"""Select best model from RandomForestClassifier and AdaBoostClassifier"""
ensembles = [
(RandomForestClassifier, SelectParam({
'estimator': RandomForestClassifier(warm_start=True, random_state=7),
'param_grid': {
'n_estimators': [10, 15,... | c1ac787d89a0086c263490b12081e0bfe98c6c57 | 19,284 |
def compareDates(dateA: list, dateB: list) -> int:
"""
Compares dateA and dateB\n
returns: 1 if dateA > dateB,\n
-1 if dateA <dateB,
0 if dateA == dateB \n
raise Exception if dates are invalid
"""
if not checkDateValidity(dateA, dateB):
raise invalidDateException('Invalid Dates')... | 927af2e0164706e8013badd90638b2561ab74241 | 19,285 |
def renderPage(res, topLevelContext=context.WebContext,
reqFactory=FakeRequest):
"""
Render the given resource. Return a Deferred which fires when it has
rendered.
"""
req = reqFactory()
ctx = topLevelContext(tag=res)
ctx.remember(req, inevow.IRequest)
render = appserver... | 136a06274c9cbb34951a7d2b8544328b4a1f4b60 | 19,286 |
def get_header_value(headers, name, default=None):
""" Return header value, doing case-insensitive match """
if not headers:
return default
if isinstance(headers, dict):
headers = headers.items()
name = to_bytes(name.lower())
for k, v in headers:
if name == to_bytes(k.lower... | 9ddb9754061554bd59b429b78e472bd514e4c14d | 19,287 |
def parse_gt_from_anno(img_anno, classes):
"""parse_gt_from_anno"""
print('parse ground truth files...')
ground_truth = {}
for img_name, annos in img_anno.items():
objs = []
for anno in annos:
if anno[1] == 0. and anno[2] == 0. and anno[3] == 0. and anno[4] == 0.:
... | 63ba02bb0511cdc02245528041257639e764605f | 19,288 |
def pt_to_tup(pt):
"""
Convenience method to generate a pair of two ints from a tuple or list.
Parameters
----------
pt : list OR tuple
Can be a list or a tuple of >=2 elements as floats or ints.
Returns
-------
pt : tuple of int
A pair of two ints.
"""
return (... | 7013b2477959f528b98d364e4cc44ac8700fb366 | 19,289 |
def _operation(m1, m2, op, k):
"""Generalized function for basic"""
"""matrix operations"""
n = len(m1)
res = [n*[0] for i in range(n)]
if n == len(m2):
for i in range(n):
for j in range(n):
tab = {
"+" : m1[i][j]+m2[i][j],
"-" : ... | 5e00ad1a9fbadb9712631450b106b81e5a3413ed | 19,290 |
def jacobi_d1(x, n, alpha, beta):
"""Evaluate the first derivative of Jacobi polynomial at x using eq. A.1.8
Args:
x: the location where the value will be evaluated
n: the order of Jacobi polynomial
alpha: the alpha parameter of Jacobi polynomial
beta: the beta parameter of Jaco... | 4a982827916466fad0ed812d2ec3792ca1605f0a | 19,291 |
def gate_expand_1toN(U, N, target):
"""
Create a Qobj representing a one-qubit gate that act on a system with N
qubits.
Parameters
----------
U : Qobj
The one-qubit gate
N : integer
The number of qubits in the target space.
target : integer
The index of the tar... | efb3d4da51e2f6dc90ba7bcf5e085cb651a4fed0 | 19,292 |
from typing import Dict
from typing import Any
from typing import List
def build_component_dependency_graph(
pipeline_definition: Dict[str, Any], component_definitions: Dict[str, Any]
) -> DiGraph:
"""
Builds a dependency graph between components. Dependencies are:
- referenced components during compo... | c70655e4d2b2405d991af43d4a1ad67eb1d8c9d3 | 19,293 |
def count_distribution_artefacts(distribution_artefacts):
"""
Count distribution artefacts in nested list.
:param distribution_artefacts: Nested list containing distribution artefacts mapped to media packages and tenants
:type distribution_artefacts: dict
:return: Amount of distribution artefacts
... | b9bc159523e8cbb4745d8b7e8897360f6f9c1960 | 19,294 |
def nelson_siegel_yield(tau, theta):
"""For details, see here.
Parameters
----------
tau : array, shape (n_,)
theta : array, shape (4,)
Returns
-------
y : array, shape (n_,)
"""
y = theta[0] - theta[1] * \
((1 - np.exp(-theta[3] * tau)) /
(theta[... | ba328c7698f088c3e371462b6a92c62517054af5 | 19,295 |
def fix_filename(filename):
"""Replace illegal or problematic characters from a filename."""
return filename.translate(_filename_trans) | dc8c8e1f85a7372db97273ae595ff69520824574 | 19,297 |
def QDenseModel(weights_f, load_weights=False):
"""Construct QDenseModel."""
x = x_in = Input((RESHAPED,), name="input")
x = QActivation("quantized_relu(4)", name="act_i")(x)
x = QDense(N_HIDDEN, kernel_quantizer=ternary(),
bias_quantizer=quantized_bits(4, 0, 1), name="dense0")(x)
x = QActivatio... | c84f591866708ea086e8c22ff333d60381e1f865 | 19,298 |
def fmt_uncertainty(x, dx, sn=None, sn_cutoff=8, unit=None):
"""Format uncertainty for latex."""
n_decimals = -int(np.floor(np.log10(np.abs(dx))))
leading_magnitude = np.abs(dx)/10**-n_decimals
if leading_magnitude <= 1.5:
n_decimals += 1
if sn is None:
if np.abs(x) >= 10**sn_cutoff ... | bcfbd5f22adc6a6afac1a659afe62b893ad34f1b | 19,300 |
def seed_test_input(clusters, limit):
"""
Select the seed inputs for fairness testing
:param clusters: the results of K-means clustering
:param limit: the size of seed inputs wanted
:return: a sequence of seed inputs
"""
i = 0
rows = []
max_size = max([len(c[0]) for c in clusters])
... | 03462327a6554c966d58d1e1982b40bd396e88c9 | 19,301 |
import numpy
def calc_senescence_water_shading(
aglivc, bgwfunc, fsdeth_1, fsdeth_3, fsdeth_4):
"""Calculate shoot death due to water stress and shading.
In months where senescence is not scheduled to occur, some shoot death
may still occur due to water stress and shading.
Parameters:
... | d45fbeaa24138b46fd88caa815f5e15c4098a7e5 | 19,302 |
def hello(friend_name: float = None) -> str:
"""Function to greet the user, takes a string and return Hello, 'string'"""
if not isinstance(friend_name, str):
raise TypeError("this function expects a string as input")
return f'Hello, {friend_name}!' | 9e5ab340fdeb1bed2cd48758bab8a0815ae6f75c | 19,303 |
def flatten(lst):
"""Shallow flatten *lst*"""
return [a for b in lst for a in b] | 203e971e43aea4d94bfa0ffa7057b416ef0bf545 | 19,304 |
def _transform_org_units(metadata: dict) -> pd.DataFrame:
"""Transform org units metadata into a formatted DataFrame."""
df = pd.DataFrame.from_dict(metadata.get("organisationUnits"))
df = df[["id", "code", "shortName", "name", "path", "geometry"]]
df.columns = ["ou_uid", "ou_code", "ou_shortname", "ou_... | a90532e5d5b09aeb2a85addad518c54301710141 | 19,305 |
def post_process(done_exec, temp_file):
"""For renaissance, `temp_file` is a path to a CSV file into which the
results were written. For other suites, it is `None`."""
if done_exec.suite == "renaissance":
assert temp_file is not None
return post_process_renaissance(done_exec, temp_file)
... | 615098d2ddc3806984fbc448bca377933c87973f | 19,306 |
def freeze(regex_frozen_weights):
"""Creates an optimizer that set learning rate to 0. for some weights.
Args:
regex_frozen_weights: The regex that matches the (flatten) parameters
that should not be optimized.
Returns:
A chainable optimizer.
"""
return scale_selected_parameters(regex_frozen_w... | bc4c511a1b6a03b1dd08c63d12fb5af55e177b62 | 19,307 |
def sep_num(number, space=True):
"""
Creates a string representation of a number with separators each thousand. If space is True, then it uses spaces for
the separator otherwise it will use commas
Note
----
Source: https://stackoverflow.com/questions/16670125/python-format-string-thousand-separ... | ee7dfbb60fb01bb7b6bb84cbe56ec50dfab4b339 | 19,309 |
def raw_smooth_l1_loss(diff, delta=1.0, max_val=10.0):
"""
Creates smooth L1 loss. The regular version is sometimes unstable so here what we do is if the difference
is > some value, we will return the log instead.
So it's then
0.5 * x^2 if |x| ... | 0f82ebdb72d27c1dc5e961d6905d1488d56e46b2 | 19,310 |
def read_parameters(request, view_kwargs):
"""
:param request: HttpRequest with attached api_info
:type request: HttpRequest
:type view_kwargs: dict[str, object]
:rtype: dict[str, object]
"""
params = {}
errors = {}
for param in request.api_info.operation.parameters:
try:
... | fb21c7a01fa4902e9e5adcb676731ee324438226 | 19,312 |
import getpass
def get_passwd():
"""Prompt user for a password
Prompts user to enter and confirm a password. Raises an exception
if the password is deemed to be invalid (e.g. too short), or if
the password confirmation fails.
Returns:
Password string entered by the user.
"""
passw... | 214f6078e07259eea55aa9bd6269cfc7742f7edc | 19,314 |
def _render_footnote_block_open(self, tokens, idx, options, env):
"""Render the footnote opening without the hr tag at the start."""
html = mdit_py_plugins.footnote.index.render_footnote_block_open(
self, tokens, idx, options, env
)
lines = html.split("\n")
if lines[0].strip().startswith("<h... | 56c3e6bfaada2bf5c4ea1fa48ebe4e5cd53dbea0 | 19,315 |
def remove_shot_from_scene(scene, shot, client=default):
"""
Remove link between a shot and a scene.
"""
scene = normalize_model_parameter(scene)
shot = normalize_model_parameter(shot)
return raw.delete(
"data/scenes/%s/shots/%s" % (scene["id"], shot["id"]),
client=client
) | ca6db744a60be7ee287aa95ba647f53b6afff42e | 19,316 |
def all_results_failed(subsystems):
"""Check if all results have failed status"""
for subsystem in subsystems.values():
if subsystem['subsystemStatus'] == 'OK':
# Found non-failed subsystem
return False
# All results failed
return True | 6612397c5b1605ad3e623e3c47264869c93cd47d | 19,317 |
from src.praxxis.sqlite import connection
def get_scene_id(current_scene_db):
"""gets the scene ID from the scene db"""
conn = connection.create_connection(current_scene_db)
cur = conn.cursor()
get_scene_id = 'SELECT ID FROM "SceneMetadata"'
cur.execute(get_scene_id)
id = str(cur.fetchone()[0... | 95c7a6ab2ef9484205fab57540ac71da22734428 | 19,318 |
def compile_playable_podcast1(playable_podcast1):
"""
@para: list containing dict of key/values pairs for playable podcasts
"""
items = []
for podcast in playable_podcast1:
items.append({
'label': podcast['title'],
'thumbnail': podcast['thumbnail'],
'path... | faf5e03aa4472a20564df9b0872ce58ffa8bce79 | 19,319 |
import math
def mouseclick(pos):
"""
Define "mouse click" event handler; implements game
"state" logic. It receives a parameter; pair of screen
coordinates, i.e. a tuple of two non-negative integers
- the position of the mouse click.
"""
# User clicks on a "card" of the "deck" (gri... | d283e9f9dd8581cf3d1daf997ff72af01e8d32cc | 19,320 |
def fixture_version_obj(bundle_data: dict, store: Store) -> models.Version:
"""Return a version object"""
return store.add_bundle(bundle_data)[1] | 4088df55621dc5cf43aefca07e8f34b8bfdf5e42 | 19,322 |
def ranges_compute(x, n_bins):
"""Computation of the ranges (borders of the bins).
Parameters
----------
x: pd.DataFrame
the data variable we want to obtain its distribution.
n_bins: int
the number of bins we want to use to plot the distribution.
Returns
-------
ranges:... | 28c0fcb61bc5a6417430e7b44972ba9e57a3914c | 19,323 |
def creation(basis_size: int, state_index: int) -> spr.csc_matrix:
"""
Generates the matrix of the fermionic creation operator for a given single particle state
:param basis_size: The total number of states in the single particle basis
:param state_index: The index of the state to be created by the oper... | 7967aa861a1366a4187a70dad31c32625410fd3d | 19,324 |
def LowercaseMutator(current, value):
"""Lower the value."""
return current.lower() | 7fed0dc4533948c54b64f649e2c85dca27ee9bc5 | 19,325 |
import collections
def write_predictions(all_examples, all_features, all_results, n_best_size,
max_answer_length, do_lower_case, verbose_logging, logger):
"""Write final predictions to the json file."""
example_index_to_features = collections.defaultdict(list)
for feature in all_fea... | a8ecc1eda5b7fc8b780f2d207e3d09d2b20f11ca | 19,327 |
def setup_view(view, request, *args, **kwargs):
"""Mimic ``as_view()``, but returns view instance.
Use this function to get view instances on which you can run unit tests,
by testing specific methods.
See https://stackoverflow.com/a/33647251 and
http://django-downloadview.readthedocs.io/en/latest/t... | 156710acfdb383c23d844fe8de4f78a1190193d9 | 19,328 |
from textwrap import dedent
def get_density(molecule_name, temperature=273.15, pressure=101325,
cycles=5000, init_cycles="auto",
forcefield="CrystalGenerator"):
"""Calculates the density of a gas through an NPT ensemble.
Args:
molecule_name: The molecule to test for ad... | c36e236c98d3f99a19979701c287e740543c909f | 19,329 |
def is_node_up(config, host):
"""
Calls nodetool statusbinary, nodetool statusthrift or both. This function checks the output returned from nodetool
and not the return code. There could be a normal return code of zero when the node is an unhealthy state and not
accepting requests.
:param health_che... | 4a80198ea8fede538f78f700f7d451dd65e8f435 | 19,330 |
def audits(program):
"""Create 2 audits mapped to the program"""
return [rest_facade.create_audit(program) for _ in xrange(2)] | 2fc7392c53cc0726dcba38b8eb44475fa5cb9ad8 | 19,331 |
def _create_run(uri, experiment_id, work_dir, entry_point):
"""
Create a ``Run`` against the current MLflow tracking server, logging metadata (e.g. the URI,
entry point, and parameters of the project) about the run. Return an ``ActiveRun`` that can be
used to report additional data about the run (metric... | 1ae9d084927423d88e0a737098b2567f940fbe11 | 19,332 |
def convertBoard(board):
"""
converts board into numerical representation
"""
flatBoard = np.zeros(64)
for i in range(64):
val = board.piece_at(i)
if val is None:
flatBoard[i] = 0
else:
flatBoard[i] = {"P": 1, "N" : 2, "B" : 3, "R" : 4, "Q" : 5... | 2ad05a0b1561b38332cb3b92686f903c8bd0f260 | 19,333 |
from typing import Dict
from typing import Any
from typing import MutableMapping
import logging
def merge_optional(default_dict: Dict[str, Any], update_dict: Dict[str, Any], tpe: str):
"""
Function to merge dictionaries to add set parameters from update dictionary into default dictionary.
@param default_d... | 32e52e58604b01061b6c5a3122287c0e5d8a9a84 | 19,334 |
def reference_pixel_map(dimensions, instrument_name):
"""Create a map that flags all reference pixels as such
Parameters
----------
dimensions : tup
(y, x) dimensions, in pixels, of the map to create
instrument_name : str
Name of JWST instrument associated with the data
Return... | 6800971d43ba481f3a62fce31eac21d93a36d42b | 19,335 |
import json
def geocode(value, spatial_keyword_type='hostname'):
"""convenience function to geocode a value"""
lat, lon = 0.0, 0.0
if spatial_keyword_type == 'hostname':
try:
hostname = urlparse(value).hostname
url = 'http://ip-api.com/json/%s' % hostname
LOGGER... | a2f94854a0881e5cb9041d0b134b0c4f811b132d | 19,336 |
def deploy_contract(w3, document_page_url, secret_key):
"""
TDeploy the contract
:param w3: the w3 connection
:param document_page_url: the document page url
:param secret_key: the operator secret key
:return: a pari tx_receipt, abi
"""
# 1. declare contract
document_sc = w3.eth.cont... | f295d263aba4929d84897da4dfc6af08fab7e808 | 19,337 |
from datetime import datetime
def format_date(format_string=None, datetime_obj=None):
"""
Format a datetime object with Java SimpleDateFormat's-like string.
If datetime_obj is not given - use current datetime.
If format_string is not given - return number of millisecond since epoch.
:param forma... | ea72af8ad5d3ba1999d9c05cd87203d59651bcc3 | 19,338 |
import pathlib
def testdata(request):
"""
If expected data is required for a test this fixture returns the path
to a folder with name '.testdata' located in the same director as the
calling test module
"""
testdata_dir = '.testdata'
module_dir = pathlib.Path(request.fspath).parent
retu... | 5d9a440b178aca00635f567420aaa9c406a1d7d2 | 19,339 |
def set_price(location, algo, order, price):
"""
https://api.nicehash.com/api?method=orders.set.price&id=8&key=3583b1df-5e93-4ba0-96d7-7d621fe15a17&location=0&algo=0&order=1881&price=2.1
:param location:
:param algo:
:param order:
:param price:
:return:
"""
resp = query('orders.set.p... | d8b90329c57e26a2a26f4aa134c66b9e1fd8b2c9 | 19,340 |
def jaccard_coef_loss(y_true, y_pred):
"""
Loss based on the jaccard coefficient, regularised with
binary crossentropy
Notes
-----
Found in https://github.com/ternaus/kaggle_dstl_submission
"""
return (-K.log(jaccard_coef(y_true, y_pred)) +
K.binary_crossentropy(y_pred, y_t... | 4c3d1def3ce650e9f7cd87e1a5d645d3a022f7a6 | 19,341 |
def safe_str(obj):
""" return the byte string representation of obj """
try:
return str(obj)
except UnicodeEncodeError:
# obj is unicode
return unicode(obj).encode('unicode_escape') | 74d3c75b03f38b0b151ff135a6a2ab3738822629 | 19,344 |
def default_user_agent():
"""Return a string representing the default user agent."""
return f'airslate/{__version__} ({__url__})' | 3de3e0adcf766a00b89479d8e8b00369a3f884a8 | 19,345 |
def join_complementary_byteblocks(block) -> int:
"""
join_complementary_byteblocks used to combine low bit data and high bit data
as the representation of complementary code
Parameters
----------
block : list
Low Digit Block -> int
High Digit Block -> int
Returns
------... | 0e86b132663f0d0517db9188a91443d698b74889 | 19,346 |
import numpy
def seed(func):
""" Decorator to seed the RNG before any function. """
@wraps(func)
def wrapper(*args, **kwargs):
numpy.random.seed(0)
return func(*args, **kwargs)
return wrapper | 3f1f563213d2e9175928e2f7fb5ddc90367ea0a6 | 19,347 |
def trim_bandstructure(
energy_cutoff: float, band_structure: BandStructure
) -> BandStructure:
"""
Trim the number of bands in a band structure object based on a cutoff.
Args:
energy_cutoff: An energy cutoff within which to keep the bands. If the system
is metallic then the bands t... | 3f3a0ead00657d4ceb32a5303823c7d9c538222f | 19,348 |
def _run_command(c: InvokeContext, cmd: str) -> CommandResult:
"""
Command runner.
:argument c: InvokeContext
:argument cmd: str the command to run
"""
try:
result = c.run(cmd)
return CommandResult(
exit_code=result.exited,
message=result.stdout,
... | 9b6e90f894099c1534b63e6171863a5430be3146 | 19,350 |
def get_proto_messages(protocol: str) -> list:
""" Get messages of a protocol. """
db = MetaDB()
rows = db.get_all_meta()
db.close_conn()
messages = set(row[1] for row in rows if row[0] == protocol)
return messages | 586b7f32b7ef1e713cacd31bdbb36d8f514e882d | 19,351 |
def TokenAMarkdownReference(href, reference, title=None):
"""
[link text][1]
[1]: <https://example.com> "Title"
<a href="https://example.com" title="Title">link text</a>
"""
title = ' "%s"' % title if title else ""
data = "[%s]: %s%s" % (reference, href, title)
token = {
"type"... | 48077864db045b841efa517a0136cf56a5d9ec8b | 19,352 |
import math
def inverse_document_frequency(word_occurrence, num_texts):
"""Takes in a word (string) and texts (list of lists and calculates the
number of texts over number of texts where the word occurs"""
try:
IDF = float(num_texts) / float(word_occurrence)
return math.log(IDF)
except... | a64e84b3c7d378e61765a84d3f4405e77b2ffd40 | 19,353 |
def bip32_mprv_from_seed(seed: octets, version: octets) -> bytes:
"""derive the master extended private key from the seed"""
if isinstance(version, str): # hex string
version = bytes.fromhex(version)
assert version in PRIVATE, "wrong version, master key must be private"
# serialization data
... | 2837bb9accc050e2defa3f38781d17d6f4917193 | 19,354 |
def create_menu_node(context: WxRenderingContext) -> WxNode:
"""Creates node from xml node using namespace as module and tag name as class name"""
inst_type = get_type(context.xml_node)
args = get_attr_args(context.xml_node, 'init', context.node_globals)
inst = inst_type(**args)
return WxNode(inst, ... | 3b3a215b917c980eb273f19f9f6dc9587df6874f | 19,355 |
def attach_calibration_pattern(ax, **calibration_pattern_kwargs):
"""Attach a calibration pattern to axes.
This function uses calibration_pattern to generate a figure.
Args:
calibration_pattern_kwargs: kwargs, optional
Parameters to be given to the calibration_pattern function.
Retur... | 935c3f9d3651162963c10580fdcfe94e11627a0f | 19,356 |
import base64
def alignplot(align_data, en_tokens = None, es_tokens = None, annot = False):
"""
plot the align data with tokens in both language
:params: annot: whether give annot on each element in the matrix
:params: align_data: attention matrix, array-like
:params: en_tokens: english tokens (li... | 52cf41491e70c8340a40fb16a6fdd4ffbcd68345 | 19,357 |
from datetime import datetime
def to_datetime(timestamp: str) -> datetime.datetime:
"""Converts a timestamp string in ISO format into a datatime object.
Parameters
----------
timstamp : string
Timestamp in ISO format
Returns
-------
datetime.datetime
Datetime object
"... | 16a2a1ac36e2d1988ddf41ec05fbc59a9a596dff | 19,359 |
from typing import Any
from typing import Union
from typing import Callable
async def handle_arg(
ctx: SlashContext,
key: str,
value: Any,
type_: Union[Callable, commands.Converter]
) -> Any:
"""
Handle an argument and deal with typing.Optional modifiers
Parameters
----------
ctx ... | 21808304b4d194cfd13d705469babd7ec8c20c20 | 19,360 |
def get_module_source_path(modname, basename=None):
"""Return module *modname* source path
If *basename* is specified, return *modname.basename* path where
*modname* is a package containing the module *basename*
*basename* is a filename (not a module name), so it must include the
file extension: .p... | b212713a53a14deb0fcd1a1518d2665bef03091f | 19,362 |
def drop_useless_columns(data):
"""Drop the columns containing duplicate or useless columns."""
data = data.drop(
labels=[
# we stay in a given city
"agency_id",
"agency_name",
"agency_short_name",
# we stay on a given transportation network
... | 7a47625a5df7e9fa66cefe2f326af3f0b9f59b79 | 19,363 |
from typing import Any
from typing import Optional
def arg_to_timestamp(arg: Any, arg_name: str, required: bool = False) -> Optional[int]:
"""Converts an XSOAR argument to a timestamp (seconds from epoch)
This function is used to quickly validate an argument provided to XSOAR
via ``demisto.args()`` into ... | 00fa81b041746be0e3f2e6a3c0545b72ab86fe3b | 19,364 |
import math
def expfloats (floats):
"""Manipulates floats so that their tiles are logarithmic sizes
large to small"""
return [math.exp(i) for i in floats] | 3943b8f8eedd4195693e0bace2223819f3728bb2 | 19,365 |
def typeChecker(obj, *types, error=True):
"""
Check type(s) of an object.
The first type correlates to the first layer of obj and so on.
Each type can be a (tuple that holds) type, string or literal object such as `None`.
:param obj: Generic obj, iterable or not
:param types: lists or tuples if... | 8ced14861295dd29bcbe2558d18a77d616cfec91 | 19,366 |
def post_profile_identifier_chunks_token(identifier, token):
"""
Updates a public chunk.
"""
chunk = models.Chunk.get_by_token(identifier, token)
if not chunk:
raise errors.ResourceNotFound('That chunk does not exist')
stream_entity = chunk.key.parent().get()
others = filter(lambda p... | 7a285df6eb2d41fc28d73b3c5da0621037808735 | 19,367 |
import logging
def get_latest_checkpoint(checkpoint_dir: str) -> int:
"""Find the episode ID of the latest checkpoint, if any."""
glob = osp.join(checkpoint_dir, 'checkpoint_*.pkl')
def extract_episode(x):
return int(x[x.rfind('checkpoint_') + 11:-4])
try:
checkpoint_files = tf.io.gfile.glob(glob)
... | 13677352d0d942bbc5348003ee449e27ea9f0371 | 19,368 |
def lazy(f):
"""A decorator to simply yield the result of a function"""
@wraps(f)
def lazyfunc(*args):
yield f(*args)
return lazyfunc | 5b44d01e0b982a8c36e8ce6aab2f9590e96509e6 | 19,369 |
def build_source_test_raw_sql(test_namespace, source, table, test_type,
test_args):
"""Build the raw SQL from a source test definition.
:param test_namespace: The test's namespace, if one exists
:param source: The source under test.
:param table: The table under test
:... | 2603081c3e36b9cdb3ca4e0c2381cbb5f34b3df4 | 19,370 |
from typing import List
from typing import Tuple
from typing import Optional
def get_random_word(used_words: List[int]) -> Tuple[Optional[str], List[int]]:
"""Select a random word from a list and pass on a list of used words.
Args:
used_words (list): A list of the indexes of every already used word.
... | bac4ebbf81cafef6fb615b8b4de7e74b848e794a | 19,371 |
def _generate_image_and_label_batch(image, label, min_queue_examples,
batch_size, height, shuffle, channels_last=True):
"""Construct a queued batch of images and labels.
Args:
image: 3-D Tensor of [height, width, 3] of type.float32.
label: 1-D Tensor of type.int32
... | 262d9ab1cace40ceb08b5bd1d8a4dd33f7fc151d | 19,372 |
def riskscoreci(x1, n1, x2, n2, alpha=0.05, correction=True):
"""Compute CI for the ratio of two binomial rates.
Implements the non-iterative method of Nam (1995).
It has better properties than Wald/Katz intervals,
especially with small samples and rare events.
Translated from R-package 'PropCI... | f1a976b744d7fca5f3e2005da952808db0d618ad | 19,373 |
def blend(a, b, alpha=0.5):
"""
Alpha blend two images.
Parameters
----------
a, b : numpy.ndarray
Images to blend.
alpha : float
Blending factor.
Returns
-------
result : numpy.ndarray
Blended image.
"""
a = skimage.img_as_float(a)
b = skimage.... | 2a3a6f68f48b7f6e3f5a51352082b40e63577955 | 19,374 |
def GetWsdlMethod(ns, wsdlName):
""" Get wsdl method from ns, wsdlName """
with _lazyLock:
method = _wsdlMethodMap[(ns, wsdlName)]
if isinstance(method, ManagedMethod):
# The type corresponding to the method is loaded,
# just return the method object
return method
elif... | 00892aa048f53d35b39184d1e72ff08e6e36b51a | 19,375 |
def plot_feature_wise(indicators, plot=False, show=True, ax=None, nf_max=40):
"""Plot the statistics feature-wise."""
n_mv_fw = indicators['feature-wise']
n_rows = indicators['global'].at[0, 'n_rows']
if show:
with pd.option_context('display.max_rows', None):
print(
... | 603839a5d3c78ae09d4212500e12fea92620169d | 19,376 |
import re
def normalize(string: str) -> str:
"""
Normalize a text string.
:param string: input string
:return: normalized string
"""
string = string.replace("\xef\xbb\xbf", "") # remove UTF-8 BOM
string = string.replace("\ufeff", "") # remov... | 2adaeffb60af598dad40bd6f5cd7e61e6b238123 | 19,377 |
def get_images(image_dir: str, image_url: str = DEFAULT_IMAGE_URL):
"""Gets image.
Args:
image (str): Image filename
image_url (str): Image url
Returns:
str: Output image filename
"""
images = list_images(image_dir)
if not images and image_url is not None:
print... | 3229d08606dabef04d43251f85c3b24c02ea9d93 | 19,378 |
import string
def generate_key(length=128):
"""Generate a suitable client secret"""
rand = SystemRandom()
return "".join(
rand.choice(string.ascii_letters + string.digits + string.punctuation)
for x in range(length)
) | 084d691c424f08d97aeefdd6dddff1012b009bc8 | 19,379 |
def upload_tosca_template(file): # noqa: E501
"""upload a tosca template description file
upload and validate a tosca template description file # noqa: E501
:param file: tosca Template description
:type file: werkzeug.datastructures.FileStorage
:rtype: str
"""
res = tosca_template_servic... | b1f62613acda7f0e2abf2df0d3a19792dc5cd029 | 19,381 |
def extract_data(mask, dra, ddc, dra_err, ddc_err, ra_rad, dc_rad, ra_dc_cor=None):
"""Get a clean sample based on mask
Parameters
----------
mask : array of boolean
mask for extract data
dra/ddc : array of float
R.A.(*cos(Dec.))/Dec. differences
dra_err/ddc_err : array of float... | 70286c6134fb19833f6033c827bb2ab2cd26afb1 | 19,382 |
def holes_filler(arr_segm_with_holes, holes_label=-1, labels_sequence=(), verbose=1):
"""
Given a segmentation with holes (holes are specified by a special labels called holes_label)
the holes are filled with the closest labels around.
It applies multi_lab_segmentation_dilate_1_above_selected_label unti... | d008553591f1f1634aa1cf584c6639a12e8343a6 | 19,383 |
def isAbsolute(uri : str) -> bool:
""" Check whether a URI is Absolute. """
return uri is not None and uri.startswith('//') | 8597efe69ce82e80ee81beb9eb39754e90fcec28 | 19,384 |
from typing import Iterable
def token_converter(tokens: Iterable[str]) -> Iterable[str]:
"""Convert tokens."""
def convert(token: str) -> str:
return token.lower().replace("-", "_")
return map(convert, tokens) | 93bf2436c81091ec55b6a7a4d6d3fc728a68e093 | 19,385 |
def update_instance(instance, validated_data):
"""Update all the instance's fields specified in the validated_data"""
for key, value in validated_data.items():
setattr(instance, key, value)
return instance.save() | 2f4d5c4ec9e524cbe348a5efad9ecae27739b339 | 19,386 |
import scipy
def pupilresponse_nnls(tx, sy, event_onsets, fs, npar=10.1, tmax=930):
"""
Estimate single-event pupil responses based on canonical PRF (`pupil_kernel()`)
using non-negative least-squares (NNLS).
Parameters
-----------
tx : np.ndarray
time-vector in milliseco... | afa8e02d5f5d566c9ed287c039cae16a97f3e0bf | 19,387 |
def _eval_expression(
expression,
params,
x,
ind_var="x",
aux_params=None,
domain=DEFAULT_DOMAIN,
rng=DEFAULT_RANGE,
):
"""Evaluate the expression at x.
Parameters
----------
expression : string
The expression that defines the calibration function.
params : array... | 2a636268412346b8f55dce8b951cff97d12410eb | 19,388 |
def negative_frequency(P_m):
"""get the negative probability"""
sample_num = []
sample_prob = []
for key, value in P_m.items():
sample_num.append(key)
sample_prob.append(value)
return sample_num, np.array(sample_prob)/sum(sample_prob) | ad761b49b759ef28f721162e537419a1fe3fe40d | 19,389 |
import pipes
def _ShellQuote(command_part):
"""Escape a part of a command to enable copy/pasting it into a shell.
"""
return pipes.quote(command_part) | 31ccd5bd64de657cd3ac5c36c643e9f2f09f2318 | 19,390 |
import logging
def LogLEVEL(val):
"""
Return a sane loglevel given some value.
"""
if isinstance(val, (float, int)):
return int(val)
if isinstance(val, basestring):
return getattr(logging, val.upper())
return val | 5d6f096f5d9b8ac319ab3a8b73b978cb99775a9c | 19,391 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.