uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
03eaff6b63b72569fb1d4566 | train | class | class TallListRepr(ObjectReprABC):
"""
Special representation for lists with tall entries (e.g. matrices)
.. automethod:: __call__
"""
def __call__(self, obj, p, cycle):
r"""
Format list/tuple.
INPUT:
- ``obj`` -- anything. Object to format.
- ``p`` -- Pr... | class TallListRepr(ObjectReprABC):
| """
Special representation for lists with tall entries (e.g. matrices)
.. automethod:: __call__
"""
def __call__(self, obj, p, cycle):
r"""
Format list/tuple.
INPUT:
- ``obj`` -- anything. Object to format.
- ``p`` -- PrettyPrinter instance.
- ``... | (klass, '__repr__', None)
if klass_repr in _baseclass_reprs:
p.text(klass_repr(obj))
else:
# A user-provided repr. Find newlines and replace them with p.break_()
try:
output = repr(obj)
except Exception:
import sys
... | 177 | 177 | 593 | 10 | 166 | sensen1/sage | src/sage/repl/display/fancy_repr.py | Python | TallListRepr | TallListRepr | 290 | 360 | 290 | 290 | a48c1f21ce0a59e6dbaea928b5685469b4e008c1 | bigcode/the-stack | train |
db3ffa893b28bb543d3dfb34 | train | class | class PlainPythonRepr(ObjectReprABC):
"""
The ordinary Python representation
.. automethod:: __call__
"""
def __call__(self, obj, p, cycle):
r"""
Format matrix.
INPUT:
- ``obj`` -- anything. Object to format.
- ``p`` -- PrettyPrinter instance.
- ... | class PlainPythonRepr(ObjectReprABC):
| """
The ordinary Python representation
.. automethod:: __call__
"""
def __call__(self, obj, p, cycle):
r"""
Format matrix.
INPUT:
- ``obj`` -- anything. Object to format.
- ``p`` -- PrettyPrinter instance.
- ``cycle`` -- boolean. Whether there is... | x 40 dense matrix over Integer Ring,
40 x 40 dense matrix over Integer Ring]
"""
if not p.toplevel():
# Do not print the help for matrices inside containers
return False
try:
from sage.matrix.matrix1 import Matrix
except ModuleNotFoundErr... | 153 | 153 | 511 | 10 | 142 | sensen1/sage | src/sage/repl/display/fancy_repr.py | Python | PlainPythonRepr | PlainPythonRepr | 218 | 287 | 218 | 218 | c83abf6fc256e020c3cbb755cd94b1a3e1e8c083 | bigcode/the-stack | train |
85ddd2fdc4a4f2b0f216b66e | train | class | class LargeMatrixHelpRepr(ObjectReprABC):
"""
Representation including help for large Sage matrices
.. automethod:: __call__
"""
def __call__(self, obj, p, cycle):
r"""
Format matrix.
INPUT:
- ``obj`` -- anything. Object to format.
- ``p`` -- PrettyPrinte... | class LargeMatrixHelpRepr(ObjectReprABC):
| """
Representation including help for large Sage matrices
.. automethod:: __call__
"""
def __call__(self, obj, p, cycle):
r"""
Format matrix.
INPUT:
- ``obj`` -- anything. Object to format.
- ``p`` -- PrettyPrinter instance.
- ``cycle`` -- boolea... | ``True``, the string representation is appended to ``p``.
EXAMPLES::
sage: from sage.repl.display.fancy_repr import SomeIPythonRepr
sage: pp = SomeIPythonRepr()
sage: pp.format_string(set([1, 2, 3]))
'{1, 2, 3}'
"""
try:
prett... | 122 | 122 | 408 | 11 | 110 | sensen1/sage | src/sage/repl/display/fancy_repr.py | Python | LargeMatrixHelpRepr | LargeMatrixHelpRepr | 158 | 215 | 158 | 158 | a8138c0942afa4157f6f4472c768ea1ebb730c4f | bigcode/the-stack | train |
4eb7b6b8088851033b5c4172 | train | class | class BuiltinNone(object):
pass
| class BuiltinNone(object):
| pass
| class BuiltinNone(object):
| 6 | 64 | 9 | 6 | 0 | d14na/zerocoding-org | public/plugins/Blockchain/sandboxer/vmbuiltins.py | Python | BuiltinNone | BuiltinNone | 1 | 2 | 1 | 1 | 8cc5ebdbc6cb168ff2bdbc41877a6b6cf3172005 | bigcode/the-stack | train |
4bcb075c9e632d163af5b854 | train | function | def setBuiltins(scope0):
scope0.inherits["help"] = lambda: None
scope0.inherits["copyright"] = lambda: None
scope0.inherits["credits"] = lambda: None
scope0.inherits["license"] = lambda: None
scope0.inherits["__package__"] = "0background"
scope0.inherits["__name__"] = "0back... | def setBuiltins(scope0):
| scope0.inherits["help"] = lambda: None
scope0.inherits["copyright"] = lambda: None
scope0.inherits["credits"] = lambda: None
scope0.inherits["license"] = lambda: None
scope0.inherits["__package__"] = "0background"
scope0.inherits["__name__"] = "0background"
scope0.inheri... | class BuiltinNone(object):
pass
old_super = super
def setBuiltins(scope0):
| 21 | 140 | 467 | 7 | 13 | d14na/zerocoding-org | public/plugins/Blockchain/sandboxer/vmbuiltins.py | Python | setBuiltins | setBuiltins | 6 | 65 | 6 | 6 | 997957319f16308e1f5793691139636911868649 | bigcode/the-stack | train |
548d48eac2031a1745128560 | train | class | class EnabledCommandProcessor(DefaultCommandProcessor):
def __init__(self, display_class, config):
super(EnabledCommandProcessor, self).__init__(display_class, enabled=None)
self.config_processor = config
def get_prompt(self):
return self.switch_configuration.name + "#"
def do_enab... | class EnabledCommandProcessor(DefaultCommandProcessor):
| def __init__(self, display_class, config):
super(EnabledCommandProcessor, self).__init__(display_class, enabled=None)
self.config_processor = config
def get_prompt(self):
return self.switch_configuration.name + "#"
def do_enable(self, *args):
pass
def do_configure(self... | # Copyright 2018 Inap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... | 188 | 201 | 673 | 8 | 179 | FrancoisLopez/fake-switches | fake_switches/arista/command_processor/enabled.py | Python | EnabledCommandProcessor | EnabledCommandProcessor | 20 | 90 | 20 | 20 | 57af5e73573af6a8e61c3087bb5ab016f989ed77 | bigcode/the-stack | train |
7ffc51c177ae861ad885f2b1 | train | class | class FastSpeechInferencer(Inferencer):
def __init__(self, model_name, model, data_loader, ckpt_path=None, ckpt_file=None, log_path=None, device='cuda', use_fp16=False, seed=None):
super(FastSpeechInferencer, self).__init__(model_name, model, data_loader, ckpt_path, ckpt_file, log_path, device, use_fp16, s... | class FastSpeechInferencer(Inferencer):
| def __init__(self, model_name, model, data_loader, ckpt_path=None, ckpt_file=None, log_path=None, device='cuda', use_fp16=False, seed=None):
super(FastSpeechInferencer, self).__init__(model_name, model, data_loader, ckpt_path, ckpt_file, log_path, device, use_fp16, seed)
def infer(self, acts=None, seq_... | DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF... | 177 | 177 | 592 | 9 | 167 | puririshi98/benchmark | DeepLearningExamples/CUDA-Optimized/FastSpeech/fastspeech/inferencer/fastspeech_inferencer.py | Python | FastSpeechInferencer | FastSpeechInferencer | 32 | 90 | 32 | 33 | b6585dc297f3370d603ed9900bd5d1ae28a1ca7f | bigcode/the-stack | train |
5f2ad34e6642d4a73b691a72 | train | function | def add_argument_for_json_arxiv_data(parser: argparse.ArgumentParser):
parser.add_argument('--input', required=True, nargs='+')
parser.add_argument('--output', required=True)
| def add_argument_for_json_arxiv_data(parser: argparse.ArgumentParser):
| parser.add_argument('--input', required=True, nargs='+')
parser.add_argument('--output', required=True)
| parsers.add_parser("json_arxiv", help="arXivのデータを今回用に加工"))
add_argument_for_merge_json(
subparsers.add_parser("merge_json", help="jsonファイルの統合"))
def add_argument_for_json_arxiv_data(parser: argparse.ArgumentParser):
| 63 | 64 | 37 | 14 | 49 | n-kats/arxiv2vec | cli/dataset.py | Python | add_argument_for_json_arxiv_data | add_argument_for_json_arxiv_data | 12 | 14 | 12 | 12 | e4dcecff3de47db5a2d074db9885b8e6c7d6b549 | bigcode/the-stack | train |
6930cb1f4dbd273f26a1d4c1 | train | function | def add_argument_for_dataset(parser: argparse.ArgumentParser):
subparsers = parser.add_subparsers(dest="dataset_mode")
add_argument_for_json_arxiv_data(
subparsers.add_parser("json_arxiv", help="arXivのデータを今回用に加工"))
add_argument_for_merge_json(
subparsers.add_parser("merge_json", help="jsonファイルの統合"))
| def add_argument_for_dataset(parser: argparse.ArgumentParser):
| subparsers = parser.add_subparsers(dest="dataset_mode")
add_argument_for_json_arxiv_data(
subparsers.add_parser("json_arxiv", help="arXivのデータを今回用に加工"))
add_argument_for_merge_json(
subparsers.add_parser("merge_json", help="jsonファイルの統合"))
| import argparse
def add_argument_for_dataset(parser: argparse.ArgumentParser):
| 14 | 64 | 86 | 11 | 2 | n-kats/arxiv2vec | cli/dataset.py | Python | add_argument_for_dataset | add_argument_for_dataset | 4 | 9 | 4 | 4 | 9215a94638fcbf7b7bfa8f531f23267a9534d38d | bigcode/the-stack | train |
09148b2be709774d0296ba68 | train | function | def add_argument_for_merge_json(parser: argparse.ArgumentParser):
parser.add_argument('--input', required=True, nargs='+')
parser.add_argument('--output', required=True)
| def add_argument_for_merge_json(parser: argparse.ArgumentParser):
| parser.add_argument('--input', required=True, nargs='+')
parser.add_argument('--output', required=True)
| _parser("merge_json", help="jsonファイルの統合"))
def add_argument_for_json_arxiv_data(parser: argparse.ArgumentParser):
parser.add_argument('--input', required=True, nargs='+')
parser.add_argument('--output', required=True)
def add_argument_for_merge_json(parser: argparse.ArgumentParser):
| 64 | 64 | 35 | 12 | 52 | n-kats/arxiv2vec | cli/dataset.py | Python | add_argument_for_merge_json | add_argument_for_merge_json | 17 | 19 | 17 | 17 | 8a4d062fb415fd1f6ca142d0d89705c10aa4cc1e | bigcode/the-stack | train |
026eb8404f95f473fcde983a | train | class | class SyncRestServlet(RestServlet):
"""
GET parameters::
timeout(int): How long to wait for new events in milliseconds.
since(batch_token): Batch token when asking for incremental deltas.
set_presence(str): What state the device presence should be set to.
default is "online"... | class SyncRestServlet(RestServlet):
| """
GET parameters::
timeout(int): How long to wait for new events in milliseconds.
since(batch_token): Batch token when asking for incremental deltas.
set_presence(str): What state the device presence should be set to.
default is "online".
filter(filter_id): A filte... | under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License ... | 256 | 256 | 2,142 | 7 | 249 | mweinelt/synapse | synapse/rest/client/v2_alpha/sync.py | Python | SyncRestServlet | SyncRestServlet | 40 | 325 | 40 | 40 | 3abc44b7684c7fd64e31069ed48d1ad4f3dbf8b1 | bigcode/the-stack | train |
52a05d6c39262ffa1f649d42 | train | function | def register_servlets(hs, http_server):
SyncRestServlet(hs).register(http_server)
| def register_servlets(hs, http_server):
| SyncRestServlet(hs).register(http_server)
| "account_data": {"events": account_data},
}
if joined:
ephemeral_events = room.ephemeral
result["ephemeral"] = {"events": ephemeral_events}
result["unread_notifications"] = room.unread_notifications
return result
def register_servlets(hs, http_server):
| 64 | 64 | 21 | 10 | 53 | mweinelt/synapse | synapse/rest/client/v2_alpha/sync.py | Python | register_servlets | register_servlets | 328 | 329 | 328 | 328 | a7324bed21d021e185c13d8d69b6931177ddc098 | bigcode/the-stack | train |
14d2431af9efb60e12725d9d | train | function | def create_resource():
"""Image members resource factory method"""
deserializer = wsgi.JSONRequestDeserializer()
serializer = wsgi.JSONResponseSerializer()
return wsgi.Resource(Controller(), deserializer, serializer)
| def create_resource():
| """Image members resource factory method"""
deserializer = wsgi.JSONRequestDeserializer()
serializer = wsgi.JSONResponseSerializer()
return wsgi.Resource(Controller(), deserializer, serializer)
| ls(self, req, image_id):
image_meta = self.get_image_meta_or_404(req, image_id)
location_uri = image_meta.get('location')
public = image_meta.get('is_public')
self.update_store_acls(req, image_id, location_uri, public)
def create_resource():
| 64 | 64 | 44 | 4 | 60 | whitepages/glance | glance/api/v1/members.py | Python | create_resource | create_resource | 233 | 237 | 233 | 233 | 16f4bea4932f2e332d5b14b1d9b0db5cad556319 | bigcode/the-stack | train |
9b672bee98bd7c465b133ab1 | train | class | class Controller(controller.BaseController):
def __init__(self):
self.policy = policy.Enforcer()
def _check_can_access_image_members(self, context):
if context.owner is None and not context.is_admin:
raise webob.exc.HTTPUnauthorized(_("No authenticated user"))
def _enforce(sel... | class Controller(controller.BaseController):
| def __init__(self):
self.policy = policy.Enforcer()
def _check_can_access_image_members(self, context):
if context.owner is None and not context.is_admin:
raise webob.exc.HTTPUnauthorized(_("No authenticated user"))
def _enforce(self, req, action):
"""Authorize an actio... | Copyright 2013 NTT corp.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | 256 | 256 | 1,662 | 6 | 250 | whitepages/glance | glance/api/v1/members.py | Python | Controller | Controller | 35 | 230 | 35 | 36 | bc19e782a61e7309456889ec6101387b5d842ae1 | bigcode/the-stack | train |
d6a75c66683ccdaaa69b915c | train | function | @borg.on(admin_cmd(pattern="compress ?(.*)"))
async def _(event):
if event.fwd_from:
return
input_str = event.pattern_match.group(1)
mone = await event.edit("Processing ...")
if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
if ev... | @borg.on(admin_cmd(pattern="compress ?(.*)"))
async def _(event):
| if event.fwd_from:
return
input_str = event.pattern_match.group(1)
mone = await event.edit("Processing ...")
if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
if event.reply_to_msg_id:
reply_message = await event.get_reply_... | from telethon import events
import asyncio
import zipfile
from pySmartDL import SmartDL
import time
import os
from uniborg.util import admin_cmd, humanbytes, progress, time_formatter
@borg.on(admin_cmd(pattern="compress ?(.*)"))
async def _(event):
| 62 | 105 | 353 | 18 | 43 | lucky7292/HarshTech | userbot/plugins/zipfile.py | Python | _ | _ | 19 | 101 | 19 | 22 | ee5eca39576257c81d5642fa2cf2f3cdacd1d45e | bigcode/the-stack | train |
e9509905d21983f493add7b9 | train | class | class Buckets(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
a... | class Buckets(object):
| """NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): Th... | # coding: utf-8
"""
InfluxDB OSS API Service.
The InfluxDB v2 API provides a programmatic interface for all interactions with InfluxDB. Access the InfluxDB API using the `/api/v2/` endpoint. # noqa: E501
OpenAPI spec version: 2.0.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa:... | 98 | 219 | 730 | 5 | 92 | bonitoo-io/influxdb-client-python | influxdb_client/domain/buckets.py | Python | Buckets | Buckets | 17 | 130 | 17 | 17 | c00ce50ffb4ea789fc61c9583713cd2fbaea5bfd | bigcode/the-stack | train |
731b73761d163713f99ea5ab | train | class | class TestCompareXLSXFiles(unittest.TestCase):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'outline01.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' + ... | class TestCompareXLSXFiles(unittest.TestCase):
| """
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'outline01.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' + filename
self.exp_filename = test_dir +... | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2014, John McNamara, jmcnamara@cpan.org
#
import unittest
import os
from ...workbook import Workbook
from ..helperfunctions import _compare_xlsx_files
class TestCompareXLSXFiles(unittest.Te... | 72 | 238 | 795 | 11 | 60 | sontek/XlsxWriter | xlsxwriter/test/comparison/test_outline01.py | Python | TestCompareXLSXFiles | TestCompareXLSXFiles | 14 | 104 | 14 | 14 | 804e16285e24b561106cc4542fb483342854d328 | bigcode/the-stack | train |
d45bb59528aa2c268787b11f | train | function | @contextlib.contextmanager
def keep_dtype_scope():
"""
Specify which layers retain the original precision.
"""
attrs = {
"_keep_dtype": attr_value_pb2.AttrValue(b=True)
}
with ops.get_default_graph()._attr_scope(attrs):
yield
| @contextlib.contextmanager
def keep_dtype_scope():
| """
Specify which layers retain the original precision.
"""
attrs = {
"_keep_dtype": attr_value_pb2.AttrValue(b=True)
}
with ops.get_default_graph()._attr_scope(attrs):
yield
| be in NpuExecutePlacement's vaule")
attrs = {
"_variable_placement": attr_value_pb2.AttrValue(s=compat.as_bytes(placement.value))
}
with ops.get_default_graph()._attr_scope(attrs):
yield
@contextlib.contextmanager
def keep_dtype_scope():
| 64 | 64 | 60 | 11 | 52 | Judithsq/tensorflow | tf_adapter/python/npu_bridge/estimator/npu/npu_scope.py | Python | keep_dtype_scope | keep_dtype_scope | 36 | 45 | 36 | 37 | 830a82dbddb1fb89feea627130e77b6d9d6460ff | bigcode/the-stack | train |
be27c21ddafcbbf9d6fe2f96 | train | function | @contextlib.contextmanager
def npu_stage_scope(stage):
"""
Enable the node in the scope adding _stage_level attr.
"""
attrs = {
"_stage_level": attr_value_pb2.AttrValue(i=stage)
}
with ops.get_default_graph()._attr_scope(attrs):
yield
| @contextlib.contextmanager
def npu_stage_scope(stage):
| """
Enable the node in the scope adding _stage_level attr.
"""
attrs = {
"_stage_level": attr_value_pb2.AttrValue(i=stage)
}
with ops.get_default_graph()._attr_scope(attrs):
yield
| _scope():
"""
Specify which layers retain the original precision.
"""
attrs = {
"_keep_dtype": attr_value_pb2.AttrValue(b=True)
}
with ops.get_default_graph()._attr_scope(attrs):
yield
@contextlib.contextmanager
def npu_stage_scope(stage):
| 64 | 64 | 67 | 13 | 50 | Judithsq/tensorflow | tf_adapter/python/npu_bridge/estimator/npu/npu_scope.py | Python | npu_stage_scope | npu_stage_scope | 48 | 57 | 48 | 49 | fd8127cab1770daa9615535095a6316731449224 | bigcode/the-stack | train |
83f01266297a24b7c835aeba | train | function | @contextlib.contextmanager
def without_npu_compile_scope():
"""
Enable the non npu compilation of operators within the scope.
"""
attrs = {
"_without_npu_compile": attr_value_pb2.AttrValue(b=True)
}
with ops.get_default_graph()._attr_scope(attrs):
yield
| @contextlib.contextmanager
def without_npu_compile_scope():
| """
Enable the non npu compilation of operators within the scope.
"""
attrs = {
"_without_npu_compile": attr_value_pb2.AttrValue(b=True)
}
with ops.get_default_graph()._attr_scope(attrs):
yield
| in mix compute mode.
"""
import contextlib
from tensorflow.core.framework import attr_value_pb2
from tensorflow.python.framework import ops
from tensorflow.python.util import compat
from npu_bridge.estimator.npu.npu_config import NpuExecutePlacement
@contextlib.contextmanager
def without_npu_compile_scope():
| 64 | 64 | 68 | 13 | 50 | Judithsq/tensorflow | tf_adapter/python/npu_bridge/estimator/npu/npu_scope.py | Python | without_npu_compile_scope | without_npu_compile_scope | 10 | 19 | 10 | 11 | 4e3686c0f60c723d82484832357645e6b83bbdad | bigcode/the-stack | train |
32e5a41b46d4a49fdacad3dd | train | function | @contextlib.contextmanager
def npu_variable_scope(placement=NpuExecutePlacement.ALL):
"""
Enable the node in the scope adding _variable_placement attr.
"""
if placement not in NpuExecutePlacement:
raise ValueError("placement vaule must be in NpuExecutePlacement's vaule")
attrs = {
"_... | @contextlib.contextmanager
def npu_variable_scope(placement=NpuExecutePlacement.ALL):
| """
Enable the node in the scope adding _variable_placement attr.
"""
if placement not in NpuExecutePlacement:
raise ValueError("placement vaule must be in NpuExecutePlacement's vaule")
attrs = {
"_variable_placement": attr_value_pb2.AttrValue(s=compat.as_bytes(placement.value))
... | operators within the scope.
"""
attrs = {
"_without_npu_compile": attr_value_pb2.AttrValue(b=True)
}
with ops.get_default_graph()._attr_scope(attrs):
yield
@contextlib.contextmanager
def npu_variable_scope(placement=NpuExecutePlacement.ALL):
| 64 | 64 | 109 | 19 | 44 | Judithsq/tensorflow | tf_adapter/python/npu_bridge/estimator/npu/npu_scope.py | Python | npu_variable_scope | npu_variable_scope | 22 | 33 | 22 | 23 | 81870c3d52d6704aface7a18d8245e7c59d61765 | bigcode/the-stack | train |
926ebd550782ff957917a496 | train | function | def extract_user(message: Message, args: List[str]) -> Optional[int]:
return extract_user_and_text(message, args)[0]
| def extract_user(message: Message, args: List[str]) -> Optional[int]:
| return extract_user_and_text(message, args)[0]
| , None
user_id = prev_message.from_user.id
res = message.text.split(None, 1)
if len(res) < 2:
return user_id, ""
return user_id, res[1]
def extract_user(message: Message, args: List[str]) -> Optional[int]:
| 64 | 64 | 28 | 16 | 48 | apisuserbot/Killua-Robot | KilluaRobot/modules/helper_funcs/extraction.py | Python | extract_user | extract_user | 20 | 21 | 20 | 20 | 48f701ff0763ea374992ae1f2ee281b6d1f7b3d6 | bigcode/the-stack | train |
74e7c0189f1c5ffd464ce8fd | train | function | def extract_user_fban(message: Message, args: List[str]) -> Optional[int]:
return extract_unt_fedban(message, args)[0]
| def extract_user_fban(message: Message, args: List[str]) -> Optional[int]:
| return extract_unt_fedban(message, args)[0]
| LOGGER.exception("Exception %s on user %s", excp.message, user_id)
return None, None
if not isinstance(user_id, int):
return None, None
return user_id, text
def extract_user_fban(message: Message, args: List[str]) -> Optional[int]:
| 64 | 64 | 32 | 18 | 45 | apisuserbot/Killua-Robot | KilluaRobot/modules/helper_funcs/extraction.py | Python | extract_user_fban | extract_user_fban | 165 | 166 | 165 | 165 | 6954cf85d928ea5929c55972ff926de583b80274 | bigcode/the-stack | train |
59d37e4f982692c547a2bc08 | train | function | def extract_user_and_text(
message: Message,
args: List[str],
) -> (Optional[int], Optional[str]):
prev_message = message.reply_to_message
split_text = message.text.split(None, 1)
if len(split_text) < 2:
return id_from_reply(message) # only option possible
text_to_parse = split_text[1... | def extract_user_and_text(
message: Message,
args: List[str],
) -> (Optional[int], Optional[str]):
| prev_message = message.reply_to_message
split_text = message.text.split(None, 1)
if len(split_text) < 2:
return id_from_reply(message) # only option possible
text_to_parse = split_text[1]
text = ""
entities = list(message.parse_entities([MessageEntity.TEXT_MENTION]))
ent = entit... | .modules.users import get_user_id
from telegram import Message, MessageEntity
from telegram.error import BadRequest
def id_from_reply(message):
prev_message = message.reply_to_message
if not prev_message:
return None, None
user_id = prev_message.from_user.id
res = message.text.split(None, 1)
... | 148 | 148 | 495 | 26 | 122 | apisuserbot/Killua-Robot | KilluaRobot/modules/helper_funcs/extraction.py | Python | extract_user_and_text | extract_user_and_text | 24 | 85 | 24 | 27 | cb0c60ad867484c66f51959cff20e6b03109c09e | bigcode/the-stack | train |
e86de934a2609a19fd287d0a | train | function | def id_from_reply(message):
prev_message = message.reply_to_message
if not prev_message:
return None, None
user_id = prev_message.from_user.id
res = message.text.split(None, 1)
if len(res) < 2:
return user_id, ""
return user_id, res[1]
| def id_from_reply(message):
| prev_message = message.reply_to_message
if not prev_message:
return None, None
user_id = prev_message.from_user.id
res = message.text.split(None, 1)
if len(res) < 2:
return user_id, ""
return user_id, res[1]
| from typing import List, Optional
from KilluaRobot import LOGGER
from KilluaRobot.modules.users import get_user_id
from telegram import Message, MessageEntity
from telegram.error import BadRequest
def id_from_reply(message):
| 46 | 64 | 72 | 6 | 39 | apisuserbot/Killua-Robot | KilluaRobot/modules/helper_funcs/extraction.py | Python | id_from_reply | id_from_reply | 9 | 17 | 9 | 9 | db2b922441fbb194d7212d96603b8146a0c48873 | bigcode/the-stack | train |
a20bb98f47774a8ad1f9e810 | train | function | def extract_unt_fedban(
message: Message,
args: List[str],
) -> (Optional[int], Optional[str]):
prev_message = message.reply_to_message
split_text = message.text.split(None, 1)
if len(split_text) < 2:
return id_from_reply(message) # only option possible
text_to_parse = split_text[1]
... | def extract_unt_fedban(
message: Message,
args: List[str],
) -> (Optional[int], Optional[str]):
| prev_message = message.reply_to_message
split_text = message.text.split(None, 1)
if len(split_text) < 2:
return id_from_reply(message) # only option possible
text_to_parse = split_text[1]
text = ""
entities = list(message.parse_entities([MessageEntity.TEXT_MENTION]))
ent = entit... | not found"):
message.reply_text(
"I don't seem to have interacted with this user before - please forward a message from "
"them to give me control! (like a voodoo doll, I need a piece of them to be able "
"to execute certain commands...)",
)
... | 163 | 163 | 546 | 28 | 135 | apisuserbot/Killua-Robot | KilluaRobot/modules/helper_funcs/extraction.py | Python | extract_unt_fedban | extract_unt_fedban | 96 | 162 | 96 | 99 | b4aede6e40e388363a8b549daf5a8ea432f75fbb | bigcode/the-stack | train |
340b7343ff2e839cb56d1df0 | train | function | def extract_text(message) -> str:
return (
message.text
or message.caption
or (message.sticker.emoji if message.sticker else None)
)
| def extract_text(message) -> str:
| return (
message.text
or message.caption
or (message.sticker.emoji if message.sticker else None)
)
| , I need a piece of them to be able "
"to execute certain commands...)",
)
else:
LOGGER.exception("Exception %s on user %s", excp.message, user_id)
return None, None
return user_id, text
def extract_text(message) -> str:
| 64 | 64 | 37 | 8 | 55 | apisuserbot/Killua-Robot | KilluaRobot/modules/helper_funcs/extraction.py | Python | extract_text | extract_text | 88 | 93 | 88 | 88 | c4bfa0cda478200e4c5123221361cac839552873 | bigcode/the-stack | train |
f62438dd01cb60d0c3f0fde4 | train | function | @pytest.mark.parametrize(
"aws_region, tag_key, tag_value, result_count", [
("eu-west-1", "tostop", "true", 3),
("eu-west-2", "tostop", "true", 3),
("eu-west-2", "badtagkey", "badtagvalue", 0),
]
)
@mock_ec2
@mock_autoscaling
def test_list_ec2_instance(aws_region, tag_key, tag_value, res... | @pytest.mark.parametrize(
"aws_region, tag_key, tag_value, result_count", [
("eu-west-1", "tostop", "true", 3),
("eu-west-2", "tostop", "true", 3),
("eu-west-2", "badtagkey", "badtagvalue", 0),
]
)
@mock_ec2
@mock_autoscaling
def test_list_ec2_instance(aws_region, tag_key, tag_value, res... | """Verify list ec2 instances function."""
client = boto3.client("ec2", region_name=aws_region)
launch_ec2_instances(3, aws_region, "tostop", "true")
ec2_scheduler = InstanceScheduler(aws_region)
taglist = ec2_scheduler.list_instances(tag_key, tag_value)
assert len(list(taglist)) == result_count
| @pytest.mark.parametrize(
"aws_region, tag_key, tag_value, result_count", [
("eu-west-1", "tostop", "true", 3),
("eu-west-2", "tostop", "true", 3),
("eu-west-2", "badtagkey", "badtagvalue", 0),
]
)
@mock_ec2
@mock_autoscaling
def test_list_ec2_instance(aws_region, tag_key, tag_value, res... | 108 | 64 | 189 | 108 | 0 | moreiramarti/terraform-aws-lambda-scheduler-stop-start | tests/unit/test_instance_scheduler.py | Python | test_list_ec2_instance | test_list_ec2_instance | 15 | 30 | 15 | 24 | b9369603c0026ac05f181f0547e3e950c5c32832 | bigcode/the-stack | train |
89c24b2e8fb12c3e8e5bcbc9 | train | function | @pytest.mark.parametrize(
"aws_region, tag_key, tag_value, result_count", [
("eu-west-1", "tostop", "true", {"Code": 16, "Name": "running"}),
("eu-west-2", "tostop", "true", {"Code": 16, "Name": "running"}),
("eu-west-2", "badtagkey", "badtagvalue", {"Code": 80, "Name": "stopped"}),
]
)
... | @pytest.mark.parametrize(
"aws_region, tag_key, tag_value, result_count", [
("eu-west-1", "tostop", "true", {"Code": 16, "Name": "running"}),
("eu-west-2", "tostop", "true", {"Code": 16, "Name": "running"}),
("eu-west-2", "badtagkey", "badtagvalue", {"Code": 80, "Name": "stopped"}),
]
)
... | """Verify start ec2 instance function."""
client = boto3.client("ec2", region_name=aws_region)
launch_ec2_instances(3, aws_region, "tostop", "true")
for ec2 in client.describe_instances()["Reservations"][0]["Instances"]:
client.stop_instances(InstanceIds=[ec2["InstanceId"]])
ec2_scheduler =... | @pytest.mark.parametrize(
"aws_region, tag_key, tag_value, result_count", [
("eu-west-1", "tostop", "true", {"Code": 16, "Name": "running"}),
("eu-west-2", "tostop", "true", {"Code": 16, "Name": "running"}),
("eu-west-2", "badtagkey", "badtagvalue", {"Code": 80, "Name": "stopped"}),
]
)
... | 141 | 83 | 279 | 141 | 0 | moreiramarti/terraform-aws-lambda-scheduler-stop-start | tests/unit/test_instance_scheduler.py | Python | test_start_ec2_instance | test_start_ec2_instance | 33 | 54 | 33 | 43 | 1f018f203a359ec5d8c52f05655ebb318d98b599 | bigcode/the-stack | train |
3fb4b299e888ac330f96a831 | train | function | @pytest.mark.parametrize(
"aws_region, tag_key, tag_value, result_count", [
("eu-west-1", "tostop", "true", {"Code": 80, "Name": "stopped"}),
("eu-west-2", "tostop", "true", {"Code": 80, "Name": "stopped"}),
("eu-west-2", "badtagkey", "badtagvalue", {"Code": 16, "Name": "running"}),
]
)
... | @pytest.mark.parametrize(
"aws_region, tag_key, tag_value, result_count", [
("eu-west-1", "tostop", "true", {"Code": 80, "Name": "stopped"}),
("eu-west-2", "tostop", "true", {"Code": 80, "Name": "stopped"}),
("eu-west-2", "badtagkey", "badtagvalue", {"Code": 16, "Name": "running"}),
]
)
... | """Verify stop ec2 instance function."""
client = boto3.client("ec2", region_name=aws_region)
launch_ec2_instances(3, aws_region, tag_key, tag_value)
ec2_scheduler = InstanceScheduler(aws_region)
ec2_scheduler.cloudwatch_alarm = CloudWatchAlarmScheduler(aws_region)
ec2_scheduler.stop("tostop", ... | @pytest.mark.parametrize(
"aws_region, tag_key, tag_value, result_count", [
("eu-west-1", "tostop", "true", {"Code": 80, "Name": "stopped"}),
("eu-west-2", "tostop", "true", {"Code": 80, "Name": "stopped"}),
("eu-west-2", "badtagkey", "badtagvalue", {"Code": 16, "Name": "running"}),
]
)
... | 142 | 78 | 263 | 142 | 0 | moreiramarti/terraform-aws-lambda-scheduler-stop-start | tests/unit/test_instance_scheduler.py | Python | test_stop_ec2_instance | test_stop_ec2_instance | 57 | 78 | 57 | 67 | 1e17178f6cea26e1569c9465776844d548ce9cf6 | bigcode/the-stack | train |
bd7e649e693a8a6c815fd287 | train | function | @pytest.mark.parametrize(
"aws_region, tag_key, tag_value, result_count", [
("eu-west-1", "tostop", "true", {"Code": 16, "Name": "running"}),
("eu-west-2", "tostop", "true", {"Code": 16, "Name": "running"}),
]
)
@mock_ec2
@mock_cloudwatch
@mock_autoscaling
def test_do_not_stop_asg_instance(aws_r... | @pytest.mark.parametrize(
"aws_region, tag_key, tag_value, result_count", [
("eu-west-1", "tostop", "true", {"Code": 16, "Name": "running"}),
("eu-west-2", "tostop", "true", {"Code": 16, "Name": "running"}),
]
)
@mock_ec2
@mock_cloudwatch
@mock_autoscaling
def test_do_not_stop_asg_instance(aws_r... | client = boto3.client("ec2", region_name=aws_region)
launch_asg(aws_region, tag_key, tag_value)
ec2_scheduler = InstanceScheduler(aws_region)
ec2_scheduler.cloudwatch_alarm = CloudWatchAlarmScheduler(aws_region)
ec2_scheduler.stop("tostop", "true")
instances = client.describe_instances()["Reser... | @pytest.mark.parametrize(
"aws_region, tag_key, tag_value, result_count", [
("eu-west-1", "tostop", "true", {"Code": 16, "Name": "running"}),
("eu-west-2", "tostop", "true", {"Code": 16, "Name": "running"}),
]
)
@mock_ec2
@mock_cloudwatch
@mock_autoscaling
def test_do_not_stop_asg_instance(aws_r... | 113 | 66 | 222 | 113 | 0 | moreiramarti/terraform-aws-lambda-scheduler-stop-start | tests/unit/test_instance_scheduler.py | Python | test_do_not_stop_asg_instance | test_do_not_stop_asg_instance | 81 | 100 | 81 | 90 | a23c579bf272da7eac04b611d3dc4227db7ab7ea | bigcode/the-stack | train |
8ad255d65581c96af3d63a6e | train | function | @pytest.mark.parametrize(
"aws_region, tag_key, tag_value, result_count", [
("eu-west-1", "tostop", "true", {"Code": 80, "Name": "stopped"}),
("eu-west-2", "tostop", "true", {"Code": 80, "Name": "stopped"}),
]
)
@mock_ec2
@mock_cloudwatch
@mock_autoscaling
def test_do_not_start_asg_instance(aws_... | @pytest.mark.parametrize(
"aws_region, tag_key, tag_value, result_count", [
("eu-west-1", "tostop", "true", {"Code": 80, "Name": "stopped"}),
("eu-west-2", "tostop", "true", {"Code": 80, "Name": "stopped"}),
]
)
@mock_ec2
@mock_cloudwatch
@mock_autoscaling
def test_do_not_start_asg_instance(aws_... | client = boto3.client("ec2", region_name=aws_region)
launch_asg(aws_region, tag_key, tag_value)
instances = client.describe_instances()["Reservations"][0]["Instances"]
for instance in instances:
client.stop_instances(InstanceIds=[instance["InstanceId"]])
ec2_scheduler = InstanceScheduler(aw... | @pytest.mark.parametrize(
"aws_region, tag_key, tag_value, result_count", [
("eu-west-1", "tostop", "true", {"Code": 80, "Name": "stopped"}),
("eu-west-2", "tostop", "true", {"Code": 80, "Name": "stopped"}),
]
)
@mock_ec2
@mock_cloudwatch
@mock_autoscaling
def test_do_not_start_asg_instance(aws_... | 115 | 77 | 257 | 115 | 0 | moreiramarti/terraform-aws-lambda-scheduler-stop-start | tests/unit/test_instance_scheduler.py | Python | test_do_not_start_asg_instance | test_do_not_start_asg_instance | 103 | 125 | 103 | 112 | 7efe0d928a5cd184525fbefc996278ee8a345599 | bigcode/the-stack | train |
7a21d06d8f68f4c4db6ffaf2 | train | function | def insert_to_hospital(profiles):
with open('hospital_data.csv','r') as csv_file:
csv_reader=csv.reader(csv_file)
hospitals=[]
for hospital in csv_reader:
file = open(hospital[0]+'_'+hospital[1]+'.csv',"w")
file.write("")
file.close()
file=open... | def insert_to_hospital(profiles):
| with open('hospital_data.csv','r') as csv_file:
csv_reader=csv.reader(csv_file)
hospitals=[]
for hospital in csv_reader:
file = open(hospital[0]+'_'+hospital[1]+'.csv',"w")
file.write("")
file.close()
file=open('patient_hospital_destination.csv... | sorting them based on their priority level
profiles=[]
with open('data.csv','r') as csv_file:
csv_reader=csv.reader(csv_file)
start=False
for line in csv_reader:
if start:
residency_status=0 if line[5]=='Foreigner' else 1
patient=... | 123 | 123 | 411 | 8 | 114 | lars-tps/Bambank-hackathon | dataprocessing.py | Python | insert_to_hospital | insert_to_hospital | 42 | 76 | 42 | 42 | a1640bcb3a4412529c59be79b177abeb1216d311 | bigcode/the-stack | train |
1dbdc54acce731154154c586 | train | function | def insert_profiles():
#getting the patient profiles and sorting them based on their priority level
profiles=[]
with open('data.csv','r') as csv_file:
csv_reader=csv.reader(csv_file)
start=False
for line in csv_reader:
if start:
residency_stat... | def insert_profiles():
#getting the patient profiles and sorting them based on their priority level
| profiles=[]
with open('data.csv','r') as csv_file:
csv_reader=csv.reader(csv_file)
start=False
for line in csv_reader:
if start:
residency_status=0 if line[5]=='Foreigner' else 1
patient=Patient(line[0],line[1],line[2],line[3],line... | self.cordsy=cordsy
self.residency_status=1 if residency_status=='Singaporean Citizen' else 0
def set_priority(self,priority_level):
self.priority_level=priority_level
def insert_profiles():
#getting the patient profiles and sorting them based on their priority level
| 64 | 64 | 126 | 19 | 44 | lars-tps/Bambank-hackathon | dataprocessing.py | Python | insert_profiles | insert_profiles | 26 | 40 | 26 | 27 | 44113a09b5c0ae7afcc5e30fe347a9d44b8b170a | bigcode/the-stack | train |
98df403e979fafe8c21b66e6 | train | class | class Hospital:
def __init__(self,name,time_slots,max_number_of_patients,cordsx,cordsy):
self.name=name
self.time_slots=time_slots
self.max_number_of_patients=int(max_number_of_patients)
self.cordsx=cordsx
self.cordsy=cordsy
| class Hospital:
| def __init__(self,name,time_slots,max_number_of_patients,cordsx,cordsy):
self.name=name
self.time_slots=time_slots
self.max_number_of_patients=int(max_number_of_patients)
self.cordsx=cordsx
self.cordsy=cordsy
| from qrcode_generator import make_qr
from ClosestHospital import calculate,calcDistance
import csv
from priority_function import priority_sort
class Hospital:
| 32 | 64 | 68 | 3 | 28 | lars-tps/Bambank-hackathon | dataprocessing.py | Python | Hospital | Hospital | 5 | 11 | 5 | 5 | bb159509769300b29b8d9adbcb78cee19f9e9b15 | bigcode/the-stack | train |
2eb923786490ba756614f0c4 | train | class | class Patient:
def __init__(self,id,age,infection_status,cordsx,cordsy,residency_status):
self.id=id
self.age=int(age)
self.infection_status=1 if infection_status=="Infected" else 0
self.cordsx=cordsx
self.cordsy=cordsy
self.residency_status=1 if residency_status=='Si... | class Patient:
| def __init__(self,id,age,infection_status,cordsx,cordsy,residency_status):
self.id=id
self.age=int(age)
self.infection_status=1 if infection_status=="Infected" else 0
self.cordsx=cordsx
self.cordsy=cordsy
self.residency_status=1 if residency_status=='Singaporean Citiz... | self,name,time_slots,max_number_of_patients,cordsx,cordsy):
self.name=name
self.time_slots=time_slots
self.max_number_of_patients=int(max_number_of_patients)
self.cordsx=cordsx
self.cordsy=cordsy
class Patient:
| 63 | 64 | 110 | 3 | 59 | lars-tps/Bambank-hackathon | dataprocessing.py | Python | Patient | Patient | 14 | 23 | 14 | 14 | 02a6812e24ae7d4abb48e2d154666a0c4224c40a | bigcode/the-stack | train |
026569e96b8a24af1d62867e | train | class | class Task:
def __init__(self, alpha, beta, gamma, n):
super().__init__()
self.alpha = alpha
self.beta = beta
self.gamma = gamma
self.n = n
self.h = 1/n
def u(self, x):
return x**self.alpha * (1-x)**self.beta
def p(self, x):
return 1 + x... | class Task:
| def __init__(self, alpha, beta, gamma, n):
super().__init__()
self.alpha = alpha
self.beta = beta
self.gamma = gamma
self.n = n
self.h = 1/n
def u(self, x):
return x**self.alpha * (1-x)**self.beta
def p(self, x):
return 1 + x**self.gamma
... | class Task:
| 3 | 123 | 411 | 3 | 0 | rtix/computational_methods_19-20 | Task.py | Python | Task | Task | 2 | 61 | 2 | 3 | cbf5b5b5d982f03fc009c0a4d946e2338cc055ae | bigcode/the-stack | train |
c5f3835ea07356b74480b346 | train | class | class Component(ApplicationSession):
"""
An application component that subscribes and receives events,
and stop after having received 5 events.
"""
@asyncio.coroutine
def onJoin(self, details):
self.received = 0
# subscribe all methods on this object decorated with "@wamp.sub... | class Component(ApplicationSession):
| """
An application component that subscribes and receives events,
and stop after having received 5 events.
"""
@asyncio.coroutine
def onJoin(self, details):
self.received = 0
# subscribe all methods on this object decorated with "@wamp.subscribe"
# as PubSub event hand... | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
###############################################################################
try:
import asyncio
except ImportError:
# Trollius >= 0.3 was renamed
import trollius as asyncio
from autobahn import wamp
from autob... | 75 | 75 | 252 | 5 | 69 | dimddev/AutobahnPython | examples/asyncio/wamp/basic/pubsub/decorators/frontend.py | Python | Component | Component | 37 | 73 | 37 | 38 | 34ed5467bc6278d2465248032188034dd5ee179e | bigcode/the-stack | train |
eef2dc909f92ab23ee1b7b09 | train | function | def _coarsen_timestamps(graph: Dict[Timestamp, Set[Timestamp]]) -> Dict[int, Set[int]]:
coarsened: Dict[int, Set[int]] = defaultdict(set)
for child, parents in graph.items():
for par in parents:
coarsened[child.cell_num].add(par.cell_num)
return coarsened
| def _coarsen_timestamps(graph: Dict[Timestamp, Set[Timestamp]]) -> Dict[int, Set[int]]:
| coarsened: Dict[int, Set[int]] = defaultdict(set)
for child, parents in graph.items():
for par in parents:
coarsened[child.cell_num].add(par.cell_num)
return coarsened
| _timestamps)
# For each dependent cell, recursively get their dependencies
for ts in dep_timestamps - dependencies:
_get_ts_dependencies(ts, dependencies, timestamp_to_ts_deps)
def _coarsen_timestamps(graph: Dict[Timestamp, Set[Timestamp]]) -> Dict[int, Set[int]]:
| 64 | 64 | 74 | 24 | 40 | nbsafety-project/nbsafety | nbsafety/analysis/slicing.py | Python | _coarsen_timestamps | _coarsen_timestamps | 62 | 67 | 62 | 62 | 6efeb688bc0c7f6af04bd5c679a892c90fe1b133 | bigcode/the-stack | train |
98773c541177dd686fd0058f | train | function | def _get_ts_dependencies(
timestamp: TimestampOrCounter,
dependencies: Set[TimestampOrCounter],
timestamp_to_ts_deps: Dict[TimestampOrCounter, Set[TimestampOrCounter]],
) -> None:
"""
For a given timestamps, this function recursively populates a set of
timestamps that the given timestamp depends... | def _get_ts_dependencies(
timestamp: TimestampOrCounter,
dependencies: Set[TimestampOrCounter],
timestamp_to_ts_deps: Dict[TimestampOrCounter, Set[TimestampOrCounter]],
) -> None:
| """
For a given timestamps, this function recursively populates a set of
timestamps that the given timestamp depends on, based on the live symbols.
Args:
- timestamp (ts_or_int): current timestamp / cell to get dependencies for
- dependencies (set<ts_or_int>): set of timestamps / cell c... | nbs
if TYPE_CHECKING:
from typing import Dict, List, Set, Type
from nbsafety.data_model.code_cell import ExecutedCodeCell
from nbsafety.types import TimestampOrCounter
logger = logging.getLogger(__name__)
logger.setLevel(logging.WARNING)
def _get_ts_dependencies(
timestamp: TimestampOrCounter,
d... | 105 | 105 | 353 | 45 | 60 | nbsafety-project/nbsafety | nbsafety/analysis/slicing.py | Python | _get_ts_dependencies | _get_ts_dependencies | 21 | 59 | 21 | 25 | 1bcdf849ec58f6f4bae09609faae0850a6fb21dd | bigcode/the-stack | train |
f5c86f9c53e647609522b231 | train | function | def _compute_slice_impl(seeds: List[TimestampOrCounter]) -> Set[TimestampOrCounter]:
assert len(seeds) > 0
dependencies: Set[TimestampOrCounter] = set()
timestamp_to_ts_deps: Dict[TimestampOrCounter, Set[TimestampOrCounter]] = defaultdict(set)
if nbs().mut_settings.dynamic_slicing_enabled:
if is... | def _compute_slice_impl(seeds: List[TimestampOrCounter]) -> Set[TimestampOrCounter]:
| assert len(seeds) > 0
dependencies: Set[TimestampOrCounter] = set()
timestamp_to_ts_deps: Dict[TimestampOrCounter, Set[TimestampOrCounter]] = defaultdict(set)
if nbs().mut_settings.dynamic_slicing_enabled:
if isinstance(seeds[0], Timestamp):
timestamp_to_ts_deps = _graph_union(timest... | _num].add(par.cell_num)
return coarsened
def _graph_union(
graph: Dict[TimestampOrCounter, Set[TimestampOrCounter]],
subsumed: Dict[TimestampOrCounter, Set[TimestampOrCounter]],
):
for child, parents in subsumed.items():
graph[child] |= parents
return graph
def _compute_slice_impl(seeds: L... | 93 | 93 | 313 | 21 | 71 | nbsafety-project/nbsafety | nbsafety/analysis/slicing.py | Python | _compute_slice_impl | _compute_slice_impl | 79 | 102 | 79 | 79 | 1512498fbfa42743b346446a6225d13c1d1fe040 | bigcode/the-stack | train |
4150f88e3c9b39a757711f64 | train | function | def _graph_union(
graph: Dict[TimestampOrCounter, Set[TimestampOrCounter]],
subsumed: Dict[TimestampOrCounter, Set[TimestampOrCounter]],
):
for child, parents in subsumed.items():
graph[child] |= parents
return graph
| def _graph_union(
graph: Dict[TimestampOrCounter, Set[TimestampOrCounter]],
subsumed: Dict[TimestampOrCounter, Set[TimestampOrCounter]],
):
| for child, parents in subsumed.items():
graph[child] |= parents
return graph
| ():
for par in parents:
coarsened[child.cell_num].add(par.cell_num)
return coarsened
def _graph_union(
graph: Dict[TimestampOrCounter, Set[TimestampOrCounter]],
subsumed: Dict[TimestampOrCounter, Set[TimestampOrCounter]],
):
| 64 | 64 | 59 | 37 | 26 | nbsafety-project/nbsafety | nbsafety/analysis/slicing.py | Python | _graph_union | _graph_union | 70 | 76 | 70 | 73 | 11d53a2b75c4ce623a9deb02691d8cbc59e96e9c | bigcode/the-stack | train |
deb68bb95d6bc8a1b253e2ea | train | class | class CodeCellSlicingMixin:
def compute_slice( # type: ignore
self: ExecutedCodeCell, stmt_level: bool = False
) -> Dict[int, str]:
return self.compute_slice_for_cells({self}, stmt_level=stmt_level)
@classmethod
def compute_slice_for_cells( # type: ignore
cls: Type[ExecutedCod... | class CodeCellSlicingMixin:
| def compute_slice( # type: ignore
self: ExecutedCodeCell, stmt_level: bool = False
) -> Dict[int, str]:
return self.compute_slice_for_cells({self}, stmt_level=stmt_level)
@classmethod
def compute_slice_for_cells( # type: ignore
cls: Type[ExecutedCodeCell], cells: Set[ExecutedC... | mut_settings.static_slicing_enabled:
if isinstance(seeds[0], Timestamp):
timestamp_to_ts_deps = _graph_union(timestamp_to_ts_deps, nbs().static_data_deps)
else:
timestamp_to_ts_deps = _graph_union(timestamp_to_ts_deps, _coarsen_timestamps(nbs().static_data_deps))
# ensure we... | 170 | 170 | 569 | 7 | 162 | nbsafety-project/nbsafety | nbsafety/analysis/slicing.py | Python | CodeCellSlicingMixin | CodeCellSlicingMixin | 105 | 164 | 105 | 105 | e5bbb00e5d5c849c86a727218aed83470a4b9c3c | bigcode/the-stack | train |
d97a7d6faecd17cc28fc01e8 | train | function | def plot_phase_fold(sample, data=None, ax=None,
with_time_unit=False, n_phase_samples=4096,
add_labels=True, show_s_errorbar=True, residual=False,
remove_trend=True, plot_kwargs=None, data_plot_kwargs=None):
"""
Plot phase-folded radial velocity curves... | def plot_phase_fold(sample, data=None, ax=None,
with_time_unit=False, n_phase_samples=4096,
add_labels=True, show_s_errorbar=True, residual=False,
remove_trend=True, plot_kwargs=None, data_plot_kwargs=None):
| """
Plot phase-folded radial velocity curves for the input orbital parameter
sample, optionally with data phase-folded to the same period.
Parameters
----------
samples : :class:`~thejoker.sampler.JokerSamples`
Posterior samples from The Joker.
data : `~thejoker.data.RVData`, option... | raise u.UnitsError("Data plot units don't match rv_unit!")
data.plot(ax=ax, relative_to_t_ref=relative_to_t_ref, add_labels=False,
**data_style)
_rv = data.rv.to(rv_unit).value
drv = _rv.max() - _rv.min()
data_ylim = (_rv.min() - 0.2*drv, _rv.max() + 0.2*drv)
els... | 256 | 256 | 1,229 | 54 | 201 | adrn/thejoker | thejoker/plot.py | Python | plot_phase_fold | plot_phase_fold | 195 | 341 | 195 | 198 | c2062db6f79d4ebd3d95f1e41719904fc33e88d4 | bigcode/the-stack | train |
e553cef58f687a6371981601 | train | function | @deprecated_renamed_argument('relative_to_t0', 'relative_to_t_ref',
since='v1.2', warning_type=DeprecationWarning)
def plot_rv_curves(samples, t_grid=None, rv_unit=None, data=None,
ax=None, plot_kwargs=dict(), data_plot_kwargs=dict(),
add_labels=True, r... | @deprecated_renamed_argument('relative_to_t0', 'relative_to_t_ref',
since='v1.2', warning_type=DeprecationWarning)
def plot_rv_curves(samples, t_grid=None, rv_unit=None, data=None,
ax=None, plot_kwargs=dict(), data_plot_kwargs=dict(),
add_labels=True, r... | """
Plot radial velocity curves for the input set of orbital parameter
samples over the input grid of times.
Parameters
----------
samples : :class:`~thejoker.sampler.JokerSamples`
Posterior samples from The Joker.
t_grid : array_like, `~astropy.time.Time`, optional
Array of... | Error("Period must be a scalar quantity")
n_grid = w / dt
if max_t_grid is not None and n_grid > max_t_grid:
dt = w / max_t_grid
n_grid = max_t_grid
if n_grid > 1e4:
warnings.warn(
"Time grid has more than 10,000 grid points, so plotting orbits "
"could be v... | 256 | 256 | 1,302 | 90 | 165 | adrn/thejoker | thejoker/plot.py | Python | plot_rv_curves | plot_rv_curves | 44 | 192 | 44 | 49 | 696a16a8798ade3fc554ae3c9acba0e1930085b9 | bigcode/the-stack | train |
502f90c07e115353b6a5ee3a | train | function | def get_t_grid(data, P, span_factor=0.1, max_t_grid=None):
w = np.ptp(data.t.mjd)
dt = P.to_value(u.day) / 64 # MAGIC NUMBER
if P.shape != ():
raise ValueError("Period must be a scalar quantity")
n_grid = w / dt
if max_t_grid is not None and n_grid > max_t_grid:
dt = w / max_t_gri... | def get_t_grid(data, P, span_factor=0.1, max_t_grid=None):
| w = np.ptp(data.t.mjd)
dt = P.to_value(u.day) / 64 # MAGIC NUMBER
if P.shape != ():
raise ValueError("Period must be a scalar quantity")
n_grid = w / dt
if max_t_grid is not None and n_grid > max_t_grid:
dt = w / max_t_grid
n_grid = max_t_grid
if n_grid > 1e4:
... | Project
from .data import RVData
from .data_helpers import validate_prepare_data
from .prior_helpers import get_v0_offsets_equiv_units
__all__ = ['plot_rv_curves', 'plot_phase_fold']
def get_t_grid(data, P, span_factor=0.1, max_t_grid=None):
| 67 | 67 | 224 | 20 | 47 | adrn/thejoker | thejoker/plot.py | Python | get_t_grid | get_t_grid | 18 | 41 | 18 | 18 | aeeaa56f480b8e9192e7c87e1ed6dd01479c3dbe | bigcode/the-stack | train |
30a6395df62a0e7f872fcd45 | train | class | class TestGjwt_auth_mutations(Gjwt_authTestCase):
# ########
# REGISTER
# ########
def test_register_mutation_success(self):
request = self.rf.request()
query = """
mutation {
register(
email: "laffe@giraffe.de",
password: "123",
... | class TestGjwt_auth_mutations(Gjwt_authTestCase):
# ########
# REGISTER
# ########
| def test_register_mutation_success(self):
request = self.rf.request()
query = """
mutation {
register(
email: "laffe@giraffe.de",
password: "123",
passwordRepeat: "123"
)
{
success
errors
... | from django.contrib.auth import get_user_model
from django.contrib.auth.tokens import default_token_generator
from djoser.email import ActivationEmail, PasswordResetEmail
from djoser import utils
from .graphql_schema import schema
from .testcases import Gjwt_authTestCase
User = get_user_model()
class TestGjwt_auth... | 88 | 256 | 1,833 | 25 | 63 | MikhailPasechnik/graphene-jwt-auth-registration | tests/test_mutations.py | Python | TestGjwt_auth_mutations | TestGjwt_auth_mutations | 16 | 360 | 16 | 20 | 9e983eeb1f718b6ed8266b46c6fe8f16baed7f68 | bigcode/the-stack | train |
a5846820fedb6d173e11dcbe | train | class | class JSONSchemaValidatorFd729F50E65695966359B589A1606B(object):
"""getGroupsByDomain request schema definition."""
def __init__(self):
super(JSONSchemaValidatorFd729F50E65695966359B589A1606B, self).__init__()
self._validator = fastjsonschema.compile(json.loads(
'''{
... | class JSONSchemaValidatorFd729F50E65695966359B589A1606B(object):
| """getGroupsByDomain request schema definition."""
def __init__(self):
super(JSONSchemaValidatorFd729F50E65695966359B589A1606B, self).__init__()
self._validator = fastjsonschema.compile(json.loads(
'''{
"$schema": "http://json-schema.org/draft-04/schema#",
... | FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
import fastjsonschema
import json
from ciscoisesdk.exceptions import MalformedRequest
from builtins import *
clas... | 90 | 90 | 303 | 21 | 69 | oianson/ciscoisesdk | tests/models/validators/v3_0_0/jsd_fd729f50e65695966359b589a1606b.py | Python | JSONSchemaValidatorFd729F50E65695966359B589A1606B | JSONSchemaValidatorFd729F50E65695966359B589A1606B | 40 | 87 | 40 | 40 | ba70deab09380ded60f715dbb785aa448eaad54d | bigcode/the-stack | train |
0651543a4898b92cb0a0ef84 | train | class | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
return ["FizzBuzz" if i % 15 == 0 else("Fizz" if i % 3 == 0 else("Buzz" if i % 5 == 0 else str(i))) for i in range(1, n + 1)]
| class Solution:
| def fizzBuzz(self, n: int) -> List[str]:
return ["FizzBuzz" if i % 15 == 0 else("Fizz" if i % 3 == 0 else("Buzz" if i % 5 == 0 else str(i))) for i in range(1, n + 1)]
| class Solution:
| 3 | 64 | 71 | 3 | 0 | forewing/lc | python/p412.py | Python | Solution | Solution | 1 | 3 | 1 | 1 | 0ab6f9082f1877873ce374a447dc1332e4b02dc8 | bigcode/the-stack | train |
cec431db5686b87ba8a127a8 | train | function | def load_station_ll_vs30(station_file: str, vs30_file: str):
""" Reads both station and vs30 file into a single pandas dataframe - keeps only the matching entries
:param station_file: Path to the station file
:param vs30_file: Path to the vs30 file
:return: pd.DataFrame
station as index and col... | def load_station_ll_vs30(station_file: str, vs30_file: str):
| """ Reads both station and vs30 file into a single pandas dataframe - keeps only the matching entries
:param station_file: Path to the station file
:param vs30_file: Path to the vs30 file
:return: pd.DataFrame
station as index and columns lon, lat, vs30
"""
vs30_df = load_vs30_file(vs3... | z1p0, z2p5
"""
return pd.read_csv(z_file, names=["z1p0", "z2p5", "sigma"], index_col=0, skiprows=1)
def load_station_ll_vs30(station_file: str, vs30_file: str):
| 64 | 64 | 131 | 18 | 46 | QuakeKorea/qcore | qcore/formats.py | Python | load_station_ll_vs30 | load_station_ll_vs30 | 107 | 119 | 107 | 107 | 9bd94a53c750e664cc4353e666df5923134d1009 | bigcode/the-stack | train |
8cf1e265e1807e05753df4d1 | train | function | def load_im_file(csv_file, all_psa=False, comp=None):
# process column names
use_cols = []
col_names = []
with open(csv_file, "r") as f:
raw_cols = list(map(str.strip, f.readline().split(",")))
for i, c in enumerate(raw_cols):
# filter out pSA that aren't round numbers, duplicates
... | def load_im_file(csv_file, all_psa=False, comp=None):
# process column names
| use_cols = []
col_names = []
with open(csv_file, "r") as f:
raw_cols = list(map(str.strip, f.readline().split(",")))
for i, c in enumerate(raw_cols):
# filter out pSA that aren't round numbers, duplicates
if c not in col_names and (
all_psa or not (c.startswith("pSA_"... | """
Functions and classes to load data that doesn't belong elsewhere.
"""
import pandas as pd
import numpy as np
def load_im_file(csv_file, all_psa=False, comp=None):
# process column names
| 44 | 86 | 287 | 21 | 22 | QuakeKorea/qcore | qcore/formats.py | Python | load_im_file | load_im_file | 9 | 40 | 9 | 11 | 2b37cebefff243478669c5b308390d73678e86d9 | bigcode/the-stack | train |
9e280d2f9bea4367f4ee7c85 | train | function | def load_z_file(z_file: str):
"""Reads the z file into a pandas dataframe
:param z_file: Path to the z file
:return: pd.DataFrame
station as index and columns z1p0, z2p5
"""
return pd.read_csv(z_file, names=["z1p0", "z2p5", "sigma"], index_col=0, skiprows=1)
| def load_z_file(z_file: str):
| """Reads the z file into a pandas dataframe
:param z_file: Path to the z file
:return: pd.DataFrame
station as index and columns z1p0, z2p5
"""
return pd.read_csv(z_file, names=["z1p0", "z2p5", "sigma"], index_col=0, skiprows=1)
| : Path to the vs30 file
:return: pd.DataFrame
station as index and columns vs30
"""
return pd.read_csv(vs30_file, sep="\s+", index_col=0, header=None, names=["vs30"])
def load_z_file(z_file: str):
| 63 | 64 | 92 | 9 | 54 | QuakeKorea/qcore | qcore/formats.py | Python | load_z_file | load_z_file | 97 | 104 | 97 | 97 | 9de26bc17cdcae2d79d6e67cc56bd01ead7ece00 | bigcode/the-stack | train |
44419cfdbd763df4632a1a7d | train | function | def load_station_file(station_file: str):
"""Reads the station file into a pandas dataframe
Parameters
----------
station_file : str
Path to the station file
Returns
-------
pd.DataFrame
station as index and columns lon, lat
"""
return pd.read_csv(
station_f... | def load_station_file(station_file: str):
| """Reads the station file into a pandas dataframe
Parameters
----------
station_file : str
Path to the station file
Returns
-------
pd.DataFrame
station as index and columns lon, lat
"""
return pd.read_csv(
station_file,
header=None,
index_co... | if not all_ims:
df = df[[im for im in df.columns if (len(im) < 15)]]
if comp is not None:
df = df[df.index.get_level_values(1) == comp]
return df
def load_station_file(station_file: str):
| 64 | 64 | 102 | 10 | 53 | QuakeKorea/qcore | qcore/formats.py | Python | load_station_file | load_station_file | 64 | 84 | 64 | 64 | 8f0d8da015ffdf41abed5bdd1c3ec42f71377148 | bigcode/the-stack | train |
cf8975149882efdeb580f332 | train | function | def load_im_file_pd(imcsv, all_ims=False, comp=None):
"""
Loads an IM file using pandas and returns a dataframe
:param imcsv: FFP to im_csv
:param all_ims: returns all_ims. Defaultly returns only short IM names (standard pSA periods etc).
Setting this to true includes all pSA periods... | def load_im_file_pd(imcsv, all_ims=False, comp=None):
| """
Loads an IM file using pandas and returns a dataframe
:param imcsv: FFP to im_csv
:param all_ims: returns all_ims. Defaultly returns only short IM names (standard pSA periods etc).
Setting this to true includes all pSA periods (and other long IM names). Extended pSA periods have
... | (
csv_file, dtype=dtype, delimiter=",", skiprows=1, usecols=tuple(use_cols)
)
)
if comp is None:
return imdb
return imdb[imdb.component == comp]
def load_im_file_pd(imcsv, all_ims=False, comp=None):
| 64 | 64 | 195 | 16 | 48 | QuakeKorea/qcore | qcore/formats.py | Python | load_im_file_pd | load_im_file_pd | 43 | 61 | 43 | 43 | 84c2faa4befc5b8e05860ace16fafc3bf0378ec3 | bigcode/the-stack | train |
fc756f0c9399ae69f0b87ef4 | train | function | def load_e3d_par(fp: str, comment_chars=("#",)):
"""
Loads an emod3d parameter file as a dictionary
As the original file does not have type data all values will be strings. Typing must be done manually.
Crashes if duplicate keys are found
:param fp: The path to the parameter file
:param comment_... | def load_e3d_par(fp: str, comment_chars=("#",)):
| """
Loads an emod3d parameter file as a dictionary
As the original file does not have type data all values will be strings. Typing must be done manually.
Crashes if duplicate keys are found
:param fp: The path to the parameter file
:param comment_chars: Any single characters that denote the line... | faults.keys():
raise ValueError(
"Fault {} has been found twice in the fault selection file, please check the file".format(
fault
)
)
faults.update({fault: count})
return faults
def load_e3d_par(fp: str, co... | 64 | 64 | 216 | 16 | 47 | QuakeKorea/qcore | qcore/formats.py | Python | load_e3d_par | load_e3d_par | 173 | 193 | 173 | 173 | 55b1f66a656871e70802b8f9f41d9f6cd302ddcb | bigcode/the-stack | train |
ad810c80c91a294cfe88f3a4 | train | function | def load_vs30_file(vs30_file: str):
"""Reads the vs30 file into a pandas dataframe
:param vs30_file: Path to the vs30 file
:return: pd.DataFrame
station as index and columns vs30
"""
return pd.read_csv(vs30_file, sep="\s+", index_col=0, header=None, names=["vs30"])
| def load_vs30_file(vs30_file: str):
| """Reads the vs30 file into a pandas dataframe
:param vs30_file: Path to the vs30 file
:return: pd.DataFrame
station as index and columns vs30
"""
return pd.read_csv(vs30_file, sep="\s+", index_col=0, header=None, names=["vs30"])
| station as index and columns lon, lat
"""
return pd.read_csv(
station_file,
header=None,
index_col=2,
names=["lon", "lat"],
engine="c",
delim_whitespace=True,
)
def load_vs30_file(vs30_file: str):
| 64 | 64 | 84 | 12 | 52 | QuakeKorea/qcore | qcore/formats.py | Python | load_vs30_file | load_vs30_file | 87 | 94 | 87 | 87 | 1fd5ea2a59f578536170acf0477344ffee852d87 | bigcode/the-stack | train |
879102014c199ec57da04aa5 | train | function | def load_fault_selection_file(fault_selection_file):
"""
Loads a fault selection file, returning a dictionary of fault:count pairs
:param fault_selection_file: The relative or absolute path to the fault selection file
:return: A dictionary of fault:count pairs for all faults found in the file
"""
... | def load_fault_selection_file(fault_selection_file):
| """
Loads a fault selection file, returning a dictionary of fault:count pairs
:param fault_selection_file: The relative or absolute path to the fault selection file
:return: A dictionary of fault:count pairs for all faults found in the file
"""
faults = {}
with open(fault_selection_file) as ... | up_file: str
Path to the rrup file to load
Returns
-------
pd.DataFrame
station as index with columns rrup, rjb and optional rx
"""
return pd.read_csv(rrup_file, header=0, index_col=0, engine="c")
def load_fault_selection_file(fault_selection_file):
| 74 | 74 | 248 | 10 | 64 | QuakeKorea/qcore | qcore/formats.py | Python | load_fault_selection_file | load_fault_selection_file | 138 | 170 | 138 | 138 | 049bfc946dace7d696ccf62338ae10311c4466ca | bigcode/the-stack | train |
109406b81eed01c12bc0f05b | train | function | def load_rrup_file(rrup_file: str):
"""Reads the rrup file into a pandas dataframe
Parameters
----------
rrup_file: str
Path to the rrup file to load
Returns
-------
pd.DataFrame
station as index with columns rrup, rjb and optional rx
"""
return pd.read_csv(rrup_fil... | def load_rrup_file(rrup_file: str):
| """Reads the rrup file into a pandas dataframe
Parameters
----------
rrup_file: str
Path to the rrup file to load
Returns
-------
pd.DataFrame
station as index with columns rrup, rjb and optional rx
"""
return pd.read_csv(rrup_file, header=0, index_col=0, engine="c"... | columns lon, lat, vs30
"""
vs30_df = load_vs30_file(vs30_file)
station_df = load_station_file(station_file)
return vs30_df.merge(station_df, left_index=True, right_index=True)
def load_rrup_file(rrup_file: str):
| 64 | 64 | 94 | 11 | 53 | QuakeKorea/qcore | qcore/formats.py | Python | load_rrup_file | load_rrup_file | 122 | 135 | 122 | 122 | 547d19474b5fd8fc5d24e64039c6a0731224506c | bigcode/the-stack | train |
716871e27d12259a4d3ee696 | train | function | def snap_eradicate(name, suffix=None):
'''
Eradicate a deleted filesystem snapshot on a Pure Storage FlashBlade.
Will return False if snapshot is not in a deleted state.
.. versionadded:: Fluorine
name : string
name of filesystem
suffix : string
name of snapshot
CLI Exa... | def snap_eradicate(name, suffix=None):
| '''
Eradicate a deleted filesystem snapshot on a Pure Storage FlashBlade.
Will return False if snapshot is not in a deleted state.
.. versionadded:: Fluorine
name : string
name of filesystem
suffix : string
name of snapshot
CLI Example:
.. code-block:: bash
... |
if eradicate is True:
try:
blade.file_system_snapshots.delete_file_system_snapshots(name=snapname)
return True
except rest.ApiException:
return False
else:
return True
else:
return False
def snap_eradicate(n... | 64 | 64 | 170 | 10 | 53 | major0/salt | salt/modules/purefb.py | Python | snap_eradicate | snap_eradicate | 251 | 281 | 251 | 251 | 1ddc0531b3f3451c12664435aade268e336f40dd | bigcode/the-stack | train |
98fea038e0c2a679bd1e3076 | train | function | def fs_update(name, rules, snapshot=False):
'''
Update filesystem on a Pure Storage FlashBlade.
Allows for change of NFS export rules and enabling/disabled
of snapshotting capability.
.. versionadded:: Fluorine
name : string
name of filesystem
rules : string
NFS export r... | def fs_update(name, rules, snapshot=False):
| '''
Update filesystem on a Pure Storage FlashBlade.
Allows for change of NFS export rules and enabling/disabled
of snapshotting capability.
.. versionadded:: Fluorine
name : string
name of filesystem
rules : string
NFS export rules for filesystem
Refer to Pure St... | ed'] = __utils__['stringutils.human_to_bytes'](size)
n_attr = FileSystem(**attr)
blade.file_systems.update_file_systems(name=name, attributes=n_attr)
return True
except rest.ApiException:
return False
else:
return False
... | 80 | 80 | 267 | 10 | 69 | major0/salt | salt/modules/purefb.py | Python | fs_update | fs_update | 469 | 508 | 469 | 469 | d14dbbac75e503a4e0c69798b9057817fd14e22d | bigcode/the-stack | train |
b37e7886f8f2c6680ae41c18 | train | function | def fs_extend(name, size):
'''
Resize an existing filesystem on a Pure Storage FlashBlade.
Will return False if new size is less than or equal to existing size.
.. versionadded:: Fluorine
name : string
name of filesystem
size : string
New capacity of filesystem.
Refe... | def fs_extend(name, size):
| '''
Resize an existing filesystem on a Pure Storage FlashBlade.
Will return False if new size is less than or equal to existing size.
.. versionadded:: Fluorine
name : string
name of filesystem
size : string
New capacity of filesystem.
Refer to Pure Storage documenta... | eradicate foo
'''
blade = _get_blade()
if _get_deleted_fs(name, blade) is not None:
try:
blade.file_systems.delete_file_systems(name)
return True
except rest.ApiException:
return False
else:
return False
def fs_extend(name, size):
| 70 | 70 | 235 | 7 | 62 | major0/salt | salt/modules/purefb.py | Python | fs_extend | fs_extend | 429 | 466 | 429 | 429 | c150bf8e5d4fd3713f68663c214ac7d3f0279935 | bigcode/the-stack | train |
387c47a7a9ccb5e1ce605d04 | train | function | def _get_blade():
'''
Get Pure Storage FlasBlade configuration
1) From the minion config
pure_tags:
fb:
san_ip: management vip or hostname for the FlashBlade
api_token: A valid api token for the FlashBlade being managed
2) From environment (PUREFB_IP and PUREFB... | def _get_blade():
| '''
Get Pure Storage FlasBlade configuration
1) From the minion config
pure_tags:
fb:
san_ip: management vip or hostname for the FlashBlade
api_token: A valid api token for the FlashBlade being managed
2) From environment (PUREFB_IP and PUREFB_API)
3) From ... | _FB = True
except ImportError:
HAS_PURITY_FB = False
__docformat__ = 'restructuredtext en'
__virtualname__ = 'purefb'
def __virtual__():
'''
Determine whether or not to load this module
'''
if HAS_PURITY_FB:
return __virtualname__
return (False, 'purefb execution module not loaded: p... | 94 | 95 | 317 | 6 | 88 | major0/salt | salt/modules/purefb.py | Python | _get_blade | _get_blade | 85 | 123 | 85 | 85 | e50306f555dbd01bd21e42833795ff3e505a2b0f | bigcode/the-stack | train |
b91844a97c026ad641a9e640 | train | function | def snap_create(name, suffix=None):
'''
Create a filesystem snapshot on a Pure Storage FlashBlade.
Will return False if filesystem selected to snap does not exist.
.. versionadded:: Fluorine
name : string
name of filesystem to snapshot
suffix : string
if specificed forces sn... | def snap_create(name, suffix=None):
| '''
Create a filesystem snapshot on a Pure Storage FlashBlade.
Will return False if filesystem selected to snap does not exist.
.. versionadded:: Fluorine
name : string
name of filesystem to snapshot
suffix : string
if specificed forces snapshot name suffix. If not specified... | _deleted_fs(name, blade):
'''
Private function to check
if a file systeem has already been deleted
'''
try:
_fs = _get_fs(name, blade)
if _fs and _fs.destroyed:
return _fs
except rest.ApiException:
return None
def snap_create(name, suffix=None):
| 73 | 73 | 246 | 8 | 64 | major0/salt | salt/modules/purefb.py | Python | snap_create | snap_create | 166 | 204 | 166 | 166 | 6300b5b40b38b55412988eb43b0a4c3369081608 | bigcode/the-stack | train |
dbe86df936e86643a5765afc | train | function | def fs_eradicate(name):
'''
Eradicate a deleted filesystem on a Pure Storage FlashBlade.
Will return False is filesystem is not in a deleted state.
.. versionadded:: Fluorine
name : string
name of filesystem
CLI Example:
.. code-block:: bash
salt '*' purefb.fs_eradica... | def fs_eradicate(name):
| '''
Eradicate a deleted filesystem on a Pure Storage FlashBlade.
Will return False is filesystem is not in a deleted state.
.. versionadded:: Fluorine
name : string
name of filesystem
CLI Example:
.. code-block:: bash
salt '*' purefb.fs_eradicate foo
'''
blad... | except rest.ApiException:
return False
if eradicate is True:
try:
blade.file_systems.delete_file_systems(name)
return True
except rest.ApiException:
return False
else:
return True
else:
return Fa... | 64 | 64 | 137 | 7 | 56 | major0/salt | salt/modules/purefb.py | Python | fs_eradicate | fs_eradicate | 399 | 426 | 399 | 399 | 264d7e7f5a6d225259d832faeeb211a839ae615c | bigcode/the-stack | train |
d042db8b6f6df1628029dc4a | train | function | def fs_delete(name, eradicate=False):
'''
Delete a share on a Pure Storage FlashBlade.
Will return False if filesystem doesn't exist or is already in a deleted state.
.. versionadded:: Fluorine
name : string
name of filesystem
eradicate : boolean
(Optional) Eradicate filesys... | def fs_delete(name, eradicate=False):
| '''
Delete a share on a Pure Storage FlashBlade.
Will return False if filesystem doesn't exist or is already in a deleted state.
.. versionadded:: Fluorine
name : string
name of filesystem
eradicate : boolean
(Optional) Eradicate filesystem after deletion if True. Default is... | ,
snapshot_directory_enabled=snapshot,
http=ProtocolRule(enabled=True),
)
else:
return False
try:
blade.file_systems.create_file_systems(fs_obj)
return True
except r... | 69 | 69 | 232 | 8 | 60 | major0/salt | salt/modules/purefb.py | Python | fs_delete | fs_delete | 355 | 396 | 355 | 355 | eae602f34e9ad0bc31f09c208c3b918684af7e07 | bigcode/the-stack | train |
3de5f8747649863d9c6d8488 | train | function | def __virtual__():
'''
Determine whether or not to load this module
'''
if HAS_PURITY_FB:
return __virtualname__
return (False, 'purefb execution module not loaded: purity_fb python library not available.')
| def __virtual__():
| '''
Determine whether or not to load this module
'''
if HAS_PURITY_FB:
return __virtualname__
return (False, 'purefb execution module not loaded: purity_fb python library not available.')
| Snapshot, SnapshotSuffix
from purity_fb import rest, NfsRule, ProtocolRule
HAS_PURITY_FB = True
except ImportError:
HAS_PURITY_FB = False
__docformat__ = 'restructuredtext en'
__virtualname__ = 'purefb'
def __virtual__():
| 64 | 64 | 52 | 5 | 59 | major0/salt | salt/modules/purefb.py | Python | __virtual__ | __virtual__ | 76 | 82 | 76 | 76 | c9c9afccba608195b8c3979d36122c323f49ef7c | bigcode/the-stack | train |
b17dda722b03ccbe1c7a5f79 | train | function | def fs_create(name, size=None, proto='NFS', nfs_rules='*(rw,no_root_squash)', snapshot=False):
'''
Create a filesystem on a Pure Storage FlashBlade.
Will return False if filesystem already exists.
.. versionadded:: Fluorine
name : string
name of filesystem (truncated to 63 characters)
... | def fs_create(name, size=None, proto='NFS', nfs_rules='*(rw,no_root_squash)', snapshot=False):
| '''
Create a filesystem on a Pure Storage FlashBlade.
Will return False if filesystem already exists.
.. versionadded:: Fluorine
name : string
name of filesystem (truncated to 63 characters)
proto : string
(Optional) Sharing protocol (NFS, CIFS or HTTP). If not specified def... | Fluorine
name : string
name of filesystem
suffix : string
name of snapshot
CLI Example:
.. code-block:: bash
salt '*' purefb.snap_eradicate foo suffix=snap
'''
blade = _get_blade()
if _get_snapshot(name, suffix, blade) is not None:
snapname = name + '.'... | 153 | 153 | 512 | 28 | 124 | major0/salt | salt/modules/purefb.py | Python | fs_create | fs_create | 284 | 352 | 284 | 284 | 63a19312291a70e2590b96ebeb6c08f8256d73ac | bigcode/the-stack | train |
5380f8e1f7e879c06124330d | train | function | def snap_delete(name, suffix=None, eradicate=False):
'''
Delete a filesystem snapshot on a Pure Storage FlashBlade.
Will return False if selected snapshot does not exist.
.. versionadded:: Fluorine
name : string
name of filesystem
suffix : string
name of snapshot
eradica... | def snap_delete(name, suffix=None, eradicate=False):
| '''
Delete a filesystem snapshot on a Pure Storage FlashBlade.
Will return False if selected snapshot does not exist.
.. versionadded:: Fluorine
name : string
name of filesystem
suffix : string
name of snapshot
eradicate : boolean
Eradicate snapshot after deletio... | ) is not None:
try:
source = []
source.append(name)
blade.file_system_snapshots.create_file_system_snapshots(sources=source,
suffix=SnapshotSuffix(suffix))
return True
except rest.ApiExce... | 73 | 73 | 244 | 11 | 61 | major0/salt | salt/modules/purefb.py | Python | snap_delete | snap_delete | 207 | 248 | 207 | 207 | 177f16315ea7abf6e1193130a0057efe0fb27ea5 | bigcode/the-stack | train |
ad128758961f39c8255d1cd6 | train | function | def _get_deleted_fs(name, blade):
'''
Private function to check
if a file systeem has already been deleted
'''
try:
_fs = _get_fs(name, blade)
if _fs and _fs.destroyed:
return _fs
except rest.ApiException:
return None
| def _get_deleted_fs(name, blade):
| '''
Private function to check
if a file systeem has already been deleted
'''
try:
_fs = _get_fs(name, blade)
if _fs and _fs.destroyed:
return _fs
except rest.ApiException:
return None
| try:
filt = 'source=\'{}\' and suffix=\'{}\''.format(name, suffix)
res = blade.file_system_snapshots.list_file_system_snapshots(filter=filt)
return res.items[0]
except rest.ApiException:
return None
def _get_deleted_fs(name, blade):
| 64 | 64 | 68 | 9 | 54 | major0/salt | salt/modules/purefb.py | Python | _get_deleted_fs | _get_deleted_fs | 153 | 163 | 153 | 153 | dd242bc2275c967c04fbc8a90a0e2b230f8d5cc7 | bigcode/the-stack | train |
fc00b344888184d833b1e738 | train | function | def _get_snapshot(name, suffix, blade):
'''
Return name of Snapshot
or None
'''
try:
filt = 'source=\'{}\' and suffix=\'{}\''.format(name, suffix)
res = blade.file_system_snapshots.list_file_system_snapshots(filter=filt)
return res.items[0]
except rest.ApiException:
... | def _get_snapshot(name, suffix, blade):
| '''
Return name of Snapshot
or None
'''
try:
filt = 'source=\'{}\' and suffix=\'{}\''.format(name, suffix)
res = blade.file_system_snapshots.list_file_system_snapshots(filter=filt)
return res.items[0]
except rest.ApiException:
return None
| existance of a filesystem
'''
_fs = []
_fs.append(name)
try:
res = blade.file_systems.list_file_systems(names=_fs)
return res.items[0]
except rest.ApiException:
return None
def _get_snapshot(name, suffix, blade):
| 64 | 64 | 79 | 10 | 53 | major0/salt | salt/modules/purefb.py | Python | _get_snapshot | _get_snapshot | 140 | 150 | 140 | 140 | 8efcda5e879b34221a82ceaf5dca86ba70faa1e9 | bigcode/the-stack | train |
ccd6c4c487cf953d63a4991c | train | function | def _get_fs(name, blade):
'''
Private function to
check for existance of a filesystem
'''
_fs = []
_fs.append(name)
try:
res = blade.file_systems.list_file_systems(names=_fs)
return res.items[0]
except rest.ApiException:
return None
| def _get_fs(name, blade):
| '''
Private function to
check for existance of a filesystem
'''
_fs = []
_fs.append(name)
try:
res = blade.file_systems.list_file_systems(names=_fs)
return res.items[0]
except rest.ApiException:
return None
| _verify_ssl()
except (KeyError, NameError):
raise CommandExecutionError('No Pure Storage FlashBlade credentials found.')
try:
blade.login(api_token)
except Exception:
raise CommandExecutionError('Pure Storage FlashBlade authentication failed.')
return blade
def _g... | 64 | 64 | 72 | 8 | 55 | major0/salt | salt/modules/purefb.py | Python | _get_fs | _get_fs | 126 | 137 | 126 | 126 | 317267e784be44f47418a1b119f3e170038dad12 | bigcode/the-stack | train |
c3075635a2797459ee551584 | train | class | @unittest.skipUnless(HAVE_WEBSOCKET, 'websocket not available')
class TestWebSocket(unittest.TestCase):
@staticmethod
def _kraken(impl):
with impl('wss://ws.kraken.com/') as ws:
ws.send('{"event":"subscribe", "subscription":{"name":"trade"}, "pair":["XBT/USD","XRP/USD"]}')
for _... | @unittest.skipUnless(HAVE_WEBSOCKET, 'websocket not available')
class TestWebSocket(unittest.TestCase):
@staticmethod
| def _kraken(impl):
with impl('wss://ws.kraken.com/') as ws:
ws.send('{"event":"subscribe", "subscription":{"name":"trade"}, "pair":["XBT/USD","XRP/USD"]}')
for _ in range(5):
print(ws.recv())
@staticmethod
def _echo(impl, url):
with impl(url) as ws:
... | Wrapper,
NodeJsWsWrapper,
)
import logging
logger = logging.getLogger('websockets')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
@unittest.skipUnless(HAVE_WEBSOCKET, 'websocket not available')
class TestWebSocket(unittest.TestCase):
@staticmethod
| 64 | 64 | 160 | 29 | 35 | shivamagarwal1999/ytdl-patched | test/test_websocket.py | Python | TestWebSocket | TestWebSocket | 32 | 50 | 32 | 35 | 9fc6caeae9dde3b977a46be7860bb43651aad1f8 | bigcode/the-stack | train |
c3b71f035b4a128ae9da1e09 | train | class | class WordSim:
def __init__(self, word1, word2, scores):
self.word1 = word1
self.word2 = word2
self.scores = scores
def evaluate(self, emb, r='spearman'):
word1_index = np.array([w.index for w in self.word1], dtype=np.int32)
word2_index = np.array([w.index for w in self.... | class WordSim:
| def __init__(self, word1, word2, scores):
self.word1 = word1
self.word2 = word2
self.scores = scores
def evaluate(self, emb, r='spearman'):
word1_index = np.array([w.index for w in self.word1], dtype=np.int32)
word2_index = np.array([w.index for w in self.word2], dtype=n... | import numpy as np
from scipy.stats import spearmanr, pearsonr
class WordSim:
| 21 | 87 | 290 | 4 | 16 | jyori112/cython-word2vec | word2vec/evaluation.py | Python | WordSim | WordSim | 4 | 43 | 4 | 4 | 049e754fe89d0cbabf5202e92ba781b5ea027aa4 | bigcode/the-stack | train |
d9a1a6c17a1205aa2d79ffd4 | train | class | class Queue(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
auto_delete_on_idle: Optional[pulumi.Input[str]] = None,
dead_lettering_on_message_expiration: Optional[pulumi.Input[bool]... | class Queue(pulumi.CustomResource):
| def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
auto_delete_on_idle: Optional[pulumi.Input[str]] = None,
dead_lettering_on_message_expiration: Optional[pulumi.Input[bool]] = None,
default_m... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilitie... | 95 | 256 | 5,014 | 8 | 87 | suresh198526/pulumi-azure | sdk/python/pulumi_azure/servicebus/queue.py | Python | Queue | Queue | 14 | 358 | 14 | 14 | 50039e2cd0bcd142de1f7510174de346e79f9c4c | bigcode/the-stack | train |
459bef60de09764ff1a32afa | train | class | class AlipayUserAntidVirtualQueryModel(object):
def __init__(self):
self._biz_scene = None
self._identification_factor_content = None
self._identification_factor_type = None
@property
def biz_scene(self):
return self._biz_scene
@biz_scene.setter
def biz_scene(self,... | class AlipayUserAntidVirtualQueryModel(object):
| def __init__(self):
self._biz_scene = None
self._identification_factor_content = None
self._identification_factor_type = None
@property
def biz_scene(self):
return self._biz_scene
@biz_scene.setter
def biz_scene(self, value):
self._biz_scene = value
@pro... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayUserAntidVirtualQueryModel(object):
| 39 | 141 | 470 | 11 | 28 | antopen/alipay-sdk-python-all | alipay/aop/api/domain/AlipayUserAntidVirtualQueryModel.py | Python | AlipayUserAntidVirtualQueryModel | AlipayUserAntidVirtualQueryModel | 8 | 68 | 8 | 9 | 15ef5d1729abadd22cc442b2c66fb97bf72bb720 | bigcode/the-stack | train |
ff09fad7c6955661b8e23f81 | train | function | @order_bp.route("/paid")
@login_required
@member_required
@verified_required
def order_paid():
"""
represents member paid order list page
"""
order_list = Order.query.filter_by(
paid_off=True,
id_member=current_user.id
).all()
return render_template("order/paidoff.html", order_... | @order_bp.route("/paid")
@login_required
@member_required
@verified_required
def order_paid():
| """
represents member paid order list page
"""
order_list = Order.query.filter_by(
paid_off=True,
id_member=current_user.id
).all()
return render_template("order/paidoff.html", order_list=order_list)
| _user, login_required
from help.app.auth import verified_required, member_required
from app.model import Order
order_bp = Blueprint(
"order",
__name__,
template_folder="view/"
)
@order_bp.route("/paid")
@login_required
@member_required
@verified_required
def order_paid():
| 64 | 64 | 77 | 22 | 42 | relarizky/flask-pre-order | controller/order/order.py | Python | order_paid | order_paid | 21 | 35 | 21 | 25 | c04577b917f7d4db6844411f89ee858c240f047a | bigcode/the-stack | train |
4b36004e5865c9ee248450c2 | train | function | @order_bp.route("/edit/<id>", methods=["POST"])
@login_required
@member_required
@verified_required
def order_edit(id: str):
"""
represents edit order processing url
"""
order = Order.query.get(id)
if order is None:
flash("error", "pemesanan tidak ditemukan")
return redirect(url_fo... | @order_bp.route("/edit/<id>", methods=["POST"])
@login_required
@member_required
@verified_required
def order_edit(id: str):
| """
represents edit order processing url
"""
order = Order.query.get(id)
if order is None:
flash("error", "pemesanan tidak ditemukan")
return redirect(url_for("index.index"))
proof = request.files.get("proof")
pieces = request.form.get("pieces")
address = request.form.... | (
"success",
"sukses order barang, silahkan edit info pembayaran"
)
return redirect(url_for("order.order_unpaid"))
@order_bp.route("/edit/<id>", methods=["POST"])
@login_required
@member_required
@verified_required
def order_edit(id: str):
| 63 | 64 | 180 | 31 | 32 | relarizky/flask-pre-order | controller/order/order.py | Python | order_edit | order_edit | 83 | 112 | 83 | 87 | 8144e64e816a0031953546392001a0708bcb0ad3 | bigcode/the-stack | train |
a50722a983ad3ba735077a08 | train | function | @order_bp.route("/delete/<id>")
@login_required
@member_required
@verified_required
def order_delete(id: str):
"""
represents delete order processing url
"""
order = Order.query.get(id)
if order is None:
flash("error", "pemesanan tidak ditemukan")
else:
order.delete()
f... | @order_bp.route("/delete/<id>")
@login_required
@member_required
@verified_required
def order_delete(id: str):
| """
represents delete order processing url
"""
order = Order.query.get(id)
if order is None:
flash("error", "pemesanan tidak ditemukan")
else:
order.delete()
flash("success", "sukses delete pemesanan")
return redirect(url_for("order.order_unpaid"))
| ", Error.__str__())
else:
flash("success", "sukses mengubah info pemesanan")
return redirect(url_for("order.order_unpaid"))
@order_bp.route("/delete/<id>")
@login_required
@member_required
@verified_required
def order_delete(id: str):
| 63 | 64 | 96 | 27 | 36 | relarizky/flask-pre-order | controller/order/order.py | Python | order_delete | order_delete | 115 | 132 | 115 | 119 | 1e4db9fcd5bd0680b6bdb6d1e136c8012eaf0d43 | bigcode/the-stack | train |
5e6501febe79c9c6452f8e48 | train | function | @order_bp.route("/process/<id>", methods=["POST"])
@login_required
@member_required
@verified_required
def order_process(id: str):
"""
represents order processing url
"""
pieces = request.form.get("pieces")
address = request.form.get("address")
try:
order = Order(pieces, address)
... | @order_bp.route("/process/<id>", methods=["POST"])
@login_required
@member_required
@verified_required
def order_process(id: str):
| """
represents order processing url
"""
pieces = request.form.get("pieces")
address = request.form.get("address")
try:
order = Order(pieces, address)
order.set_object_member(current_user.id)
order.set_object_product(id)
order.save()
except Exception as Error... | paid_off=False,
id_member=current_user.id
).all()
return render_template("order/unpaidoff.html", order_list=order_list)
@order_bp.route("/process/<id>", methods=["POST"])
@login_required
@member_required
@verified_required
def order_process(id: str):
| 64 | 64 | 144 | 31 | 33 | relarizky/flask-pre-order | controller/order/order.py | Python | order_process | order_process | 55 | 80 | 55 | 59 | 217dd3ec93355fefa3ee5df6f88fd44cad92af00 | bigcode/the-stack | train |
d8fc0a4d734420f082a07d15 | train | function | @order_bp.route("/unpaid")
@login_required
@member_required
@verified_required
def order_unpaid():
"""
represents member unpaid order list page
"""
order_list = Order.query.filter_by(
paid_off=False,
id_member=current_user.id
).all()
return render_template("order/unpaidoff.html... | @order_bp.route("/unpaid")
@login_required
@member_required
@verified_required
def order_unpaid():
| """
represents member unpaid order list page
"""
order_list = Order.query.filter_by(
paid_off=False,
id_member=current_user.id
).all()
return render_template("order/unpaidoff.html", order_list=order_list)
| = Order.query.filter_by(
paid_off=True,
id_member=current_user.id
).all()
return render_template("order/paidoff.html", order_list=order_list)
@order_bp.route("/unpaid")
@login_required
@member_required
@verified_required
def order_unpaid():
| 64 | 64 | 79 | 24 | 40 | relarizky/flask-pre-order | controller/order/order.py | Python | order_unpaid | order_unpaid | 38 | 52 | 38 | 42 | 31c04cf04843b9232bf6f1eab4a8324622126710 | bigcode/the-stack | train |
866f51ca9a17807c604e3661 | train | function | def main():
import logging
parser = argparse.ArgumentParser()
parser.add_argument("--env", type=str, default="CartPole-v0")
parser.add_argument("--seed", type=int, default=0, help="Random seed [0, 2 ** 32)")
parser.add_argument("--gpu", type=int, default=0)
parser.add_argument(
"--outdi... | def main():
| import logging
parser = argparse.ArgumentParser()
parser.add_argument("--env", type=str, default="CartPole-v0")
parser.add_argument("--seed", type=int, default=0, help="Random seed [0, 2 ** 32)")
parser.add_argument("--gpu", type=int, default=0)
parser.add_argument(
"--outdir",
... | """An example of training a REINFORCE agent against OpenAI Gym envs.
This script is an example of training a REINFORCE agent against OpenAI Gym
envs. Both discrete and continuous action spaces are supported.
To solve CartPole-v0, run:
python train_reinforce_gym.py
To solve InvertedPendulum-v1, run:
python tr... | 153 | 256 | 1,006 | 3 | 149 | ummavi/pfrl-1 | examples/gym/train_reinforce_gym.py | Python | main | main | 24 | 147 | 24 | 24 | 160309a3133168ff76723226df75ac1209d7d9c3 | bigcode/the-stack | train |
c0c82762bf19987a7d3e2679 | train | class | class AcceptBlockTest(BitcoinTestFramework):
def add_options(self, parser):
parser.add_option("--testbinary", dest="testbinary",
default=os.getenv("BROCOIND", "brocoind"),
help="brocoind binary to test")
def set_test_params(self):
self.setup_c... | class AcceptBlockTest(BitcoinTestFramework):
| def add_options(self, parser):
parser.add_option("--testbinary", dest="testbinary",
default=os.getenv("BROCOIND", "brocoind"),
help="brocoind binary to test")
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2
... | last block (too far ahead in height).
5. Send a duplicate of the block in #3 to Node0.
Node0 should not process the block because it is unrequested, and stay on
the shorter chain.
6. Send Node0 an inv for the height 3 block produced in #4 above.
Node0 should figure out that Node0 has the missing height 2 bl... | 256 | 256 | 2,961 | 9 | 246 | brocoinofficial/brocoinofficial | test/functional/p2p-acceptblock.py | Python | AcceptBlockTest | AcceptBlockTest | 60 | 326 | 60 | 60 | bb189e52a5537d9ec60314075dd0931685bcad10 | bigcode/the-stack | train |
346672e016481db89e993799 | train | class | class ClipTest(test.TestCase):
def DISABLED_testClipByValueGradient(self):
inputs = constant_op.constant([1.0, 2.0, 3.0, 4.0], dtype=dtypes.float32)
outputs_1 = clip_ops.clip_by_value(inputs, 0.5, 3.5)
min_val = constant_op.constant([0.5, 0.5, 0.5, 0.5], dtype=dtypes.float32)
max_val = constant_op.co... | class ClipTest(test.TestCase):
| def DISABLED_testClipByValueGradient(self):
inputs = constant_op.constant([1.0, 2.0, 3.0, 4.0], dtype=dtypes.float32)
outputs_1 = clip_ops.clip_by_value(inputs, 0.5, 3.5)
min_val = constant_op.constant([0.5, 0.5, 0.5, 0.5], dtype=dtypes.float32)
max_val = constant_op.constant([3.5, 3.5, 3.5, 3.5], dty... | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 249 | 256 | 5,773 | 7 | 241 | yanzhiwei1990/tensorflow | tensorflow/python/kernel_tests/clip_ops_test.py | Python | ClipTest | ClipTest | 34 | 451 | 34 | 35 | cfd07225c9fe78c57cbf8cb7108ec03a3acfd73c | bigcode/the-stack | train |
16cfd2fed23d270ccffa7c02 | train | class | class TestRuleSchemaField(unittest.TestCase):
"""RuleSchemaField unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testRuleSchemaField(self):
"""Test RuleSchemaField"""
# FIXME: construct object with mandatory attributes with example values
... | class TestRuleSchemaField(unittest.TestCase):
| """RuleSchemaField unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testRuleSchemaField(self):
"""Test RuleSchemaField"""
# FIXME: construct object with mandatory attributes with example values
# model = swagger_client.models.rule_schema_fi... | by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_client
from swagger_client.models.rule_schema_field import RuleSchemaField # noqa: E501
from swagger_client.rest import ApiException
class TestRuleSchemaField(unittest.TestCase):
| 64 | 64 | 89 | 9 | 54 | dmontagner/healthbot-py-client | docs/jnpr_healthbot_swagger/test/test_rule_schema_field.py | Python | TestRuleSchemaField | TestRuleSchemaField | 23 | 36 | 23 | 23 | c55232bd55327d29d2ce0a9e407d3d5f8e027443 | bigcode/the-stack | train |
9771a8905f277a9641593d3b | train | function | def main():
get_env('INFRABOX_DATABASE_DB')
get_env('INFRABOX_DATABASE_USER')
get_env('INFRABOX_DATABASE_PASSWORD')
get_env('INFRABOX_DATABASE_HOST')
get_env('INFRABOX_DATABASE_PORT')
gc = GC()
gc.run()
| def main():
| get_env('INFRABOX_DATABASE_DB')
get_env('INFRABOX_DATABASE_USER')
get_env('INFRABOX_DATABASE_PASSWORD')
get_env('INFRABOX_DATABASE_HOST')
get_env('INFRABOX_DATABASE_PORT')
gc = GC()
gc.run()
| ', len(r))
for j in r:
logger.info('Deleting cache %s/%s', j['project_id'], j['name'])
key = 'project_%s_job_%s.tar.snappy' % (j['project_id'], j['name'])
storage.delete_cache(key)
def main():
| 64 | 64 | 67 | 3 | 61 | sap-coutantm/InfraBox | src/gc/gc.py | Python | main | main | 154 | 162 | 154 | 154 | 08fe04a7376e4291a20a8734ca6df4f09fc33838 | bigcode/the-stack | train |
677124e3218720c97890ce0a | train | class | class GC(object):
def run(self):
# TODO: Delete storage objects: uploads, outputs
# TODO: Delete images from registry
while True:
db = dbpool.get()
try:
logger.info('Starting next GC run')
self._gc(db)
logger.info('Fini... | class GC(object):
| def run(self):
# TODO: Delete storage objects: uploads, outputs
# TODO: Delete images from registry
while True:
db = dbpool.get()
try:
logger.info('Starting next GC run')
self._gc(db)
logger.info('Finished GC run')
... | import time
from pyinfraboxutils import get_logger, get_env
from pyinfraboxutils import dbpool
from pyinfraboxutils.storage import storage
logger = get_logger("gc")
class GC(object):
| 47 | 256 | 947 | 4 | 43 | sap-coutantm/InfraBox | src/gc/gc.py | Python | GC | GC | 9 | 152 | 9 | 9 | 73f37ddf99247c90d5b3026756c427bf151ac0b1 | bigcode/the-stack | train |
968538228bf02fe0f900db30 | train | class | class TestPriorLoad(unittest.TestCase):
def test_load(self):
RestrictedPrior(
filename="../studies/injection_study/gw151226_like_injection/followup_pt1/followup_pt1.prior",
mcmc_n=5
)
| class TestPriorLoad(unittest.TestCase):
| def test_load(self):
RestrictedPrior(
filename="../studies/injection_study/gw151226_like_injection/followup_pt1/followup_pt1.prior",
mcmc_n=5
)
| from deep_gw_pe_followup.restricted_prior import RestrictedPrior
import unittest
class TestPriorLoad(unittest.TestCase):
| 25 | 64 | 57 | 8 | 16 | avivajpeyi/gw_pe_judge | tests/load_pri.py | Python | TestPriorLoad | TestPriorLoad | 6 | 11 | 6 | 6 | d6c56679540af66fc127787fa9eb9321962f1144 | bigcode/the-stack | train |
576dc93e5e70c49485d4331f | train | function | def remove_docstrings(source):
"""
Returns 'source' minus docstrings.
"""
io_obj = StringIO(source)
out = ""
prev_toktype = tokenize.INDENT
last_lineno = -1
last_col = 0
for tok in tokenize.generate_tokens(io_obj.readline):
token_type = tok[0]
token_string = tok[1]
... | def remove_docstrings(source):
| """
Returns 'source' minus docstrings.
"""
io_obj = StringIO(source)
out = ""
prev_toktype = tokenize.INDENT
last_lineno = -1
last_col = 0
for tok in tokenize.generate_tokens(io_obj.readline):
token_type = tok[0]
token_string = tok[1]
start_line, start_col = t... | """
A collection of functions for modifying the source code
"""
import os
import re
import tokenize
import importlib
import inspect
import sqlite3
import subprocess
import tempfile
from six import StringIO, PY3
from redbaron import RedBaron
sqlite_file = 'feature_docs_unit_test_db.sqlite' # name of the sqlite da... | 100 | 147 | 491 | 6 | 93 | hwangjt/blue | openmdao/docs/_utils/docutil.py | Python | remove_docstrings | remove_docstrings | 22 | 73 | 22 | 22 | d24408426400765bb4d99e6c32ee07ead84188bf | bigcode/the-stack | train |
c79cc165724623b38d07fcf0 | train | function | def get_unit_test_source_and_run_outputs_in_out(method_path):
'''
1. Get the source code for a unit test method
2. Replace the asserts with prints -> source_minus_docstrings_with_prints_cleaned
3. Split source_minus_docstrings_with_prints_cleaned up into groups of "In" blocks -> input_blocks
4. Inse... | def get_unit_test_source_and_run_outputs_in_out(method_path):
| '''
1. Get the source code for a unit test method
2. Replace the asserts with prints -> source_minus_docstrings_with_prints_cleaned
3. Split source_minus_docstrings_with_prints_cleaned up into groups of "In" blocks -> input_blocks
4. Insert extra print statements into source_minus_docstrings_with_pr... | _blocks = []
current_in_block = ''
for in_block, out_block in zip(input_blocks, output_blocks):
if current_in_block and not current_in_block.endswith('\n'):
current_in_block += '\n'
current_in_block += in_block
if out_block:
new_input_blocks.append(current_in_bloc... | 256 | 256 | 2,028 | 13 | 242 | hwangjt/blue | openmdao/docs/_utils/docutil.py | Python | get_unit_test_source_and_run_outputs_in_out | get_unit_test_source_and_run_outputs_in_out | 554 | 745 | 554 | 554 | 81c5cc383f85441323f305b8e2edee3ce66ceb57 | bigcode/the-stack | train |
42fd58c514807c10c50e5d6d | train | function | def get_lines_before_test_cases(code):
'''Only get the top part of the test file including imports and other class definitions
Need this so the unit test has everything it needs to run
'''
top_code = ''
rb = RedBaron(code)
# Keep looping through the lines of code until encountering
# the... | def get_lines_before_test_cases(code):
| '''Only get the top part of the test file including imports and other class definitions
Need this so the unit test has everything it needs to run
'''
top_code = ''
rb = RedBaron(code)
# Keep looping through the lines of code until encountering
# the start of a definition of a unittest.Te... | rb.findAll("DefNode")[0] # Look for the 'def' node. Should only be one!
def_node.value.decrease_indentation(8) # so that the code is all the way to the left
return def_node.value.dumps()
def get_lines_before_test_cases(code):
| 64 | 64 | 199 | 8 | 56 | hwangjt/blue | openmdao/docs/_utils/docutil.py | Python | get_lines_before_test_cases | get_lines_before_test_cases | 153 | 174 | 153 | 153 | f6ec232a04b1e44bd2efdfde5276ea7ae967c98d | bigcode/the-stack | train |
4856356527bed0f379fa6338 | train | function | def remove_initial_empty_lines_from_source(source):
'''Some initial empty lines were added to keep RedBaron happy.
Need to strip these out before we pass the source code to the
directive for including source code into feature doc files'''
idx = re.search(r'\S', source, re.MULTILINE).start()
return ... | def remove_initial_empty_lines_from_source(source):
| '''Some initial empty lines were added to keep RedBaron happy.
Need to strip these out before we pass the source code to the
directive for including source code into feature doc files'''
idx = re.search(r'\S', source, re.MULTILINE).start()
return source[idx:]
| the definition of a TestCase, since that class might be needed in
# a test
if 'unittest.TestCase' in r.inherit_from.dumps():
break
top_code += r.dumps() + '\n'
return top_code
def remove_initial_empty_lines_from_source(source):
| 64 | 64 | 73 | 9 | 54 | hwangjt/blue | openmdao/docs/_utils/docutil.py | Python | remove_initial_empty_lines_from_source | remove_initial_empty_lines_from_source | 177 | 183 | 177 | 177 | 7f568da8ef3775f8bb20df074dba89b7100bf3dc | bigcode/the-stack | train |
711c0a1841350cb84615fa3e | train | function | def remove_redbaron_node(node, index):
'''Utility function for removing a node using RedBaron.
RedBaron has some problems with modifying code lines that run across
multiple lines. ( It is mentioned somewhere online but cannot seem to
find it now. )
RedBaron throws an Exception but when you check, ... | def remove_redbaron_node(node, index):
| '''Utility function for removing a node using RedBaron.
RedBaron has some problems with modifying code lines that run across
multiple lines. ( It is mentioned somewhere online but cannot seem to
find it now. )
RedBaron throws an Exception but when you check, it seems like it does
what you aske... | # "The spaces before this string do not get a token"
# ]
else:
out += token_string
prev_toktype = token_type
last_col = end_col
last_lineno = end_line
return out
def remove_redbaron_node(node, index):
| 64 | 64 | 153 | 10 | 53 | hwangjt/blue | openmdao/docs/_utils/docutil.py | Python | remove_redbaron_node | remove_redbaron_node | 76 | 93 | 76 | 76 | 70d8e92417e9e96d055c3e1fa963cc3e06ef03bc | bigcode/the-stack | train |
8507178c056e4034c126c1ca | train | function | def remove_leading_trailing_whitespace_lines(src):
lines = src.splitlines()
non_whitespace_lines = []
for i, l in enumerate( lines ):
if l and not l.isspace():
non_whitespace_lines.append(i)
imin = min(non_whitespace_lines)
imax = max(non_whitespace_lines)
return '\n'.join(... | def remove_leading_trailing_whitespace_lines(src):
| lines = src.splitlines()
non_whitespace_lines = []
for i, l in enumerate( lines ):
if l and not l.isspace():
non_whitespace_lines.append(i)
imin = min(non_whitespace_lines)
imax = max(non_whitespace_lines)
return '\n'.join(lines[imin: imax+1])
| _run_path)
if PY3:
run_outputs = "".join(map(chr, run_outputs)) # in Python 3, run_outputs is of type bytes!
return source_minus_docstrings_with_prints_cleaned, run_outputs, skipped, failed
def remove_leading_trailing_whitespace_lines(src):
| 64 | 64 | 87 | 11 | 52 | hwangjt/blue | openmdao/docs/_utils/docutil.py | Python | remove_leading_trailing_whitespace_lines | remove_leading_trailing_whitespace_lines | 442 | 452 | 442 | 442 | 7204e975639a3278da084ae1b88c5132dcc31de2 | bigcode/the-stack | train |
0abb080b07a5029b9059e849 | train | function | def get_test_source_code_for_feature(feature_name):
'''The function to be called from the custom Sphinx directive code
that includes relevant unit test code(s).
It gets the test source from the unit tests that have been
marked to indicate that they are associated with the "feature_name"'''
# get t... | def get_test_source_code_for_feature(feature_name):
| '''The function to be called from the custom Sphinx directive code
that includes relevant unit test code(s).
It gets the test source from the unit tests that have been
marked to indicate that they are associated with the "feature_name"'''
# get the:
#
# 1. title of the test
# 2. te... |
if remove_docstring:
source = remove_docstrings(source)
return source
"""
Definition of function to be called by the showunittestexamples directive
"""
sqlite_file = 'feature_docs_unit_test_db.sqlite' # name of the sqlite database file
table_name = 'feature_unit_tests' # name of the table to b... | 83 | 83 | 279 | 10 | 72 | hwangjt/blue | openmdao/docs/_utils/docutil.py | Python | get_test_source_code_for_feature | get_test_source_code_for_feature | 247 | 278 | 247 | 247 | 7f4bba0f1b8604f37371e36841b1ab3833a11241 | bigcode/the-stack | train |
e18697448a286da4d023453a | train | function | def replace_asserts_with_prints(source_code):
'''Using RedBaron, replace some assert calls with
print statements that print the actual value given in the asserts.
Depending on the calls, the actual value can be the first or second
argument.'''
rb = RedBaron(source_code) # convert to RedBaron inte... | def replace_asserts_with_prints(source_code):
| '''Using RedBaron, replace some assert calls with
print statements that print the actual value given in the asserts.
Depending on the calls, the actual value can be the first or second
argument.'''
rb = RedBaron(source_code) # convert to RedBaron internal structure
for assert_type in ['asser... | '''Utility function for removing a node using RedBaron.
RedBaron has some problems with modifying code lines that run across
multiple lines. ( It is mentioned somewhere online but cannot seem to
find it now. )
RedBaron throws an Exception but when you check, it seems like it does
what you asked i... | 152 | 152 | 508 | 10 | 141 | hwangjt/blue | openmdao/docs/_utils/docutil.py | Python | replace_asserts_with_prints | replace_asserts_with_prints | 96 | 136 | 96 | 96 | f848c21a73ad362503860ccea57ee51b0b1fa99f | bigcode/the-stack | train |
92f081a523e61cdc5bda1518 | train | function | def remove_raise_skip_tests(source):
'''
Remove from the code any raise unittest.SkipTest lines since we don't want those in
what the user sees
'''
rb = RedBaron(source)
raise_nodes = rb.findAll("RaiseNode")
for rn in raise_nodes:
# only the raise for SkipTest
if rn.val... | def remove_raise_skip_tests(source):
| '''
Remove from the code any raise unittest.SkipTest lines since we don't want those in
what the user sees
'''
rb = RedBaron(source)
raise_nodes = rb.findAll("RaiseNode")
for rn in raise_nodes:
# only the raise for SkipTest
if rn.value[:2].dumps() == 'unittestSkipTest':... | .value[1].value.to_python())
elif def_nodes[0].decorators[0].value.dumps() == 'unittest.skip':
return (None, def_nodes[0].decorators[0].call.value[0].value.to_python())
return None
def remove_raise_skip_tests(source):
| 64 | 64 | 100 | 7 | 56 | hwangjt/blue | openmdao/docs/_utils/docutil.py | Python | remove_raise_skip_tests | remove_raise_skip_tests | 302 | 313 | 302 | 302 | bc2d0063a8284af6ffd92ba5b25931678fa21c27 | bigcode/the-stack | train |
fc128c54f55918dcab7ab92f | train | function | def extract_output_blocks(run_output):
'''
'''
output_blocks = []
# Look for start and end lines that look like this:
# <<<<<4
# >>>>>4
output_block = []
for line in run_output.splitlines():
if line.startswith('>>>>>'):
output_blocks.append('\n'.join(output_block))... | def extract_output_blocks(run_output):
| '''
'''
output_blocks = []
# Look for start and end lines that look like this:
# <<<<<4
# >>>>>4
output_block = []
for line in run_output.splitlines():
if line.startswith('>>>>>'):
output_blocks.append('\n'.join(output_block))
output_block = []
... | )
current_in_block = ''
# if there was no output, return the one input block and empty output block
if current_in_block:
new_input_blocks.append(current_in_block)
new_output_blocks.append('')
return new_input_blocks, new_output_blocks
def extract_output_blocks(run_output):
| 64 | 64 | 111 | 7 | 56 | hwangjt/blue | openmdao/docs/_utils/docutil.py | Python | extract_output_blocks | extract_output_blocks | 534 | 552 | 534 | 534 | fef18625918d969cb198193c374d99a7854ad4bf | bigcode/the-stack | train |
3ed56e7e8e857c57512a61ca | train | function | def get_source_code_of_class_or_method(class_or_method_path, remove_docstring=True):
"""
Return source code as a text string.
Parameters
----------
class_or_method_path : str
Package path to the class or function.
remove_docstring : bool
Set to False to keep docstrings in the te... | def get_source_code_of_class_or_method(class_or_method_path, remove_docstring=True):
| """
Return source code as a text string.
Parameters
----------
class_or_method_path : str
Package path to the class or function.
remove_docstring : bool
Set to False to keep docstrings in the text.
"""
# First, assume module path since we want to support loading a full ... | strip these out before we pass the source code to the
directive for including source code into feature doc files'''
idx = re.search(r'\S', source, re.MULTILINE).start()
return source[idx:]
"""
Function that returns the source code of a method or class.
The docstrings are stripped from the code
"""
# py... | 96 | 96 | 321 | 18 | 77 | hwangjt/blue | openmdao/docs/_utils/docutil.py | Python | get_source_code_of_class_or_method | get_source_code_of_class_or_method | 194 | 236 | 194 | 194 | 4b8dd12639cc5630e25316d3b0e47962e1b67648 | bigcode/the-stack | train |
6e5e9800e09dadcb356956c4 | train | function | def get_unit_test_source_and_run_outputs(method_path):
'''
Get the source code for a unit test method, run the test,
and capture the output of the run
'''
module_path = '.'.join(method_path.split('.')[:-2])
class_name = method_path.split('.')[-2]
method_name = method_path.split('.')[-1]
... | def get_unit_test_source_and_run_outputs(method_path):
| '''
Get the source code for a unit test method, run the test,
and capture the output of the run
'''
module_path = '.'.join(method_path.split('.')[:-2])
class_name = method_path.split('.')[-2]
method_name = method_path.split('.')[-1]
test_module = importlib.import_module(module_path)
... | (source)
def_nodes = rb.findAll("DefNode", name=method_name)
if def_nodes:
if def_nodes[0].decorators:
if def_nodes[0].decorators[0].value.dumps() == 'unittest.skipUnless':
return (def_nodes[0].decorators[0].call.value[0].dumps(),
def_nodes[0].decorato... | 256 | 256 | 1,394 | 11 | 245 | hwangjt/blue | openmdao/docs/_utils/docutil.py | Python | get_unit_test_source_and_run_outputs | get_unit_test_source_and_run_outputs | 316 | 440 | 316 | 316 | 3b92fcbfdc2d3ba18239f22220157d6473bf0389 | bigcode/the-stack | train |
ff7cc173549005f1c4eca3e5 | train | function | def insert_output_start_stop_indicators(src):
'''
'''
rb = RedBaron(src)
src_with_out_start_stop_indicators = []
input_block_number = 0
for r in rb:
line = r.dumps()
# not sure why some lines from RedBaron do not have newlines
if not line.endswith('\n'):
line... | def insert_output_start_stop_indicators(src):
| '''
'''
rb = RedBaron(src)
src_with_out_start_stop_indicators = []
input_block_number = 0
for r in rb:
line = r.dumps()
# not sure why some lines from RedBaron do not have newlines
if not line.endswith('\n'):
line += '\n'
if r.type == 'print':
... | make an input code block
in_code_block = ''.join(in_code_block)
in_code_block = remove_leading_trailing_whitespace_lines(in_code_block)
in_code_blocks.append(in_code_block)
in_code_block = []
if in_code_block: # If anything left over
in_code_blocks.append(''... | 88 | 88 | 294 | 9 | 78 | hwangjt/blue | openmdao/docs/_utils/docutil.py | Python | insert_output_start_stop_indicators | insert_output_start_stop_indicators | 483 | 508 | 483 | 483 | 748765aaf70a9419c928e5dc75f4974c17cc7e32 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.