Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|>
def parse_linkauth(data):
return proto.EosActionLinkAuth(
account=name_to_number(data['account']),
code=name_to_number(data['code']),
type=name_to_number(data['type']),
requirement=name_to_number(data['requirement'])
)
def parse_unlinkauth(data):
return proto.EosActionUnlinkAuth(
account=name_to_number(data['account']),
code=name_to_number(data['code']),
type=name_to_number(data['type'])
)
def parse_authorization(data):
keys = []
for key in data['keys']:
if 'key' in key:
_t, _k = public_key_to_buffer(key['key'])
keys.append(
proto.EosAuthorizationKey(
type=_t,
key=_k,
weight=int(key['weight'])
)
)
elif 'address_n' in key:
<|code_end|>
with the help of current file imports:
import hashlib
import binascii
import struct
from datetime import datetime
from .tools import b58decode, b58encode, parse_path, int_to_big_endian
from . import messages_eos_pb2 as proto
and context from other files:
# Path: keepkeylib/tools.py
# def b58decode(v, length):
# """ decode v into a string of len bytes."""
# long_value = 0
# for (i, c) in enumerate(v[::-1]):
# long_value += __b58chars.find(c) * (__b58base ** i)
#
# result = b''
# while long_value >= 256:
# div, mod = divmod(long_value, 256)
# result = struct.pack('B', mod) + result
# long_value = div
# result = struct.pack('B', long_value) + result
#
# nPad = 0
# for c in v:
# if c == __b58chars[0]:
# nPad += 1
# else:
# break
#
# result = b'\x00' * nPad + result
# if length is not None and len(result) != length:
# return None
#
# return result
#
# def b58encode(v):
# """ encode v, which is a string of bytes, to base58."""
#
# long_value = 0
# for c in iterbytes(v):
# long_value = long_value * 256 + c
#
# result = ''
# while long_value >= __b58base:
# div, mod = divmod(long_value, __b58base)
# result = __b58chars[mod] + result
# long_value = div
# result = __b58chars[long_value] + result
#
# # Bitcoin does a little leading-zero-compression:
# # leading 0-bytes in the input become leading-1s
# nPad = 0
# for c in iterbytes(v):
# if c == 0:
# nPad += 1
# else:
# break
#
# return (__b58chars[0] * nPad) + result
#
# def parse_path(nstr):
# """
# Convert BIP32 path string to list of uint32 integers with hardened flags.
# Several conventions are supported to set the hardened flag: -1, 1', 1h
# e.g.: "0/1h/1" -> [0, 0x80000001, 1]
# :param nstr: path string
# :return: list of integers
# """
# if not nstr:
# return []
#
# n = nstr.split('/')
#
# # m/a/b/c => a/b/c
# if n[0] == 'm':
# n = n[1:]
#
# # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c
# #if n[0] in slip44:
# # coin_id = slip44[n[0]]
# # n[0:1] = ['44h', '{}h'.format(coin_id)]
#
# def str_to_harden(x):
# if x.startswith('-'):
# return H_(abs(int(x)))
# elif x.endswith(('h', "'")):
# return H_(int(x[:-1]))
# else:
# return int(x)
#
# try:
# return list(str_to_harden(x) for x in n)
# except Exception:
# raise ValueError('Invalid BIP32 path', nstr)
#
# def int_to_big_endian(value):
# import struct
#
# res = b''
# while 0 < value:
# res = struct.pack("B", value & 0xff) + res
# value = value >> 8
#
# return res
, which may contain function names, class names, or code. Output only the next line. | address_n=parse_path(key['address_n']) |
Given the following code snippet before the placeholder: <|code_start|> self.setup_mnemonic_nopin_nopassphrase()
# tx: d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882
# input 0: 0.0039 BTC
inp1 = proto_types.TxInputType(address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e
# amount=390000,
prev_hash=binascii.unhexlify('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882'),
prev_index=0,
)
out1 = proto_types.TxOutputType(address='1MJ2tj2ThBE62zXbBYA5ZaN3fdve5CPAz1',
amount=400000,
script_type=proto_types.PAYTOADDRESS,
)
with self.client:
self.client.set_expected_responses([
proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)),
proto.TxRequest(request_type=proto_types.TXMETA, details=proto_types.TxRequestDetailsType(tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))),
proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))),
proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))),
proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))),
proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)),
proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput),
proto.Failure(code=proto_types.Failure_NotEnoughFunds)
])
try:
self.client.sign_tx('Bitcoin', [inp1, ], [out1, ])
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import common
import binascii
import itertools
import keepkeylib.messages_pb2 as proto
import keepkeylib.types_pb2 as proto_types
from keepkeylib.client import CallException
from keepkeylib import tx_api
and context including class names, function names, and sometimes code from other files:
# Path: keepkeylib/client.py
# class CallException(Exception):
# def __init__(self, code, message):
# super(CallException, self).__init__()
# self.args = [code, message]
#
# Path: keepkeylib/tx_api.py
# def pack_varint(n):
# def __init__(self, network, url):
# def fetch_json(self, url, resource, resourceid):
# def get_tx(self, txhash):
# def __init__(self, network, url, zcash=None):
# def get_tx(self, txhash):
# def get_raw_tx(self, txhash):
# class TxApi(object):
# class TxApiInsight(TxApi):
. Output only the next line. | except CallException as e: |
Predict the next line after this snippet: <|code_start|> proto.TxRequest(request_type=proto_types.TXFINISHED),
])
(signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, ])
# Accepted by network: tx fd79435246dee76b2f159d2db08032d666c95adc544de64c8c49f474df4a7fee
self.assertEqual(binascii.hexlify(serialized_tx), '010000000182488650ef25a58fef6788bd71b8212038d7f2bbe4750bc7bcb44701e85ef6d5000000006b4830450221009a0b7be0d4ed3146ee262b42202841834698bb3ee39c24e7437df208b8b7077102202b79ab1e7736219387dffe8d615bbdba87e11477104b867ef47afed1a5ede7810121023230848585885f63803a0a8aecdd6538792d5c539215c91698e315bf0253b43dffffffff0160cc0500000000001976a914de9b2a8da088824e8fe51debea566617d851537888ac00000000')
def test_testnet_one_two_fee(self):
self.setup_mnemonic_nopin_nopassphrase()
# tx: 6f90f3c7cbec2258b0971056ef3fe34128dbde30daa9c0639a898f9977299d54
# input 1: 10.00000000 BTC
inp1 = proto_types.TxInputType(address_n=[0], # mirio8q3gtv7fhdnmb3TpZ4EuafdzSs7zL
# amount=1000000000,
prev_hash=binascii.unhexlify('6f90f3c7cbec2258b0971056ef3fe34128dbde30daa9c0639a898f9977299d54'),
prev_index=1,
)
out1 = proto_types.TxOutputType(address='mfiGQVPcRcaEvQPYDErR34DcCovtxYvUUV',
amount=1000000000 - 500000000 - 10000000,
script_type=proto_types.PAYTOADDRESS,
)
out2 = proto_types.TxOutputType(address_n=[2],
amount=500000000,
script_type=proto_types.PAYTOADDRESS,
)
with self.client:
<|code_end|>
using the current file's imports:
import unittest
import common
import binascii
import itertools
import keepkeylib.messages_pb2 as proto
import keepkeylib.types_pb2 as proto_types
from keepkeylib.client import CallException
from keepkeylib import tx_api
and any relevant context from other files:
# Path: keepkeylib/client.py
# class CallException(Exception):
# def __init__(self, code, message):
# super(CallException, self).__init__()
# self.args = [code, message]
#
# Path: keepkeylib/tx_api.py
# def pack_varint(n):
# def __init__(self, network, url):
# def fetch_json(self, url, resource, resourceid):
# def get_tx(self, txhash):
# def __init__(self, network, url, zcash=None):
# def get_tx(self, txhash):
# def get_raw_tx(self, txhash):
# class TxApi(object):
# class TxApiInsight(TxApi):
. Output only the next line. | self.client.set_tx_api(tx_api.TxApiTestnet) |
Given the code snippet: <|code_start|>
DEFAULT_BIP32_PATH = "m/44h/931h/0h/0/0"
class TestMsgThorChainGetAddress(common.KeepKeyTest):
def test_thorchain_get_address(self):
self.requires_firmware("7.0.2")
self.setup_mnemonic_nopin_nopassphrase()
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import common
import keepkeylib.messages_pb2 as proto
import keepkeylib.types_pb2 as proto_types
import keepkeylib.messages_thorchain_pb2 as thorchain_proto
from keepkeylib.client import CallException
from keepkeylib.tools import parse_path
and context (functions, classes, or occasionally code) from other files:
# Path: keepkeylib/client.py
# class CallException(Exception):
# def __init__(self, code, message):
# super(CallException, self).__init__()
# self.args = [code, message]
#
# Path: keepkeylib/tools.py
# def parse_path(nstr):
# """
# Convert BIP32 path string to list of uint32 integers with hardened flags.
# Several conventions are supported to set the hardened flag: -1, 1', 1h
# e.g.: "0/1h/1" -> [0, 0x80000001, 1]
# :param nstr: path string
# :return: list of integers
# """
# if not nstr:
# return []
#
# n = nstr.split('/')
#
# # m/a/b/c => a/b/c
# if n[0] == 'm':
# n = n[1:]
#
# # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c
# #if n[0] in slip44:
# # coin_id = slip44[n[0]]
# # n[0:1] = ['44h', '{}h'.format(coin_id)]
#
# def str_to_harden(x):
# if x.startswith('-'):
# return H_(abs(int(x)))
# elif x.endswith(('h', "'")):
# return H_(int(x[:-1]))
# else:
# return int(x)
#
# try:
# return list(str_to_harden(x) for x in n)
# except Exception:
# raise ValueError('Invalid BIP32 path', nstr)
. Output only the next line. | address = self.client.thorchain_get_address(parse_path(DEFAULT_BIP32_PATH), testnet=True) |
Given snippet: <|code_start|># This file is part of the Trezor project.
#
# Copyright (C) 2012-2018 SatoshiLabs and contributors
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the License along with this library.
# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
# https://blockbook-test.groestlcoin.org/tx/9b5c4859a8a31e69788cb4402812bb28f14ad71cbd8c60b09903478bc56f79a3
class TestMsgSigntxNativeSegwitGRS(KeepKeyTest):
def test_send_native(self):
self.setup_mnemonic_allallall()
self.client.set_tx_api(TxApiGroestlcoinTestnet)
inp1 = proto_types.TxInputType(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import common
import unittest
from binascii import hexlify, unhexlify
from keepkeylib import ckd_public as bip32
from common import KeepKeyTest
from keepkeylib import messages_pb2 as proto
from keepkeylib import types_pb2 as proto_types
from keepkeylib.client import CallException
from keepkeylib.tools import parse_path
from keepkeylib.tx_api import TxApiGroestlcoinTestnet
and context:
# Path: keepkeylib/ckd_public.py
# PRIME_DERIVATION_FLAG = 0x80000000
# I64 = hmac.HMAC(key=node.chain_code, msg=data, digestmod=hashlib.sha512).digest()
# def point_to_pubkey(point):
# def sec_to_public_pair(pubkey):
# def public_pair_for_x(generator, x, is_even):
# def is_prime(n):
# def fingerprint(pubkey):
# def get_address(public_node, address_type):
# def public_ckd(public_node, n):
# def get_subnode(node, i):
# def serialize(node, version=0x0488B21E):
# def deserialize(xpub):
#
# Path: keepkeylib/client.py
# class CallException(Exception):
# def __init__(self, code, message):
# super(CallException, self).__init__()
# self.args = [code, message]
#
# Path: keepkeylib/tools.py
# def parse_path(nstr):
# """
# Convert BIP32 path string to list of uint32 integers with hardened flags.
# Several conventions are supported to set the hardened flag: -1, 1', 1h
# e.g.: "0/1h/1" -> [0, 0x80000001, 1]
# :param nstr: path string
# :return: list of integers
# """
# if not nstr:
# return []
#
# n = nstr.split('/')
#
# # m/a/b/c => a/b/c
# if n[0] == 'm':
# n = n[1:]
#
# # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c
# #if n[0] in slip44:
# # coin_id = slip44[n[0]]
# # n[0:1] = ['44h', '{}h'.format(coin_id)]
#
# def str_to_harden(x):
# if x.startswith('-'):
# return H_(abs(int(x)))
# elif x.endswith(('h', "'")):
# return H_(int(x[:-1]))
# else:
# return int(x)
#
# try:
# return list(str_to_harden(x) for x in n)
# except Exception:
# raise ValueError('Invalid BIP32 path', nstr)
#
# Path: keepkeylib/tx_api.py
# def pack_varint(n):
# def __init__(self, network, url):
# def fetch_json(self, url, resource, resourceid):
# def get_tx(self, txhash):
# def __init__(self, network, url, zcash=None):
# def get_tx(self, txhash):
# def get_raw_tx(self, txhash):
# class TxApi(object):
# class TxApiInsight(TxApi):
which might include code, classes, or functions. Output only the next line. | address_n=parse_path("84'/1'/0'/0/0"), # tgrs1qkvwu9g3k2pdxewfqr7syz89r3gj557l3ued7ja |
Here is a snippet: <|code_start|># This file is part of the Trezor project.
#
# Copyright (C) 2012-2018 SatoshiLabs and contributors
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the License along with this library.
# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
# https://blockbook-test.groestlcoin.org/tx/9b5c4859a8a31e69788cb4402812bb28f14ad71cbd8c60b09903478bc56f79a3
class TestMsgSigntxNativeSegwitGRS(KeepKeyTest):
def test_send_native(self):
self.setup_mnemonic_allallall()
<|code_end|>
. Write the next line using the current file imports:
import common
import unittest
from binascii import hexlify, unhexlify
from keepkeylib import ckd_public as bip32
from common import KeepKeyTest
from keepkeylib import messages_pb2 as proto
from keepkeylib import types_pb2 as proto_types
from keepkeylib.client import CallException
from keepkeylib.tools import parse_path
from keepkeylib.tx_api import TxApiGroestlcoinTestnet
and context from other files:
# Path: keepkeylib/ckd_public.py
# PRIME_DERIVATION_FLAG = 0x80000000
# I64 = hmac.HMAC(key=node.chain_code, msg=data, digestmod=hashlib.sha512).digest()
# def point_to_pubkey(point):
# def sec_to_public_pair(pubkey):
# def public_pair_for_x(generator, x, is_even):
# def is_prime(n):
# def fingerprint(pubkey):
# def get_address(public_node, address_type):
# def public_ckd(public_node, n):
# def get_subnode(node, i):
# def serialize(node, version=0x0488B21E):
# def deserialize(xpub):
#
# Path: keepkeylib/client.py
# class CallException(Exception):
# def __init__(self, code, message):
# super(CallException, self).__init__()
# self.args = [code, message]
#
# Path: keepkeylib/tools.py
# def parse_path(nstr):
# """
# Convert BIP32 path string to list of uint32 integers with hardened flags.
# Several conventions are supported to set the hardened flag: -1, 1', 1h
# e.g.: "0/1h/1" -> [0, 0x80000001, 1]
# :param nstr: path string
# :return: list of integers
# """
# if not nstr:
# return []
#
# n = nstr.split('/')
#
# # m/a/b/c => a/b/c
# if n[0] == 'm':
# n = n[1:]
#
# # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c
# #if n[0] in slip44:
# # coin_id = slip44[n[0]]
# # n[0:1] = ['44h', '{}h'.format(coin_id)]
#
# def str_to_harden(x):
# if x.startswith('-'):
# return H_(abs(int(x)))
# elif x.endswith(('h', "'")):
# return H_(int(x[:-1]))
# else:
# return int(x)
#
# try:
# return list(str_to_harden(x) for x in n)
# except Exception:
# raise ValueError('Invalid BIP32 path', nstr)
#
# Path: keepkeylib/tx_api.py
# def pack_varint(n):
# def __init__(self, network, url):
# def fetch_json(self, url, resource, resourceid):
# def get_tx(self, txhash):
# def __init__(self, network, url, zcash=None):
# def get_tx(self, txhash):
# def get_raw_tx(self, txhash):
# class TxApi(object):
# class TxApiInsight(TxApi):
, which may include functions, classes, or code. Output only the next line. | self.client.set_tx_api(TxApiGroestlcoinTestnet) |
Given the following code snippet before the placeholder: <|code_start|>
def test_xfer_node_error(self):
self.setup_mnemonic_nopin_nopassphrase()
# tx: d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882
# input 0: 0.0039 BTC
inp1 = proto_types.TxInputType(address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e
# amount=390000,
prev_hash=binascii.unhexlify('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882'),
prev_index=0,
)
# Transfer Output address
out1 = proto_types.TxOutputType(address_n=[0x8000002c, 0x80000000, 0x80000000, 1, 0 ],
#error -^-
amount=390000 - 10000,
script_type=proto_types.PAYTOADDRESS,
address_type=1,
)
# Change Output address
out2 = proto_types.TxOutputType(address_n=[0x8000002c, 0x80000000, 0x80000000, 1, 1 ],
amount=8000,
script_type=proto_types.PAYTOADDRESS,
address_type=2,
)
try:
self.client.sign_tx('Bitcoin', [inp1, ], [out1, out2])
<|code_end|>
, predict the next line using imports from the current file:
import unittest
import common
import binascii
import itertools
import keepkeylib.messages_pb2 as proto
import keepkeylib.types_pb2 as proto_types
from keepkeylib.client import CallException
from keepkeylib import tx_api
and context including class names, function names, and sometimes code from other files:
# Path: keepkeylib/client.py
# class CallException(Exception):
# def __init__(self, code, message):
# super(CallException, self).__init__()
# self.args = [code, message]
#
# Path: keepkeylib/tx_api.py
# def pack_varint(n):
# def __init__(self, network, url):
# def fetch_json(self, url, resource, resourceid):
# def get_tx(self, txhash):
# def __init__(self, network, url, zcash=None):
# def get_tx(self, txhash):
# def get_raw_tx(self, txhash):
# class TxApi(object):
# class TxApiInsight(TxApi):
. Output only the next line. | except CallException as e:
|
Next line prediction: <|code_start|>
class ConfigData(unittest.TestCase):
def test_todict_noconv(self):
for x in ({}, 0, None, 1, "", True, False, 0.0, -1, -1.1, 1.1, {1: 1}):
<|code_end|>
. Use current file imports:
(import copy
import unittest
from ecmcli.commands import base, remote)
and context including class names, function names, or small code snippets from other files:
# Path: ecmcli/commands/base.py
# def toxml(data, root_tag='ecmcli'):
# def crawl(obj, parent):
# def totuples(data):
# def crawl(obj, path):
# def todict(obj, str_array_keys=False):
# def api_complete(self, resource, field, startswith):
# def make_completer(self, resource, field):
# def cached(startswith):
# def wrap(startswith, *args):
# def api_search(self, resource, fields, terms, match='icontains',
# **options):
# def res_flatten(self, resource, fields):
# def confirm(self, msg, exit=True):
# def make_searcher(self, resource, field_desc, **search_options):
# def lookup(terms, **options):
# def complete(startswith, args):
# def add_completer_argument(self, *keys, resource=None, res_field=None,
# **options):
# def add_router_argument(self, *keys, **options):
# def add_group_argument(self, *keys, **options):
# def add_account_argument(self, *keys, **options):
# def add_product_argument(self, *keys, **options):
# def add_firmware_argument(self, *keys, **options):
# def add_role_argument(self, *keys, **options):
# def add_user_argument(self, *keys, **options):
# def add_search_argument(self, searcher, *keys, **options):
# def inject_table_factory(self, *args, **kwargs):
# def setup_make_table(argument_ns):
# class ECMCommand(shellish.Command):
#
# Path: ecmcli/commands/remote.py
# class DeviceSelectorsMixin(object):
# class Get(DeviceSelectorsMixin, base.ECMCommand):
# class Set(DeviceSelectorsMixin, base.ECMCommand):
# class Diff(base.ECMCommand):
# class Remote(base.ECMCommand):
# def setup_args(self, parser):
# def api_res_lookup(self, *args, **kwargs):
# def gen_selection_filters(self, args_namespace):
# def completion_router_elect(self, **filters):
# def try_complete_path(self, prefix, args=None):
# def remote_lookup(self, rid_and_path):
# def setup_args(self, parser):
# def run(self, args):
# def data_flatten(self, args, datafeed):
# def responses():
# def make_response_tree(self, resp):
# def tree_format(self, args, results_feed, file):
# def cook():
# def table_format(self, args, results_feed, file):
# def json_format(self, args, results_feed, file):
# def xml_format(self, args, results_feed, file):
# def csv_format(self, args, results_feed, file):
# def setup_args(self, parser):
# def run(self, args):
# def setup_args(self, parser):
# def complete_dtd_path(self, prefix, args=None):
# def run(self, args):
# def __init__(self, *args, **kwargs):
. Output only the next line. | self.assertEqual(base.todict(x), copy.deepcopy(x)) |
Using the snippet: <|code_start|> 'Welcome to the ECM shell.',
'Type "help" or "?" to list commands and "exit" to quit.'
])
def verror(self, *args, **kwargs):
msg = ' '.join(map(str, args))
shellish.vtmlprint(msg, file=sys.stderr, **kwargs)
def prompt_info(self):
info = super().prompt_info()
ident = self.root_command.api.ident
username = ident['user']['username'] if ident else '*LOGGED_OUT*'
info.update({
"user": username,
"site": self.root_command.api.site.split('//', 1)[1]
})
return info
def execute(self, *args, **kwargs):
try:
return super().execute(*args, **kwargs)
except api.TOSRequired:
self.verror('TOS Acceptance Required')
input('Press <enter> to review TOS')
return self.root_command['tos']['accept'](argv='')
except api.AuthFailure as e:
self.verror('Auth error:' % e)
return self.root_command['login'](argv='')
<|code_end|>
, determine the next line of code. You have imports:
import importlib
import logging
import pkg_resources
import shellish
import shellish.logging
import sys
from . import api
from .commands import base, shtools
from shellish.command import contrib
and context (class names, function names, or code) available:
# Path: ecmcli/commands/base.py
# def toxml(data, root_tag='ecmcli'):
# def crawl(obj, parent):
# def totuples(data):
# def crawl(obj, path):
# def todict(obj, str_array_keys=False):
# def api_complete(self, resource, field, startswith):
# def make_completer(self, resource, field):
# def cached(startswith):
# def wrap(startswith, *args):
# def api_search(self, resource, fields, terms, match='icontains',
# **options):
# def res_flatten(self, resource, fields):
# def confirm(self, msg, exit=True):
# def make_searcher(self, resource, field_desc, **search_options):
# def lookup(terms, **options):
# def complete(startswith, args):
# def add_completer_argument(self, *keys, resource=None, res_field=None,
# **options):
# def add_router_argument(self, *keys, **options):
# def add_group_argument(self, *keys, **options):
# def add_account_argument(self, *keys, **options):
# def add_product_argument(self, *keys, **options):
# def add_firmware_argument(self, *keys, **options):
# def add_role_argument(self, *keys, **options):
# def add_user_argument(self, *keys, **options):
# def add_search_argument(self, searcher, *keys, **options):
# def inject_table_factory(self, *args, **kwargs):
# def setup_make_table(argument_ns):
# class ECMCommand(shellish.Command):
#
# Path: ecmcli/commands/shtools.py
# class Debug(base.ECMCommand):
# def run(self, args):
. Output only the next line. | class ECMRoot(base.ECMCommand): |
Given the following code snippet before the placeholder: <|code_start|>class ECMRoot(base.ECMCommand):
""" ECM Command Line Interface
This utility represents a collection of sub-commands to perform against
the Cradlepoint ECM service. You must already have a valid ECM
username/password to use this tool. For more info go to
https://cradlepointecm.com/. """
name = 'ecm'
use_pager = False
Session = ECMSession
def setup_args(self, parser):
distro = pkg_resources.get_distribution('ecmcli')
self.add_argument('--api-username')
self.add_argument('--api-password')
self.add_argument('--api-site',
help='E.g. https://cradlepointecm.com')
self.add_argument('--debug', action='store_true')
self.add_argument('--trace', action='store_true')
self.add_argument('--no-pager', action='store_true')
self.add_argument('--version', action='version',
version=distro.version)
self.add_subcommand(contrib.Commands)
self.add_subcommand(contrib.SystemCompletion)
self.add_subcommand(contrib.Help)
def prerun(self, args):
""" Add the interactive commands just before it goes to the prompt so
they don't show up in the --help from the commands line. """
<|code_end|>
, predict the next line using imports from the current file:
import importlib
import logging
import pkg_resources
import shellish
import shellish.logging
import sys
from . import api
from .commands import base, shtools
from shellish.command import contrib
and context including class names, function names, and sometimes code from other files:
# Path: ecmcli/commands/base.py
# def toxml(data, root_tag='ecmcli'):
# def crawl(obj, parent):
# def totuples(data):
# def crawl(obj, path):
# def todict(obj, str_array_keys=False):
# def api_complete(self, resource, field, startswith):
# def make_completer(self, resource, field):
# def cached(startswith):
# def wrap(startswith, *args):
# def api_search(self, resource, fields, terms, match='icontains',
# **options):
# def res_flatten(self, resource, fields):
# def confirm(self, msg, exit=True):
# def make_searcher(self, resource, field_desc, **search_options):
# def lookup(terms, **options):
# def complete(startswith, args):
# def add_completer_argument(self, *keys, resource=None, res_field=None,
# **options):
# def add_router_argument(self, *keys, **options):
# def add_group_argument(self, *keys, **options):
# def add_account_argument(self, *keys, **options):
# def add_product_argument(self, *keys, **options):
# def add_firmware_argument(self, *keys, **options):
# def add_role_argument(self, *keys, **options):
# def add_user_argument(self, *keys, **options):
# def add_search_argument(self, searcher, *keys, **options):
# def inject_table_factory(self, *args, **kwargs):
# def setup_make_table(argument_ns):
# class ECMCommand(shellish.Command):
#
# Path: ecmcli/commands/shtools.py
# class Debug(base.ECMCommand):
# def run(self, args):
. Output only the next line. | for x in shtools.command_classes: |
Predict the next line after this snippet: <|code_start|>
class ArgSanity(unittest.TestCase):
def setUp(self):
api = unittest.mock.Mock()
fake = dict(name='foo', id='1')
api.get_by_id_or_name.return_value = fake
api.get_pager.return_value = [fake]
<|code_end|>
using the current file's imports:
import unittest.mock
from ecmcli.commands import routers
and any relevant context from other files:
# Path: ecmcli/commands/routers.py
# class Printer(object):
# class List(Printer, base.ECMCommand):
# class Search(Printer, base.ECMCommand):
# class GroupAssign(base.ECMCommand):
# class GroupUnassign(base.ECMCommand):
# class Edit(base.ECMCommand):
# class Move(base.ECMCommand):
# class Delete(base.ECMCommand):
# class Reboot(base.ECMCommand):
# class FlashLEDS(base.ECMCommand):
# class Routers(base.ECMCommand):
# def setup_args(self, parser):
# def prerun(self, args):
# def verbose_printer(self, routers):
# def acc(x):
# def group_name(self, group):
# def terse_printer(self, routers):
# def colorize_conn_state(self, state):
# def bundle_router(self, router):
# def setup_args(self, parser):
# def run(self, args):
# def setup_args(self, parser):
# def run(self, args):
# def setup_args(self, parser):
# def run(self, args):
# def setup_args(self, parser):
# def run(self, args):
# def setup_args(self, parser):
# def run(self, args):
# def setup_args(self, parser):
# def run(self, args):
# def setup_args(self, parser):
# def run(self, args):
# def setup_args(self, parser):
# def run(self, args):
# def setup_args(self, parser):
# def run(self, args):
# def __init__(self, *args, **kwargs):
. Output only the next line. | self.cmd = routers.Reboot(api=api) |
Predict the next line for this snippet: <|code_start|> __str__ = __ir_json__str__
def __new__(self, *args, **kwargs):
return float.__new__(self, *args, **kwargs)
# Cannot subclass NoneType, so use IRNullType to represent null.
class _IRJsonNull(IRNullType):
def __str__(self):
return 'null'
class IRJsonValue(type):
'''
IRJsonValue - A value which is interpreted as json.
Supports object (dicts), strings, array, number.
"null" is supported using IRNullType, because cannot subclass "NoneType".
"bool" is supported using a number 0.0 or 1.0 - because cannot subclass "bool"
'''
# TODO: This generally can't be indexable, because while the outer may be fixed-order for some
# types, inner elements (like elements in a list) might not be. So it'd be dependent on the
# value itself, not the value type each time, which makes it not 100% yes or no, which means no.
CAN_INDEX = False
def __init__(self, *args, **kwargs):
pass
def __str__(self):
if bool(self) is False:
<|code_end|>
with the help of current file imports:
import json
from . import irNull, IRNullType
from datetime import datetime
from ..compat_str import to_unicode
and context from other files:
# Path: IndexedRedis/fields/null.py
# IR_NULL_STR = 'IRNullType()'
# IR_NULL_BYTES = b'IRNullType()'
# IR_NULL_UNICODE = u'IRNullType()'
# IR_NULL_STRINGS = (IR_NULL_STR, IR_NULL_BYTES)
# IR_NULL_STRINGS = (IR_NULL_STR, )
# class IRNullType(IrNullBaseType):
# def __new__(self, val=''):
# def __eq__(self, otherVal):
# def __ne__(self, otherVal):
# def __str__(self):
# def __bool__(self):
# def __nonzero__(self):
# def __repr__(self):
#
# Path: IndexedRedis/compat_str.py
# def to_unicode(x, encoding=None):
# '''
# to_unicode - Ensure a given value is decoded into unicode type
#
# @param x - Value
# @param encoding <None/str> (default None) - None to use defaultIREncoding, otherwise an explicit encoding
#
# @return - "x" as a unicode type
# '''
# if encoding is None:
# global defaultIREncoding
# encoding = defaultIREncoding
#
# if isinstance(x, unicode):
# return x
# elif isinstance(x, str):
# return x.decode(encoding)
# else:
# return str(x).decode(encoding)
, which may contain function names, class names, or code. Output only the next line. | return irNull |
Using the snippet: <|code_start|>
class _IRJsonDict(dict):
__str__ = __ir_json__str__
def __new__(self, *args, **kwargs):
return dict.__new__(self, *args, **kwargs)
_IRJsonObject = _IRJsonDict
class _IRJsonString(str):
__str__ = __ir_json__str__
def __new__(self, *args, **kwargs):
return str.__new__(self, *args, **kwargs)
# Cannot subclass bool..... how stupid.
#class _IRJsonBool(bool):
# __str__ = __ir_json__str__
# def __new__(self, *args, **kwargs):
# return bool.__new__(self, *args, **kwargs)
class _IRJsonArray(list):
__str__ = __ir_json__str__
def __new__(self, *args, **kwargs):
return list.__new__(self, *args, **kwargs)
class _IRJsonNumber(float):
__str__ = __ir_json__str__
def __new__(self, *args, **kwargs):
return float.__new__(self, *args, **kwargs)
# Cannot subclass NoneType, so use IRNullType to represent null.
<|code_end|>
, determine the next line of code. You have imports:
import json
from . import irNull, IRNullType
from datetime import datetime
from ..compat_str import to_unicode
and context (class names, function names, or code) available:
# Path: IndexedRedis/fields/null.py
# IR_NULL_STR = 'IRNullType()'
# IR_NULL_BYTES = b'IRNullType()'
# IR_NULL_UNICODE = u'IRNullType()'
# IR_NULL_STRINGS = (IR_NULL_STR, IR_NULL_BYTES)
# IR_NULL_STRINGS = (IR_NULL_STR, )
# class IRNullType(IrNullBaseType):
# def __new__(self, val=''):
# def __eq__(self, otherVal):
# def __ne__(self, otherVal):
# def __str__(self):
# def __bool__(self):
# def __nonzero__(self):
# def __repr__(self):
#
# Path: IndexedRedis/compat_str.py
# def to_unicode(x, encoding=None):
# '''
# to_unicode - Ensure a given value is decoded into unicode type
#
# @param x - Value
# @param encoding <None/str> (default None) - None to use defaultIREncoding, otherwise an explicit encoding
#
# @return - "x" as a unicode type
# '''
# if encoding is None:
# global defaultIREncoding
# encoding = defaultIREncoding
#
# if isinstance(x, unicode):
# return x
# elif isinstance(x, str):
# return x.decode(encoding)
# else:
# return str(x).decode(encoding)
. Output only the next line. | class _IRJsonNull(IRNullType): |
Continue the code snippet: <|code_start|># Copyright (c) 2016, 2017 Timothy Savannah under LGPL version 2.1. See LICENSE for more information.
#
# FieldValueTypes - Types that can be passed to "valueType" of an IRField for special implicit conversions
#
__all__ = ('IRDatetimeValue', 'IRJsonValue')
try:
unicode
except NameError:
unicode = str
class IRDatetimeValue(datetime):
'''
IRDatetimeValue - A field type that is a datetime. Pass this as "valueType" to an IRField to use a datetime
'''
CAN_INDEX = True
def __new__(self, *args, **kwargs):
# No need to actually create this object, we just need to override instantiation to create a datetime from several forms.
if len(args) == 1:
if type(args[0]) == bytes:
<|code_end|>
. Use current file imports:
import json
from . import irNull, IRNullType
from datetime import datetime
from ..compat_str import to_unicode
and context (classes, functions, or code) from other files:
# Path: IndexedRedis/fields/null.py
# IR_NULL_STR = 'IRNullType()'
# IR_NULL_BYTES = b'IRNullType()'
# IR_NULL_UNICODE = u'IRNullType()'
# IR_NULL_STRINGS = (IR_NULL_STR, IR_NULL_BYTES)
# IR_NULL_STRINGS = (IR_NULL_STR, )
# class IRNullType(IrNullBaseType):
# def __new__(self, val=''):
# def __eq__(self, otherVal):
# def __ne__(self, otherVal):
# def __str__(self):
# def __bool__(self):
# def __nonzero__(self):
# def __repr__(self):
#
# Path: IndexedRedis/compat_str.py
# def to_unicode(x, encoding=None):
# '''
# to_unicode - Ensure a given value is decoded into unicode type
#
# @param x - Value
# @param encoding <None/str> (default None) - None to use defaultIREncoding, otherwise an explicit encoding
#
# @return - "x" as a unicode type
# '''
# if encoding is None:
# global defaultIREncoding
# encoding = defaultIREncoding
#
# if isinstance(x, unicode):
# return x
# elif isinstance(x, str):
# return x.decode(encoding)
# else:
# return str(x).decode(encoding)
. Output only the next line. | theArg = to_unicode(args[0]) |
Predict the next line after this snippet: <|code_start|>
class TestTemplateServer(TestCase):
def test_get_cwd(self):
"""
This is a bad test
"""
<|code_end|>
using the current file's imports:
from django.test import TestCase
from isomorphic.server.template_server import TemplateServer
and any relevant context from other files:
# Path: isomorphic/server/template_server.py
# class TemplateServer():
# def __init__(self):
# self.started = False
# self.proc = None
#
# def get_cwd(self):
# pth = os.path.join(
# os.path.dirname(__file__),
# '../javascript/dist/'
# )
# return pth
#
# def get_options(self):
# options = [
# 'debug={}'.format(settings.DEBUG),
# ]
# renderer = getattr(settings, 'DJANGO_ISOMORPHIC_RENDERER', None)
# if renderer:
# options.append('renderer={}'.format(renderer))
# return options
#
# def start(self):
# if self.started:
# return
# self.started = True
#
# cwd = self.get_cwd()
# options = self.get_options()
# self.proc = Popen(['node', 'template-server.js'] + options, cwd=cwd, preexec_fn=os.setsid)
#
# def terminate(self):
# os.killpg(self.proc.pid, signal.SIGTERM)
. Output only the next line. | template_server = TemplateServer() |
Given the following code snippet before the placeholder: <|code_start|>
class FakeRequest():
def __init__(self):
self.META = {}
@property
def path(self):
return '/'
def build_absolute_uri(self):
return 'http://localhost:8000/'
class TestJsTemplate(TestCase):
def test_render_template_without_request(self):
"""
Render a template
"""
loader = JsLoader(engine=None)
template_path = loader.load_template('test-component.js', template_dirs=[settings.TEMPLATE_DIR])[0]
<|code_end|>
, predict the next line using imports from the current file:
from django.test import TestCase
from django.conf import settings
from isomorphic.template.backend import JsTemplate
from isomorphic.template.loaders import JsLoader
and context including class names, function names, and sometimes code from other files:
# Path: isomorphic/template/backend.py
# class JsTemplate(object):
# def __init__(self, template_path):
# self.template_path = template_path
#
# def render(self, context=None, request=None):
# context = context.copy()
# request_data = {}
#
# if request is not None:
# context['csrf_token'] = get_token(request)
#
# request_data['path'] = request.path
# request_data['absolute_uri'] = request.build_absolute_uri()
#
# client = TemplateClient()
# return client.render_template(self.template_path, context, request_data)
#
# Path: isomorphic/template/loaders.py
# class JsLoader(Loader):
# def load_template_source(self, template_name, template_dirs=None):
# tried = []
# for filepath in self.get_template_sources(template_name, template_dirs):
# if exists(filepath):
# return filepath, None
# else:
# tried.append(filepath)
#
# if tried:
# error_msg = "Tried %s" % tried
# else:
# error_msg = ("Your template directories configuration is empty. "
# "Change it to point to at least one template directory.")
# raise TemplateDoesNotExist(error_msg)
#
# def load_template(self, template_name, template_dirs=None):
# """
# Only the file path is returned
# """
# filepath, display_name = self.load_template_source(template_name, template_dirs)
# return filepath, template_name
. Output only the next line. | template = JsTemplate(template_path) |
Next line prediction: <|code_start|>
class FakeRequest():
def __init__(self):
self.META = {}
@property
def path(self):
return '/'
def build_absolute_uri(self):
return 'http://localhost:8000/'
class TestJsTemplate(TestCase):
def test_render_template_without_request(self):
"""
Render a template
"""
<|code_end|>
. Use current file imports:
(from django.test import TestCase
from django.conf import settings
from isomorphic.template.backend import JsTemplate
from isomorphic.template.loaders import JsLoader)
and context including class names, function names, or small code snippets from other files:
# Path: isomorphic/template/backend.py
# class JsTemplate(object):
# def __init__(self, template_path):
# self.template_path = template_path
#
# def render(self, context=None, request=None):
# context = context.copy()
# request_data = {}
#
# if request is not None:
# context['csrf_token'] = get_token(request)
#
# request_data['path'] = request.path
# request_data['absolute_uri'] = request.build_absolute_uri()
#
# client = TemplateClient()
# return client.render_template(self.template_path, context, request_data)
#
# Path: isomorphic/template/loaders.py
# class JsLoader(Loader):
# def load_template_source(self, template_name, template_dirs=None):
# tried = []
# for filepath in self.get_template_sources(template_name, template_dirs):
# if exists(filepath):
# return filepath, None
# else:
# tried.append(filepath)
#
# if tried:
# error_msg = "Tried %s" % tried
# else:
# error_msg = ("Your template directories configuration is empty. "
# "Change it to point to at least one template directory.")
# raise TemplateDoesNotExist(error_msg)
#
# def load_template(self, template_name, template_dirs=None):
# """
# Only the file path is returned
# """
# filepath, display_name = self.load_template_source(template_name, template_dirs)
# return filepath, template_name
. Output only the next line. | loader = JsLoader(engine=None) |
Given snippet: <|code_start|>
class MockSock():
def send(self, message):
pass
def recv(self, buffer_size):
return b''
def mock_connect():
return MockSock()
class TestTemplateClient(TestCase):
def test_make_none(self):
"""
Test JSON conversion doesn't fail when object can't be serialized
"""
class Foo():
def __str__(self):
return 'foo'
foo = Foo()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.test import TestCase
from isomorphic.client import template_client
from django.conf import settings
from os.path import join
and context:
# Path: isomorphic/client/template_client.py
# BUFFER_SIZE = 8192
# def _make_none(obj):
# def clean_context(context):
# def render_template(self, file_path, context=None, request_data=None):
# def connect(self):
# def receive(self, sock):
# class JsTemplateException(Exception):
# class TemplateClient():
which might include code, classes, or functions. Output only the next line. | is_none = template_client._make_none(foo) |
Based on the snippet: <|code_start|>
class JsTemplates(BaseEngine):
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(JsTemplates, self).__init__(params)
self.engine = JsEngine(self.dirs, self.app_dirs, **options)
def get_template(self, template_name, dirs=_dirs_undefined):
return JsTemplate(self.engine.get_template(template_name))
class JsTemplate(object):
def __init__(self, template_path):
self.template_path = template_path
def render(self, context=None, request=None):
context = context.copy()
request_data = {}
if request is not None:
context['csrf_token'] = get_token(request)
request_data['path'] = request.path
request_data['absolute_uri'] = request.build_absolute_uri()
<|code_end|>
, predict the immediate next line with the help of imports:
from django.middleware.csrf import get_token
from django.template.backends.base import BaseEngine
from django.template.engine import _dirs_undefined
from ..client.template_client import TemplateClient
from ..template.engine import JsEngine
and context (classes, functions, sometimes code) from other files:
# Path: isomorphic/client/template_client.py
# class TemplateClient():
# def render_template(self, file_path, context=None, request_data=None):
# data = {
# 'template': file_path,
# 'request': request_data,
# 'context': clean_context(context)
# }
# message = json.dumps(data, default=_make_none).encode()
#
# sock = self.connect()
# sock.send(message)
# response = self.receive(sock)
#
# if not response:
# raise JsTemplateException('Empty template response')
#
# status = response[0]
#
# if status != '0':
# raise JsTemplateException(response[1:])
#
# return response[1:]
#
# def connect(self):
# sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# sock.connect(server_address)
# return sock
#
# def receive(self, sock):
# message = []
# while True:
# data = sock.recv(BUFFER_SIZE)
# if not data:
# break
# message.append(data.decode())
# return ''.join(message)
#
# Path: isomorphic/template/engine.py
# class JsEngine(Engine):
# def __init__(self, dirs=None, app_dirs=False,
# allowed_include_roots=None, context_processors=None,
# debug=False, loaders=None, string_if_invalid='',
# file_charset='utf-8'):
#
# # Set the default loader to the JS loader
# if loaders is None:
# loaders = ['isomorphic.template.loaders.JsLoader']
# if app_dirs:
# loaders += ['django.template.loaders.app_directories.Loader']
# app_dirs = False
#
# super(JsEngine, self).__init__(
# dirs=dirs,
# app_dirs=app_dirs,
# allowed_include_roots=allowed_include_roots, context_processors=context_processors,
# debug=debug, loaders=loaders, string_if_invalid=string_if_invalid,
# file_charset=file_charset
# )
#
# def get_template(self, template_name, dirs=_dirs_undefined):
# if dirs is _dirs_undefined:
# dirs = None
#
# template_path, origin = self.find_template(template_name, dirs)
# return template_path
. Output only the next line. | client = TemplateClient() |
Given the code snippet: <|code_start|>
class JsTemplates(BaseEngine):
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(JsTemplates, self).__init__(params)
<|code_end|>
, generate the next line using the imports in this file:
from django.middleware.csrf import get_token
from django.template.backends.base import BaseEngine
from django.template.engine import _dirs_undefined
from ..client.template_client import TemplateClient
from ..template.engine import JsEngine
and context (functions, classes, or occasionally code) from other files:
# Path: isomorphic/client/template_client.py
# class TemplateClient():
# def render_template(self, file_path, context=None, request_data=None):
# data = {
# 'template': file_path,
# 'request': request_data,
# 'context': clean_context(context)
# }
# message = json.dumps(data, default=_make_none).encode()
#
# sock = self.connect()
# sock.send(message)
# response = self.receive(sock)
#
# if not response:
# raise JsTemplateException('Empty template response')
#
# status = response[0]
#
# if status != '0':
# raise JsTemplateException(response[1:])
#
# return response[1:]
#
# def connect(self):
# sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# sock.connect(server_address)
# return sock
#
# def receive(self, sock):
# message = []
# while True:
# data = sock.recv(BUFFER_SIZE)
# if not data:
# break
# message.append(data.decode())
# return ''.join(message)
#
# Path: isomorphic/template/engine.py
# class JsEngine(Engine):
# def __init__(self, dirs=None, app_dirs=False,
# allowed_include_roots=None, context_processors=None,
# debug=False, loaders=None, string_if_invalid='',
# file_charset='utf-8'):
#
# # Set the default loader to the JS loader
# if loaders is None:
# loaders = ['isomorphic.template.loaders.JsLoader']
# if app_dirs:
# loaders += ['django.template.loaders.app_directories.Loader']
# app_dirs = False
#
# super(JsEngine, self).__init__(
# dirs=dirs,
# app_dirs=app_dirs,
# allowed_include_roots=allowed_include_roots, context_processors=context_processors,
# debug=debug, loaders=loaders, string_if_invalid=string_if_invalid,
# file_charset=file_charset
# )
#
# def get_template(self, template_name, dirs=_dirs_undefined):
# if dirs is _dirs_undefined:
# dirs = None
#
# template_path, origin = self.find_template(template_name, dirs)
# return template_path
. Output only the next line. | self.engine = JsEngine(self.dirs, self.app_dirs, **options) |
Given snippet: <|code_start|>
class TestLoader(TestCase):
def test_render_template(self):
"""
Render a template with the template tag
"""
context = RequestContext(request=None)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.template import RequestContext
from django.test import TestCase
from isomorphic.templatetags import djangojs
from isomorphic.templatetags.djangojs import JsMissingTemplateDirException
and context:
# Path: isomorphic/templatetags/djangojs.py
# class JsMissingTemplateDirException(Exception):
# def _get_template_dirs():
# def _get_template_path(template_name):
# def include_js(context, template_name, **kwargs):
#
# Path: isomorphic/templatetags/djangojs.py
# class JsMissingTemplateDirException(Exception):
# pass
which might include code, classes, or functions. Output only the next line. | template = djangojs.include_js(context, template_name='test-component.js') |
Given snippet: <|code_start|>
class TestLoader(TestCase):
def test_render_template(self):
"""
Render a template with the template tag
"""
context = RequestContext(request=None)
template = djangojs.include_js(context, template_name='test-component.js')
self.assertEqual(template, '<span>Test component</span>')
def test_try_to_render_template_without_the_js_backend(self):
"""
Raises JsMissingTemplateDirException if the backend is not specified
"""
context = RequestContext(request=None)
with self.settings(TEMPLATES=[{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': []}]):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.template import RequestContext
from django.test import TestCase
from isomorphic.templatetags import djangojs
from isomorphic.templatetags.djangojs import JsMissingTemplateDirException
and context:
# Path: isomorphic/templatetags/djangojs.py
# class JsMissingTemplateDirException(Exception):
# def _get_template_dirs():
# def _get_template_path(template_name):
# def include_js(context, template_name, **kwargs):
#
# Path: isomorphic/templatetags/djangojs.py
# class JsMissingTemplateDirException(Exception):
# pass
which might include code, classes, or functions. Output only the next line. | with self.assertRaises(JsMissingTemplateDirException): |
Given the code snippet: <|code_start|>
register = template.Library()
loader = JsLoader(engine=None)
class JsMissingTemplateDirException(Exception):
pass
def _get_template_dirs():
for t in settings.TEMPLATES:
if t['BACKEND'] == 'isomorphic.template.backend.JsTemplates':
return t['DIRS']
return None
def _get_template_path(template_name):
template_dirs = _get_template_dirs()
if not template_dirs:
return None
template_path, _ = loader.load_template(template_name, template_dirs=template_dirs)
return template_path
@register.simple_tag(takes_context=True)
def include_js(context, template_name, **kwargs):
request = context.get('request')
template_path = _get_template_path(template_name)
if not template_path:
raise JsMissingTemplateDirException('No template directory')
<|code_end|>
, generate the next line using the imports in this file:
from django import template
from django.conf import settings
from ..template.backend import JsTemplate
from ..template.loaders import JsLoader
and context (functions, classes, or occasionally code) from other files:
# Path: isomorphic/template/backend.py
# class JsTemplate(object):
# def __init__(self, template_path):
# self.template_path = template_path
#
# def render(self, context=None, request=None):
# context = context.copy()
# request_data = {}
#
# if request is not None:
# context['csrf_token'] = get_token(request)
#
# request_data['path'] = request.path
# request_data['absolute_uri'] = request.build_absolute_uri()
#
# client = TemplateClient()
# return client.render_template(self.template_path, context, request_data)
#
# Path: isomorphic/template/loaders.py
# class JsLoader(Loader):
# def load_template_source(self, template_name, template_dirs=None):
# tried = []
# for filepath in self.get_template_sources(template_name, template_dirs):
# if exists(filepath):
# return filepath, None
# else:
# tried.append(filepath)
#
# if tried:
# error_msg = "Tried %s" % tried
# else:
# error_msg = ("Your template directories configuration is empty. "
# "Change it to point to at least one template directory.")
# raise TemplateDoesNotExist(error_msg)
#
# def load_template(self, template_name, template_dirs=None):
# """
# Only the file path is returned
# """
# filepath, display_name = self.load_template_source(template_name, template_dirs)
# return filepath, template_name
. Output only the next line. | template = JsTemplate(template_path) |
Predict the next line for this snippet: <|code_start|>
class TestEngine(TestCase):
def test_get_template(self):
"""
Get a template by name
"""
params = {
'DIRS': [settings.TEMPLATE_DIR],
'APP_DIRS': False,
'NAME': 'backend',
'OPTIONS': {}
}
<|code_end|>
with the help of current file imports:
from django.conf import settings
from django.test import TestCase
from isomorphic.template.backend import JsTemplates, JsTemplate
and context from other files:
# Path: isomorphic/template/backend.py
# class JsTemplates(BaseEngine):
# def __init__(self, params):
# params = params.copy()
# options = params.pop('OPTIONS').copy()
# super(JsTemplates, self).__init__(params)
# self.engine = JsEngine(self.dirs, self.app_dirs, **options)
#
# def get_template(self, template_name, dirs=_dirs_undefined):
# return JsTemplate(self.engine.get_template(template_name))
#
# class JsTemplate(object):
# def __init__(self, template_path):
# self.template_path = template_path
#
# def render(self, context=None, request=None):
# context = context.copy()
# request_data = {}
#
# if request is not None:
# context['csrf_token'] = get_token(request)
#
# request_data['path'] = request.path
# request_data['absolute_uri'] = request.build_absolute_uri()
#
# client = TemplateClient()
# return client.render_template(self.template_path, context, request_data)
, which may contain function names, class names, or code. Output only the next line. | templates = JsTemplates(params) |
Here is a snippet: <|code_start|>
class TestEngine(TestCase):
def test_get_template(self):
"""
Get a template by name
"""
params = {
'DIRS': [settings.TEMPLATE_DIR],
'APP_DIRS': False,
'NAME': 'backend',
'OPTIONS': {}
}
templates = JsTemplates(params)
template = templates.get_template('empty-template.js')
<|code_end|>
. Write the next line using the current file imports:
from django.conf import settings
from django.test import TestCase
from isomorphic.template.backend import JsTemplates, JsTemplate
and context from other files:
# Path: isomorphic/template/backend.py
# class JsTemplates(BaseEngine):
# def __init__(self, params):
# params = params.copy()
# options = params.pop('OPTIONS').copy()
# super(JsTemplates, self).__init__(params)
# self.engine = JsEngine(self.dirs, self.app_dirs, **options)
#
# def get_template(self, template_name, dirs=_dirs_undefined):
# return JsTemplate(self.engine.get_template(template_name))
#
# class JsTemplate(object):
# def __init__(self, template_path):
# self.template_path = template_path
#
# def render(self, context=None, request=None):
# context = context.copy()
# request_data = {}
#
# if request is not None:
# context['csrf_token'] = get_token(request)
#
# request_data['path'] = request.path
# request_data['absolute_uri'] = request.build_absolute_uri()
#
# client = TemplateClient()
# return client.render_template(self.template_path, context, request_data)
, which may include functions, classes, or code. Output only the next line. | self.assertIsInstance(template, JsTemplate) |
Continue the code snippet: <|code_start|>
class TestLoader(TestCase):
def test_load_missing_template(self):
engine = JsEngine(dirs=[settings.TEMPLATE_DIR])
<|code_end|>
. Use current file imports:
from django.conf import settings
from django.template import TemplateDoesNotExist
from django.test import TestCase
from isomorphic.template.engine import JsEngine
from isomorphic.template.loaders import JsLoader
and context (classes, functions, or code) from other files:
# Path: isomorphic/template/engine.py
# class JsEngine(Engine):
# def __init__(self, dirs=None, app_dirs=False,
# allowed_include_roots=None, context_processors=None,
# debug=False, loaders=None, string_if_invalid='',
# file_charset='utf-8'):
#
# # Set the default loader to the JS loader
# if loaders is None:
# loaders = ['isomorphic.template.loaders.JsLoader']
# if app_dirs:
# loaders += ['django.template.loaders.app_directories.Loader']
# app_dirs = False
#
# super(JsEngine, self).__init__(
# dirs=dirs,
# app_dirs=app_dirs,
# allowed_include_roots=allowed_include_roots, context_processors=context_processors,
# debug=debug, loaders=loaders, string_if_invalid=string_if_invalid,
# file_charset=file_charset
# )
#
# def get_template(self, template_name, dirs=_dirs_undefined):
# if dirs is _dirs_undefined:
# dirs = None
#
# template_path, origin = self.find_template(template_name, dirs)
# return template_path
#
# Path: isomorphic/template/loaders.py
# class JsLoader(Loader):
# def load_template_source(self, template_name, template_dirs=None):
# tried = []
# for filepath in self.get_template_sources(template_name, template_dirs):
# if exists(filepath):
# return filepath, None
# else:
# tried.append(filepath)
#
# if tried:
# error_msg = "Tried %s" % tried
# else:
# error_msg = ("Your template directories configuration is empty. "
# "Change it to point to at least one template directory.")
# raise TemplateDoesNotExist(error_msg)
#
# def load_template(self, template_name, template_dirs=None):
# """
# Only the file path is returned
# """
# filepath, display_name = self.load_template_source(template_name, template_dirs)
# return filepath, template_name
. Output only the next line. | loader = JsLoader(engine) |
Given the code snippet: <|code_start|> Notes
-----
The ``coords`` attribute will contain the coordinates of each lattice
point determined by the coordinate index and the primitive lattice
vectors. E.g., in 2-dimensions
lattice.coord[i, j] = (i - N1//2) * primitiveVector[0] + (j - N2//2) * primitiveVector[1]
Note, this convention places
lattice.coord[0,0] = (-N1//2) * primitiveVector[0] + (-N2/2) * primitiveVector[1]
but the location of lattice.coord[-1,-1] depends on whether the size of
each dimension is even or odd. An odd-sized dimension is "centered", in
that the 0-coordinate is precisely in the middle of the dimension. An
even-sized dimension will be slightly decentered, with more negative
points than positive points. The above convention is the same as for
numpy.fft.fftfreq.
"""
def __init__(self, array, primitiveVectors):
primitiveVectors = np.atleast_2d(primitiveVectors)
if array.ndim != len(primitiveVectors):
raise ValueError("Not enough primitiveVectors for array")
if array.ndim != len(primitiveVectors[0]):
raise ValueError("primitiveVectors are too small for array")
self.array = array
self.primitiveVectors = primitiveVectors
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from .utils import lazy_property
and context (functions, classes, or occasionally code) from other files:
# Path: batoid/utils.py
# class lazy_property(object):
# """
# meant to be used for lazy evaluation of an object attribute.
# property should represent non-mutable data, as it replaces itself.
# """
# def __init__(self, fget):
# self.fget = fget
# self.func_name = fget.__name__
#
# def __get__(self, obj, cls):
# if obj is None:
# return self
# value = self.fget(obj)
# setattr(obj, self.func_name, value)
# return value
. Output only the next line. | @lazy_property |
Here is a snippet: <|code_start|> batoid.SellmeierMedium(B1, B2, B3, C1, C2, C3, B1)
wavelengths = rng.uniform(300e-9, 1100e-9, size=1000)
indices = silica.getN(wavelengths)
for w, index in zip(wavelengths, indices):
assert silica.getN(w) == index
# CSV also from refractiveindex.info
filename = os.path.join(
os.path.dirname(__file__),
"testdata",
"silicaDispersion.csv"
)
wmicron, ncsv = np.loadtxt(filename, delimiter=',').T
n = silica.getN(wmicron*1e-6)
np.testing.assert_allclose(n, ncsv, atol=0, rtol=1e-13)
do_pickle(silica)
@timer
def test_SumitaMedium():
rng = np.random.default_rng(57)
# K-BK-7 coefficients
# https://refractiveindex.info/?shelf=glass&book=SUMITA-BK&page=K-BK7
A0 = 2.2705778
A1 = -0.010059376
A2 = 0.010414999
A3 = 0.00028872517
A4 = -2.2214495e-5
A5 = 1.4258559e-6
<|code_end|>
. Write the next line using the current file imports:
from batoid.medium import SumitaMedium, TableMedium
from test_helpers import timer, do_pickle, all_obj_diff
import os
import numpy as np
import batoid
and context from other files:
# Path: batoid/medium.py
# class SumitaMedium(Medium):
# r"""A `Medium` with Sumita dispersion formula, also known as the Schott
# dispersion formula.
#
# The Sumita formula is
#
# .. math::
#
# n = \sqrt{A_0 + A_1 \lambda^2 + \sum_{i=2}^5 A_i \lambda^{-2 (i-1)}}
#
# where :math:`\lambda` is the vacuum wavelength in microns.
#
# Parameters
# ----------
# coefs: array of float
# Sumita coefficients (A0, A1, A2, A3, A4, A5)
# """
# def __init__(self, *args, **kwargs):
# if len(args) == 6:
# coefs = tuple(args)
# elif len(args) == 1:
# coefs = tuple(args[0])
# elif kwargs:
# coefs = tuple([
# kwargs[k] for k in ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']
# ])
# else:
# raise ValueError("Incorrect number of arguments")
# self.coefs = coefs
# self._medium = _batoid.CPPSumitaMedium(*coefs)
#
# def __eq__(self, rhs):
# if type(rhs) == type(self):
# return self.coefs == rhs.coefs
# return False
#
# def __getstate__(self):
# return self.coefs
#
# def __setstate__(self, coefs):
# self.coefs = coefs
# self._medium = _batoid.CPPSumitaMedium(*coefs)
#
# def __hash__(self):
# return hash(("batoid.SumitaMedium", self.coefs))
#
# def __repr__(self):
# return f"SumitaMedium({self.coefs})"
#
# class TableMedium(Medium):
# """A `Medium` with refractive index defined via a lookup table.
#
# Parameters
# ----------
# wavelengths : array of float
# Wavelengths in meters.
# ns : array of float
# Refractive indices.
# """
# def __init__(self, wavelengths, ns):
# self.wavelengths = np.array(wavelengths)
# self.ns = np.array(ns)
# self._medium = _batoid.CPPTableMedium(
# self.wavelengths.ctypes.data,
# self.ns.ctypes.data,
# len(self.wavelengths)
# )
#
# @classmethod
# def fromTxt(cls, filename, **kwargs):
# """Load a text file with refractive index information in it.
# The file should have two columns, the first with wavelength in microns,
# and the second with the corresponding refractive indices.
# """
# import os
# try:
# wavelength, n = np.loadtxt(filename, unpack=True, **kwargs)
# except IOError:
# import glob
# from . import datadir
# filenames = glob.glob(os.path.join(datadir, "**", "*.txt"))
# for candidate in filenames:
# if os.path.basename(candidate) == filename:
# wavelength, n = np.loadtxt(candidate, unpack=True, **kwargs)
# break
# else:
# raise FileNotFoundError(filename)
# return TableMedium(wavelength*1e-6, n)
#
# def __eq__(self, rhs):
# if type(rhs) == type(self):
# return (
# np.array_equal(self.wavelengths, rhs.wavelengths)
# and np.array_equal(self.ns, rhs.ns)
# )
# return False
#
# def __getstate__(self):
# return self.wavelengths, self.ns
#
# def __setstate__(self, args):
# self.__init__(*args)
#
# def __hash__(self):
# return hash((
# "batoid.TableMedium", tuple(self.wavelengths), tuple(self.ns)
# ))
#
# def __repr__(self):
# return f"TableMedium({self.wavelengths!r}, {self.ns!r})"
, which may include functions, classes, or code. Output only the next line. | kbk7 = batoid.SumitaMedium([A0, A1, A2, A3, A4, A5]) |
Next line prediction: <|code_start|>
@timer
def test_ConstMedium():
rng = np.random.default_rng(5)
for i in range(100):
n = rng.uniform(1.0, 2.0)
const_medium = batoid.ConstMedium(n)
wavelengths = rng.uniform(300e-9, 1100e-9, size=100)
for w in wavelengths:
assert const_medium.getN(w) == n
np.testing.assert_array_equal(
const_medium.getN(wavelengths),
np.full_like(wavelengths, n)
)
do_pickle(const_medium)
@timer
def test_TableMedium():
rng = np.random.default_rng(57)
for i in range(100):
ws = np.linspace(300e-9, 1100e-9, 6)
ns = rng.uniform(1.0, 1.5, size=6)
<|code_end|>
. Use current file imports:
(from batoid.medium import SumitaMedium, TableMedium
from test_helpers import timer, do_pickle, all_obj_diff
import os
import numpy as np
import batoid)
and context including class names, function names, or small code snippets from other files:
# Path: batoid/medium.py
# class SumitaMedium(Medium):
# r"""A `Medium` with Sumita dispersion formula, also known as the Schott
# dispersion formula.
#
# The Sumita formula is
#
# .. math::
#
# n = \sqrt{A_0 + A_1 \lambda^2 + \sum_{i=2}^5 A_i \lambda^{-2 (i-1)}}
#
# where :math:`\lambda` is the vacuum wavelength in microns.
#
# Parameters
# ----------
# coefs: array of float
# Sumita coefficients (A0, A1, A2, A3, A4, A5)
# """
# def __init__(self, *args, **kwargs):
# if len(args) == 6:
# coefs = tuple(args)
# elif len(args) == 1:
# coefs = tuple(args[0])
# elif kwargs:
# coefs = tuple([
# kwargs[k] for k in ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']
# ])
# else:
# raise ValueError("Incorrect number of arguments")
# self.coefs = coefs
# self._medium = _batoid.CPPSumitaMedium(*coefs)
#
# def __eq__(self, rhs):
# if type(rhs) == type(self):
# return self.coefs == rhs.coefs
# return False
#
# def __getstate__(self):
# return self.coefs
#
# def __setstate__(self, coefs):
# self.coefs = coefs
# self._medium = _batoid.CPPSumitaMedium(*coefs)
#
# def __hash__(self):
# return hash(("batoid.SumitaMedium", self.coefs))
#
# def __repr__(self):
# return f"SumitaMedium({self.coefs})"
#
# class TableMedium(Medium):
# """A `Medium` with refractive index defined via a lookup table.
#
# Parameters
# ----------
# wavelengths : array of float
# Wavelengths in meters.
# ns : array of float
# Refractive indices.
# """
# def __init__(self, wavelengths, ns):
# self.wavelengths = np.array(wavelengths)
# self.ns = np.array(ns)
# self._medium = _batoid.CPPTableMedium(
# self.wavelengths.ctypes.data,
# self.ns.ctypes.data,
# len(self.wavelengths)
# )
#
# @classmethod
# def fromTxt(cls, filename, **kwargs):
# """Load a text file with refractive index information in it.
# The file should have two columns, the first with wavelength in microns,
# and the second with the corresponding refractive indices.
# """
# import os
# try:
# wavelength, n = np.loadtxt(filename, unpack=True, **kwargs)
# except IOError:
# import glob
# from . import datadir
# filenames = glob.glob(os.path.join(datadir, "**", "*.txt"))
# for candidate in filenames:
# if os.path.basename(candidate) == filename:
# wavelength, n = np.loadtxt(candidate, unpack=True, **kwargs)
# break
# else:
# raise FileNotFoundError(filename)
# return TableMedium(wavelength*1e-6, n)
#
# def __eq__(self, rhs):
# if type(rhs) == type(self):
# return (
# np.array_equal(self.wavelengths, rhs.wavelengths)
# and np.array_equal(self.ns, rhs.ns)
# )
# return False
#
# def __getstate__(self):
# return self.wavelengths, self.ns
#
# def __setstate__(self, args):
# self.__init__(*args)
#
# def __hash__(self):
# return hash((
# "batoid.TableMedium", tuple(self.wavelengths), tuple(self.ns)
# ))
#
# def __repr__(self):
# return f"TableMedium({self.wavelengths!r}, {self.ns!r})"
. Output only the next line. | table_medium = batoid.TableMedium(ws, ns) |
Given the following code snippet before the placeholder: <|code_start|>
@timer
def test_rSplit():
rng = np.random.default_rng(5)
for _ in range(100):
R = rng.normal(0.7, 0.8)
conic = rng.uniform(-2.0, 1.0)
ncoef = rng.integers(0, 5)
coefs = [rng.normal(0, 1e-10) for i in range(ncoef)]
asphere = batoid.Asphere(R, conic, coefs)
theta_x = rng.normal(0.0, 1e-8)
theta_y = rng.normal(0.0, 1e-8)
rays = batoid.RayVector.asPolar(
backDist=10.0, medium=batoid.Air(),
wavelength=500e-9, outer=0.25*R,
theta_x=theta_x, theta_y=theta_y,
nrad=10, naz=10
)
coating = batoid.SimpleCoating(0.9, 0.1)
reflectedRays = asphere.reflect(rays.copy(), coating=coating)
m1 = batoid.Air()
<|code_end|>
, predict the next line using imports from the current file:
from batoid.medium import ConstMedium
from batoid.optic import RefractiveInterface
from test_helpers import timer, rays_allclose
import batoid
import numpy as np
and context including class names, function names, and sometimes code from other files:
# Path: batoid/medium.py
# class ConstMedium(Medium):
# """A `Medium` with wavelength-independent refractive index.
#
# Parameters
# ----------
# n : float
# The refractive index.
# """
# def __init__(self, n):
# self.n = n
# self._medium = _batoid.CPPConstMedium(n)
#
# def __eq__(self, rhs):
# if type(rhs) == type(self):
# return self.n == rhs.n
# return False
#
# def __getstate__(self):
# return self.n
#
# def __setstate__(self, n):
# self.n = n
# self._medium = _batoid.CPPConstMedium(n)
#
# def __hash__(self):
# return hash(("batoid.ConstMedium", self.n))
#
# def __repr__(self):
# return f"ConstMedium({self.n})"
#
# Path: batoid/optic.py
# class RefractiveInterface(Interface):
# """Specialization for refractive interfaces.
#
# Rays will interact with this surface by refracting through it.
# """
# def __init__(self, *args, **kwargs):
# Interface.__init__(self, *args, **kwargs)
# self.forwardCoating = SimpleCoating(
# reflectivity=0.0, transmissivity=1.0
# )
# self.reverseCoating = SimpleCoating(
# reflectivity=0.0, transmissivity=1.0
# )
#
# def interact(self, rv, reverse=False):
# if reverse:
# m1, m2 = self.outMedium, self.inMedium
# else:
# m1, m2 = self.inMedium, self.outMedium
# return self.surface.refract(rv, m1, m2, coordSys=self.coordSys)
#
# def rSplit(self, rv, reverse=False):
# # always return in order: refracted, reflected
# if reverse:
# m1 = self.outMedium
# m2 = self.inMedium
# coating = self.forwardCoating
# else:
# m1 = self.inMedium
# m2 = self.outMedium
# coating = self.reverseCoating
#
# return self.surface.rSplit(rv, m1, m2, coating, coordSys=self.coordSys)
. Output only the next line. | m2 = batoid.ConstMedium(1.1) |
Based on the snippet: <|code_start|> asphere = batoid.Asphere(R, conic, coefs)
theta_x = rng.normal(0.0, 1e-8)
theta_y = rng.normal(0.0, 1e-8)
rays = batoid.RayVector.asPolar(
backDist=10.0, medium=batoid.Air(),
wavelength=500e-9, outer=0.25*R,
theta_x=theta_x, theta_y=theta_y,
nrad=10, naz=10
)
coating = batoid.SimpleCoating(0.9, 0.1)
reflectedRays = asphere.reflect(rays.copy(), coating=coating)
m1 = batoid.Air()
m2 = batoid.ConstMedium(1.1)
refractedRays = asphere.refract(rays.copy(), m1, m2, coating=coating)
refractedRays2, reflectedRays2 = asphere.rSplit(rays, m1, m2, coating)
rays_allclose(reflectedRays, reflectedRays2)
rays_allclose(refractedRays, refractedRays2)
@timer
def test_traceSplit_simple():
telescope = batoid.CompoundOptic(
name = "simple",
stopSurface=batoid.Interface(batoid.Plane()),
items = [
batoid.Lens(
name = "L1",
items = [
<|code_end|>
, predict the immediate next line with the help of imports:
from batoid.medium import ConstMedium
from batoid.optic import RefractiveInterface
from test_helpers import timer, rays_allclose
import batoid
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: batoid/medium.py
# class ConstMedium(Medium):
# """A `Medium` with wavelength-independent refractive index.
#
# Parameters
# ----------
# n : float
# The refractive index.
# """
# def __init__(self, n):
# self.n = n
# self._medium = _batoid.CPPConstMedium(n)
#
# def __eq__(self, rhs):
# if type(rhs) == type(self):
# return self.n == rhs.n
# return False
#
# def __getstate__(self):
# return self.n
#
# def __setstate__(self, n):
# self.n = n
# self._medium = _batoid.CPPConstMedium(n)
#
# def __hash__(self):
# return hash(("batoid.ConstMedium", self.n))
#
# def __repr__(self):
# return f"ConstMedium({self.n})"
#
# Path: batoid/optic.py
# class RefractiveInterface(Interface):
# """Specialization for refractive interfaces.
#
# Rays will interact with this surface by refracting through it.
# """
# def __init__(self, *args, **kwargs):
# Interface.__init__(self, *args, **kwargs)
# self.forwardCoating = SimpleCoating(
# reflectivity=0.0, transmissivity=1.0
# )
# self.reverseCoating = SimpleCoating(
# reflectivity=0.0, transmissivity=1.0
# )
#
# def interact(self, rv, reverse=False):
# if reverse:
# m1, m2 = self.outMedium, self.inMedium
# else:
# m1, m2 = self.inMedium, self.outMedium
# return self.surface.refract(rv, m1, m2, coordSys=self.coordSys)
#
# def rSplit(self, rv, reverse=False):
# # always return in order: refracted, reflected
# if reverse:
# m1 = self.outMedium
# m2 = self.inMedium
# coating = self.forwardCoating
# else:
# m1 = self.inMedium
# m2 = self.outMedium
# coating = self.reverseCoating
#
# return self.surface.rSplit(rv, m1, m2, coating, coordSys=self.coordSys)
. Output only the next line. | batoid.RefractiveInterface( |
Based on the snippet: <|code_start|> optic : batoid.Optic
Optical system
theta_x, theta_y : float
Field angle in radians
wavelength : float
Wavelength in meters
nrad : int, optional
Number of ray radii to use. (see RayVector.asPolar())
naz : int, optional
Approximate number of azimuthal angles in outermost ring. (see
RayVector.asPolar())
projection : {'postel', 'zemax', 'gnomonic', 'stereographic', 'lambert', 'orthographic'}
Projection used to convert field angle to direction cosines.
Returns
-------
dkdu : (2, 2), ndarray
Jacobian transformation matrix for converting between (kx, ky) of rays
impacting the focal plane and initial pupil plane coordinate.
"""
rays = batoid.RayVector.asPolar(
optic=optic, theta_x=theta_x, theta_y=theta_y, wavelength=wavelength,
projection=projection, nrad=nrad, naz=naz
)
ux = np.array(rays.x)
uy = np.array(rays.y)
optic.trace(rays)
w = ~rays.vignetted
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
import batoid
import galsim
import galsim
import galsim
import galsim
from .utils import bilinear_fit, fieldToDirCos
from numbers import Real
and context (classes, functions, sometimes code) from other files:
# Path: batoid/utils.py
# def bilinear_fit(ux, uy, kx, ky):
# a = np.empty((len(ux), 3), dtype=float)
# a[:,0] = 1
# a[:,1] = ux
# a[:,2] = uy
# b = np.empty((len(ux), 2), dtype=float)
# b[:,0] = kx
# b[:,1] = ky
# x, _, _, _ = np.linalg.lstsq(a, b, rcond=-1)
# return x
#
# def fieldToDirCos(u, v, projection='postel'):
# """Convert field angle to direction cosines using specified projection.
#
# Parameters
# ----------
# u, v : float
# Tangent plane coordinates in radians.
# projection : {'postel', 'zemax', 'gnomonic', 'stereographic', 'lambert', 'orthographic'}
# Projection used to convert field angle to direction cosines.
#
# Returns
# -------
# alpha, beta, gamma : float
# Direction cosines (unit vector projected onto x, y, z in order)
#
# Notes
# -----
# The tangent plane reference is at (u,v) = (0,0), which corresponds to
# (alpha, beta, gamma) = (0, 0, -1) (a ray coming directly from above). The
# orientation is such that vx (vy) is positive when u (v) is positive.
# """
# if projection == 'postel':
# return postelToDirCos(u, v)
# elif projection == 'zemax':
# return zemaxToDirCos(u, v)
# elif projection == 'gnomonic':
# return gnomonicToDirCos(u, v)
# elif projection == 'stereographic':
# return stereographicToDirCos(u, v)
# elif projection == 'lambert':
# return lambertToDirCos(u, v)
# elif projection == 'orthographic':
# return orthographicToDirCos(u, v)
# else:
# raise ValueError("Bad projection: {}".format(projection))
. Output only the next line. | soln = bilinear_fit(ux[w], uy[w], rays.kx[w], rays.ky[w]) |
Given snippet: <|code_start|> optic : batoid.Optic
Optical system
theta_x, theta_y : float
Field angle in radians
wavelength : float
Wavelength in meters
nrad : int, optional
Number of ray radii to use. (see RayVector.asPolar())
naz : int, optional
Approximate number of azimuthal angles in outermost ring. (see
RayVector.asPolar())
projection : {'postel', 'zemax', 'gnomonic', 'stereographic', 'lambert', 'orthographic'}
Projection used to convert field angle to direction cosines.
Returns
-------
drdth : (2, 2), ndarray
Jacobian transformation matrix for converting between (theta_x, theta_y)
and (x, y) on the focal plane.
Notes
-----
This is the Jacobian of pixels -> tangent plane, (and importantly, not
pixels -> ra/dec). It should be *close* to the inverse plate scale
though, especially near the center of the tangent plane projection.
"""
# We just use a finite difference approach here.
dth = 1e-5
# Make direction cosine vectors
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
import batoid
import galsim
import galsim
import galsim
import galsim
from .utils import bilinear_fit, fieldToDirCos
from numbers import Real
and context:
# Path: batoid/utils.py
# def bilinear_fit(ux, uy, kx, ky):
# a = np.empty((len(ux), 3), dtype=float)
# a[:,0] = 1
# a[:,1] = ux
# a[:,2] = uy
# b = np.empty((len(ux), 2), dtype=float)
# b[:,0] = kx
# b[:,1] = ky
# x, _, _, _ = np.linalg.lstsq(a, b, rcond=-1)
# return x
#
# def fieldToDirCos(u, v, projection='postel'):
# """Convert field angle to direction cosines using specified projection.
#
# Parameters
# ----------
# u, v : float
# Tangent plane coordinates in radians.
# projection : {'postel', 'zemax', 'gnomonic', 'stereographic', 'lambert', 'orthographic'}
# Projection used to convert field angle to direction cosines.
#
# Returns
# -------
# alpha, beta, gamma : float
# Direction cosines (unit vector projected onto x, y, z in order)
#
# Notes
# -----
# The tangent plane reference is at (u,v) = (0,0), which corresponds to
# (alpha, beta, gamma) = (0, 0, -1) (a ray coming directly from above). The
# orientation is such that vx (vy) is positive when u (v) is positive.
# """
# if projection == 'postel':
# return postelToDirCos(u, v)
# elif projection == 'zemax':
# return zemaxToDirCos(u, v)
# elif projection == 'gnomonic':
# return gnomonicToDirCos(u, v)
# elif projection == 'stereographic':
# return stereographicToDirCos(u, v)
# elif projection == 'lambert':
# return lambertToDirCos(u, v)
# elif projection == 'orthographic':
# return orthographicToDirCos(u, v)
# else:
# raise ValueError("Bad projection: {}".format(projection))
which might include code, classes, or functions. Output only the next line. | nominalCos = fieldToDirCos(theta_x, theta_y, projection=projection) |
Given snippet: <|code_start|>
class Repository(CaseClass):
def __init__(self, driver, group_id):
super(Repository, self).__init__(['driver', 'group_id', 'artifacts'])
self.driver = driver
self.group_id = group_id
self.artifacts = defaultdict(list)
def load(self, artifact_id):
"""
Load artifacts index for specified artifact id from storage
:param artifact_id: artifact id to load
:return: None
"""
s = self.driver.read_index(artifact_id)
xs = json.loads(s, encoding='utf-8') if s else []
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import logging
import sys
from copy import deepcopy
from collections import defaultdict
from .artifact import Artifact, BasicInfo
from .util import *
and context:
# Path: src/artifactcli/artifact/artifact.py
# class Artifact(BaseInfo):
# keys = ['basic_info', 'file_info', 'scm_info']
#
# def __init__(self, basic_info, file_info, scm_info=None):
# super(Artifact, self).__init__(Artifact.keys)
# self.basic_info = basic_info
# self.file_info = file_info
# self.scm_info = scm_info
#
# def __str__(self):
# buf = [self.basic_info, self.file_info] + ([self.scm_info] if self.scm_info else [])
# return '\n'.join(map(str, buf))
#
# def to_dict(self):
# ret = {
# 'basic_info': self.basic_info.to_dict(),
# 'file_info': self.file_info.to_dict(),
# }
# if self.scm_info:
# ret.update({'scm_info': self.scm_info.to_dict()})
# return ret
#
# @staticmethod
# def from_dict(d):
# bi = BasicInfo.from_dict(d['basic_info'])
# fi = FileInfo.from_dict(d['file_info'])
# si = None
# if 'scm_info' in d:
# if d['scm_info']['system'] == 'git':
# si = GitInfo.from_dict(d['scm_info'])
# return Artifact(bi, fi, si)
#
# @staticmethod
# def from_path(group_id, path):
# # revision will be set to None
# return Artifact(BasicInfo.from_path(group_id, path), FileInfo.from_path(path), GitInfo.from_path(path))
#
# Path: src/artifactcli/artifact/basicinfo.py
# class BasicInfo(BaseInfo):
# keys = ['group_id', 'artifact_id', 'version', 'packaging', 'revision']
#
# def __init__(self, group_id, artifact_id, version, packaging, revision):
# super(BasicInfo, self).__init__(BasicInfo.keys)
# self.group_id = group_id
# self.artifact_id = artifact_id
# self.version = version
# self.packaging = packaging
# self.revision = revision
#
# def __str__(self):
# buf = [
# 'Basic Info:',
# ' Group ID : %s' % self.group_id,
# ' Artifact ID: %s' % self.artifact_id,
# ' Version : %s' % self.version,
# ' Packaging : %s' % self.packaging,
# ' Revision : %s' % self.revision
# ]
# return '\n'.join(buf)
#
# def filename(self):
# return '%s-%s.%s' % (self.artifact_id, self.version, self.packaging)
#
# def s3_path(self):
# if self.revision is None:
# raise ValueError('Revision is not defined')
# else:
# xs = (str(x) for x in [self.group_id, self.artifact_id, self.version, self.revision, self.filename()])
# return '/'.join(xs)
#
# @staticmethod
# def from_dict(d):
# return BasicInfo(*[d[k] for k in BasicInfo.keys])
#
# @staticmethod
# def from_path(group_id, path, revision=None):
# basename = os.path.basename(path)
# prefix, extension = os.path.splitext(basename)
# extension = extension[1:] # remove dot
# tokens = reversed(prefix.split('-'))
#
# artifact_tokens = []
# version_tokens = []
# version_found = False
# for token in tokens:
# if version_found:
# artifact_tokens.append(token)
# else:
# version_tokens.append(token)
# if BasicInfo._is_version_like(token):
# version_found = True
#
# artifact_id = '-'.join(reversed(artifact_tokens))
# version = '-'.join(reversed(version_tokens))
#
# # validate values
# if not version_found:
# raise ValueError('Could not parse version from path: %s' % path)
# if not artifact_id:
# raise ValueError('Could not parse artifact id from path: %s' % path)
# if not extension:
# raise ValueError('Could not parse extension from path: %s' % path)
#
# return BasicInfo(group_id, artifact_id, version, extension, revision)
#
# @staticmethod
# def _is_version_like(s):
# return re.match("^[0-9]+(?:[.][0-9]+)*$", s) is not None
which might include code, classes, or functions. Output only the next line. | self.artifacts[artifact_id] = [Artifact.from_dict(x) for x in xs] |
Here is a snippet: <|code_start|> x.file_info.size_format(),
'%s' % x.file_info.mtime,
','.join(x.scm_info.tags) if x.scm_info else '',
x.scm_info.summary if x.scm_info else '',
] for x in arts]
column_len = [max([unicode_width(x) + 2 for x in xs]) for xs in zip(*([headers] + values))]
header_line = ' '.join(unicode_ljust(s, x) for s, x in zip(headers, column_len))
buf += [header_line, '-' * len(header_line)]
buf += (' '.join(unicode_ljust(s, x) for s, x in zip(v, column_len)) for v in values)
elif output == 'json':
buf.append(json.dumps([x.to_dict() for x in arts], ensure_ascii=False))
else:
raise ValueError('Unknown output format: %s' % output)
for line in buf:
fp.write(line + '\n')
def print_info(self, file_name, revision=None, output=None, fp=sys.stdout):
output = output or 'text'
art = self._get_artifact_from_path(file_name, revision)
if output == 'text':
s = str(art)
elif output == 'json':
s = json.dumps(art.to_dict(), ensure_ascii=False)
else:
raise ValueError('Unknown output format: %s' % output)
fp.write(s + '\n')
def _get_artifact_from_path(self, path, revision=None):
<|code_end|>
. Write the next line using the current file imports:
import json
import logging
import sys
from copy import deepcopy
from collections import defaultdict
from .artifact import Artifact, BasicInfo
from .util import *
and context from other files:
# Path: src/artifactcli/artifact/artifact.py
# class Artifact(BaseInfo):
# keys = ['basic_info', 'file_info', 'scm_info']
#
# def __init__(self, basic_info, file_info, scm_info=None):
# super(Artifact, self).__init__(Artifact.keys)
# self.basic_info = basic_info
# self.file_info = file_info
# self.scm_info = scm_info
#
# def __str__(self):
# buf = [self.basic_info, self.file_info] + ([self.scm_info] if self.scm_info else [])
# return '\n'.join(map(str, buf))
#
# def to_dict(self):
# ret = {
# 'basic_info': self.basic_info.to_dict(),
# 'file_info': self.file_info.to_dict(),
# }
# if self.scm_info:
# ret.update({'scm_info': self.scm_info.to_dict()})
# return ret
#
# @staticmethod
# def from_dict(d):
# bi = BasicInfo.from_dict(d['basic_info'])
# fi = FileInfo.from_dict(d['file_info'])
# si = None
# if 'scm_info' in d:
# if d['scm_info']['system'] == 'git':
# si = GitInfo.from_dict(d['scm_info'])
# return Artifact(bi, fi, si)
#
# @staticmethod
# def from_path(group_id, path):
# # revision will be set to None
# return Artifact(BasicInfo.from_path(group_id, path), FileInfo.from_path(path), GitInfo.from_path(path))
#
# Path: src/artifactcli/artifact/basicinfo.py
# class BasicInfo(BaseInfo):
# keys = ['group_id', 'artifact_id', 'version', 'packaging', 'revision']
#
# def __init__(self, group_id, artifact_id, version, packaging, revision):
# super(BasicInfo, self).__init__(BasicInfo.keys)
# self.group_id = group_id
# self.artifact_id = artifact_id
# self.version = version
# self.packaging = packaging
# self.revision = revision
#
# def __str__(self):
# buf = [
# 'Basic Info:',
# ' Group ID : %s' % self.group_id,
# ' Artifact ID: %s' % self.artifact_id,
# ' Version : %s' % self.version,
# ' Packaging : %s' % self.packaging,
# ' Revision : %s' % self.revision
# ]
# return '\n'.join(buf)
#
# def filename(self):
# return '%s-%s.%s' % (self.artifact_id, self.version, self.packaging)
#
# def s3_path(self):
# if self.revision is None:
# raise ValueError('Revision is not defined')
# else:
# xs = (str(x) for x in [self.group_id, self.artifact_id, self.version, self.revision, self.filename()])
# return '/'.join(xs)
#
# @staticmethod
# def from_dict(d):
# return BasicInfo(*[d[k] for k in BasicInfo.keys])
#
# @staticmethod
# def from_path(group_id, path, revision=None):
# basename = os.path.basename(path)
# prefix, extension = os.path.splitext(basename)
# extension = extension[1:] # remove dot
# tokens = reversed(prefix.split('-'))
#
# artifact_tokens = []
# version_tokens = []
# version_found = False
# for token in tokens:
# if version_found:
# artifact_tokens.append(token)
# else:
# version_tokens.append(token)
# if BasicInfo._is_version_like(token):
# version_found = True
#
# artifact_id = '-'.join(reversed(artifact_tokens))
# version = '-'.join(reversed(version_tokens))
#
# # validate values
# if not version_found:
# raise ValueError('Could not parse version from path: %s' % path)
# if not artifact_id:
# raise ValueError('Could not parse artifact id from path: %s' % path)
# if not extension:
# raise ValueError('Could not parse extension from path: %s' % path)
#
# return BasicInfo(group_id, artifact_id, version, extension, revision)
#
# @staticmethod
# def _is_version_like(s):
# return re.match("^[0-9]+(?:[.][0-9]+)*$", s) is not None
, which may include functions, classes, or code. Output only the next line. | bi = BasicInfo.from_path(self.group_id, path) |
Given the code snippet: <|code_start|>
initialize_empty_form = True
form_data = self.request.session.get(MULTISEEK_SESSION_KEY, {})
if form_data:
form_data = json.loads(form_data)
initialize_empty_form = False
js_init = registry.recreate_form(form_data)
js_removed = ",".join(
'"%(x)s"' % dict(x=x)
for x in self.request.session.get(MULTISEEK_SESSION_KEY_REMOVED, [])
)
return dict(
js_fields=js_fields,
js_ops=js_ops,
js_types=js_types,
js_autocompletes=js_autocompletes,
js_value_lists=js_value_lists,
js_and=AND,
js_or=OR,
js_init=js_init,
js_remove_message=LAST_FIELD_REMOVE_MESSAGE,
js_removed=js_removed,
user_allowed_to_save_forms=user_allowed_to_save_forms(self.request.user),
initialize_empty_form=initialize_empty_form,
order_boxes=registry.order_boxes,
ordering=registry.ordering,
report_types=registry.get_report_types(self.request),
saved_forms=SearchForm.objects.get_for_user(self.request.user),
MULTISEEK_ORDERING_PREFIX=MULTISEEK_ORDERING_PREFIX,
<|code_end|>
, generate the next line using the imports in this file:
import json
from builtins import str as text
from django import http, shortcuts
from django.db import transaction
from django.http import HttpResponseForbidden, HttpResponseNotFound
from django.http.response import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import gettext_lazy
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.generic import ListView, TemplateView
from multiseek.logic import MULTISEEK_REPORT_TYPE
from multiseek.models import SearchForm
from .logic import (
AND,
AUTOCOMPLETE,
MULTISEEK_ORDERING_PREFIX,
OR,
VALUE_LIST,
ParseError,
UnknownField,
UnknownOperation,
get_registry,
)
and context (functions, classes, or occasionally code) from other files:
# Path: multiseek/logic.py
# MULTISEEK_REPORT_TYPE = "_ms_report_type"
#
# Path: multiseek/models.py
# class SearchForm(models.Model):
# name = models.TextField(verbose_name=_("Name"), unique=True)
# owner = models.ForeignKey(settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE)
# public = models.BooleanField(
# verbose_name=_("Public"),
# default=False, help_text=_(
# "Make this search publicly available?"))
# data = models.TextField(verbose_name=_("Form data (JSON)"))
#
# objects = SearchFormManager()
#
# class Meta:
# ordering = ['name',]
#
# def __str__(self):
# return self.name
#
# Path: multiseek/logic.py
# AND = "and"
#
# AUTOCOMPLETE = "autocomplete"
#
# MULTISEEK_ORDERING_PREFIX = "order_"
#
# OR = "or"
#
# VALUE_LIST = "value-list"
#
# class ParseError(Exception):
# pass
#
# class UnknownField(Exception):
# pass
#
# class UnknownOperation(Exception):
# pass
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
. Output only the next line. | MULTISEEK_REPORT_TYPE=MULTISEEK_REPORT_TYPE, |
Predict the next line after this snippet: <|code_start|> )
)
initialize_empty_form = True
form_data = self.request.session.get(MULTISEEK_SESSION_KEY, {})
if form_data:
form_data = json.loads(form_data)
initialize_empty_form = False
js_init = registry.recreate_form(form_data)
js_removed = ",".join(
'"%(x)s"' % dict(x=x)
for x in self.request.session.get(MULTISEEK_SESSION_KEY_REMOVED, [])
)
return dict(
js_fields=js_fields,
js_ops=js_ops,
js_types=js_types,
js_autocompletes=js_autocompletes,
js_value_lists=js_value_lists,
js_and=AND,
js_or=OR,
js_init=js_init,
js_remove_message=LAST_FIELD_REMOVE_MESSAGE,
js_removed=js_removed,
user_allowed_to_save_forms=user_allowed_to_save_forms(self.request.user),
initialize_empty_form=initialize_empty_form,
order_boxes=registry.order_boxes,
ordering=registry.ordering,
report_types=registry.get_report_types(self.request),
<|code_end|>
using the current file's imports:
import json
from builtins import str as text
from django import http, shortcuts
from django.db import transaction
from django.http import HttpResponseForbidden, HttpResponseNotFound
from django.http.response import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import gettext_lazy
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.generic import ListView, TemplateView
from multiseek.logic import MULTISEEK_REPORT_TYPE
from multiseek.models import SearchForm
from .logic import (
AND,
AUTOCOMPLETE,
MULTISEEK_ORDERING_PREFIX,
OR,
VALUE_LIST,
ParseError,
UnknownField,
UnknownOperation,
get_registry,
)
and any relevant context from other files:
# Path: multiseek/logic.py
# MULTISEEK_REPORT_TYPE = "_ms_report_type"
#
# Path: multiseek/models.py
# class SearchForm(models.Model):
# name = models.TextField(verbose_name=_("Name"), unique=True)
# owner = models.ForeignKey(settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE)
# public = models.BooleanField(
# verbose_name=_("Public"),
# default=False, help_text=_(
# "Make this search publicly available?"))
# data = models.TextField(verbose_name=_("Form data (JSON)"))
#
# objects = SearchFormManager()
#
# class Meta:
# ordering = ['name',]
#
# def __str__(self):
# return self.name
#
# Path: multiseek/logic.py
# AND = "and"
#
# AUTOCOMPLETE = "autocomplete"
#
# MULTISEEK_ORDERING_PREFIX = "order_"
#
# OR = "or"
#
# VALUE_LIST = "value-list"
#
# class ParseError(Exception):
# pass
#
# class UnknownField(Exception):
# pass
#
# class UnknownOperation(Exception):
# pass
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
. Output only the next line. | saved_forms=SearchForm.objects.get_for_user(self.request.user), |
Given snippet: <|code_start|> if callable(values):
return values()
return values
js_value_lists = json.dumps(
dict(
[
(text(field.label), [text(x) for x in get_values(field.values)])
for field in registry.field_by_type(VALUE_LIST, self.request)
]
)
)
initialize_empty_form = True
form_data = self.request.session.get(MULTISEEK_SESSION_KEY, {})
if form_data:
form_data = json.loads(form_data)
initialize_empty_form = False
js_init = registry.recreate_form(form_data)
js_removed = ",".join(
'"%(x)s"' % dict(x=x)
for x in self.request.session.get(MULTISEEK_SESSION_KEY_REMOVED, [])
)
return dict(
js_fields=js_fields,
js_ops=js_ops,
js_types=js_types,
js_autocompletes=js_autocompletes,
js_value_lists=js_value_lists,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
from builtins import str as text
from django import http, shortcuts
from django.db import transaction
from django.http import HttpResponseForbidden, HttpResponseNotFound
from django.http.response import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import gettext_lazy
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.generic import ListView, TemplateView
from multiseek.logic import MULTISEEK_REPORT_TYPE
from multiseek.models import SearchForm
from .logic import (
AND,
AUTOCOMPLETE,
MULTISEEK_ORDERING_PREFIX,
OR,
VALUE_LIST,
ParseError,
UnknownField,
UnknownOperation,
get_registry,
)
and context:
# Path: multiseek/logic.py
# MULTISEEK_REPORT_TYPE = "_ms_report_type"
#
# Path: multiseek/models.py
# class SearchForm(models.Model):
# name = models.TextField(verbose_name=_("Name"), unique=True)
# owner = models.ForeignKey(settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE)
# public = models.BooleanField(
# verbose_name=_("Public"),
# default=False, help_text=_(
# "Make this search publicly available?"))
# data = models.TextField(verbose_name=_("Form data (JSON)"))
#
# objects = SearchFormManager()
#
# class Meta:
# ordering = ['name',]
#
# def __str__(self):
# return self.name
#
# Path: multiseek/logic.py
# AND = "and"
#
# AUTOCOMPLETE = "autocomplete"
#
# MULTISEEK_ORDERING_PREFIX = "order_"
#
# OR = "or"
#
# VALUE_LIST = "value-list"
#
# class ParseError(Exception):
# pass
#
# class UnknownField(Exception):
# pass
#
# class UnknownOperation(Exception):
# pass
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
which might include code, classes, or functions. Output only the next line. | js_and=AND, |
Given the code snippet: <|code_start|>def user_allowed_to_save_forms(user):
if hasattr(user, "is_staff"):
return user.is_staff
class MultiseekPageMixin:
registry = None
class MultiseekFormPage(MultiseekPageMixin, TemplateView):
"""
This view renders multiseek form and javascript required to manipulate
it.
"""
def get_context_data(self):
registry = get_registry(self.registry)
fields = registry.get_fields(self.request)
js_fields = json.dumps([text(x.label) for x in fields])
js_ops = json.dumps(
dict([(text(f.label), [text(x) for x in f.ops]) for f in fields])
)
js_types = json.dumps(dict([(text(f.label), f.type) for f in fields]))
js_autocompletes = json.dumps(
dict(
[
(text(field.label), reverse_or_just_url(field.get_url()))
<|code_end|>
, generate the next line using the imports in this file:
import json
from builtins import str as text
from django import http, shortcuts
from django.db import transaction
from django.http import HttpResponseForbidden, HttpResponseNotFound
from django.http.response import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import gettext_lazy
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.generic import ListView, TemplateView
from multiseek.logic import MULTISEEK_REPORT_TYPE
from multiseek.models import SearchForm
from .logic import (
AND,
AUTOCOMPLETE,
MULTISEEK_ORDERING_PREFIX,
OR,
VALUE_LIST,
ParseError,
UnknownField,
UnknownOperation,
get_registry,
)
and context (functions, classes, or occasionally code) from other files:
# Path: multiseek/logic.py
# MULTISEEK_REPORT_TYPE = "_ms_report_type"
#
# Path: multiseek/models.py
# class SearchForm(models.Model):
# name = models.TextField(verbose_name=_("Name"), unique=True)
# owner = models.ForeignKey(settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE)
# public = models.BooleanField(
# verbose_name=_("Public"),
# default=False, help_text=_(
# "Make this search publicly available?"))
# data = models.TextField(verbose_name=_("Form data (JSON)"))
#
# objects = SearchFormManager()
#
# class Meta:
# ordering = ['name',]
#
# def __str__(self):
# return self.name
#
# Path: multiseek/logic.py
# AND = "and"
#
# AUTOCOMPLETE = "autocomplete"
#
# MULTISEEK_ORDERING_PREFIX = "order_"
#
# OR = "or"
#
# VALUE_LIST = "value-list"
#
# class ParseError(Exception):
# pass
#
# class UnknownField(Exception):
# pass
#
# class UnknownOperation(Exception):
# pass
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
. Output only the next line. | for field in registry.field_by_type(AUTOCOMPLETE, self.request) |
Here is a snippet: <|code_start|> )
initialize_empty_form = True
form_data = self.request.session.get(MULTISEEK_SESSION_KEY, {})
if form_data:
form_data = json.loads(form_data)
initialize_empty_form = False
js_init = registry.recreate_form(form_data)
js_removed = ",".join(
'"%(x)s"' % dict(x=x)
for x in self.request.session.get(MULTISEEK_SESSION_KEY_REMOVED, [])
)
return dict(
js_fields=js_fields,
js_ops=js_ops,
js_types=js_types,
js_autocompletes=js_autocompletes,
js_value_lists=js_value_lists,
js_and=AND,
js_or=OR,
js_init=js_init,
js_remove_message=LAST_FIELD_REMOVE_MESSAGE,
js_removed=js_removed,
user_allowed_to_save_forms=user_allowed_to_save_forms(self.request.user),
initialize_empty_form=initialize_empty_form,
order_boxes=registry.order_boxes,
ordering=registry.ordering,
report_types=registry.get_report_types(self.request),
saved_forms=SearchForm.objects.get_for_user(self.request.user),
<|code_end|>
. Write the next line using the current file imports:
import json
from builtins import str as text
from django import http, shortcuts
from django.db import transaction
from django.http import HttpResponseForbidden, HttpResponseNotFound
from django.http.response import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import gettext_lazy
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.generic import ListView, TemplateView
from multiseek.logic import MULTISEEK_REPORT_TYPE
from multiseek.models import SearchForm
from .logic import (
AND,
AUTOCOMPLETE,
MULTISEEK_ORDERING_PREFIX,
OR,
VALUE_LIST,
ParseError,
UnknownField,
UnknownOperation,
get_registry,
)
and context from other files:
# Path: multiseek/logic.py
# MULTISEEK_REPORT_TYPE = "_ms_report_type"
#
# Path: multiseek/models.py
# class SearchForm(models.Model):
# name = models.TextField(verbose_name=_("Name"), unique=True)
# owner = models.ForeignKey(settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE)
# public = models.BooleanField(
# verbose_name=_("Public"),
# default=False, help_text=_(
# "Make this search publicly available?"))
# data = models.TextField(verbose_name=_("Form data (JSON)"))
#
# objects = SearchFormManager()
#
# class Meta:
# ordering = ['name',]
#
# def __str__(self):
# return self.name
#
# Path: multiseek/logic.py
# AND = "and"
#
# AUTOCOMPLETE = "autocomplete"
#
# MULTISEEK_ORDERING_PREFIX = "order_"
#
# OR = "or"
#
# VALUE_LIST = "value-list"
#
# class ParseError(Exception):
# pass
#
# class UnknownField(Exception):
# pass
#
# class UnknownOperation(Exception):
# pass
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
, which may include functions, classes, or code. Output only the next line. | MULTISEEK_ORDERING_PREFIX=MULTISEEK_ORDERING_PREFIX, |
Next line prediction: <|code_start|> return values()
return values
js_value_lists = json.dumps(
dict(
[
(text(field.label), [text(x) for x in get_values(field.values)])
for field in registry.field_by_type(VALUE_LIST, self.request)
]
)
)
initialize_empty_form = True
form_data = self.request.session.get(MULTISEEK_SESSION_KEY, {})
if form_data:
form_data = json.loads(form_data)
initialize_empty_form = False
js_init = registry.recreate_form(form_data)
js_removed = ",".join(
'"%(x)s"' % dict(x=x)
for x in self.request.session.get(MULTISEEK_SESSION_KEY_REMOVED, [])
)
return dict(
js_fields=js_fields,
js_ops=js_ops,
js_types=js_types,
js_autocompletes=js_autocompletes,
js_value_lists=js_value_lists,
js_and=AND,
<|code_end|>
. Use current file imports:
(import json
from builtins import str as text
from django import http, shortcuts
from django.db import transaction
from django.http import HttpResponseForbidden, HttpResponseNotFound
from django.http.response import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import gettext_lazy
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.generic import ListView, TemplateView
from multiseek.logic import MULTISEEK_REPORT_TYPE
from multiseek.models import SearchForm
from .logic import (
AND,
AUTOCOMPLETE,
MULTISEEK_ORDERING_PREFIX,
OR,
VALUE_LIST,
ParseError,
UnknownField,
UnknownOperation,
get_registry,
))
and context including class names, function names, or small code snippets from other files:
# Path: multiseek/logic.py
# MULTISEEK_REPORT_TYPE = "_ms_report_type"
#
# Path: multiseek/models.py
# class SearchForm(models.Model):
# name = models.TextField(verbose_name=_("Name"), unique=True)
# owner = models.ForeignKey(settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE)
# public = models.BooleanField(
# verbose_name=_("Public"),
# default=False, help_text=_(
# "Make this search publicly available?"))
# data = models.TextField(verbose_name=_("Form data (JSON)"))
#
# objects = SearchFormManager()
#
# class Meta:
# ordering = ['name',]
#
# def __str__(self):
# return self.name
#
# Path: multiseek/logic.py
# AND = "and"
#
# AUTOCOMPLETE = "autocomplete"
#
# MULTISEEK_ORDERING_PREFIX = "order_"
#
# OR = "or"
#
# VALUE_LIST = "value-list"
#
# class ParseError(Exception):
# pass
#
# class UnknownField(Exception):
# pass
#
# class UnknownOperation(Exception):
# pass
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
. Output only the next line. | js_or=OR, |
Predict the next line after this snippet: <|code_start|>
def get_context_data(self):
registry = get_registry(self.registry)
fields = registry.get_fields(self.request)
js_fields = json.dumps([text(x.label) for x in fields])
js_ops = json.dumps(
dict([(text(f.label), [text(x) for x in f.ops]) for f in fields])
)
js_types = json.dumps(dict([(text(f.label), f.type) for f in fields]))
js_autocompletes = json.dumps(
dict(
[
(text(field.label), reverse_or_just_url(field.get_url()))
for field in registry.field_by_type(AUTOCOMPLETE, self.request)
]
)
)
def get_values(values):
if callable(values):
return values()
return values
js_value_lists = json.dumps(
dict(
[
(text(field.label), [text(x) for x in get_values(field.values)])
<|code_end|>
using the current file's imports:
import json
from builtins import str as text
from django import http, shortcuts
from django.db import transaction
from django.http import HttpResponseForbidden, HttpResponseNotFound
from django.http.response import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import gettext_lazy
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.generic import ListView, TemplateView
from multiseek.logic import MULTISEEK_REPORT_TYPE
from multiseek.models import SearchForm
from .logic import (
AND,
AUTOCOMPLETE,
MULTISEEK_ORDERING_PREFIX,
OR,
VALUE_LIST,
ParseError,
UnknownField,
UnknownOperation,
get_registry,
)
and any relevant context from other files:
# Path: multiseek/logic.py
# MULTISEEK_REPORT_TYPE = "_ms_report_type"
#
# Path: multiseek/models.py
# class SearchForm(models.Model):
# name = models.TextField(verbose_name=_("Name"), unique=True)
# owner = models.ForeignKey(settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE)
# public = models.BooleanField(
# verbose_name=_("Public"),
# default=False, help_text=_(
# "Make this search publicly available?"))
# data = models.TextField(verbose_name=_("Form data (JSON)"))
#
# objects = SearchFormManager()
#
# class Meta:
# ordering = ['name',]
#
# def __str__(self):
# return self.name
#
# Path: multiseek/logic.py
# AND = "and"
#
# AUTOCOMPLETE = "autocomplete"
#
# MULTISEEK_ORDERING_PREFIX = "order_"
#
# OR = "or"
#
# VALUE_LIST = "value-list"
#
# class ParseError(Exception):
# pass
#
# class UnknownField(Exception):
# pass
#
# class UnknownOperation(Exception):
# pass
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
. Output only the next line. | for field in registry.field_by_type(VALUE_LIST, self.request) |
Given snippet: <|code_start|>
def convert_context_to_json(self, context):
return json.dumps(context)
class MultiseekSaveForm(MultiseekPageMixin, JSONResponseMixin, TemplateView):
def get(self, request, *args, **kw):
if not user_allowed_to_save_forms(request.user):
return HttpResponseForbidden()
return super(MultiseekSaveForm, self).get(request, *args, **kw)
post = get
@transaction.atomic
def get_context_data(self):
_json = self.request.POST.get("json")
name = self.request.POST.get("name")
public = self.request.POST.get("public") == "true"
overwrite = self.request.POST.get("overwrite") == "true"
if not _json:
return dict(result=text(ERR_NO_FORM_DATA))
try:
json.loads(_json)
except ValueError:
return dict(result=text(ERR_PARSING_DATA))
try:
get_registry(self.registry).recreate_form(json.loads(_json))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
from builtins import str as text
from django import http, shortcuts
from django.db import transaction
from django.http import HttpResponseForbidden, HttpResponseNotFound
from django.http.response import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import gettext_lazy
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.generic import ListView, TemplateView
from multiseek.logic import MULTISEEK_REPORT_TYPE
from multiseek.models import SearchForm
from .logic import (
AND,
AUTOCOMPLETE,
MULTISEEK_ORDERING_PREFIX,
OR,
VALUE_LIST,
ParseError,
UnknownField,
UnknownOperation,
get_registry,
)
and context:
# Path: multiseek/logic.py
# MULTISEEK_REPORT_TYPE = "_ms_report_type"
#
# Path: multiseek/models.py
# class SearchForm(models.Model):
# name = models.TextField(verbose_name=_("Name"), unique=True)
# owner = models.ForeignKey(settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE)
# public = models.BooleanField(
# verbose_name=_("Public"),
# default=False, help_text=_(
# "Make this search publicly available?"))
# data = models.TextField(verbose_name=_("Form data (JSON)"))
#
# objects = SearchFormManager()
#
# class Meta:
# ordering = ['name',]
#
# def __str__(self):
# return self.name
#
# Path: multiseek/logic.py
# AND = "and"
#
# AUTOCOMPLETE = "autocomplete"
#
# MULTISEEK_ORDERING_PREFIX = "order_"
#
# OR = "or"
#
# VALUE_LIST = "value-list"
#
# class ParseError(Exception):
# pass
#
# class UnknownField(Exception):
# pass
#
# class UnknownOperation(Exception):
# pass
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
which might include code, classes, or functions. Output only the next line. | except (TypeError, UnknownField, ParseError, UnknownOperation): |
Here is a snippet: <|code_start|>
def convert_context_to_json(self, context):
return json.dumps(context)
class MultiseekSaveForm(MultiseekPageMixin, JSONResponseMixin, TemplateView):
def get(self, request, *args, **kw):
if not user_allowed_to_save_forms(request.user):
return HttpResponseForbidden()
return super(MultiseekSaveForm, self).get(request, *args, **kw)
post = get
@transaction.atomic
def get_context_data(self):
_json = self.request.POST.get("json")
name = self.request.POST.get("name")
public = self.request.POST.get("public") == "true"
overwrite = self.request.POST.get("overwrite") == "true"
if not _json:
return dict(result=text(ERR_NO_FORM_DATA))
try:
json.loads(_json)
except ValueError:
return dict(result=text(ERR_PARSING_DATA))
try:
get_registry(self.registry).recreate_form(json.loads(_json))
<|code_end|>
. Write the next line using the current file imports:
import json
from builtins import str as text
from django import http, shortcuts
from django.db import transaction
from django.http import HttpResponseForbidden, HttpResponseNotFound
from django.http.response import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import gettext_lazy
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.generic import ListView, TemplateView
from multiseek.logic import MULTISEEK_REPORT_TYPE
from multiseek.models import SearchForm
from .logic import (
AND,
AUTOCOMPLETE,
MULTISEEK_ORDERING_PREFIX,
OR,
VALUE_LIST,
ParseError,
UnknownField,
UnknownOperation,
get_registry,
)
and context from other files:
# Path: multiseek/logic.py
# MULTISEEK_REPORT_TYPE = "_ms_report_type"
#
# Path: multiseek/models.py
# class SearchForm(models.Model):
# name = models.TextField(verbose_name=_("Name"), unique=True)
# owner = models.ForeignKey(settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE)
# public = models.BooleanField(
# verbose_name=_("Public"),
# default=False, help_text=_(
# "Make this search publicly available?"))
# data = models.TextField(verbose_name=_("Form data (JSON)"))
#
# objects = SearchFormManager()
#
# class Meta:
# ordering = ['name',]
#
# def __str__(self):
# return self.name
#
# Path: multiseek/logic.py
# AND = "and"
#
# AUTOCOMPLETE = "autocomplete"
#
# MULTISEEK_ORDERING_PREFIX = "order_"
#
# OR = "or"
#
# VALUE_LIST = "value-list"
#
# class ParseError(Exception):
# pass
#
# class UnknownField(Exception):
# pass
#
# class UnknownOperation(Exception):
# pass
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
, which may include functions, classes, or code. Output only the next line. | except (TypeError, UnknownField, ParseError, UnknownOperation): |
Given snippet: <|code_start|>
def convert_context_to_json(self, context):
return json.dumps(context)
class MultiseekSaveForm(MultiseekPageMixin, JSONResponseMixin, TemplateView):
def get(self, request, *args, **kw):
if not user_allowed_to_save_forms(request.user):
return HttpResponseForbidden()
return super(MultiseekSaveForm, self).get(request, *args, **kw)
post = get
@transaction.atomic
def get_context_data(self):
_json = self.request.POST.get("json")
name = self.request.POST.get("name")
public = self.request.POST.get("public") == "true"
overwrite = self.request.POST.get("overwrite") == "true"
if not _json:
return dict(result=text(ERR_NO_FORM_DATA))
try:
json.loads(_json)
except ValueError:
return dict(result=text(ERR_PARSING_DATA))
try:
get_registry(self.registry).recreate_form(json.loads(_json))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
from builtins import str as text
from django import http, shortcuts
from django.db import transaction
from django.http import HttpResponseForbidden, HttpResponseNotFound
from django.http.response import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import gettext_lazy
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.generic import ListView, TemplateView
from multiseek.logic import MULTISEEK_REPORT_TYPE
from multiseek.models import SearchForm
from .logic import (
AND,
AUTOCOMPLETE,
MULTISEEK_ORDERING_PREFIX,
OR,
VALUE_LIST,
ParseError,
UnknownField,
UnknownOperation,
get_registry,
)
and context:
# Path: multiseek/logic.py
# MULTISEEK_REPORT_TYPE = "_ms_report_type"
#
# Path: multiseek/models.py
# class SearchForm(models.Model):
# name = models.TextField(verbose_name=_("Name"), unique=True)
# owner = models.ForeignKey(settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE)
# public = models.BooleanField(
# verbose_name=_("Public"),
# default=False, help_text=_(
# "Make this search publicly available?"))
# data = models.TextField(verbose_name=_("Form data (JSON)"))
#
# objects = SearchFormManager()
#
# class Meta:
# ordering = ['name',]
#
# def __str__(self):
# return self.name
#
# Path: multiseek/logic.py
# AND = "and"
#
# AUTOCOMPLETE = "autocomplete"
#
# MULTISEEK_ORDERING_PREFIX = "order_"
#
# OR = "or"
#
# VALUE_LIST = "value-list"
#
# class ParseError(Exception):
# pass
#
# class UnknownField(Exception):
# pass
#
# class UnknownOperation(Exception):
# pass
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
which might include code, classes, or functions. Output only the next line. | except (TypeError, UnknownField, ParseError, UnknownOperation): |
Using the snippet: <|code_start|>
MULTISEEK_SESSION_KEY = "multiseek_json"
MULTISEEK_SESSION_KEY_REMOVED = "multiseek_json_removed"
def reverse_or_just_url(s):
if s.startswith("/"):
return s
return reverse(s)
LAST_FIELD_REMOVE_MESSAGE = _("The ability to remove the last field has been disabled.")
def user_allowed_to_save_forms(user):
if hasattr(user, "is_staff"):
return user.is_staff
class MultiseekPageMixin:
registry = None
class MultiseekFormPage(MultiseekPageMixin, TemplateView):
"""
This view renders multiseek form and javascript required to manipulate
it.
"""
def get_context_data(self):
<|code_end|>
, determine the next line of code. You have imports:
import json
from builtins import str as text
from django import http, shortcuts
from django.db import transaction
from django.http import HttpResponseForbidden, HttpResponseNotFound
from django.http.response import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import gettext_lazy
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.generic import ListView, TemplateView
from multiseek.logic import MULTISEEK_REPORT_TYPE
from multiseek.models import SearchForm
from .logic import (
AND,
AUTOCOMPLETE,
MULTISEEK_ORDERING_PREFIX,
OR,
VALUE_LIST,
ParseError,
UnknownField,
UnknownOperation,
get_registry,
)
and context (class names, function names, or code) available:
# Path: multiseek/logic.py
# MULTISEEK_REPORT_TYPE = "_ms_report_type"
#
# Path: multiseek/models.py
# class SearchForm(models.Model):
# name = models.TextField(verbose_name=_("Name"), unique=True)
# owner = models.ForeignKey(settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE)
# public = models.BooleanField(
# verbose_name=_("Public"),
# default=False, help_text=_(
# "Make this search publicly available?"))
# data = models.TextField(verbose_name=_("Form data (JSON)"))
#
# objects = SearchFormManager()
#
# class Meta:
# ordering = ['name',]
#
# def __str__(self):
# return self.name
#
# Path: multiseek/logic.py
# AND = "and"
#
# AUTOCOMPLETE = "autocomplete"
#
# MULTISEEK_ORDERING_PREFIX = "order_"
#
# OR = "or"
#
# VALUE_LIST = "value-list"
#
# class ParseError(Exception):
# pass
#
# class UnknownField(Exception):
# pass
#
# class UnknownOperation(Exception):
# pass
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
. Output only the next line. | registry = get_registry(self.registry) |
Next line prediction: <|code_start|># -*- encoding: utf-8 -*-
class TestModels(TransactionTestCase):
def test_search_form_manager(self):
u = baker.make(User)
<|code_end|>
. Use current file imports:
(from django.contrib.auth.models import AnonymousUser, User
from django.test import TransactionTestCase
from multiseek.models import SearchForm
from model_bakery import baker)
and context including class names, function names, or small code snippets from other files:
# Path: multiseek/models.py
# class SearchForm(models.Model):
# name = models.TextField(verbose_name=_("Name"), unique=True)
# owner = models.ForeignKey(settings.AUTH_USER_MODEL,
# on_delete=models.CASCADE)
# public = models.BooleanField(
# verbose_name=_("Public"),
# default=False, help_text=_(
# "Make this search publicly available?"))
# data = models.TextField(verbose_name=_("Form data (JSON)"))
#
# objects = SearchFormManager()
#
# class Meta:
# ordering = ['name',]
#
# def __str__(self):
# return self.name
. Output only the next line. | s1 = baker.make(SearchForm, owner=u, public=False, name='A') |
Given the following code snippet before the placeholder: <|code_start|> Zwracana wartość słownika 'value' może być różna dla różnych typów
pól (np dla multiseek.logic.RANGE jest to lista z wartościami z obu pól)
"""
ret = {}
for elem in ['type', 'op', 'prev-op', 'close-button']:
try:
e = element.find_by_id(elem, wait_time=0)[0]
except ElementDoesNotExist as x:
# prev-op may be None
if elem != 'prev-op':
raise x
e = None
ret[elem] = e
selected = ret['type'].value
ret['selected'] = selected
inner_type = self.registry.field_by_name.get(selected).type
ret['inner_type'] = inner_type
if inner_type in [STRING, VALUE_LIST]:
ret['value_widget'] = element.find_by_id("value")
elif inner_type == RANGE:
ret['value_widget'] = [
element.find_by_id("value_min"),
element.find_by_id("value_max")]
<|code_end|>
, predict the next line using imports from the current file:
import json
import pytest
import datetime
from django.conf import settings
from django.urls import reverse
from model_bakery import baker
from selenium.webdriver.support.expected_conditions import staleness_of, \
alert_is_present
from selenium.webdriver.support.ui import WebDriverWait
from splinter.exceptions import ElementDoesNotExist
from multiseek.logic import DATE, AUTOCOMPLETE, RANGE, STRING, VALUE_LIST, \
get_registry
from .models import Language, Author, Book
from builtins import str as text
from django.utils.translation import gettext_lazy as _
from .testutil import wait_for_page_load
and context including class names, function names, and sometimes code from other files:
# Path: multiseek/logic.py
# DATE = "date"
#
# AUTOCOMPLETE = "autocomplete"
#
# RANGE = "range"
#
# STRING = "string"
#
# VALUE_LIST = "value-list"
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
#
# Path: test_project/test_app/models.py
# class Language(models.Model):
# name = models.TextField()
# description = models.TextField()
#
# def __str__(self):
# return self.name
#
# class Author(models.Model):
# last_name = models.TextField()
# first_name = models.TextField()
#
# def __str__(self):
# return u"%s %s" % (self.first_name, self.last_name)
#
# class Book(models.Model):
# title = models.TextField()
# year = models.IntegerField()
# language = models.ForeignKey(Language, on_delete=models.CASCADE)
# authors = models.ManyToManyField(Author)
# no_editors = models.IntegerField()
# last_updated = models.DateField(auto_now=True)
# available = models.BooleanField(default=False)
#
# def __str__(self):
# return u"%s by %s" % (self.title, u", ".join(
# [str(author) for author in self.authors.all()]))
#
# Path: test_project/test_app/testutil.py
# class wait_for_page_load(object):
# def __init__(self, browser):
# self.browser = browser
#
# def __enter__(self):
# self.old_page = self.browser.find_by_tag("html")[0]._element
#
# def __exit__(self, *_):
# WebDriverWait(self.browser, 10).until(
# lambda driver: staleness_of(self.old_page)
# )
. Output only the next line. | elif inner_type == DATE: |
Continue the code snippet: <|code_start|> for elem in ['type', 'op', 'prev-op', 'close-button']:
try:
e = element.find_by_id(elem, wait_time=0)[0]
except ElementDoesNotExist as x:
# prev-op may be None
if elem != 'prev-op':
raise x
e = None
ret[elem] = e
selected = ret['type'].value
ret['selected'] = selected
inner_type = self.registry.field_by_name.get(selected).type
ret['inner_type'] = inner_type
if inner_type in [STRING, VALUE_LIST]:
ret['value_widget'] = element.find_by_id("value")
elif inner_type == RANGE:
ret['value_widget'] = [
element.find_by_id("value_min"),
element.find_by_id("value_max")]
elif inner_type == DATE:
ret['value_widget'] = [
element.find_by_id("value"),
element.find_by_id("value_max")]
<|code_end|>
. Use current file imports:
import json
import pytest
import datetime
from django.conf import settings
from django.urls import reverse
from model_bakery import baker
from selenium.webdriver.support.expected_conditions import staleness_of, \
alert_is_present
from selenium.webdriver.support.ui import WebDriverWait
from splinter.exceptions import ElementDoesNotExist
from multiseek.logic import DATE, AUTOCOMPLETE, RANGE, STRING, VALUE_LIST, \
get_registry
from .models import Language, Author, Book
from builtins import str as text
from django.utils.translation import gettext_lazy as _
from .testutil import wait_for_page_load
and context (classes, functions, or code) from other files:
# Path: multiseek/logic.py
# DATE = "date"
#
# AUTOCOMPLETE = "autocomplete"
#
# RANGE = "range"
#
# STRING = "string"
#
# VALUE_LIST = "value-list"
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
#
# Path: test_project/test_app/models.py
# class Language(models.Model):
# name = models.TextField()
# description = models.TextField()
#
# def __str__(self):
# return self.name
#
# class Author(models.Model):
# last_name = models.TextField()
# first_name = models.TextField()
#
# def __str__(self):
# return u"%s %s" % (self.first_name, self.last_name)
#
# class Book(models.Model):
# title = models.TextField()
# year = models.IntegerField()
# language = models.ForeignKey(Language, on_delete=models.CASCADE)
# authors = models.ManyToManyField(Author)
# no_editors = models.IntegerField()
# last_updated = models.DateField(auto_now=True)
# available = models.BooleanField(default=False)
#
# def __str__(self):
# return u"%s by %s" % (self.title, u", ".join(
# [str(author) for author in self.authors.all()]))
#
# Path: test_project/test_app/testutil.py
# class wait_for_page_load(object):
# def __init__(self, browser):
# self.browser = browser
#
# def __enter__(self):
# self.old_page = self.browser.find_by_tag("html")[0]._element
#
# def __exit__(self, *_):
# WebDriverWait(self.browser, 10).until(
# lambda driver: staleness_of(self.old_page)
# )
. Output only the next line. | elif inner_type == AUTOCOMPLETE: |
Next line prediction: <|code_start|> następna operacja, przycisk zamknięcia
Z pomocniczych wartości, zwracanych w słowniku mamy 'type' czyli
tekstowy typ, odpowiadający definicjom w bpp.multiseek.logic.fields.keys()
Zwracana wartość słownika 'value' może być różna dla różnych typów
pól (np dla multiseek.logic.RANGE jest to lista z wartościami z obu pól)
"""
ret = {}
for elem in ['type', 'op', 'prev-op', 'close-button']:
try:
e = element.find_by_id(elem, wait_time=0)[0]
except ElementDoesNotExist as x:
# prev-op may be None
if elem != 'prev-op':
raise x
e = None
ret[elem] = e
selected = ret['type'].value
ret['selected'] = selected
inner_type = self.registry.field_by_name.get(selected).type
ret['inner_type'] = inner_type
if inner_type in [STRING, VALUE_LIST]:
ret['value_widget'] = element.find_by_id("value")
<|code_end|>
. Use current file imports:
(import json
import pytest
import datetime
from django.conf import settings
from django.urls import reverse
from model_bakery import baker
from selenium.webdriver.support.expected_conditions import staleness_of, \
alert_is_present
from selenium.webdriver.support.ui import WebDriverWait
from splinter.exceptions import ElementDoesNotExist
from multiseek.logic import DATE, AUTOCOMPLETE, RANGE, STRING, VALUE_LIST, \
get_registry
from .models import Language, Author, Book
from builtins import str as text
from django.utils.translation import gettext_lazy as _
from .testutil import wait_for_page_load)
and context including class names, function names, or small code snippets from other files:
# Path: multiseek/logic.py
# DATE = "date"
#
# AUTOCOMPLETE = "autocomplete"
#
# RANGE = "range"
#
# STRING = "string"
#
# VALUE_LIST = "value-list"
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
#
# Path: test_project/test_app/models.py
# class Language(models.Model):
# name = models.TextField()
# description = models.TextField()
#
# def __str__(self):
# return self.name
#
# class Author(models.Model):
# last_name = models.TextField()
# first_name = models.TextField()
#
# def __str__(self):
# return u"%s %s" % (self.first_name, self.last_name)
#
# class Book(models.Model):
# title = models.TextField()
# year = models.IntegerField()
# language = models.ForeignKey(Language, on_delete=models.CASCADE)
# authors = models.ManyToManyField(Author)
# no_editors = models.IntegerField()
# last_updated = models.DateField(auto_now=True)
# available = models.BooleanField(default=False)
#
# def __str__(self):
# return u"%s by %s" % (self.title, u", ".join(
# [str(author) for author in self.authors.all()]))
#
# Path: test_project/test_app/testutil.py
# class wait_for_page_load(object):
# def __init__(self, browser):
# self.browser = browser
#
# def __enter__(self):
# self.old_page = self.browser.find_by_tag("html")[0]._element
#
# def __exit__(self, *_):
# WebDriverWait(self.browser, 10).until(
# lambda driver: staleness_of(self.old_page)
# )
. Output only the next line. | elif inner_type == RANGE: |
Predict the next line for this snippet: <|code_start|> formularzu. Pole - czyli wiersz z kolejnymi selectami:
pole przeszukiwane, operacja, wartość wyszukiwana,
następna operacja, przycisk zamknięcia
Z pomocniczych wartości, zwracanych w słowniku mamy 'type' czyli
tekstowy typ, odpowiadający definicjom w bpp.multiseek.logic.fields.keys()
Zwracana wartość słownika 'value' może być różna dla różnych typów
pól (np dla multiseek.logic.RANGE jest to lista z wartościami z obu pól)
"""
ret = {}
for elem in ['type', 'op', 'prev-op', 'close-button']:
try:
e = element.find_by_id(elem, wait_time=0)[0]
except ElementDoesNotExist as x:
# prev-op may be None
if elem != 'prev-op':
raise x
e = None
ret[elem] = e
selected = ret['type'].value
ret['selected'] = selected
inner_type = self.registry.field_by_name.get(selected).type
ret['inner_type'] = inner_type
<|code_end|>
with the help of current file imports:
import json
import pytest
import datetime
from django.conf import settings
from django.urls import reverse
from model_bakery import baker
from selenium.webdriver.support.expected_conditions import staleness_of, \
alert_is_present
from selenium.webdriver.support.ui import WebDriverWait
from splinter.exceptions import ElementDoesNotExist
from multiseek.logic import DATE, AUTOCOMPLETE, RANGE, STRING, VALUE_LIST, \
get_registry
from .models import Language, Author, Book
from builtins import str as text
from django.utils.translation import gettext_lazy as _
from .testutil import wait_for_page_load
and context from other files:
# Path: multiseek/logic.py
# DATE = "date"
#
# AUTOCOMPLETE = "autocomplete"
#
# RANGE = "range"
#
# STRING = "string"
#
# VALUE_LIST = "value-list"
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
#
# Path: test_project/test_app/models.py
# class Language(models.Model):
# name = models.TextField()
# description = models.TextField()
#
# def __str__(self):
# return self.name
#
# class Author(models.Model):
# last_name = models.TextField()
# first_name = models.TextField()
#
# def __str__(self):
# return u"%s %s" % (self.first_name, self.last_name)
#
# class Book(models.Model):
# title = models.TextField()
# year = models.IntegerField()
# language = models.ForeignKey(Language, on_delete=models.CASCADE)
# authors = models.ManyToManyField(Author)
# no_editors = models.IntegerField()
# last_updated = models.DateField(auto_now=True)
# available = models.BooleanField(default=False)
#
# def __str__(self):
# return u"%s by %s" % (self.title, u", ".join(
# [str(author) for author in self.authors.all()]))
#
# Path: test_project/test_app/testutil.py
# class wait_for_page_load(object):
# def __init__(self, browser):
# self.browser = browser
#
# def __enter__(self):
# self.old_page = self.browser.find_by_tag("html")[0]._element
#
# def __exit__(self, *_):
# WebDriverWait(self.browser, 10).until(
# lambda driver: staleness_of(self.old_page)
# )
, which may contain function names, class names, or code. Output only the next line. | if inner_type in [STRING, VALUE_LIST]: |
Predict the next line after this snippet: <|code_start|> formularzu. Pole - czyli wiersz z kolejnymi selectami:
pole przeszukiwane, operacja, wartość wyszukiwana,
następna operacja, przycisk zamknięcia
Z pomocniczych wartości, zwracanych w słowniku mamy 'type' czyli
tekstowy typ, odpowiadający definicjom w bpp.multiseek.logic.fields.keys()
Zwracana wartość słownika 'value' może być różna dla różnych typów
pól (np dla multiseek.logic.RANGE jest to lista z wartościami z obu pól)
"""
ret = {}
for elem in ['type', 'op', 'prev-op', 'close-button']:
try:
e = element.find_by_id(elem, wait_time=0)[0]
except ElementDoesNotExist as x:
# prev-op may be None
if elem != 'prev-op':
raise x
e = None
ret[elem] = e
selected = ret['type'].value
ret['selected'] = selected
inner_type = self.registry.field_by_name.get(selected).type
ret['inner_type'] = inner_type
<|code_end|>
using the current file's imports:
import json
import pytest
import datetime
from django.conf import settings
from django.urls import reverse
from model_bakery import baker
from selenium.webdriver.support.expected_conditions import staleness_of, \
alert_is_present
from selenium.webdriver.support.ui import WebDriverWait
from splinter.exceptions import ElementDoesNotExist
from multiseek.logic import DATE, AUTOCOMPLETE, RANGE, STRING, VALUE_LIST, \
get_registry
from .models import Language, Author, Book
from builtins import str as text
from django.utils.translation import gettext_lazy as _
from .testutil import wait_for_page_load
and any relevant context from other files:
# Path: multiseek/logic.py
# DATE = "date"
#
# AUTOCOMPLETE = "autocomplete"
#
# RANGE = "range"
#
# STRING = "string"
#
# VALUE_LIST = "value-list"
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
#
# Path: test_project/test_app/models.py
# class Language(models.Model):
# name = models.TextField()
# description = models.TextField()
#
# def __str__(self):
# return self.name
#
# class Author(models.Model):
# last_name = models.TextField()
# first_name = models.TextField()
#
# def __str__(self):
# return u"%s %s" % (self.first_name, self.last_name)
#
# class Book(models.Model):
# title = models.TextField()
# year = models.IntegerField()
# language = models.ForeignKey(Language, on_delete=models.CASCADE)
# authors = models.ManyToManyField(Author)
# no_editors = models.IntegerField()
# last_updated = models.DateField(auto_now=True)
# available = models.BooleanField(default=False)
#
# def __str__(self):
# return u"%s by %s" % (self.title, u", ".join(
# [str(author) for author in self.authors.all()]))
#
# Path: test_project/test_app/testutil.py
# class wait_for_page_load(object):
# def __init__(self, browser):
# self.browser = browser
#
# def __enter__(self):
# self.old_page = self.browser.find_by_tag("html")[0]._element
#
# def __exit__(self, *_):
# WebDriverWait(self.browser, 10).until(
# lambda driver: staleness_of(self.old_page)
# )
. Output only the next line. | if inner_type in [STRING, VALUE_LIST]: |
Next line prediction: <|code_start|> self.click_save_button()
WebDriverWait(self.browser, 10).until(alert_is_present())
alert = self.browser.driver.switch_to.alert
alert.fill_with(name)
alert.accept()
WebDriverWait(self.browser, 10).until_not(alert_is_present())
def count_elements_in_form_selector(self, name):
select = self.browser.find_by_id("formsSelector")
assert select.visible == True
passed = 0
for option in select.find_by_tag("option"):
if option.text == name:
passed += 1
return passed
def accept_alert(self):
with self.browser.get_alert() as alert:
alert.accept()
def dismiss_alert(self):
with self.browser.get_alert() as alert:
alert.dismiss()
@pytest.fixture
def multiseek_page(browser, live_server, initial_data):
browser.visit(live_server + reverse('multiseek:index'))
<|code_end|>
. Use current file imports:
(import json
import pytest
import datetime
from django.conf import settings
from django.urls import reverse
from model_bakery import baker
from selenium.webdriver.support.expected_conditions import staleness_of, \
alert_is_present
from selenium.webdriver.support.ui import WebDriverWait
from splinter.exceptions import ElementDoesNotExist
from multiseek.logic import DATE, AUTOCOMPLETE, RANGE, STRING, VALUE_LIST, \
get_registry
from .models import Language, Author, Book
from builtins import str as text
from django.utils.translation import gettext_lazy as _
from .testutil import wait_for_page_load)
and context including class names, function names, or small code snippets from other files:
# Path: multiseek/logic.py
# DATE = "date"
#
# AUTOCOMPLETE = "autocomplete"
#
# RANGE = "range"
#
# STRING = "string"
#
# VALUE_LIST = "value-list"
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
#
# Path: test_project/test_app/models.py
# class Language(models.Model):
# name = models.TextField()
# description = models.TextField()
#
# def __str__(self):
# return self.name
#
# class Author(models.Model):
# last_name = models.TextField()
# first_name = models.TextField()
#
# def __str__(self):
# return u"%s %s" % (self.first_name, self.last_name)
#
# class Book(models.Model):
# title = models.TextField()
# year = models.IntegerField()
# language = models.ForeignKey(Language, on_delete=models.CASCADE)
# authors = models.ManyToManyField(Author)
# no_editors = models.IntegerField()
# last_updated = models.DateField(auto_now=True)
# available = models.BooleanField(default=False)
#
# def __str__(self):
# return u"%s by %s" % (self.title, u", ".join(
# [str(author) for author in self.authors.all()]))
#
# Path: test_project/test_app/testutil.py
# class wait_for_page_load(object):
# def __init__(self, browser):
# self.browser = browser
#
# def __enter__(self):
# self.old_page = self.browser.find_by_tag("html")[0]._element
#
# def __exit__(self, *_):
# WebDriverWait(self.browser, 10).until(
# lambda driver: staleness_of(self.old_page)
# )
. Output only the next line. | registry = get_registry(settings.MULTISEEK_REGISTRY) |
Predict the next line after this snippet: <|code_start|>
@pytest.fixture
def multiseek_page(browser, live_server, initial_data):
browser.visit(live_server + reverse('multiseek:index'))
registry = get_registry(settings.MULTISEEK_REGISTRY)
page = MultiseekWebPage(browser=browser, registry=registry,
live_server_url=live_server.url)
yield page
page.browser.quit()
@pytest.fixture
def multiseek_admin_page(multiseek_page, admin_user):
multiseek_page.login(admin_user.username, "password")
return multiseek_page
@pytest.fixture(scope='session')
def splinter_firefox_profile_preferences():
return {
"browser.startup.homepage": "about:blank",
"startup.homepage_welcome_url": "about:blank",
"startup.homepage_welcome_url.additional": "about:blank",
"intl.accept_languages": "en-us"
}
@pytest.fixture
def initial_data():
<|code_end|>
using the current file's imports:
import json
import pytest
import datetime
from django.conf import settings
from django.urls import reverse
from model_bakery import baker
from selenium.webdriver.support.expected_conditions import staleness_of, \
alert_is_present
from selenium.webdriver.support.ui import WebDriverWait
from splinter.exceptions import ElementDoesNotExist
from multiseek.logic import DATE, AUTOCOMPLETE, RANGE, STRING, VALUE_LIST, \
get_registry
from .models import Language, Author, Book
from builtins import str as text
from django.utils.translation import gettext_lazy as _
from .testutil import wait_for_page_load
and any relevant context from other files:
# Path: multiseek/logic.py
# DATE = "date"
#
# AUTOCOMPLETE = "autocomplete"
#
# RANGE = "range"
#
# STRING = "string"
#
# VALUE_LIST = "value-list"
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
#
# Path: test_project/test_app/models.py
# class Language(models.Model):
# name = models.TextField()
# description = models.TextField()
#
# def __str__(self):
# return self.name
#
# class Author(models.Model):
# last_name = models.TextField()
# first_name = models.TextField()
#
# def __str__(self):
# return u"%s %s" % (self.first_name, self.last_name)
#
# class Book(models.Model):
# title = models.TextField()
# year = models.IntegerField()
# language = models.ForeignKey(Language, on_delete=models.CASCADE)
# authors = models.ManyToManyField(Author)
# no_editors = models.IntegerField()
# last_updated = models.DateField(auto_now=True)
# available = models.BooleanField(default=False)
#
# def __str__(self):
# return u"%s by %s" % (self.title, u", ".join(
# [str(author) for author in self.authors.all()]))
#
# Path: test_project/test_app/testutil.py
# class wait_for_page_load(object):
# def __init__(self, browser):
# self.browser = browser
#
# def __enter__(self):
# self.old_page = self.browser.find_by_tag("html")[0]._element
#
# def __exit__(self, *_):
# WebDriverWait(self.browser, 10).until(
# lambda driver: staleness_of(self.old_page)
# )
. Output only the next line. | eng = baker.make(Language, name=_("english"), description="English language") |
Given snippet: <|code_start|>@pytest.fixture
def multiseek_page(browser, live_server, initial_data):
browser.visit(live_server + reverse('multiseek:index'))
registry = get_registry(settings.MULTISEEK_REGISTRY)
page = MultiseekWebPage(browser=browser, registry=registry,
live_server_url=live_server.url)
yield page
page.browser.quit()
@pytest.fixture
def multiseek_admin_page(multiseek_page, admin_user):
multiseek_page.login(admin_user.username, "password")
return multiseek_page
@pytest.fixture(scope='session')
def splinter_firefox_profile_preferences():
return {
"browser.startup.homepage": "about:blank",
"startup.homepage_welcome_url": "about:blank",
"startup.homepage_welcome_url.additional": "about:blank",
"intl.accept_languages": "en-us"
}
@pytest.fixture
def initial_data():
eng = baker.make(Language, name=_("english"), description="English language")
baker.make(Language, name=_("polish"), description="Polish language")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import pytest
import datetime
from django.conf import settings
from django.urls import reverse
from model_bakery import baker
from selenium.webdriver.support.expected_conditions import staleness_of, \
alert_is_present
from selenium.webdriver.support.ui import WebDriverWait
from splinter.exceptions import ElementDoesNotExist
from multiseek.logic import DATE, AUTOCOMPLETE, RANGE, STRING, VALUE_LIST, \
get_registry
from .models import Language, Author, Book
from builtins import str as text
from django.utils.translation import gettext_lazy as _
from .testutil import wait_for_page_load
and context:
# Path: multiseek/logic.py
# DATE = "date"
#
# AUTOCOMPLETE = "autocomplete"
#
# RANGE = "range"
#
# STRING = "string"
#
# VALUE_LIST = "value-list"
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
#
# Path: test_project/test_app/models.py
# class Language(models.Model):
# name = models.TextField()
# description = models.TextField()
#
# def __str__(self):
# return self.name
#
# class Author(models.Model):
# last_name = models.TextField()
# first_name = models.TextField()
#
# def __str__(self):
# return u"%s %s" % (self.first_name, self.last_name)
#
# class Book(models.Model):
# title = models.TextField()
# year = models.IntegerField()
# language = models.ForeignKey(Language, on_delete=models.CASCADE)
# authors = models.ManyToManyField(Author)
# no_editors = models.IntegerField()
# last_updated = models.DateField(auto_now=True)
# available = models.BooleanField(default=False)
#
# def __str__(self):
# return u"%s by %s" % (self.title, u", ".join(
# [str(author) for author in self.authors.all()]))
#
# Path: test_project/test_app/testutil.py
# class wait_for_page_load(object):
# def __init__(self, browser):
# self.browser = browser
#
# def __enter__(self):
# self.old_page = self.browser.find_by_tag("html")[0]._element
#
# def __exit__(self, *_):
# WebDriverWait(self.browser, 10).until(
# lambda driver: staleness_of(self.old_page)
# )
which might include code, classes, or functions. Output only the next line. | a1 = baker.make(Author, last_name="Smith", first_name="John") |
Here is a snippet: <|code_start|> browser.visit(live_server + reverse('multiseek:index'))
registry = get_registry(settings.MULTISEEK_REGISTRY)
page = MultiseekWebPage(browser=browser, registry=registry,
live_server_url=live_server.url)
yield page
page.browser.quit()
@pytest.fixture
def multiseek_admin_page(multiseek_page, admin_user):
multiseek_page.login(admin_user.username, "password")
return multiseek_page
@pytest.fixture(scope='session')
def splinter_firefox_profile_preferences():
return {
"browser.startup.homepage": "about:blank",
"startup.homepage_welcome_url": "about:blank",
"startup.homepage_welcome_url.additional": "about:blank",
"intl.accept_languages": "en-us"
}
@pytest.fixture
def initial_data():
eng = baker.make(Language, name=_("english"), description="English language")
baker.make(Language, name=_("polish"), description="Polish language")
a1 = baker.make(Author, last_name="Smith", first_name="John")
a2 = baker.make(Author, last_name="Kovalsky", first_name="Ian")
<|code_end|>
. Write the next line using the current file imports:
import json
import pytest
import datetime
from django.conf import settings
from django.urls import reverse
from model_bakery import baker
from selenium.webdriver.support.expected_conditions import staleness_of, \
alert_is_present
from selenium.webdriver.support.ui import WebDriverWait
from splinter.exceptions import ElementDoesNotExist
from multiseek.logic import DATE, AUTOCOMPLETE, RANGE, STRING, VALUE_LIST, \
get_registry
from .models import Language, Author, Book
from builtins import str as text
from django.utils.translation import gettext_lazy as _
from .testutil import wait_for_page_load
and context from other files:
# Path: multiseek/logic.py
# DATE = "date"
#
# AUTOCOMPLETE = "autocomplete"
#
# RANGE = "range"
#
# STRING = "string"
#
# VALUE_LIST = "value-list"
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
#
# Path: test_project/test_app/models.py
# class Language(models.Model):
# name = models.TextField()
# description = models.TextField()
#
# def __str__(self):
# return self.name
#
# class Author(models.Model):
# last_name = models.TextField()
# first_name = models.TextField()
#
# def __str__(self):
# return u"%s %s" % (self.first_name, self.last_name)
#
# class Book(models.Model):
# title = models.TextField()
# year = models.IntegerField()
# language = models.ForeignKey(Language, on_delete=models.CASCADE)
# authors = models.ManyToManyField(Author)
# no_editors = models.IntegerField()
# last_updated = models.DateField(auto_now=True)
# available = models.BooleanField(default=False)
#
# def __str__(self):
# return u"%s by %s" % (self.title, u", ".join(
# [str(author) for author in self.authors.all()]))
#
# Path: test_project/test_app/testutil.py
# class wait_for_page_load(object):
# def __init__(self, browser):
# self.browser = browser
#
# def __enter__(self):
# self.old_page = self.browser.find_by_tag("html")[0]._element
#
# def __exit__(self, *_):
# WebDriverWait(self.browser, 10).until(
# lambda driver: staleness_of(self.old_page)
# )
, which may include functions, classes, or code. Output only the next line. | b1 = baker.make(Book, title="A book with a title", year=2013, language=eng, |
Next line prediction: <|code_start|># -*- encoding: utf-8 -*-
class SplinterLoginMixin:
def login(self, username="admin", password="password"):
url = self.browser.url
<|code_end|>
. Use current file imports:
(import json
import pytest
import datetime
from django.conf import settings
from django.urls import reverse
from model_bakery import baker
from selenium.webdriver.support.expected_conditions import staleness_of, \
alert_is_present
from selenium.webdriver.support.ui import WebDriverWait
from splinter.exceptions import ElementDoesNotExist
from multiseek.logic import DATE, AUTOCOMPLETE, RANGE, STRING, VALUE_LIST, \
get_registry
from .models import Language, Author, Book
from builtins import str as text
from django.utils.translation import gettext_lazy as _
from .testutil import wait_for_page_load)
and context including class names, function names, or small code snippets from other files:
# Path: multiseek/logic.py
# DATE = "date"
#
# AUTOCOMPLETE = "autocomplete"
#
# RANGE = "range"
#
# STRING = "string"
#
# VALUE_LIST = "value-list"
#
# def get_registry(registry):
# """
# :rtype: MultiseekRegistry
# """
#
# if isinstance(registry, str):
# if registry not in _cached_registry:
# m = importlib.import_module(registry).registry
# _cached_registry[registry] = m
# return _cached_registry[registry]
#
# return registry
#
# Path: test_project/test_app/models.py
# class Language(models.Model):
# name = models.TextField()
# description = models.TextField()
#
# def __str__(self):
# return self.name
#
# class Author(models.Model):
# last_name = models.TextField()
# first_name = models.TextField()
#
# def __str__(self):
# return u"%s %s" % (self.first_name, self.last_name)
#
# class Book(models.Model):
# title = models.TextField()
# year = models.IntegerField()
# language = models.ForeignKey(Language, on_delete=models.CASCADE)
# authors = models.ManyToManyField(Author)
# no_editors = models.IntegerField()
# last_updated = models.DateField(auto_now=True)
# available = models.BooleanField(default=False)
#
# def __str__(self):
# return u"%s by %s" % (self.title, u", ".join(
# [str(author) for author in self.authors.all()]))
#
# Path: test_project/test_app/testutil.py
# class wait_for_page_load(object):
# def __init__(self, browser):
# self.browser = browser
#
# def __enter__(self):
# self.old_page = self.browser.find_by_tag("html")[0]._element
#
# def __exit__(self, *_):
# WebDriverWait(self.browser, 10).until(
# lambda driver: staleness_of(self.old_page)
# )
. Output only the next line. | with wait_for_page_load(self.browser): |
Predict the next line after this snippet: <|code_start|># -*- encoding: utf-8 -*-
urlpatterns = [
url(r'^jsi18n/$',
JavaScriptCatalog.as_view(packages=['multiseek']),
name="js_i18n"),
<|code_end|>
using the current file's imports:
from django.conf.urls import url
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.views.i18n import JavaScriptCatalog
from multiseek import views
from multiseek.views import load_form
and any relevant context from other files:
# Path: multiseek/views.py
# SAVED = "saved"
# OVERWRITE_PROMPT = "overwrite-prompt"
# ERR_FORM_NAME = _("Form name must not be empty")
# ERR_LOADING_DATA = _("Error while loading form data")
# ERR_PARSING_DATA = _("Error while parsing form data")
# ERR_NO_FORM_DATA = _("No form data provided")
# MULTISEEK_SESSION_KEY = "multiseek_json"
# MULTISEEK_SESSION_KEY_REMOVED = "multiseek_json_removed"
# LAST_FIELD_REMOVE_MESSAGE = _("The ability to remove the last field has been disabled.")
# JSON_OK = HttpResponse(json.dumps({"status": "OK"}), content_type="application/json")
# def reverse_or_just_url(s):
# def user_allowed_to_save_forms(user):
# def get_context_data(self):
# def get_values(values):
# def reset_form(request):
# def load_form(request, search_form_pk):
# def render_to_response(self, context):
# def get_json_response(self, content, **httpresponse_kwargs):
# def convert_context_to_json(self, context):
# def get(self, request, *args, **kw):
# def get_context_data(self):
# def post(self, request, *args, **kwargs):
# def get_multiseek_data(self):
# def get_removed_records(self):
# def describe_multiseek_data(self):
# def _recur(d):
# def get_context_data(self, **kwargs):
# def get_queryset(self):
# def manually_add_or_remove(request, pk, add=True):
# def remove_by_hand(request, pk):
# def remove_from_removed_by_hand(request, pk):
# def reenable_removed_by_hand(request):
# class MultiseekPageMixin:
# class MultiseekFormPage(MultiseekPageMixin, TemplateView):
# class JSONResponseMixin(object):
# class MultiseekSaveForm(MultiseekPageMixin, JSONResponseMixin, TemplateView):
# class MultiseekResults(MultiseekPageMixin, ListView):
#
# Path: multiseek/views.py
# def load_form(request, search_form_pk):
# try:
# sf = SearchForm.objects.get(pk=search_form_pk)
# except SearchForm.DoesNotExist:
# return HttpResponseNotFound()
#
# if request.user.is_anonymous and not sf.public:
# return HttpResponseForbidden()
#
# request.session[MULTISEEK_SESSION_KEY] = sf.data
# return shortcuts.redirect("..")
. Output only the next line. | url(r'^$', csrf_exempt(views.MultiseekFormPage.as_view( |
Based on the snippet: <|code_start|> )), name="index"),
url(r'^results/$',
csrf_exempt(views.MultiseekResults.as_view(
registry=settings.MULTISEEK_REGISTRY,
template_name="multiseek/results.html"
)), name="results"),
url(r'^save_form/$',
csrf_exempt(views.MultiseekSaveForm.as_view(
registry=settings.MULTISEEK_REGISTRY
)), name="save_form"),
url(r'^reset/$',
csrf_exempt(views.reset_form),
name="reset"),
url(r'^remove-from-results/(?P<pk>\d+)$',
views.remove_by_hand,
name="remove_from_results"),
url(r'^remove-from-removed-results/(?P<pk>\d+)$',
views.remove_from_removed_by_hand,
name="remove_from_removed_results"),
url(r'^reenable-removed-ids/$',
views.reenable_removed_by_hand,
name="reenable_removed_ids"),
url(r'^load_form/(?P<search_form_pk>\d+)',
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf.urls import url
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.views.i18n import JavaScriptCatalog
from multiseek import views
from multiseek.views import load_form
and context (classes, functions, sometimes code) from other files:
# Path: multiseek/views.py
# SAVED = "saved"
# OVERWRITE_PROMPT = "overwrite-prompt"
# ERR_FORM_NAME = _("Form name must not be empty")
# ERR_LOADING_DATA = _("Error while loading form data")
# ERR_PARSING_DATA = _("Error while parsing form data")
# ERR_NO_FORM_DATA = _("No form data provided")
# MULTISEEK_SESSION_KEY = "multiseek_json"
# MULTISEEK_SESSION_KEY_REMOVED = "multiseek_json_removed"
# LAST_FIELD_REMOVE_MESSAGE = _("The ability to remove the last field has been disabled.")
# JSON_OK = HttpResponse(json.dumps({"status": "OK"}), content_type="application/json")
# def reverse_or_just_url(s):
# def user_allowed_to_save_forms(user):
# def get_context_data(self):
# def get_values(values):
# def reset_form(request):
# def load_form(request, search_form_pk):
# def render_to_response(self, context):
# def get_json_response(self, content, **httpresponse_kwargs):
# def convert_context_to_json(self, context):
# def get(self, request, *args, **kw):
# def get_context_data(self):
# def post(self, request, *args, **kwargs):
# def get_multiseek_data(self):
# def get_removed_records(self):
# def describe_multiseek_data(self):
# def _recur(d):
# def get_context_data(self, **kwargs):
# def get_queryset(self):
# def manually_add_or_remove(request, pk, add=True):
# def remove_by_hand(request, pk):
# def remove_from_removed_by_hand(request, pk):
# def reenable_removed_by_hand(request):
# class MultiseekPageMixin:
# class MultiseekFormPage(MultiseekPageMixin, TemplateView):
# class JSONResponseMixin(object):
# class MultiseekSaveForm(MultiseekPageMixin, JSONResponseMixin, TemplateView):
# class MultiseekResults(MultiseekPageMixin, ListView):
#
# Path: multiseek/views.py
# def load_form(request, search_form_pk):
# try:
# sf = SearchForm.objects.get(pk=search_form_pk)
# except SearchForm.DoesNotExist:
# return HttpResponseNotFound()
#
# if request.user.is_anonymous and not sf.public:
# return HttpResponseForbidden()
#
# request.session[MULTISEEK_SESSION_KEY] = sf.data
# return shortcuts.redirect("..")
. Output only the next line. | load_form, |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
graph_colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k']
def time_ticks(x, pos):
return "{:10.2f}".format(float(x) / 1.0)
formatter = ticker.FuncFormatter(time_ticks)
def get_total_seconds(td):
return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 1e6) / 1e6
def time_delta(dt1, dt2):
return get_total_seconds(max([dt1, dt2]) - min([dt1, dt2]))
def draw_custom_graph(user_agents):
plot_x_y = []
# requests = log_parser.get_log_dicts(user_agent = r'SiteSucker.*')
for user_agent in user_agents:
<|code_end|>
. Write the next line using the current file imports:
import StringIO
import matplotlib.pyplot as plt
from matplotlib import ticker
from matplotlib.backends.backend_svg import FigureCanvasSVG as FigureCanvas
from project.tools import logger
and context from other files:
# Path: project/tools/logger.py
# def get_log_dicts(user_agent=None, path_regex=None, last_n_lines=None):
# def get_log_dicts_success():
# def get_log_dicts_failure():
# def clear_log(user_agents=None):
# def get_log_user_agents():
# def per_request_callbacks(response):
# def get_http_user_agent():
, which may include functions, classes, or code. Output only the next line. | requests = logger.get_log_dicts(user_agent=user_agent) |
Given snippet: <|code_start|> potTemplateFile = 'potTemplate.png'
cv2.imwrite(os.path.join(self.timestreamRootPath, self.settingPath, potTemplateFile), self.potTemplate[:,:,::-1])
potDict['potTemplateFile'] = potTemplateFile
else:
potDict = {}
self.settings['potdetect'] = potDict
self.settings['plantextract'] = {'meth': 'method1',
'methargs': {'threshold' : 0.6,
'kSize' : 5, 'blobMinSize' : 50} }
with open(self.settingFileName, 'w') as outfile:
outfile.write( yaml.dump(self.settings, default_flow_style=None) )
self.status.append('Saved initial data to ' + self.settingFileName)
def testPipeline(self):
''' try running processing pipeline based on user inputs'''
if self.tsImages != None:
# load setting file if missing
if self.settingFileName == None:
settingFileName = str(QtGui.QFileDialog.getOpenFileName(self, 'Open pipeline setting file', self.ts.path))
if len(settingFileName) > 0:
self.settingFileName = settingFileName
else:
return
# initialise pipeline
if self.pl == None:
f = file(self.settingFileName)
self.settings = yaml.load(f)
self.ts.data["settings"] = self.settings
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import matplotlib.pyplot as plt
import os, shutil
import cv2
import numpy as np
import timestream
import timestream.manipulate.correct_detect as cd
import yaml
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from timestream.manipulate import pipeline
and context:
# Path: timestream/manipulate/pipeline.py
# class ImagePipeline (object):
# def __init__(self, plConf, context):
# def process(self, contArgs, initArgs, visualise=False):
# def printCompList(cls):
which might include code, classes, or functions. Output only the next line. | self.pl = pipeline.ImagePipeline(self.settings) |
Using the snippet: <|code_start|>
class TestValidateTimestreamManfiest(TestCase):
"""Tests for ts.parse.validate.validate_timestream_manifest"""
str_dict = {
"name": "BVZ0022-GC05L-CN650D-Cam07~fullres-orig",
"start_datetime": "2013_10_30_03_00_00",
"end_datetime": "2013_10_30_06_00_00",
"version": "1",
"image_type": "jpg",
"extension": "JPG",
"interval": "30",
"missing": [],
}
val_dict = {
"name": "BVZ0022-GC05L-CN650D-Cam07~fullres-orig",
"start_datetime": dt.datetime(2013, 10, 30, 3, 0, 0),
"end_datetime": dt.datetime(2013, 10, 30, 6, 0, 0),
"version": 1,
"image_type": "jpg",
"extension": "JPG",
"interval": 30,
"missing": [],
}
def test_validate_valid(self):
"""Test validate_timestream_manifest with valid manfests"""
<|code_end|>
, determine the next line of code. You have imports:
import datetime as dt
from unittest import TestCase
from voluptuous import MultipleInvalid
from timestream.parse.validate import (
validate_timestream_manifest,
)
from timestream.util.validation import v_date
and context (class names, function names, or code) available:
# Path: timestream/parse/validate.py
# def validate_timestream_manifest(manifest):
# """Validtes a json manifest, and returns the validated ``dict``
#
# :param dict manifest: The raw json manifest from ``json.load`` or similar.
# :returns: The validated and type-converted manifest as a ``dict``
# :rtype: dict
# :raises: TypeError, MultipleInvalid
# """
# if not isinstance(manifest, dict):
# raise TypeError("Manfiest should be in ``dict`` form.")
# sch = Schema({
# Required("name"): All(str, Length(min=1)),
# Required("version"): All(v_num_str, Range(min=1, max=2)),
# Required("start_datetime"): v_datetime,
# Required("end_datetime"): v_datetime,
# Required("image_type"): Any(*IMAGE_TYPE_CONSTANTS),
# Required("extension"): Any(*IMAGE_EXT_CONSTANTS),
# Required("interval", default=1): All(v_num_str, Range(min=1)),
# "missing": list,
# })
# return sch(manifest)
#
# Path: timestream/util/validation.py
# def v_date(x, format="%Y_%m_%d"):
# """Validate string contains a date in ``fmt`` strptime-compatible format,
# and coerce to a ``datetime.datetime`` object.
#
# :arg str x: String to validate.
# :keyword str fmt: String date format to strip time with.
# :returns: the parsed object
# :rtype: datetime.datetime
# :raises: ``ValueError``
# """
# if isinstance(x, datetime.datetime):
# return x
# else:
# return datetime.datetime.strptime(x, format)
. Output only the next line. | self.assertDictEqual(validate_timestream_manifest(self.str_dict), |
Given the code snippet: <|code_start|> "image_type": "jpg",
"extension": "JPG",
"interval": 30,
"missing": [],
}
def test_validate_valid(self):
"""Test validate_timestream_manifest with valid manfests"""
self.assertDictEqual(validate_timestream_manifest(self.str_dict),
self.val_dict)
self.assertDictEqual(validate_timestream_manifest(self.val_dict),
self.val_dict)
def test_validate_invalid(self):
"""Test validate_timestream_manifest with invalid manfests"""
with self.assertRaises(TypeError):
validate_timestream_manifest(None)
with self.assertRaises(MultipleInvalid):
validate_timestream_manifest({"A": "b", })
class TestDateValidators(TestCase):
"""Tests for misc date format validators"""
def test_v_date_invalid(self):
"""Test v_date validator with invalid dates"""
# standard date format
date_str = "2013_44_01"
with self.assertRaises(ValueError):
<|code_end|>
, generate the next line using the imports in this file:
import datetime as dt
from unittest import TestCase
from voluptuous import MultipleInvalid
from timestream.parse.validate import (
validate_timestream_manifest,
)
from timestream.util.validation import v_date
and context (functions, classes, or occasionally code) from other files:
# Path: timestream/parse/validate.py
# def validate_timestream_manifest(manifest):
# """Validtes a json manifest, and returns the validated ``dict``
#
# :param dict manifest: The raw json manifest from ``json.load`` or similar.
# :returns: The validated and type-converted manifest as a ``dict``
# :rtype: dict
# :raises: TypeError, MultipleInvalid
# """
# if not isinstance(manifest, dict):
# raise TypeError("Manfiest should be in ``dict`` form.")
# sch = Schema({
# Required("name"): All(str, Length(min=1)),
# Required("version"): All(v_num_str, Range(min=1, max=2)),
# Required("start_datetime"): v_datetime,
# Required("end_datetime"): v_datetime,
# Required("image_type"): Any(*IMAGE_TYPE_CONSTANTS),
# Required("extension"): Any(*IMAGE_EXT_CONSTANTS),
# Required("interval", default=1): All(v_num_str, Range(min=1)),
# "missing": list,
# })
# return sch(manifest)
#
# Path: timestream/util/validation.py
# def v_date(x, format="%Y_%m_%d"):
# """Validate string contains a date in ``fmt`` strptime-compatible format,
# and coerce to a ``datetime.datetime`` object.
#
# :arg str x: String to validate.
# :keyword str fmt: String date format to strip time with.
# :returns: the parsed object
# :rtype: datetime.datetime
# :raises: ``ValueError``
# """
# if isinstance(x, datetime.datetime):
# return x
# else:
# return datetime.datetime.strptime(x, format)
. Output only the next line. | v_date(date_str) |
Continue the code snippet: <|code_start|> '%Y_%m_%d',
'%Y_%m_%d_%H',
'{tsname:s}_%Y_%m_%d_%H_%M_%S_{n:02d}.{ext:s}',
]
TS_V1_FMT = path.join(*__TS_V1_LEVELS)
TS_MANIFEST_KEYS = [
"name",
"version",
"start_datetime",
"end_datetime",
"image_type",
"extension",
"interval",
]
def validate_timestream_manifest(manifest):
"""Validtes a json manifest, and returns the validated ``dict``
:param dict manifest: The raw json manifest from ``json.load`` or similar.
:returns: The validated and type-converted manifest as a ``dict``
:rtype: dict
:raises: TypeError, MultipleInvalid
"""
if not isinstance(manifest, dict):
raise TypeError("Manfiest should be in ``dict`` form.")
sch = Schema({
Required("name"): All(str, Length(min=1)),
Required("version"): All(v_num_str, Range(min=1, max=2)),
<|code_end|>
. Use current file imports:
from os import path
from voluptuous import Schema, Required, Range, All, Length, Any
from timestream.util.validation import (
v_datetime,
v_num_str,
)
and context (classes, functions, or code) from other files:
# Path: timestream/util/validation.py
# def v_datetime(x, format="%Y_%m_%d_%H_%M_%S"):
# """Validate string contains a date in ``fmt`` strptime-compatible format,
# and coerce to a ``datetime.datetime`` object.
#
# :arg str x: String to validate.
# :keyword str fmt: String date format to strip time with.
# :returns: the parsed object
# :rtype: datetime.datetime
# :raises: ``ValueError``
# """
# if isinstance(x, datetime.datetime):
# return x
# else:
# return datetime.datetime.strptime(x, format)
#
# def v_num_str(x):
# """Validate an object that can be coerced to an ``int``."""
# return int(x)
. Output only the next line. | Required("start_datetime"): v_datetime, |
Predict the next line after this snippet: <|code_start|> '%Y_%m',
'%Y_%m_%d',
'%Y_%m_%d_%H',
'{tsname:s}_%Y_%m_%d_%H_%M_%S_{n:02d}.{ext:s}',
]
TS_V1_FMT = path.join(*__TS_V1_LEVELS)
TS_MANIFEST_KEYS = [
"name",
"version",
"start_datetime",
"end_datetime",
"image_type",
"extension",
"interval",
]
def validate_timestream_manifest(manifest):
"""Validtes a json manifest, and returns the validated ``dict``
:param dict manifest: The raw json manifest from ``json.load`` or similar.
:returns: The validated and type-converted manifest as a ``dict``
:rtype: dict
:raises: TypeError, MultipleInvalid
"""
if not isinstance(manifest, dict):
raise TypeError("Manfiest should be in ``dict`` form.")
sch = Schema({
Required("name"): All(str, Length(min=1)),
<|code_end|>
using the current file's imports:
from os import path
from voluptuous import Schema, Required, Range, All, Length, Any
from timestream.util.validation import (
v_datetime,
v_num_str,
)
and any relevant context from other files:
# Path: timestream/util/validation.py
# def v_datetime(x, format="%Y_%m_%d_%H_%M_%S"):
# """Validate string contains a date in ``fmt`` strptime-compatible format,
# and coerce to a ``datetime.datetime`` object.
#
# :arg str x: String to validate.
# :keyword str fmt: String date format to strip time with.
# :returns: the parsed object
# :rtype: datetime.datetime
# :raises: ``ValueError``
# """
# if isinstance(x, datetime.datetime):
# return x
# else:
# return datetime.datetime.strptime(x, format)
#
# def v_num_str(x):
# """Validate an object that can be coerced to an ``int``."""
# return int(x)
. Output only the next line. | Required("version"): All(v_num_str, Range(min=1, max=2)), |
Given the code snippet: <|code_start|>
CLI_DOC = """
USAGE:
fixChamberPos.py [-n] -c COLUMN -i INPUT
OPTIONS:
-n CSV has no header
-c COLUMN Column to convert.
-i INPUT Input CSV
"""
def main(opts):
ifh = open(opts['-i'])
rdr = csv.reader(ifh)
col = int(opts['-c']) - 1
if not opts['-n']:
print(','.join(next(rdr)))
for line in rdr:
if col < 0 or col > len(line) - 1:
print "Invalid column", opts['-c']
exit(1)
<|code_end|>
, generate the next line using the imports in this file:
import csv
from docopt import docopt
from timestream.util.layouts import traypos_to_chamber_index
and context (functions, classes, or occasionally code) from other files:
# Path: timestream/util/layouts.py
# def traypos_to_chamber_index(traypos, tray_cap=20, col_cap=5):
# if not isinstance(traypos, str):
# msg = PARAM_TYPE_ERR.format(func='traypos_to_chamber_index',
# param='traypos', type='str')
# LOG.error(msg)
# raise TypeError(msg)
# extractor = re.compile(r'^(\d{1,2})([a-zA-Z])([1-9])$')
# match = extractor.match(traypos)
# if match is None:
# msg = "Tray Pos '{}' is invalid".format(traypos)
# LOG.error(msg)
# raise ValueError(msg)
# tray, col, row = match.groups()
# tray = int(tray)
# col = ord(col.upper()) - 65 # Numericise the col num, 0-based
# row = int(row)
# index = (tray - 1) * tray_cap + col * col_cap + row
# return index
. Output only the next line. | line[col] = str(traypos_to_chamber_index(line[col])) |
Given the code snippet: <|code_start|> ignored_timestamps = list(ts_set)
print('ignored_timestamps = ', ignored_timestamps)
# We put everything else that is not an time series into outputroot.
ctx.setVal("outputroot", os.path.abspath(outputRootPath) + '-results')
if not os.path.exists(ctx.outputroot):
os.mkdir(ctx.outputroot)
# Dictionary where we put all values that should be added with an image as soon
# as it is output with the TimeStream
ctx.setVal("outputwithimage", {})
# initialise processing pipeline
pl = pipeline.ImagePipeline(plConf.pipeline, ctx)
# for img in ts.iter_by_files():
for img in ts.iter_by_files(ignored_timestamps):
if len(img.pixels) == 0:
print('Missing image at {}'.format(img.datetime))
continue
# Detach img from timestream. We don't need it!
img.parent_timestream = None
print("Process", img.path, '...'),
print("Time stamp", img.datetime)
ctx.setVal("origImg", img)
try:
result = pl.process(ctx, [img], visualise)
<|code_end|>
, generate the next line using the imports in this file:
import csv
import glob
import docopt
import sys, os
import timestream
import logging
import timestream.manipulate.configuration as pipeconf
import timestream.manipulate.pipeline as pipeline
import yaml
import datetime
from timestream.manipulate.pipecomponents import PCExBrakeInPipeline
and context (functions, classes, or occasionally code) from other files:
# Path: timestream/manipulate/pipecomponents.py
# LOG = logging.getLogger("timestreamlib")
# TLC = self.backgroundWindow[0:2]
# BRC = self.backgroundWindow[2:]
# W = 2.0*np.tan(self.fieldOfView[0]/2.0/180.0*np.pi)
# H = 2.0*np.tan(self.fieldOfView[1]/2.0/180.0*np.pi)
# H, T = os.path.split(fpath)
# class PipeComponent (object):
# class ImageMarginAdder(PipeComponent):
# class ImageUndistorter (PipeComponent):
# class ColorCardDetector (PipeComponent):
# class ImageColorCorrector (PipeComponent):
# class TrayDetector (PipeComponent):
# class PotDetector (PipeComponent):
# class PotDetectorGlassHouse (PipeComponent):
# class PlantExtractor (PipeComponent):
# class FeatureExtractor (PipeComponent):
# class ResultingFeatureWriter(PipeComponent):
# class ResultingImageWriter (PipeComponent):
# class ResizeImage (PipeComponent):
# class DerandomizeTimeStreams (PipeComponent):
# class ResizeAndWriteImage (PipeComponent):
# def __init__(self, *args, **kwargs):
# def __call__(self, context, *args):
# def __chkExcept__(self, context, *args):
# def __exec__(self, context, *args):
# def info(cls, _str=True):
# def show(self):
# def __init__(self, context, **kwargs):
# def __exec__(self, context, *args):
# def padlocal(self, vector, pad_width, iaxis, kwargs):
# def show(self):
# def __init__(self, context, **kwargs):
# def __exec__(self, context, *args):
# def show(self):
# def __init__(self, context, **kwargs):
# def __exec__(self, context, *args):
# def show(self):
# def __init__(self, context, **kwargs):
# def __exec__(self, context, *args):
# def show(self):
# def __init__(self, context, **kwargs):
# def __exec__(self, context, *args):
# def show(self):
# def __init__(self, context, **kwargs):
# def __exec__(self, context, *args):
# def show(self):
# def __init__(self, context, **kwargs):
# def __call__(self, context, *args):
# def show(self):
# def __init__(self, context, **kwargs):
# def __exec__(self, context, *args):
# def segAllPots(self):
# def show(self):
# def __init__(self, context, **kwargs):
# def __exec__(self, context, *args):
# def __init__(self, context, **kwargs):
# def __exec__(self, context, *args):
# def __chkExcept__(self, context, *args):
# def _guessTimeStamp(self, img):
# def _addErrStr(self, timestamp, filename):
# def _recoverFromPrev(self, timestamp, featName):
# def _initHeaders(self, fPath, ipm, potIds):
# def _initPrevCsvIndex(self):
# def _appendToAudit(self, ts, val):
# def __init__(self, context, **kwargs):
# def __exec__(self, context, *args):
# def __init__(self, context, **kwargs):
# def __exec__(self, context, *args):
# def __init__(self, context, **kwargs):
# def __exec__(self, context, *args):
# def createCompoundImage(self, timestamp):
# def getMidGrpImg(self, mid, potList, maxPotRect, numPotPerMidSize):
# def refreshMids(self, timestamp=None):
# def __init__(self, context, **kwargs):
# def __exec__(self, context, *args):
# def show(self):
. Output only the next line. | except PCExBrakeInPipeline as bip: |
Given snippet: <|code_start|>
class TestTrayPosToChamberIndex(TestCase):
_multiprocess_can_split_ = True
maxDiff = None
def test_tray_pos_to_chamber_idx(self):
"""Tests for ts.util.traypos_to_chamber_index"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from unittest import TestCase
from timestream.util import (
layouts, # module
)
and context:
# Path: timestream/util/layouts.py
# LOG = logging.getLogger("timestreamlib")
# def traypos_to_chamber_index(traypos, tray_cap=20, col_cap=5):
which might include code, classes, or functions. Output only the next line. | self.assertEqual(layouts.traypos_to_chamber_index("1A1"), 1) |
Given the code snippet: <|code_start|> """
return remove_www(request.get_host().split(":")[0]).lower()
def process_request(self, request):
# Connection needs first to be at the public schema, as this is where
# the tenant metadata is stored.
connection.set_schema_to_public()
hostname = self.hostname_from_request(request)
TenantModel = get_tenant_model()
try:
# get_tenant must be implemented by extending this class.
tenant = self.get_tenant(TenantModel, hostname, request)
assert isinstance(tenant, TenantModel)
except TenantModel.DoesNotExist:
raise self.TENANT_NOT_FOUND_EXCEPTION(
"No tenant for {!r}".format(request.get_host())
)
except AssertionError:
raise self.TENANT_NOT_FOUND_EXCEPTION(
"Invalid tenant {!r}".format(request.tenant)
)
request.tenant = tenant
connection.set_tenant(request.tenant)
# Do we have a public-specific urlconf?
if (
hasattr(settings, "PUBLIC_SCHEMA_URLCONF")
<|code_end|>
, generate the next line using the imports in this file:
import django
from django.conf import settings
from django.core.exceptions import DisallowedHost
from django.db import connection
from django.http import Http404
from tenant_schemas.utils import (
get_public_schema_name,
get_tenant_model,
remove_www,
)
and context (functions, classes, or occasionally code) from other files:
# Path: tenant_schemas/utils.py
# def get_public_schema_name():
# return getattr(settings, 'PUBLIC_SCHEMA_NAME', 'public')
#
# def get_tenant_model():
# return get_model(*settings.TENANT_MODEL.split("."))
#
# def remove_www(hostname):
# """
# Removes www. from the beginning of the address. Only for
# routing purposes. www.test.com/login/ and test.com/login/ should
# find the same tenant.
# """
# if hostname.startswith("www."):
# return hostname[4:]
#
# return hostname
. Output only the next line. | and request.tenant.schema_name == get_public_schema_name() |
Given the code snippet: <|code_start|>Extend BaseTenantMiddleware for a custom tenant selection strategy,
such as inspecting the header, or extracting it from some OAuth token.
"""
class BaseTenantMiddleware(django.utils.deprecation.MiddlewareMixin):
TENANT_NOT_FOUND_EXCEPTION = Http404
"""
Subclass and override this to achieve desired behaviour. Given a
request, return the tenant to use. Tenant should be an instance
of TENANT_MODEL. We have three parameters for backwards compatibility
(the request would be enough).
"""
def get_tenant(self, model, hostname, request):
raise NotImplementedError
def hostname_from_request(self, request):
""" Extracts hostname from request. Used for custom requests filtering.
By default removes the request's port and common prefixes.
"""
return remove_www(request.get_host().split(":")[0]).lower()
def process_request(self, request):
# Connection needs first to be at the public schema, as this is where
# the tenant metadata is stored.
connection.set_schema_to_public()
hostname = self.hostname_from_request(request)
<|code_end|>
, generate the next line using the imports in this file:
import django
from django.conf import settings
from django.core.exceptions import DisallowedHost
from django.db import connection
from django.http import Http404
from tenant_schemas.utils import (
get_public_schema_name,
get_tenant_model,
remove_www,
)
and context (functions, classes, or occasionally code) from other files:
# Path: tenant_schemas/utils.py
# def get_public_schema_name():
# return getattr(settings, 'PUBLIC_SCHEMA_NAME', 'public')
#
# def get_tenant_model():
# return get_model(*settings.TENANT_MODEL.split("."))
#
# def remove_www(hostname):
# """
# Removes www. from the beginning of the address. Only for
# routing purposes. www.test.com/login/ and test.com/login/ should
# find the same tenant.
# """
# if hostname.startswith("www."):
# return hostname[4:]
#
# return hostname
. Output only the next line. | TenantModel = get_tenant_model() |
Here is a snippet: <|code_start|>
"""
These middlewares should be placed at the very top of the middleware stack.
Selects the proper database schema using request information. Can fail in
various ways which is better than corrupting or revealing data.
Extend BaseTenantMiddleware for a custom tenant selection strategy,
such as inspecting the header, or extracting it from some OAuth token.
"""
class BaseTenantMiddleware(django.utils.deprecation.MiddlewareMixin):
TENANT_NOT_FOUND_EXCEPTION = Http404
"""
Subclass and override this to achieve desired behaviour. Given a
request, return the tenant to use. Tenant should be an instance
of TENANT_MODEL. We have three parameters for backwards compatibility
(the request would be enough).
"""
def get_tenant(self, model, hostname, request):
raise NotImplementedError
def hostname_from_request(self, request):
""" Extracts hostname from request. Used for custom requests filtering.
By default removes the request's port and common prefixes.
"""
<|code_end|>
. Write the next line using the current file imports:
import django
from django.conf import settings
from django.core.exceptions import DisallowedHost
from django.db import connection
from django.http import Http404
from tenant_schemas.utils import (
get_public_schema_name,
get_tenant_model,
remove_www,
)
and context from other files:
# Path: tenant_schemas/utils.py
# def get_public_schema_name():
# return getattr(settings, 'PUBLIC_SCHEMA_NAME', 'public')
#
# def get_tenant_model():
# return get_model(*settings.TENANT_MODEL.split("."))
#
# def remove_www(hostname):
# """
# Removes www. from the beginning of the address. Only for
# routing purposes. www.test.com/login/ and test.com/login/ should
# find the same tenant.
# """
# if hostname.startswith("www."):
# return hostname[4:]
#
# return hostname
, which may include functions, classes, or code. Output only the next line. | return remove_www(request.get_host().split(":")[0]).lower() |
Given the code snippet: <|code_start|>
class BaseTestCase(TestCase):
"""
Base test case that comes packed with overloaded INSTALLED_APPS,
custom public tenant, and schemas cleanup on tearDown.
"""
@classmethod
def setUpClass(cls):
settings.TENANT_MODEL = 'tenant_schemas.Tenant'
settings.SHARED_APPS = ('tenant_schemas', )
settings.TENANT_APPS = ('dts_test_app',
'django.contrib.contenttypes',
'django.contrib.auth', )
settings.INSTALLED_APPS = settings.SHARED_APPS + settings.TENANT_APPS
if '.test.com' not in settings.ALLOWED_HOSTS:
settings.ALLOWED_HOSTS += ['.test.com']
# Django calls syncdb by default for the test database, but we want
# a blank public schema for this set of tests.
connection.set_schema_to_public()
cursor = connection.cursor()
cursor.execute('DROP SCHEMA IF EXISTS %s CASCADE; CREATE SCHEMA %s;'
<|code_end|>
, generate the next line using the imports in this file:
import inspect
from django.conf import settings
from django.core.management import call_command
from django.db import connection
from django.test import TestCase
from tenant_schemas.utils import get_public_schema_name
and context (functions, classes, or occasionally code) from other files:
# Path: tenant_schemas/utils.py
# def get_public_schema_name():
# return getattr(settings, 'PUBLIC_SCHEMA_NAME', 'public')
. Output only the next line. | % (get_public_schema_name(), get_public_schema_name())) |
Continue the code snippet: <|code_start|>"""
Adaptations of the cached and filesystem template loader working in a
multi-tenant setting
"""
class CachedLoader(cached.Loader):
def cache_key(self, *args, **kwargs):
key = super(CachedLoader, self).cache_key(*args, **kwargs)
<|code_end|>
. Use current file imports:
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db import connection
from django.template.loaders import cached, filesystem
from ordered_set import OrderedSet
from tenant_schemas.postgresql_backend.base import FakeTenant
and context (classes, functions, or code) from other files:
# Path: tenant_schemas/postgresql_backend/base.py
# class FakeTenant:
# """
# We can't import any db model in a backend (apparently?), so this class is used
# for wrapping schema names in a tenant-like structure.
# """
# def __init__(self, schema_name):
# self.schema_name = schema_name
. Output only the next line. | if not connection.tenant or isinstance(connection.tenant, FakeTenant): |
Next line prediction: <|code_start|> stderr = OutputWrapper(sys.stderr)
stderr.style_func = style_func
if int(options.get('verbosity', 1)) >= 1:
stdout.write(style.NOTICE("=== Running migrate for schema %s" % schema_name))
connection.set_schema(schema_name)
MigrateCommand(stdout=stdout, stderr=stderr).execute(*args, **options)
try:
transaction.commit()
connection.close()
connection.connection = None
except transaction.TransactionManagementError:
if not allow_atomic:
raise
# We are in atomic transaction, don't close connections
pass
connection.set_schema_to_public()
class MigrationExecutor(object):
codename = None
def __init__(self, args, options):
self.args = args
self.options = options
def run_migrations(self, tenants):
<|code_end|>
. Use current file imports:
(import sys
from django.core.management.commands.migrate import Command as MigrateCommand
from django.db import transaction
from tenant_schemas.utils import get_public_schema_name
from django.core.management import color
from django.core.management.base import OutputWrapper
from django.db import connection)
and context including class names, function names, or small code snippets from other files:
# Path: tenant_schemas/utils.py
# def get_public_schema_name():
# return getattr(settings, 'PUBLIC_SCHEMA_NAME', 'public')
. Output only the next line. | public_schema_name = get_public_schema_name() |
Given the following code snippet before the placeholder: <|code_start|>
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None,
current_app=None):
url = reverse_default(
viewname=viewname,
urlconf=urlconf,
args=args,
kwargs=kwargs,
current_app=current_app
)
<|code_end|>
, predict the next line using imports from the current file:
from django.core.urlresolvers import reverse as reverse_default
from django.utils.functional import lazy
from tenant_schemas.utils import clean_tenant_url
and context including class names, function names, and sometimes code from other files:
# Path: tenant_schemas/utils.py
# def clean_tenant_url(url_string):
# """
# Removes the TENANT_TOKEN from a particular string
# """
# if hasattr(settings, 'PUBLIC_SCHEMA_URLCONF'):
# if (settings.PUBLIC_SCHEMA_URLCONF and
# url_string.startswith(settings.PUBLIC_SCHEMA_URLCONF)):
# url_string = url_string[len(settings.PUBLIC_SCHEMA_URLCONF):]
# return url_string
. Output only the next line. | return clean_tenant_url(url) |
Predict the next line for this snippet: <|code_start|>
class TenantTutorialMiddleware(object):
def process_request(self, request):
connection.set_schema_to_public()
hostname_without_port = remove_www_and_dev(request.get_host().split(':')[0])
<|code_end|>
with the help of current file imports:
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db import connection
from django.http import Http404
from tenant_schemas.utils import get_tenant_model, remove_www_and_dev, get_public_schema_name
from django.db import utils
and context from other files:
# Path: tenant_schemas/utils.py
# def get_tenant_model():
# return get_model(*settings.TENANT_MODEL.split("."))
#
# def remove_www_and_dev(hostname):
# """
# Legacy function - just in case someone is still using the old name
# """
# return remove_www(hostname)
#
# def get_public_schema_name():
# return getattr(settings, 'PUBLIC_SCHEMA_NAME', 'public')
, which may contain function names, class names, or code. Output only the next line. | TenantModel = get_tenant_model() |
Using the snippet: <|code_start|>
class TenantTutorialMiddleware(object):
def process_request(self, request):
connection.set_schema_to_public()
<|code_end|>
, determine the next line of code. You have imports:
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db import connection
from django.http import Http404
from tenant_schemas.utils import get_tenant_model, remove_www_and_dev, get_public_schema_name
from django.db import utils
and context (class names, function names, or code) available:
# Path: tenant_schemas/utils.py
# def get_tenant_model():
# return get_model(*settings.TENANT_MODEL.split("."))
#
# def remove_www_and_dev(hostname):
# """
# Legacy function - just in case someone is still using the old name
# """
# return remove_www(hostname)
#
# def get_public_schema_name():
# return getattr(settings, 'PUBLIC_SCHEMA_NAME', 'public')
. Output only the next line. | hostname_without_port = remove_www_and_dev(request.get_host().split(':')[0]) |
Given snippet: <|code_start|>
class TenantTutorialMiddleware(object):
def process_request(self, request):
connection.set_schema_to_public()
hostname_without_port = remove_www_and_dev(request.get_host().split(':')[0])
TenantModel = get_tenant_model()
try:
request.tenant = TenantModel.objects.get(domain_url=hostname_without_port)
except utils.DatabaseError:
request.urlconf = settings.PUBLIC_SCHEMA_URLCONF
return
except TenantModel.DoesNotExist:
if hostname_without_port in ("127.0.0.1", "localhost"):
request.urlconf = settings.PUBLIC_SCHEMA_URLCONF
return
else:
raise Http404
connection.set_tenant(request.tenant)
ContentType.objects.clear_cache()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db import connection
from django.http import Http404
from tenant_schemas.utils import get_tenant_model, remove_www_and_dev, get_public_schema_name
from django.db import utils
and context:
# Path: tenant_schemas/utils.py
# def get_tenant_model():
# return get_model(*settings.TENANT_MODEL.split("."))
#
# def remove_www_and_dev(hostname):
# """
# Legacy function - just in case someone is still using the old name
# """
# return remove_www(hostname)
#
# def get_public_schema_name():
# return getattr(settings, 'PUBLIC_SCHEMA_NAME', 'public')
which might include code, classes, or functions. Output only the next line. | if hasattr(settings, 'PUBLIC_SCHEMA_URLCONF') and request.tenant.schema_name == get_public_schema_name(): |
Given the code snippet: <|code_start|>
class Command(BaseCommand):
def handle(self, *args, **options):
database = options.get('database', 'default')
if (settings.DATABASES[database]['ENGINE'] == 'tenant_schemas.postgresql_backend'):
raise CommandError("migrate has been disabled, for database '{0}'. Use migrate_schemas "
"instead. Please read the documentation if you don't know why you "
"shouldn't call migrate directly!".format(database))
super(Command, self).handle(*args, **options)
<|code_end|>
, generate the next line using the imports in this file:
from django.conf import settings
from django.core.management.base import CommandError, BaseCommand
from tenant_schemas.management.commands.migrate_schemas import Command as MigrateSchemasCommand
from tenant_schemas.utils import django_is_in_test_mode
and context (functions, classes, or occasionally code) from other files:
# Path: tenant_schemas/utils.py
# def django_is_in_test_mode():
# """
# I know this is very ugly! I'm looking for more elegant solutions.
# See: http://stackoverflow.com/questions/6957016/detect-django-testing-mode
# """
# return hasattr(mail, 'outbox')
. Output only the next line. | if django_is_in_test_mode(): |
Given the code snippet: <|code_start|> for obj in self:
result = obj.delete()
if result is not None:
current_counter, current_counter_dict = result
counter += current_counter
counter_dict.update(current_counter_dict)
if counter:
return counter, counter_dict
class TenantMixin(models.Model):
"""
All tenant models must inherit this class.
"""
auto_drop_schema = False
"""
USE THIS WITH CAUTION!
Set this flag to true on a parent class if you want the schema to be
automatically deleted if the tenant row gets deleted.
"""
auto_create_schema = True
"""
Set this flag to false on a parent class if you don't want the schema
to be automatically created upon save.
"""
domain_url = models.CharField(max_length=128, unique=True)
schema_name = models.CharField(max_length=63, unique=True,
<|code_end|>
, generate the next line using the imports in this file:
from django.core.management import call_command
from django.db import connection, models
from tenant_schemas.postgresql_backend.base import _check_schema_name
from tenant_schemas.signals import post_schema_sync
from tenant_schemas.utils import get_public_schema_name, schema_exists
and context (functions, classes, or occasionally code) from other files:
# Path: tenant_schemas/postgresql_backend/base.py
# def _check_schema_name(name):
# if not _is_valid_schema_name(name):
# raise ValidationError("Invalid string used for the schema name.")
#
# Path: tenant_schemas/utils.py
# def get_public_schema_name():
# return getattr(settings, 'PUBLIC_SCHEMA_NAME', 'public')
#
# def schema_exists(schema_name):
# cursor = connection.cursor()
#
# # check if this schema already exists in the db
# sql = 'SELECT EXISTS(SELECT 1 FROM pg_catalog.pg_namespace WHERE LOWER(nspname) = LOWER(%s))'
# cursor.execute(sql, (schema_name, ))
#
# row = cursor.fetchone()
# if row:
# exists = row[0]
# else:
# exists = False
#
# cursor.close()
#
# return exists
. Output only the next line. | validators=[_check_schema_name]) |
Using the snippet: <|code_start|>
class TenantMixin(models.Model):
"""
All tenant models must inherit this class.
"""
auto_drop_schema = False
"""
USE THIS WITH CAUTION!
Set this flag to true on a parent class if you want the schema to be
automatically deleted if the tenant row gets deleted.
"""
auto_create_schema = True
"""
Set this flag to false on a parent class if you don't want the schema
to be automatically created upon save.
"""
domain_url = models.CharField(max_length=128, unique=True)
schema_name = models.CharField(max_length=63, unique=True,
validators=[_check_schema_name])
objects = TenantQueryset.as_manager()
class Meta:
abstract = True
def save(self, verbosity=1, *args, **kwargs):
is_new = self.pk is None
<|code_end|>
, determine the next line of code. You have imports:
from django.core.management import call_command
from django.db import connection, models
from tenant_schemas.postgresql_backend.base import _check_schema_name
from tenant_schemas.signals import post_schema_sync
from tenant_schemas.utils import get_public_schema_name, schema_exists
and context (class names, function names, or code) available:
# Path: tenant_schemas/postgresql_backend/base.py
# def _check_schema_name(name):
# if not _is_valid_schema_name(name):
# raise ValidationError("Invalid string used for the schema name.")
#
# Path: tenant_schemas/utils.py
# def get_public_schema_name():
# return getattr(settings, 'PUBLIC_SCHEMA_NAME', 'public')
#
# def schema_exists(schema_name):
# cursor = connection.cursor()
#
# # check if this schema already exists in the db
# sql = 'SELECT EXISTS(SELECT 1 FROM pg_catalog.pg_namespace WHERE LOWER(nspname) = LOWER(%s))'
# cursor.execute(sql, (schema_name, ))
#
# row = cursor.fetchone()
# if row:
# exists = row[0]
# else:
# exists = False
#
# cursor.close()
#
# return exists
. Output only the next line. | if is_new and connection.schema_name != get_public_schema_name(): |
Continue the code snippet: <|code_start|> raise Exception("Can't create tenant outside the public schema. "
"Current schema is %s." % connection.schema_name)
elif not is_new and connection.schema_name not in (self.schema_name, get_public_schema_name()):
raise Exception("Can't update tenant outside it's own schema or "
"the public schema. Current schema is %s."
% connection.schema_name)
super(TenantMixin, self).save(*args, **kwargs)
if is_new and self.auto_create_schema:
try:
self.create_schema(check_if_exists=True, verbosity=verbosity)
except:
# We failed creating the tenant, delete what we created and
# re-raise the exception
self.delete(force_drop=True)
raise
else:
post_schema_sync.send(sender=TenantMixin, tenant=self)
def delete(self, force_drop=False, *args, **kwargs):
"""
Deletes this row. Drops the tenant's schema if the attribute
auto_drop_schema set to True.
"""
if connection.schema_name not in (self.schema_name, get_public_schema_name()):
raise Exception("Can't delete tenant outside it's own schema or "
"the public schema. Current schema is %s."
% connection.schema_name)
<|code_end|>
. Use current file imports:
from django.core.management import call_command
from django.db import connection, models
from tenant_schemas.postgresql_backend.base import _check_schema_name
from tenant_schemas.signals import post_schema_sync
from tenant_schemas.utils import get_public_schema_name, schema_exists
and context (classes, functions, or code) from other files:
# Path: tenant_schemas/postgresql_backend/base.py
# def _check_schema_name(name):
# if not _is_valid_schema_name(name):
# raise ValidationError("Invalid string used for the schema name.")
#
# Path: tenant_schemas/utils.py
# def get_public_schema_name():
# return getattr(settings, 'PUBLIC_SCHEMA_NAME', 'public')
#
# def schema_exists(schema_name):
# cursor = connection.cursor()
#
# # check if this schema already exists in the db
# sql = 'SELECT EXISTS(SELECT 1 FROM pg_catalog.pg_namespace WHERE LOWER(nspname) = LOWER(%s))'
# cursor.execute(sql, (schema_name, ))
#
# row = cursor.fetchone()
# if row:
# exists = row[0]
# else:
# exists = False
#
# cursor.close()
#
# return exists
. Output only the next line. | if schema_exists(self.schema_name) and (self.auto_drop_schema or force_drop): |
Predict the next line for this snippet: <|code_start|>
class StandardExecutor(MigrationExecutor):
codename = 'standard'
def run_tenant_migrations(self, tenants):
for schema_name in tenants:
<|code_end|>
with the help of current file imports:
from tenant_schemas.migration_executors.base import MigrationExecutor, run_migrations
and context from other files:
# Path: tenant_schemas/migration_executors/base.py
# class MigrationExecutor(object):
# codename = None
#
# def __init__(self, args, options):
# self.args = args
# self.options = options
#
# def run_migrations(self, tenants):
# public_schema_name = get_public_schema_name()
#
# if public_schema_name in tenants:
# run_migrations(self.args, self.options, self.codename, public_schema_name)
# tenants.pop(tenants.index(public_schema_name))
#
# self.run_tenant_migrations(tenants)
#
# def run_tenant_migrations(self, tenant):
# raise NotImplementedError
#
# def run_migrations(args, options, executor_codename, schema_name, allow_atomic=True):
# from django.core.management import color
# from django.core.management.base import OutputWrapper
# from django.db import connection
#
# style = color.color_style()
#
# def style_func(msg):
# return '[%s:%s] %s' % (
# style.NOTICE(executor_codename),
# style.NOTICE(schema_name),
# msg
# )
#
# stdout = OutputWrapper(sys.stdout)
# stdout.style_func = style_func
# stderr = OutputWrapper(sys.stderr)
# stderr.style_func = style_func
# if int(options.get('verbosity', 1)) >= 1:
# stdout.write(style.NOTICE("=== Running migrate for schema %s" % schema_name))
#
# connection.set_schema(schema_name)
# MigrateCommand(stdout=stdout, stderr=stderr).execute(*args, **options)
#
# try:
# transaction.commit()
# connection.close()
# connection.connection = None
# except transaction.TransactionManagementError:
# if not allow_atomic:
# raise
#
# # We are in atomic transaction, don't close connections
# pass
#
# connection.set_schema_to_public()
, which may contain function names, class names, or code. Output only the next line. | run_migrations(self.args, self.options, self.codename, schema_name) |
Given snippet: <|code_start|> obj="django.conf.settings",
hint="This is necessary to overwrite built-in django "
"management commands with their schema-aware "
"implementations.",
id="tenant_schemas.W001"),
])
@override_settings(INSTALLED_APPS=[
'dts_test_app',
'customers',
'tenant_schemas',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
])
def test_tenant_schemas_after_custom_apps_in_installed_apps(self):
self.assertBestPractice([])
@override_settings(TENANT_APPS=())
def test_tenant_apps_empty(self):
self.assertBestPractice([
Error("TENANT_APPS is empty.",
hint="Maybe you don't need this app?",
id="tenant_schemas.E001"),
])
@override_settings(PG_EXTRA_SEARCH_PATHS=['public', 'demo1', 'demo2'])
def test_public_schema_on_extra_search_paths(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.apps import apps
from django.core.checks import Critical, Error, Warning
from django.test import TestCase
from django.test.utils import override_settings
from tenant_schemas.apps import best_practice
from tenant_schemas.utils import get_tenant_model
from django.conf import settings
from django.conf import settings
from django.conf import settings
and context:
# Path: tenant_schemas/utils.py
# def get_tenant_model():
# return get_model(*settings.TENANT_MODEL.split("."))
which might include code, classes, or functions. Output only the next line. | TenantModel = get_tenant_model() |
Predict the next line for this snippet: <|code_start|> else:
files.append(filename)
return dirs, files
def size(self, name):
return len(self.files[name])
class LocalStorage(MemoryStorage):
"""
Emulates a storage class that stores files on disk.
"""
def path(self, name):
return '/path/to/' + name
class RemoteStorage(MemoryStorage):
"""
Emulates a storage class that stores files in memory.
"""
def url(self, name):
return '/url/of/' + name
class StoragesTest(TestCase):
@override_settings(GALLERY_FOO_STORAGE='gallery.test_storages.MemoryStorage')
def test_get_storage(self):
<|code_end|>
with the help of current file imports:
import io
from django.core.exceptions import ImproperlyConfigured
from django.core.files.storage import FileSystemStorage, Storage
from django.test import TestCase
from django.test.utils import override_settings
from .storages import get_storage
and context from other files:
# Path: gallery/storages.py
# @functools.lru_cache()
# def get_storage(name):
# name = name.upper()
# storage_setting = f'GALLERY_{name}_STORAGE'
# dir_setting = f'GALLERY_{name}_DIR'
# try:
# storage_class = getattr(settings, storage_setting)
# except AttributeError:
# # There's a good chance that this fallback will survive for a long
# # time because deprecating it would require updating all the tests.
# try:
# storage_dir = getattr(settings, dir_setting)
# except AttributeError:
# raise ImproperlyConfigured(
# f"Please define {storage_setting} or {dir_setting}")
# else:
# return FileSystemStorage(location=storage_dir)
# else:
# return import_string(storage_class)()
, which may contain function names, class names, or code. Output only the next line. | foo_storage = get_storage('foo') |
Predict the next line after this snippet: <|code_start|> Utility function to create an image for testing.
"""
im = Image.new(mode, (width, height))
draw = ImageDraw.Draw(im)
draw.rectangle([0, 0, width // 2, height // 2], '#F00')
draw.rectangle([width // 2, 0, width, height // 2], '#0F0')
draw.rectangle([0, height // 2, width // 2, height], '#00F')
draw.rectangle([width // 2, height // 2, width, height], '#000')
draw.rectangle([width // 4, height // 4, 3 * width // 4, 3 * height // 4], '#FFF')
im_bytes_io = io.BytesIO()
im.save(im_bytes_io, format)
im_bytes_io.seek(0)
storage.save(name, im_bytes_io)
@override_settings(GALLERY_RESIZE_PRESETS={
'thumbnail': (8, 8, True),
'preview': (16, 16, False),
})
class ThumbnailTests(TestCase):
def setUp(self):
super().setUp()
self.storage = MemoryStorage()
def make_image(self, width, height,
image_name='original.jpg', format='JPEG', mode='RGB'):
make_image(self.storage, image_name, width, height, format, mode)
<|code_end|>
using the current file's imports:
import io
from django.test import TestCase
from django.test.utils import override_settings
from PIL import Image, ImageDraw
from .imgutil import make_thumbnail
from .test_storages import MemoryStorage
and any relevant context from other files:
# Path: gallery/imgutil.py
# def make_thumbnail(image_name, thumb_name, preset,
# image_storage, thumb_storage):
#
# options = getattr(settings, 'GALLERY_RESIZE_OPTIONS', {})
# presets = getattr(settings, 'GALLERY_RESIZE_PRESETS', {})
#
# # Load the image
# image = Image.open(image_storage.open(image_name))
# format = image.format
#
# if format == 'JPEG':
# # Auto-rotate JPEG files based on EXIF information
# try: # pragma: no cover
# # Use of an undocumented API — let's catch exceptions liberally
# orientation = image._getexif()[274]
# image = exif_rotations[orientation](image)
# except Exception:
# pass
#
# # Increase Pillow's buffer from 64k to 4MB to avoid JPEG save errors
# ImageFile.MAXBLOCK = 4194304
#
# # Pre-crop if requested and the aspect ratios don't match exactly
# image_width, image_height = image.size
# thumb_width, thumb_height, crop = presets[preset]
# if crop:
# if thumb_width * image_height > image_width * thumb_height:
# target_height = image_width * thumb_height // thumb_width
# top = (image_height - target_height) // 2
# image = image.crop((0, top, image_width, top + target_height))
# elif thumb_width * image_height < image_width * thumb_height:
# target_width = image_height * thumb_width // thumb_height
# left = (image_width - target_width) // 2
# image = image.crop((left, 0, left + target_width, image_height))
#
# # Resize
# image.thumbnail((thumb_width, thumb_height), Image.ANTIALIAS)
#
# # Save the thumbnail
# thumb_bytes_io = io.BytesIO()
# image.save(thumb_bytes_io, format, **options.get(image.format, {}))
# thumb_bytes_io.seek(0)
# thumb_storage.save(thumb_name, thumb_bytes_io)
#
# Path: gallery/test_storages.py
# class MemoryStorage(Storage):
# """
# Limited implementation of an in-memory file storage.
#
# This class does the bare minimum for tests to pass. It doesn't implement
# accessed/created/modified_time.
#
# """
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.files = {}
#
# def _open(self, name, mode='rb'):
# assert mode == 'rb'
# return io.BytesIO(self.files[name])
#
# def _save(self, name, content):
# content = content.read()
# assert isinstance(content, bytes)
# self.files[name] = content
# return name
#
# def delete(self, name):
# self.files.pop(name, None)
#
# def exists(self, name):
# return name in self.files
#
# def listdir(self, name):
# dirs, files = [], []
# for filename in sorted(self.files):
# filename = filename[len(name):]
# if '/' in filename:
# dirs.append(filename.partition('/')[0])
# else:
# files.append(filename)
# return dirs, files
#
# def size(self, name):
# return len(self.files[name])
. Output only the next line. | def make_thumbnail(self, preset, |
Predict the next line after this snippet: <|code_start|>
def make_image(storage, name, width, height, format='JPEG', mode='RGB'):
"""
Utility function to create an image for testing.
"""
im = Image.new(mode, (width, height))
draw = ImageDraw.Draw(im)
draw.rectangle([0, 0, width // 2, height // 2], '#F00')
draw.rectangle([width // 2, 0, width, height // 2], '#0F0')
draw.rectangle([0, height // 2, width // 2, height], '#00F')
draw.rectangle([width // 2, height // 2, width, height], '#000')
draw.rectangle([width // 4, height // 4, 3 * width // 4, 3 * height // 4], '#FFF')
im_bytes_io = io.BytesIO()
im.save(im_bytes_io, format)
im_bytes_io.seek(0)
storage.save(name, im_bytes_io)
@override_settings(GALLERY_RESIZE_PRESETS={
'thumbnail': (8, 8, True),
'preview': (16, 16, False),
})
class ThumbnailTests(TestCase):
def setUp(self):
super().setUp()
<|code_end|>
using the current file's imports:
import io
from django.test import TestCase
from django.test.utils import override_settings
from PIL import Image, ImageDraw
from .imgutil import make_thumbnail
from .test_storages import MemoryStorage
and any relevant context from other files:
# Path: gallery/imgutil.py
# def make_thumbnail(image_name, thumb_name, preset,
# image_storage, thumb_storage):
#
# options = getattr(settings, 'GALLERY_RESIZE_OPTIONS', {})
# presets = getattr(settings, 'GALLERY_RESIZE_PRESETS', {})
#
# # Load the image
# image = Image.open(image_storage.open(image_name))
# format = image.format
#
# if format == 'JPEG':
# # Auto-rotate JPEG files based on EXIF information
# try: # pragma: no cover
# # Use of an undocumented API — let's catch exceptions liberally
# orientation = image._getexif()[274]
# image = exif_rotations[orientation](image)
# except Exception:
# pass
#
# # Increase Pillow's buffer from 64k to 4MB to avoid JPEG save errors
# ImageFile.MAXBLOCK = 4194304
#
# # Pre-crop if requested and the aspect ratios don't match exactly
# image_width, image_height = image.size
# thumb_width, thumb_height, crop = presets[preset]
# if crop:
# if thumb_width * image_height > image_width * thumb_height:
# target_height = image_width * thumb_height // thumb_width
# top = (image_height - target_height) // 2
# image = image.crop((0, top, image_width, top + target_height))
# elif thumb_width * image_height < image_width * thumb_height:
# target_width = image_height * thumb_width // thumb_height
# left = (image_width - target_width) // 2
# image = image.crop((left, 0, left + target_width, image_height))
#
# # Resize
# image.thumbnail((thumb_width, thumb_height), Image.ANTIALIAS)
#
# # Save the thumbnail
# thumb_bytes_io = io.BytesIO()
# image.save(thumb_bytes_io, format, **options.get(image.format, {}))
# thumb_bytes_io.seek(0)
# thumb_storage.save(thumb_name, thumb_bytes_io)
#
# Path: gallery/test_storages.py
# class MemoryStorage(Storage):
# """
# Limited implementation of an in-memory file storage.
#
# This class does the bare minimum for tests to pass. It doesn't implement
# accessed/created/modified_time.
#
# """
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.files = {}
#
# def _open(self, name, mode='rb'):
# assert mode == 'rb'
# return io.BytesIO(self.files[name])
#
# def _save(self, name, content):
# content = content.read()
# assert isinstance(content, bytes)
# self.files[name] = content
# return name
#
# def delete(self, name):
# self.files.pop(name, None)
#
# def exists(self, name):
# return name in self.files
#
# def listdir(self, name):
# dirs, files = [], []
# for filename in sorted(self.files):
# filename = filename[len(name):]
# if '/' in filename:
# dirs.append(filename.partition('/')[0])
# else:
# files.append(filename)
# return dirs, files
#
# def size(self, name):
# return len(self.files[name])
. Output only the next line. | self.storage = MemoryStorage() |
Given the following code snippet before the placeholder: <|code_start|> def get_previous_in_queryset(self, photos):
if self.date is None:
photos = photos.filter(
date__isnull=True, filename__lt=self.filename)
else:
photos = photos.filter(
Q(date__isnull=True) |
Q(date__lt=self.date) |
Q(date=self.date, filename__gt=self.filename))
return photos.order_by('-date', '-filename')[:1].get()
def image_name(self):
return os.path.join(self.album.dirpath, self.filename)
def thumb_name(self, preset):
prefix = self.album.date.strftime('%y%m')
hsh = hashlib.md5()
hsh.update(str(settings.SECRET_KEY).encode())
hsh.update(str(self.album.pk).encode())
hsh.update(str(self.pk).encode())
hsh.update(str(settings.GALLERY_RESIZE_PRESETS[preset]).encode())
ext = os.path.splitext(self.filename)[1].lower()
return os.path.join(prefix, hsh.hexdigest() + ext)
def thumbnail(self, preset):
image_name = self.image_name()
thumb_name = self.thumb_name(preset)
photo_storage = get_storage('photo')
cache_storage = get_storage('cache')
if not cache_storage.exists(thumb_name):
<|code_end|>
, predict the next line using imports from the current file:
import hashlib
import os
from django.conf import settings
from django.contrib.auth.models import Group, User
from django.db import models
from django.db.models import Q
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from .imgutil import make_thumbnail
from .storages import get_storage
and context including class names, function names, and sometimes code from other files:
# Path: gallery/imgutil.py
# def make_thumbnail(image_name, thumb_name, preset,
# image_storage, thumb_storage):
#
# options = getattr(settings, 'GALLERY_RESIZE_OPTIONS', {})
# presets = getattr(settings, 'GALLERY_RESIZE_PRESETS', {})
#
# # Load the image
# image = Image.open(image_storage.open(image_name))
# format = image.format
#
# if format == 'JPEG':
# # Auto-rotate JPEG files based on EXIF information
# try: # pragma: no cover
# # Use of an undocumented API — let's catch exceptions liberally
# orientation = image._getexif()[274]
# image = exif_rotations[orientation](image)
# except Exception:
# pass
#
# # Increase Pillow's buffer from 64k to 4MB to avoid JPEG save errors
# ImageFile.MAXBLOCK = 4194304
#
# # Pre-crop if requested and the aspect ratios don't match exactly
# image_width, image_height = image.size
# thumb_width, thumb_height, crop = presets[preset]
# if crop:
# if thumb_width * image_height > image_width * thumb_height:
# target_height = image_width * thumb_height // thumb_width
# top = (image_height - target_height) // 2
# image = image.crop((0, top, image_width, top + target_height))
# elif thumb_width * image_height < image_width * thumb_height:
# target_width = image_height * thumb_width // thumb_height
# left = (image_width - target_width) // 2
# image = image.crop((left, 0, left + target_width, image_height))
#
# # Resize
# image.thumbnail((thumb_width, thumb_height), Image.ANTIALIAS)
#
# # Save the thumbnail
# thumb_bytes_io = io.BytesIO()
# image.save(thumb_bytes_io, format, **options.get(image.format, {}))
# thumb_bytes_io.seek(0)
# thumb_storage.save(thumb_name, thumb_bytes_io)
#
# Path: gallery/storages.py
# @functools.lru_cache()
# def get_storage(name):
# name = name.upper()
# storage_setting = f'GALLERY_{name}_STORAGE'
# dir_setting = f'GALLERY_{name}_DIR'
# try:
# storage_class = getattr(settings, storage_setting)
# except AttributeError:
# # There's a good chance that this fallback will survive for a long
# # time because deprecating it would require updating all the tests.
# try:
# storage_dir = getattr(settings, dir_setting)
# except AttributeError:
# raise ImproperlyConfigured(
# f"Please define {storage_setting} or {dir_setting}")
# else:
# return FileSystemStorage(location=storage_dir)
# else:
# return import_string(storage_class)()
. Output only the next line. | make_thumbnail(image_name, thumb_name, preset, |
Using the snippet: <|code_start|> Q(date=self.date, filename__gt=self.filename))
return photos.order_by('date', 'filename')[:1].get()
def get_previous_in_queryset(self, photos):
if self.date is None:
photos = photos.filter(
date__isnull=True, filename__lt=self.filename)
else:
photos = photos.filter(
Q(date__isnull=True) |
Q(date__lt=self.date) |
Q(date=self.date, filename__gt=self.filename))
return photos.order_by('-date', '-filename')[:1].get()
def image_name(self):
return os.path.join(self.album.dirpath, self.filename)
def thumb_name(self, preset):
prefix = self.album.date.strftime('%y%m')
hsh = hashlib.md5()
hsh.update(str(settings.SECRET_KEY).encode())
hsh.update(str(self.album.pk).encode())
hsh.update(str(self.pk).encode())
hsh.update(str(settings.GALLERY_RESIZE_PRESETS[preset]).encode())
ext = os.path.splitext(self.filename)[1].lower()
return os.path.join(prefix, hsh.hexdigest() + ext)
def thumbnail(self, preset):
image_name = self.image_name()
thumb_name = self.thumb_name(preset)
<|code_end|>
, determine the next line of code. You have imports:
import hashlib
import os
from django.conf import settings
from django.contrib.auth.models import Group, User
from django.db import models
from django.db.models import Q
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from .imgutil import make_thumbnail
from .storages import get_storage
and context (class names, function names, or code) available:
# Path: gallery/imgutil.py
# def make_thumbnail(image_name, thumb_name, preset,
# image_storage, thumb_storage):
#
# options = getattr(settings, 'GALLERY_RESIZE_OPTIONS', {})
# presets = getattr(settings, 'GALLERY_RESIZE_PRESETS', {})
#
# # Load the image
# image = Image.open(image_storage.open(image_name))
# format = image.format
#
# if format == 'JPEG':
# # Auto-rotate JPEG files based on EXIF information
# try: # pragma: no cover
# # Use of an undocumented API — let's catch exceptions liberally
# orientation = image._getexif()[274]
# image = exif_rotations[orientation](image)
# except Exception:
# pass
#
# # Increase Pillow's buffer from 64k to 4MB to avoid JPEG save errors
# ImageFile.MAXBLOCK = 4194304
#
# # Pre-crop if requested and the aspect ratios don't match exactly
# image_width, image_height = image.size
# thumb_width, thumb_height, crop = presets[preset]
# if crop:
# if thumb_width * image_height > image_width * thumb_height:
# target_height = image_width * thumb_height // thumb_width
# top = (image_height - target_height) // 2
# image = image.crop((0, top, image_width, top + target_height))
# elif thumb_width * image_height < image_width * thumb_height:
# target_width = image_height * thumb_width // thumb_height
# left = (image_width - target_width) // 2
# image = image.crop((left, 0, left + target_width, image_height))
#
# # Resize
# image.thumbnail((thumb_width, thumb_height), Image.ANTIALIAS)
#
# # Save the thumbnail
# thumb_bytes_io = io.BytesIO()
# image.save(thumb_bytes_io, format, **options.get(image.format, {}))
# thumb_bytes_io.seek(0)
# thumb_storage.save(thumb_name, thumb_bytes_io)
#
# Path: gallery/storages.py
# @functools.lru_cache()
# def get_storage(name):
# name = name.upper()
# storage_setting = f'GALLERY_{name}_STORAGE'
# dir_setting = f'GALLERY_{name}_DIR'
# try:
# storage_class = getattr(settings, storage_setting)
# except AttributeError:
# # There's a good chance that this fallback will survive for a long
# # time because deprecating it would require updating all the tests.
# try:
# storage_dir = getattr(settings, dir_setting)
# except AttributeError:
# raise ImproperlyConfigured(
# f"Please define {storage_setting} or {dir_setting}")
# else:
# return FileSystemStorage(location=storage_dir)
# else:
# return import_string(storage_class)()
. Output only the next line. | photo_storage = get_storage('photo') |
Given the following code snippet before the placeholder: <|code_start|>"""
Bare view implementation of the pet resource.
"""
def find_pets(request, limit=None, tags=()):
pets = Pet.objects.all()[:limit]
if tags:
tags_q = reduce(
lambda q, term: q | Q(tag=term),
tags,
Q()
)
pets = pets.filter(tags_q)
<|code_end|>
, predict the next line using imports from the current file:
from functools import reduce
from django.db.models import Q
from lepo_tests.models import Pet
from lepo_tests.schemata import PetSchema
and context including class names, function names, and sometimes code from other files:
# Path: lepo_tests/models.py
# class Pet(models.Model):
# name = models.CharField(max_length=128)
# tag = models.CharField(max_length=128, blank=True)
#
# Path: lepo_tests/schemata.py
# class PetSchema(Schema):
# id = fields.Integer(required=False)
# name = fields.Str(required=True)
# tag = fields.Str(required=False)
. Output only the next line. | return PetSchema().dump(pets, many=True) |
Next line prediction: <|code_start|> if type == 'number' or format in ('float', 'double'):
return float(value)
if format == 'byte': # base64 encoded characters
return base64.b64decode(value)
if format == 'binary': # any sequence of octets
return force_bytes(value)
if format == 'date': # ISO8601 date
return iso8601.parse_date(value).date()
if format == 'dateTime': # ISO8601 datetime
return iso8601.parse_date(value)
if type == 'string':
return force_str(value)
return value
def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
"""
:param request: HttpRequest with attached api_info
:type request: HttpRequest
:type view_kwargs: dict[str, object]
:type capture_errors: bool
:rtype: dict[str, object]
"""
if view_kwargs is None:
view_kwargs = {}
params = {}
errors = {}
for param in request.api_info.operation.parameters:
try:
value = param.get_value(request, view_kwargs)
<|code_end|>
. Use current file imports:
(import base64
import iso8601
from django.core.exceptions import ImproperlyConfigured
from django.utils.encoding import force_bytes, force_str
from lepo.apidef.parameter.base import NO_VALUE
from lepo.excs import ErroneousParameters, MissingParameter)
and context including class names, function names, or small code snippets from other files:
# Path: lepo/apidef/parameter/base.py
# NO_VALUE = object()
#
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class MissingParameter(ValueError):
# pass
. Output only the next line. | if value is NO_VALUE: |
Given the following code snippet before the placeholder: <|code_start|>
def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
"""
:param request: HttpRequest with attached api_info
:type request: HttpRequest
:type view_kwargs: dict[str, object]
:type capture_errors: bool
:rtype: dict[str, object]
"""
if view_kwargs is None:
view_kwargs = {}
params = {}
errors = {}
for param in request.api_info.operation.parameters:
try:
value = param.get_value(request, view_kwargs)
if value is NO_VALUE:
if param.has_default:
params[param.name] = param.default
elif param.required: # Required but missing
errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing')
continue # No value, or a default was added, or an error was added.
params[param.name] = param.cast(request.api_info.api, value)
except (NotImplementedError, ImproperlyConfigured):
raise
except Exception as e:
if not capture_errors:
raise
errors[param.name] = e
if errors:
<|code_end|>
, predict the next line using imports from the current file:
import base64
import iso8601
from django.core.exceptions import ImproperlyConfigured
from django.utils.encoding import force_bytes, force_str
from lepo.apidef.parameter.base import NO_VALUE
from lepo.excs import ErroneousParameters, MissingParameter
and context including class names, function names, and sometimes code from other files:
# Path: lepo/apidef/parameter/base.py
# NO_VALUE = object()
#
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class MissingParameter(ValueError):
# pass
. Output only the next line. | raise ErroneousParameters(errors, params) |
Given snippet: <|code_start|> if format == 'binary': # any sequence of octets
return force_bytes(value)
if format == 'date': # ISO8601 date
return iso8601.parse_date(value).date()
if format == 'dateTime': # ISO8601 datetime
return iso8601.parse_date(value)
if type == 'string':
return force_str(value)
return value
def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901
"""
:param request: HttpRequest with attached api_info
:type request: HttpRequest
:type view_kwargs: dict[str, object]
:type capture_errors: bool
:rtype: dict[str, object]
"""
if view_kwargs is None:
view_kwargs = {}
params = {}
errors = {}
for param in request.api_info.operation.parameters:
try:
value = param.get_value(request, view_kwargs)
if value is NO_VALUE:
if param.has_default:
params[param.name] = param.default
elif param.required: # Required but missing
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import base64
import iso8601
from django.core.exceptions import ImproperlyConfigured
from django.utils.encoding import force_bytes, force_str
from lepo.apidef.parameter.base import NO_VALUE
from lepo.excs import ErroneousParameters, MissingParameter
and context:
# Path: lepo/apidef/parameter/base.py
# NO_VALUE = object()
#
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class MissingParameter(ValueError):
# pass
which might include code, classes, or functions. Output only the next line. | errors[param.name] = MissingParameter(f'parameter {param.name} is required but missing') |
Given the code snippet: <|code_start|>
@doc_versions
def test_codegen(doc_version, capsys):
path = os.path.realpath(os.path.join(os.path.dirname(__file__), doc_version, 'petstore-expanded.yaml'))
<|code_end|>
, generate the next line using the imports in this file:
import os
from lepo import codegen
from lepo_tests.tests.utils import doc_versions
and context (functions, classes, or occasionally code) from other files:
# Path: lepo/codegen.py
# HANDLER_TEMPLATE = '''
# def {func_name}(request, {parameters}):
# raise NotImplementedError('Handler {operation_id} not implemented')
# '''.strip()
# def generate_handler_stub(router, handler_template=HANDLER_TEMPLATE):
# def cmdline(args=None): # pragma: no cover
#
# Path: lepo_tests/tests/utils.py
# TESTS_DIR = os.path.dirname(__file__)
# DOC_VERSIONS = ['swagger2', 'openapi3']
# def get_router(fixture_name):
# def get_data_from_response(response, status=200):
# def cast_parameter_value(apidoc, parameter, value):
# def get_apidoc_from_version(version, content={}):
# def make_request_for_operation(operation, method='GET', query_string=''):
. Output only the next line. | codegen.cmdline([path]) |
Based on the snippet: <|code_start|> return self.data['operationId']
@cached_property
def parameters(self):
"""
Combined path-level and operation-level parameters.
Any $refs are resolved here.
Note that this implementation differs from the spec in that we only use
the _name_ of a parameter to consider its uniqueness, not the name and location.
This is because we end up passing parameters to the handler by name anyway,
so any duplicate names, even if they had different locations, would be horribly mangled.
:rtype: list[Parameter]
"""
return list(self.get_parameter_dict().values())
def get_parameter_dict(self):
parameters = OrderedDict()
for parameter in self._get_regular_parameters():
parameters[parameter.name] = parameter
return parameters
def _get_regular_parameters(self):
for source in (
self.path.mapping.get('parameters', ()),
self.data.get('parameters', {}),
):
<|code_end|>
, predict the immediate next line with the help of imports:
from collections.__init__ import OrderedDict
from django.utils.functional import cached_property
from lepo.utils import maybe_resolve
and context (classes, functions, sometimes code) from other files:
# Path: lepo/utils.py
# def maybe_resolve(object, resolve):
# """
# Call `resolve` on the `object`'s `$ref` value if it has one.
#
# :param object: An object.
# :param resolve: A resolving function.
# :return: An object, or some other object! :sparkles:
# """
# if isinstance(object, dict) and object.get('$ref'):
# return resolve(object['$ref'])
# return object
. Output only the next line. | source = maybe_resolve(source, self.api.resolve_reference) |
Here is a snippet: <|code_start|> return force_str(value).split(',')
def dot_split(value):
return force_str(value).split('.')
def space_split(value):
return force_str(value).split(' ')
def tab_split(value):
return force_str(value).split('\t')
def pipe_split(value):
return force_str(value).split('|')
def read_body(request, parameter=None):
if parameter:
if parameter.type == 'binary':
return request.body.read()
try:
if request.content_type == 'multipart/form-data':
# TODO: this definitely doesn't handle multiple values for the same key correctly
data = dict()
data.update(request.POST.items())
data.update(request.FILES.items())
return data
<|code_end|>
. Write the next line using the current file imports:
import jsonschema
from django.core.files import File
from django.utils.encoding import force_str
from jsonschema import Draft4Validator
from lepo.decoders import get_decoder
from lepo.excs import InvalidBodyContent
from lepo.utils import maybe_resolve
and context from other files:
# Path: lepo/decoders.py
# def get_decoder(content_type):
# """
# Get a decoder function for the content type given, or None if there is none.
#
# :param content_type: Content type string
# :type content_type: str
# :return: function or None
# """
# if content_type.endswith('+json'): # Process all +json vendor types like JSON
# content_type = 'application/json'
#
# if content_type in DECODERS:
# return DECODERS[content_type]
#
# return None
#
# Path: lepo/excs.py
# class InvalidBodyContent(ValueError):
# pass
#
# Path: lepo/utils.py
# def maybe_resolve(object, resolve):
# """
# Call `resolve` on the `object`'s `$ref` value if it has one.
#
# :param object: An object.
# :param resolve: A resolving function.
# :return: An object, or some other object! :sparkles:
# """
# if isinstance(object, dict) and object.get('$ref'):
# return resolve(object['$ref'])
# return object
, which may include functions, classes, or code. Output only the next line. | decoder = get_decoder(request.content_type) |
Given snippet: <|code_start|> return force_str(value).split('.')
def space_split(value):
return force_str(value).split(' ')
def tab_split(value):
return force_str(value).split('\t')
def pipe_split(value):
return force_str(value).split('|')
def read_body(request, parameter=None):
if parameter:
if parameter.type == 'binary':
return request.body.read()
try:
if request.content_type == 'multipart/form-data':
# TODO: this definitely doesn't handle multiple values for the same key correctly
data = dict()
data.update(request.POST.items())
data.update(request.FILES.items())
return data
decoder = get_decoder(request.content_type)
if decoder:
return decoder(request.body, encoding=request.content_params.get('charset', 'UTF-8'))
except Exception as exc:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import jsonschema
from django.core.files import File
from django.utils.encoding import force_str
from jsonschema import Draft4Validator
from lepo.decoders import get_decoder
from lepo.excs import InvalidBodyContent
from lepo.utils import maybe_resolve
and context:
# Path: lepo/decoders.py
# def get_decoder(content_type):
# """
# Get a decoder function for the content type given, or None if there is none.
#
# :param content_type: Content type string
# :type content_type: str
# :return: function or None
# """
# if content_type.endswith('+json'): # Process all +json vendor types like JSON
# content_type = 'application/json'
#
# if content_type in DECODERS:
# return DECODERS[content_type]
#
# return None
#
# Path: lepo/excs.py
# class InvalidBodyContent(ValueError):
# pass
#
# Path: lepo/utils.py
# def maybe_resolve(object, resolve):
# """
# Call `resolve` on the `object`'s `$ref` value if it has one.
#
# :param object: An object.
# :param resolve: A resolving function.
# :return: An object, or some other object! :sparkles:
# """
# if isinstance(object, dict) and object.get('$ref'):
# return resolve(object['$ref'])
# return object
which might include code, classes, or functions. Output only the next line. | raise InvalidBodyContent(f'Unable to parse this body as {request.content_type}') from exc |
Given the code snippet: <|code_start|>
def read_body(request, parameter=None):
if parameter:
if parameter.type == 'binary':
return request.body.read()
try:
if request.content_type == 'multipart/form-data':
# TODO: this definitely doesn't handle multiple values for the same key correctly
data = dict()
data.update(request.POST.items())
data.update(request.FILES.items())
return data
decoder = get_decoder(request.content_type)
if decoder:
return decoder(request.body, encoding=request.content_params.get('charset', 'UTF-8'))
except Exception as exc:
raise InvalidBodyContent(f'Unable to parse this body as {request.content_type}') from exc
raise NotImplementedError(f'No idea how to parse content-type {request.content_type}') # pragma: no cover
class LepoDraft4Validator(Draft4Validator):
def iter_errors(self, instance, _schema=None):
if isinstance(instance, File):
# Skip validating File instances that come from POST requests...
return
yield from super().iter_errors(instance, _schema)
def validate_schema(schema, api, value):
<|code_end|>
, generate the next line using the imports in this file:
import jsonschema
from django.core.files import File
from django.utils.encoding import force_str
from jsonschema import Draft4Validator
from lepo.decoders import get_decoder
from lepo.excs import InvalidBodyContent
from lepo.utils import maybe_resolve
and context (functions, classes, or occasionally code) from other files:
# Path: lepo/decoders.py
# def get_decoder(content_type):
# """
# Get a decoder function for the content type given, or None if there is none.
#
# :param content_type: Content type string
# :type content_type: str
# :return: function or None
# """
# if content_type.endswith('+json'): # Process all +json vendor types like JSON
# content_type = 'application/json'
#
# if content_type in DECODERS:
# return DECODERS[content_type]
#
# return None
#
# Path: lepo/excs.py
# class InvalidBodyContent(ValueError):
# pass
#
# Path: lepo/utils.py
# def maybe_resolve(object, resolve):
# """
# Call `resolve` on the `object`'s `$ref` value if it has one.
#
# :param object: An object.
# :param resolve: A resolving function.
# :return: An object, or some other object! :sparkles:
# """
# if isinstance(object, dict) and object.get('$ref'):
# return resolve(object['$ref'])
# return object
. Output only the next line. | schema = maybe_resolve(schema, resolve=api.resolve_reference) |
Next line prediction: <|code_start|> pet1 = Pet.objects.create(name='henlo')
pet2 = Pet.objects.create(name='worl')
assert len(get_data_from_response(client.get('/api/pets'))) == 2
client.delete(f'/api/pets/{pet1.id}')
assert len(get_data_from_response(client.get('/api/pets'))) == 1
@pytest.mark.django_db
def test_update_pet(client, api_urls):
pet1 = Pet.objects.create(name='henlo')
payload = {'name': 'worl', 'tag': 'bunner'}
resp = client.patch(
f'/api/pets/{pet1.id}',
json.dumps(payload),
content_type='application/json'
)
assert resp.status_code == 200
pet_data = get_data_from_response(client.get('/api/pets'))[0]
assert pet_data['name'] == 'worl'
assert pet_data['tag'] == 'bunner'
@pytest.mark.django_db
def test_invalid_operation(client, api_urls):
assert client.patch('/api/pets').status_code == 405
@pytest.mark.django_db
def test_invalid_body_format(client, api_urls):
<|code_end|>
. Use current file imports:
(import json
import django.conf
import pytest
from django.utils.crypto import get_random_string
from lepo.excs import ErroneousParameters, InvalidBodyContent, InvalidBodyFormat
from lepo_tests.models import Pet
from lepo_tests.tests.utils import get_data_from_response
from lepo_tests.utils import urlconf_map
from django.urls import clear_url_caches, set_urlconf
from django.core.urlresolvers import clear_url_caches, set_urlconf)
and context including class names, function names, or small code snippets from other files:
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class InvalidBodyContent(ValueError):
# pass
#
# class InvalidBodyFormat(ValueError):
# pass
#
# Path: lepo_tests/models.py
# class Pet(models.Model):
# name = models.CharField(max_length=128)
# tag = models.CharField(max_length=128, blank=True)
#
# Path: lepo_tests/tests/utils.py
# def get_data_from_response(response, status=200):
# if status and response.status_code != status:
# raise ValueError(f'failed status check ({response.status_code} != expected {status})') # pragma: no cover
# return json.loads(response.content.decode('utf-8'))
#
# Path: lepo_tests/utils.py
# def get_urlpatterns(handler_module, definition_file='swagger2/petstore-expanded.yaml'):
# def generate_urlconf_module(handler_style, version):
# def generate_urlconf_modules(handler_styles, versions):
# URLCONF_TEMPLATE = '''
# from lepo_tests.handlers import %(module)s
# from lepo_tests.utils import get_urlpatterns
# urlpatterns = get_urlpatterns(%(module)s, %(file)r)
# '''
. Output only the next line. | with pytest.raises(ErroneousParameters) as ei: |
Predict the next line for this snippet: <|code_start|>
pet_data = get_data_from_response(client.get('/api/pets'))[0]
assert pet_data['name'] == 'worl'
assert pet_data['tag'] == 'bunner'
@pytest.mark.django_db
def test_invalid_operation(client, api_urls):
assert client.patch('/api/pets').status_code == 405
@pytest.mark.django_db
def test_invalid_body_format(client, api_urls):
with pytest.raises(ErroneousParameters) as ei:
client.post(
'/api/pets',
b'<pet></pet>',
content_type='application/xml'
)
assert isinstance(ei.value.errors['pet'], InvalidBodyFormat)
@pytest.mark.django_db
def test_invalid_body_content(client, api_urls):
with pytest.raises(ErroneousParameters) as ei:
client.post(
'/api/pets',
b'{',
content_type='application/json'
)
<|code_end|>
with the help of current file imports:
import json
import django.conf
import pytest
from django.utils.crypto import get_random_string
from lepo.excs import ErroneousParameters, InvalidBodyContent, InvalidBodyFormat
from lepo_tests.models import Pet
from lepo_tests.tests.utils import get_data_from_response
from lepo_tests.utils import urlconf_map
from django.urls import clear_url_caches, set_urlconf
from django.core.urlresolvers import clear_url_caches, set_urlconf
and context from other files:
# Path: lepo/excs.py
# class ErroneousParameters(Exception):
# def __init__(self, error_map, parameters):
# self.errors = error_map
# self.parameters = parameters
#
# class InvalidBodyContent(ValueError):
# pass
#
# class InvalidBodyFormat(ValueError):
# pass
#
# Path: lepo_tests/models.py
# class Pet(models.Model):
# name = models.CharField(max_length=128)
# tag = models.CharField(max_length=128, blank=True)
#
# Path: lepo_tests/tests/utils.py
# def get_data_from_response(response, status=200):
# if status and response.status_code != status:
# raise ValueError(f'failed status check ({response.status_code} != expected {status})') # pragma: no cover
# return json.loads(response.content.decode('utf-8'))
#
# Path: lepo_tests/utils.py
# def get_urlpatterns(handler_module, definition_file='swagger2/petstore-expanded.yaml'):
# def generate_urlconf_module(handler_style, version):
# def generate_urlconf_modules(handler_styles, versions):
# URLCONF_TEMPLATE = '''
# from lepo_tests.handlers import %(module)s
# from lepo_tests.utils import get_urlpatterns
# urlpatterns = get_urlpatterns(%(module)s, %(file)r)
# '''
, which may contain function names, class names, or code. Output only the next line. | assert isinstance(ei.value.errors['pet'], InvalidBodyContent) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.