Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|>
class WireguardPeers(OpenWrtConverter):
netjson_key = 'wireguard_peers'
intermediate_key = 'network'
<|code_end|>
, predict the next line using imports from the current file:
from ..schema import schema
from .base import OpenWrtConverter
and context including class names, function names, and sometimes code from other files:
# Path: netjsonconfig/backends/openwrt/schema.py
. Output only the next line. | _schema = schema['properties']['wireguard_peers']['items'] |
Given snippet: <|code_start|>
class TestDefault(unittest.TestCase, _TabsMixin):
maxDiff = None
def test_render_default(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from openwisp_utils.tests import capture_stdout
from netjsonconfig import OpenWrt
from netjsonconfig.utils import _TabsMixin
and context:
# Path: netjsonconfig/backends/openwrt/openwrt.py
# class OpenWrt(BaseBackend):
# """
# OpenWRT / LEDE Configuration Backend
# """
#
# schema = schema
# converters = [
# converters.General,
# converters.Ntp,
# converters.Led,
# converters.Interfaces,
# converters.Routes,
# converters.Rules,
# converters.Switch,
# converters.Radios,
# converters.Wireless,
# converters.OpenVpn,
# converters.WireguardPeers,
# converters.Default,
# ]
# parser = OpenWrtParser
# renderer = OpenWrtRenderer
# list_identifiers = ['name', 'config_value', 'id']
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# uci = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# packages = packages_pattern.split(uci)
# if '' in packages:
# packages.remove('')
# # create an UCI file for each configuration package used
# for package in packages:
# lines = package.split('\n')
# package_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(config_path, package_name),
# contents=text_contents,
# )
#
# @classmethod
# def wireguard_auto_client(cls, **kwargs):
# data = Wireguard.auto_client(**kwargs)
# config = {
# 'interfaces': [
# {
# 'name': data['interface_name'],
# 'type': 'wireguard',
# 'private_key': data['client']['private_key'],
# 'port': data['client']['port'],
# # Default values for Wireguard Interface
# 'mtu': 1420,
# 'nohostroute': False,
# 'fwmark': '',
# 'ip6prefix': [],
# 'addresses': [],
# 'network': '',
# }
# ],
# 'wireguard_peers': [
# {
# 'interface': data['interface_name'],
# 'public_key': data['server']['public_key'],
# 'allowed_ips': data['server']['allowed_ips'],
# 'endpoint_host': data['server']['endpoint_host'],
# 'endpoint_port': data['server']['endpoint_port'],
# # Default values for Wireguard Peers
# 'preshared_key': '',
# 'persistent_keepalive': 60,
# 'route_allowed_ips': True,
# }
# ],
# }
# if data['client']['ip_address']:
# config['interfaces'][0]['addresses'] = [
# {
# 'proto': 'static',
# 'family': 'ipv4',
# 'address': data['client']['ip_address'],
# 'mask': 32,
# },
# ]
# return config
#
# @classmethod
# def vxlan_wireguard_auto_client(cls, **kwargs):
# config = cls.wireguard_auto_client(**kwargs)
# vxlan_config = VxlanWireguard.auto_client(**kwargs)
# vxlan_interface = {
# 'name': 'vxlan',
# 'type': 'vxlan',
# 'vtep': vxlan_config['server_ip_address'],
# 'port': 4789,
# 'vni': vxlan_config['vni'],
# 'tunlink': config['interfaces'][0]['name'],
# # Default values for VXLAN interface
# 'rxcsum': True,
# 'txcsum': True,
# 'mtu': 1280,
# 'ttl': 64,
# 'mac': '',
# 'disabled': False,
# 'network': '',
# }
# config['interfaces'].append(vxlan_interface)
# return config
#
# Path: netjsonconfig/utils.py
# class _TabsMixin(object): # pragma: nocover
# """
# mixin that adds _tabs method to test classes
# """
#
# def _tabs(self, string):
# """
# replace 4 spaces with 1 tab
# """
# return string.replace(' ', '\t')
which might include code, classes, or functions. Output only the next line. | o = OpenWrt( |
Given snippet: <|code_start|> 'contents': tar.extractfile(member).read().decode(),
}
)
return self.parse_text(text)
def _get_vpns(self, text):
results = re.split(vpn_pattern, text)
vpns = []
for result in results:
result = result.strip()
if not result:
continue
vpns.append(self._get_config(result))
return {'openvpn': vpns}
def _get_config(self, contents):
lines = contents.split('\n')
name = lines[0]
config = {'name': name}
for line in lines[1:]:
line = line.strip()
if not line:
continue
match = re.search(config_pattern, line)
parts = match.groups()
key = parts[0].replace('-', '_')
value = parts[1]
if not value:
value = True
config[key] = value
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
import tarfile
from ...utils import sorted_dict
from ..base.parser import BaseParser
and context:
# Path: netjsonconfig/utils.py
# def sorted_dict(dict_):
# return OrderedDict(sorted(dict_.items()))
#
# Path: netjsonconfig/backends/base/parser.py
# class BaseParser(object):
# """
# Base Parser class
# Parsers are used to parse a string or tar.gz
# which represents the router configuration
# """
#
# def __init__(self, config):
# if isinstance(config, str):
# data = self.parse_text(config)
# # presence of read() method
# # indicates a file-like object
# elif hasattr(config, 'read'):
# data = self.parse_tar(config)
# else:
# raise ParseError('Unrecognized format')
# self.intermediate_data = data
#
# def parse_text(self, config):
# raise NotImplementedError()
#
# def parse_tar(self, config):
# raise NotImplementedError()
which might include code, classes, or functions. Output only the next line. | return sorted_dict(config) |
Given snippet: <|code_start|>
vpn_pattern = re.compile('^# openvpn config:\s', flags=re.MULTILINE)
config_pattern = re.compile('^([^\s]*) ?(.*)$')
config_suffix = '.conf'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
import tarfile
from ...utils import sorted_dict
from ..base.parser import BaseParser
and context:
# Path: netjsonconfig/utils.py
# def sorted_dict(dict_):
# return OrderedDict(sorted(dict_.items()))
#
# Path: netjsonconfig/backends/base/parser.py
# class BaseParser(object):
# """
# Base Parser class
# Parsers are used to parse a string or tar.gz
# which represents the router configuration
# """
#
# def __init__(self, config):
# if isinstance(config, str):
# data = self.parse_text(config)
# # presence of read() method
# # indicates a file-like object
# elif hasattr(config, 'read'):
# data = self.parse_tar(config)
# else:
# raise ParseError('Unrecognized format')
# self.intermediate_data = data
#
# def parse_text(self, config):
# raise NotImplementedError()
#
# def parse_tar(self, config):
# raise NotImplementedError()
which might include code, classes, or functions. Output only the next line. | class OpenVpnParser(BaseParser): |
Continue the code snippet: <|code_start|> },
},
{"$ref": "#/definitions/tunnel"},
{"$ref": "#/definitions/server"},
],
},
},
"properties": {
"openvpn": {
"type": "array",
"title": "OpenVPN",
"uniqueItems": True,
"additionalItems": True,
"propertyOrder": 11,
"items": {
"type": "object",
"title": "VPN",
"additionalProperties": True,
"oneOf": [
{"$ref": "#/definitions/client"},
{"$ref": "#/definitions/server_manual"},
{"$ref": "#/definitions/server_bridged"},
{"$ref": "#/definitions/server_routed"},
],
},
}
},
}
schema = deepcopy(base_openvpn_schema)
<|code_end|>
. Use current file imports:
from copy import deepcopy
from ...schema import schema as default_schema
and context (classes, functions, or code) from other files:
# Path: netjsonconfig/schema.py
# DEFAULT_FILE_MODE = '0644'
# X509_FILE_MODE = '0600'
# MAC_PATTERN = '([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})'
# MAC_PATTERN_BLANK = '^({0}|)$'.format(MAC_PATTERN)
. Output only the next line. | schema['properties']['files'] = default_schema['properties']['files'] |
Given the code snippet: <|code_start|>
class TestDialup(unittest.TestCase, _TabsMixin):
maxDiff = None
_dialup_interface_netjson = {
"interfaces": [
{
"mtu": 1448,
"network": "xdsl",
"type": "dialup",
"name": "dsl0",
"password": "jf93nf82o023$",
"username": "dsluser",
"proto": "pppoe",
},
]
}
_dialup_interface_uci = """package network
config interface 'xdsl'
option ifname 'dsl0'
option mtu '1448'
option password 'jf93nf82o023$'
option proto 'pppoe'
option username 'dsluser'
"""
def test_render_dialup_interface(self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from netjsonconfig import OpenWrt
from netjsonconfig.utils import _TabsMixin
and context (functions, classes, or occasionally code) from other files:
# Path: netjsonconfig/backends/openwrt/openwrt.py
# class OpenWrt(BaseBackend):
# """
# OpenWRT / LEDE Configuration Backend
# """
#
# schema = schema
# converters = [
# converters.General,
# converters.Ntp,
# converters.Led,
# converters.Interfaces,
# converters.Routes,
# converters.Rules,
# converters.Switch,
# converters.Radios,
# converters.Wireless,
# converters.OpenVpn,
# converters.WireguardPeers,
# converters.Default,
# ]
# parser = OpenWrtParser
# renderer = OpenWrtRenderer
# list_identifiers = ['name', 'config_value', 'id']
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# uci = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# packages = packages_pattern.split(uci)
# if '' in packages:
# packages.remove('')
# # create an UCI file for each configuration package used
# for package in packages:
# lines = package.split('\n')
# package_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(config_path, package_name),
# contents=text_contents,
# )
#
# @classmethod
# def wireguard_auto_client(cls, **kwargs):
# data = Wireguard.auto_client(**kwargs)
# config = {
# 'interfaces': [
# {
# 'name': data['interface_name'],
# 'type': 'wireguard',
# 'private_key': data['client']['private_key'],
# 'port': data['client']['port'],
# # Default values for Wireguard Interface
# 'mtu': 1420,
# 'nohostroute': False,
# 'fwmark': '',
# 'ip6prefix': [],
# 'addresses': [],
# 'network': '',
# }
# ],
# 'wireguard_peers': [
# {
# 'interface': data['interface_name'],
# 'public_key': data['server']['public_key'],
# 'allowed_ips': data['server']['allowed_ips'],
# 'endpoint_host': data['server']['endpoint_host'],
# 'endpoint_port': data['server']['endpoint_port'],
# # Default values for Wireguard Peers
# 'preshared_key': '',
# 'persistent_keepalive': 60,
# 'route_allowed_ips': True,
# }
# ],
# }
# if data['client']['ip_address']:
# config['interfaces'][0]['addresses'] = [
# {
# 'proto': 'static',
# 'family': 'ipv4',
# 'address': data['client']['ip_address'],
# 'mask': 32,
# },
# ]
# return config
#
# @classmethod
# def vxlan_wireguard_auto_client(cls, **kwargs):
# config = cls.wireguard_auto_client(**kwargs)
# vxlan_config = VxlanWireguard.auto_client(**kwargs)
# vxlan_interface = {
# 'name': 'vxlan',
# 'type': 'vxlan',
# 'vtep': vxlan_config['server_ip_address'],
# 'port': 4789,
# 'vni': vxlan_config['vni'],
# 'tunlink': config['interfaces'][0]['name'],
# # Default values for VXLAN interface
# 'rxcsum': True,
# 'txcsum': True,
# 'mtu': 1280,
# 'ttl': 64,
# 'mac': '',
# 'disabled': False,
# 'network': '',
# }
# config['interfaces'].append(vxlan_interface)
# return config
#
# Path: netjsonconfig/utils.py
# class _TabsMixin(object): # pragma: nocover
# """
# mixin that adds _tabs method to test classes
# """
#
# def _tabs(self, string):
# """
# replace 4 spaces with 1 tab
# """
# return string.replace(' ', '\t')
. Output only the next line. | result = OpenWrt(self._dialup_interface_netjson).render() |
Using the snippet: <|code_start|>
class TestBackend(unittest.TestCase):
"""
tests for OpenVpn backend
"""
maxDiff = None
def test_server_mode(self):
<|code_end|>
, determine the next line of code. You have imports:
import copy
import tarfile
import unittest
from netjsonconfig import OpenVpn
from netjsonconfig.exceptions import ValidationError
and context (class names, function names, or code) available:
# Path: netjsonconfig/backends/openvpn/openvpn.py
# class OpenVpn(BaseVpnBackend):
# """
# OpenVPN 2.x Configuration Backend
# """
#
# schema = schema
# converters = [converters.OpenVpn]
# parser = OpenVpnParser
# renderer = OpenVpnRenderer
# list_identifiers = ['name']
# # BaseVpnBackend attributes
# vpn_pattern = vpn_pattern
# config_suffix = config_suffix
#
# @classmethod
# def auto_client(
# cls,
# host,
# server,
# ca_path=None,
# ca_contents=None,
# cert_path=None,
# cert_contents=None,
# key_path=None,
# key_contents=None,
# ):
# """
# Returns a configuration dictionary representing an OpenVPN client configuration
# that is compatible with the passed server configuration.
#
# :param host: remote VPN server
# :param server: dictionary representing a single OpenVPN server configuration
# :param ca_path: optional string representing path to CA, will consequently add
# a file in the resulting configuration dictionary
# :param ca_contents: optional string representing contents of CA file
# :param cert_path: optional string representing path to certificate, will consequently add
# a file in the resulting configuration dictionary
# :param cert_contents: optional string representing contents of cert file
# :param key_path: optional string representing path to key, will consequently add
# a file in the resulting configuration dictionary
# :param key_contents: optional string representing contents of key file
# :returns: dictionary representing a single OpenVPN client configuration
# """
# # client defaults
# client = {
# "mode": "p2p",
# "nobind": True,
# "resolv_retry": "infinite",
# "tls_client": True,
# }
# # remote
# port = server.get('port') or 1195
# client['remote'] = [{'host': host, 'port': port}]
# # proto
# if server.get('proto') == 'tcp-server':
# client['proto'] = 'tcp-client'
# else:
# client['proto'] = 'udp'
# # determine if pull must be True
# if 'server' in server or 'server_bridge' in server:
# client['pull'] = True
# # tls_client
# if 'tls_server' not in server or not server['tls_server']:
# client['tls_client'] = False
# # ns_cert_type
# ns_cert_type = {None: '', '': '', 'client': 'server'}
# client['ns_cert_type'] = ns_cert_type[server.get('ns_cert_type')]
# # remote_cert_tls
# remote_cert_tls = {None: '', '': '', 'client': 'server'}
# client['remote_cert_tls'] = remote_cert_tls[server.get('remote_cert_tls')]
# copy_keys = [
# 'name',
# 'dev_type',
# 'dev',
# 'comp_lzo',
# 'auth',
# 'cipher',
# 'ca',
# 'cert',
# 'key',
# 'pkcs12',
# 'mtu_test',
# 'fragment',
# 'mssfix',
# 'keepalive',
# 'persist_tun',
# 'mute',
# 'persist_key',
# 'script_security',
# 'user',
# 'group',
# 'log',
# 'mute_replay_warnings',
# 'secret',
# 'reneg_sec',
# 'tls_timeout',
# 'tls_cipher',
# 'float',
# 'fast_io',
# 'verb',
# "auth_nocache",
# ]
# for key in copy_keys:
# if key in server:
# client[key] = server[key]
# files = cls._auto_client_files(
# client,
# ca_path,
# ca_contents,
# cert_path,
# cert_contents,
# key_path,
# key_contents,
# )
# return {'openvpn': [client], 'files': files}
#
# @classmethod
# def _auto_client_files(
# cls,
# client,
# ca_path=None,
# ca_contents=None,
# cert_path=None,
# cert_contents=None,
# key_path=None,
# key_contents=None,
# ):
# """
# returns a list of NetJSON extra files for automatically generated clients
# produces side effects in ``client`` dictionary
# """
# files = []
# if ca_path and ca_contents:
# client['ca'] = ca_path
# files.append(dict(path=ca_path, contents=ca_contents, mode=X509_FILE_MODE))
# if cert_path and cert_contents:
# client['cert'] = cert_path
# files.append(
# dict(path=cert_path, contents=cert_contents, mode=X509_FILE_MODE)
# )
# if key_path and key_contents:
# client['key'] = key_path
# files.append(
# dict(
# path=key_path,
# contents=key_contents,
# mode=X509_FILE_MODE,
# )
# )
# return files
. Output only the next line. | c = OpenVpn( |
Continue the code snippet: <|code_start|>
class TestWireguard(unittest.TestCase, _TabsMixin):
maxDiff = None
def test_render_wireguard_interface(self):
<|code_end|>
. Use current file imports:
import unittest
from netjsonconfig import OpenWrt
from netjsonconfig.utils import _TabsMixin
and context (classes, functions, or code) from other files:
# Path: netjsonconfig/backends/openwrt/openwrt.py
# class OpenWrt(BaseBackend):
# """
# OpenWRT / LEDE Configuration Backend
# """
#
# schema = schema
# converters = [
# converters.General,
# converters.Ntp,
# converters.Led,
# converters.Interfaces,
# converters.Routes,
# converters.Rules,
# converters.Switch,
# converters.Radios,
# converters.Wireless,
# converters.OpenVpn,
# converters.WireguardPeers,
# converters.Default,
# ]
# parser = OpenWrtParser
# renderer = OpenWrtRenderer
# list_identifiers = ['name', 'config_value', 'id']
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# uci = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# packages = packages_pattern.split(uci)
# if '' in packages:
# packages.remove('')
# # create an UCI file for each configuration package used
# for package in packages:
# lines = package.split('\n')
# package_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(config_path, package_name),
# contents=text_contents,
# )
#
# @classmethod
# def wireguard_auto_client(cls, **kwargs):
# data = Wireguard.auto_client(**kwargs)
# config = {
# 'interfaces': [
# {
# 'name': data['interface_name'],
# 'type': 'wireguard',
# 'private_key': data['client']['private_key'],
# 'port': data['client']['port'],
# # Default values for Wireguard Interface
# 'mtu': 1420,
# 'nohostroute': False,
# 'fwmark': '',
# 'ip6prefix': [],
# 'addresses': [],
# 'network': '',
# }
# ],
# 'wireguard_peers': [
# {
# 'interface': data['interface_name'],
# 'public_key': data['server']['public_key'],
# 'allowed_ips': data['server']['allowed_ips'],
# 'endpoint_host': data['server']['endpoint_host'],
# 'endpoint_port': data['server']['endpoint_port'],
# # Default values for Wireguard Peers
# 'preshared_key': '',
# 'persistent_keepalive': 60,
# 'route_allowed_ips': True,
# }
# ],
# }
# if data['client']['ip_address']:
# config['interfaces'][0]['addresses'] = [
# {
# 'proto': 'static',
# 'family': 'ipv4',
# 'address': data['client']['ip_address'],
# 'mask': 32,
# },
# ]
# return config
#
# @classmethod
# def vxlan_wireguard_auto_client(cls, **kwargs):
# config = cls.wireguard_auto_client(**kwargs)
# vxlan_config = VxlanWireguard.auto_client(**kwargs)
# vxlan_interface = {
# 'name': 'vxlan',
# 'type': 'vxlan',
# 'vtep': vxlan_config['server_ip_address'],
# 'port': 4789,
# 'vni': vxlan_config['vni'],
# 'tunlink': config['interfaces'][0]['name'],
# # Default values for VXLAN interface
# 'rxcsum': True,
# 'txcsum': True,
# 'mtu': 1280,
# 'ttl': 64,
# 'mac': '',
# 'disabled': False,
# 'network': '',
# }
# config['interfaces'].append(vxlan_interface)
# return config
#
# Path: netjsonconfig/utils.py
# class _TabsMixin(object): # pragma: nocover
# """
# mixin that adds _tabs method to test classes
# """
#
# def _tabs(self, string):
# """
# replace 4 spaces with 1 tab
# """
# return string.replace(' ', '\t')
. Output only the next line. | o = OpenWrt( |
Next line prediction: <|code_start|>
class TestParser(unittest.TestCase):
maxDiff = None
def test_parse_text(self):
native = """# openvpn config: bridged
ca ca.pem
cert cert.pem
dev tap0
dev-type tap
dh dh.pem
key key.pem
mode server
proto udp
server-bridge 10.8.0.4 255.255.255.0 10.8.0.128 10.8.0.254
tls-server
"""
<|code_end|>
. Use current file imports:
(import os
import unittest
from copy import deepcopy
from netjsonconfig import OpenVpn
from netjsonconfig.exceptions import ParseError)
and context including class names, function names, or small code snippets from other files:
# Path: netjsonconfig/backends/openvpn/openvpn.py
# class OpenVpn(BaseVpnBackend):
# """
# OpenVPN 2.x Configuration Backend
# """
#
# schema = schema
# converters = [converters.OpenVpn]
# parser = OpenVpnParser
# renderer = OpenVpnRenderer
# list_identifiers = ['name']
# # BaseVpnBackend attributes
# vpn_pattern = vpn_pattern
# config_suffix = config_suffix
#
# @classmethod
# def auto_client(
# cls,
# host,
# server,
# ca_path=None,
# ca_contents=None,
# cert_path=None,
# cert_contents=None,
# key_path=None,
# key_contents=None,
# ):
# """
# Returns a configuration dictionary representing an OpenVPN client configuration
# that is compatible with the passed server configuration.
#
# :param host: remote VPN server
# :param server: dictionary representing a single OpenVPN server configuration
# :param ca_path: optional string representing path to CA, will consequently add
# a file in the resulting configuration dictionary
# :param ca_contents: optional string representing contents of CA file
# :param cert_path: optional string representing path to certificate, will consequently add
# a file in the resulting configuration dictionary
# :param cert_contents: optional string representing contents of cert file
# :param key_path: optional string representing path to key, will consequently add
# a file in the resulting configuration dictionary
# :param key_contents: optional string representing contents of key file
# :returns: dictionary representing a single OpenVPN client configuration
# """
# # client defaults
# client = {
# "mode": "p2p",
# "nobind": True,
# "resolv_retry": "infinite",
# "tls_client": True,
# }
# # remote
# port = server.get('port') or 1195
# client['remote'] = [{'host': host, 'port': port}]
# # proto
# if server.get('proto') == 'tcp-server':
# client['proto'] = 'tcp-client'
# else:
# client['proto'] = 'udp'
# # determine if pull must be True
# if 'server' in server or 'server_bridge' in server:
# client['pull'] = True
# # tls_client
# if 'tls_server' not in server or not server['tls_server']:
# client['tls_client'] = False
# # ns_cert_type
# ns_cert_type = {None: '', '': '', 'client': 'server'}
# client['ns_cert_type'] = ns_cert_type[server.get('ns_cert_type')]
# # remote_cert_tls
# remote_cert_tls = {None: '', '': '', 'client': 'server'}
# client['remote_cert_tls'] = remote_cert_tls[server.get('remote_cert_tls')]
# copy_keys = [
# 'name',
# 'dev_type',
# 'dev',
# 'comp_lzo',
# 'auth',
# 'cipher',
# 'ca',
# 'cert',
# 'key',
# 'pkcs12',
# 'mtu_test',
# 'fragment',
# 'mssfix',
# 'keepalive',
# 'persist_tun',
# 'mute',
# 'persist_key',
# 'script_security',
# 'user',
# 'group',
# 'log',
# 'mute_replay_warnings',
# 'secret',
# 'reneg_sec',
# 'tls_timeout',
# 'tls_cipher',
# 'float',
# 'fast_io',
# 'verb',
# "auth_nocache",
# ]
# for key in copy_keys:
# if key in server:
# client[key] = server[key]
# files = cls._auto_client_files(
# client,
# ca_path,
# ca_contents,
# cert_path,
# cert_contents,
# key_path,
# key_contents,
# )
# return {'openvpn': [client], 'files': files}
#
# @classmethod
# def _auto_client_files(
# cls,
# client,
# ca_path=None,
# ca_contents=None,
# cert_path=None,
# cert_contents=None,
# key_path=None,
# key_contents=None,
# ):
# """
# returns a list of NetJSON extra files for automatically generated clients
# produces side effects in ``client`` dictionary
# """
# files = []
# if ca_path and ca_contents:
# client['ca'] = ca_path
# files.append(dict(path=ca_path, contents=ca_contents, mode=X509_FILE_MODE))
# if cert_path and cert_contents:
# client['cert'] = cert_path
# files.append(
# dict(path=cert_path, contents=cert_contents, mode=X509_FILE_MODE)
# )
# if key_path and key_contents:
# client['key'] = key_path
# files.append(
# dict(
# path=key_path,
# contents=key_contents,
# mode=X509_FILE_MODE,
# )
# )
# return files
. Output only the next line. | o = OpenVpn(native=native) |
Given snippet: <|code_start|>
class Ntp(OpenWrtConverter):
netjson_key = 'ntp'
intermediate_key = 'system'
_uci_types = ['timeserver']
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ..schema import schema
from .base import OpenWrtConverter
and context:
# Path: netjsonconfig/backends/openwrt/schema.py
which might include code, classes, or functions. Output only the next line. | _schema = schema['properties']['ntp'] |
Given the following code snippet before the placeholder: <|code_start|> client[key] = server[key]
files = cls._auto_client_files(
client,
ca_path,
ca_contents,
cert_path,
cert_contents,
key_path,
key_contents,
)
return {'openvpn': [client], 'files': files}
@classmethod
def _auto_client_files(
cls,
client,
ca_path=None,
ca_contents=None,
cert_path=None,
cert_contents=None,
key_path=None,
key_contents=None,
):
"""
returns a list of NetJSON extra files for automatically generated clients
produces side effects in ``client`` dictionary
"""
files = []
if ca_path and ca_contents:
client['ca'] = ca_path
<|code_end|>
, predict the next line using imports from the current file:
from ...schema import X509_FILE_MODE
from ..base.backend import BaseVpnBackend
from . import converters
from .parser import OpenVpnParser, config_suffix, vpn_pattern
from .renderer import OpenVpnRenderer
from .schema import schema
and context including class names, function names, and sometimes code from other files:
# Path: netjsonconfig/schema.py
# X509_FILE_MODE = '0600'
#
# Path: netjsonconfig/backends/base/backend.py
# class BaseVpnBackend(BaseBackend):
# """
# Shared logic between VPN backends
# Requires setting the following attributes:
#
# - vpn_pattern
# - config_suffix
# """
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# text = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# vpn_instances = self.vpn_pattern.split(text)
# if '' in vpn_instances:
# vpn_instances.remove('')
# # create a file for each VPN
# for vpn in vpn_instances:
# lines = vpn.split('\n')
# vpn_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# # do not end with double new line
# if text_contents.endswith('\n\n'):
# text_contents = text_contents[0:-1]
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(vpn_name, self.config_suffix),
# contents=text_contents,
# )
#
# Path: netjsonconfig/backends/openvpn/parser.py
# class OpenVpnParser(BaseParser):
# def parse_text(self, config):
# def parse_tar(self, tar):
# def _get_vpns(self, text):
# def _get_config(self, contents):
#
# Path: netjsonconfig/backends/openvpn/renderer.py
# class OpenVpnRenderer(BaseRenderer):
# """
# OpenVPN Renderer
# """
#
# def cleanup(self, output):
# # remove indentations
# output = output.replace(' ', '')
# # remove last newline
# if output.endswith('\n\n'):
# output = output[0:-1]
# return output
#
# Path: netjsonconfig/backends/openvpn/schema.py
. Output only the next line. | files.append(dict(path=ca_path, contents=ca_contents, mode=X509_FILE_MODE)) |
Here is a snippet: <|code_start|>
class OpenVpn(BaseVpnBackend):
"""
OpenVPN 2.x Configuration Backend
"""
schema = schema
converters = [converters.OpenVpn]
<|code_end|>
. Write the next line using the current file imports:
from ...schema import X509_FILE_MODE
from ..base.backend import BaseVpnBackend
from . import converters
from .parser import OpenVpnParser, config_suffix, vpn_pattern
from .renderer import OpenVpnRenderer
from .schema import schema
and context from other files:
# Path: netjsonconfig/schema.py
# X509_FILE_MODE = '0600'
#
# Path: netjsonconfig/backends/base/backend.py
# class BaseVpnBackend(BaseBackend):
# """
# Shared logic between VPN backends
# Requires setting the following attributes:
#
# - vpn_pattern
# - config_suffix
# """
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# text = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# vpn_instances = self.vpn_pattern.split(text)
# if '' in vpn_instances:
# vpn_instances.remove('')
# # create a file for each VPN
# for vpn in vpn_instances:
# lines = vpn.split('\n')
# vpn_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# # do not end with double new line
# if text_contents.endswith('\n\n'):
# text_contents = text_contents[0:-1]
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(vpn_name, self.config_suffix),
# contents=text_contents,
# )
#
# Path: netjsonconfig/backends/openvpn/parser.py
# class OpenVpnParser(BaseParser):
# def parse_text(self, config):
# def parse_tar(self, tar):
# def _get_vpns(self, text):
# def _get_config(self, contents):
#
# Path: netjsonconfig/backends/openvpn/renderer.py
# class OpenVpnRenderer(BaseRenderer):
# """
# OpenVPN Renderer
# """
#
# def cleanup(self, output):
# # remove indentations
# output = output.replace(' ', '')
# # remove last newline
# if output.endswith('\n\n'):
# output = output[0:-1]
# return output
#
# Path: netjsonconfig/backends/openvpn/schema.py
, which may include functions, classes, or code. Output only the next line. | parser = OpenVpnParser |
Continue the code snippet: <|code_start|>
class OpenVpn(BaseVpnBackend):
"""
OpenVPN 2.x Configuration Backend
"""
schema = schema
converters = [converters.OpenVpn]
parser = OpenVpnParser
renderer = OpenVpnRenderer
list_identifiers = ['name']
# BaseVpnBackend attributes
vpn_pattern = vpn_pattern
<|code_end|>
. Use current file imports:
from ...schema import X509_FILE_MODE
from ..base.backend import BaseVpnBackend
from . import converters
from .parser import OpenVpnParser, config_suffix, vpn_pattern
from .renderer import OpenVpnRenderer
from .schema import schema
and context (classes, functions, or code) from other files:
# Path: netjsonconfig/schema.py
# X509_FILE_MODE = '0600'
#
# Path: netjsonconfig/backends/base/backend.py
# class BaseVpnBackend(BaseBackend):
# """
# Shared logic between VPN backends
# Requires setting the following attributes:
#
# - vpn_pattern
# - config_suffix
# """
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# text = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# vpn_instances = self.vpn_pattern.split(text)
# if '' in vpn_instances:
# vpn_instances.remove('')
# # create a file for each VPN
# for vpn in vpn_instances:
# lines = vpn.split('\n')
# vpn_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# # do not end with double new line
# if text_contents.endswith('\n\n'):
# text_contents = text_contents[0:-1]
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(vpn_name, self.config_suffix),
# contents=text_contents,
# )
#
# Path: netjsonconfig/backends/openvpn/parser.py
# class OpenVpnParser(BaseParser):
# def parse_text(self, config):
# def parse_tar(self, tar):
# def _get_vpns(self, text):
# def _get_config(self, contents):
#
# Path: netjsonconfig/backends/openvpn/renderer.py
# class OpenVpnRenderer(BaseRenderer):
# """
# OpenVPN Renderer
# """
#
# def cleanup(self, output):
# # remove indentations
# output = output.replace(' ', '')
# # remove last newline
# if output.endswith('\n\n'):
# output = output[0:-1]
# return output
#
# Path: netjsonconfig/backends/openvpn/schema.py
. Output only the next line. | config_suffix = config_suffix |
Given the code snippet: <|code_start|>
class OpenVpn(BaseVpnBackend):
"""
OpenVPN 2.x Configuration Backend
"""
schema = schema
converters = [converters.OpenVpn]
parser = OpenVpnParser
renderer = OpenVpnRenderer
list_identifiers = ['name']
# BaseVpnBackend attributes
<|code_end|>
, generate the next line using the imports in this file:
from ...schema import X509_FILE_MODE
from ..base.backend import BaseVpnBackend
from . import converters
from .parser import OpenVpnParser, config_suffix, vpn_pattern
from .renderer import OpenVpnRenderer
from .schema import schema
and context (functions, classes, or occasionally code) from other files:
# Path: netjsonconfig/schema.py
# X509_FILE_MODE = '0600'
#
# Path: netjsonconfig/backends/base/backend.py
# class BaseVpnBackend(BaseBackend):
# """
# Shared logic between VPN backends
# Requires setting the following attributes:
#
# - vpn_pattern
# - config_suffix
# """
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# text = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# vpn_instances = self.vpn_pattern.split(text)
# if '' in vpn_instances:
# vpn_instances.remove('')
# # create a file for each VPN
# for vpn in vpn_instances:
# lines = vpn.split('\n')
# vpn_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# # do not end with double new line
# if text_contents.endswith('\n\n'):
# text_contents = text_contents[0:-1]
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(vpn_name, self.config_suffix),
# contents=text_contents,
# )
#
# Path: netjsonconfig/backends/openvpn/parser.py
# class OpenVpnParser(BaseParser):
# def parse_text(self, config):
# def parse_tar(self, tar):
# def _get_vpns(self, text):
# def _get_config(self, contents):
#
# Path: netjsonconfig/backends/openvpn/renderer.py
# class OpenVpnRenderer(BaseRenderer):
# """
# OpenVPN Renderer
# """
#
# def cleanup(self, output):
# # remove indentations
# output = output.replace(' ', '')
# # remove last newline
# if output.endswith('\n\n'):
# output = output[0:-1]
# return output
#
# Path: netjsonconfig/backends/openvpn/schema.py
. Output only the next line. | vpn_pattern = vpn_pattern |
Predict the next line for this snippet: <|code_start|>
class OpenVpn(BaseVpnBackend):
"""
OpenVPN 2.x Configuration Backend
"""
schema = schema
converters = [converters.OpenVpn]
parser = OpenVpnParser
<|code_end|>
with the help of current file imports:
from ...schema import X509_FILE_MODE
from ..base.backend import BaseVpnBackend
from . import converters
from .parser import OpenVpnParser, config_suffix, vpn_pattern
from .renderer import OpenVpnRenderer
from .schema import schema
and context from other files:
# Path: netjsonconfig/schema.py
# X509_FILE_MODE = '0600'
#
# Path: netjsonconfig/backends/base/backend.py
# class BaseVpnBackend(BaseBackend):
# """
# Shared logic between VPN backends
# Requires setting the following attributes:
#
# - vpn_pattern
# - config_suffix
# """
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# text = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# vpn_instances = self.vpn_pattern.split(text)
# if '' in vpn_instances:
# vpn_instances.remove('')
# # create a file for each VPN
# for vpn in vpn_instances:
# lines = vpn.split('\n')
# vpn_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# # do not end with double new line
# if text_contents.endswith('\n\n'):
# text_contents = text_contents[0:-1]
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(vpn_name, self.config_suffix),
# contents=text_contents,
# )
#
# Path: netjsonconfig/backends/openvpn/parser.py
# class OpenVpnParser(BaseParser):
# def parse_text(self, config):
# def parse_tar(self, tar):
# def _get_vpns(self, text):
# def _get_config(self, contents):
#
# Path: netjsonconfig/backends/openvpn/renderer.py
# class OpenVpnRenderer(BaseRenderer):
# """
# OpenVPN Renderer
# """
#
# def cleanup(self, output):
# # remove indentations
# output = output.replace(' ', '')
# # remove last newline
# if output.endswith('\n\n'):
# output = output[0:-1]
# return output
#
# Path: netjsonconfig/backends/openvpn/schema.py
, which may contain function names, class names, or code. Output only the next line. | renderer = OpenVpnRenderer |
Based on the snippet: <|code_start|> if not isinstance(templates, list):
raise TypeError('templates argument must be an instance of list')
# merge templates with main configuration
result = {}
config_list = templates + [config]
for merging in config_list:
result = merge_config(result, self._load(merging), self.list_identifiers)
return result
def _evaluate_vars(self, config, context):
"""
Evaluates configuration variables
"""
# return immediately if context is empty
if not context:
return config
# only if variables are found perform evaluation
return evaluate_vars(config, context)
def _render_files(self):
"""
Renders additional files specified in ``self.config['files']``
"""
output = ''
# render files
files = self.config.get('files', [])
# add delimiter
if files:
output += '\n{0}\n\n'.format(self.FILE_SECTION_DELIMITER)
for f in files:
<|code_end|>
, predict the immediate next line with the help of imports:
import gzip
import ipaddress
import json
import tarfile
from collections import OrderedDict
from copy import deepcopy
from io import BytesIO
from jsonschema import Draft4Validator, draft4_format_checker
from jsonschema.exceptions import ValidationError as JsonSchemaError
from ...exceptions import ValidationError
from ...schema import DEFAULT_FILE_MODE
from ...utils import evaluate_vars, merge_config
and context (classes, functions, sometimes code) from other files:
# Path: netjsonconfig/schema.py
# DEFAULT_FILE_MODE = '0644'
#
# Path: netjsonconfig/utils.py
# def evaluate_vars(data, context=None):
# """
# Evaluates variables in ``data``
#
# :param data: data structure containing variables, may be
# ``str``, ``dict`` or ``list``
# :param context: ``dict`` containing variables
# :returns: modified data structure
# """
# context = context or {}
# if isinstance(data, (dict, list)):
# if isinstance(data, dict):
# loop_items = data.items()
# elif isinstance(data, list):
# loop_items = enumerate(data)
# for key, value in loop_items:
# data[key] = evaluate_vars(value, context)
# elif isinstance(data, str):
# vars_found = var_pattern.findall(data)
# for var in vars_found:
# var = var.strip()
# # if found multiple variables, create a new regexp pattern for each
# # variable, otherwise different variables would get the same value
# # (see https://github.com/openwisp/netjsonconfig/issues/55)
# if len(vars_found) > 1:
# pattern = r'\{\{(\s*%s\s*)\}\}' % var
# # in case of single variables, use the precompiled
# # regexp pattern to save computation
# else:
# pattern = var_pattern
# if var in context:
# data = re.sub(pattern, str(context[var]), data)
# return data
#
# def merge_config(template, config, list_identifiers=None):
# """
# Merges ``config`` on top of ``template``.
#
# Conflicting keys are handled in the following way:
#
# * simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will
# overwrite the ones in ``template``
# * values of type ``list`` in both ``config`` and ``template`` will be
# merged using to the ``merge_list`` function
# * values of type ``dict`` will be merged recursively
#
# :param template: template ``dict``
# :param config: config ``dict``
# :param list_identifiers: ``list`` or ``None``
# :returns: merged ``dict``
# """
# result = deepcopy(template)
# for key, value in config.items():
# if isinstance(value, dict):
# node = result.get(key, OrderedDict())
# result[key] = merge_config(node, value)
# elif isinstance(value, list) and isinstance(result.get(key), list):
# result[key] = merge_list(result[key], value, list_identifiers)
# else:
# result[key] = value
# return result
. Output only the next line. | mode = f.get('mode', DEFAULT_FILE_MODE) |
Here is a snippet: <|code_start|> if not isinstance(config, dict):
raise TypeError(
'config block must be an instance of dict or a valid NetJSON string'
)
return config
def _merge_config(self, config, templates):
"""
Merges config with templates
"""
if not templates:
return config
# type check
if not isinstance(templates, list):
raise TypeError('templates argument must be an instance of list')
# merge templates with main configuration
result = {}
config_list = templates + [config]
for merging in config_list:
result = merge_config(result, self._load(merging), self.list_identifiers)
return result
def _evaluate_vars(self, config, context):
"""
Evaluates configuration variables
"""
# return immediately if context is empty
if not context:
return config
# only if variables are found perform evaluation
<|code_end|>
. Write the next line using the current file imports:
import gzip
import ipaddress
import json
import tarfile
from collections import OrderedDict
from copy import deepcopy
from io import BytesIO
from jsonschema import Draft4Validator, draft4_format_checker
from jsonschema.exceptions import ValidationError as JsonSchemaError
from ...exceptions import ValidationError
from ...schema import DEFAULT_FILE_MODE
from ...utils import evaluate_vars, merge_config
and context from other files:
# Path: netjsonconfig/schema.py
# DEFAULT_FILE_MODE = '0644'
#
# Path: netjsonconfig/utils.py
# def evaluate_vars(data, context=None):
# """
# Evaluates variables in ``data``
#
# :param data: data structure containing variables, may be
# ``str``, ``dict`` or ``list``
# :param context: ``dict`` containing variables
# :returns: modified data structure
# """
# context = context or {}
# if isinstance(data, (dict, list)):
# if isinstance(data, dict):
# loop_items = data.items()
# elif isinstance(data, list):
# loop_items = enumerate(data)
# for key, value in loop_items:
# data[key] = evaluate_vars(value, context)
# elif isinstance(data, str):
# vars_found = var_pattern.findall(data)
# for var in vars_found:
# var = var.strip()
# # if found multiple variables, create a new regexp pattern for each
# # variable, otherwise different variables would get the same value
# # (see https://github.com/openwisp/netjsonconfig/issues/55)
# if len(vars_found) > 1:
# pattern = r'\{\{(\s*%s\s*)\}\}' % var
# # in case of single variables, use the precompiled
# # regexp pattern to save computation
# else:
# pattern = var_pattern
# if var in context:
# data = re.sub(pattern, str(context[var]), data)
# return data
#
# def merge_config(template, config, list_identifiers=None):
# """
# Merges ``config`` on top of ``template``.
#
# Conflicting keys are handled in the following way:
#
# * simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will
# overwrite the ones in ``template``
# * values of type ``list`` in both ``config`` and ``template`` will be
# merged using to the ``merge_list`` function
# * values of type ``dict`` will be merged recursively
#
# :param template: template ``dict``
# :param config: config ``dict``
# :param list_identifiers: ``list`` or ``None``
# :returns: merged ``dict``
# """
# result = deepcopy(template)
# for key, value in config.items():
# if isinstance(value, dict):
# node = result.get(key, OrderedDict())
# result[key] = merge_config(node, value)
# elif isinstance(value, list) and isinstance(result.get(key), list):
# result[key] = merge_list(result[key], value, list_identifiers)
# else:
# result[key] = value
# return result
, which may include functions, classes, or code. Output only the next line. | return evaluate_vars(config, context) |
Given the following code snippet before the placeholder: <|code_start|> )
def _load(self, config):
"""
Loads config from string or dict
"""
if isinstance(config, str):
try:
config = json.loads(config)
except ValueError:
pass
if not isinstance(config, dict):
raise TypeError(
'config block must be an instance of dict or a valid NetJSON string'
)
return config
def _merge_config(self, config, templates):
"""
Merges config with templates
"""
if not templates:
return config
# type check
if not isinstance(templates, list):
raise TypeError('templates argument must be an instance of list')
# merge templates with main configuration
result = {}
config_list = templates + [config]
for merging in config_list:
<|code_end|>
, predict the next line using imports from the current file:
import gzip
import ipaddress
import json
import tarfile
from collections import OrderedDict
from copy import deepcopy
from io import BytesIO
from jsonschema import Draft4Validator, draft4_format_checker
from jsonschema.exceptions import ValidationError as JsonSchemaError
from ...exceptions import ValidationError
from ...schema import DEFAULT_FILE_MODE
from ...utils import evaluate_vars, merge_config
and context including class names, function names, and sometimes code from other files:
# Path: netjsonconfig/schema.py
# DEFAULT_FILE_MODE = '0644'
#
# Path: netjsonconfig/utils.py
# def evaluate_vars(data, context=None):
# """
# Evaluates variables in ``data``
#
# :param data: data structure containing variables, may be
# ``str``, ``dict`` or ``list``
# :param context: ``dict`` containing variables
# :returns: modified data structure
# """
# context = context or {}
# if isinstance(data, (dict, list)):
# if isinstance(data, dict):
# loop_items = data.items()
# elif isinstance(data, list):
# loop_items = enumerate(data)
# for key, value in loop_items:
# data[key] = evaluate_vars(value, context)
# elif isinstance(data, str):
# vars_found = var_pattern.findall(data)
# for var in vars_found:
# var = var.strip()
# # if found multiple variables, create a new regexp pattern for each
# # variable, otherwise different variables would get the same value
# # (see https://github.com/openwisp/netjsonconfig/issues/55)
# if len(vars_found) > 1:
# pattern = r'\{\{(\s*%s\s*)\}\}' % var
# # in case of single variables, use the precompiled
# # regexp pattern to save computation
# else:
# pattern = var_pattern
# if var in context:
# data = re.sub(pattern, str(context[var]), data)
# return data
#
# def merge_config(template, config, list_identifiers=None):
# """
# Merges ``config`` on top of ``template``.
#
# Conflicting keys are handled in the following way:
#
# * simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will
# overwrite the ones in ``template``
# * values of type ``list`` in both ``config`` and ``template`` will be
# merged using to the ``merge_list`` function
# * values of type ``dict`` will be merged recursively
#
# :param template: template ``dict``
# :param config: config ``dict``
# :param list_identifiers: ``list`` or ``None``
# :returns: merged ``dict``
# """
# result = deepcopy(template)
# for key, value in config.items():
# if isinstance(value, dict):
# node = result.get(key, OrderedDict())
# result[key] = merge_config(node, value)
# elif isinstance(value, list) and isinstance(result.get(key), list):
# result[key] = merge_list(result[key], value, list_identifiers)
# else:
# result[key] = value
# return result
. Output only the next line. | result = merge_config(result, self._load(merging), self.list_identifiers) |
Predict the next line for this snippet: <|code_start|> "mac": "82:29:23:7d:c2:14",
"mtu": 1500,
"txqueuelen": 0,
"autostart": True,
"bridge_members": ["wlan0", "vpn.40"],
"addresses": [
{
"address": "fe80::8029:23ff:fe7d:c214",
"mask": 64,
"family": "ipv6",
"proto": "static",
}
],
},
],
"routes": [
{"device": "eth0", "destination": "10.0.3.1", "next": "10.0.2.1", "cost": 1}
],
"dns_servers": ["10.254.0.1", "10.254.0.2"],
"dns_search": ["domain.com"],
}
class TestNetJson(unittest.TestCase):
"""
ensures OpenWrt backend is compatible with
NetJSON DeviceConfiguration example
"""
def test_netjson_example(self):
<|code_end|>
with the help of current file imports:
import unittest
from netjsonconfig import OpenWrt
and context from other files:
# Path: netjsonconfig/backends/openwrt/openwrt.py
# class OpenWrt(BaseBackend):
# """
# OpenWRT / LEDE Configuration Backend
# """
#
# schema = schema
# converters = [
# converters.General,
# converters.Ntp,
# converters.Led,
# converters.Interfaces,
# converters.Routes,
# converters.Rules,
# converters.Switch,
# converters.Radios,
# converters.Wireless,
# converters.OpenVpn,
# converters.WireguardPeers,
# converters.Default,
# ]
# parser = OpenWrtParser
# renderer = OpenWrtRenderer
# list_identifiers = ['name', 'config_value', 'id']
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# uci = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# packages = packages_pattern.split(uci)
# if '' in packages:
# packages.remove('')
# # create an UCI file for each configuration package used
# for package in packages:
# lines = package.split('\n')
# package_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(config_path, package_name),
# contents=text_contents,
# )
#
# @classmethod
# def wireguard_auto_client(cls, **kwargs):
# data = Wireguard.auto_client(**kwargs)
# config = {
# 'interfaces': [
# {
# 'name': data['interface_name'],
# 'type': 'wireguard',
# 'private_key': data['client']['private_key'],
# 'port': data['client']['port'],
# # Default values for Wireguard Interface
# 'mtu': 1420,
# 'nohostroute': False,
# 'fwmark': '',
# 'ip6prefix': [],
# 'addresses': [],
# 'network': '',
# }
# ],
# 'wireguard_peers': [
# {
# 'interface': data['interface_name'],
# 'public_key': data['server']['public_key'],
# 'allowed_ips': data['server']['allowed_ips'],
# 'endpoint_host': data['server']['endpoint_host'],
# 'endpoint_port': data['server']['endpoint_port'],
# # Default values for Wireguard Peers
# 'preshared_key': '',
# 'persistent_keepalive': 60,
# 'route_allowed_ips': True,
# }
# ],
# }
# if data['client']['ip_address']:
# config['interfaces'][0]['addresses'] = [
# {
# 'proto': 'static',
# 'family': 'ipv4',
# 'address': data['client']['ip_address'],
# 'mask': 32,
# },
# ]
# return config
#
# @classmethod
# def vxlan_wireguard_auto_client(cls, **kwargs):
# config = cls.wireguard_auto_client(**kwargs)
# vxlan_config = VxlanWireguard.auto_client(**kwargs)
# vxlan_interface = {
# 'name': 'vxlan',
# 'type': 'vxlan',
# 'vtep': vxlan_config['server_ip_address'],
# 'port': 4789,
# 'vni': vxlan_config['vni'],
# 'tunlink': config['interfaces'][0]['name'],
# # Default values for VXLAN interface
# 'rxcsum': True,
# 'txcsum': True,
# 'mtu': 1280,
# 'ttl': 64,
# 'mac': '',
# 'disabled': False,
# 'network': '',
# }
# config['interfaces'].append(vxlan_interface)
# return config
, which may contain function names, class names, or code. Output only the next line. | o = OpenWrt(netjson_example) |
Based on the snippet: <|code_start|> counter = 0
for result in results:
result = result.strip()
if not result:
continue
counter += 1
lines = result.split('\n')
parts = lines[0].split()
config_type = self._strip_quotes(parts[0])
try:
config_name = self._strip_quotes(parts[1])
except IndexError:
config_name = '{0}_{1}'.format(config_type, counter)
block = OrderedDict()
block['.type'] = config_type
block['.name'] = config_name
# loop over rest of lines
for line in lines[1:]:
match = re.search(config_pattern, line.strip())
if not match:
continue
parts = match.groups()
key = self._strip_quotes(parts[1])
value = self._strip_quotes(parts[2])
# simple options
if parts[0] == 'option':
block[key] = value
# list options
else:
block[key] = block.get(key, []) + [value]
<|code_end|>
, predict the immediate next line with the help of imports:
import re
import tarfile
from collections import OrderedDict
from ...utils import sorted_dict
from ..base.parser import BaseParser
and context (classes, functions, sometimes code) from other files:
# Path: netjsonconfig/utils.py
# def sorted_dict(dict_):
# return OrderedDict(sorted(dict_.items()))
#
# Path: netjsonconfig/backends/base/parser.py
# class BaseParser(object):
# """
# Base Parser class
# Parsers are used to parse a string or tar.gz
# which represents the router configuration
# """
#
# def __init__(self, config):
# if isinstance(config, str):
# data = self.parse_text(config)
# # presence of read() method
# # indicates a file-like object
# elif hasattr(config, 'read'):
# data = self.parse_tar(config)
# else:
# raise ParseError('Unrecognized format')
# self.intermediate_data = data
#
# def parse_text(self, config):
# raise NotImplementedError()
#
# def parse_tar(self, config):
# raise NotImplementedError()
. Output only the next line. | blocks.append(sorted_dict(block)) |
Here is a snippet: <|code_start|>
packages_pattern = re.compile('^package\s', flags=re.MULTILINE)
block_pattern = re.compile('^config\s', flags=re.MULTILINE)
config_pattern = re.compile('^(option|list)\s*([^\s]*)\s*(.*)')
config_path = 'etc/config/'
<|code_end|>
. Write the next line using the current file imports:
import re
import tarfile
from collections import OrderedDict
from ...utils import sorted_dict
from ..base.parser import BaseParser
and context from other files:
# Path: netjsonconfig/utils.py
# def sorted_dict(dict_):
# return OrderedDict(sorted(dict_.items()))
#
# Path: netjsonconfig/backends/base/parser.py
# class BaseParser(object):
# """
# Base Parser class
# Parsers are used to parse a string or tar.gz
# which represents the router configuration
# """
#
# def __init__(self, config):
# if isinstance(config, str):
# data = self.parse_text(config)
# # presence of read() method
# # indicates a file-like object
# elif hasattr(config, 'read'):
# data = self.parse_tar(config)
# else:
# raise ParseError('Unrecognized format')
# self.intermediate_data = data
#
# def parse_text(self, config):
# raise NotImplementedError()
#
# def parse_tar(self, config):
# raise NotImplementedError()
, which may include functions, classes, or code. Output only the next line. | class OpenWrtParser(BaseParser): |
Predict the next line after this snippet: <|code_start|> self.assertEqual(result, {"list": ["element1", "element2"]})
def test_merge_originals_unchanged(self):
template = {"str": "original", "dict": {"a": "a"}, "list": ["element1"]}
config = {"str": "changed", "dict": {"b": "b"}, "list": ["element2"]}
merge_config(template, config)
# ensure original structures not changed
self.assertEqual(
template, {"str": "original", "dict": {"a": "a"}, "list": ["element1"]}
)
self.assertEqual(
config, {"str": "changed", "dict": {"b": "b"}, "list": ["element2"]}
)
def test_merge_list_of_dicts_unchanged(self):
template = {"list": [{"a": "original"}, {"b": "original"}]}
config = {"list": [{"c": "original"}]}
result = merge_config(template, config)
template['list'][0]['a'] = 'changed'
config['list'][0]['c'] = 'changed'
result['list'][1]['b'] = 'changed'
# ensure originals changed
# but not result of merge
self.assertEqual(template, {"list": [{"a": "changed"}, {"b": "original"}]})
self.assertEqual(config, {"list": [{"c": "changed"}]})
self.assertEqual(
result, {"list": [{"a": "original"}, {"b": "changed"}, {"c": "original"}]}
)
def test_evaluate_vars(self):
<|code_end|>
using the current file's imports:
import unittest
from netjsonconfig.utils import evaluate_vars, get_copy, merge_config, merge_list
and any relevant context from other files:
# Path: netjsonconfig/utils.py
# def evaluate_vars(data, context=None):
# """
# Evaluates variables in ``data``
#
# :param data: data structure containing variables, may be
# ``str``, ``dict`` or ``list``
# :param context: ``dict`` containing variables
# :returns: modified data structure
# """
# context = context or {}
# if isinstance(data, (dict, list)):
# if isinstance(data, dict):
# loop_items = data.items()
# elif isinstance(data, list):
# loop_items = enumerate(data)
# for key, value in loop_items:
# data[key] = evaluate_vars(value, context)
# elif isinstance(data, str):
# vars_found = var_pattern.findall(data)
# for var in vars_found:
# var = var.strip()
# # if found multiple variables, create a new regexp pattern for each
# # variable, otherwise different variables would get the same value
# # (see https://github.com/openwisp/netjsonconfig/issues/55)
# if len(vars_found) > 1:
# pattern = r'\{\{(\s*%s\s*)\}\}' % var
# # in case of single variables, use the precompiled
# # regexp pattern to save computation
# else:
# pattern = var_pattern
# if var in context:
# data = re.sub(pattern, str(context[var]), data)
# return data
#
# def get_copy(dict_, key, default=None):
# """
# Looks for a key in a dictionary, if found returns
# a deepcopied value, otherwise returns default value
# """
# value = dict_.get(key, default)
# if value:
# return deepcopy(value)
# return value
#
# def merge_config(template, config, list_identifiers=None):
# """
# Merges ``config`` on top of ``template``.
#
# Conflicting keys are handled in the following way:
#
# * simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will
# overwrite the ones in ``template``
# * values of type ``list`` in both ``config`` and ``template`` will be
# merged using to the ``merge_list`` function
# * values of type ``dict`` will be merged recursively
#
# :param template: template ``dict``
# :param config: config ``dict``
# :param list_identifiers: ``list`` or ``None``
# :returns: merged ``dict``
# """
# result = deepcopy(template)
# for key, value in config.items():
# if isinstance(value, dict):
# node = result.get(key, OrderedDict())
# result[key] = merge_config(node, value)
# elif isinstance(value, list) and isinstance(result.get(key), list):
# result[key] = merge_list(result[key], value, list_identifiers)
# else:
# result[key] = value
# return result
#
# def merge_list(list1, list2, identifiers=None):
# """
# Merges ``list2`` on top of ``list1``.
#
# If both lists contain dictionaries which have keys specified
# in ``identifiers`` which have equal values, those dicts will
# be merged (dicts in ``list2`` will override dicts in ``list1``).
# The remaining elements will be summed in order to create a list
# which contains elements of both lists.
#
# :param list1: ``list`` from template
# :param list2: ``list`` from config
# :param identifiers: ``list`` or ``None``
# :returns: merged ``list``
# """
# identifiers = identifiers or []
# dict_map = {'list1': OrderedDict(), 'list2': OrderedDict()}
# counter = 1
# for list_ in [list1, list2]:
# container = dict_map['list{0}'.format(counter)]
# for el in list_:
# # merge by internal python id by default
# key = id(el)
# # if el is a dict, merge by keys specified in ``identifiers``
# if isinstance(el, dict):
# for id_key in identifiers:
# if id_key in el:
# key = el[id_key]
# break
# container[key] = deepcopy(el)
# counter += 1
# merged = merge_config(dict_map['list1'], dict_map['list2'])
# return list(merged.values())
. Output only the next line. | self.assertEqual(evaluate_vars('{{ tz }}', {'tz': 'UTC'}), 'UTC') |
Predict the next line after this snippet: <|code_start|> self.assertEqual(output, 'contentAcontentBcontent')
def test_evaluate_vars_immersed(self):
output = evaluate_vars('content{{a}}content', {'a': 'A'})
self.assertEqual(output, 'contentAcontent')
def test_evaluate_vars_one_char(self):
self.assertEqual(evaluate_vars('{{ a }}', {'a': 'letter-A'}), 'letter-A')
def test_merge_list_override(self):
template = [{"name": "test1", "tx": 1}]
config = [{"name": "test1", "tx": 2}]
result = merge_list(template, config, ['name'])
self.assertEqual(result, config)
def test_merge_list_union_and_override(self):
template = [{"id": "test1", "a": "a"}]
config = [{"id": "test1", "a": "0", "b": "b"}, {"id": "test2", "c": "c"}]
result = merge_list(template, config, ['id'])
self.assertEqual(
result, [{"id": "test1", "a": "0", "b": "b"}, {"id": "test2", "c": "c"}]
)
def test_merge_list_config_value(self):
template = [{"config_value": "test1", "tx": 1}]
config = [{"config_value": "test1", "tx": 2}]
result = merge_list(template, config, ['config_value'])
self.assertEqual(result, config)
def test_get_copy_default(self):
<|code_end|>
using the current file's imports:
import unittest
from netjsonconfig.utils import evaluate_vars, get_copy, merge_config, merge_list
and any relevant context from other files:
# Path: netjsonconfig/utils.py
# def evaluate_vars(data, context=None):
# """
# Evaluates variables in ``data``
#
# :param data: data structure containing variables, may be
# ``str``, ``dict`` or ``list``
# :param context: ``dict`` containing variables
# :returns: modified data structure
# """
# context = context or {}
# if isinstance(data, (dict, list)):
# if isinstance(data, dict):
# loop_items = data.items()
# elif isinstance(data, list):
# loop_items = enumerate(data)
# for key, value in loop_items:
# data[key] = evaluate_vars(value, context)
# elif isinstance(data, str):
# vars_found = var_pattern.findall(data)
# for var in vars_found:
# var = var.strip()
# # if found multiple variables, create a new regexp pattern for each
# # variable, otherwise different variables would get the same value
# # (see https://github.com/openwisp/netjsonconfig/issues/55)
# if len(vars_found) > 1:
# pattern = r'\{\{(\s*%s\s*)\}\}' % var
# # in case of single variables, use the precompiled
# # regexp pattern to save computation
# else:
# pattern = var_pattern
# if var in context:
# data = re.sub(pattern, str(context[var]), data)
# return data
#
# def get_copy(dict_, key, default=None):
# """
# Looks for a key in a dictionary, if found returns
# a deepcopied value, otherwise returns default value
# """
# value = dict_.get(key, default)
# if value:
# return deepcopy(value)
# return value
#
# def merge_config(template, config, list_identifiers=None):
# """
# Merges ``config`` on top of ``template``.
#
# Conflicting keys are handled in the following way:
#
# * simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will
# overwrite the ones in ``template``
# * values of type ``list`` in both ``config`` and ``template`` will be
# merged using to the ``merge_list`` function
# * values of type ``dict`` will be merged recursively
#
# :param template: template ``dict``
# :param config: config ``dict``
# :param list_identifiers: ``list`` or ``None``
# :returns: merged ``dict``
# """
# result = deepcopy(template)
# for key, value in config.items():
# if isinstance(value, dict):
# node = result.get(key, OrderedDict())
# result[key] = merge_config(node, value)
# elif isinstance(value, list) and isinstance(result.get(key), list):
# result[key] = merge_list(result[key], value, list_identifiers)
# else:
# result[key] = value
# return result
#
# def merge_list(list1, list2, identifiers=None):
# """
# Merges ``list2`` on top of ``list1``.
#
# If both lists contain dictionaries which have keys specified
# in ``identifiers`` which have equal values, those dicts will
# be merged (dicts in ``list2`` will override dicts in ``list1``).
# The remaining elements will be summed in order to create a list
# which contains elements of both lists.
#
# :param list1: ``list`` from template
# :param list2: ``list`` from config
# :param identifiers: ``list`` or ``None``
# :returns: merged ``list``
# """
# identifiers = identifiers or []
# dict_map = {'list1': OrderedDict(), 'list2': OrderedDict()}
# counter = 1
# for list_ in [list1, list2]:
# container = dict_map['list{0}'.format(counter)]
# for el in list_:
# # merge by internal python id by default
# key = id(el)
# # if el is a dict, merge by keys specified in ``identifiers``
# if isinstance(el, dict):
# for id_key in identifiers:
# if id_key in el:
# key = el[id_key]
# break
# container[key] = deepcopy(el)
# counter += 1
# merged = merge_config(dict_map['list1'], dict_map['list2'])
# return list(merged.values())
. Output only the next line. | self.assertEqual('test', get_copy({}, key='hello', default='test')) |
Given the code snippet: <|code_start|>
class TestUtils(unittest.TestCase):
"""
tests for netjsonconfig.utils
"""
def test_merge_config(self):
template = {"a": "a", "c": "template"}
config = {"b": "b", "c": "config"}
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from netjsonconfig.utils import evaluate_vars, get_copy, merge_config, merge_list
and context (functions, classes, or occasionally code) from other files:
# Path: netjsonconfig/utils.py
# def evaluate_vars(data, context=None):
# """
# Evaluates variables in ``data``
#
# :param data: data structure containing variables, may be
# ``str``, ``dict`` or ``list``
# :param context: ``dict`` containing variables
# :returns: modified data structure
# """
# context = context or {}
# if isinstance(data, (dict, list)):
# if isinstance(data, dict):
# loop_items = data.items()
# elif isinstance(data, list):
# loop_items = enumerate(data)
# for key, value in loop_items:
# data[key] = evaluate_vars(value, context)
# elif isinstance(data, str):
# vars_found = var_pattern.findall(data)
# for var in vars_found:
# var = var.strip()
# # if found multiple variables, create a new regexp pattern for each
# # variable, otherwise different variables would get the same value
# # (see https://github.com/openwisp/netjsonconfig/issues/55)
# if len(vars_found) > 1:
# pattern = r'\{\{(\s*%s\s*)\}\}' % var
# # in case of single variables, use the precompiled
# # regexp pattern to save computation
# else:
# pattern = var_pattern
# if var in context:
# data = re.sub(pattern, str(context[var]), data)
# return data
#
# def get_copy(dict_, key, default=None):
# """
# Looks for a key in a dictionary, if found returns
# a deepcopied value, otherwise returns default value
# """
# value = dict_.get(key, default)
# if value:
# return deepcopy(value)
# return value
#
# def merge_config(template, config, list_identifiers=None):
# """
# Merges ``config`` on top of ``template``.
#
# Conflicting keys are handled in the following way:
#
# * simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will
# overwrite the ones in ``template``
# * values of type ``list`` in both ``config`` and ``template`` will be
# merged using to the ``merge_list`` function
# * values of type ``dict`` will be merged recursively
#
# :param template: template ``dict``
# :param config: config ``dict``
# :param list_identifiers: ``list`` or ``None``
# :returns: merged ``dict``
# """
# result = deepcopy(template)
# for key, value in config.items():
# if isinstance(value, dict):
# node = result.get(key, OrderedDict())
# result[key] = merge_config(node, value)
# elif isinstance(value, list) and isinstance(result.get(key), list):
# result[key] = merge_list(result[key], value, list_identifiers)
# else:
# result[key] = value
# return result
#
# def merge_list(list1, list2, identifiers=None):
# """
# Merges ``list2`` on top of ``list1``.
#
# If both lists contain dictionaries which have keys specified
# in ``identifiers`` which have equal values, those dicts will
# be merged (dicts in ``list2`` will override dicts in ``list1``).
# The remaining elements will be summed in order to create a list
# which contains elements of both lists.
#
# :param list1: ``list`` from template
# :param list2: ``list`` from config
# :param identifiers: ``list`` or ``None``
# :returns: merged ``list``
# """
# identifiers = identifiers or []
# dict_map = {'list1': OrderedDict(), 'list2': OrderedDict()}
# counter = 1
# for list_ in [list1, list2]:
# container = dict_map['list{0}'.format(counter)]
# for el in list_:
# # merge by internal python id by default
# key = id(el)
# # if el is a dict, merge by keys specified in ``identifiers``
# if isinstance(el, dict):
# for id_key in identifiers:
# if id_key in el:
# key = el[id_key]
# break
# container[key] = deepcopy(el)
# counter += 1
# merged = merge_config(dict_map['list1'], dict_map['list2'])
# return list(merged.values())
. Output only the next line. | result = merge_config(template, config) |
Given snippet: <|code_start|> """
see https://github.com/openwisp/netjsonconfig/issues/55
"""
output = evaluate_vars('{{ a }}\n{{ b }}\n', {'a': 'a', 'b': 'b'})
self.assertEqual(output, 'a\nb\n')
def test_evaluate_vars_multiple_space(self):
output = evaluate_vars('{{ a }} {{ b }}', {'a': 'a', 'b': 'b'})
self.assertEqual(output, 'a b')
def test_evaluate_vars_comma(self):
output = evaluate_vars('{{ a }},{{ b }}', {'a': 'a', 'b': 'b'})
self.assertEqual(output, 'a,b')
def test_evaluate_vars_multiple_immersed(self):
output = evaluate_vars(
'content{{a}}content{{ b }}content', {'a': 'A', 'b': 'B'}
)
self.assertEqual(output, 'contentAcontentBcontent')
def test_evaluate_vars_immersed(self):
output = evaluate_vars('content{{a}}content', {'a': 'A'})
self.assertEqual(output, 'contentAcontent')
def test_evaluate_vars_one_char(self):
self.assertEqual(evaluate_vars('{{ a }}', {'a': 'letter-A'}), 'letter-A')
def test_merge_list_override(self):
template = [{"name": "test1", "tx": 1}]
config = [{"name": "test1", "tx": 2}]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from netjsonconfig.utils import evaluate_vars, get_copy, merge_config, merge_list
and context:
# Path: netjsonconfig/utils.py
# def evaluate_vars(data, context=None):
# """
# Evaluates variables in ``data``
#
# :param data: data structure containing variables, may be
# ``str``, ``dict`` or ``list``
# :param context: ``dict`` containing variables
# :returns: modified data structure
# """
# context = context or {}
# if isinstance(data, (dict, list)):
# if isinstance(data, dict):
# loop_items = data.items()
# elif isinstance(data, list):
# loop_items = enumerate(data)
# for key, value in loop_items:
# data[key] = evaluate_vars(value, context)
# elif isinstance(data, str):
# vars_found = var_pattern.findall(data)
# for var in vars_found:
# var = var.strip()
# # if found multiple variables, create a new regexp pattern for each
# # variable, otherwise different variables would get the same value
# # (see https://github.com/openwisp/netjsonconfig/issues/55)
# if len(vars_found) > 1:
# pattern = r'\{\{(\s*%s\s*)\}\}' % var
# # in case of single variables, use the precompiled
# # regexp pattern to save computation
# else:
# pattern = var_pattern
# if var in context:
# data = re.sub(pattern, str(context[var]), data)
# return data
#
# def get_copy(dict_, key, default=None):
# """
# Looks for a key in a dictionary, if found returns
# a deepcopied value, otherwise returns default value
# """
# value = dict_.get(key, default)
# if value:
# return deepcopy(value)
# return value
#
# def merge_config(template, config, list_identifiers=None):
# """
# Merges ``config`` on top of ``template``.
#
# Conflicting keys are handled in the following way:
#
# * simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will
# overwrite the ones in ``template``
# * values of type ``list`` in both ``config`` and ``template`` will be
# merged using to the ``merge_list`` function
# * values of type ``dict`` will be merged recursively
#
# :param template: template ``dict``
# :param config: config ``dict``
# :param list_identifiers: ``list`` or ``None``
# :returns: merged ``dict``
# """
# result = deepcopy(template)
# for key, value in config.items():
# if isinstance(value, dict):
# node = result.get(key, OrderedDict())
# result[key] = merge_config(node, value)
# elif isinstance(value, list) and isinstance(result.get(key), list):
# result[key] = merge_list(result[key], value, list_identifiers)
# else:
# result[key] = value
# return result
#
# def merge_list(list1, list2, identifiers=None):
# """
# Merges ``list2`` on top of ``list1``.
#
# If both lists contain dictionaries which have keys specified
# in ``identifiers`` which have equal values, those dicts will
# be merged (dicts in ``list2`` will override dicts in ``list1``).
# The remaining elements will be summed in order to create a list
# which contains elements of both lists.
#
# :param list1: ``list`` from template
# :param list2: ``list`` from config
# :param identifiers: ``list`` or ``None``
# :returns: merged ``list``
# """
# identifiers = identifiers or []
# dict_map = {'list1': OrderedDict(), 'list2': OrderedDict()}
# counter = 1
# for list_ in [list1, list2]:
# container = dict_map['list{0}'.format(counter)]
# for el in list_:
# # merge by internal python id by default
# key = id(el)
# # if el is a dict, merge by keys specified in ``identifiers``
# if isinstance(el, dict):
# for id_key in identifiers:
# if id_key in el:
# key = el[id_key]
# break
# container[key] = deepcopy(el)
# counter += 1
# merged = merge_config(dict_map['list1'], dict_map['list2'])
# return list(merged.values())
which might include code, classes, or functions. Output only the next line. | result = merge_list(template, config, ['name']) |
Using the snippet: <|code_start|>
class Rules(OpenWrtConverter):
netjson_key = 'ip_rules'
intermediate_key = 'network'
_uci_types = ['rule', 'rule6']
<|code_end|>
, determine the next line of code. You have imports:
from ipaddress import ip_network
from ..schema import schema
from .base import OpenWrtConverter
and context (class names, function names, or code) available:
# Path: netjsonconfig/backends/openwrt/schema.py
. Output only the next line. | _schema = schema['properties']['ip_rules']['items'] |
Predict the next line after this snippet: <|code_start|>"""
OpenWisp specific JSON-Schema definition
(extends OpenWrt JSON-Schema)
"""
schema = merge_config(
<|code_end|>
using the current file's imports:
from ...utils import merge_config
from ..openwrt.schema import schema as openwrt_schema
and any relevant context from other files:
# Path: netjsonconfig/utils.py
# def merge_config(template, config, list_identifiers=None):
# """
# Merges ``config`` on top of ``template``.
#
# Conflicting keys are handled in the following way:
#
# * simple values (eg: ``str``, ``int``, ``float``, ecc) in ``config`` will
# overwrite the ones in ``template``
# * values of type ``list`` in both ``config`` and ``template`` will be
# merged using to the ``merge_list`` function
# * values of type ``dict`` will be merged recursively
#
# :param template: template ``dict``
# :param config: config ``dict``
# :param list_identifiers: ``list`` or ``None``
# :returns: merged ``dict``
# """
# result = deepcopy(template)
# for key, value in config.items():
# if isinstance(value, dict):
# node = result.get(key, OrderedDict())
# result[key] = merge_config(node, value)
# elif isinstance(value, list) and isinstance(result.get(key), list):
# result[key] = merge_list(result[key], value, list_identifiers)
# else:
# result[key] = value
# return result
#
# Path: netjsonconfig/backends/openwrt/schema.py
. Output only the next line. | openwrt_schema, |
Given snippet: <|code_start|> result.setdefault('network', [])
result['network'].append(route)
return result
def __intermediate_route(self, route, index):
network = ip_interface(route.pop('destination'))
target = network.ip if network.version == 4 else network.network
route.update(
{
'.type': 'route{0}'.format('6' if network.version == 6 else ''),
'.name': route.pop('name', None) or self.__get_auto_name(index),
'interface': route.pop('device'),
'target': str(target),
'gateway': route.pop('next'),
'metric': route.pop('cost'),
}
)
if network.version == 4:
route['netmask'] = str(network.netmask)
return self.sorted_dict(route)
def __get_auto_name(self, i):
return 'route{0}'.format(i)
def to_netjson_loop(self, block, result, index):
rule = self.__netjson_route(block, index)
result.setdefault('routes', [])
result['routes'].append(rule)
return result
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ipaddress import ip_interface
from ..schema import schema
from .base import OpenWrtConverter
and context:
# Path: netjsonconfig/backends/openwrt/schema.py
which might include code, classes, or functions. Output only the next line. | _schema = schema['properties']['routes']['items'] |
Using the snippet: <|code_start|> # determine extra packages used
extra_packages = OrderedDict()
for key, value in self.netjson.items():
# skip blocks present in ignore_list
# or blocks not represented by lists
if key in ignore_list or not isinstance(value, list):
continue
block_list = []
# sort each config block
i = 1
for block in list(value):
# config block must be a dict
# with a key named "config_name"
# otherwise it's skipped with a warning
if not isinstance(block, dict) or 'config_name' not in block:
json_block = json.dumps(block, indent=4)
print(
'Unrecognized config block was skipped:\n\n'
'{0}\n\n'.format(json_block)
)
continue
block['.type'] = block.pop('config_name')
block['.name'] = block.pop(
'config_value',
# default value in case the
# UCI name is not defined
'{0}_{1}'.format(block['.type'], i),
)
# ensure UCI name is valid
block['.name'] = self._get_uci_name(block['.name'])
<|code_end|>
, determine the next line of code. You have imports:
import json
from collections import OrderedDict
from ....utils import sorted_dict
from .base import OpenWrtConverter
and context (class names, function names, or code) available:
# Path: netjsonconfig/utils.py
# def sorted_dict(dict_):
# return OrderedDict(sorted(dict_.items()))
. Output only the next line. | block_list.append(sorted_dict(block)) |
Given the code snippet: <|code_start|>
def test_eggs_object(self):
test_i = {'test_object': {'eggs': True}}
validate(test_i, schema)
def test_burrito_object(self):
test_i = {'test_object': {'burrito': 'yes'}}
self.assertRaises(ValidationError, validate, test_i, schema)
def test_burrito_error_message(self):
test_i = {'test_object': {'burrito': 'yes'}}
with self.assertRaises(ValidationError) as e:
validate(test_i, schema)
message_list = [
"'spam' is a required property",
"'eggs' is a required property",
]
self.assertEqual([err.message for err in e.exception.context], message_list)
def test_list_errors(self):
test_i = {'test_object': {'burrito': 'yes'}}
with self.assertRaises(ValidationError) as e:
validate(test_i, schema)
suberror_list = [
({'$ref': '#/definitions/spam_object'}, "'spam' is a required property"),
({'$ref': '#/definitions/eggs_object'}, "'eggs' is a required property"),
]
self.assertEqual(_list_errors(e.exception), suberror_list)
def test_error_str(self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from jsonschema import Draft4Validator, ValidationError
from netjsonconfig import OpenWrt
from netjsonconfig.exceptions import _list_errors
and context (functions, classes, or occasionally code) from other files:
# Path: netjsonconfig/backends/openwrt/openwrt.py
# class OpenWrt(BaseBackend):
# """
# OpenWRT / LEDE Configuration Backend
# """
#
# schema = schema
# converters = [
# converters.General,
# converters.Ntp,
# converters.Led,
# converters.Interfaces,
# converters.Routes,
# converters.Rules,
# converters.Switch,
# converters.Radios,
# converters.Wireless,
# converters.OpenVpn,
# converters.WireguardPeers,
# converters.Default,
# ]
# parser = OpenWrtParser
# renderer = OpenWrtRenderer
# list_identifiers = ['name', 'config_value', 'id']
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# uci = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# packages = packages_pattern.split(uci)
# if '' in packages:
# packages.remove('')
# # create an UCI file for each configuration package used
# for package in packages:
# lines = package.split('\n')
# package_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(config_path, package_name),
# contents=text_contents,
# )
#
# @classmethod
# def wireguard_auto_client(cls, **kwargs):
# data = Wireguard.auto_client(**kwargs)
# config = {
# 'interfaces': [
# {
# 'name': data['interface_name'],
# 'type': 'wireguard',
# 'private_key': data['client']['private_key'],
# 'port': data['client']['port'],
# # Default values for Wireguard Interface
# 'mtu': 1420,
# 'nohostroute': False,
# 'fwmark': '',
# 'ip6prefix': [],
# 'addresses': [],
# 'network': '',
# }
# ],
# 'wireguard_peers': [
# {
# 'interface': data['interface_name'],
# 'public_key': data['server']['public_key'],
# 'allowed_ips': data['server']['allowed_ips'],
# 'endpoint_host': data['server']['endpoint_host'],
# 'endpoint_port': data['server']['endpoint_port'],
# # Default values for Wireguard Peers
# 'preshared_key': '',
# 'persistent_keepalive': 60,
# 'route_allowed_ips': True,
# }
# ],
# }
# if data['client']['ip_address']:
# config['interfaces'][0]['addresses'] = [
# {
# 'proto': 'static',
# 'family': 'ipv4',
# 'address': data['client']['ip_address'],
# 'mask': 32,
# },
# ]
# return config
#
# @classmethod
# def vxlan_wireguard_auto_client(cls, **kwargs):
# config = cls.wireguard_auto_client(**kwargs)
# vxlan_config = VxlanWireguard.auto_client(**kwargs)
# vxlan_interface = {
# 'name': 'vxlan',
# 'type': 'vxlan',
# 'vtep': vxlan_config['server_ip_address'],
# 'port': 4789,
# 'vni': vxlan_config['vni'],
# 'tunlink': config['interfaces'][0]['name'],
# # Default values for VXLAN interface
# 'rxcsum': True,
# 'txcsum': True,
# 'mtu': 1280,
# 'ttl': 64,
# 'mac': '',
# 'disabled': False,
# 'network': '',
# }
# config['interfaces'].append(vxlan_interface)
# return config
. Output only the next line. | o = OpenWrt({'interfaces': [{'wrong': True}]}) |
Continue the code snippet: <|code_start|>
class TestSystem(unittest.TestCase, _TabsMixin):
maxDiff = None
_system_netjson = {
"general": {"hostname": "test-system", "timezone": "Europe/Rome"}
}
_system_uci = """package system
config system 'system'
option hostname 'test-system'
option timezone 'CET-1CEST,M3.5.0,M10.5.0/3'
option zonename 'Europe/Rome'
"""
def test_render_system(self):
<|code_end|>
. Use current file imports:
import unittest
from netjsonconfig import OpenWrt
from netjsonconfig.backends.openwrt.timezones import timezones_reversed
from netjsonconfig.exceptions import ValidationError
from netjsonconfig.utils import _TabsMixin
and context (classes, functions, or code) from other files:
# Path: netjsonconfig/backends/openwrt/openwrt.py
# class OpenWrt(BaseBackend):
# """
# OpenWRT / LEDE Configuration Backend
# """
#
# schema = schema
# converters = [
# converters.General,
# converters.Ntp,
# converters.Led,
# converters.Interfaces,
# converters.Routes,
# converters.Rules,
# converters.Switch,
# converters.Radios,
# converters.Wireless,
# converters.OpenVpn,
# converters.WireguardPeers,
# converters.Default,
# ]
# parser = OpenWrtParser
# renderer = OpenWrtRenderer
# list_identifiers = ['name', 'config_value', 'id']
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# uci = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# packages = packages_pattern.split(uci)
# if '' in packages:
# packages.remove('')
# # create an UCI file for each configuration package used
# for package in packages:
# lines = package.split('\n')
# package_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(config_path, package_name),
# contents=text_contents,
# )
#
# @classmethod
# def wireguard_auto_client(cls, **kwargs):
# data = Wireguard.auto_client(**kwargs)
# config = {
# 'interfaces': [
# {
# 'name': data['interface_name'],
# 'type': 'wireguard',
# 'private_key': data['client']['private_key'],
# 'port': data['client']['port'],
# # Default values for Wireguard Interface
# 'mtu': 1420,
# 'nohostroute': False,
# 'fwmark': '',
# 'ip6prefix': [],
# 'addresses': [],
# 'network': '',
# }
# ],
# 'wireguard_peers': [
# {
# 'interface': data['interface_name'],
# 'public_key': data['server']['public_key'],
# 'allowed_ips': data['server']['allowed_ips'],
# 'endpoint_host': data['server']['endpoint_host'],
# 'endpoint_port': data['server']['endpoint_port'],
# # Default values for Wireguard Peers
# 'preshared_key': '',
# 'persistent_keepalive': 60,
# 'route_allowed_ips': True,
# }
# ],
# }
# if data['client']['ip_address']:
# config['interfaces'][0]['addresses'] = [
# {
# 'proto': 'static',
# 'family': 'ipv4',
# 'address': data['client']['ip_address'],
# 'mask': 32,
# },
# ]
# return config
#
# @classmethod
# def vxlan_wireguard_auto_client(cls, **kwargs):
# config = cls.wireguard_auto_client(**kwargs)
# vxlan_config = VxlanWireguard.auto_client(**kwargs)
# vxlan_interface = {
# 'name': 'vxlan',
# 'type': 'vxlan',
# 'vtep': vxlan_config['server_ip_address'],
# 'port': 4789,
# 'vni': vxlan_config['vni'],
# 'tunlink': config['interfaces'][0]['name'],
# # Default values for VXLAN interface
# 'rxcsum': True,
# 'txcsum': True,
# 'mtu': 1280,
# 'ttl': 64,
# 'mac': '',
# 'disabled': False,
# 'network': '',
# }
# config['interfaces'].append(vxlan_interface)
# return config
#
# Path: netjsonconfig/backends/openwrt/timezones.py
#
# Path: netjsonconfig/utils.py
# class _TabsMixin(object): # pragma: nocover
# """
# mixin that adds _tabs method to test classes
# """
#
# def _tabs(self, string):
# """
# replace 4 spaces with 1 tab
# """
# return string.replace(' ', '\t')
. Output only the next line. | o = OpenWrt(self._system_netjson) |
Using the snippet: <|code_start|> _system_id_uci = """package system
config system 'arbitrary'
option hostname 'test-system'
option timezone 'UTC'
option zonename 'UTC'
"""
def test_parse_system_custom_id(self):
o = OpenWrt(native=self._system_id_uci)
self.assertDictEqual(o.config, self._system_id_netjson)
def test_render_system_custom_id(self):
o = OpenWrt(self._system_id_netjson)
expected = self._tabs(self._system_id_uci)
self.assertEqual(o.render(), expected)
def test_parse_system_timezone(self):
native = self._tabs(
"""package system
config system 'system'
option hostname 'test-system'
option timezone 'CET-1CEST,M3.5.0,M10.5.0/3'
"""
)
o = OpenWrt(native=native)
expected = {
"general": {
"hostname": "test-system",
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from netjsonconfig import OpenWrt
from netjsonconfig.backends.openwrt.timezones import timezones_reversed
from netjsonconfig.exceptions import ValidationError
from netjsonconfig.utils import _TabsMixin
and context (class names, function names, or code) available:
# Path: netjsonconfig/backends/openwrt/openwrt.py
# class OpenWrt(BaseBackend):
# """
# OpenWRT / LEDE Configuration Backend
# """
#
# schema = schema
# converters = [
# converters.General,
# converters.Ntp,
# converters.Led,
# converters.Interfaces,
# converters.Routes,
# converters.Rules,
# converters.Switch,
# converters.Radios,
# converters.Wireless,
# converters.OpenVpn,
# converters.WireguardPeers,
# converters.Default,
# ]
# parser = OpenWrtParser
# renderer = OpenWrtRenderer
# list_identifiers = ['name', 'config_value', 'id']
#
# def _generate_contents(self, tar):
# """
# Adds configuration files to tarfile instance.
#
# :param tar: tarfile instance
# :returns: None
# """
# uci = self.render(files=False)
# # create a list with all the packages (and remove empty entries)
# packages = packages_pattern.split(uci)
# if '' in packages:
# packages.remove('')
# # create an UCI file for each configuration package used
# for package in packages:
# lines = package.split('\n')
# package_name = lines[0]
# text_contents = '\n'.join(lines[2:])
# self._add_file(
# tar=tar,
# name='{0}{1}'.format(config_path, package_name),
# contents=text_contents,
# )
#
# @classmethod
# def wireguard_auto_client(cls, **kwargs):
# data = Wireguard.auto_client(**kwargs)
# config = {
# 'interfaces': [
# {
# 'name': data['interface_name'],
# 'type': 'wireguard',
# 'private_key': data['client']['private_key'],
# 'port': data['client']['port'],
# # Default values for Wireguard Interface
# 'mtu': 1420,
# 'nohostroute': False,
# 'fwmark': '',
# 'ip6prefix': [],
# 'addresses': [],
# 'network': '',
# }
# ],
# 'wireguard_peers': [
# {
# 'interface': data['interface_name'],
# 'public_key': data['server']['public_key'],
# 'allowed_ips': data['server']['allowed_ips'],
# 'endpoint_host': data['server']['endpoint_host'],
# 'endpoint_port': data['server']['endpoint_port'],
# # Default values for Wireguard Peers
# 'preshared_key': '',
# 'persistent_keepalive': 60,
# 'route_allowed_ips': True,
# }
# ],
# }
# if data['client']['ip_address']:
# config['interfaces'][0]['addresses'] = [
# {
# 'proto': 'static',
# 'family': 'ipv4',
# 'address': data['client']['ip_address'],
# 'mask': 32,
# },
# ]
# return config
#
# @classmethod
# def vxlan_wireguard_auto_client(cls, **kwargs):
# config = cls.wireguard_auto_client(**kwargs)
# vxlan_config = VxlanWireguard.auto_client(**kwargs)
# vxlan_interface = {
# 'name': 'vxlan',
# 'type': 'vxlan',
# 'vtep': vxlan_config['server_ip_address'],
# 'port': 4789,
# 'vni': vxlan_config['vni'],
# 'tunlink': config['interfaces'][0]['name'],
# # Default values for VXLAN interface
# 'rxcsum': True,
# 'txcsum': True,
# 'mtu': 1280,
# 'ttl': 64,
# 'mac': '',
# 'disabled': False,
# 'network': '',
# }
# config['interfaces'].append(vxlan_interface)
# return config
#
# Path: netjsonconfig/backends/openwrt/timezones.py
#
# Path: netjsonconfig/utils.py
# class _TabsMixin(object): # pragma: nocover
# """
# mixin that adds _tabs method to test classes
# """
#
# def _tabs(self, string):
# """
# replace 4 spaces with 1 tab
# """
# return string.replace(' ', '\t')
. Output only the next line. | "timezone": timezones_reversed["CET-1CEST,M3.5.0,M10.5.0/3"], |
Given the following code snippet before the placeholder: <|code_start|> during the backward conversion process (native to NetJSON)
"""
return cls.intermediate_key in intermediate_data
def type_cast(self, item, schema=None):
"""
Loops over item and performs type casting
according to supplied schema fragment
"""
if schema is None:
schema = self._schema
properties = schema['properties']
for key, value in item.items():
if key not in properties:
continue
try:
json_type = properties[key]['type']
except KeyError:
json_type = None
# if multiple types are supported, the first
# one takes precedence when parsing
if isinstance(json_type, list) and json_type:
json_type = json_type[0]
if json_type == 'integer' and not isinstance(value, int):
value = int(value)
elif json_type == 'boolean' and not isinstance(value, bool):
value = value == '1'
item[key] = value
return item
<|code_end|>
, predict the next line using imports from the current file:
from collections import OrderedDict
from ...utils import get_copy, sorted_dict
and context including class names, function names, and sometimes code from other files:
# Path: netjsonconfig/utils.py
# def get_copy(dict_, key, default=None):
# """
# Looks for a key in a dictionary, if found returns
# a deepcopied value, otherwise returns default value
# """
# value = dict_.get(key, default)
# if value:
# return deepcopy(value)
# return value
#
# def sorted_dict(dict_):
# return OrderedDict(sorted(dict_.items()))
. Output only the next line. | def get_copy(self, dict_, key, default=None): |
Given the following code snippet before the placeholder: <|code_start|>
def type_cast(self, item, schema=None):
"""
Loops over item and performs type casting
according to supplied schema fragment
"""
if schema is None:
schema = self._schema
properties = schema['properties']
for key, value in item.items():
if key not in properties:
continue
try:
json_type = properties[key]['type']
except KeyError:
json_type = None
# if multiple types are supported, the first
# one takes precedence when parsing
if isinstance(json_type, list) and json_type:
json_type = json_type[0]
if json_type == 'integer' and not isinstance(value, int):
value = int(value)
elif json_type == 'boolean' and not isinstance(value, bool):
value = value == '1'
item[key] = value
return item
def get_copy(self, dict_, key, default=None):
return get_copy(dict_, key, default)
<|code_end|>
, predict the next line using imports from the current file:
from collections import OrderedDict
from ...utils import get_copy, sorted_dict
and context including class names, function names, and sometimes code from other files:
# Path: netjsonconfig/utils.py
# def get_copy(dict_, key, default=None):
# """
# Looks for a key in a dictionary, if found returns
# a deepcopied value, otherwise returns default value
# """
# value = dict_.get(key, default)
# if value:
# return deepcopy(value)
# return value
#
# def sorted_dict(dict_):
# return OrderedDict(sorted(dict_.items()))
. Output only the next line. | def sorted_dict(self, dict_): |
Predict the next line after this snippet: <|code_start|>
class Radios(OpenWrtConverter):
netjson_key = 'radios'
intermediate_key = 'wireless'
_uci_types = ['wifi-device']
def to_intermediate_loop(self, block, result, index=None):
radio = self.__intermediate_radio(block)
result.setdefault('wireless', [])
result['wireless'].append(radio)
return result
def __intermediate_radio(self, radio):
radio.update({'.type': 'wifi-device', '.name': radio.pop('name')})
# rename tx_power to txpower
if 'tx_power' in radio:
radio['txpower'] = radio.pop('tx_power')
# rename driver to type
<|code_end|>
using the current file's imports:
from ..schema import default_radio_driver
from .base import OpenWrtConverter
and any relevant context from other files:
# Path: netjsonconfig/backends/openwrt/schema.py
. Output only the next line. | radio['type'] = radio.pop('driver', default_radio_driver) |
Next line prediction: <|code_start|> else:
varargs.append(arg)
return func(self, *chain(args[:nposargs], varargs), **kwargs)
method.__name__ = func.__name__
return method
@staticmethod
def option_keys_from_vars(func):
def method(self, *args, **kwargs):
try:
variables = BuiltIn()._variables
except RobotNotRunningError:
pass
else:
for key, value in list(dictitems(kwargs)):
if is_scalar_var(key):
kwargs[variables[key]] = kwargs.pop(key)
return func(self, *args, **kwargs)
method.__name__ = func.__name__
return method
@staticmethod
def option_normalized_kwargs(func):
"""Normalize the keys of **kwargs using robot.utils.NormalizedDict
(convert to lowercase and remove spaces).
"""
def method(self, *args, **kwargs):
kwargs = NormalizedDict(kwargs)
<|code_end|>
. Use current file imports:
(from six import PY3
from itertools import chain
from moretools import isstring, dictitems
from robot.utils import NormalizedDict
from robot.variables import is_scalar_var
from robot.libraries.BuiltIn import BuiltIn, RobotNotRunningError
from robottools.utils import normdictdata
from .utils import KeywordName
from .errors import InvalidKeywordOption, KeywordNotDefined
import inspect)
and context including class names, function names, or small code snippets from other files:
# Path: robottools/utils/normdict.py
# def normdictdata(nd):
# """Get the internal data dict with normalized keys
# of :class:`robot.utils.NormalizedDict` instance `nd`
# """
# if not isinstance(nd, base):
# raise TypeError(
# "normdictdata() arg must be a robot.utils.NormalizedDict instance")
# return nd.data if _has_UserDict_base else nd._data
#
# Path: robottools/library/keywords/utils.py
# class KeywordName(str):
# """:class:`str` wrapper to work with Keyword names in a Robot way.
#
# * Converts the given raw Keyword name (usually a function name)
# to Capitalized Robot Style.
# * Uses :func:`robot.utils.normalize`d conversions
# (plain lowercase without spaces and underscores)
# for comparing and hashing.
# """
# def __new__(cls, name='', convert=True):
# if convert and type(name) is not KeywordName:
# name = camelize(name, joiner=' ')
# return str.__new__(cls, name)
#
# @property
# def normalized(self):
# return normalize(str(self), ignore='_')
#
# def __eq__(self, name):
# return self.normalized == normalize(name, ignore='_')
#
# def __hash__(self):
# return hash(self.normalized)
#
# Path: robottools/library/keywords/errors.py
# class InvalidKeywordOption(LookupError):
# pass
#
# class KeywordNotDefined(LookupError):
# pass
. Output only the next line. | return func(self, *args, **normdictdata(kwargs)) |
Using the snippet: <|code_start|>
def create_dictionary(*args, **items):
iargs = iter(args)
return dict(zip(iargs, iargs), **items)
class KeywordDecoratorType(object):
"""The base class for a Test Library's `keyword` decorator.
- Stores the Keyword method function
in the Test Library's `keywords` mapping,
after applying additional options (decorators) to the function.
- Options are added with `__getattr__`,
which generates new decorator class instances.
"""
def __init__(self, keywords, *options, **meta):
"""Initialize with a Test Library's :class:`KeywordsDict` instance,
additional `options` to apply to the decorated methods
and custom `meta` info like name and args list overrides
and explicit argtypes for automatic type conversions.
"""
self.keywords = keywords
for optionname in options:
if not hasattr(type(self), 'option_' + optionname):
raise InvalidKeywordOption(optionname)
self.options = options
name = meta.get('name')
<|code_end|>
, determine the next line of code. You have imports:
from six import PY3
from itertools import chain
from moretools import isstring, dictitems
from robot.utils import NormalizedDict
from robot.variables import is_scalar_var
from robot.libraries.BuiltIn import BuiltIn, RobotNotRunningError
from robottools.utils import normdictdata
from .utils import KeywordName
from .errors import InvalidKeywordOption, KeywordNotDefined
import inspect
and context (class names, function names, or code) available:
# Path: robottools/utils/normdict.py
# def normdictdata(nd):
# """Get the internal data dict with normalized keys
# of :class:`robot.utils.NormalizedDict` instance `nd`
# """
# if not isinstance(nd, base):
# raise TypeError(
# "normdictdata() arg must be a robot.utils.NormalizedDict instance")
# return nd.data if _has_UserDict_base else nd._data
#
# Path: robottools/library/keywords/utils.py
# class KeywordName(str):
# """:class:`str` wrapper to work with Keyword names in a Robot way.
#
# * Converts the given raw Keyword name (usually a function name)
# to Capitalized Robot Style.
# * Uses :func:`robot.utils.normalize`d conversions
# (plain lowercase without spaces and underscores)
# for comparing and hashing.
# """
# def __new__(cls, name='', convert=True):
# if convert and type(name) is not KeywordName:
# name = camelize(name, joiner=' ')
# return str.__new__(cls, name)
#
# @property
# def normalized(self):
# return normalize(str(self), ignore='_')
#
# def __eq__(self, name):
# return self.normalized == normalize(name, ignore='_')
#
# def __hash__(self):
# return hash(self.normalized)
#
# Path: robottools/library/keywords/errors.py
# class InvalidKeywordOption(LookupError):
# pass
#
# class KeywordNotDefined(LookupError):
# pass
. Output only the next line. | self.keyword_name = name and KeywordName(name, convert=False) |
Given snippet: <|code_start|>
def create_dictionary(*args, **items):
iargs = iter(args)
return dict(zip(iargs, iargs), **items)
class KeywordDecoratorType(object):
"""The base class for a Test Library's `keyword` decorator.
- Stores the Keyword method function
in the Test Library's `keywords` mapping,
after applying additional options (decorators) to the function.
- Options are added with `__getattr__`,
which generates new decorator class instances.
"""
def __init__(self, keywords, *options, **meta):
"""Initialize with a Test Library's :class:`KeywordsDict` instance,
additional `options` to apply to the decorated methods
and custom `meta` info like name and args list overrides
and explicit argtypes for automatic type conversions.
"""
self.keywords = keywords
for optionname in options:
if not hasattr(type(self), 'option_' + optionname):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from six import PY3
from itertools import chain
from moretools import isstring, dictitems
from robot.utils import NormalizedDict
from robot.variables import is_scalar_var
from robot.libraries.BuiltIn import BuiltIn, RobotNotRunningError
from robottools.utils import normdictdata
from .utils import KeywordName
from .errors import InvalidKeywordOption, KeywordNotDefined
import inspect
and context:
# Path: robottools/utils/normdict.py
# def normdictdata(nd):
# """Get the internal data dict with normalized keys
# of :class:`robot.utils.NormalizedDict` instance `nd`
# """
# if not isinstance(nd, base):
# raise TypeError(
# "normdictdata() arg must be a robot.utils.NormalizedDict instance")
# return nd.data if _has_UserDict_base else nd._data
#
# Path: robottools/library/keywords/utils.py
# class KeywordName(str):
# """:class:`str` wrapper to work with Keyword names in a Robot way.
#
# * Converts the given raw Keyword name (usually a function name)
# to Capitalized Robot Style.
# * Uses :func:`robot.utils.normalize`d conversions
# (plain lowercase without spaces and underscores)
# for comparing and hashing.
# """
# def __new__(cls, name='', convert=True):
# if convert and type(name) is not KeywordName:
# name = camelize(name, joiner=' ')
# return str.__new__(cls, name)
#
# @property
# def normalized(self):
# return normalize(str(self), ignore='_')
#
# def __eq__(self, name):
# return self.normalized == normalize(name, ignore='_')
#
# def __hash__(self):
# return hash(self.normalized)
#
# Path: robottools/library/keywords/errors.py
# class InvalidKeywordOption(LookupError):
# pass
#
# class KeywordNotDefined(LookupError):
# pass
which might include code, classes, or functions. Output only the next line. | raise InvalidKeywordOption(optionname) |
Based on the snippet: <|code_start|> decorator = getattr(type(self), 'option_' + optionname)
func = decorator(func)
try: # does returned function still have argspec attribute?
# (unchanged function or option has assigned new argspec)
argspec = func.argspec
except AttributeError:
# Store previous argspec
func.argspec = argspec
if name:
name = KeywordName(name, convert=False)
else:
name = self.keyword_name or func.__name__
if func.__doc__:
# Update saved doc string
doc = func.__doc__
# Keep existing (or explicitly given) method name
func.__name__ = name
# Keep method doc string
func.__doc__ = doc
# # Store original method argspec
# func.argspec = argspec
# Store optional override args list and explicit argtypes
func.args = args or self.keyword_args
func.argtypes = argtypes or self.keyword_argtypes
# Add method to the Library's Keywords mapping
if contexts:
try:
keyword = self.keywords[name]
except KeyError:
<|code_end|>
, predict the immediate next line with the help of imports:
from six import PY3
from itertools import chain
from moretools import isstring, dictitems
from robot.utils import NormalizedDict
from robot.variables import is_scalar_var
from robot.libraries.BuiltIn import BuiltIn, RobotNotRunningError
from robottools.utils import normdictdata
from .utils import KeywordName
from .errors import InvalidKeywordOption, KeywordNotDefined
import inspect
and context (classes, functions, sometimes code) from other files:
# Path: robottools/utils/normdict.py
# def normdictdata(nd):
# """Get the internal data dict with normalized keys
# of :class:`robot.utils.NormalizedDict` instance `nd`
# """
# if not isinstance(nd, base):
# raise TypeError(
# "normdictdata() arg must be a robot.utils.NormalizedDict instance")
# return nd.data if _has_UserDict_base else nd._data
#
# Path: robottools/library/keywords/utils.py
# class KeywordName(str):
# """:class:`str` wrapper to work with Keyword names in a Robot way.
#
# * Converts the given raw Keyword name (usually a function name)
# to Capitalized Robot Style.
# * Uses :func:`robot.utils.normalize`d conversions
# (plain lowercase without spaces and underscores)
# for comparing and hashing.
# """
# def __new__(cls, name='', convert=True):
# if convert and type(name) is not KeywordName:
# name = camelize(name, joiner=' ')
# return str.__new__(cls, name)
#
# @property
# def normalized(self):
# return normalize(str(self), ignore='_')
#
# def __eq__(self, name):
# return self.normalized == normalize(name, ignore='_')
#
# def __hash__(self):
# return hash(self.normalized)
#
# Path: robottools/library/keywords/errors.py
# class InvalidKeywordOption(LookupError):
# pass
#
# class KeywordNotDefined(LookupError):
# pass
. Output only the next line. | raise KeywordNotDefined(name) |
Predict the next line for this snippet: <|code_start|> that catches the exception that caused a Keyword FAIL
for debugging.
"""
# Robot 2.8
def _report_failure(self, context):
debug_fail(context)
# Robot >= 2.9
def __enter__(self):
if NormalRunner:
# Robot 2.9
# HACK: monkey-patch robot.running's NormalRunner
# to catch the Keyword exception
robot.running.keywordrunner.NormalRunner = DebugNormalRunner
if StatusReporter:
# Robot 3.0
# HACK: monkey-patch robot.running's StatusReporter._get_failure()
# to catch the Keyword exception
robot.running.statusreporter.StatusReporter._get_failure \
= debug_get_failure
def __exit__(self, *exc):
if NormalRunner:
robot.running.keywordrunner.NormalRunner = NormalRunner
if StatusReporter:
robot.running.statusreporter.StatusReporter._get_failure \
= _get_failure
<|code_end|>
with the help of current file imports:
import sys
import robot.running
from six import reraise, text_type as unicode
from robot.errors import HandlerExecutionFailed, ExecutionFailed
from robot.running.steprunner import StepRunner
from robot.running.statusreporter import StatusReporter
from robot.running.keywordrunner import NormalRunner
from robottools.library.inspector.keyword import KeywordInspector
from .handler import Handler
and context from other files:
# Path: robottools/library/inspector/keyword.py
# class KeywordInspector(object):
#
# def __init__(self, handler):
# self._handler = handler
#
# @property
# def __doc__(self):
# return "%s\n\n%s" % (repr(self), self._handler.doc)
#
# @property
# def arguments(self):
# return KeywordArgumentsInspector(self._handler.arguments)
#
# def __eq__(self, other):
# return isinstance(other, KeywordInspector) and \
# self._handler == other._handler
#
# def __getattr__(self, name):
# return getattr(self._handler, name)
#
# def __dir__(self):
# return ['name', 'doc', 'shortdoc']
#
# def __str__(self):
# return self._handler.longname
#
# def __repr__(self):
# return '[Keyword] %s [ %s ]' % (self, self.arguments)
#
# Path: robottools/testrobot/handler.py
# class Handler(with_metaclass(HandlerMeta, object)):
# """A wrapper base class for instances of classes
# from ``robot.running.handlers``.
#
# * Implements a custom :meth:`.resolve_arguments`,
# which supports passing arbitrary python objects
# as keyword argument values.
# """
# # HACK
# def resolve_arguments(self, args_and_kwargs, variables=None):
# """More Pythonic argument handling for interactive
# :class:`robottools.testrobot.keyword.Keyword` calls.
#
# Original ``resolve_arguments`` methods from ``robot.running.handlers``
# expect as first argument a single list of Keyword arguments
# coming from an RFW script::
#
# ['arg0', 'arg1', ..., 'name=value', ...]
#
# So there is no chance to pass unstringified named argument values.
# Only unstringified positional arguments are possible.
#
# This wrapper method takes a normal Python `args_and_kwargs` pair
# instead as first argument::
#
# (arg0, arg1, ...), {name: value, ...}
#
# It resolves the named arguments stringified via the original method
# but returns the original Python values::
#
# [arg0, arg1, ...], [(name, value), ...]
#
# Only strings are untouched.
# So RFW ``'...${variable}...'`` substitution still works.
# """
# posargs, kwargs = args_and_kwargs
# rfwargs = list(posargs)
# # prepare 'key=value' strings for original RFW method
# for name, value in dictitems(kwargs):
# if not isstring(value):
# value = repr(value)
# rfwargs.append(u'%s=%s' % (name, value))
# posargs, rfwkwargs = self._resolve_arguments(rfwargs, variables)
# # and replace values with original non-string objects after resolving
# kwargslist = []
# if isdict(rfwkwargs):
# # ==> RFW < 3.0
# rfwkwargs = dictitems(rfwkwargs)
# for name, rfwvalue in rfwkwargs:
# value = kwargs[name]
# if isstring(value):
# value = rfwvalue
# kwargslist.append((name, value))
# if hasattr(self, 'run'):
# # ==> RFW < 3.0
# return posargs, dict(kwargslist)
# # RFW >= 3.0
# return posargs, kwargslist
, which may contain function names, class names, or code. Output only the next line. | class Keyword(KeywordInspector): |
Using the snippet: <|code_start|>
# Robot 2.8
def _report_failure(self, context):
debug_fail(context)
# Robot >= 2.9
def __enter__(self):
if NormalRunner:
# Robot 2.9
# HACK: monkey-patch robot.running's NormalRunner
# to catch the Keyword exception
robot.running.keywordrunner.NormalRunner = DebugNormalRunner
if StatusReporter:
# Robot 3.0
# HACK: monkey-patch robot.running's StatusReporter._get_failure()
# to catch the Keyword exception
robot.running.statusreporter.StatusReporter._get_failure \
= debug_get_failure
def __exit__(self, *exc):
if NormalRunner:
robot.running.keywordrunner.NormalRunner = NormalRunner
if StatusReporter:
robot.running.statusreporter.StatusReporter._get_failure \
= _get_failure
class Keyword(KeywordInspector):
def __init__(self, handler, context, debug=False):
KeywordInspector.__init__(self, handler)
<|code_end|>
, determine the next line of code. You have imports:
import sys
import robot.running
from six import reraise, text_type as unicode
from robot.errors import HandlerExecutionFailed, ExecutionFailed
from robot.running.steprunner import StepRunner
from robot.running.statusreporter import StatusReporter
from robot.running.keywordrunner import NormalRunner
from robottools.library.inspector.keyword import KeywordInspector
from .handler import Handler
and context (class names, function names, or code) available:
# Path: robottools/library/inspector/keyword.py
# class KeywordInspector(object):
#
# def __init__(self, handler):
# self._handler = handler
#
# @property
# def __doc__(self):
# return "%s\n\n%s" % (repr(self), self._handler.doc)
#
# @property
# def arguments(self):
# return KeywordArgumentsInspector(self._handler.arguments)
#
# def __eq__(self, other):
# return isinstance(other, KeywordInspector) and \
# self._handler == other._handler
#
# def __getattr__(self, name):
# return getattr(self._handler, name)
#
# def __dir__(self):
# return ['name', 'doc', 'shortdoc']
#
# def __str__(self):
# return self._handler.longname
#
# def __repr__(self):
# return '[Keyword] %s [ %s ]' % (self, self.arguments)
#
# Path: robottools/testrobot/handler.py
# class Handler(with_metaclass(HandlerMeta, object)):
# """A wrapper base class for instances of classes
# from ``robot.running.handlers``.
#
# * Implements a custom :meth:`.resolve_arguments`,
# which supports passing arbitrary python objects
# as keyword argument values.
# """
# # HACK
# def resolve_arguments(self, args_and_kwargs, variables=None):
# """More Pythonic argument handling for interactive
# :class:`robottools.testrobot.keyword.Keyword` calls.
#
# Original ``resolve_arguments`` methods from ``robot.running.handlers``
# expect as first argument a single list of Keyword arguments
# coming from an RFW script::
#
# ['arg0', 'arg1', ..., 'name=value', ...]
#
# So there is no chance to pass unstringified named argument values.
# Only unstringified positional arguments are possible.
#
# This wrapper method takes a normal Python `args_and_kwargs` pair
# instead as first argument::
#
# (arg0, arg1, ...), {name: value, ...}
#
# It resolves the named arguments stringified via the original method
# but returns the original Python values::
#
# [arg0, arg1, ...], [(name, value), ...]
#
# Only strings are untouched.
# So RFW ``'...${variable}...'`` substitution still works.
# """
# posargs, kwargs = args_and_kwargs
# rfwargs = list(posargs)
# # prepare 'key=value' strings for original RFW method
# for name, value in dictitems(kwargs):
# if not isstring(value):
# value = repr(value)
# rfwargs.append(u'%s=%s' % (name, value))
# posargs, rfwkwargs = self._resolve_arguments(rfwargs, variables)
# # and replace values with original non-string objects after resolving
# kwargslist = []
# if isdict(rfwkwargs):
# # ==> RFW < 3.0
# rfwkwargs = dictitems(rfwkwargs)
# for name, rfwvalue in rfwkwargs:
# value = kwargs[name]
# if isstring(value):
# value = rfwvalue
# kwargslist.append((name, value))
# if hasattr(self, 'run'):
# # ==> RFW < 3.0
# return posargs, dict(kwargslist)
# # RFW >= 3.0
# return posargs, kwargslist
. Output only the next line. | if not isinstance(handler, Handler): |
Predict the next line after this snippet: <|code_start|># the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# robotframework-tools 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with robotframework-tools. If not, see <http://www.gnu.org/licenses/>.
"""robottools.library.inspector.keyword
.. moduleauthor:: Stefan Zimmermann <zimmermann.code@gmail.com>
"""
__all__ = ['KeywordInspector']
class KeywordInspector(object):
def __init__(self, handler):
self._handler = handler
@property
def __doc__(self):
return "%s\n\n%s" % (repr(self), self._handler.doc)
@property
def arguments(self):
<|code_end|>
using the current file's imports:
from .arguments import KeywordArgumentsInspector
and any relevant context from other files:
# Path: robottools/library/inspector/arguments.py
# class KeywordArgumentsInspector(object):
# def __init__(self, arguments):
# self._arguments = arguments
#
# def __getattr__(self, name):
# return getattr(self._arguments, name)
#
# def __dir__(self):
# return ['positional', 'defaults', 'varargs', 'kwargs']
#
# def __iter__(self):
# args = self._arguments
# for argname, defaults_index in zip(
# args.positional, range(-len(args.positional), 0)
# ):
# try:
# default = args.defaults[defaults_index]
# except IndexError:
# yield argname
# else:
# yield '%s=%s' % (argname, default)
# if args.varargs:
# yield '*' + args.varargs
# if args.kwargs:
# yield '**' + args.kwargs
#
# def __str__(self):
# return ' | '.join(self)
#
# def __repr__(self):
# return '[Arguments] %s' % self
. Output only the next line. | return KeywordArgumentsInspector(self._handler.arguments) |
Using the snippet: <|code_start|> LOGGER.unregister_logger(self)
# unset internal streams
self._out = self._err = None
_re_log_level = re.compile('|'.join(r % '|'.join(LOG_LEVELS)
for r in [r'^\[ ?(%s) ?\] *', r'^\* ?(%s) ?\* *']))
def message(self, message):
msg = message.message
try:
_, brackets, stars, msg = self._re_log_level.split(msg)
except ValueError:
level = message.level
else:
level = brackets or stars
if not self._is_logged(level):
return
# select streams to use
if level == 'INFO':
stream = self._out or sys.__stdout__
else:
stream = self._err or sys.__stderr__
#... and finally write the message
stream.write("[ ")
try:
color = LOG_LEVEL_COLORS[level]
except KeyError:
stream.write(level)
else:
<|code_end|>
, determine the next line of code. You have imports:
import re
import sys
import logging
from robot.output import LOGGER, LEVELS as LOG_LEVELS
from robot.output.loggerhelper import AbstractLogger
from robot.output.pyloggingconf import RobotHandler
from robot.output.listeners import LibraryListeners
from .highlighting import Highlighter
and context (class names, function names, or code) available:
# Path: robottools/testrobot/highlighting.py
# class Highlighter(object):
# def __init__(self, color, stream):
# self.color = color
# self.stream = stream
# self._highlighter = _Highlighter(stream)
#
# def __enter__(self):
# getattr(self._highlighter, self.color)()
# return self.stream
#
# def __exit__(self, *exc):
# self._highlighter.reset()
. Output only the next line. | with Highlighter(color, stream) as hl: |
Using the snippet: <|code_start|> #HACK: Registers output to LOGGER
self.output.__enter__()
return self
def __exit__(self, *exc):
#HACK: Unregisters output from LOGGER
self.output.__exit__(*exc)
#HACK:
EXECUTION_CONTEXTS._contexts = []
robot.running.namespace.IMPORTER = None
@property
def variables(self):
return self.testrobot._variables
@property
def output(self):
return self.testrobot._output
@property
def namespace(self):
return self.testrobot._namespace
@property
def keywords(self):
return []
def get_handler(self, name):
try:
keyword = self.testrobot[name]
<|code_end|>
, determine the next line of code. You have imports:
from robot.errors import DataError
from robot.running import EXECUTION_CONTEXTS
from robot.running.namespace import Importer
from .keyword import Keyword
import robot.running.namespace
and context (class names, function names, or code) available:
# Path: robottools/testrobot/keyword.py
# class Keyword(KeywordInspector):
# def __init__(self, handler, context, debug=False):
# KeywordInspector.__init__(self, handler)
# if not isinstance(handler, Handler):
# handler.__class__ = Handler[handler.__class__]
# self._context = context
# self._debug = debug
#
# @property
# def __doc__(self):
# return KeywordInspector.__doc__.fget(self)
#
# def __call__(self, *args, **kwargs):
# # HACK: normally, RFW's Keyword argument resolvers expect
# # a plain list of arguments coming from an RFW script,
# # which has limitations, as described in the .handler.Handler wrapper,
# # which is patched later into the actual Keyword function runner
# # by self._context.get_runner(),
# # and which expects the (args, kwargs) pair instead
# if self._debug:
# runner = DebugKeyword(self.name, args=(args, kwargs))
# else:
# runner = robot.running.Keyword(self.name, args=(args, kwargs))
# # HACK: `with` registers Context to EXECUTION_CONTEXTS
# # and Output to LOGGER:
# with self._context as ctx:
# try:
# # Robot >= 2.9
# if (StatusReporter or NormalRunner) and isinstance(
# runner, DebugKeyword
# ):
# with runner:
# return runner.run(ctx)
#
# return runner.run(ctx)
# # Robot 2.8: raised by robot.running.Keyword:
# except HandlerExecutionFailed:
# pass
#
# def debug(self, *args, **kwargs):
# keyword = Keyword(self._handler, self._context, debug=True)
# return keyword(*args, **kwargs)
. Output only the next line. | if type(keyword) is not Keyword: |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
"""
Generate a sitemap.xml file for dc metro metrics
and a json file with an array of urls.
The json file is used with grunt in order to crawl dcmetrometrics.com and regenerate
the static version of the site.
"""
#######################
# Set up logging
sh = logging.StreamHandler(sys.stderr)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('SiteMapGenerator')
logger.setLevel(logging.DEBUG)
logger.addHandler(sh)
#######################
URL_ROOT = 'http://localhost:80'
def unit_urls():
logger.info("Generating Unit URLS...")
<|code_end|>
with the help of current file imports:
from dcmetrometrics.eles import models as models_eles
from dcmetrometrics.hotcars import models as models_hotcars
import sys
import logging
import xml.etree.ElementTree as ET
import json
and context from other files:
# Path: dcmetrometrics/eles/models.py
# class KeyStatuses(WebJSONMixin, EmbeddedDocument):
# class UnitPerformancePeriod(WebJSONMixin, EmbeddedDocument):
# class UnitPerformanceSummary(WebJSONMixin, EmbeddedDocument):
# class SymptomCodeOld(Document):
# class SymptomCode(Document):
# class Station(WebJSONMixin, DataWriteable, Document):
# class Unit(WebJSONMixin, DataWriteable, Document):
# class UnitStatus(WebJSONMixin, DataWriteable, Document):
# class DailyServiceReport(WebJSONMixin, DataWriteable, Document):
# class UnitTypeServiceReport(WebJSONMixin, DataWriteable, EmbeddedDocument):
# class SystemServiceReport(WebJSONMixin, DataWriteable, Document):
# class ElevatorAppState(Document):
# class EscalatorAppState(Document):
# def get_last_symptoms(cls, unit_ids = None):
# def select_key_statuses(cls, statuses):
# def getStatus(timeToStatusDict):
# def __str__(self):
# def make_new_format(self):
# def add(cls, code, description):
# def __str__(self):
# def add(cls, description):
# def other_lines(self):
# def other_station_code(self):
# def line_code1(self):
# def line_code2(self):
# def line_code3(self):
# def get_shared_stations(self):
# def add(cls, code, long_name, medium_name, short_name, lines, all_lines, all_codes):
# def _get_units(self, shared = True, escalators = True, elevators = True):
# def get_shared_units(self, **kwargs):
# def get_units(self, **kwargs):
# def get_escalators(self):
# def get_elevators(self):
# def get_recent_statuses(self, n = 20):
# def get_station_directory(cls):
# def is_elevator(self):
# def is_escalator(self):
# def __str__(self):
# def add(cls, curTime = None, **kwargs):
# def get_statuses(self, *args, **kwargs):
# def compute_performance_summary(self, statuses = None, save = False, end_time = None):
# def update(self, unit_status):
# def _get_unit_statuses(object_id=None, start_time = None, end_time = None):
# def compute_key_statuses(self, save = False):
# def compute_daily_service_reports(self, save = False, statuses = [],
# start_day = date(2013, 6, 1),
# last_day = None):
# def clean(self):
# def __str__(self):
# def denormalize(self):
# def compute_metro_open_time(self):
# def _add_timezones(self):
# def is_active(self):
# def start_time(self):
# def compute_for_unit(cls, unit, day, statuses = None):
# def from_daily_service_reports(cls, reports):
# def compute_for_day(cls, day, reports = None, save = True):
# def __init__(self, *args, **kwargs):
# def get(cls):
# G = dbGlobals.G()
, which may contain function names, class names, or code. Output only the next line. | units = models_eles.Unit.objects |
Based on the snippet: <|code_start|> Save the KeyStatuses doc and return it.
If the key statuses have already been computed,
use the KeyStatuses.update method to simply update
the existing KeyStatuses record with the latest escalator
status.
"""
statuses = self.get_statuses()
self.key_statuses = None
if not statuses:
return None
logger.info("Computing key statuses entry for unit: " + self.unit_id)
self.key_statuses = KeyStatuses.select_key_statuses(statuses)
if save:
self.save()
return self.key_statuses
def compute_daily_service_reports(self, save = False, statuses = [],
start_day = date(2013, 6, 1),
last_day = None):
if last_day is None:
last_day = date.today() + timedelta(days=1)
if not statuses:
statuses = self.get_statuses()
docs = []
<|code_end|>
, predict the immediate next line with the help of imports:
from mongoengine import *
from operator import attrgetter
from ..common.metroTimes import TimeRange, UTCToLocalTime, toUtc, tzny, utcnow, dateToOpen
from ..common.WebJSONMixin import WebJSONMixin
from ..common.DataWriteable import DataWriteable
from ..common.utils import gen_days
from .defs import symptomToCategory, SYMPTOM_CHOICES
from ..common import dbGlobals
from .misc_utils import *
from .StatusGroup import StatusGroup
from datetime import timedelta, datetime, date
import sys
import logging
and context (classes, functions, sometimes code) from other files:
# Path: dcmetrometrics/common/utils.py
# def gen_days(s, e):
# """Generate days between start_day s and end_day e (exclusive)"""
# d = s
# while d < e:
# yield d
# d = d + timedelta(days = 1)
#
# Path: dcmetrometrics/common/dbGlobals.py
# class _DBGlobals(object):
# def __init__(self):
# def update(self):
# def getEscalatorIds(self):
# def getElevatorIds(self):
# def getUnitIds(self):
# def getDB(self):
# def getDB():
# def connect():
# def G():
# _G = None # Global object
# _G = _DBGlobals()
. Output only the next line. | for day in gen_days(start_day, last_day): |
Predict the next line after this snippet: <|code_start|> Add a unit to the database if it does not already exist.
If the unit is being added for the first time, create an initial
operational UnitStatus entry.
If the unit already exists and a status already exists,
do nothing.
"""
unit_id = kwargs['unit_id']
try:
unit = Unit.objects.get(unit_id = unit_id)
except DoesNotExist:
logger.info("Adding Unit to DB: " + unit_id)
unit = cls(**kwargs)
unit.save()
# Add a new entry to the escalator_statuses collection if necessary
status_count = UnitStatus.objects(unit = unit).count()
has_key_statuses = unit.key_statuses is not None
has_performance_summary = unit.performance_summary is not None
updated_unit = False
if status_count == 0:
if curTime is None:
curTime = datetime.now()
<|code_end|>
using the current file's imports:
from mongoengine import *
from operator import attrgetter
from ..common.metroTimes import TimeRange, UTCToLocalTime, toUtc, tzny, utcnow, dateToOpen
from ..common.WebJSONMixin import WebJSONMixin
from ..common.DataWriteable import DataWriteable
from ..common.utils import gen_days
from .defs import symptomToCategory, SYMPTOM_CHOICES
from ..common import dbGlobals
from .misc_utils import *
from .StatusGroup import StatusGroup
from datetime import timedelta, datetime, date
import sys
import logging
and any relevant context from other files:
# Path: dcmetrometrics/common/utils.py
# def gen_days(s, e):
# """Generate days between start_day s and end_day e (exclusive)"""
# d = s
# while d < e:
# yield d
# d = d + timedelta(days = 1)
#
# Path: dcmetrometrics/common/dbGlobals.py
# class _DBGlobals(object):
# def __init__(self):
# def update(self):
# def getEscalatorIds(self):
# def getElevatorIds(self):
# def getUnitIds(self):
# def getDB(self):
# def getDB():
# def connect():
# def G():
# _G = None # Global object
# _G = _DBGlobals()
. Output only the next line. | G = dbGlobals.G() |
Here is a snippet: <|code_start|>Define the HotCarApp as a restartingGreenlet.
This app will use the Twitter API to search for tweets about #wmata
#hotcar's. These tweets and the hotcar data are stored in a database.
Tweet acknowledgements are posted to the @MetroHotCars twitter account.
"""
# TEST CODE
if __name__ == "__main__":
OUTPUT_DIR = DATA_DIR
###############################################################
# Log the HotCarApp App to a file.
LOG_FILE_NAME = os.path.join(DATA_DIR, 'HotCarApp.log')
fh = logging.FileHandler(LOG_FILE_NAME)
sh = logging.StreamHandler(sys.stderr)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
sh.setFormatter(formatter)
logger = logging.getLogger('HotCarApp')
logger.addHandler(fh)
logger.addHandler(sh)
#################################################################
<|code_end|>
. Write the next line using the current file imports:
import test.setup
import gevent
import os
import sys
import logging
import traceback
from datetime import datetime
from dcmetrometrics.common.restartingGreenlet import RestartingGreenlet
from dcmetrometrics.common import dbGlobals
from dcmetrometrics.hotcars import hotCars
from dcmetrometrics.common.globals import DATA_DIR, REPO_DIR, DATA_DIR
from time import sleep
and context from other files:
# Path: dcmetrometrics/common/restartingGreenlet.py
# class RestartingGreenlet(Greenlet):
#
# def __init__(self, *args, **kwargs):
# Greenlet.__init__(self)
#
# # Save the constructer arguments
# # so we can recreate the Greenlet
# self.rsargs = args
# self.rskwargs = kwargs
#
# # Set up this Greenlet to use the restarter
# self.link(self.restart)
#
# @staticmethod
# def restart(g):
# newg = makeNewGreenlet(g)
# newg.start()
#
# Path: dcmetrometrics/common/dbGlobals.py
# class _DBGlobals(object):
# def __init__(self):
# def update(self):
# def getEscalatorIds(self):
# def getElevatorIds(self):
# def getUnitIds(self):
# def getDB(self):
# def getDB():
# def connect():
# def G():
# _G = None # Global object
# _G = _DBGlobals()
#
# Path: dcmetrometrics/hotcars/hotCars.py
# DEBUG = logger.debug
# ME = 'MetroHotCars'.upper()
# WUNDERGROUND_API_KEY = None
# T = getTwitterAPI()
# T = getTwitterAPI()
# T = getTwitterAPI()
# T = getTwitterAPI()
# def hasForbiddenWord(t):
# def getHotCarUrl(carNum):
# def getWundergroundAPI():
# def tick(tweetLive = False):
# def tweetMentionsMe(tweet):
# def filterSelfRetweets(t):
# def makeUTCDateTime(secSinceEpoch):
# def updateDBFromTweet(tweet, hotCarData):
# def filterDuplicateReports(tweetData):
# def doc_to_data(doc):
# def genResponseTweet(handle, hotCarData):
# def getForbiddenCarsByMention():
# def isAutomatedTweet(tweet):
# def getTimeCarPairs(tweet):
# def getMentions(curTime):
# def tweetIsForbidden(tweet):
# def countWeekdays(t1, t2):
# def summarizeReports(db, reports):
, which may include functions, classes, or code. Output only the next line. | class HotCarApp(RestartingGreenlet): |
Next line prediction: <|code_start|>Tweet acknowledgements are posted to the @MetroHotCars twitter account.
"""
# TEST CODE
if __name__ == "__main__":
OUTPUT_DIR = DATA_DIR
###############################################################
# Log the HotCarApp App to a file.
LOG_FILE_NAME = os.path.join(DATA_DIR, 'HotCarApp.log')
fh = logging.FileHandler(LOG_FILE_NAME)
sh = logging.StreamHandler(sys.stderr)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
sh.setFormatter(formatter)
logger = logging.getLogger('HotCarApp')
logger.addHandler(fh)
logger.addHandler(sh)
#################################################################
class HotCarApp(RestartingGreenlet):
def __init__(self, LIVE=False):
<|code_end|>
. Use current file imports:
( import test.setup
import gevent
import os
import sys
import logging
import traceback
from datetime import datetime
from dcmetrometrics.common.restartingGreenlet import RestartingGreenlet
from dcmetrometrics.common import dbGlobals
from dcmetrometrics.hotcars import hotCars
from dcmetrometrics.common.globals import DATA_DIR, REPO_DIR, DATA_DIR
from time import sleep)
and context including class names, function names, or small code snippets from other files:
# Path: dcmetrometrics/common/restartingGreenlet.py
# class RestartingGreenlet(Greenlet):
#
# def __init__(self, *args, **kwargs):
# Greenlet.__init__(self)
#
# # Save the constructer arguments
# # so we can recreate the Greenlet
# self.rsargs = args
# self.rskwargs = kwargs
#
# # Set up this Greenlet to use the restarter
# self.link(self.restart)
#
# @staticmethod
# def restart(g):
# newg = makeNewGreenlet(g)
# newg.start()
#
# Path: dcmetrometrics/common/dbGlobals.py
# class _DBGlobals(object):
# def __init__(self):
# def update(self):
# def getEscalatorIds(self):
# def getElevatorIds(self):
# def getUnitIds(self):
# def getDB(self):
# def getDB():
# def connect():
# def G():
# _G = None # Global object
# _G = _DBGlobals()
#
# Path: dcmetrometrics/hotcars/hotCars.py
# DEBUG = logger.debug
# ME = 'MetroHotCars'.upper()
# WUNDERGROUND_API_KEY = None
# T = getTwitterAPI()
# T = getTwitterAPI()
# T = getTwitterAPI()
# T = getTwitterAPI()
# def hasForbiddenWord(t):
# def getHotCarUrl(carNum):
# def getWundergroundAPI():
# def tick(tweetLive = False):
# def tweetMentionsMe(tweet):
# def filterSelfRetweets(t):
# def makeUTCDateTime(secSinceEpoch):
# def updateDBFromTweet(tweet, hotCarData):
# def filterDuplicateReports(tweetData):
# def doc_to_data(doc):
# def genResponseTweet(handle, hotCarData):
# def getForbiddenCarsByMention():
# def isAutomatedTweet(tweet):
# def getTimeCarPairs(tweet):
# def getMentions(curTime):
# def tweetIsForbidden(tweet):
# def countWeekdays(t1, t2):
# def summarizeReports(db, reports):
. Output only the next line. | dbGlobals.connect() |
Using the snippet: <|code_start|>LOG_FILE_NAME = os.path.join(DATA_DIR, 'HotCarApp.log')
fh = logging.FileHandler(LOG_FILE_NAME)
sh = logging.StreamHandler(sys.stderr)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
sh.setFormatter(formatter)
logger = logging.getLogger('HotCarApp')
logger.addHandler(fh)
logger.addHandler(sh)
#################################################################
class HotCarApp(RestartingGreenlet):
def __init__(self, LIVE=False):
dbGlobals.connect()
RestartingGreenlet.__init__(self, LIVE=LIVE)
self.SLEEP = 40 # Run every 10 seconds
self.LIVE = LIVE
# Run forever
def _run(self):
while True:
try:
<|code_end|>
, determine the next line of code. You have imports:
import test.setup
import gevent
import os
import sys
import logging
import traceback
from datetime import datetime
from dcmetrometrics.common.restartingGreenlet import RestartingGreenlet
from dcmetrometrics.common import dbGlobals
from dcmetrometrics.hotcars import hotCars
from dcmetrometrics.common.globals import DATA_DIR, REPO_DIR, DATA_DIR
from time import sleep
and context (class names, function names, or code) available:
# Path: dcmetrometrics/common/restartingGreenlet.py
# class RestartingGreenlet(Greenlet):
#
# def __init__(self, *args, **kwargs):
# Greenlet.__init__(self)
#
# # Save the constructer arguments
# # so we can recreate the Greenlet
# self.rsargs = args
# self.rskwargs = kwargs
#
# # Set up this Greenlet to use the restarter
# self.link(self.restart)
#
# @staticmethod
# def restart(g):
# newg = makeNewGreenlet(g)
# newg.start()
#
# Path: dcmetrometrics/common/dbGlobals.py
# class _DBGlobals(object):
# def __init__(self):
# def update(self):
# def getEscalatorIds(self):
# def getElevatorIds(self):
# def getUnitIds(self):
# def getDB(self):
# def getDB():
# def connect():
# def G():
# _G = None # Global object
# _G = _DBGlobals()
#
# Path: dcmetrometrics/hotcars/hotCars.py
# DEBUG = logger.debug
# ME = 'MetroHotCars'.upper()
# WUNDERGROUND_API_KEY = None
# T = getTwitterAPI()
# T = getTwitterAPI()
# T = getTwitterAPI()
# T = getTwitterAPI()
# def hasForbiddenWord(t):
# def getHotCarUrl(carNum):
# def getWundergroundAPI():
# def tick(tweetLive = False):
# def tweetMentionsMe(tweet):
# def filterSelfRetweets(t):
# def makeUTCDateTime(secSinceEpoch):
# def updateDBFromTweet(tweet, hotCarData):
# def filterDuplicateReports(tweetData):
# def doc_to_data(doc):
# def genResponseTweet(handle, hotCarData):
# def getForbiddenCarsByMention():
# def isAutomatedTweet(tweet):
# def getTimeCarPairs(tweet):
# def getMentions(curTime):
# def tweetIsForbidden(tweet):
# def countWeekdays(t1, t2):
# def summarizeReports(db, reports):
. Output only the next line. | hotCars.tick(tweetLive = self.LIVE) |
Based on the snippet: <|code_start|> Create a cumulative histogram for each label in a probabilistic atlas
Parameters
----------
p: numpy array
keys
nrows
ncols
fontsize
img_fname
Returns
-------
"""
fig, axs = plt.subplots(nrows, ncols, figsize=(12,9))
axs = np.array(axs).reshape(-1)
im = []
# Determine lower left axis index
lower_left = (nrows - 1) * ncols
for aa, ax in enumerate(axs):
if aa < len(keys):
v = p[:,:,:,aa].ravel()
v = v[v > 0]
im = ax.hist(v, bins=50, cumulative=True, density=True, range=(0,1))
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
import argparse
import nibabel as nib
import numpy as np
import matplotlib.pyplot as plt
from atlas_report import do_strip_prefix
and context (classes, functions, sometimes code) from other files:
# Path: atlas_report.py
# def do_strip_prefix(label_name):
# # if desired, remove prefixes from label names
# idx = label_name.rfind('_') + 1
# stripped_label_name = label_name[idx:]
# # print("Stripping atlas label name, from %s to %s" % (label_name, stripped_label_name))
# return stripped_label_name
. Output only the next line. | key = do_strip_prefix(keys[aa]) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
"""
This example shows how to use the FedEx Service Validation,
Availability and Commitment Service.
The variables populated below represents common values.
You will need to fill out the required values or risk seeing a SchemaValidationError
exception thrown by suds.
"""
# Un-comment to see the response from Fedex printed in stdout.
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
# This is the object that will be handling our service availability request.
# We're using the FedexConfig object from example_config.py in this dir.
customer_transaction_id = "*** AvailabilityAndCommitment Request v4 using Python ***" # Optional transaction_id
<|code_end|>
with the help of current file imports:
import logging
import sys
import datetime
from example_config import CONFIG_OBJ
from fedex.services.availability_commitment_service import FedexAvailabilityCommitmentRequest
and context from other files:
# Path: fedex/services/availability_commitment_service.py
# class FedexAvailabilityCommitmentRequest(FedexBaseService):
# """
# This class allows you validate service availability
# """
#
# def __init__(self, config_obj, *args, **kwargs):
# """
# @type config_obj: L{FedexConfig}
# @param config_obj: A valid FedexConfig object.
# """
#
# self._config_obj = config_obj
# # Holds version info for the VersionId SOAP object.
# self._version_info = {
# 'service_id': 'vacs',
# 'major': '8',
# 'intermediate': '0',
# 'minor': '0'
# }
#
# self.CarrierCode = None
# """@ivar: Carrier Code Default to Fedex (FDXE), or can bbe FDXG."""
#
# self.Origin = None
# """@ivar: Holds Origin Address WSDL object."""
#
# self.Destination = None
# """@ivar: Holds Destination Address WSDL object."""
#
# self.ShipDate = None
# """@ivar: Ship Date date WSDL object."""
#
# self.Service = None
# """@ivar: Service type, if set to None will get all available service information."""
#
# self.Packaging = None
# """@ivar: Type of packaging to narrow down available shipping options or defaults to YOUR_PACKAGING."""
#
# # Call the parent FedexBaseService class for basic setup work.
# # Shortened the name of the wsdl, otherwise suds did not load it properly.
# # Suds throws the following error when using the long file name from FedEx:
# #
# # File "/Library/Python/2.7/site-packages/suds/wsdl.py", line 878, in resolve
# # raise Exception("binding '%s', not-found" % p.binding)
# # Exception: binding 'ns:ValidationAvailabilityAndCommitmentServiceSoapBinding', not-found
#
# super(FedexAvailabilityCommitmentRequest, self).__init__(
# self._config_obj, 'ValidationAvailabilityAndCommitmentService_v8.wsdl', *args, **kwargs)
#
# def _prepare_wsdl_objects(self):
# """
# Create the data structure and get it ready for the WSDL request.
# """
# self.CarrierCode = 'FDXE'
# self.Origin = self.client.factory.create('Address')
# self.Destination = self.client.factory.create('Address')
# self.ShipDate = datetime.date.today().isoformat()
# self.Service = None
# self.Packaging = 'YOUR_PACKAGING'
#
# def _assemble_and_send_request(self):
# """
# Fires off the Fedex request.
#
# @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(),
# WHICH RESIDES ON FedexBaseService AND IS INHERITED.
# """
#
# # We get an exception like this when specifying an IntegratorId:
# # suds.TypeNotFound: Type not found: 'IntegratorId'
# # Setting it to None does not seem to appease it.
# del self.ClientDetail.IntegratorId
# self.logger.debug(self.WebAuthenticationDetail)
# self.logger.debug(self.ClientDetail)
# self.logger.debug(self.TransactionDetail)
# self.logger.debug(self.VersionId)
# # Fire off the query.
# return self.client.service.serviceAvailability(
# WebAuthenticationDetail=self.WebAuthenticationDetail,
# ClientDetail=self.ClientDetail,
# TransactionDetail=self.TransactionDetail,
# Version=self.VersionId,
# Origin=self.Origin,
# Destination=self.Destination,
# ShipDate=self.ShipDate,
# CarrierCode=self.CarrierCode,
# Service=self.Service,
# Packaging=self.Packaging)
, which may contain function names, class names, or code. Output only the next line. | avc_request = FedexAvailabilityCommitmentRequest(CONFIG_OBJ, customer_transaction_id=customer_transaction_id) |
Based on the snippet: <|code_start|>"""
Test module for the Fedex TrackService WSDL.
"""
sys.path.insert(0, '..')
# Common global config object for testing.
CONFIG_OBJ = get_fedex_config()
logging.getLogger('suds').setLevel(logging.ERROR)
logging.getLogger('fedex').setLevel(logging.INFO)
@unittest.skipIf(not CONFIG_OBJ.account_number, "No credentials provided.")
class TrackServiceTests(unittest.TestCase):
"""
These tests verify that the shipping service WSDL is in good shape.
"""
def test_track(self):
# Test shipment tracking. Query for a tracking number and make sure the
# first (and hopefully only) result matches up.
tracking_num = '781820562774'
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
import logging
import sys
from fedex.services.track_service import FedexTrackRequest
from tests.common import get_fedex_config
and context (classes, functions, sometimes code) from other files:
# Path: fedex/services/track_service.py
# class FedexTrackRequest(FedexBaseService):
# """
# This class allows you to track shipments by providing a tracking
# number or other identifying features. By default, you
# can simply pass a tracking number to the constructor. If you would like
# to query shipments based on something other than tracking number, you will
# want to read the documentation for the L{__init__} method.
# Particularly, the tracking_value and package_identifier arguments.
# """
#
# def __init__(self, config_obj, *args, **kwargs):
# """
# Sends a shipment tracking request. The optional keyword args
# detailed on L{FedexBaseService} apply here as well.
#
# @type config_obj: L{FedexConfig}
# @param config_obj: A valid FedexConfig object.
# """
#
# self._config_obj = config_obj
#
# # Holds version info for the VersionId SOAP object.
# self._version_info = {
# 'service_id': 'trck',
# 'major': '16',
# 'intermediate': '0',
# 'minor': '0'
# }
# self.SelectionDetails = None
# """@ivar: Holds the SelectionDetails WSDL object that includes tracking type and value."""
#
# # Set Default as None. 'INCLUDE_DETAILED_SCANS' or None
# self.ProcessingOptions = None
# """@ivar: Holds the TrackRequestProcessingOptionType WSDL object that defaults no None."""
#
# # Call the parent FedexBaseService class for basic setup work.
# super(FedexTrackRequest, self).__init__(
# self._config_obj, 'TrackService_v16.wsdl', *args, **kwargs)
# self.IncludeDetailedScans = False
#
# def _prepare_wsdl_objects(self):
# """
# This sets the package identifier information. This may be a tracking
# number or a few different things as per the Fedex spec.
# """
#
# self.SelectionDetails = self.client.factory.create('TrackSelectionDetail')
#
# # Default to Fedex
# self.SelectionDetails.CarrierCode = 'FDXE'
#
# track_package_id = self.client.factory.create('TrackPackageIdentifier')
#
# # Default to tracking number.
# track_package_id.Type = 'TRACKING_NUMBER_OR_DOORTAG'
#
# self.SelectionDetails.PackageIdentifier = track_package_id
#
# def _check_response_for_request_errors(self):
# """
# Checks the response to see if there were any errors specific to
# this WSDL.
# """
# if self.response.HighestSeverity == "ERROR": # pragma: no cover
# for notification in self.response.Notifications:
# if notification.Severity == "ERROR":
# if "Invalid tracking number" in notification.Message:
# raise FedexInvalidTrackingNumber(
# notification.Code, notification.Message)
# else:
# raise FedexError(notification.Code, notification.Message)
#
# def _assemble_and_send_request(self):
# """
# Fires off the Fedex request.
#
# @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES
# ON FedexBaseService AND IS INHERITED.
# """
#
# client = self.client
# # Fire off the query.
# return client.service.track(
# WebAuthenticationDetail=self.WebAuthenticationDetail,
# ClientDetail=self.ClientDetail,
# TransactionDetail=self.TransactionDetail,
# Version=self.VersionId,
# SelectionDetails=self.SelectionDetails,
# ProcessingOptions=self.ProcessingOptions)
. Output only the next line. | track = FedexTrackRequest(CONFIG_OBJ) |
Predict the next line after this snippet: <|code_start|> i = i - 1
p1 = h.find('"', p)
p2 = h.find('"', p1+1)
self.parms[key] = h[p1+1:p2]
p = self.header.find('=', p+1)
#print(self.parms)
def rootNode(self):
if self.parent is None:
return self
else:
return self.parent.rootNode()
def prettify(self, indent='', indentIncrease=' '):
if len(self.children) == 0:
return indent + self.header + self.footer
else:
return indent + self.header + '\n' + '\n'.join([c.prettify( indent+indentIncrease ) for c in self.children]) + '\n' + indent + self.footer
def __repr__(self):
return self.prettify()
def applyTransforms(self, x, y):
R = numpy.eye(2)
r_o = numpy.zeros(2)
tx, ty = 0, 0
sx, sy = 1.0, 1.0
if 'transform=' in self.header:
if 'rotate(' in self.header:
<|code_end|>
using the current file's imports:
import numpy
from numpy import sin, cos, dot
from drawingDimensioning.py3_helpers import map
and any relevant context from other files:
# Path: drawingDimensioning/py3_helpers.py
# def map(function, arg):
# return list(_map(function, arg))
. Output only the next line. | rotateParms = map(float, extractParms(self.header, 0, 'rotate(', ', ', ')')) |
Predict the next line after this snippet: <|code_start|>if __name__ == '__main__':
print('''run tests via
FreeCAD_drawing_dimensioning$ python2 test''')
exit()
def xml_prettify( xml_str ):
xml = minidom.parseString( xml_str )
S = xml.toprettyxml(indent=' ')
return '\n'.join( s for s in S.split('\n') if s.strip() != '' )
class Tests(unittest.TestCase):
def test_dy( self ):
<|code_end|>
using the current file's imports:
import unittest
import xml.etree.ElementTree as XML_Tree
import xml.dom.minidom as minidom
import numpy
from drawingDimensioning.linearDimension import linearDimensionSVG_points
and any relevant context from other files:
# Path: drawingDimensioning/linearDimension.py
# def linearDimensionSVG_points( x1, y1, x2, y2, x3, y3, x4=None, y4=None, autoPlaceText=False, autoPlaceOffset=2.0,
# scale=1.0, textFormat_linear='%(value)3.3f', comma_decimal_place=False,
# gap_datum_points = 2, dimension_line_overshoot=1, arrowL1=3, arrowL2=1, arrowW=2, strokeWidth=0.5, lineColor='blue', arrow_scheme='auto',
# halfDimension_linear=False, textRenderer= defaultTextRenderer):
# lines = []
# p1 = numpy.array([ x1, y1 ])
# p2 = numpy.array([ x2, y2 ])
# p3 = numpy.array([ x3, y3 ])
# if min(x1,x2) <= x3 and x3 <= max(x1,x2):
# d = numpy.array([ 0, 1])
# textRotation = 0
# elif min(y1,y2) <= y3 and y3 <= max(y1,y2):
# d = numpy.array([ 1, 0])
# textRotation = -90
# elif numpy.linalg.norm(p2 - p1) > 0:
# d = numpy.dot( [[ 0, -1],[ 1, 0]], directionVector(p1,p2))
# if abs( sum( numpy.sign(d) * numpy.sign( p3- (p1+p2)/2 ))) == 0:
# return None
# textRotation = numpy.arctan( (y2 - y1)/(x2 - x1)) / numpy.pi * 180
# #if textRotation <
# else:
# return None
# A = p1 + numpy.dot(p3-p1,d)*d
# B = p2 + numpy.dot(p3-p2,d)*d
# if not halfDimension_linear:
# lines.append( dimensionSVG_trimLine( p1, A, gap_datum_points,-dimension_line_overshoot))
# lines.append( dimensionSVG_trimLine( p2, B, gap_datum_points,-dimension_line_overshoot))
# lines.append( A.tolist() + B.tolist() )
# else:
# lines.append( dimensionSVG_trimLine( p2, B, gap_datum_points,-dimension_line_overshoot)) #linePerpendic2
# lines.append( p3.tolist() + B.tolist() ) #line from pointer to B
# lineXML = '\n'.join( svgLine( x1, y1, x2, y2, lineColor, strokeWidth ) for x1, y1, x2, y2 in lines )
# v = numpy.linalg.norm(A-B)*scale
# text = dimensionText( v, textFormat_linear, comma=comma_decimal_place)
# textXML = textPlacement_common_procedure(A, B, text, x4, y4, textRotation, textRenderer, autoPlaceText, autoPlaceOffset)
# distAB = numpy.linalg.norm(A-B)
# if distAB > 0 and arrow_scheme != 'off': #then draw arrows
# if arrow_scheme == 'auto':
# s = 1 if distAB > 2.5*(arrowL1 + arrowL2) else -1
# elif arrow_scheme == 'in':
# s = 1
# elif arrow_scheme == 'out':
# s = -1
# arrowXML = arrowHeadSVG( B, s*directionVector(B,A), arrowL1, arrowL2, arrowW, lineColor )
# if not halfDimension_linear:
# arrowXML = arrowXML + arrowHeadSVG( A, s*directionVector(A,B), arrowL1, arrowL2, arrowW, lineColor )
# else:
# arrowXML = ''
# return '<g> \n %s \n %s \n %s </g>' % ( lineXML, arrowXML, textXML )
. Output only the next line. | svg_string = linearDimensionSVG_points( x1 = 0, y1 = 10 , x2 = 30, y2= 25, x3 = 40, y3= 20, x4 = 50, y4 = 30 ) |
Continue the code snippet: <|code_start|> return _centerLinesSVG( center, topLeft, bottomRight, viewScale, centerLine_len_dot, centerLine_len_dash, centerLine_len_gap, centerLine_width, centerLine_color, v, not v )
d.registerPreference( 'centerLine_len_dot', 3 , label='dot length', increment=0.5)
d.registerPreference( 'centerLine_len_dash', 6 , label='dash length', increment=0.5)
d.registerPreference( 'centerLine_len_gap', 2 , label='gap length', increment=0.5)
d.registerPreference( 'centerLine_width', 0.32 , label='line width', increment=0.05)
d.registerPreference( 'centerLine_color', 255 << 8, kind='color' )
d.max_selections = 3
def centerLine_preview(mouseX, mouseY):
selections = d.selections + [ PlacementClick( mouseX, mouseY, condensed_args=True) ] if len(d.selections) < d.max_selections else d.selections
return d.SVGFun( *selections_to_svg_fun_args(selections), viewScale = d.viewScale, **d.dimensionConstructorKWs )
def centerLine_clickHandler( x, y ):
d.selections.append( PlacementClick( x, y, condensed_args=True) )
if len(d.selections) == d.max_selections:
return 'createDimension:%s' % findUnusedObjectName('centerLines')
def selectFun( event, referer, elementXML, elementParms, elementViewObject ):
viewInfo = selectionOverlay.DrawingsViews_info[elementViewObject.Name]
d.viewScale = elementXML.rootNode().scaling()
# center line
if isinstance(referer,selectionOverlay.PointSelectionGraphicsItem):
d.selections = [ PointSelection( elementParms, elementXML, viewInfo, condensed_args=True ) ]
selectionOverlay.hideSelectionGraphicsItems()
previewDimension.initializePreview( d, centerLine_preview , centerLine_clickHandler)
elif isinstance(referer,selectionOverlay.LineSelectionGraphicsItem):
if len(d.selections) == 0:
d.selections = [ TwoLineSelection() ]
<|code_end|>
. Use current file imports:
from drawingDimensioning.command import *
from .linearDimension import linearDimension_parallels_hide_non_parallel
and context (classes, functions, or code) from other files:
# Path: drawingDimensioning/linearDimension.py
# def linearDimension_parallels_hide_non_parallel(elementParms, elementViewObject):
# x1,y1,x2,y2 = [ elementParms[k] for k in [ 'x1', 'y1', 'x2', 'y2' ] ]
# d = numpy.array([ x2 - x1, y2 - y1] )
# d_ref = d / numpy.linalg.norm(d)
# p = numpy.array([ x1, y1] )
# def hideFun( gi ):
# if isinstance(gi,selectionOverlay.LineSelectionGraphicsItem):
# if gi.elementParms != elementParms:
# x1,y1,x2,y2 = [ gi.elementParms[k] for k in [ 'x1', 'y1', 'x2', 'y2' ] ]
# d = numpy.array([ x2 - x1, y2 - y1] )
# d = d / numpy.linalg.norm(d)
# if abs(numpy.dot(d_ref,d)) > 1.0 - 10**-9: #then parallel
# d_rotated = rotate2D(d, numpy.pi/2)
# offset = numpy.array([ x1, y1] ) - p
# if abs(numpy.dot(d_rotated, offset)) > 10**-6: #then not colinear
# return False
# elif isinstance(gi,selectionOverlay.PointSelectionGraphicsItem):
# return False
# return True
# selectionOverlay.hideSelectionGraphicsItems(hideFun)
. Output only the next line. | linearDimension_parallels_hide_non_parallel( elementParms, elementViewObject) |
Given the code snippet: <|code_start|> if instruction == None:
pass
elif instruction.startswith('createDimension:'):
viewName = instruction.split(':')[1]
FreeCAD.ActiveDocument.openTransaction(viewName)
XML = self.dimensionSvgFun( x, y )
debugPrint(3, XML)
debugPrint(2, 'creating dimension %s' % viewName)
obj = App.ActiveDocument.addObject('Drawing::FeatureViewPython',viewName)
obj.ViewResult = XML
d = preview.dimensioningProcessTracker
d.ProxyClass( obj, d.selections, d.proxy_svgFun )
if hasattr( obj.ViewObject, 'Proxy'):
d.ViewObjectProxyClass( obj.ViewObject, d.dialogIconPath )
preview.drawingVars.page.addObject( obj ) #App.ActiveDocument.getObject(viewName) )
removePreviewGraphicItems( recomputeActiveDocument=True, launchEndFunction=True )
FreeCAD.ActiveDocument.commitTransaction()
elif instruction == 'stopPreview':
removePreviewGraphicItems( recomputeActiveDocument=True, launchEndFunction=True )
else:
event.ignore()
except:
App.Console.PrintError(traceback.format_exc())
def hoverMoveEvent(self, event):
try:
x, y = preview.applyTransform( event.scenePos() )
debugPrint(4, 'hoverMoveEvent: x %f, y %f' % (x, y) )
x, y= applyGridRounding( x, y)
XML = '<svg width="%i" height="%i"> %s </svg>' % (preview.drawingVars.width, preview.drawingVars.height, self.dimensionSvgFun( x, y ))
<|code_end|>
, generate the next line using the imports in this file:
from .core import *
from .core import __dir__ # not imported with * directive
from .grid import *
from drawingDimensioning.py3_helpers import unicode_type, encode_if_py2
and context (functions, classes, or occasionally code) from other files:
# Path: drawingDimensioning/core.py
# def debugPrint( level, msg ):
# def findUnusedObjectName(base, counterStart=1, fmt='%03i'):
# def errorMessagebox_with_traceback(title='Error'):
# def getDrawingPageGUIVars():
# def __init__(self, data):
# def recomputeWithOutViewReset( drawingVars ):
# def printGraphicsViewInfo( drawingVars ):
# def Activated(self):
# def GetResources(self):
# def dimensionableObjects ( page ):
# class DrawingPageGUIVars:
# class helpCommand:
# T = gV.transform()
# T = drawingVars.graphicsView.transform()
#
# Path: drawingDimensioning/py3_helpers.py
# def unicode(*args):
# def translate(*args):
# def encode_if_py2(unicode_object):
# def map(function, arg):
. Output only the next line. | if isinstance(XML, unicode_type): |
Given snippet: <|code_start|> pass
elif instruction.startswith('createDimension:'):
viewName = instruction.split(':')[1]
FreeCAD.ActiveDocument.openTransaction(viewName)
XML = self.dimensionSvgFun( x, y )
debugPrint(3, XML)
debugPrint(2, 'creating dimension %s' % viewName)
obj = App.ActiveDocument.addObject('Drawing::FeatureViewPython',viewName)
obj.ViewResult = XML
d = preview.dimensioningProcessTracker
d.ProxyClass( obj, d.selections, d.proxy_svgFun )
if hasattr( obj.ViewObject, 'Proxy'):
d.ViewObjectProxyClass( obj.ViewObject, d.dialogIconPath )
preview.drawingVars.page.addObject( obj ) #App.ActiveDocument.getObject(viewName) )
removePreviewGraphicItems( recomputeActiveDocument=True, launchEndFunction=True )
FreeCAD.ActiveDocument.commitTransaction()
elif instruction == 'stopPreview':
removePreviewGraphicItems( recomputeActiveDocument=True, launchEndFunction=True )
else:
event.ignore()
except:
App.Console.PrintError(traceback.format_exc())
def hoverMoveEvent(self, event):
try:
x, y = preview.applyTransform( event.scenePos() )
debugPrint(4, 'hoverMoveEvent: x %f, y %f' % (x, y) )
x, y= applyGridRounding( x, y)
XML = '<svg width="%i" height="%i"> %s </svg>' % (preview.drawingVars.width, preview.drawingVars.height, self.dimensionSvgFun( x, y ))
if isinstance(XML, unicode_type):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .core import *
from .core import __dir__ # not imported with * directive
from .grid import *
from drawingDimensioning.py3_helpers import unicode_type, encode_if_py2
and context:
# Path: drawingDimensioning/core.py
# def debugPrint( level, msg ):
# def findUnusedObjectName(base, counterStart=1, fmt='%03i'):
# def errorMessagebox_with_traceback(title='Error'):
# def getDrawingPageGUIVars():
# def __init__(self, data):
# def recomputeWithOutViewReset( drawingVars ):
# def printGraphicsViewInfo( drawingVars ):
# def Activated(self):
# def GetResources(self):
# def dimensionableObjects ( page ):
# class DrawingPageGUIVars:
# class helpCommand:
# T = gV.transform()
# T = drawingVars.graphicsView.transform()
#
# Path: drawingDimensioning/py3_helpers.py
# def unicode(*args):
# def translate(*args):
# def encode_if_py2(unicode_object):
# def map(function, arg):
which might include code, classes, or functions. Output only the next line. | XML = encode_if_py2(XML) |
Next line prediction: <|code_start|> if radialLine_x != None and radialLine_y != None:
XML_body.append( svgLine(radialLine_x, radialLine_y, start_x, start_y, lineColor, strokeWidth) )
if tail_x != None and tail_y != None:
XML_body.append( svgLine(radialLine_x, radialLine_y, tail_x, radialLine_y, lineColor, strokeWidth) )
XML_body.append(' <circle cx ="%f" cy ="%f" r="%f" stroke="%s" fill="%s" /> ' % (tail_x, radialLine_y, noteCircle_radius, lineColor, noteCircle_fill) )
XML_body.append( textRenderer_noteCircle( tail_x - 1.5, radialLine_y + 1.5, noteCircleText ) )
return '<g> %s </g>' % '\n'.join(XML_body)
d.registerPreference( 'strokeWidth')
d.registerPreference( 'lineColor' )
d.registerPreference( 'noteCircle_radius', 4.5, increment=0.5, label='radius')
d.registerPreference( 'noteCircle_fill', RGBtoUnsigned(255, 255, 255), kind='color', label='fill' )
d.registerPreference( 'textRenderer_noteCircle', ['inherit','5', 150<<16], 'text properties (Note Circle)', kind='font' )
d.max_selections = 3
class NoteCircleText_widget:
def __init__(self):
self.counter = 1
def valueChanged( self, arg1):
d.noteCircleText = '%i' % arg1
self.counter = arg1 + 1
def generateWidget( self, dimensioningProcess ):
self.spinbox = QtGui.QSpinBox()
self.spinbox.setValue(self.counter)
d.noteCircleText = '%i' % self.counter
self.spinbox.valueChanged.connect(self.valueChanged)
self.counter = self.counter + 1
return DimensioningTaskDialog_generate_row_hbox('no.', self.spinbox)
def add_properties_to_dimension_object( self, obj ):
obj.addProperty("App::PropertyString", 'noteText', 'Parameters')
<|code_end|>
. Use current file imports:
(from drawingDimensioning.command import *
from drawingDimensioning.py3_helpers import encode_if_py2
from .grabPointAdd import Proxy_grabPoint)
and context including class names, function names, or small code snippets from other files:
# Path: drawingDimensioning/py3_helpers.py
# def encode_if_py2(unicode_object):
# '''return unicode for py3 and bytes for py2'''
# if sys.version_info.major < 3:
# return unicode_object.encode("utf8")
# else:
# return unicode_object
. Output only the next line. | obj.noteText = encode_if_py2(d.noteCircleText) |
Predict the next line after this snippet: <|code_start|> self.label_3 = QtGui.QLabel(Dialog)
self.label_3.setObjectName("label_3")
self.horizontalLayout_4.addWidget(self.label_3)
spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem2)
self.colorLineEdit = QtGui.QLineEdit(Dialog)
self.colorLineEdit.setObjectName("colorLineEdit")
self.horizontalLayout_4.addWidget(self.colorLineEdit)
self.verticalLayout.addLayout(self.horizontalLayout_4)
self.horizontalLayout_5 = QtGui.QHBoxLayout()
self.horizontalLayout_5.setObjectName("horizontalLayout_5")
self.label_4 = QtGui.QLabel(Dialog)
self.label_4.setObjectName("label_4")
self.horizontalLayout_5.addWidget(self.label_4)
spacerItem3 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_5.addItem(spacerItem3)
self.familyLineEdit = QtGui.QLineEdit(Dialog)
self.familyLineEdit.setObjectName("familyLineEdit")
self.horizontalLayout_5.addWidget(self.familyLineEdit)
self.verticalLayout.addLayout(self.horizontalLayout_5)
self.placeButton = QtGui.QPushButton(Dialog)
self.placeButton.setObjectName("placeButton")
self.verticalLayout.addWidget(self.placeButton)
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.placeButton, QtCore.SIGNAL("released()"), Dialog.accept)
QtCore.QObject.connect(self.textLineEdit, QtCore.SIGNAL("returnPressed()"), Dialog.accept)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
<|code_end|>
using the current file's imports:
from drawingDimensioning.py3_helpers import unicode, translate
from PySide import QtCore, QtGui
and any relevant context from other files:
# Path: drawingDimensioning/py3_helpers.py
# def unicode(*args):
# return str(args[0])
#
# def translate(*args):
# if len(args) < 3:
# args.append(None)
# try:
# return QtGui.QApplication.translate(args[0], args[1], args[2], QtGui.QApplication.UnicodeUTF8)
# except AttributeError:
# return QtGui.QApplication.translate(args[0], args[1], args[2])
. Output only the next line. | Dialog.setWindowTitle(translate("Dialog", "Add Text", None)) |
Predict the next line for this snippet: <|code_start|> return self.dd_parms.GetFloat( self.name, self.defaultValue )
def updateDefault(self):
self.dd_parms.SetFloat( self.name, self.dimensioningProcess.dimensionConstructorKWs[ self.name ] )
def revertToDefault( self ):
self.spinbox.setValue( self.getDefaultValue() )
def generateWidget( self, dimensioningProcess ):
self.dimensioningProcess = dimensioningProcess
spinbox = QtGui.QDoubleSpinBox()
spinbox.setValue( self.getDefaultValue() )
spinbox.setMinimum( self.spinBox_min )
spinbox.setSingleStep( self.spinBox_increment )
spinbox.setDecimals(self.spinBox_decimals)
spinbox.valueChanged.connect( self.valueChanged )
self.spinbox = spinbox
return DimensioningTaskDialog_generate_row_hbox( self.label, spinbox )
def add_properties_to_dimension_object( self, obj ):
obj.addProperty("App::PropertyFloat", self.name, self.category)
KWs = self.dimensioningProcess.dimensionConstructorKWs
setattr( obj, self.name, KWs[ self.name ] )
if sys.version_info.major < 3:
DimensioningPreferenceClasses["<type 'float'>"] = DimensioningPreference_float
DimensioningPreferenceClasses["<type 'int'>"] = DimensioningPreference_float
else:
DimensioningPreferenceClasses["<class 'float'>"] = DimensioningPreference_float
DimensioningPreferenceClasses["<class 'int'>"] = DimensioningPreference_float
class DimensioningPreference_unicode(DimensioningPreference_prototype):
def getDefaultValue(self):
encoded_value = self.dd_parms.GetString( self.name, encode_if_py2(self.defaultValue) )
<|code_end|>
with the help of current file imports:
import sys
import FreeCAD
from drawingDimensioning.py3_helpers import unicode, unicode_type, map, encode_if_py2
from PySide import QtGui, QtCore, QtSvg
from drawingDimensioning.svgConstructor import SvgTextRenderer
and context from other files:
# Path: drawingDimensioning/py3_helpers.py
# def unicode(*args):
# def translate(*args):
# def encode_if_py2(unicode_object):
# def map(function, arg):
#
# Path: drawingDimensioning/svgLib.py
# class SvgTextRenderer:
# def __init__(self, font_family='inherit', font_size='inherit', fill='rgb(0,0,0)'):
# self.font_family = font_family
# self.font_size = font_size
# self.fill = fill
# def __call__(self, x, y, text, text_anchor='inherit', rotation=None):
# '''
# text_anchor = start | middle | end | inherit
# rotation is in degress, and is done about x,y
# '''
# try:
# XML = '''<text x="%f" y="%f" font-family="%s" font-size="%s" fill="%s" text-anchor="%s" %s >%s</text>''' % ( x, y, self.font_family, self.font_size, self.fill, text_anchor, 'transform="rotate(%f %f,%f)"' % (rotation,x,y) if rotation != None else '', text )
# except UnicodeDecodeError:
# text_utf8 = unicode( text, 'utf8' )
# XML = '''<text x="%f" y="%f" font-family="%s" font-size="%s" fill="%s" text-anchor="%s" %s >%s</text>''' % ( x, y, self.font_family, self.font_size, self.fill, text_anchor, 'transform="rotate(%f %f,%f)"' % (rotation,x,y) if rotation != None else '', text_utf8 )
# return XML
# def __repr__(self):
# return '<svgLib_dd.SvgTextRenderer family="%s" font_size="%s" fill="%s">' % (self.font_family, self.font_size, self.fill )
, which may contain function names, class names, or code. Output only the next line. | return unicode( encoded_value, 'utf8' ) |
Using the snippet: <|code_start|>if sys.version_info.major < 3:
DimensioningPreferenceClasses["<type 'float'>"] = DimensioningPreference_float
DimensioningPreferenceClasses["<type 'int'>"] = DimensioningPreference_float
else:
DimensioningPreferenceClasses["<class 'float'>"] = DimensioningPreference_float
DimensioningPreferenceClasses["<class 'int'>"] = DimensioningPreference_float
class DimensioningPreference_unicode(DimensioningPreference_prototype):
def getDefaultValue(self):
encoded_value = self.dd_parms.GetString( self.name, encode_if_py2(self.defaultValue) )
return unicode( encoded_value, 'utf8' )
def updateDefault(self):
self.dd_parms.SetString( self.name, encode_if_py2(self.dimensioningProcess.dimensionConstructorKWs[ self.name ]) )
def revertToDefault( self ):
self.textbox.setText( self.getDefaultValue() )
def generateWidget( self, dimensioningProcess ):
self.dimensioningProcess = dimensioningProcess
textbox = QtGui.QLineEdit()
#debugPrint(1,self.getDefaultValue() )
textbox.setText( self.getDefaultValue() )
textbox.textChanged.connect( self.valueChanged )
self.textbox = textbox
return DimensioningTaskDialog_generate_row_hbox( self.label, textbox )
def add_properties_to_dimension_object( self, obj ):
obj.addProperty("App::PropertyString", self.name, self.category)
KWs = self.dimensioningProcess.dimensionConstructorKWs
setattr( obj, self.name, encode_if_py2(KWs[ self.name ]) )
def get_values_from_dimension_object( self, obj, KWs ):
#KWs[self.name] = unicode( getattr( obj, self.name ), 'utf8' )
KWs[self.name] = getattr( obj, self.name )
<|code_end|>
, determine the next line of code. You have imports:
import sys
import FreeCAD
from drawingDimensioning.py3_helpers import unicode, unicode_type, map, encode_if_py2
from PySide import QtGui, QtCore, QtSvg
from drawingDimensioning.svgConstructor import SvgTextRenderer
and context (class names, function names, or code) available:
# Path: drawingDimensioning/py3_helpers.py
# def unicode(*args):
# def translate(*args):
# def encode_if_py2(unicode_object):
# def map(function, arg):
#
# Path: drawingDimensioning/svgLib.py
# class SvgTextRenderer:
# def __init__(self, font_family='inherit', font_size='inherit', fill='rgb(0,0,0)'):
# self.font_family = font_family
# self.font_size = font_size
# self.fill = fill
# def __call__(self, x, y, text, text_anchor='inherit', rotation=None):
# '''
# text_anchor = start | middle | end | inherit
# rotation is in degress, and is done about x,y
# '''
# try:
# XML = '''<text x="%f" y="%f" font-family="%s" font-size="%s" fill="%s" text-anchor="%s" %s >%s</text>''' % ( x, y, self.font_family, self.font_size, self.fill, text_anchor, 'transform="rotate(%f %f,%f)"' % (rotation,x,y) if rotation != None else '', text )
# except UnicodeDecodeError:
# text_utf8 = unicode( text, 'utf8' )
# XML = '''<text x="%f" y="%f" font-family="%s" font-size="%s" fill="%s" text-anchor="%s" %s >%s</text>''' % ( x, y, self.font_family, self.font_size, self.fill, text_anchor, 'transform="rotate(%f %f,%f)"' % (rotation,x,y) if rotation != None else '', text_utf8 )
# return XML
# def __repr__(self):
# return '<svgLib_dd.SvgTextRenderer family="%s" font_size="%s" fill="%s">' % (self.font_family, self.font_size, self.fill )
. Output only the next line. | if not type(KWs[self.name]) == unicode_type: |
Next line prediction: <|code_start|> def FreeCAD_parm_to_val( self, FreeCAD_parm ):
return [ unicode( line, 'utf8' ) for line in FreeCAD_parm.split('\n') ]
def getDefaultValue(self):
return self.FreeCAD_parm_to_val( self.dd_parms.GetString( self.name, self.val_to_FreeCAD_parm( self.defaultValue ) ) )
def updateDefault(self):
self.dd_parms.SetString( self.name, self.val_to_FreeCAD_parm( self.dimensioningProcess.dimensionConstructorKWs[ self.name ] ) )
def set_textbox_text( self, values ):
self.textbox.clear()
for v in values:
self.textbox.append( str(v) if type(v) == float else v )
def revertToDefault( self ):
self.set_textbox_text( self.getDefaultValue() )
def generateWidget( self, dimensioningProcess ):
self.dimensioningProcess = dimensioningProcess
self.textbox = QtGui.QTextEdit()
self.revertToDefault()
self.textbox.textChanged.connect( self.textChanged )
return DimensioningTaskDialog_generate_row_hbox( self.label, self.textbox )
def textChanged( self, arg1=None):
self.dimensioningProcess.dimensionConstructorKWs[ self.name ] = self.textbox.toPlainText().split('\n')
def add_properties_to_dimension_object( self, obj ):
obj.addProperty("App::PropertyStringList", self.name, self.category)
KWs = self.dimensioningProcess.dimensionConstructorKWs
setattr( obj, self.name, [ encode_if_py2(v) for v in KWs[ self.name ] ] )
def get_values_from_dimension_object( self, obj, KWs ):
KWs[self.name] = getattr( obj, self.name )
DimensioningPreferenceClasses['string_list'] = DimensioningPreference_string_list
class DimensioningPreference_float_list(DimensioningPreference_string_list):
def val_to_FreeCAD_parm( self, val ):
<|code_end|>
. Use current file imports:
(import sys
import FreeCAD
from drawingDimensioning.py3_helpers import unicode, unicode_type, map, encode_if_py2
from PySide import QtGui, QtCore, QtSvg
from drawingDimensioning.svgConstructor import SvgTextRenderer)
and context including class names, function names, or small code snippets from other files:
# Path: drawingDimensioning/py3_helpers.py
# def unicode(*args):
# def translate(*args):
# def encode_if_py2(unicode_object):
# def map(function, arg):
#
# Path: drawingDimensioning/svgLib.py
# class SvgTextRenderer:
# def __init__(self, font_family='inherit', font_size='inherit', fill='rgb(0,0,0)'):
# self.font_family = font_family
# self.font_size = font_size
# self.fill = fill
# def __call__(self, x, y, text, text_anchor='inherit', rotation=None):
# '''
# text_anchor = start | middle | end | inherit
# rotation is in degress, and is done about x,y
# '''
# try:
# XML = '''<text x="%f" y="%f" font-family="%s" font-size="%s" fill="%s" text-anchor="%s" %s >%s</text>''' % ( x, y, self.font_family, self.font_size, self.fill, text_anchor, 'transform="rotate(%f %f,%f)"' % (rotation,x,y) if rotation != None else '', text )
# except UnicodeDecodeError:
# text_utf8 = unicode( text, 'utf8' )
# XML = '''<text x="%f" y="%f" font-family="%s" font-size="%s" fill="%s" text-anchor="%s" %s >%s</text>''' % ( x, y, self.font_family, self.font_size, self.fill, text_anchor, 'transform="rotate(%f %f,%f)"' % (rotation,x,y) if rotation != None else '', text_utf8 )
# return XML
# def __repr__(self):
# return '<svgLib_dd.SvgTextRenderer family="%s" font_size="%s" fill="%s">' % (self.font_family, self.font_size, self.fill )
. Output only the next line. | return '\n'.join(map(str, val)) |
Here is a snippet: <|code_start|> def getDefaultValue(self):
return self.dd_parms.GetFloat( self.name, self.defaultValue )
def updateDefault(self):
self.dd_parms.SetFloat( self.name, self.dimensioningProcess.dimensionConstructorKWs[ self.name ] )
def revertToDefault( self ):
self.spinbox.setValue( self.getDefaultValue() )
def generateWidget( self, dimensioningProcess ):
self.dimensioningProcess = dimensioningProcess
spinbox = QtGui.QDoubleSpinBox()
spinbox.setValue( self.getDefaultValue() )
spinbox.setMinimum( self.spinBox_min )
spinbox.setSingleStep( self.spinBox_increment )
spinbox.setDecimals(self.spinBox_decimals)
spinbox.valueChanged.connect( self.valueChanged )
self.spinbox = spinbox
return DimensioningTaskDialog_generate_row_hbox( self.label, spinbox )
def add_properties_to_dimension_object( self, obj ):
obj.addProperty("App::PropertyFloat", self.name, self.category)
KWs = self.dimensioningProcess.dimensionConstructorKWs
setattr( obj, self.name, KWs[ self.name ] )
if sys.version_info.major < 3:
DimensioningPreferenceClasses["<type 'float'>"] = DimensioningPreference_float
DimensioningPreferenceClasses["<type 'int'>"] = DimensioningPreference_float
else:
DimensioningPreferenceClasses["<class 'float'>"] = DimensioningPreference_float
DimensioningPreferenceClasses["<class 'int'>"] = DimensioningPreference_float
class DimensioningPreference_unicode(DimensioningPreference_prototype):
def getDefaultValue(self):
<|code_end|>
. Write the next line using the current file imports:
import sys
import FreeCAD
from drawingDimensioning.py3_helpers import unicode, unicode_type, map, encode_if_py2
from PySide import QtGui, QtCore, QtSvg
from drawingDimensioning.svgConstructor import SvgTextRenderer
and context from other files:
# Path: drawingDimensioning/py3_helpers.py
# def unicode(*args):
# def translate(*args):
# def encode_if_py2(unicode_object):
# def map(function, arg):
#
# Path: drawingDimensioning/svgLib.py
# class SvgTextRenderer:
# def __init__(self, font_family='inherit', font_size='inherit', fill='rgb(0,0,0)'):
# self.font_family = font_family
# self.font_size = font_size
# self.fill = fill
# def __call__(self, x, y, text, text_anchor='inherit', rotation=None):
# '''
# text_anchor = start | middle | end | inherit
# rotation is in degress, and is done about x,y
# '''
# try:
# XML = '''<text x="%f" y="%f" font-family="%s" font-size="%s" fill="%s" text-anchor="%s" %s >%s</text>''' % ( x, y, self.font_family, self.font_size, self.fill, text_anchor, 'transform="rotate(%f %f,%f)"' % (rotation,x,y) if rotation != None else '', text )
# except UnicodeDecodeError:
# text_utf8 = unicode( text, 'utf8' )
# XML = '''<text x="%f" y="%f" font-family="%s" font-size="%s" fill="%s" text-anchor="%s" %s >%s</text>''' % ( x, y, self.font_family, self.font_size, self.fill, text_anchor, 'transform="rotate(%f %f,%f)"' % (rotation,x,y) if rotation != None else '', text_utf8 )
# return XML
# def __repr__(self):
# return '<svgLib_dd.SvgTextRenderer family="%s" font_size="%s" fill="%s">' % (self.font_family, self.font_size, self.fill )
, which may include functions, classes, or code. Output only the next line. | encoded_value = self.dd_parms.GetString( self.name, encode_if_py2(self.defaultValue) ) |
Predict the next line after this snippet: <|code_start|> return DimensioningTaskDialog_generate_row_hbox( self.label, colorBox )
def add_properties_to_dimension_object( self, obj ):
obj.addProperty("App::PropertyString", self.name, self.category)
KWs = self.dimensioningProcess.dimensionConstructorKWs
setattr( obj, self.name, encode_if_py2(KWs[ self.name ]) )
def get_values_from_dimension_object( self, obj, KWs ):
KWs[self.name] = getattr( obj, self.name )
DimensioningPreferenceClasses["color"] = DimensioningPreference_color
class DimensioningPreference_font(DimensioningPreference_color):
'3 linked parameters: $name_family $name_size $name_color'
def update_dimensionConstructorKWs(self , notUsed=None):
textRenderer = self.dimensioningProcess.dimensionConstructorKWs[ self.name ]
textRenderer.font_family = self.family_textbox.text()
textRenderer.font_size = self.size_textbox.text()
color = self.colorRect.brush().color()
textRenderer.fill = 'rgb(%i,%i,%i)' % (color.red(), color.green(), color.blue() )
def clickFun(self):
color = QtGui.QColorDialog.getColor( self.colorRect.brush().color() )
if color.isValid():
self.colorRect.setBrush( QtGui.QBrush(color) )
self.update_dimensionConstructorKWs()
def getDefaultValue(self):
family = self.dd_parms.GetString( self.name + '_family', self.defaultValue[0])
size = self.dd_parms.GetString( self.name + '_size', self.defaultValue[1])
color = unsignedToRGBText(self.dd_parms.GetUnsigned( self.name + '_color', self.defaultValue[2] ))
<|code_end|>
using the current file's imports:
import sys
import FreeCAD
from drawingDimensioning.py3_helpers import unicode, unicode_type, map, encode_if_py2
from PySide import QtGui, QtCore, QtSvg
from drawingDimensioning.svgConstructor import SvgTextRenderer
and any relevant context from other files:
# Path: drawingDimensioning/py3_helpers.py
# def unicode(*args):
# def translate(*args):
# def encode_if_py2(unicode_object):
# def map(function, arg):
#
# Path: drawingDimensioning/svgLib.py
# class SvgTextRenderer:
# def __init__(self, font_family='inherit', font_size='inherit', fill='rgb(0,0,0)'):
# self.font_family = font_family
# self.font_size = font_size
# self.fill = fill
# def __call__(self, x, y, text, text_anchor='inherit', rotation=None):
# '''
# text_anchor = start | middle | end | inherit
# rotation is in degress, and is done about x,y
# '''
# try:
# XML = '''<text x="%f" y="%f" font-family="%s" font-size="%s" fill="%s" text-anchor="%s" %s >%s</text>''' % ( x, y, self.font_family, self.font_size, self.fill, text_anchor, 'transform="rotate(%f %f,%f)"' % (rotation,x,y) if rotation != None else '', text )
# except UnicodeDecodeError:
# text_utf8 = unicode( text, 'utf8' )
# XML = '''<text x="%f" y="%f" font-family="%s" font-size="%s" fill="%s" text-anchor="%s" %s >%s</text>''' % ( x, y, self.font_family, self.font_size, self.fill, text_anchor, 'transform="rotate(%f %f,%f)"' % (rotation,x,y) if rotation != None else '', text_utf8 )
# return XML
# def __repr__(self):
# return '<svgLib_dd.SvgTextRenderer family="%s" font_size="%s" fill="%s">' % (self.font_family, self.font_size, self.fill )
. Output only the next line. | return SvgTextRenderer(family, size, color) |
Given the following code snippet before the placeholder: <|code_start|>BD 0 5E 232 189 0 94
BD 7E 9D 233 189 126 157
81 0 40 234 129 0 64
81 56 6B 235 129 86 107
68 0 34 236 104 0 52
68 45 56 237 104 69 86
4F 0 27 238 79 0 39
4F 35 42 239 79 53 66
FF 0 3F 240 255 0 63
FF AA BF 241 255 170 191
BD 0 2E 242 189 0 46
BD 7E 8D 243 189 126 141
81 0 1F 244 129 0 31
81 56 60 245 129 86 96
68 0 19 246 104 0 25
68 45 4E 247 104 69 78
4F 0 13 248 79 0 19
4F 35 3B 249 79 53 59
33 33 33 250 51 51 51
50 50 50 251 80 80 80
69 69 69 252 105 105 105
82 82 82 253 130 130 130
BE BE BE 254 190 190 190
FF FF FF 255 255 255 255'''
dxf_colours = numpy.zeros([ 256, 3 ])
for line in color_table_text.split('\n'):
parts = line.split()
ind = int(parts[3])
<|code_end|>
, predict the next line using imports from the current file:
from drawingDimensioning.command import *
from drawingDimensioning.py3_helpers import map
from drawingDimensioning.XMLlib import SvgXMLTreeNode
from drawingDimensioning.svgLib import SvgTextParser, SvgPath, SvgPolygon
from drawingDimensioning.circleLib import fitCircle_to_path, findCircularArcCentrePoint, pointsAlongCircularArc
from numpy import arctan2
from dxfwrite import DXFEngine as dxf
import subprocess
and context including class names, function names, and sometimes code from other files:
# Path: drawingDimensioning/py3_helpers.py
# def map(function, arg):
# return list(_map(function, arg))
. Output only the next line. | r,g,b = map(int, parts[4:]) |
Here is a snippet: <|code_start|>sys.path.append('/usr/lib/freecad/lib/') #path to FreeCAD library on Linux
try:
except ImportError as msg:
print('Import error, is this testing script being run from Python2?')
raise ImportError(msg)
assert not hasattr(FreeCADGui, 'addCommand')
def addCommand_check( name, command):
pass
#if not name.startswith('assembly2_'):
# raise ValueError('%s does not begin with %s' % ( name, 'assembly2_' ) )
FreeCADGui.addCommand = addCommand_check
app = QtGui.QApplication([])
#need to be defined before drawingDimensioning , else Qt crashes
parser = argparse.ArgumentParser()
parser.add_argument('--failfast', action='store_true', help='Stop the test run on the first error or failure.')
parser.add_argument('--buffer', action='store_true', help='The standard output and standard error streams are buffered during the test run. Output during a passing test is discarded. Output is echoed normally on test fail or error and is added to the failure messages.')
parser.add_argument('-v','--verbosity', type=int, default=1 )
parser.add_argument('--no_descriptions', action='store_true' )
parser.add_argument('testSuiteName', type=str, nargs='*')
args = parser.parse_args()
debugPrint.level = 0
testLoader = unittest.TestLoader()
if args.testSuiteName == []:
suite = testLoader.discover(
<|code_end|>
. Write the next line using the current file imports:
import unittest
import sys, os
import FreeCAD, FreeCADGui
import argparse
import drawingDimensioning
from PySide import QtGui, QtSvg, QtCore
from drawingDimensioning.core import __dir__, debugPrint
and context from other files:
# Path: drawingDimensioning/core.py
# def debugPrint( level, msg ):
# def findUnusedObjectName(base, counterStart=1, fmt='%03i'):
# def errorMessagebox_with_traceback(title='Error'):
# def getDrawingPageGUIVars():
# def __init__(self, data):
# def recomputeWithOutViewReset( drawingVars ):
# def printGraphicsViewInfo( drawingVars ):
# def Activated(self):
# def GetResources(self):
# def dimensionableObjects ( page ):
# class DrawingPageGUIVars:
# class helpCommand:
# T = gV.transform()
# T = drawingVars.graphicsView.transform()
, which may include functions, classes, or code. Output only the next line. | start_dir = os.path.join( __dir__ , 'test' ), |
Continue the code snippet: <|code_start|>sys.path.append('/usr/lib/freecad/lib/') #path to FreeCAD library on Linux
try:
except ImportError as msg:
print('Import error, is this testing script being run from Python2?')
raise ImportError(msg)
assert not hasattr(FreeCADGui, 'addCommand')
def addCommand_check( name, command):
pass
#if not name.startswith('assembly2_'):
# raise ValueError('%s does not begin with %s' % ( name, 'assembly2_' ) )
FreeCADGui.addCommand = addCommand_check
app = QtGui.QApplication([])
#need to be defined before drawingDimensioning , else Qt crashes
parser = argparse.ArgumentParser()
parser.add_argument('--failfast', action='store_true', help='Stop the test run on the first error or failure.')
parser.add_argument('--buffer', action='store_true', help='The standard output and standard error streams are buffered during the test run. Output during a passing test is discarded. Output is echoed normally on test fail or error and is added to the failure messages.')
parser.add_argument('-v','--verbosity', type=int, default=1 )
parser.add_argument('--no_descriptions', action='store_true' )
parser.add_argument('testSuiteName', type=str, nargs='*')
args = parser.parse_args()
<|code_end|>
. Use current file imports:
import unittest
import sys, os
import FreeCAD, FreeCADGui
import argparse
import drawingDimensioning
from PySide import QtGui, QtSvg, QtCore
from drawingDimensioning.core import __dir__, debugPrint
and context (classes, functions, or code) from other files:
# Path: drawingDimensioning/core.py
# def debugPrint( level, msg ):
# def findUnusedObjectName(base, counterStart=1, fmt='%03i'):
# def errorMessagebox_with_traceback(title='Error'):
# def getDrawingPageGUIVars():
# def __init__(self, data):
# def recomputeWithOutViewReset( drawingVars ):
# def printGraphicsViewInfo( drawingVars ):
# def Activated(self):
# def GetResources(self):
# def dimensionableObjects ( page ):
# class DrawingPageGUIVars:
# class helpCommand:
# T = gV.transform()
# T = drawingVars.graphicsView.transform()
. Output only the next line. | debugPrint.level = 0 |
Predict the next line for this snippet: <|code_start|> sizePolicy.setHeightForWidth(self.label_2.sizePolicy().hasHeightForWidth())
self.label_2.setSizePolicy(sizePolicy)
self.label_2.setMinimumSize(QtCore.QSize(61, 0))
self.label_2.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.label_2.setObjectName("label_2")
self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1)
self.upperLineEdit = QtGui.QLineEdit(Dialog)
self.upperLineEdit.setObjectName("upperLineEdit")
self.gridLayout.addWidget(self.upperLineEdit, 0, 1, 1, 1)
self.lowerLineEdit = QtGui.QLineEdit(Dialog)
self.lowerLineEdit.setObjectName("lowerLineEdit")
self.gridLayout.addWidget(self.lowerLineEdit, 1, 1, 1, 1)
self.label_3 = QtGui.QLabel(Dialog)
self.label_3.setObjectName("label_3")
self.gridLayout.addWidget(self.label_3, 2, 0, 1, 1)
self.scaleDoubleSpinBox = QtGui.QDoubleSpinBox(Dialog)
self.scaleDoubleSpinBox.setMinimum(0.05)
self.scaleDoubleSpinBox.setSingleStep(0.05)
self.scaleDoubleSpinBox.setProperty("value", 0.8)
self.scaleDoubleSpinBox.setObjectName("scaleDoubleSpinBox")
self.gridLayout.addWidget(self.scaleDoubleSpinBox, 2, 1, 1, 1)
self.gridLayout_2.addLayout(self.gridLayout, 1, 0, 1, 1)
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.placeButton, QtCore.SIGNAL("released()"), Dialog.accept)
QtCore.QObject.connect(self.upperLineEdit, QtCore.SIGNAL("returnPressed()"), Dialog.accept)
QtCore.QObject.connect(self.lowerLineEdit, QtCore.SIGNAL("returnPressed()"), Dialog.accept)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
<|code_end|>
with the help of current file imports:
from drawingDimensioning.py3_helpers import translate
from PySide import QtCore, QtGui
and context from other files:
# Path: drawingDimensioning/py3_helpers.py
# def translate(*args):
# if len(args) < 3:
# args.append(None)
# try:
# return QtGui.QApplication.translate(args[0], args[1], args[2], QtGui.QApplication.UnicodeUTF8)
# except AttributeError:
# return QtGui.QApplication.translate(args[0], args[1], args[2])
, which may contain function names, class names, or code. Output only the next line. | Dialog.setWindowTitle(translate("Dialog", "Add tolerance", None)) |
Predict the next line for this snippet: <|code_start|> return '<g> %s </g>' % textRenderer_addText(x,y,text,rotation=rotation)
d.registerPreference( 'textRenderer_addText', ['inherit','5', 0], 'text properties (AddText)', kind='font' )
class text_widget:
def valueChanged( self, arg1):
d.text = arg1
def generateWidget( self, dimensioningProcess ):
self.lineEdit = QtGui.QLineEdit()
self.lineEdit.setText('text')
d.text = 'text'
self.lineEdit.textChanged.connect(self.valueChanged)
return self.lineEdit
def add_properties_to_dimension_object( self, obj ):
obj.addProperty("App::PropertyString", 'text', 'Parameters')
obj.text = encode_if_py2(d.text)
def get_values_from_dimension_object( self, obj, KWs ):
KWs['text'] = obj.text #should be unicode
d.dialogWidgets.append( text_widget() )
class rotation_widget:
def valueChanged( self, arg1):
d.rotation = arg1
def generateWidget( self, dimensioningProcess ):
self.spinbox = QtGui.QDoubleSpinBox()
self.spinbox.setValue(0)
d.rotation = 0
self.spinbox.setMinimum( -180 )
self.spinbox.setMaximum( 180 )
self.spinbox.setDecimals( 1 )
self.spinbox.setSingleStep( 5 )
<|code_end|>
with the help of current file imports:
from drawingDimensioning.py3_helpers import unicode, encode_if_py2
from drawingDimensioning.command import *
and context from other files:
# Path: drawingDimensioning/py3_helpers.py
# def unicode(*args):
# return str(args[0])
#
# def encode_if_py2(unicode_object):
# '''return unicode for py3 and bytes for py2'''
# if sys.version_info.major < 3:
# return unicode_object.encode("utf8")
# else:
# return unicode_object
, which may contain function names, class names, or code. Output only the next line. | self.spinbox.setSuffix(unicode('°','utf8')) |
Using the snippet: <|code_start|># This Python file uses the following encoding: utf-8
d = DimensioningCommand()
def textSVG( x, y, text='text', rotation=0.0, textRenderer_addText= defaultTextRenderer):
return '<g> %s </g>' % textRenderer_addText(x,y,text,rotation=rotation)
d.registerPreference( 'textRenderer_addText', ['inherit','5', 0], 'text properties (AddText)', kind='font' )
class text_widget:
def valueChanged( self, arg1):
d.text = arg1
def generateWidget( self, dimensioningProcess ):
self.lineEdit = QtGui.QLineEdit()
self.lineEdit.setText('text')
d.text = 'text'
self.lineEdit.textChanged.connect(self.valueChanged)
return self.lineEdit
def add_properties_to_dimension_object( self, obj ):
obj.addProperty("App::PropertyString", 'text', 'Parameters')
<|code_end|>
, determine the next line of code. You have imports:
from drawingDimensioning.py3_helpers import unicode, encode_if_py2
from drawingDimensioning.command import *
and context (class names, function names, or code) available:
# Path: drawingDimensioning/py3_helpers.py
# def unicode(*args):
# return str(args[0])
#
# def encode_if_py2(unicode_object):
# '''return unicode for py3 and bytes for py2'''
# if sys.version_info.major < 3:
# return unicode_object.encode("utf8")
# else:
# return unicode_object
. Output only the next line. | obj.text = encode_if_py2(d.text) |
Based on the snippet: <|code_start|>
class Dimensioning_Selection_prototype:
'these selection classes are for purposes of recording a drawing view selection for later updates'
def __init__( self, svg_KWs, svg_element, viewInfo, **extraKWs ):
self.init_for_svg_KWs( svg_KWs, svg_element, **extraKWs )
#info for updating selection after its drawing view has been updated
self.svg_element_tag = svg_element.tag
self.viewInfo = viewInfo #view bounds etc ...
def init_for_svg_KWs( self, svg_KWs, svg_element ):
raise(NotImplementedError,'needs to overwritten depending upon the selection type')
def svg_fun_args( self, args ):
raise(NotImplementedError,'needs to overwritten depending upon the selection type')
class PointSelection( Dimensioning_Selection_prototype ):
def init_for_svg_KWs( self, svg_KWs, svg_element, condensed_args = False ):
self.x = svg_KWs['x']
self.y = svg_KWs['y']
self.condensed_args = condensed_args
def xy(self):
return self.x, self.y
def svg_fun_args( self, args ):
if self.condensed_args:
args.append( [self.x, self.y] )
else:
args.extend( [self.x, self.y] )
def updateValues( self, doc ):
if not self.viewInfo.changed( doc ):
return False
<|code_end|>
, predict the immediate next line with the help of imports:
import pickle
import base64
from numpy.linalg import norm
from numpy import log
from .core import debugPrint
from .svgLib import SvgTextParser
from .recomputeDimensions import SvgElements
from .recomputeDimensions import SvgElements
from .recomputeDimensions import SvgElements
from .recomputeDimensions import SvgElements
and context (classes, functions, sometimes code) from other files:
# Path: drawingDimensioning/core.py
# def debugPrint( level, msg ):
# if level <= debugPrint.level:
# App.Console.PrintMessage(msg + '\n')
#
# Path: drawingDimensioning/svgLib.py
# class SvgTextParser:
# def __init__(self, xml):
# p_header_end = xml.find('>')
# self.header = xml[:p_header_end]
# try:
# self.text = unicode(xml[ p_header_end+1:-len('</text>') ],'utf8')
# except TypeError:
# self.text = unicode(xml[ p_header_end+1:-len('</text>') ])
# #import FreeCAD
# #FreeCAD.Console.PrintMessage(self.text)
# self.parms = {}
# h = self.header
# p = h.find('=')
# while p > -1:
# i = p-1
# key = ''
# while key == '' or h[i] != ' ':
# if h[i] != ' ':
# key = h[i] + key
# i = i - 1
# p1 = h.find('"', p)
# p2 = h.find('"', p1+1)
# self.parms[key] = h[p1+1:p2]
# p = self.header.find('=', p+1)
# self.x = float(self.parms['x'])
# self.y = float(self.parms['y'])
# self.font_family = self.parms.get('font-family', 'inherit')
# self.font_size = self.parms.get('font-size','inherit')
# if 'style' in self.parms: #for backwards compadiability
# self.font_size = self.parms['style'][len('font-size:'):]
# self.fill = self.parms.get('fill','rgb(0,0,0)')
# self.transform = self.parms.get('transform')
# if self.transform != None:
# t = self.transform
# if 'rotate(' in t:
# self.rotation = float(t[t.find('rotate(')+len('rotate('):].split()[0])
# else:
# self.rotation = 0
# else:
# self.rotation = 0
# self.text_anchor = self.parms.get('text-anchor','inherit')
# def toXML(self):
# XML = '''<text x="%f" y="%f" font-family="%s" font-size="%s" fill="%s" text-anchor="%s" %s >%s</text>''' % ( self.x, self.y, self.font_family, self.font_size, self.fill, self.text_anchor, 'transform="rotate(%f %f,%f)"' % (self.rotation,self.x,self.y) if self.rotation != 0 else '', self.text )
# return XML
# def convertUnits(self,value):
# '''http://www.w3.org/TR/SVG/coords.html#Units
# units do not seem to have on font size though:
# 8cm == 8pt == 8blah?'''
# i = 0
# while i < len(value) and value[i] in '0123456789.':
# i = i + 1
# v = value[:i]
# factor = 1.0
# return float(v)*factor
#
# def textRect(self):
# sizeInPoints = self.convertUnits(self.font_size.strip())
# font = QtGui.QFont(self.font_family, sizeInPoints)
# fm = QtGui.QFontMetrics(font)
# return fm.boundingRect(self.text)
#
# def width(self):
# 'return width of untransformed text'
# return self.textRect().width() *0.63
# def height(self):
# 'height of untransformed text'
# return self.textRect().height() *0.6
#
# def __unicode__(self):
# return u'<svgLib_dd.SvgTextParser family="%s" font_size="%s" fill="%s" rotation="%f" text="%s">' % (self.font_family, self.font_size, self.fill, self.rotation, self.text )
#
# def __repr__(self):
# return u'<svgLib_dd.SvgTextParser family="%s" font_size="%s" fill="%s" rotation="%f">' % (self.font_family, self.font_size, self.fill, self.rotation )
. Output only the next line. | debugPrint(3,'PointSelection: drawing %s has changed, updating values' % self.viewInfo.name ) |
Given the code snippet: <|code_start|> def svg_fun_args( self, args ):
if self.output_mode == 'xyr':
args.extend( [self.x, self.y, self.r] )
elif self.output_mode == 'xy':
args.append( [self.x, self.y] )
else:
raise(NotImplementedError, "output_mode %s not implemented" % self.output_mode)
def updateValues( self, doc ):
if not self.viewInfo.changed( doc ):
return False
debugPrint(3,'CircularArcSelection: drawing %s has changed, updating values' % self.viewInfo.name )
new_vi = self.viewInfo.get_up_to_date_version( doc )
old_vi = self.viewInfo
pos_ref = old_vi.normalize_position ( self.x, self.y )
r_ref = self.r / old_vi.scale
svg = SvgElements( doc.getObject( self.viewInfo.name ).ViewResult, self.svg_element_tag)
min_error = None
for x,y,r in svg.circles:
error1 = norm( pos_ref - new_vi.normalize_position ( x,y ) )
error2 = abs( log( r_ref / (r/new_vi.scale) ) )
error = error2 + error1 #giving radius and center position equal priority ...
if min_error == None or error < min_error:
self.x, self.y, self.r = x,y,r
self.viewInfo = new_vi
return True
class TextSelection( Dimensioning_Selection_prototype ):
def init_for_svg_KWs( self, svg_KWs, svg_element ):
<|code_end|>
, generate the next line using the imports in this file:
import pickle
import base64
from numpy.linalg import norm
from numpy import log
from .core import debugPrint
from .svgLib import SvgTextParser
from .recomputeDimensions import SvgElements
from .recomputeDimensions import SvgElements
from .recomputeDimensions import SvgElements
from .recomputeDimensions import SvgElements
and context (functions, classes, or occasionally code) from other files:
# Path: drawingDimensioning/core.py
# def debugPrint( level, msg ):
# if level <= debugPrint.level:
# App.Console.PrintMessage(msg + '\n')
#
# Path: drawingDimensioning/svgLib.py
# class SvgTextParser:
# def __init__(self, xml):
# p_header_end = xml.find('>')
# self.header = xml[:p_header_end]
# try:
# self.text = unicode(xml[ p_header_end+1:-len('</text>') ],'utf8')
# except TypeError:
# self.text = unicode(xml[ p_header_end+1:-len('</text>') ])
# #import FreeCAD
# #FreeCAD.Console.PrintMessage(self.text)
# self.parms = {}
# h = self.header
# p = h.find('=')
# while p > -1:
# i = p-1
# key = ''
# while key == '' or h[i] != ' ':
# if h[i] != ' ':
# key = h[i] + key
# i = i - 1
# p1 = h.find('"', p)
# p2 = h.find('"', p1+1)
# self.parms[key] = h[p1+1:p2]
# p = self.header.find('=', p+1)
# self.x = float(self.parms['x'])
# self.y = float(self.parms['y'])
# self.font_family = self.parms.get('font-family', 'inherit')
# self.font_size = self.parms.get('font-size','inherit')
# if 'style' in self.parms: #for backwards compadiability
# self.font_size = self.parms['style'][len('font-size:'):]
# self.fill = self.parms.get('fill','rgb(0,0,0)')
# self.transform = self.parms.get('transform')
# if self.transform != None:
# t = self.transform
# if 'rotate(' in t:
# self.rotation = float(t[t.find('rotate(')+len('rotate('):].split()[0])
# else:
# self.rotation = 0
# else:
# self.rotation = 0
# self.text_anchor = self.parms.get('text-anchor','inherit')
# def toXML(self):
# XML = '''<text x="%f" y="%f" font-family="%s" font-size="%s" fill="%s" text-anchor="%s" %s >%s</text>''' % ( self.x, self.y, self.font_family, self.font_size, self.fill, self.text_anchor, 'transform="rotate(%f %f,%f)"' % (self.rotation,self.x,self.y) if self.rotation != 0 else '', self.text )
# return XML
# def convertUnits(self,value):
# '''http://www.w3.org/TR/SVG/coords.html#Units
# units do not seem to have on font size though:
# 8cm == 8pt == 8blah?'''
# i = 0
# while i < len(value) and value[i] in '0123456789.':
# i = i + 1
# v = value[:i]
# factor = 1.0
# return float(v)*factor
#
# def textRect(self):
# sizeInPoints = self.convertUnits(self.font_size.strip())
# font = QtGui.QFont(self.font_family, sizeInPoints)
# fm = QtGui.QFontMetrics(font)
# return fm.boundingRect(self.text)
#
# def width(self):
# 'return width of untransformed text'
# return self.textRect().width() *0.63
# def height(self):
# 'height of untransformed text'
# return self.textRect().height() *0.6
#
# def __unicode__(self):
# return u'<svgLib_dd.SvgTextParser family="%s" font_size="%s" fill="%s" rotation="%f" text="%s">' % (self.font_family, self.font_size, self.fill, self.rotation, self.text )
#
# def __repr__(self):
# return u'<svgLib_dd.SvgTextParser family="%s" font_size="%s" fill="%s" rotation="%f">' % (self.font_family, self.font_size, self.fill, self.rotation )
. Output only the next line. | self.svgText = SvgTextParser( svg_element.XML[svg_element.pStart:svg_element.pEnd]) |
Here is a snippet: <|code_start|>
class PhotoRequestFilter(django_filters.FilterSet):
class Meta:
model = models.PhotoRequest
fields = {'story': ['exact'],
'assignees': ['exact'],
'time': ['exact', 'lt', 'gt']
}
<|code_end|>
. Write the next line using the current file imports:
import django_filters
from rest_framework import viewsets
from revisions.views import VersionableModelViewSetMixin
from . import serializers
from . import models
and context from other files:
# Path: revisions/views.py
# class VersionableModelViewSetMixin(viewsets.ModelViewSet):
# """Provides routes to versioned models for listing revisions and reverting
# to them.
#
# Include this mixin on ModelViewSets which have their revision history
# tracked with django-reversion. It provides two endpoints:
#
# 1. "/revisions" (method: GET) - append to a detail view URL (e.g.
# "/v1/stories/24/revisions") to view a list of revisions associated with
# this object.
# 2. "/revert" (method: PUT) - append to a detail view URL (e.g.
# "/v1/stories/24/revert") and provide payload data in the format
# "revision: <revision_id>", where revision_id is the id of the revision
# associated with this object to which you want to revert this object.
# On success, will return HTTP 200 and JSON string of the object's fields
# at the specified revision. If no revision id is provided or an invalid
# revision id is provided (revision doesn't exist or revision is not
# associated with this object), a 404 error will be returned.
#
# Associated Django Rest Framework implementation docs:
# http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing
# """
#
# @detail_route(methods=['get'])
# def revisions(self, request, pk=None):
# object = self.get_object()
# versions = reversion.get_for_object(object)
# version_serializer = serializers.VersionSerializer(versions, many=True)
# return Response(version_serializer.data)
#
# @detail_route(methods=['put'])
# def revert(self, request, pk=None):
# object = self.get_object()
# version = get_object_or_404(Version, object_id=object.id,
# id=request.data.get('revision'))
# # http://django-reversion.readthedocs.org/en/release-1.8.1/api.html#reverting-to-previous-revisions
# version.revert()
# return Response(version.field_dict)
, which may include functions, classes, or code. Output only the next line. | class PhotoRequestViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet): |
Given the code snippet: <|code_start|>
router = routers.DefaultRouter()
# get the view for auto-generated API docs from Swagger
docs_view = get_swagger_view(title='docs')
# access
router.register(r'users', access_views.UserViewSet)
router.register(r'groups', access_views.GroupViewSet)
router.register(r'permissions', access_views.PermissionViewSet)
# attachments
<|code_end|>
, generate the next line using the imports in this file:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from rest_framework import routers
from rest_framework.authtoken import views as rest_framework_views
from rest_framework_swagger.views import get_swagger_view
from access import views as access_views
from attachments import views as attachments_views
from authors import views as authors_views
from comments import views as comments_views
from core import views as core_views
from display import views as display_views
from organization import views as organization_views
from requests import views as requests_views
from sports import views as sports_views
and context (functions, classes, or occasionally code) from other files:
# Path: access/views.py
# class UserFilter(django_filters.FilterSet):
# class Meta:
# class UserViewSet(viewsets.ModelViewSet):
# class GroupViewSet(viewsets.ModelViewSet):
# class PermissionViewSet(viewsets.ModelViewSet):
#
# Path: attachments/views.py
# class ImageViewSet(viewsets.ModelViewSet):
# class VideoViewSet(viewsets.ModelViewSet):
# class AudioViewSet(viewsets.ModelViewSet):
# class ReviewFilter(django_filters.FilterSet):
# class Meta:
# class ReviewViewSet(viewsets.ModelViewSet):
# class PollViewSet(viewsets.ModelViewSet):
# class PollChoiceViewSet(viewsets.ModelViewSet):
#
# Path: authors/views.py
# class AuthorViewSet(viewsets.ModelViewSet):
# class OrganizationViewSet(viewsets.ModelViewSet):
# class PositionViewSet(viewsets.ModelViewSet):
#
# Path: comments/views.py
# class InternalCommentFilter(django_filters.FilterSet):
# class Meta:
# class InternalCommentViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
#
# Path: core/views.py
# class SchemaViewSet(viewsets.ViewSet):
# class StatusViewSet(viewsets.ModelViewSet):
# class StoryFilter(django_filters.FilterSet):
# class Meta:
# class StoryViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# class PageViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# def list(self, request):
# def get_queryset(self):
#
# Path: display/views.py
# class CardSizeViewSet(viewsets.ModelViewSet):
# class StylesheetViewSet(viewsets.ModelViewSet):
# class ScriptViewSet(viewsets.ModelViewSet):
# class TemplateViewSet(viewsets.ModelViewSet):
#
# Path: organization/views.py
# class SectionViewSet(viewsets.ModelViewSet):
# class TagViewSet(viewsets.ModelViewSet):
# class SiteViewSet(viewsets.ModelViewSet):
#
# Path: requests/views.py
# class PhotoRequestFilter(django_filters.FilterSet):
# class Meta:
# class PhotoRequestViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# class GraphicRequestViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
# class IllustrationRequestViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
#
# Path: sports/views.py
# class SportViewSet(viewsets.ModelViewSet):
# class SchoolViewSet(viewsets.ModelViewSet):
# class GameFilter(django_filters.FilterSet):
# class Meta:
# class GameViewSet(viewsets.ModelViewSet):
. Output only the next line. | router.register(r'images', attachments_views.ImageViewSet) |
Predict the next line after this snippet: <|code_start|>
router = routers.DefaultRouter()
# get the view for auto-generated API docs from Swagger
docs_view = get_swagger_view(title='docs')
# access
router.register(r'users', access_views.UserViewSet)
router.register(r'groups', access_views.GroupViewSet)
router.register(r'permissions', access_views.PermissionViewSet)
# attachments
router.register(r'images', attachments_views.ImageViewSet)
router.register(r'videos', attachments_views.VideoViewSet)
router.register(r'audio', attachments_views.AudioViewSet)
router.register(r'reviews', attachments_views.ReviewViewSet)
router.register(r'polls', attachments_views.PollViewSet)
router.register(r'poll_choices', attachments_views.PollChoiceViewSet)
# authors
<|code_end|>
using the current file's imports:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from rest_framework import routers
from rest_framework.authtoken import views as rest_framework_views
from rest_framework_swagger.views import get_swagger_view
from access import views as access_views
from attachments import views as attachments_views
from authors import views as authors_views
from comments import views as comments_views
from core import views as core_views
from display import views as display_views
from organization import views as organization_views
from requests import views as requests_views
from sports import views as sports_views
and any relevant context from other files:
# Path: access/views.py
# class UserFilter(django_filters.FilterSet):
# class Meta:
# class UserViewSet(viewsets.ModelViewSet):
# class GroupViewSet(viewsets.ModelViewSet):
# class PermissionViewSet(viewsets.ModelViewSet):
#
# Path: attachments/views.py
# class ImageViewSet(viewsets.ModelViewSet):
# class VideoViewSet(viewsets.ModelViewSet):
# class AudioViewSet(viewsets.ModelViewSet):
# class ReviewFilter(django_filters.FilterSet):
# class Meta:
# class ReviewViewSet(viewsets.ModelViewSet):
# class PollViewSet(viewsets.ModelViewSet):
# class PollChoiceViewSet(viewsets.ModelViewSet):
#
# Path: authors/views.py
# class AuthorViewSet(viewsets.ModelViewSet):
# class OrganizationViewSet(viewsets.ModelViewSet):
# class PositionViewSet(viewsets.ModelViewSet):
#
# Path: comments/views.py
# class InternalCommentFilter(django_filters.FilterSet):
# class Meta:
# class InternalCommentViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
#
# Path: core/views.py
# class SchemaViewSet(viewsets.ViewSet):
# class StatusViewSet(viewsets.ModelViewSet):
# class StoryFilter(django_filters.FilterSet):
# class Meta:
# class StoryViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# class PageViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# def list(self, request):
# def get_queryset(self):
#
# Path: display/views.py
# class CardSizeViewSet(viewsets.ModelViewSet):
# class StylesheetViewSet(viewsets.ModelViewSet):
# class ScriptViewSet(viewsets.ModelViewSet):
# class TemplateViewSet(viewsets.ModelViewSet):
#
# Path: organization/views.py
# class SectionViewSet(viewsets.ModelViewSet):
# class TagViewSet(viewsets.ModelViewSet):
# class SiteViewSet(viewsets.ModelViewSet):
#
# Path: requests/views.py
# class PhotoRequestFilter(django_filters.FilterSet):
# class Meta:
# class PhotoRequestViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# class GraphicRequestViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
# class IllustrationRequestViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
#
# Path: sports/views.py
# class SportViewSet(viewsets.ModelViewSet):
# class SchoolViewSet(viewsets.ModelViewSet):
# class GameFilter(django_filters.FilterSet):
# class Meta:
# class GameViewSet(viewsets.ModelViewSet):
. Output only the next line. | router.register(r'authors', authors_views.AuthorViewSet) |
Continue the code snippet: <|code_start|>
router = routers.DefaultRouter()
# get the view for auto-generated API docs from Swagger
docs_view = get_swagger_view(title='docs')
# access
router.register(r'users', access_views.UserViewSet)
router.register(r'groups', access_views.GroupViewSet)
router.register(r'permissions', access_views.PermissionViewSet)
# attachments
router.register(r'images', attachments_views.ImageViewSet)
router.register(r'videos', attachments_views.VideoViewSet)
router.register(r'audio', attachments_views.AudioViewSet)
router.register(r'reviews', attachments_views.ReviewViewSet)
router.register(r'polls', attachments_views.PollViewSet)
router.register(r'poll_choices', attachments_views.PollChoiceViewSet)
# authors
router.register(r'authors', authors_views.AuthorViewSet)
router.register(r'organizations', authors_views.OrganizationViewSet)
router.register(r'positions', authors_views.PositionViewSet)
# comments
<|code_end|>
. Use current file imports:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from rest_framework import routers
from rest_framework.authtoken import views as rest_framework_views
from rest_framework_swagger.views import get_swagger_view
from access import views as access_views
from attachments import views as attachments_views
from authors import views as authors_views
from comments import views as comments_views
from core import views as core_views
from display import views as display_views
from organization import views as organization_views
from requests import views as requests_views
from sports import views as sports_views
and context (classes, functions, or code) from other files:
# Path: access/views.py
# class UserFilter(django_filters.FilterSet):
# class Meta:
# class UserViewSet(viewsets.ModelViewSet):
# class GroupViewSet(viewsets.ModelViewSet):
# class PermissionViewSet(viewsets.ModelViewSet):
#
# Path: attachments/views.py
# class ImageViewSet(viewsets.ModelViewSet):
# class VideoViewSet(viewsets.ModelViewSet):
# class AudioViewSet(viewsets.ModelViewSet):
# class ReviewFilter(django_filters.FilterSet):
# class Meta:
# class ReviewViewSet(viewsets.ModelViewSet):
# class PollViewSet(viewsets.ModelViewSet):
# class PollChoiceViewSet(viewsets.ModelViewSet):
#
# Path: authors/views.py
# class AuthorViewSet(viewsets.ModelViewSet):
# class OrganizationViewSet(viewsets.ModelViewSet):
# class PositionViewSet(viewsets.ModelViewSet):
#
# Path: comments/views.py
# class InternalCommentFilter(django_filters.FilterSet):
# class Meta:
# class InternalCommentViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
#
# Path: core/views.py
# class SchemaViewSet(viewsets.ViewSet):
# class StatusViewSet(viewsets.ModelViewSet):
# class StoryFilter(django_filters.FilterSet):
# class Meta:
# class StoryViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# class PageViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# def list(self, request):
# def get_queryset(self):
#
# Path: display/views.py
# class CardSizeViewSet(viewsets.ModelViewSet):
# class StylesheetViewSet(viewsets.ModelViewSet):
# class ScriptViewSet(viewsets.ModelViewSet):
# class TemplateViewSet(viewsets.ModelViewSet):
#
# Path: organization/views.py
# class SectionViewSet(viewsets.ModelViewSet):
# class TagViewSet(viewsets.ModelViewSet):
# class SiteViewSet(viewsets.ModelViewSet):
#
# Path: requests/views.py
# class PhotoRequestFilter(django_filters.FilterSet):
# class Meta:
# class PhotoRequestViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# class GraphicRequestViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
# class IllustrationRequestViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
#
# Path: sports/views.py
# class SportViewSet(viewsets.ModelViewSet):
# class SchoolViewSet(viewsets.ModelViewSet):
# class GameFilter(django_filters.FilterSet):
# class Meta:
# class GameViewSet(viewsets.ModelViewSet):
. Output only the next line. | router.register(r'internal_comments', comments_views.InternalCommentViewSet) |
Based on the snippet: <|code_start|>
router = routers.DefaultRouter()
# get the view for auto-generated API docs from Swagger
docs_view = get_swagger_view(title='docs')
# access
router.register(r'users', access_views.UserViewSet)
router.register(r'groups', access_views.GroupViewSet)
router.register(r'permissions', access_views.PermissionViewSet)
# attachments
router.register(r'images', attachments_views.ImageViewSet)
router.register(r'videos', attachments_views.VideoViewSet)
router.register(r'audio', attachments_views.AudioViewSet)
router.register(r'reviews', attachments_views.ReviewViewSet)
router.register(r'polls', attachments_views.PollViewSet)
router.register(r'poll_choices', attachments_views.PollChoiceViewSet)
# authors
router.register(r'authors', authors_views.AuthorViewSet)
router.register(r'organizations', authors_views.OrganizationViewSet)
router.register(r'positions', authors_views.PositionViewSet)
# comments
router.register(r'internal_comments', comments_views.InternalCommentViewSet)
# core
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from rest_framework import routers
from rest_framework.authtoken import views as rest_framework_views
from rest_framework_swagger.views import get_swagger_view
from access import views as access_views
from attachments import views as attachments_views
from authors import views as authors_views
from comments import views as comments_views
from core import views as core_views
from display import views as display_views
from organization import views as organization_views
from requests import views as requests_views
from sports import views as sports_views
and context (classes, functions, sometimes code) from other files:
# Path: access/views.py
# class UserFilter(django_filters.FilterSet):
# class Meta:
# class UserViewSet(viewsets.ModelViewSet):
# class GroupViewSet(viewsets.ModelViewSet):
# class PermissionViewSet(viewsets.ModelViewSet):
#
# Path: attachments/views.py
# class ImageViewSet(viewsets.ModelViewSet):
# class VideoViewSet(viewsets.ModelViewSet):
# class AudioViewSet(viewsets.ModelViewSet):
# class ReviewFilter(django_filters.FilterSet):
# class Meta:
# class ReviewViewSet(viewsets.ModelViewSet):
# class PollViewSet(viewsets.ModelViewSet):
# class PollChoiceViewSet(viewsets.ModelViewSet):
#
# Path: authors/views.py
# class AuthorViewSet(viewsets.ModelViewSet):
# class OrganizationViewSet(viewsets.ModelViewSet):
# class PositionViewSet(viewsets.ModelViewSet):
#
# Path: comments/views.py
# class InternalCommentFilter(django_filters.FilterSet):
# class Meta:
# class InternalCommentViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
#
# Path: core/views.py
# class SchemaViewSet(viewsets.ViewSet):
# class StatusViewSet(viewsets.ModelViewSet):
# class StoryFilter(django_filters.FilterSet):
# class Meta:
# class StoryViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# class PageViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# def list(self, request):
# def get_queryset(self):
#
# Path: display/views.py
# class CardSizeViewSet(viewsets.ModelViewSet):
# class StylesheetViewSet(viewsets.ModelViewSet):
# class ScriptViewSet(viewsets.ModelViewSet):
# class TemplateViewSet(viewsets.ModelViewSet):
#
# Path: organization/views.py
# class SectionViewSet(viewsets.ModelViewSet):
# class TagViewSet(viewsets.ModelViewSet):
# class SiteViewSet(viewsets.ModelViewSet):
#
# Path: requests/views.py
# class PhotoRequestFilter(django_filters.FilterSet):
# class Meta:
# class PhotoRequestViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# class GraphicRequestViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
# class IllustrationRequestViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
#
# Path: sports/views.py
# class SportViewSet(viewsets.ModelViewSet):
# class SchoolViewSet(viewsets.ModelViewSet):
# class GameFilter(django_filters.FilterSet):
# class Meta:
# class GameViewSet(viewsets.ModelViewSet):
. Output only the next line. | router.register(r'schema', core_views.SchemaViewSet, base_name='schema') |
Next line prediction: <|code_start|>docs_view = get_swagger_view(title='docs')
# access
router.register(r'users', access_views.UserViewSet)
router.register(r'groups', access_views.GroupViewSet)
router.register(r'permissions', access_views.PermissionViewSet)
# attachments
router.register(r'images', attachments_views.ImageViewSet)
router.register(r'videos', attachments_views.VideoViewSet)
router.register(r'audio', attachments_views.AudioViewSet)
router.register(r'reviews', attachments_views.ReviewViewSet)
router.register(r'polls', attachments_views.PollViewSet)
router.register(r'poll_choices', attachments_views.PollChoiceViewSet)
# authors
router.register(r'authors', authors_views.AuthorViewSet)
router.register(r'organizations', authors_views.OrganizationViewSet)
router.register(r'positions', authors_views.PositionViewSet)
# comments
router.register(r'internal_comments', comments_views.InternalCommentViewSet)
# core
router.register(r'schema', core_views.SchemaViewSet, base_name='schema')
router.register(r'statuses', core_views.StatusViewSet)
router.register(r'stories', core_views.StoryViewSet)
router.register(r'pages', core_views.PageViewSet)
# display
<|code_end|>
. Use current file imports:
(from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from rest_framework import routers
from rest_framework.authtoken import views as rest_framework_views
from rest_framework_swagger.views import get_swagger_view
from access import views as access_views
from attachments import views as attachments_views
from authors import views as authors_views
from comments import views as comments_views
from core import views as core_views
from display import views as display_views
from organization import views as organization_views
from requests import views as requests_views
from sports import views as sports_views)
and context including class names, function names, or small code snippets from other files:
# Path: access/views.py
# class UserFilter(django_filters.FilterSet):
# class Meta:
# class UserViewSet(viewsets.ModelViewSet):
# class GroupViewSet(viewsets.ModelViewSet):
# class PermissionViewSet(viewsets.ModelViewSet):
#
# Path: attachments/views.py
# class ImageViewSet(viewsets.ModelViewSet):
# class VideoViewSet(viewsets.ModelViewSet):
# class AudioViewSet(viewsets.ModelViewSet):
# class ReviewFilter(django_filters.FilterSet):
# class Meta:
# class ReviewViewSet(viewsets.ModelViewSet):
# class PollViewSet(viewsets.ModelViewSet):
# class PollChoiceViewSet(viewsets.ModelViewSet):
#
# Path: authors/views.py
# class AuthorViewSet(viewsets.ModelViewSet):
# class OrganizationViewSet(viewsets.ModelViewSet):
# class PositionViewSet(viewsets.ModelViewSet):
#
# Path: comments/views.py
# class InternalCommentFilter(django_filters.FilterSet):
# class Meta:
# class InternalCommentViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
#
# Path: core/views.py
# class SchemaViewSet(viewsets.ViewSet):
# class StatusViewSet(viewsets.ModelViewSet):
# class StoryFilter(django_filters.FilterSet):
# class Meta:
# class StoryViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# class PageViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# def list(self, request):
# def get_queryset(self):
#
# Path: display/views.py
# class CardSizeViewSet(viewsets.ModelViewSet):
# class StylesheetViewSet(viewsets.ModelViewSet):
# class ScriptViewSet(viewsets.ModelViewSet):
# class TemplateViewSet(viewsets.ModelViewSet):
#
# Path: organization/views.py
# class SectionViewSet(viewsets.ModelViewSet):
# class TagViewSet(viewsets.ModelViewSet):
# class SiteViewSet(viewsets.ModelViewSet):
#
# Path: requests/views.py
# class PhotoRequestFilter(django_filters.FilterSet):
# class Meta:
# class PhotoRequestViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# class GraphicRequestViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
# class IllustrationRequestViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
#
# Path: sports/views.py
# class SportViewSet(viewsets.ModelViewSet):
# class SchoolViewSet(viewsets.ModelViewSet):
# class GameFilter(django_filters.FilterSet):
# class Meta:
# class GameViewSet(viewsets.ModelViewSet):
. Output only the next line. | router.register(r'card_sizes', display_views.CardSizeViewSet) |
Based on the snippet: <|code_start|>
# attachments
router.register(r'images', attachments_views.ImageViewSet)
router.register(r'videos', attachments_views.VideoViewSet)
router.register(r'audio', attachments_views.AudioViewSet)
router.register(r'reviews', attachments_views.ReviewViewSet)
router.register(r'polls', attachments_views.PollViewSet)
router.register(r'poll_choices', attachments_views.PollChoiceViewSet)
# authors
router.register(r'authors', authors_views.AuthorViewSet)
router.register(r'organizations', authors_views.OrganizationViewSet)
router.register(r'positions', authors_views.PositionViewSet)
# comments
router.register(r'internal_comments', comments_views.InternalCommentViewSet)
# core
router.register(r'schema', core_views.SchemaViewSet, base_name='schema')
router.register(r'statuses', core_views.StatusViewSet)
router.register(r'stories', core_views.StoryViewSet)
router.register(r'pages', core_views.PageViewSet)
# display
router.register(r'card_sizes', display_views.CardSizeViewSet)
router.register(r'stylesheets', display_views.StylesheetViewSet)
router.register(r'scripts', display_views.ScriptViewSet)
router.register(r'templates', display_views.TemplateViewSet)
# organization
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from rest_framework import routers
from rest_framework.authtoken import views as rest_framework_views
from rest_framework_swagger.views import get_swagger_view
from access import views as access_views
from attachments import views as attachments_views
from authors import views as authors_views
from comments import views as comments_views
from core import views as core_views
from display import views as display_views
from organization import views as organization_views
from requests import views as requests_views
from sports import views as sports_views
and context (classes, functions, sometimes code) from other files:
# Path: access/views.py
# class UserFilter(django_filters.FilterSet):
# class Meta:
# class UserViewSet(viewsets.ModelViewSet):
# class GroupViewSet(viewsets.ModelViewSet):
# class PermissionViewSet(viewsets.ModelViewSet):
#
# Path: attachments/views.py
# class ImageViewSet(viewsets.ModelViewSet):
# class VideoViewSet(viewsets.ModelViewSet):
# class AudioViewSet(viewsets.ModelViewSet):
# class ReviewFilter(django_filters.FilterSet):
# class Meta:
# class ReviewViewSet(viewsets.ModelViewSet):
# class PollViewSet(viewsets.ModelViewSet):
# class PollChoiceViewSet(viewsets.ModelViewSet):
#
# Path: authors/views.py
# class AuthorViewSet(viewsets.ModelViewSet):
# class OrganizationViewSet(viewsets.ModelViewSet):
# class PositionViewSet(viewsets.ModelViewSet):
#
# Path: comments/views.py
# class InternalCommentFilter(django_filters.FilterSet):
# class Meta:
# class InternalCommentViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
#
# Path: core/views.py
# class SchemaViewSet(viewsets.ViewSet):
# class StatusViewSet(viewsets.ModelViewSet):
# class StoryFilter(django_filters.FilterSet):
# class Meta:
# class StoryViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# class PageViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# def list(self, request):
# def get_queryset(self):
#
# Path: display/views.py
# class CardSizeViewSet(viewsets.ModelViewSet):
# class StylesheetViewSet(viewsets.ModelViewSet):
# class ScriptViewSet(viewsets.ModelViewSet):
# class TemplateViewSet(viewsets.ModelViewSet):
#
# Path: organization/views.py
# class SectionViewSet(viewsets.ModelViewSet):
# class TagViewSet(viewsets.ModelViewSet):
# class SiteViewSet(viewsets.ModelViewSet):
#
# Path: requests/views.py
# class PhotoRequestFilter(django_filters.FilterSet):
# class Meta:
# class PhotoRequestViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# class GraphicRequestViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
# class IllustrationRequestViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
#
# Path: sports/views.py
# class SportViewSet(viewsets.ModelViewSet):
# class SchoolViewSet(viewsets.ModelViewSet):
# class GameFilter(django_filters.FilterSet):
# class Meta:
# class GameViewSet(viewsets.ModelViewSet):
. Output only the next line. | router.register(r'sections', organization_views.SectionViewSet) |
Predict the next line after this snippet: <|code_start|>router.register(r'reviews', attachments_views.ReviewViewSet)
router.register(r'polls', attachments_views.PollViewSet)
router.register(r'poll_choices', attachments_views.PollChoiceViewSet)
# authors
router.register(r'authors', authors_views.AuthorViewSet)
router.register(r'organizations', authors_views.OrganizationViewSet)
router.register(r'positions', authors_views.PositionViewSet)
# comments
router.register(r'internal_comments', comments_views.InternalCommentViewSet)
# core
router.register(r'schema', core_views.SchemaViewSet, base_name='schema')
router.register(r'statuses', core_views.StatusViewSet)
router.register(r'stories', core_views.StoryViewSet)
router.register(r'pages', core_views.PageViewSet)
# display
router.register(r'card_sizes', display_views.CardSizeViewSet)
router.register(r'stylesheets', display_views.StylesheetViewSet)
router.register(r'scripts', display_views.ScriptViewSet)
router.register(r'templates', display_views.TemplateViewSet)
# organization
router.register(r'sections', organization_views.SectionViewSet)
router.register(r'tags', organization_views.TagViewSet)
router.register(r'sites', organization_views.SiteViewSet)
# requests
<|code_end|>
using the current file's imports:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from rest_framework import routers
from rest_framework.authtoken import views as rest_framework_views
from rest_framework_swagger.views import get_swagger_view
from access import views as access_views
from attachments import views as attachments_views
from authors import views as authors_views
from comments import views as comments_views
from core import views as core_views
from display import views as display_views
from organization import views as organization_views
from requests import views as requests_views
from sports import views as sports_views
and any relevant context from other files:
# Path: access/views.py
# class UserFilter(django_filters.FilterSet):
# class Meta:
# class UserViewSet(viewsets.ModelViewSet):
# class GroupViewSet(viewsets.ModelViewSet):
# class PermissionViewSet(viewsets.ModelViewSet):
#
# Path: attachments/views.py
# class ImageViewSet(viewsets.ModelViewSet):
# class VideoViewSet(viewsets.ModelViewSet):
# class AudioViewSet(viewsets.ModelViewSet):
# class ReviewFilter(django_filters.FilterSet):
# class Meta:
# class ReviewViewSet(viewsets.ModelViewSet):
# class PollViewSet(viewsets.ModelViewSet):
# class PollChoiceViewSet(viewsets.ModelViewSet):
#
# Path: authors/views.py
# class AuthorViewSet(viewsets.ModelViewSet):
# class OrganizationViewSet(viewsets.ModelViewSet):
# class PositionViewSet(viewsets.ModelViewSet):
#
# Path: comments/views.py
# class InternalCommentFilter(django_filters.FilterSet):
# class Meta:
# class InternalCommentViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
#
# Path: core/views.py
# class SchemaViewSet(viewsets.ViewSet):
# class StatusViewSet(viewsets.ModelViewSet):
# class StoryFilter(django_filters.FilterSet):
# class Meta:
# class StoryViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# class PageViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# def list(self, request):
# def get_queryset(self):
#
# Path: display/views.py
# class CardSizeViewSet(viewsets.ModelViewSet):
# class StylesheetViewSet(viewsets.ModelViewSet):
# class ScriptViewSet(viewsets.ModelViewSet):
# class TemplateViewSet(viewsets.ModelViewSet):
#
# Path: organization/views.py
# class SectionViewSet(viewsets.ModelViewSet):
# class TagViewSet(viewsets.ModelViewSet):
# class SiteViewSet(viewsets.ModelViewSet):
#
# Path: requests/views.py
# class PhotoRequestFilter(django_filters.FilterSet):
# class Meta:
# class PhotoRequestViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# class GraphicRequestViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
# class IllustrationRequestViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
#
# Path: sports/views.py
# class SportViewSet(viewsets.ModelViewSet):
# class SchoolViewSet(viewsets.ModelViewSet):
# class GameFilter(django_filters.FilterSet):
# class Meta:
# class GameViewSet(viewsets.ModelViewSet):
. Output only the next line. | router.register(r'photo_requests', requests_views.PhotoRequestViewSet) |
Given snippet: <|code_start|>router.register(r'organizations', authors_views.OrganizationViewSet)
router.register(r'positions', authors_views.PositionViewSet)
# comments
router.register(r'internal_comments', comments_views.InternalCommentViewSet)
# core
router.register(r'schema', core_views.SchemaViewSet, base_name='schema')
router.register(r'statuses', core_views.StatusViewSet)
router.register(r'stories', core_views.StoryViewSet)
router.register(r'pages', core_views.PageViewSet)
# display
router.register(r'card_sizes', display_views.CardSizeViewSet)
router.register(r'stylesheets', display_views.StylesheetViewSet)
router.register(r'scripts', display_views.ScriptViewSet)
router.register(r'templates', display_views.TemplateViewSet)
# organization
router.register(r'sections', organization_views.SectionViewSet)
router.register(r'tags', organization_views.TagViewSet)
router.register(r'sites', organization_views.SiteViewSet)
# requests
router.register(r'photo_requests', requests_views.PhotoRequestViewSet)
router.register(r'graphic_requests', requests_views.GraphicRequestViewSet)
router.register(r'illustration_requests',
requests_views.IllustrationRequestViewSet)
# sports
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from rest_framework import routers
from rest_framework.authtoken import views as rest_framework_views
from rest_framework_swagger.views import get_swagger_view
from access import views as access_views
from attachments import views as attachments_views
from authors import views as authors_views
from comments import views as comments_views
from core import views as core_views
from display import views as display_views
from organization import views as organization_views
from requests import views as requests_views
from sports import views as sports_views
and context:
# Path: access/views.py
# class UserFilter(django_filters.FilterSet):
# class Meta:
# class UserViewSet(viewsets.ModelViewSet):
# class GroupViewSet(viewsets.ModelViewSet):
# class PermissionViewSet(viewsets.ModelViewSet):
#
# Path: attachments/views.py
# class ImageViewSet(viewsets.ModelViewSet):
# class VideoViewSet(viewsets.ModelViewSet):
# class AudioViewSet(viewsets.ModelViewSet):
# class ReviewFilter(django_filters.FilterSet):
# class Meta:
# class ReviewViewSet(viewsets.ModelViewSet):
# class PollViewSet(viewsets.ModelViewSet):
# class PollChoiceViewSet(viewsets.ModelViewSet):
#
# Path: authors/views.py
# class AuthorViewSet(viewsets.ModelViewSet):
# class OrganizationViewSet(viewsets.ModelViewSet):
# class PositionViewSet(viewsets.ModelViewSet):
#
# Path: comments/views.py
# class InternalCommentFilter(django_filters.FilterSet):
# class Meta:
# class InternalCommentViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
#
# Path: core/views.py
# class SchemaViewSet(viewsets.ViewSet):
# class StatusViewSet(viewsets.ModelViewSet):
# class StoryFilter(django_filters.FilterSet):
# class Meta:
# class StoryViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# class PageViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# def list(self, request):
# def get_queryset(self):
#
# Path: display/views.py
# class CardSizeViewSet(viewsets.ModelViewSet):
# class StylesheetViewSet(viewsets.ModelViewSet):
# class ScriptViewSet(viewsets.ModelViewSet):
# class TemplateViewSet(viewsets.ModelViewSet):
#
# Path: organization/views.py
# class SectionViewSet(viewsets.ModelViewSet):
# class TagViewSet(viewsets.ModelViewSet):
# class SiteViewSet(viewsets.ModelViewSet):
#
# Path: requests/views.py
# class PhotoRequestFilter(django_filters.FilterSet):
# class Meta:
# class PhotoRequestViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
# class GraphicRequestViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
# class IllustrationRequestViewSet(VersionableModelViewSetMixin,
# viewsets.ModelViewSet):
#
# Path: sports/views.py
# class SportViewSet(viewsets.ModelViewSet):
# class SchoolViewSet(viewsets.ModelViewSet):
# class GameFilter(django_filters.FilterSet):
# class Meta:
# class GameViewSet(viewsets.ModelViewSet):
which might include code, classes, or functions. Output only the next line. | router.register(r'sports', sports_views.SportViewSet) |
Predict the next line for this snippet: <|code_start|> """
permission_classes = (permissions.IsAuthenticated,)
@method_decorator(cache_page(60*60)) # cache view for one hour
def list(self, request):
return Response(serializers.schema_serializer(request))
class StatusViewSet(viewsets.ModelViewSet):
queryset = models.Status.objects.all()
serializer_class = serializers.StatusSerializer
filter_fields = ()
search_fields = ('name',)
ordering_fields = "__all__"
class StoryFilter(django_filters.FilterSet):
class Meta:
model = models.Story
fields = {'status': ['exact', 'lt', 'gt'],
'authors': ['exact'],
'position': ['exact', 'lt', 'gt'],
'sections': ['exact'],
'tags': ['exact'],
'sites': ['exact'],
'publish_time': ['exact', 'lt', 'gt']
}
<|code_end|>
with the help of current file imports:
import json
import django_filters
from rest_framework import viewsets, permissions
from rest_framework.response import Response
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from revisions.views import VersionableModelViewSetMixin
from . import serializers
from . import models
and context from other files:
# Path: revisions/views.py
# class VersionableModelViewSetMixin(viewsets.ModelViewSet):
# """Provides routes to versioned models for listing revisions and reverting
# to them.
#
# Include this mixin on ModelViewSets which have their revision history
# tracked with django-reversion. It provides two endpoints:
#
# 1. "/revisions" (method: GET) - append to a detail view URL (e.g.
# "/v1/stories/24/revisions") to view a list of revisions associated with
# this object.
# 2. "/revert" (method: PUT) - append to a detail view URL (e.g.
# "/v1/stories/24/revert") and provide payload data in the format
# "revision: <revision_id>", where revision_id is the id of the revision
# associated with this object to which you want to revert this object.
# On success, will return HTTP 200 and JSON string of the object's fields
# at the specified revision. If no revision id is provided or an invalid
# revision id is provided (revision doesn't exist or revision is not
# associated with this object), a 404 error will be returned.
#
# Associated Django Rest Framework implementation docs:
# http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing
# """
#
# @detail_route(methods=['get'])
# def revisions(self, request, pk=None):
# object = self.get_object()
# versions = reversion.get_for_object(object)
# version_serializer = serializers.VersionSerializer(versions, many=True)
# return Response(version_serializer.data)
#
# @detail_route(methods=['put'])
# def revert(self, request, pk=None):
# object = self.get_object()
# version = get_object_or_404(Version, object_id=object.id,
# id=request.data.get('revision'))
# # http://django-reversion.readthedocs.org/en/release-1.8.1/api.html#reverting-to-previous-revisions
# version.revert()
# return Response(version.field_dict)
, which may contain function names, class names, or code. Output only the next line. | class StoryViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet): |
Given the code snippet: <|code_start|>class PositionSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Position
fields = "__all__"
class JobSerializer(serializers.HyperlinkedModelSerializer):
position = PositionSerializer()
is_current = serializers.SerializerMethodField()
def get_is_current(self, obj):
return obj.is_current()
class Meta:
model = models.Job
exclude = ('author', 'url')
class AuthorSerializer(serializers.HyperlinkedModelSerializer):
organization = OrganizationSerializer()
positions = JobSerializer(source='job_set', many=True)
class Meta:
model = models.Author
exclude = ('user',)
def __init__(self, *args, **kwargs):
super(AuthorSerializer, self).__init__(*args, **kwargs)
request = self.context.get('request')
if request and request.user.is_authenticated():
<|code_end|>
, generate the next line using the imports in this file:
from rest_framework import serializers
from access import serializers as access_serializers
from . import models
and context (functions, classes, or occasionally code) from other files:
# Path: access/serializers.py
# class PermissionSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class GroupSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class UserSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
. Output only the next line. | self.fields['user'] = access_serializers.UserSerializer() |
Predict the next line after this snippet: <|code_start|>
class Media(models.Model):
"""A piece of content which has a main component and may have associated
Authors and a caption."""
caption = models.TextField(blank=True)
@property
def credit(self):
"""Forces child classes to define a "credit" attribute."""
raise NotImplementedError('Models which inherit from this class must '
'define a "credit" attribute which is a '
'ManyToManyField of authors.Author.')
def is_courtesy(self):
"""Checks if this Media is courtesy of another organization.
Returns True if any of the Authors of the Media is not a member of
this organization."""
<|code_end|>
using the current file's imports:
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.validators import MaxValueValidator
from sorl.thumbnail import get_thumbnail
from authors.models import Organization
and any relevant context from other files:
# Path: authors/models.py
# class Organization(models.Model):
# """A group of people under a single name."""
#
# name = models.CharField(max_length=64)
#
# def __str__(self):
# return self.name
. Output only the next line. | this_organization = Organization.objects.get(pk=1) |
Predict the next line after this snippet: <|code_start|>
class InternalCommentFilter(django_filters.FilterSet):
class Meta:
model = models.InternalComment
fields = {'user': ['exact'],
'time_posted': ['exact', 'lt', 'gt'],
'content_type': ['exact'],
'object_id': ['exact']
}
<|code_end|>
using the current file's imports:
import django_filters
from rest_framework import viewsets
from revisions.views import VersionableModelViewSetMixin
from . import serializers
from . import models
and any relevant context from other files:
# Path: revisions/views.py
# class VersionableModelViewSetMixin(viewsets.ModelViewSet):
# """Provides routes to versioned models for listing revisions and reverting
# to them.
#
# Include this mixin on ModelViewSets which have their revision history
# tracked with django-reversion. It provides two endpoints:
#
# 1. "/revisions" (method: GET) - append to a detail view URL (e.g.
# "/v1/stories/24/revisions") to view a list of revisions associated with
# this object.
# 2. "/revert" (method: PUT) - append to a detail view URL (e.g.
# "/v1/stories/24/revert") and provide payload data in the format
# "revision: <revision_id>", where revision_id is the id of the revision
# associated with this object to which you want to revert this object.
# On success, will return HTTP 200 and JSON string of the object's fields
# at the specified revision. If no revision id is provided or an invalid
# revision id is provided (revision doesn't exist or revision is not
# associated with this object), a 404 error will be returned.
#
# Associated Django Rest Framework implementation docs:
# http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing
# """
#
# @detail_route(methods=['get'])
# def revisions(self, request, pk=None):
# object = self.get_object()
# versions = reversion.get_for_object(object)
# version_serializer = serializers.VersionSerializer(versions, many=True)
# return Response(version_serializer.data)
#
# @detail_route(methods=['put'])
# def revert(self, request, pk=None):
# object = self.get_object()
# version = get_object_or_404(Version, object_id=object.id,
# id=request.data.get('revision'))
# # http://django-reversion.readthedocs.org/en/release-1.8.1/api.html#reverting-to-previous-revisions
# version.revert()
# return Response(version.field_dict)
. Output only the next line. | class InternalCommentViewSet(VersionableModelViewSetMixin, |
Given snippet: <|code_start|>
class BodyTextSerializer(serializers.HyperlinkedModelSerializer):
"""Abstract base class which strips internal comments from an object's
'body' field and adds a 'body_unsanitized' field for authenticated users.
"""
body = serializers.SerializerMethodField()
def __init__(self, *args, **kwargs):
super(BodyTextSerializer, self).__init__(*args, **kwargs)
request = self.context.get('request')
if request and request.user.is_authenticated():
# sometimes a serializer is initialized without a request, so we
# must check for its existence first
self.fields['body_unsanitized'] = serializers.\
SerializerMethodField()
def get_body(self, obj):
return utils.strip_internal_comments(obj.body)
def get_body_unsanitized(self, obj):
return obj.body
class StorySerializer(BodyTextSerializer):
authors = authors_serializers.AuthorSerializer(many=True)
alternate_template = display_serializers.TemplateSerializer()
sections = organization_serializers.SectionSerializer(many=True)
tags = organization_serializers.TagSerializer(many=True)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import inspect
from rest_framework import serializers
from django.db.models.fields import Field
from django.contrib.contenttypes.models import ContentType
from attachments import serializers as attachments_serializers
from authors import serializers as authors_serializers
from display import serializers as display_serializers
from organization import serializers as organization_serializers
from sports import serializers as sports_serializers
from . import models
from . import utils
and context:
# Path: attachments/serializers.py
# class MediaSerializer(serializers.HyperlinkedModelSerializer):
# class ImageSerializer(MediaSerializer):
# class Meta:
# class VideoSerializer(MediaSerializer):
# class Meta:
# class AudioSerializer(MediaSerializer):
# class Meta:
# class ReviewSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class PollChoiceSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class PollSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# def get_is_courtesy(self, obj):
# def get_resized(self, obj):
# def get_art_request(self, obj):
#
# Path: authors/serializers.py
# class OrganizationSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class PositionSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class JobSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class AuthorSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# def get_is_current(self, obj):
# def __init__(self, *args, **kwargs):
#
# Path: display/serializers.py
# class CardSizeSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class StylesheetSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class ScriptSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class TemplateSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
#
# Path: organization/serializers.py
# class SectionSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class TagSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class SiteSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
#
# Path: sports/serializers.py
# class SportSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class SchoolSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class GameSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
which might include code, classes, or functions. Output only the next line. | card = attachments_serializers.ImageSerializer() |
Based on the snippet: <|code_start|>class StatusSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Status
fields = "__all__"
class BodyTextSerializer(serializers.HyperlinkedModelSerializer):
"""Abstract base class which strips internal comments from an object's
'body' field and adds a 'body_unsanitized' field for authenticated users.
"""
body = serializers.SerializerMethodField()
def __init__(self, *args, **kwargs):
super(BodyTextSerializer, self).__init__(*args, **kwargs)
request = self.context.get('request')
if request and request.user.is_authenticated():
# sometimes a serializer is initialized without a request, so we
# must check for its existence first
self.fields['body_unsanitized'] = serializers.\
SerializerMethodField()
def get_body(self, obj):
return utils.strip_internal_comments(obj.body)
def get_body_unsanitized(self, obj):
return obj.body
class StorySerializer(BodyTextSerializer):
<|code_end|>
, predict the immediate next line with the help of imports:
import inspect
from rest_framework import serializers
from django.db.models.fields import Field
from django.contrib.contenttypes.models import ContentType
from attachments import serializers as attachments_serializers
from authors import serializers as authors_serializers
from display import serializers as display_serializers
from organization import serializers as organization_serializers
from sports import serializers as sports_serializers
from . import models
from . import utils
and context (classes, functions, sometimes code) from other files:
# Path: attachments/serializers.py
# class MediaSerializer(serializers.HyperlinkedModelSerializer):
# class ImageSerializer(MediaSerializer):
# class Meta:
# class VideoSerializer(MediaSerializer):
# class Meta:
# class AudioSerializer(MediaSerializer):
# class Meta:
# class ReviewSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class PollChoiceSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class PollSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# def get_is_courtesy(self, obj):
# def get_resized(self, obj):
# def get_art_request(self, obj):
#
# Path: authors/serializers.py
# class OrganizationSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class PositionSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class JobSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class AuthorSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# def get_is_current(self, obj):
# def __init__(self, *args, **kwargs):
#
# Path: display/serializers.py
# class CardSizeSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class StylesheetSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class ScriptSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class TemplateSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
#
# Path: organization/serializers.py
# class SectionSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class TagSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class SiteSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
#
# Path: sports/serializers.py
# class SportSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class SchoolSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class GameSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
. Output only the next line. | authors = authors_serializers.AuthorSerializer(many=True) |
Given the following code snippet before the placeholder: <|code_start|> class Meta:
model = models.Status
fields = "__all__"
class BodyTextSerializer(serializers.HyperlinkedModelSerializer):
"""Abstract base class which strips internal comments from an object's
'body' field and adds a 'body_unsanitized' field for authenticated users.
"""
body = serializers.SerializerMethodField()
def __init__(self, *args, **kwargs):
super(BodyTextSerializer, self).__init__(*args, **kwargs)
request = self.context.get('request')
if request and request.user.is_authenticated():
# sometimes a serializer is initialized without a request, so we
# must check for its existence first
self.fields['body_unsanitized'] = serializers.\
SerializerMethodField()
def get_body(self, obj):
return utils.strip_internal_comments(obj.body)
def get_body_unsanitized(self, obj):
return obj.body
class StorySerializer(BodyTextSerializer):
authors = authors_serializers.AuthorSerializer(many=True)
<|code_end|>
, predict the next line using imports from the current file:
import inspect
from rest_framework import serializers
from django.db.models.fields import Field
from django.contrib.contenttypes.models import ContentType
from attachments import serializers as attachments_serializers
from authors import serializers as authors_serializers
from display import serializers as display_serializers
from organization import serializers as organization_serializers
from sports import serializers as sports_serializers
from . import models
from . import utils
and context including class names, function names, and sometimes code from other files:
# Path: attachments/serializers.py
# class MediaSerializer(serializers.HyperlinkedModelSerializer):
# class ImageSerializer(MediaSerializer):
# class Meta:
# class VideoSerializer(MediaSerializer):
# class Meta:
# class AudioSerializer(MediaSerializer):
# class Meta:
# class ReviewSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class PollChoiceSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class PollSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# def get_is_courtesy(self, obj):
# def get_resized(self, obj):
# def get_art_request(self, obj):
#
# Path: authors/serializers.py
# class OrganizationSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class PositionSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class JobSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class AuthorSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# def get_is_current(self, obj):
# def __init__(self, *args, **kwargs):
#
# Path: display/serializers.py
# class CardSizeSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class StylesheetSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class ScriptSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class TemplateSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
#
# Path: organization/serializers.py
# class SectionSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class TagSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class SiteSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
#
# Path: sports/serializers.py
# class SportSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class SchoolSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class GameSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
. Output only the next line. | alternate_template = display_serializers.TemplateSerializer() |
Using the snippet: <|code_start|> model = models.Status
fields = "__all__"
class BodyTextSerializer(serializers.HyperlinkedModelSerializer):
"""Abstract base class which strips internal comments from an object's
'body' field and adds a 'body_unsanitized' field for authenticated users.
"""
body = serializers.SerializerMethodField()
def __init__(self, *args, **kwargs):
super(BodyTextSerializer, self).__init__(*args, **kwargs)
request = self.context.get('request')
if request and request.user.is_authenticated():
# sometimes a serializer is initialized without a request, so we
# must check for its existence first
self.fields['body_unsanitized'] = serializers.\
SerializerMethodField()
def get_body(self, obj):
return utils.strip_internal_comments(obj.body)
def get_body_unsanitized(self, obj):
return obj.body
class StorySerializer(BodyTextSerializer):
authors = authors_serializers.AuthorSerializer(many=True)
alternate_template = display_serializers.TemplateSerializer()
<|code_end|>
, determine the next line of code. You have imports:
import inspect
from rest_framework import serializers
from django.db.models.fields import Field
from django.contrib.contenttypes.models import ContentType
from attachments import serializers as attachments_serializers
from authors import serializers as authors_serializers
from display import serializers as display_serializers
from organization import serializers as organization_serializers
from sports import serializers as sports_serializers
from . import models
from . import utils
and context (class names, function names, or code) available:
# Path: attachments/serializers.py
# class MediaSerializer(serializers.HyperlinkedModelSerializer):
# class ImageSerializer(MediaSerializer):
# class Meta:
# class VideoSerializer(MediaSerializer):
# class Meta:
# class AudioSerializer(MediaSerializer):
# class Meta:
# class ReviewSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class PollChoiceSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class PollSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# def get_is_courtesy(self, obj):
# def get_resized(self, obj):
# def get_art_request(self, obj):
#
# Path: authors/serializers.py
# class OrganizationSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class PositionSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class JobSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class AuthorSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# def get_is_current(self, obj):
# def __init__(self, *args, **kwargs):
#
# Path: display/serializers.py
# class CardSizeSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class StylesheetSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class ScriptSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class TemplateSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
#
# Path: organization/serializers.py
# class SectionSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class TagSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class SiteSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
#
# Path: sports/serializers.py
# class SportSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class SchoolSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class GameSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
. Output only the next line. | sections = organization_serializers.SectionSerializer(many=True) |
Using the snippet: <|code_start|> body = serializers.SerializerMethodField()
def __init__(self, *args, **kwargs):
super(BodyTextSerializer, self).__init__(*args, **kwargs)
request = self.context.get('request')
if request and request.user.is_authenticated():
# sometimes a serializer is initialized without a request, so we
# must check for its existence first
self.fields['body_unsanitized'] = serializers.\
SerializerMethodField()
def get_body(self, obj):
return utils.strip_internal_comments(obj.body)
def get_body_unsanitized(self, obj):
return obj.body
class StorySerializer(BodyTextSerializer):
authors = authors_serializers.AuthorSerializer(many=True)
alternate_template = display_serializers.TemplateSerializer()
sections = organization_serializers.SectionSerializer(many=True)
tags = organization_serializers.TagSerializer(many=True)
card = attachments_serializers.ImageSerializer()
card_size = display_serializers.CardSizeSerializer()
featured_image = attachments_serializers.ImageSerializer()
featured_video = attachments_serializers.VideoSerializer()
featured_audio = attachments_serializers.AudioSerializer()
review = attachments_serializers.ReviewSerializer()
poll = attachments_serializers.PollSerializer()
<|code_end|>
, determine the next line of code. You have imports:
import inspect
from rest_framework import serializers
from django.db.models.fields import Field
from django.contrib.contenttypes.models import ContentType
from attachments import serializers as attachments_serializers
from authors import serializers as authors_serializers
from display import serializers as display_serializers
from organization import serializers as organization_serializers
from sports import serializers as sports_serializers
from . import models
from . import utils
and context (class names, function names, or code) available:
# Path: attachments/serializers.py
# class MediaSerializer(serializers.HyperlinkedModelSerializer):
# class ImageSerializer(MediaSerializer):
# class Meta:
# class VideoSerializer(MediaSerializer):
# class Meta:
# class AudioSerializer(MediaSerializer):
# class Meta:
# class ReviewSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class PollChoiceSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class PollSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# def get_is_courtesy(self, obj):
# def get_resized(self, obj):
# def get_art_request(self, obj):
#
# Path: authors/serializers.py
# class OrganizationSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class PositionSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class JobSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class AuthorSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# def get_is_current(self, obj):
# def __init__(self, *args, **kwargs):
#
# Path: display/serializers.py
# class CardSizeSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class StylesheetSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class ScriptSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class TemplateSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
#
# Path: organization/serializers.py
# class SectionSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class TagSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class SiteSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
#
# Path: sports/serializers.py
# class SportSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class SchoolSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
# class GameSerializer(serializers.HyperlinkedModelSerializer):
# class Meta:
. Output only the next line. | game = sports_serializers.GameSerializer() |
Predict the next line for this snippet: <|code_start|>
class ArtRequest(models.Model):
"""A request for a piece of art to accompany a Story."""
story = models.ForeignKey('core.Story')
assignees = models.ManyToManyField('authors.Author', blank=True)
instructions = models.TextField(blank=True)
<|code_end|>
with the help of current file imports:
from django.db import models
from django.contrib.contenttypes.fields import GenericRelation
from attachments import models as attachments_models
and context from other files:
# Path: attachments/models.py
# class Media(models.Model):
# class Meta:
# class Image(Media):
# class Video(Media):
# class Audio(Media):
# class Meta:
# class Review(models.Model):
# class Poll(models.Model):
# class PollChoice(models.Model):
# def credit(self):
# def is_courtesy(self):
# def get_image_at_resolution(self, resolution, crop='center', quality=90):
# def aspect_ratio(self):
# def __str__(self):
# def __str__(self):
# def __str__(self):
# def __str__(self):
# def __str__(self):
# def __str__(self):
, which may contain function names, class names, or code. Output only the next line. | images = GenericRelation(attachments_models.Image) |
Using the snippet: <|code_start|> if f not in article["nlp"]:
task.log(logging.WARNING, f"Cannot find field {f} in the document {article['_id']}")
continue
if "tokens" not in article["nlp"][f]:
task.log(
logging.WARNING,
f"Cannot find tokenized version of field {f} in the document {article['_id']}",
)
continue
for s in article["nlp"][f]["tokens"].split("\n"):
# ignoring default model tokenizer in order to use whitespace tokenizer
tok_sent = Sentence()
for w in s.split(" "):
tok_sent.addWord(w)
sent_lemmas = []
sent_postags = []
sent_features = []
model.tag(tok_sent)
for w in tok_sent.words[1:]:
poses.update([w.upostag])
sent_lemmas.append(w.lemma)
# Again, not moving that to a separate function to
# reduce number of unnecessary calls
try:
<|code_end|>
, determine the next line of code. You have imports:
import logging
import bz2
import lzma
import os.path
import pathlib
import csv
import pymongo
from collections import defaultdict, Counter
from typing import TextIO
from django.conf import settings
from django_task.job import Job
from .ud_converter import COMPRESS_UPOS_MAPPING, compress_features, decompress
from .models import ExportCorpusTask, _CORPORA_CHOICES
from .mongodb import get_db
from .mongodb import get_db
from .udpipe_model import Model as UDPipeModel
from ufal.udpipe import Sentence # type: ignore
from .mongodb import get_db
and context (class names, function names, or code) available:
# Path: languk/corpus/ud_converter.py
# COMPRESS_UPOS_MAPPING = dict(_UPOS_MAPPING)
#
# def compress_features(feats):
# res = ""
# for pair in feats.split("|"):
# if not pair:
# continue
# cat, val = pair.split("=")
#
# try:
# c_cat = COMPRESS_FEATURES_MAPPING[cat]
# except KeyError:
# logger.warning(f"Cannot find the feature '{cat}' in the mapping, skipping it for now")
# continue
#
# try:
# c_val = COMPRESS_FEATURE_VALUES_MAPPING[cat][val]
# except KeyError:
# logger.warning(f"Cannot find the value '{val}' for the feature '{cat}' in the mapping, skipping it for now")
# continue
#
# res += c_cat + c_val
#
# return res
#
# def decompress(tokens: str=None, ud_lemmas: str=None, ud_features: str=None, ud_postags: str=None) -> List[OrderedDict]:
# params = locals()
#
# assert any(
# map(lambda x: x is not None, params.values())
# ), "at least one param should be not None"
#
# zipped: dict = {}
#
# for param_name, param_value in params.items():
# if param_value is not None:
# # if param_name == "tokens":
# # # TODO: validate if this workaround can be properly fixed
# # param_value = param_value.strip()
# zipped[param_name] = unpack_values(param_name, param_value)
#
#
# sentences_length: set = set(map(len, zipped.values()))
# assert len(sentences_length) == 1, f"Text contains different number of sentences: {sentences_length}"
#
# res: list = []
# param_names: list[str] = list(zipped.keys())
# param_values: list[str] = list(zipped.values())
#
# for sent in zip(*param_values):
# word_length:set = set(map(len, sent))
#
# assert len(sentences_length) == 1, f"Text contains different number of words in sentence: {sent}"
#
# res.append(
# [OrderedDict(zip(param_names, word_info)) for word_info in zip(*sent)]
# )
#
#
# return res
#
# Path: languk/corpus/models.py
# class ExportCorpusTask(TaskRQ):
# file_format = models.CharField(
# max_length=5, null=False, blank=False, default="txt", choices=(("txt", "Text File"),)
# )
# file_compression = models.CharField(
# max_length=5,
# null=False,
# blank=False,
# default="none",
# choices=(
# ("none", "No compression"),
# ("bz2", "Bzip2"),
# ("lzma", "LZMA"),
# ),
# )
#
# corpora = ChoiceArrayField(
# models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=_CORPORA_CHOICES,
# ),
# blank=False,
# )
#
# filtering = ChoiceArrayField(
# models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=_FILTERING_CHOICES,
# ),
# blank=True,
# )
#
# processing = models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=(
# ("orig", "Original texts in markdown format"),
# ("tokens", "Tokenized by NLP-UK lib"),
# ("lemmas", "Lemmatized by NLP-UK lib"),
# ),
# )
#
# TASK_QUEUE = settings.QUEUE_DEFAULT
#
# DEFAULT_VERBOSITY = 2
# TASK_TIMEOUT = 0
# LOG_TO_FIELD = True
# LOG_TO_FILE = False
#
# @staticmethod
# def get_jobclass():
# from .jobs import ExportCorpusJob
#
# return ExportCorpusJob
#
# _CORPORA_CHOICES: Tuple[Tuple[str, str]] = (
# ("news", "News and magazines"),
# ("wikipedia", "Ukrainian Wikipedia"),
# ("fiction", "Fiction"),
# ("court", "Sampled court decisions"),
# ("laws", "Laws and bylaws"),
# )
. Output only the next line. | sent_postags.append(COMPRESS_UPOS_MAPPING[w.upostag]) |
Predict the next line for this snippet: <|code_start|> )
continue
for s in article["nlp"][f]["tokens"].split("\n"):
# ignoring default model tokenizer in order to use whitespace tokenizer
tok_sent = Sentence()
for w in s.split(" "):
tok_sent.addWord(w)
sent_lemmas = []
sent_postags = []
sent_features = []
model.tag(tok_sent)
for w in tok_sent.words[1:]:
poses.update([w.upostag])
sent_lemmas.append(w.lemma)
# Again, not moving that to a separate function to
# reduce number of unnecessary calls
try:
sent_postags.append(COMPRESS_UPOS_MAPPING[w.upostag])
except KeyError:
task.log(
logging.WARNING,
f"Cannot find {w.upostag} in the COMPRESS_UPOS_MAPPING, skipping for now",
)
sent_postags.append("Z")
<|code_end|>
with the help of current file imports:
import logging
import bz2
import lzma
import os.path
import pathlib
import csv
import pymongo
from collections import defaultdict, Counter
from typing import TextIO
from django.conf import settings
from django_task.job import Job
from .ud_converter import COMPRESS_UPOS_MAPPING, compress_features, decompress
from .models import ExportCorpusTask, _CORPORA_CHOICES
from .mongodb import get_db
from .mongodb import get_db
from .udpipe_model import Model as UDPipeModel
from ufal.udpipe import Sentence # type: ignore
from .mongodb import get_db
and context from other files:
# Path: languk/corpus/ud_converter.py
# COMPRESS_UPOS_MAPPING = dict(_UPOS_MAPPING)
#
# def compress_features(feats):
# res = ""
# for pair in feats.split("|"):
# if not pair:
# continue
# cat, val = pair.split("=")
#
# try:
# c_cat = COMPRESS_FEATURES_MAPPING[cat]
# except KeyError:
# logger.warning(f"Cannot find the feature '{cat}' in the mapping, skipping it for now")
# continue
#
# try:
# c_val = COMPRESS_FEATURE_VALUES_MAPPING[cat][val]
# except KeyError:
# logger.warning(f"Cannot find the value '{val}' for the feature '{cat}' in the mapping, skipping it for now")
# continue
#
# res += c_cat + c_val
#
# return res
#
# def decompress(tokens: str=None, ud_lemmas: str=None, ud_features: str=None, ud_postags: str=None) -> List[OrderedDict]:
# params = locals()
#
# assert any(
# map(lambda x: x is not None, params.values())
# ), "at least one param should be not None"
#
# zipped: dict = {}
#
# for param_name, param_value in params.items():
# if param_value is not None:
# # if param_name == "tokens":
# # # TODO: validate if this workaround can be properly fixed
# # param_value = param_value.strip()
# zipped[param_name] = unpack_values(param_name, param_value)
#
#
# sentences_length: set = set(map(len, zipped.values()))
# assert len(sentences_length) == 1, f"Text contains different number of sentences: {sentences_length}"
#
# res: list = []
# param_names: list[str] = list(zipped.keys())
# param_values: list[str] = list(zipped.values())
#
# for sent in zip(*param_values):
# word_length:set = set(map(len, sent))
#
# assert len(sentences_length) == 1, f"Text contains different number of words in sentence: {sent}"
#
# res.append(
# [OrderedDict(zip(param_names, word_info)) for word_info in zip(*sent)]
# )
#
#
# return res
#
# Path: languk/corpus/models.py
# class ExportCorpusTask(TaskRQ):
# file_format = models.CharField(
# max_length=5, null=False, blank=False, default="txt", choices=(("txt", "Text File"),)
# )
# file_compression = models.CharField(
# max_length=5,
# null=False,
# blank=False,
# default="none",
# choices=(
# ("none", "No compression"),
# ("bz2", "Bzip2"),
# ("lzma", "LZMA"),
# ),
# )
#
# corpora = ChoiceArrayField(
# models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=_CORPORA_CHOICES,
# ),
# blank=False,
# )
#
# filtering = ChoiceArrayField(
# models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=_FILTERING_CHOICES,
# ),
# blank=True,
# )
#
# processing = models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=(
# ("orig", "Original texts in markdown format"),
# ("tokens", "Tokenized by NLP-UK lib"),
# ("lemmas", "Lemmatized by NLP-UK lib"),
# ),
# )
#
# TASK_QUEUE = settings.QUEUE_DEFAULT
#
# DEFAULT_VERBOSITY = 2
# TASK_TIMEOUT = 0
# LOG_TO_FIELD = True
# LOG_TO_FILE = False
#
# @staticmethod
# def get_jobclass():
# from .jobs import ExportCorpusJob
#
# return ExportCorpusJob
#
# _CORPORA_CHOICES: Tuple[Tuple[str, str]] = (
# ("news", "News and magazines"),
# ("wikipedia", "Ukrainian Wikipedia"),
# ("fiction", "Fiction"),
# ("court", "Sampled court decisions"),
# ("laws", "Laws and bylaws"),
# )
, which may contain function names, class names, or code. Output only the next line. | sent_features.append(compress_features(w.feats)) |
Given the code snippet: <|code_start|>
count_by_pos = defaultdict(Counter)
document_frequency = defaultdict(Counter)
for i, (corpus, article) in enumerate(BuildFreqVocabJob.get_iter(db, job, task)):
if BuildFreqVocabJob.apply_filter(job, task, article):
processed_articles += 1
lemmas_in_doc: set = set()
for f in ["title", "text"]:
if "nlp" not in article:
task.log(logging.WARNING, f"Cannot find field 'nlp' in the document {article['_id']}")
continue
if f not in article["nlp"]:
task.log(logging.WARNING, f"Cannot find field {f} in the document {article['_id']}")
continue
if "ud_lemmas" not in article["nlp"][f]:
task.log(
logging.WARNING,
f"Cannot find lemmatized version of field {f} in the document {article['_id']}",
)
continue
if "ud_postags" not in article["nlp"][f]:
task.log(
logging.WARNING, f"Cannot find udpipe postags of field {f} in the document {article['_id']}"
)
continue
<|code_end|>
, generate the next line using the imports in this file:
import logging
import bz2
import lzma
import os.path
import pathlib
import csv
import pymongo
from collections import defaultdict, Counter
from typing import TextIO
from django.conf import settings
from django_task.job import Job
from .ud_converter import COMPRESS_UPOS_MAPPING, compress_features, decompress
from .models import ExportCorpusTask, _CORPORA_CHOICES
from .mongodb import get_db
from .mongodb import get_db
from .udpipe_model import Model as UDPipeModel
from ufal.udpipe import Sentence # type: ignore
from .mongodb import get_db
and context (functions, classes, or occasionally code) from other files:
# Path: languk/corpus/ud_converter.py
# COMPRESS_UPOS_MAPPING = dict(_UPOS_MAPPING)
#
# def compress_features(feats):
# res = ""
# for pair in feats.split("|"):
# if not pair:
# continue
# cat, val = pair.split("=")
#
# try:
# c_cat = COMPRESS_FEATURES_MAPPING[cat]
# except KeyError:
# logger.warning(f"Cannot find the feature '{cat}' in the mapping, skipping it for now")
# continue
#
# try:
# c_val = COMPRESS_FEATURE_VALUES_MAPPING[cat][val]
# except KeyError:
# logger.warning(f"Cannot find the value '{val}' for the feature '{cat}' in the mapping, skipping it for now")
# continue
#
# res += c_cat + c_val
#
# return res
#
# def decompress(tokens: str=None, ud_lemmas: str=None, ud_features: str=None, ud_postags: str=None) -> List[OrderedDict]:
# params = locals()
#
# assert any(
# map(lambda x: x is not None, params.values())
# ), "at least one param should be not None"
#
# zipped: dict = {}
#
# for param_name, param_value in params.items():
# if param_value is not None:
# # if param_name == "tokens":
# # # TODO: validate if this workaround can be properly fixed
# # param_value = param_value.strip()
# zipped[param_name] = unpack_values(param_name, param_value)
#
#
# sentences_length: set = set(map(len, zipped.values()))
# assert len(sentences_length) == 1, f"Text contains different number of sentences: {sentences_length}"
#
# res: list = []
# param_names: list[str] = list(zipped.keys())
# param_values: list[str] = list(zipped.values())
#
# for sent in zip(*param_values):
# word_length:set = set(map(len, sent))
#
# assert len(sentences_length) == 1, f"Text contains different number of words in sentence: {sent}"
#
# res.append(
# [OrderedDict(zip(param_names, word_info)) for word_info in zip(*sent)]
# )
#
#
# return res
#
# Path: languk/corpus/models.py
# class ExportCorpusTask(TaskRQ):
# file_format = models.CharField(
# max_length=5, null=False, blank=False, default="txt", choices=(("txt", "Text File"),)
# )
# file_compression = models.CharField(
# max_length=5,
# null=False,
# blank=False,
# default="none",
# choices=(
# ("none", "No compression"),
# ("bz2", "Bzip2"),
# ("lzma", "LZMA"),
# ),
# )
#
# corpora = ChoiceArrayField(
# models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=_CORPORA_CHOICES,
# ),
# blank=False,
# )
#
# filtering = ChoiceArrayField(
# models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=_FILTERING_CHOICES,
# ),
# blank=True,
# )
#
# processing = models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=(
# ("orig", "Original texts in markdown format"),
# ("tokens", "Tokenized by NLP-UK lib"),
# ("lemmas", "Lemmatized by NLP-UK lib"),
# ),
# )
#
# TASK_QUEUE = settings.QUEUE_DEFAULT
#
# DEFAULT_VERBOSITY = 2
# TASK_TIMEOUT = 0
# LOG_TO_FIELD = True
# LOG_TO_FILE = False
#
# @staticmethod
# def get_jobclass():
# from .jobs import ExportCorpusJob
#
# return ExportCorpusJob
#
# _CORPORA_CHOICES: Tuple[Tuple[str, str]] = (
# ("news", "News and magazines"),
# ("wikipedia", "Ukrainian Wikipedia"),
# ("fiction", "Fiction"),
# ("court", "Sampled court decisions"),
# ("laws", "Laws and bylaws"),
# )
. Output only the next line. | decompressed_result = decompress( |
Based on the snippet: <|code_start|>
class BaseCorpusTask(Job):
@staticmethod
def get_total_count(db, job, task) -> int:
total = 0
for corpus in task.corpora:
total += db[corpus].count()
return total
@staticmethod
def get_iter(db, job, task):
for corpus in task.corpora:
for article in db[corpus].find():
yield corpus, article
@staticmethod
def execute(job, task):
raise NotImplementedError()
@staticmethod
def generate_filename(
job, task, basedir: str = settings.CORPUS_EXPORT_PATH, file_prefix: str = "ubertext"
) -> pathlib.Path:
suffixes: list[tuple[str, str]] = []
if hasattr(task, "corpora"):
corpora: list[str] = sorted(task.corpora)
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import bz2
import lzma
import os.path
import pathlib
import csv
import pymongo
from collections import defaultdict, Counter
from typing import TextIO
from django.conf import settings
from django_task.job import Job
from .ud_converter import COMPRESS_UPOS_MAPPING, compress_features, decompress
from .models import ExportCorpusTask, _CORPORA_CHOICES
from .mongodb import get_db
from .mongodb import get_db
from .udpipe_model import Model as UDPipeModel
from ufal.udpipe import Sentence # type: ignore
from .mongodb import get_db
and context (classes, functions, sometimes code) from other files:
# Path: languk/corpus/ud_converter.py
# COMPRESS_UPOS_MAPPING = dict(_UPOS_MAPPING)
#
# def compress_features(feats):
# res = ""
# for pair in feats.split("|"):
# if not pair:
# continue
# cat, val = pair.split("=")
#
# try:
# c_cat = COMPRESS_FEATURES_MAPPING[cat]
# except KeyError:
# logger.warning(f"Cannot find the feature '{cat}' in the mapping, skipping it for now")
# continue
#
# try:
# c_val = COMPRESS_FEATURE_VALUES_MAPPING[cat][val]
# except KeyError:
# logger.warning(f"Cannot find the value '{val}' for the feature '{cat}' in the mapping, skipping it for now")
# continue
#
# res += c_cat + c_val
#
# return res
#
# def decompress(tokens: str=None, ud_lemmas: str=None, ud_features: str=None, ud_postags: str=None) -> List[OrderedDict]:
# params = locals()
#
# assert any(
# map(lambda x: x is not None, params.values())
# ), "at least one param should be not None"
#
# zipped: dict = {}
#
# for param_name, param_value in params.items():
# if param_value is not None:
# # if param_name == "tokens":
# # # TODO: validate if this workaround can be properly fixed
# # param_value = param_value.strip()
# zipped[param_name] = unpack_values(param_name, param_value)
#
#
# sentences_length: set = set(map(len, zipped.values()))
# assert len(sentences_length) == 1, f"Text contains different number of sentences: {sentences_length}"
#
# res: list = []
# param_names: list[str] = list(zipped.keys())
# param_values: list[str] = list(zipped.values())
#
# for sent in zip(*param_values):
# word_length:set = set(map(len, sent))
#
# assert len(sentences_length) == 1, f"Text contains different number of words in sentence: {sent}"
#
# res.append(
# [OrderedDict(zip(param_names, word_info)) for word_info in zip(*sent)]
# )
#
#
# return res
#
# Path: languk/corpus/models.py
# class ExportCorpusTask(TaskRQ):
# file_format = models.CharField(
# max_length=5, null=False, blank=False, default="txt", choices=(("txt", "Text File"),)
# )
# file_compression = models.CharField(
# max_length=5,
# null=False,
# blank=False,
# default="none",
# choices=(
# ("none", "No compression"),
# ("bz2", "Bzip2"),
# ("lzma", "LZMA"),
# ),
# )
#
# corpora = ChoiceArrayField(
# models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=_CORPORA_CHOICES,
# ),
# blank=False,
# )
#
# filtering = ChoiceArrayField(
# models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=_FILTERING_CHOICES,
# ),
# blank=True,
# )
#
# processing = models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=(
# ("orig", "Original texts in markdown format"),
# ("tokens", "Tokenized by NLP-UK lib"),
# ("lemmas", "Lemmatized by NLP-UK lib"),
# ),
# )
#
# TASK_QUEUE = settings.QUEUE_DEFAULT
#
# DEFAULT_VERBOSITY = 2
# TASK_TIMEOUT = 0
# LOG_TO_FIELD = True
# LOG_TO_FILE = False
#
# @staticmethod
# def get_jobclass():
# from .jobs import ExportCorpusJob
#
# return ExportCorpusJob
#
# _CORPORA_CHOICES: Tuple[Tuple[str, str]] = (
# ("news", "News and magazines"),
# ("wikipedia", "Ukrainian Wikipedia"),
# ("fiction", "Fiction"),
# ("court", "Sampled court decisions"),
# ("laws", "Laws and bylaws"),
# )
. Output only the next line. | if len(_CORPORA_CHOICES) == len(corpora): |
Here is a snippet: <|code_start|> if isinstance(res, list):
value = [self.base_field.to_python(val) for val in res]
return value
def validate(self, value, model_instance):
if not self.editable:
# Skip validation for non-editable fields.
return
if self.choices is not None and value not in self.empty_values:
if set(value).issubset({option_key for option_key, _ in self.choices}):
return
raise exceptions.ValidationError(
self.error_messages["invalid_choice"],
code="invalid_choice",
params={"value": value},
)
if value is None and not self.null:
raise exceptions.ValidationError(self.error_messages["null"], code="null")
if not self.blank and value in self.empty_values:
raise exceptions.ValidationError(self.error_messages["blank"], code="blank")
class Corpus:
@staticmethod
def get_sources():
grouped = defaultdict(list)
<|code_end|>
. Write the next line using the current file imports:
from collections import defaultdict
from typing import Tuple
from django import forms
from django.core import exceptions
from django.db import models
from django.contrib.postgres.fields import ArrayField
from django.conf import settings
from django_task.models import TaskRQ
from .mongodb import db
from .jobs import ExportCorpusJob
from .jobs import TagWithUDPipeJob
from .jobs import BuildFreqVocabJob
and context from other files:
# Path: languk/corpus/mongodb.py
# def with_reconnect(func):
# def _reconnector(*args, **kwargs):
# def __init__(self, collection):
# def __getattr__(self, func):
# def __repr__(self):
# def __str__(self):
# def __init__(self, database):
# def __getattr__(self, func):
# def __getitem__(self, func):
# def __repr__(self):
# def __str__(self):
# def __init__(self, connection, default=None):
# def __getattr__(self, alias):
# def __repr__(self):
# def __str__(self):
# def __init__(self, databases):
# def __getitem__(self, alias):
# def get_db():
# class ConnectionDoesNotExist(Exception):
# class CollectionWrapper(object):
# class DatabaseWrapper(object):
# class ConnectionWrapper(object):
# class MongoHandler(object):
, which may include functions, classes, or code. Output only the next line. | for source in db.corpus__sources.find(): |
Next line prediction: <|code_start|>
class CorpusHomeView(TemplateView):
template_name = "corpus/corpus_home.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
<|code_end|>
. Use current file imports:
(from django.utils.translation import gettext as _
from django.http import Http404
from django.views.generic.base import TemplateView
from .models import Corpus)
and context including class names, function names, or small code snippets from other files:
# Path: languk/corpus/models.py
# class Corpus:
# @staticmethod
# def get_sources():
# grouped = defaultdict(list)
#
# for source in db.corpus__sources.find():
# try:
# grouped[source["collection"]].append(source)
# except KeyError:
# pass
#
# return grouped
#
# @staticmethod
# def get_source(collection, _id):
#
# return db.corpus__sources.find_one({"collection": collection, "_id": _id})
#
# @staticmethod
# def get_sample(source, slug):
# if slug not in source["sampling_results"]:
# return None
#
# sample = source["sampling_results"][slug]
# samples = [i["_id"] for i in sample["ids"]]
#
# documents = list(db[source["collection"]].find({"_id": {"$in": samples}}))
# documents.sort(key=lambda doc: samples.index(doc["_id"]))
#
# sample["documents"] = documents
#
# return sample
#
# @staticmethod
# def get_article(source, article_id):
# article = db[source["collection"]].find_one({"_id": article_id})
#
# return article
. Output only the next line. | context["corpus_sources"] = Corpus.get_sources() |
Using the snippet: <|code_start|>
@admin.register(ExportCorpusTask)
class ExportCorpusTask(TaskAdmin):
pass
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib import admin
from django_task.admin import TaskAdmin
from .models import ExportCorpusTask, TagWithUDPipeTask, BuildFreqVocabTask
and context (class names, function names, or code) available:
# Path: languk/corpus/models.py
# class ExportCorpusTask(TaskRQ):
# file_format = models.CharField(
# max_length=5, null=False, blank=False, default="txt", choices=(("txt", "Text File"),)
# )
# file_compression = models.CharField(
# max_length=5,
# null=False,
# blank=False,
# default="none",
# choices=(
# ("none", "No compression"),
# ("bz2", "Bzip2"),
# ("lzma", "LZMA"),
# ),
# )
#
# corpora = ChoiceArrayField(
# models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=_CORPORA_CHOICES,
# ),
# blank=False,
# )
#
# filtering = ChoiceArrayField(
# models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=_FILTERING_CHOICES,
# ),
# blank=True,
# )
#
# processing = models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=(
# ("orig", "Original texts in markdown format"),
# ("tokens", "Tokenized by NLP-UK lib"),
# ("lemmas", "Lemmatized by NLP-UK lib"),
# ),
# )
#
# TASK_QUEUE = settings.QUEUE_DEFAULT
#
# DEFAULT_VERBOSITY = 2
# TASK_TIMEOUT = 0
# LOG_TO_FIELD = True
# LOG_TO_FILE = False
#
# @staticmethod
# def get_jobclass():
# from .jobs import ExportCorpusJob
#
# return ExportCorpusJob
#
# class TagWithUDPipeTask(TaskRQ):
# corpora = ChoiceArrayField(
# models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=_CORPORA_CHOICES,
# ),
# blank=False,
# )
#
# force = models.BooleanField(
# "Tag all texts, including already tagged",
# default=False,
# )
#
# TASK_QUEUE = settings.QUEUE_DEFAULT
#
# DEFAULT_VERBOSITY = 2
# TASK_TIMEOUT = 0
# LOG_TO_FIELD = True
# LOG_TO_FILE = False
#
# @staticmethod
# def get_jobclass():
# from .jobs import TagWithUDPipeJob
#
# return TagWithUDPipeJob
#
# class BuildFreqVocabTask(TaskRQ):
# corpora = ChoiceArrayField(
# models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=_CORPORA_CHOICES,
# ),
# blank=False,
# )
#
# filtering = ChoiceArrayField(
# models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=_FILTERING_CHOICES,
# ),
# blank=True,
# default=list
# )
#
# file_format = models.CharField(
# max_length=5, null=False, blank=False, default="csv", choices=(("csv", "CSV file"),)
# )
# file_compression = models.CharField(
# max_length=5,
# null=False,
# blank=False,
# default="none",
# choices=(
# ("none", "No compression"),
# ("bz2", "Bzip2"),
# ("lzma", "LZMA"),
# ),
# )
# TASK_QUEUE = settings.QUEUE_DEFAULT
#
# DEFAULT_VERBOSITY = 2
# TASK_TIMEOUT = 0
# LOG_TO_FIELD = True
# LOG_TO_FILE = False
#
# @staticmethod
# def get_jobclass():
# from .jobs import BuildFreqVocabJob
#
# return BuildFreqVocabJob
. Output only the next line. | @admin.register(TagWithUDPipeTask) |
Predict the next line for this snippet: <|code_start|>
@admin.register(ExportCorpusTask)
class ExportCorpusTask(TaskAdmin):
pass
@admin.register(TagWithUDPipeTask)
class TagWithUDPipeTask(TaskAdmin):
pass
<|code_end|>
with the help of current file imports:
from django.contrib import admin
from django_task.admin import TaskAdmin
from .models import ExportCorpusTask, TagWithUDPipeTask, BuildFreqVocabTask
and context from other files:
# Path: languk/corpus/models.py
# class ExportCorpusTask(TaskRQ):
# file_format = models.CharField(
# max_length=5, null=False, blank=False, default="txt", choices=(("txt", "Text File"),)
# )
# file_compression = models.CharField(
# max_length=5,
# null=False,
# blank=False,
# default="none",
# choices=(
# ("none", "No compression"),
# ("bz2", "Bzip2"),
# ("lzma", "LZMA"),
# ),
# )
#
# corpora = ChoiceArrayField(
# models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=_CORPORA_CHOICES,
# ),
# blank=False,
# )
#
# filtering = ChoiceArrayField(
# models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=_FILTERING_CHOICES,
# ),
# blank=True,
# )
#
# processing = models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=(
# ("orig", "Original texts in markdown format"),
# ("tokens", "Tokenized by NLP-UK lib"),
# ("lemmas", "Lemmatized by NLP-UK lib"),
# ),
# )
#
# TASK_QUEUE = settings.QUEUE_DEFAULT
#
# DEFAULT_VERBOSITY = 2
# TASK_TIMEOUT = 0
# LOG_TO_FIELD = True
# LOG_TO_FILE = False
#
# @staticmethod
# def get_jobclass():
# from .jobs import ExportCorpusJob
#
# return ExportCorpusJob
#
# class TagWithUDPipeTask(TaskRQ):
# corpora = ChoiceArrayField(
# models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=_CORPORA_CHOICES,
# ),
# blank=False,
# )
#
# force = models.BooleanField(
# "Tag all texts, including already tagged",
# default=False,
# )
#
# TASK_QUEUE = settings.QUEUE_DEFAULT
#
# DEFAULT_VERBOSITY = 2
# TASK_TIMEOUT = 0
# LOG_TO_FIELD = True
# LOG_TO_FILE = False
#
# @staticmethod
# def get_jobclass():
# from .jobs import TagWithUDPipeJob
#
# return TagWithUDPipeJob
#
# class BuildFreqVocabTask(TaskRQ):
# corpora = ChoiceArrayField(
# models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=_CORPORA_CHOICES,
# ),
# blank=False,
# )
#
# filtering = ChoiceArrayField(
# models.CharField(
# max_length=10,
# null=False,
# blank=False,
# choices=_FILTERING_CHOICES,
# ),
# blank=True,
# default=list
# )
#
# file_format = models.CharField(
# max_length=5, null=False, blank=False, default="csv", choices=(("csv", "CSV file"),)
# )
# file_compression = models.CharField(
# max_length=5,
# null=False,
# blank=False,
# default="none",
# choices=(
# ("none", "No compression"),
# ("bz2", "Bzip2"),
# ("lzma", "LZMA"),
# ),
# )
# TASK_QUEUE = settings.QUEUE_DEFAULT
#
# DEFAULT_VERBOSITY = 2
# TASK_TIMEOUT = 0
# LOG_TO_FIELD = True
# LOG_TO_FILE = False
#
# @staticmethod
# def get_jobclass():
# from .jobs import BuildFreqVocabJob
#
# return BuildFreqVocabJob
, which may contain function names, class names, or code. Output only the next line. | @admin.register(BuildFreqVocabTask) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.