Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Here is a snippet: <|code_start|>
def tearDown(self):
del self.dj
self.requests_mock.stop()
def run_case(self, case_filename, expected_dict=None):
sample_path = os.path.join(self.SAMPLES_DIR, case_filename + ".json")
result_path = os.path.join(self.RESULTS_DIR, case_filename + ".json")
if expected_dict is None:
with io.open(result_path, encoding='utf8') as result_file:
expected_dict = json.load(result_file)
response_bool = self.dj.is_valid_catalog(sample_path)
response_dict = self.dj.validate_catalog(sample_path)
print(text_type(json.dumps(
response_dict, indent=4, separators=(",", ": "),
ensure_ascii=False
)))
if expected_dict["status"] == "OK":
assert_true(response_bool)
elif expected_dict["status"] == "ERROR":
assert_false(response_bool)
else:
raise Exception("LA RESPUESTA {} TIENE UN status INVALIDO".format(
case_filename))
assert_dict_equal.__self__.maxDiff = None
<|code_end|>
. Write the next line using the current file imports:
import json
import os.path
import re
import requests_mock
import vcr
import mock
import io
from nose.tools import assert_true, assert_false, assert_dict_equal, \
assert_regexp_matches
from six import iteritems, text_type
from tests.support.factories.core_files import TEST_FILE_RESPONSES
from .support.constants import BAD_DATAJSON_URL, BAD_DATAJSON_URL2
from .support.utils import jsonschema_str
from unittest import mock
from .context import pydatajson
from .support.decorators import RESULTS_DIR
and context from other files:
# Path: tests/support/factories/core_files.py
# TEST_FILE_RESPONSES = {}
#
# Path: tests/support/constants.py
# BAD_DATAJSON_URL = "http://104.131.35.253/data.json"
#
# BAD_DATAJSON_URL2 = "http://181.209.63.71/data.json"
#
# Path: tests/support/utils.py
# def jsonschema_str(string):
# return repr(string)
#
# Path: tests/context.py
#
# Path: tests/support/decorators.py
# RESULTS_DIR = os.path.join("tests", "results")
, which may include functions, classes, or code. Output only the next line. | assert_dict_equal(expected_dict, response_dict) |
Here is a snippet: <|code_start|> self.catalog = pydatajson.readers.read_catalog(
self.get_sample("full_data.json"))
self.maxDiff = None
self.longMessage = True
self.requests_mock = requests_mock.Mocker()
self.requests_mock.start()
self.requests_mock.get(requests_mock.ANY, real_http=True)
self.requests_mock.head(requests_mock.ANY, status_code=200)
def tearDown(self):
del self.dj
self.requests_mock.stop()
def run_case(self, case_filename, expected_dict=None):
sample_path = os.path.join(self.SAMPLES_DIR, case_filename + ".json")
result_path = os.path.join(self.RESULTS_DIR, case_filename + ".json")
if expected_dict is None:
with io.open(result_path, encoding='utf8') as result_file:
expected_dict = json.load(result_file)
response_bool = self.dj.is_valid_catalog(sample_path)
response_dict = self.dj.validate_catalog(sample_path)
print(text_type(json.dumps(
response_dict, indent=4, separators=(",", ": "),
ensure_ascii=False
)))
<|code_end|>
. Write the next line using the current file imports:
import json
import os.path
import re
import requests_mock
import vcr
import mock
import io
from nose.tools import assert_true, assert_false, assert_dict_equal, \
assert_regexp_matches
from six import iteritems, text_type
from tests.support.factories.core_files import TEST_FILE_RESPONSES
from .support.constants import BAD_DATAJSON_URL, BAD_DATAJSON_URL2
from .support.utils import jsonschema_str
from unittest import mock
from .context import pydatajson
from .support.decorators import RESULTS_DIR
and context from other files:
# Path: tests/support/factories/core_files.py
# TEST_FILE_RESPONSES = {}
#
# Path: tests/support/constants.py
# BAD_DATAJSON_URL = "http://104.131.35.253/data.json"
#
# BAD_DATAJSON_URL2 = "http://181.209.63.71/data.json"
#
# Path: tests/support/utils.py
# def jsonschema_str(string):
# return repr(string)
#
# Path: tests/context.py
#
# Path: tests/support/decorators.py
# RESULTS_DIR = os.path.join("tests", "results")
, which may include functions, classes, or code. Output only the next line. | if expected_dict["status"] == "OK": |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, with_statement
try:
except ImportError:
my_vcr = vcr.VCR(path_transformer=vcr.VCR.ensure_suffix('.yaml'),
cassette_library_dir=os.path.join("tests", "cassetes"),
record_mode='once')
class TestDataJsonTestCase(object):
SAMPLES_DIR = os.path.join("tests", "samples")
RESULTS_DIR = RESULTS_DIR
TEMP_DIR = os.path.join("tests", "temp")
@classmethod
def get_sample(cls, sample_filename):
return os.path.join(cls.SAMPLES_DIR, sample_filename)
def setUp(self):
self.dj = pydatajson.DataJson(self.get_sample("full_data.json"))
self.catalog = pydatajson.readers.read_catalog(
self.get_sample("full_data.json"))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import os.path
import re
import requests_mock
import vcr
import mock
import io
from nose.tools import assert_true, assert_false, assert_dict_equal, \
assert_regexp_matches
from six import iteritems, text_type
from tests.support.factories.core_files import TEST_FILE_RESPONSES
from .support.constants import BAD_DATAJSON_URL, BAD_DATAJSON_URL2
from .support.utils import jsonschema_str
from unittest import mock
from .context import pydatajson
from .support.decorators import RESULTS_DIR
and context:
# Path: tests/support/factories/core_files.py
# TEST_FILE_RESPONSES = {}
#
# Path: tests/support/constants.py
# BAD_DATAJSON_URL = "http://104.131.35.253/data.json"
#
# BAD_DATAJSON_URL2 = "http://181.209.63.71/data.json"
#
# Path: tests/support/utils.py
# def jsonschema_str(string):
# return repr(string)
#
# Path: tests/context.py
#
# Path: tests/support/decorators.py
# RESULTS_DIR = os.path.join("tests", "results")
which might include code, classes, or functions. Output only the next line. | self.maxDiff = None |
Next line prediction: <|code_start|> self.dj = pydatajson.DataJson(self.get_sample("full_data.json"))
self.catalog = pydatajson.readers.read_catalog(
self.get_sample("full_data.json"))
self.maxDiff = None
self.longMessage = True
self.requests_mock = requests_mock.Mocker()
self.requests_mock.start()
self.requests_mock.get(requests_mock.ANY, real_http=True)
self.requests_mock.head(requests_mock.ANY, status_code=200)
def tearDown(self):
del self.dj
self.requests_mock.stop()
def test_urls_with_status_code_200_is_valid(self):
assert_true(self.dj.is_valid_catalog(broken_links=True))
def test_urls_with_status_code_203_is_valid(self):
self.requests_mock.head(requests_mock.ANY, status_code=203)
assert_true(self.dj.is_valid_catalog(broken_links=True))
def test_urls_with_status_code_302_is_valid(self):
self.requests_mock.head(requests_mock.ANY, status_code=302)
assert_true(self.dj.is_valid_catalog(broken_links=True))
def test_urls_with_invalid_status_codes_are_not_valid(self):
self.requests_mock.head(requests_mock.ANY, status_code=404)
assert_false(self.dj.is_valid_catalog(broken_links=True))
def test_throws_exception(self):
<|code_end|>
. Use current file imports:
(import os
import requests_mock
import pydatajson
from nose.tools import assert_true, assert_false
from requests import Timeout
from .support.decorators import RESULTS_DIR)
and context including class names, function names, or small code snippets from other files:
# Path: tests/support/decorators.py
# RESULTS_DIR = os.path.join("tests", "results")
. Output only the next line. | self.requests_mock.head(requests_mock.ANY, exc=Timeout) |
Predict the next line for this snippet: <|code_start|> "instance": None,
"validator": "required",
"path": [
"dataset",
0
],
"message": "%s is a required property" % jsonschema_str('description'),
"error_code": 1,
"validator_value": [
"title",
"description",
"publisher",
"superTheme",
"distribution",
"accrualPeriodicity",
"issued",
"identifier"
]
})
def invalid_multiple_fields_type():
return gen_error({
"instance": [
"Ministerio de Modernización",
"datosargentina@jefatura.gob.ar"
],
"validator": "type",
"path": [
"publisher"
<|code_end|>
with the help of current file imports:
from tests.support.utils import jsonschema_str
and context from other files:
# Path: tests/support/utils.py
# def jsonschema_str(string):
# return repr(string)
, which may contain function names, class names, or code. Output only the next line. | ], |
Using the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
class UrlValidator(SimpleValidator):
def __init__(self, catalog, verify_ssl, url_check_timeout, threads_count):
super(UrlValidator, self).__init__(catalog)
self.verify_ssl = verify_ssl
self.url_check_timeout = url_check_timeout
self.threads_count = threads_count
def validate(self):
raise NotImplementedError
def is_working_url(self, url):
try:
response = requests.head(url,
timeout=self.url_check_timeout,
verify=self.verify_ssl)
matches = []
if response.status_code not in EXCEPTION_STATUS_CODES:
matches = \
[re.match(pattern, str(response.status_code)) is not None
for pattern in INVALID_STATUS_CODES_REGEX]
<|code_end|>
, determine the next line of code. You have imports:
import re
import requests
from requests import RequestException, Timeout
from pydatajson.constants import EXCEPTION_STATUS_CODES, \
INVALID_STATUS_CODES_REGEX
from pydatajson.validators.simple_validator import SimpleValidator
and context (class names, function names, or code) available:
# Path: pydatajson/constants.py
# EXCEPTION_STATUS_CODES = [429]
#
# INVALID_STATUS_CODES_REGEX = ["^4[0-9]+$", "^5[0-9]+$"]
#
# Path: pydatajson/validators/simple_validator.py
# class SimpleValidator(object):
#
# def __init__(self, catalog):
# self.catalog = catalog
#
# def validate(self):
# raise NotImplementedError
. Output only the next line. | return True not in matches, response.status_code |
Using the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
class UrlValidator(SimpleValidator):
def __init__(self, catalog, verify_ssl, url_check_timeout, threads_count):
super(UrlValidator, self).__init__(catalog)
self.verify_ssl = verify_ssl
self.url_check_timeout = url_check_timeout
self.threads_count = threads_count
def validate(self):
raise NotImplementedError
def is_working_url(self, url):
try:
response = requests.head(url,
timeout=self.url_check_timeout,
verify=self.verify_ssl)
matches = []
if response.status_code not in EXCEPTION_STATUS_CODES:
matches = \
[re.match(pattern, str(response.status_code)) is not None
for pattern in INVALID_STATUS_CODES_REGEX]
return True not in matches, response.status_code
<|code_end|>
, determine the next line of code. You have imports:
import re
import requests
from requests import RequestException, Timeout
from pydatajson.constants import EXCEPTION_STATUS_CODES, \
INVALID_STATUS_CODES_REGEX
from pydatajson.validators.simple_validator import SimpleValidator
and context (class names, function names, or code) available:
# Path: pydatajson/constants.py
# EXCEPTION_STATUS_CODES = [429]
#
# INVALID_STATUS_CODES_REGEX = ["^4[0-9]+$", "^5[0-9]+$"]
#
# Path: pydatajson/validators/simple_validator.py
# class SimpleValidator(object):
#
# def __init__(self, catalog):
# self.catalog = catalog
#
# def validate(self):
# raise NotImplementedError
. Output only the next line. | except Timeout: |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
class UrlValidator(SimpleValidator):
def __init__(self, catalog, verify_ssl, url_check_timeout, threads_count):
super(UrlValidator, self).__init__(catalog)
self.verify_ssl = verify_ssl
self.url_check_timeout = url_check_timeout
self.threads_count = threads_count
def validate(self):
raise NotImplementedError
def is_working_url(self, url):
try:
response = requests.head(url,
<|code_end|>
. Use current file imports:
(import re
import requests
from requests import RequestException, Timeout
from pydatajson.constants import EXCEPTION_STATUS_CODES, \
INVALID_STATUS_CODES_REGEX
from pydatajson.validators.simple_validator import SimpleValidator)
and context including class names, function names, or small code snippets from other files:
# Path: pydatajson/constants.py
# EXCEPTION_STATUS_CODES = [429]
#
# INVALID_STATUS_CODES_REGEX = ["^4[0-9]+$", "^5[0-9]+$"]
#
# Path: pydatajson/validators/simple_validator.py
# class SimpleValidator(object):
#
# def __init__(self, catalog):
# self.catalog = catalog
#
# def validate(self):
# raise NotImplementedError
. Output only the next line. | timeout=self.url_check_timeout, |
Given the following code snippet before the placeholder: <|code_start|>
def is_list_of_matching_dicts(list_of_dicts, expected_keys=None):
"""Comprueba que una lista esté compuesta únicamente por diccionarios,
que comparten exactamente las mismas claves.
Args:
list_of_dicts (list): Lista de diccionarios a comparar.
expected_keys (set): Conjunto de las claves que cada diccionario debe
tener. Si no se incluye, se asume que son las claves del primer
diccionario de la lista.
Returns:
bool: True si todos los diccionarios comparten sus claves.
"""
if isinstance(list_of_dicts, list) and len(list_of_dicts) == 0:
return False
is_not_list_msg = """
{} no es una lista. Debe ingresar una lista""".format(list_of_dicts)
assert isinstance(list_of_dicts, list), is_not_list_msg
not_all_dicts_msg = """
No todos los elementos de {} son diccionarios. Ingrese una lista compuesta
solo por diccionarios.""".format(list_of_dicts)
assert all([isinstance(d, dict) for d in list_of_dicts]), not_all_dicts_msg
# Si no se pasan expected_keys, se las toma del primer diccionario
expected_keys = expected_keys or set(list_of_dicts[0].keys())
<|code_end|>
, predict the next line using imports from the current file:
import json
import logging
import os
import re
import tempfile
from contextlib import contextmanager
from datetime import datetime
from openpyxl import load_workbook
from six import string_types, iteritems
from six.moves.urllib_parse import urlparse
from unidecode import unidecode
from pydatajson.download import download_to_file
and context including class names, function names, and sometimes code from other files:
# Path: pydatajson/download.py
# def download_to_file(url, file_path, **kwargs):
# """
# Descarga un archivo a través del protocolo HTTP, en uno o más intentos, y
# escribe el contenido descargado el el path especificado.
#
# Args:
# url (str): URL (schema HTTP) del archivo a descargar.
# file_path (str): Path del archivo a escribir. Si un archivo ya existe
# en el path especificado, se sobrescribirá con nuevos contenidos.
# kwargs: Parámetros para download().
# """
# content = download(url, file_path, **kwargs)
. Output only the next line. | elements = [set(d.keys()) == expected_keys for d in list_of_dicts] |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
class CustomRemoteCKAN(RemoteCKAN):
def __init__(self, address, apikey=None, user_agent=None, get_only=False,
verify_ssl=False, requests_timeout=REQUESTS_TIMEOUT):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ckanapi import RemoteCKAN
from pydatajson.constants import REQUESTS_TIMEOUT
and context:
# Path: pydatajson/constants.py
# REQUESTS_TIMEOUT = 30
which might include code, classes, or functions. Output only the next line. | self.verify_ssl = verify_ssl |
Based on the snippet: <|code_start|> def test_full_datasets_meta_error_cant(self):
self.assertEqual(0, self.gen_full_data.datasets_meta_error_cant())
def test_empty_datasets_meta_error_cant(self):
self.assertEqual(0, self.gen_empty.datasets_meta_error_cant())
def test_just_datasets_meta_ok_pct(self):
self.assertEqual(0.9375, self.gen_justicia.datasets_meta_ok_pct())
def test_full_datasets_meta_ok_pct(self):
self.assertEqual(1.0, self.gen_full_data.datasets_meta_ok_pct())
def test_empty_datasets_meta_ok_pct(self):
self.assertEqual(None, self.gen_empty.datasets_meta_ok_pct())
def test_just_datasets_con_datos_cant(self):
self.assertEqual(16, self.gen_justicia.datasets_con_datos_cant())
def test_full_datasets_con_datos_cant(self):
self.assertEqual(1, self.gen_full_data.datasets_con_datos_cant())
def test_empty_datasets_con_datos_cant(self):
self.assertEqual(0, self.gen_empty.datasets_con_datos_cant())
def test_just_datasets_sin_datos_cant(self):
self.assertEqual(0, self.gen_justicia.datasets_sin_datos_cant())
def test_full_datasets_sin_datos_cant(self):
self.assertEqual(1, self.gen_full_data.datasets_sin_datos_cant())
<|code_end|>
, predict the immediate next line with the help of imports:
import os.path
import re
import unittest
import requests_mock
import mock
from pydatajson.status_indicators_generator import StatusIndicatorsGenerator
from unittest import mock
and context (classes, functions, sometimes code) from other files:
# Path: pydatajson/status_indicators_generator.py
# class StatusIndicatorsGenerator(object):
#
# def __init__(self, catalog, validator=None, verify_ssl=True,
# url_check_timeout=1, threads_count=1):
# self.download_url_ok = None
# self.catalog = read_catalog(catalog)
# self.summary = generate_datasets_summary(self.catalog,
# validator=validator,
# verify_ssl=verify_ssl)
# self.verify_url = verify_ssl
# self.url_check_timeout = url_check_timeout
# self.threads_count = threads_count
#
# def datasets_cant(self):
# return len(self.summary)
#
# def distribuciones_cant(self):
# return sum(ds['cant_distribuciones'] for ds in self.summary)
#
# def datasets_meta_ok_cant(self):
# return sum(ds['estado_metadatos'] == 'OK' for ds in self.summary)
#
# def datasets_meta_error_cant(self):
# return sum(ds['estado_metadatos'] == 'ERROR' for ds in self.summary)
#
# def datasets_meta_ok_pct(self):
# return self._get_dataset_percentage(self.datasets_meta_ok_cant)
#
# def datasets_con_datos_cant(self):
# return sum(ds['tiene_datos'] == 'SI' for ds in self.summary)
#
# def datasets_sin_datos_cant(self):
# return sum(ds['tiene_datos'] == 'NO' for ds in self.summary)
#
# def datasets_con_datos_pct(self):
# return self._get_dataset_percentage(self.datasets_con_datos_cant)
#
# def distribuciones_download_url_ok_cant(self):
# if self.download_url_ok:
# return self.download_url_ok
# validator = DistributionDownloadUrlsValidator(
# self.catalog, self.verify_url, self.url_check_timeout,
# self.threads_count)
# self.download_url_ok = validator.validate()
# return self.download_url_ok
#
# def distribuciones_download_url_error_cant(self):
# return self.distribuciones_cant() - \
# self.distribuciones_download_url_ok_cant()
#
# def distribuciones_download_url_ok_pct(self):
# total = self.distribuciones_cant()
# if not total:
# return None
# return \
# round(float(self.distribuciones_download_url_ok_cant()) / total, 4)
#
# def _get_dataset_percentage(self, indicator):
# total = self.datasets_cant()
# if not total:
# return None
# return round(float(indicator()) / total, 4)
. Output only the next line. | def test_empty_datasets_sin_datos_cant(self): |
Based on the snippet: <|code_start|> "error_code": 2,
"message": "%s is not valid under any of the given schemas"
% jsonschema_str('datosATmodernizacion.gob.ar'),
"validator": "anyOf",
"path": ["publisher", "mbox"],
"instance": "datosATmodernizacion.gob.ar",
"validator_value": [
{
"type": "string",
"format": "email",
},
{
"type": "string",
"maxLength": 0,
}]
})
def null_catalog_publisher():
return catalog_error({
"error_code": 2,
"message": "None is not of type %s" % jsonschema_str('object'),
"path": ['publisher'],
"validator": 'type',
"validator_value": 'object',
})
def empty_mandatory_string():
return catalog_error({
<|code_end|>
, predict the immediate next line with the help of imports:
from tests.support.utils import jsonschema_str
and context (classes, functions, sometimes code) from other files:
# Path: tests/support/utils.py
# def jsonschema_str(string):
# return repr(string)
. Output only the next line. | "error_code": 2, |
Given the following code snippet before the placeholder: <|code_start|> {"a": 1, "b": 2},
{"a": 1, "b": 2},
{"a": 1, "b": 2}
])
self.assertTrue(result)
def test_is_list_of_matching_dicts_with_mismatched_dicts(self):
"""is_list_of_matching_dicts devuelve False si no todos los elementos
del input tienen las mismas claves."""
result = pydatajson.helpers.is_list_of_matching_dicts([
{"a": 1, "b": 2},
{"a": 1},
{"a": 1, "b": 2}
])
self.assertFalse(result)
def test_parse_repeating_time_interval_to_days(self):
# Testea función auxiliar para interpretar intervalos repetidos en días
self.assertEqual(
parse_repeating_time_interval_to_days("R/P6M"), 180
)
def test_parse_repeating_time_interval_to_str(self):
# Testea función auxiliar para interpretar intervalos repetidos en días
self.assertEqual(
parse_repeating_time_interval_to_str("R/P6M"), "Cada medio año"
<|code_end|>
, predict the next line using imports from the current file:
import os.path
import unittest
import nose
import openpyxl as pyxl
from pydatajson.helpers import fields_to_uppercase
from .context import pydatajson
from pydatajson.helpers import parse_repeating_time_interval_to_days
from pydatajson.helpers import parse_repeating_time_interval_to_str
and context including class names, function names, and sometimes code from other files:
# Path: pydatajson/helpers.py
# def fields_to_uppercase(fields):
# uppercase_fields = fields.copy()
#
# for key in fields:
# lower_key = key.lower()
# upper_key = key.upper()
#
# if not key.isupper():
# lowercase_counts = uppercase_fields.pop(lower_key, 0)
# uppercase_counts = uppercase_fields.pop(upper_key, 0)
# counts = uppercase_fields.pop(key, 0)
#
# uppercase_fields[upper_key] = \
# uppercase_counts + lowercase_counts + counts
#
# return uppercase_fields
#
# Path: tests/context.py
. Output only the next line. | ) |
Continue the code snippet: <|code_start|> "distribuciones_formatos_cant": {
"SHP": 207,
"ZIP": 122,
"JPEG": 26,
"PDF": 235,
"CSV": 499,
"XLS": 25,
"RDF": 1,
"JSON": 5
},
"una_lista": ["b", 2, False, "a", 1, True],
"dict_anidado": {
"valor": 36
}
}
result = pydatajson.helpers.add_dicts(one_dict, other_dict)
self.assertDictEqual(result, expected)
def test_parse_date_string(self):
self.assertEqual(pydatajson.helpers.parse_date_string(""), None)
def test_title_to_name(self):
self.assertEqual(
pydatajson.helpers.title_to_name(
"Exportación en $ de tomates año 2017 (*)"),
"exportacion-tomates-ano-2017"
)
def test_fields_to_uppercase_returns_unique_uppercase_keys(self):
fields = {
<|code_end|>
. Use current file imports:
import os.path
import unittest
import nose
import openpyxl as pyxl
from pydatajson.helpers import fields_to_uppercase
from .context import pydatajson
from pydatajson.helpers import parse_repeating_time_interval_to_days
from pydatajson.helpers import parse_repeating_time_interval_to_str
and context (classes, functions, or code) from other files:
# Path: pydatajson/helpers.py
# def fields_to_uppercase(fields):
# uppercase_fields = fields.copy()
#
# for key in fields:
# lower_key = key.lower()
# upper_key = key.upper()
#
# if not key.isupper():
# lowercase_counts = uppercase_fields.pop(lower_key, 0)
# uppercase_counts = uppercase_fields.pop(upper_key, 0)
# counts = uppercase_fields.pop(key, 0)
#
# uppercase_fields[upper_key] = \
# uppercase_counts + lowercase_counts + counts
#
# return uppercase_fields
#
# Path: tests/context.py
. Output only the next line. | 'csv': 10, |
Next line prediction: <|code_start|>
class ListFormatter(ValidationResponseFormatter):
def format(self):
rows_catalog = []
validation_result = {
"catalog_title": self.response["error"]["catalog"]["title"],
"catalog_status": self.response["error"]["catalog"]["status"],
}
for error in self.response["error"]["catalog"]["errors"]:
catalog_result = dict(validation_result)
catalog_result.update({
"catalog_error_message": error["message"],
"catalog_error_location": ", ".join(error["path"]),
})
rows_catalog.append(catalog_result)
if len(self.response["error"]["catalog"]["errors"]) == 0:
catalog_result = dict(validation_result)
catalog_result.update({
"catalog_error_message": None,
"catalog_error_location": None
})
rows_catalog.append(catalog_result)
# crea una lista de dicts para volcarse en una tabla (dataset)
rows_dataset = []
for dataset in self.response["error"]["dataset"]:
validation_result = {
"dataset_title": dataset["title"],
<|code_end|>
. Use current file imports:
(from pydatajson.response_formatters.validation_response_formatter import \
ValidationResponseFormatter)
and context including class names, function names, or small code snippets from other files:
# Path: pydatajson/response_formatters/validation_response_formatter.py
# class ValidationResponseFormatter(object):
#
# def __init__(self, response):
# self.response = response
#
# @abc.abstractmethod
# def format(self):
# raise NotImplementedError
. Output only the next line. | "dataset_identifier": dataset["identifier"], |
Given snippet: <|code_start|> "errors": [
{
"instance": None,
"validator": "required",
"path": [
"dataset",
0,
"distribution",
0
],
"message": "%s is a required property"
% jsonschema_str('title'),
"error_code": 1,
"validator_value": [
"accessURL",
"downloadURL",
"title",
"issued",
"identifier"
]
}
],
"title": "Sistema de contrataciones electrónicas"
}
]
}
}
def missing_distribution_title():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from tests.support.utils import jsonschema_str
and context:
# Path: tests/support/utils.py
# def jsonschema_str(string):
# return repr(string)
which might include code, classes, or functions. Output only the next line. | return distribution_error() |
Predict the next line after this snippet: <|code_start|> origin_tz=self.dates['tz_london'], # GMT+1,
dst_tz=self.dates['tz_new_york']
)
res_london = convert_iso_string_to_dst_timezone(
date,
origin_tz=self.dates['tz_london'], # GMT+1,
dst_tz=self.dates['tz_london']
)
self.assertEqual(expected_date_bs_as, res_bs_as)
self.assertEqual(expected_date_new_york, res_new_york)
self.assertEqual(expected_date_london, res_london)
def test_res_date_is_congruent_to_given_origin_and_dst_tzs(self):
date = '2018-06-29T15:14:09.291510'
expected_date_bs_as = '2018-06-29T16:14:09.291510'
expected_date_new_york = '2018-06-29T15:14:09.291510'
expected_date_london = '2018-06-29T20:14:09.291510'
res_bs_as = convert_iso_string_to_dst_timezone(
date,
origin_tz=self.dates['tz_new_york'], # GMT-4,
dst_tz=self.dates['tz_bs_as']
)
res_new_york = convert_iso_string_to_dst_timezone(
date,
origin_tz=self.dates['tz_new_york'], # GMT-4,
dst_tz=self.dates['tz_new_york']
)
res_london = convert_iso_string_to_dst_timezone(
<|code_end|>
using the current file's imports:
import os
import unittest
from pydatajson.ckan_utils import *
from pydatajson.helpers import title_to_name
from .context import pydatajson
and any relevant context from other files:
# Path: pydatajson/helpers.py
# def title_to_name(title, decode=True, max_len=None, use_complete_words=True):
# """Convierte un título en un nombre normalizado para generar urls."""
# # decodifica y pasa a minúsculas
# if decode:
# title = unidecode(title)
# title = title.lower()
#
# # remueve caracteres no permitidos
# filtered_title = re.sub(r'[^a-z0-9- ]+', '', title)
#
# # remueve stop words y espacios y une palabras sólo con un "-"
# normalized_title = '-'.join([word for word in filtered_title.split()
# if word not in STOP_WORDS])
#
# # recorto el titulo normalizado si excede la longitud máxima
# if max_len and len(normalized_title) > max_len:
#
# # busco la última palabra completa
# if use_complete_words:
# last_word_index = normalized_title.rindex("-", 0, max_len)
# normalized_title = normalized_title[:last_word_index]
#
# # corto en el último caracter
# else:
# normalized_title = normalized_title[:max_len]
#
# return normalized_title
#
# Path: tests/context.py
. Output only the next line. | date, |
Given the code snippet: <|code_start|> for s_theme in self.dataset.get('superTheme')]
try:
self.assertItemsEqual(super_themes, groups)
except AttributeError:
self.assertCountEqual(super_themes, groups)
tags = [tag['name'] for tag in package['tags']]
keywords = self.dataset.get('keyword', [])
themes = self.dataset.get('theme', [])
theme_labels = []
for theme in themes:
label = self.catalog.get_theme(identifier=theme)['label']
label = re.sub(r'[^\w .-]+', '', label, flags=re.UNICODE)
theme_labels.append(label)
try:
self.assertItemsEqual(keywords + theme_labels, tags)
except AttributeError:
self.assertCountEqual(keywords + theme_labels, tags)
def test_themes_are_preserved_if_not_demoted(self):
package = map_dataset_to_package(
self.catalog,
self.dataset,
'owner',
catalog_id=self.catalog_id,
demote_themes=False)
groups = [group['name'] for group in package.get('groups', [])]
super_themes = [title_to_name(s_theme.lower())
<|code_end|>
, generate the next line using the imports in this file:
import os
import unittest
from pydatajson.ckan_utils import *
from pydatajson.helpers import title_to_name
from .context import pydatajson
and context (functions, classes, or occasionally code) from other files:
# Path: pydatajson/helpers.py
# def title_to_name(title, decode=True, max_len=None, use_complete_words=True):
# """Convierte un título en un nombre normalizado para generar urls."""
# # decodifica y pasa a minúsculas
# if decode:
# title = unidecode(title)
# title = title.lower()
#
# # remueve caracteres no permitidos
# filtered_title = re.sub(r'[^a-z0-9- ]+', '', title)
#
# # remueve stop words y espacios y une palabras sólo con un "-"
# normalized_title = '-'.join([word for word in filtered_title.split()
# if word not in STOP_WORDS])
#
# # recorto el titulo normalizado si excede la longitud máxima
# if max_len and len(normalized_title) > max_len:
#
# # busco la última palabra completa
# if use_complete_words:
# last_word_index = normalized_title.rindex("-", 0, max_len)
# normalized_title = normalized_title[:last_word_index]
#
# # corto en el último caracter
# else:
# normalized_title = normalized_title[:max_len]
#
# return normalized_title
#
# Path: tests/context.py
. Output only the next line. | for s_theme in self.dataset.get('superTheme')] |
Continue the code snippet: <|code_start|># coding: utf-8
from __future__ import unicode_literals, absolute_import
logger = logging.getLogger(__name__)
class WeiXinHook(View):
@csrf_exempt
def dispatch(self, request, *args, **kwargs):
signature = request.GET.get('signature', '')
timestamp = request.GET.get('timestamp', '')
nonce = request.GET.get('nonce', '')
try:
check_signature(settings.WX_SIGN_TOKEN, signature, timestamp, nonce)
return super(WeiXinHook, self).dispatch(request, *args, **kwargs)
except InvalidSignatureException:
<|code_end|>
. Use current file imports:
import logging
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from django.views.generic import View
from wechatpy.utils import check_signature
from wechatpy import parse_message
from wechatpy.exceptions import InvalidSignatureException
from .message_handler import handle_message
and context (classes, functions, or code) from other files:
# Path: WeCron/wxhook/message_handler.py
# def handle_message(msg):
# # msgid = str(msg.id)
# # if msgid not in ['0', 'None'] and shove.get('last_msgid') == msgid: # Duplicated message
# # return TextReply(
# # content='',
# # message=msg,
# # ).render()
# # TODO unique based on msgid
# resp_msg = WechatMessage(msg).handle()
# # shove['last_msgid'] = msgid
# return resp_msg
. Output only the next line. | logger.warning('Invalid signature when accessing %s', request.get_full_path()) |
Here is a snippet: <|code_start|> self.time_fields['day'] = day
# 2016年12月14日周三在上海举办的2016 Google 开发者大会
# 2016年12月14日(周三)在上海举办的2016 Google 开发者大会
self.consume_word(u'(', u'(')
if self.consume_word(u'周', u'星期'):
self.consume_word(u'日', u'天') or self.consume_digit()
self.consume_word(u')', u')')
# set default time
if not self.consume_hour():
self.time_fields['hour'] = DEFAULT_HOUR
self.time_fields['minute'] = DEFAULT_MINUTE
self.exclude_time_range(self.consume_day)
return self.get_index() - beginning
def consume_hour(self):
beginning1 = self.get_index()
if self.consume_word(u'凌晨', u'半夜', u'夜里', u'深夜'):
self.afternoon = False
self.time_delta_fields['days'] = 1
self.time_fields['hour'] = 0
self.time_fields['minute'] = DEFAULT_MINUTE
elif self.consume_word(u'早', u'早上', u'早晨', u'今早', u'上午'):
self.afternoon = False
self.time_fields['hour'] = DEFAULT_HOUR
self.time_fields['minute'] = DEFAULT_MINUTE
elif self.consume_word(u'中午'):
self.afternoon = False
self.time_fields['hour'] = 12
self.time_fields['minute'] = DEFAULT_MINUTE
elif self.consume_word(u'下午'):
<|code_end|>
. Write the next line using the current file imports:
import os
import re
import logging
import jieba
import jieba.posseg as pseg
from dateutil.relativedelta import relativedelta
from django.utils import timezone
from remind.models import Remind
from remind.models.remind import REPEAT_KEY_YEAR, REPEAT_KEY_MONTH, \
REPEAT_KEY_DAY, REPEAT_KEY_WEEK, REPEAT_KEY_HOUR, REPEAT_KEY_MINUTE
from .exceptions import ParseError
and context from other files:
# Path: WeCron/wxhook/todo_parser/exceptions.py
# class ParseError(ValueError):
# pass
, which may include functions, classes, or code. Output only the next line. | self.afternoon = True |
Continue the code snippet: <|code_start|> <PicUrl><![CDATA[this is a url]]></PicUrl>
<MediaId><![CDATA[media_id]]></MediaId>
<MsgId>12345678901234563</MsgId>
</xml>
"""
wechat_msg = self.build_wechat_msg(req_text)
resp_xml = handle_message(wechat_msg)
self.assertIn(self.instructions_to_use, resp_xml)
def test_voice(self):
req_text = """
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[FromUser]]></FromUserName>
<CreateTime>1357290913</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
<MediaId><![CDATA[media_id]]></MediaId>
<Format><![CDATA[Format]]></Format>
<Recognition><![CDATA[%s]]></Recognition>
<MsgId>12345678901234564</MsgId>
</xml>
""" % self.remind_desc
wechat_msg = self.build_wechat_msg(req_text)
resp_xml = handle_message(wechat_msg)
self.assertIn('时间:', resp_xml)
def test_voice_with_media_id(self):
media_id = '1sew2_7_hbIOymbtyeZEoxaAnR83Hff0PM9b8ChEUmt5FRVA6-fHrmHdGre6iKGN'
req_text = """
<xml>
<|code_end|>
. Use current file imports:
from django.test import TestCase
from django.db.models.signals import post_save
from django.utils import timezone
from wechatpy import parse_message
from httmock import urlmatch, response, HTTMock
from common import wechat_client
from common.tests import access_token_mock
from ..message_handler import handle_message
from wechat_user.models import WechatUser
from remind.models import Remind
and context (classes, functions, or code) from other files:
# Path: WeCron/wxhook/message_handler.py
# def handle_message(msg):
# # msgid = str(msg.id)
# # if msgid not in ['0', 'None'] and shove.get('last_msgid') == msgid: # Duplicated message
# # return TextReply(
# # content='',
# # message=msg,
# # ).render()
# # TODO unique based on msgid
# resp_msg = WechatMessage(msg).handle()
# # shove['last_msgid'] = msgid
# return resp_msg
. Output only the next line. | <ToUserName><![CDATA[toUser]]></ToUserName> |
Next line prediction: <|code_start|> text = '半个钟头后提醒我同步'
reminder = self.parse(text)
self.assertEqual(reminder.desc, text)
self.assertEqual(reminder.title(), '同步')
self.assertAlmostEqual((reminder.time - self.now).seconds, 30 * 60, delta=2)
def test_parse_day_period(self):
text = '明天九点58提醒秒杀流量'
reminder = self.parse(text)
self.assertEqual(reminder.desc, text)
self.assertEqual(reminder.title(), '秒杀流量')
self.assertEqual((self.now + relativedelta(days=1)).day, reminder.time.day)
self.assertEquals(reminder.time.hour, 9)
self.assertEquals(reminder.time.minute, 58)
def test_parse_day_period_with_half(self):
text = '明晚八点去看电影'
reminder = self.parse(text)
self.assertEqual(reminder.desc, text)
self.assertEqual(reminder.title(), '去看电影')
self.assertEqual((self.now + relativedelta(days=1)).day, reminder.time.day)
self.assertEquals(reminder.time.hour, 20)
self.assertEquals(reminder.time.minute, 0)
self.setUp()
reminder = self.parse(u'今晚八点去看电影')
self.assertEqual(reminder.time.day - self.now.day, 0)
self.assertEquals(reminder.time.hour, 20)
self.assertEquals(reminder.time.minute, 0)
def test_parse_middle_night(self):
<|code_end|>
. Use current file imports:
(import unittest
from dateutil.relativedelta import relativedelta
from django.utils import timezone
from django.test import TestCase
from ..todo_parser.local_parser import LocalParser, parse_cn_number, DEFAULT_HOUR, ParseError
from remind.models import remind)
and context including class names, function names, or small code snippets from other files:
# Path: WeCron/wxhook/todo_parser/local_parser.py
# CN_NUM = {
# u'〇': 0,
# u'一': 1,
# u'二': 2,
# u'三': 3,
# u'四': 4,
# u'五': 5,
# u'六': 6,
# u'七': 7,
# u'八': 8,
# u'九': 9,
#
# u'零': 0,
# u'壹': 1,
# u'贰': 2,
# u'叁': 3,
# u'肆': 4,
# u'伍': 5,
# u'陆': 6,
# u'柒': 7,
# u'捌': 8,
# u'玖': 9,
#
# u'貮': 2,
# u'两': 2,
# }
# CN_UNIT = {
# u'十': 10,
# u'拾': 10,
# u'百': 100,
# u'佰': 100,
# u'千': 1000,
# u'仟': 1000,
# u'万': 10000,
# u'萬': 10000,
# u'亿': 100000000,
# u'億': 100000000,
# u'兆': 1000000000000,
# }
# DEFAULT_HOUR = 8
# DEFAULT_MINUTE = 0
# def parse_cn_number(cn_sentence):
# def __init__(self):
# def parse_by_rules(self, text):
# def consume_repeat(self):
# def consume_year(self):
# def consume_month(self):
# def consume_day(self):
# def consume_hour(self):
# def consume_minute(self):
# def consume_second(self):
# def exclude_time_range(self, next_expectation):
# def consume_year_period(self):
# def consume_month_period(self):
# def consume_day_period(self):
# def consume_weekday_period(self):
# def consume_hour_period(self):
# def consume_minute_period(self):
# def consume_second_period(self):
# def consume_to_end(self):
# def consume_word(self, *words):
# def consume_phrase(self, *words):
# def consume_digit(self, consume=True):
# def current_word(self):
# def current_tag(self):
# def peek_next_word(self, step=1):
# def get_index(self):
# def set_index(self, idx):
# def has_next(self):
# def advance(self, step=1):
# class LocalParser(object):
. Output only the next line. | for text in ('晚上零点提醒我 我姐生日', '凌晨零点提醒我 我姐生日'): |
Predict the next line after this snippet: <|code_start|> reminder = self.parse(text)
self.assertEqual(reminder.desc, text)
self.assertEqual(reminder.event, '')
self.assertEqual(reminder.title(), '闹钟')
self.assertAlmostEqual((reminder.time - self.now).seconds, 60+59, delta=2)
def test_parse_hour_period_with_minute(self):
# 分后 is required here, for when HMM is True, "分后" will become a word
text = '一小时三十分后提醒我'
reminder = self.parse(text)
self.assertEqual(reminder.desc, text)
self.assertEqual(reminder.title(), '闹钟')
self.assertAlmostEqual((reminder.time - self.now).seconds, 90 * 60, delta=2)
def test_parse_hour_period_with_half(self):
text = '两个半小时后提醒我'
reminder = self.parse(text)
self.assertEqual(reminder.desc, text)
self.assertEqual(reminder.title(), '闹钟')
self.assertAlmostEqual((reminder.time - self.now).seconds, 150 * 60, delta=2)
def test_parse_hour_period_with_only_half(self):
text = '半小时后提醒我同步'
reminder = self.parse(text)
self.assertEqual(reminder.desc, text)
self.assertEqual(reminder.title(), '同步')
self.assertAlmostEqual((reminder.time - self.now).seconds, 30 * 60, delta=2)
self.setUp()
text = '半个钟头后提醒我同步'
reminder = self.parse(text)
<|code_end|>
using the current file's imports:
import unittest
from dateutil.relativedelta import relativedelta
from django.utils import timezone
from django.test import TestCase
from ..todo_parser.local_parser import LocalParser, parse_cn_number, DEFAULT_HOUR, ParseError
from remind.models import remind
and any relevant context from other files:
# Path: WeCron/wxhook/todo_parser/local_parser.py
# CN_NUM = {
# u'〇': 0,
# u'一': 1,
# u'二': 2,
# u'三': 3,
# u'四': 4,
# u'五': 5,
# u'六': 6,
# u'七': 7,
# u'八': 8,
# u'九': 9,
#
# u'零': 0,
# u'壹': 1,
# u'贰': 2,
# u'叁': 3,
# u'肆': 4,
# u'伍': 5,
# u'陆': 6,
# u'柒': 7,
# u'捌': 8,
# u'玖': 9,
#
# u'貮': 2,
# u'两': 2,
# }
# CN_UNIT = {
# u'十': 10,
# u'拾': 10,
# u'百': 100,
# u'佰': 100,
# u'千': 1000,
# u'仟': 1000,
# u'万': 10000,
# u'萬': 10000,
# u'亿': 100000000,
# u'億': 100000000,
# u'兆': 1000000000000,
# }
# DEFAULT_HOUR = 8
# DEFAULT_MINUTE = 0
# def parse_cn_number(cn_sentence):
# def __init__(self):
# def parse_by_rules(self, text):
# def consume_repeat(self):
# def consume_year(self):
# def consume_month(self):
# def consume_day(self):
# def consume_hour(self):
# def consume_minute(self):
# def consume_second(self):
# def exclude_time_range(self, next_expectation):
# def consume_year_period(self):
# def consume_month_period(self):
# def consume_day_period(self):
# def consume_weekday_period(self):
# def consume_hour_period(self):
# def consume_minute_period(self):
# def consume_second_period(self):
# def consume_to_end(self):
# def consume_word(self, *words):
# def consume_phrase(self, *words):
# def consume_digit(self, consume=True):
# def current_word(self):
# def current_tag(self):
# def peek_next_word(self, step=1):
# def get_index(self):
# def set_index(self, idx):
# def has_next(self):
# def advance(self, step=1):
# class LocalParser(object):
. Output only the next line. | self.assertEqual(reminder.desc, text) |
Next line prediction: <|code_start|> self.assertEqual(reminder.time.year, self.now.year)
self.assertEqual(reminder.time.month, 12)
self.assertEqual(reminder.time.day, 16)
self.assertEquals(reminder.time.hour, 9)
self.assertEquals(reminder.time.minute, 10)
def test_parse_repeat_year(self):
text = '每年1月22号生日'
reminder = self.parse(text)
self.assertEqual(reminder.desc, text)
self.assertEqual(reminder.title(), '生日')
self.assertEqual(reminder.get_repeat_text(), '每年')
self.assertEqual(reminder.time.month, 1)
self.assertEquals(reminder.time.day, 22)
self.assertEquals(reminder.time.hour, DEFAULT_HOUR)
self.assertEquals(reminder.time.minute, 0)
def test_parse_nongli(self):
for text in ('每年阴历八月初九提醒我生日', '每年农历八月初九提醒我生日'):
self.setUp()
self.assertRaises(ParseError, self.parse, text)
def test_parse_repeat_no_need_reschedule(self):
text = '每月20号提醒我还信用卡'
_now = remind.now()
remind.now = lambda: _now.replace(day=1)
reminder = self.parse(text)
self.assertEqual(reminder.desc, text)
self.assertEqual(reminder.title(), '还信用卡')
self.assertEqual(reminder.get_repeat_text(), '每月')
<|code_end|>
. Use current file imports:
(import unittest
from dateutil.relativedelta import relativedelta
from django.utils import timezone
from django.test import TestCase
from ..todo_parser.local_parser import LocalParser, parse_cn_number, DEFAULT_HOUR, ParseError
from remind.models import remind)
and context including class names, function names, or small code snippets from other files:
# Path: WeCron/wxhook/todo_parser/local_parser.py
# CN_NUM = {
# u'〇': 0,
# u'一': 1,
# u'二': 2,
# u'三': 3,
# u'四': 4,
# u'五': 5,
# u'六': 6,
# u'七': 7,
# u'八': 8,
# u'九': 9,
#
# u'零': 0,
# u'壹': 1,
# u'贰': 2,
# u'叁': 3,
# u'肆': 4,
# u'伍': 5,
# u'陆': 6,
# u'柒': 7,
# u'捌': 8,
# u'玖': 9,
#
# u'貮': 2,
# u'两': 2,
# }
# CN_UNIT = {
# u'十': 10,
# u'拾': 10,
# u'百': 100,
# u'佰': 100,
# u'千': 1000,
# u'仟': 1000,
# u'万': 10000,
# u'萬': 10000,
# u'亿': 100000000,
# u'億': 100000000,
# u'兆': 1000000000000,
# }
# DEFAULT_HOUR = 8
# DEFAULT_MINUTE = 0
# def parse_cn_number(cn_sentence):
# def __init__(self):
# def parse_by_rules(self, text):
# def consume_repeat(self):
# def consume_year(self):
# def consume_month(self):
# def consume_day(self):
# def consume_hour(self):
# def consume_minute(self):
# def consume_second(self):
# def exclude_time_range(self, next_expectation):
# def consume_year_period(self):
# def consume_month_period(self):
# def consume_day_period(self):
# def consume_weekday_period(self):
# def consume_hour_period(self):
# def consume_minute_period(self):
# def consume_second_period(self):
# def consume_to_end(self):
# def consume_word(self, *words):
# def consume_phrase(self, *words):
# def consume_digit(self, consume=True):
# def current_word(self):
# def current_tag(self):
# def peek_next_word(self, step=1):
# def get_index(self):
# def set_index(self, idx):
# def has_next(self):
# def advance(self, step=1):
# class LocalParser(object):
. Output only the next line. | self.assertEqual(self.now.month, reminder.time.month) |
Continue the code snippet: <|code_start|> def test_parse_hour_period_with_half(self):
text = '两个半小时后提醒我'
reminder = self.parse(text)
self.assertEqual(reminder.desc, text)
self.assertEqual(reminder.title(), '闹钟')
self.assertAlmostEqual((reminder.time - self.now).seconds, 150 * 60, delta=2)
def test_parse_hour_period_with_only_half(self):
text = '半小时后提醒我同步'
reminder = self.parse(text)
self.assertEqual(reminder.desc, text)
self.assertEqual(reminder.title(), '同步')
self.assertAlmostEqual((reminder.time - self.now).seconds, 30 * 60, delta=2)
self.setUp()
text = '半个钟头后提醒我同步'
reminder = self.parse(text)
self.assertEqual(reminder.desc, text)
self.assertEqual(reminder.title(), '同步')
self.assertAlmostEqual((reminder.time - self.now).seconds, 30 * 60, delta=2)
def test_parse_day_period(self):
text = '明天九点58提醒秒杀流量'
reminder = self.parse(text)
self.assertEqual(reminder.desc, text)
self.assertEqual(reminder.title(), '秒杀流量')
self.assertEqual((self.now + relativedelta(days=1)).day, reminder.time.day)
self.assertEquals(reminder.time.hour, 9)
self.assertEquals(reminder.time.minute, 58)
def test_parse_day_period_with_half(self):
<|code_end|>
. Use current file imports:
import unittest
from dateutil.relativedelta import relativedelta
from django.utils import timezone
from django.test import TestCase
from ..todo_parser.local_parser import LocalParser, parse_cn_number, DEFAULT_HOUR, ParseError
from remind.models import remind
and context (classes, functions, or code) from other files:
# Path: WeCron/wxhook/todo_parser/local_parser.py
# CN_NUM = {
# u'〇': 0,
# u'一': 1,
# u'二': 2,
# u'三': 3,
# u'四': 4,
# u'五': 5,
# u'六': 6,
# u'七': 7,
# u'八': 8,
# u'九': 9,
#
# u'零': 0,
# u'壹': 1,
# u'贰': 2,
# u'叁': 3,
# u'肆': 4,
# u'伍': 5,
# u'陆': 6,
# u'柒': 7,
# u'捌': 8,
# u'玖': 9,
#
# u'貮': 2,
# u'两': 2,
# }
# CN_UNIT = {
# u'十': 10,
# u'拾': 10,
# u'百': 100,
# u'佰': 100,
# u'千': 1000,
# u'仟': 1000,
# u'万': 10000,
# u'萬': 10000,
# u'亿': 100000000,
# u'億': 100000000,
# u'兆': 1000000000000,
# }
# DEFAULT_HOUR = 8
# DEFAULT_MINUTE = 0
# def parse_cn_number(cn_sentence):
# def __init__(self):
# def parse_by_rules(self, text):
# def consume_repeat(self):
# def consume_year(self):
# def consume_month(self):
# def consume_day(self):
# def consume_hour(self):
# def consume_minute(self):
# def consume_second(self):
# def exclude_time_range(self, next_expectation):
# def consume_year_period(self):
# def consume_month_period(self):
# def consume_day_period(self):
# def consume_weekday_period(self):
# def consume_hour_period(self):
# def consume_minute_period(self):
# def consume_second_period(self):
# def consume_to_end(self):
# def consume_word(self, *words):
# def consume_phrase(self, *words):
# def consume_digit(self, consume=True):
# def current_word(self):
# def current_tag(self):
# def peek_next_word(self, step=1):
# def get_index(self):
# def set_index(self, idx):
# def has_next(self):
# def advance(self, step=1):
# class LocalParser(object):
. Output only the next line. | text = '明晚八点去看电影' |
Given snippet: <|code_start|># coding: utf-8
from __future__ import unicode_literals, absolute_import
DISPLAY_POST = True
@urlmatch(netloc=r'(.*\.)?mp\.weixin\.qq\.com$', path='.*showqrcode')
def get_qr_image_mock(url, request):
content = open(TPL_IMAGE_PATH, 'rb').read()
headers = {
'Content-Type': 'image/png'
}
return response(200, content, request=request)
class SharePostTestCase(TestCase):
def setUp(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.test import TestCase
from django.utils import timezone
from httmock import urlmatch, response, with_httmock
from common.tests import access_token_mock
from .test_serializers import create_qrcode_mock
from remind.models import Remind
from wechat_user.models import WechatUser
from remind.share_post import draw_post, TPL_IMAGE_PATH
and context:
# Path: WeCron/remind/tests/test_serializers.py
# @urlmatch(netloc=r'(.*\.)?api\.weixin\.qq\.com$', path='.*qrcode/create')
# def create_qrcode_mock(url, request):
# content = {
# 'ticket': 'gQH47joAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL2taZ2Z3TVRtNzJXV1Brb3ZhYmJJAAIEZ23sUwMEmm3sUw==',
# 'expires_in': 30,
# 'url': 'http:\/\/weixin.qq.com\/q\/kZgfwMTm72WWPkovabbI',
# }
# headers = {
# 'Content-Type': 'application/json'
# }
# return response(200, content, headers, request=request)
which might include code, classes, or functions. Output only the next line. | self.user = WechatUser(openid='miao', nickname='miaomiao', subscribe=True, last_login=timezone.now()) |
Given the following code snippet before the placeholder: <|code_start|> DEBUG stdout: # (use "git add <file>..." to update what will be committed)
DEBUG stdout: # (use "git checkout -- <file>..." to discard changes in working directory)
DEBUG stdout: #
DEBUG stdout: # modified: foo4.txt
DEBUG stdout: #
DEBUG stdout: # Untracked files:
DEBUG stdout: # (use "git add <file>..." to include in what will be committed)
DEBUG stdout: #
DEBUG stdout: # untracked_file
'# On branch public/1002/anything\n# Changes to be committed:\n# (use "git reset HEAD <file>..." to unstage)\n#\n#\tnew file: staged_file\n#\n# Changes not staged for commit:\n# (use "git add <file>..." to update what will be committed)\n# (use "git checkout -- <file>..." to discard changes in working directory)\n#\n#\tmodified: foo4.txt\n#\n# Untracked files:\n# (use "git add <file>..." to include in what will be committed)\n#\n#\tuntracked_file\n'
sage: git.execute('status', foo=True) # --foo is not a valid parameter
Traceback (most recent call last):
...
git_trac.git_error.GitError: git returned with non-zero exit code (129)
when executing "git status --foo"
STDERR: error: unknown option `foo'
STDERR: usage: git status [options] [--] <pathspec>...
STDERR:
STDERR: -v, --verbose be verbose
STDERR: -s, --short show status concisely
STDERR: -b, --branch show branch information
STDERR: --porcelain machine-readable output
STDERR: --long show status in long format (default)
STDERR: -z, --null terminate entries with NUL
STDERR: -u, --untracked-files[=<mode>]
STDERR: show untracked files, optional modes: all, normal, no. (Default: all)
STDERR: --ignored show ignored files
STDERR: --ignore-submodules[=<when>]
STDERR: ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)
<|code_end|>
, predict the next line using imports from the current file:
import os
import subprocess
from .git_error import GitError
from .logger import logger
and context including class names, function names, and sometimes code from other files:
# Path: git_trac/git_error.py
# class GitError(RuntimeError):
# r"""
# Error raised when git exits with a non-zero exit code.
#
# EXAMPLES::
#
# sage: from git_trac.git_error import GitError
# sage: raise GitError({'exit_code':128, 'stdout':'', 'stderr':'', 'cmd':'command'})
# Traceback (most recent call last):
# ...
# GitError: git returned with
# non-zero exit code (128) when executing "command"
# """
# def __init__(self, result, explain=None, advice=None):
# r"""
# Initialization.
#
# TESTS::
#
# sage: from git_trac.git_error import GitError
# sage: type(GitError({'exit_code':128, 'stdout':'', 'stderr':'', 'cmd':'command'}))
# <class 'git_trac.git_error.GitError'>
# """
# self.exit_code = result['exit_code']
# self.cmd = result['cmd'].strip()
# def prefix(string, prefix):
# return '\n'.join([prefix + ': ' + line.rstrip() for line in string.splitlines()])
# self.stdout = prefix(result['stdout'], ' STDOUT')
# self.stderr = prefix(result['stderr'], ' STDERR')
# self.explain = explain
# self.advice = advice
# template = 'git returned with non-zero exit code ({0}) when executing "{1}"'
# msg = template.format(self.exit_code, self.cmd)
# if len(self.stdout) != 0:
# msg += '\n' + self.stdout
# if len(self.stderr) != 0:
# msg += '\n' + self.stderr
# RuntimeError.__init__(self, msg)
#
# Path: git_trac/logger.py
# def make_logger(name, doctest_mode=False):
# def enable_doctest_mode():
. Output only the next line. | STDERR: --column[=<style>] list untracked files in columns |
Given snippet: <|code_start|>## -*- encoding: utf-8 -*-
r"""
Git Interface
This module provides a python interface to git. Essentially, it is
a raw wrapper around calls to git and retuns the output as strings.
EXAMPLES::
sage: git.execute('status', porcelain=True)
DEBUG cmd: git status --porcelain
DEBUG stdout: M foo4.txt
DEBUG stdout: A staged_file
DEBUG stdout: ?? untracked_file
' M foo4.txt\nA staged_file\n?? untracked_file\n'
sage: git.status(porcelain=True)
DEBUG cmd: git status --porcelain
DEBUG stdout: M foo4.txt
DEBUG stdout: A staged_file
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import subprocess
from .git_error import GitError
from .logger import logger
and context:
# Path: git_trac/git_error.py
# class GitError(RuntimeError):
# r"""
# Error raised when git exits with a non-zero exit code.
#
# EXAMPLES::
#
# sage: from git_trac.git_error import GitError
# sage: raise GitError({'exit_code':128, 'stdout':'', 'stderr':'', 'cmd':'command'})
# Traceback (most recent call last):
# ...
# GitError: git returned with
# non-zero exit code (128) when executing "command"
# """
# def __init__(self, result, explain=None, advice=None):
# r"""
# Initialization.
#
# TESTS::
#
# sage: from git_trac.git_error import GitError
# sage: type(GitError({'exit_code':128, 'stdout':'', 'stderr':'', 'cmd':'command'}))
# <class 'git_trac.git_error.GitError'>
# """
# self.exit_code = result['exit_code']
# self.cmd = result['cmd'].strip()
# def prefix(string, prefix):
# return '\n'.join([prefix + ': ' + line.rstrip() for line in string.splitlines()])
# self.stdout = prefix(result['stdout'], ' STDOUT')
# self.stderr = prefix(result['stderr'], ' STDERR')
# self.explain = explain
# self.advice = advice
# template = 'git returned with non-zero exit code ({0}) when executing "{1}"'
# msg = template.format(self.exit_code, self.cmd)
# if len(self.stdout) != 0:
# msg += '\n' + self.stdout
# if len(self.stderr) != 0:
# msg += '\n' + self.stderr
# RuntimeError.__init__(self, msg)
#
# Path: git_trac/logger.py
# def make_logger(name, doctest_mode=False):
# def enable_doctest_mode():
which might include code, classes, or functions. Output only the next line. | DEBUG stdout: ?? untracked_file |
Given the code snippet: <|code_start|>r"""
HTTP transport to the trac server
AUTHORS:
<|code_end|>
, generate the next line using the imports in this file:
import urllib.request
import urllib.parse
from xmlrpc.client import SafeTransport, Fault
from .trac_error import \
TracInternalError, TracAuthenticationError, TracConnectionError
from .cached_property import cached_property
and context (functions, classes, or occasionally code) from other files:
# Path: git_trac/trac_error.py
# class TracInternalError(TracError):
# def __init__(self, fault):
# self._fault = fault
# self.faultCode = fault.faultCode
#
# def __str__(self):
# return str(self._fault)
#
# class TracAuthenticationError(TracError):
# def __init__(self):
# TracError.__init__(self, 'Authentication with trac server failed.')
#
# class TracConnectionError(TracError):
# def __init__(self, msg=None):
# if msg is None:
# TracError.__init__(self, 'Connection to trac server failed.')
# else:
# TracError.__init__(self, msg)
#
# Path: git_trac/cached_property.py
# class cached_property(object):
#
# def __init__(self, method, name=None):
# self.method = method
# self.name = name or method.__name__
# self.__doc__ = method.__doc__
#
# def __get__(self, instance, cls):
# if instance is None:
# return self
# result = self.method(instance)
# setattr(instance, self.name, result)
# return result
. Output only the next line. | - David Roe, Julian Rueth, Robert Bradshaw: initial version |
Given the following code snippet before the placeholder: <|code_start|>
exconf = {
"environment" : "devel",
"container" : { 'docker' : { 'image' : "python:2.7" } },
"name" : "TESTJOB",
"service" : False,
<|code_end|>
, predict the next line using imports from the current file:
from gen.apache.aurora.api.ttypes import *
from gen.apache.aurora.api.constants import AURORA_EXECUTOR_NAME
import munch
and context including class names, function names, and sometimes code from other files:
# Path: gen/apache/aurora/api/constants.py
# AURORA_EXECUTOR_NAME = "AuroraExecutor"
. Output only the next line. | "max_task_failures" : 1, |
Using the snippet: <|code_start|>
class RandomTest(unittest.TestCase):
def test_distribution(self):
d = Random.Distribution()
expected = {
'high': 256,
'low': 0,
'mode': None,
'name': 'triangular',
'scale': 1,
}
self.assertEqual(d.vars(), expected)
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from BiblioPixelAnimations.simple import Random
and context (class names, function names, or code) available:
# Path: BiblioPixelAnimations/simple/Random.py
# class Random(Animation):
# """
# Randomly set the color
# """
# def __init__(self, *args, distribution=None, every=0, count=0, levels=None,
# **kwds):
# super().__init__(*args, **kwds)
# self.distribution = Distribution(**(distribution or {}))
# self.count = count
# self.every = every
# self.levels = levels or [1, 1, 1]
#
# def step(self, amt=1):
# if not (self.every and self.cur_step % self.every):
# indexes = range(len(self.color_list))
# if self.count:
# indexes = random.sample(indexes, self.count)
# d = self.distribution
# r, g, b = self.levels
# for i in indexes:
# self.color_list[i] = (r * d(), g * d(), b * d())
. Output only the next line. | N = 100 |
Predict the next line after this snippet: <|code_start|> self.coordinates = (min_real+1j*min_imag, max_real+1j*min_imag,
max_real+1j*max_imag, min_real+1j*max_imag)
def __iter__(self):
"""
Returns
-------
gen: generator
A generator which yields (s, w), where s is the complex frequency
and w is the integration weight
"""
# integrate over all 4 lines
for line_count in range(4):
s_start = self.coordinates[line_count]
s_end = self.coordinates[(line_count+1) % 4]
ds = s_end-s_start
for x, w in self.integration_rule:
s = s_start + ds*x
yield(s, w*ds)
def __len__(self):
return 4*len(self.integration_rule)
class ExternalModeContour(Contour):
"""A modified rectangular contour which finds external modes of objects,
including on the negative real axis, but avoids internal modes on the
imaginary axis, and takes a detour about the origin"""
def __init__(self, corner, integration_rule=GaussLegendreRule(20),
<|code_end|>
using the current file's imports:
import numpy as np
import numpy.linalg as la
import scipy.special
from openmodes.helpers import Identified
from openmodes.external.point_in_polygon import wn_PnPoly
from openmodes import dunavant
and any relevant context from other files:
# Path: openmodes/helpers.py
# class Identified(object):
# """An object which can be uniquely identified by an id number. It is
# assumed that any object which subclasses Identified is immutable, so that
# its id can be used for caching complex results which depend on this object.
# """
#
# def __init__(self):
# self.id = uuid.uuid4()
#
# def __hash__(self):
# return self.id.__hash__()
#
# def __eq__(self, other):
# return hasattr(other, 'id') and (self.id == other.id)
#
# def __repr__(self):
# "Represent the object by its id, in addition to its memory address"
# return ("<%s at 0x%08x with id %s>" % (str(self.__class__)[8:-2],
# id(self),
# str(self.id)))
#
# Path: openmodes/external/point_in_polygon.py
# def wn_PnPoly(P, V):
# wn = 0 # the winding number counter
#
# # repeat the first vertex at end
# V = tuple(V[:]) + (V[0],)
#
# # loop through all edges of the polygon
# for i in range(len(V)-1): # edge from V[i] to V[i+1]
# if V[i][1] <= P[1]: # start y <= P[1]
# if V[i+1][1] > P[1]: # an upward crossing
# if is_left(V[i], V[i+1], P) > 0: # P left of edge
# wn += 1 # have a valid up intersect
# else: # start y > P[1] (no test needed)
# if V[i+1][1] <= P[1]: # a downward crossing
# if is_left(V[i], V[i+1], P) < 0: # P right of edge
# wn -= 1 # have a valid down intersect
# return wn
. Output only the next line. | overlap_axes=None, avoid_origin=None): |
Next line prediction: <|code_start|> self.coordinates = (min_real+1j*min_imag, max_real+1j*min_imag,
max_real+1j*max_imag, min_real+1j*max_imag)
def __iter__(self):
"""
Returns
-------
gen: generator
A generator which yields (s, w), where s is the complex frequency
and w is the integration weight
"""
# integrate over all 4 lines
for line_count in range(4):
s_start = self.coordinates[line_count]
s_end = self.coordinates[(line_count+1) % 4]
ds = s_end-s_start
for x, w in self.integration_rule:
s = s_start + ds*x
yield(s, w*ds)
def __len__(self):
return 4*len(self.integration_rule)
class ExternalModeContour(Contour):
"""A modified rectangular contour which finds external modes of objects,
including on the negative real axis, but avoids internal modes on the
imaginary axis, and takes a detour about the origin"""
def __init__(self, corner, integration_rule=GaussLegendreRule(20),
<|code_end|>
. Use current file imports:
(import numpy as np
import numpy.linalg as la
import scipy.special
from openmodes.helpers import Identified
from openmodes.external.point_in_polygon import wn_PnPoly
from openmodes import dunavant)
and context including class names, function names, or small code snippets from other files:
# Path: openmodes/helpers.py
# class Identified(object):
# """An object which can be uniquely identified by an id number. It is
# assumed that any object which subclasses Identified is immutable, so that
# its id can be used for caching complex results which depend on this object.
# """
#
# def __init__(self):
# self.id = uuid.uuid4()
#
# def __hash__(self):
# return self.id.__hash__()
#
# def __eq__(self, other):
# return hasattr(other, 'id') and (self.id == other.id)
#
# def __repr__(self):
# "Represent the object by its id, in addition to its memory address"
# return ("<%s at 0x%08x with id %s>" % (str(self.__class__)[8:-2],
# id(self),
# str(self.id)))
#
# Path: openmodes/external/point_in_polygon.py
# def wn_PnPoly(P, V):
# wn = 0 # the winding number counter
#
# # repeat the first vertex at end
# V = tuple(V[:]) + (V[0],)
#
# # loop through all edges of the polygon
# for i in range(len(V)-1): # edge from V[i] to V[i+1]
# if V[i][1] <= P[1]: # start y <= P[1]
# if V[i+1][1] > P[1]: # an upward crossing
# if is_left(V[i], V[i+1], P) > 0: # P left of edge
# wn += 1 # have a valid up intersect
# else: # start y > P[1] (no test needed)
# if V[i+1][1] <= P[1]: # a downward crossing
# if is_left(V[i], V[i+1], P) < 0: # P right of edge
# wn -= 1 # have a valid down intersect
# return wn
. Output only the next line. | overlap_axes=None, avoid_origin=None): |
Given the code snippet: <|code_start|># OpenModes - An eigenmode solver for open electromagnetic resonantors
# Copyright (C) 2013 David Powell
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
#-----------------------------------------------------------------------------
"""This module contains most of the matrix construction routines which are
fully specific to RWG and related basis functions"""
def impedance_curl_G(s, integration_rule, basis_o, nodes_o, basis_s, nodes_s,
normals, self_impedance, epsilon, mu, num_singular_terms,
singularity_accuracy, tangential_form):
"""Calculates the impedance matrix corresponding to the equation:
fm . curl(G) . fn
for RWG and related basis functions"""
transform_o, _ = basis_o.transformation_matrices
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from openmodes.operator.singularities import singular_impedance_rwg
from openmodes.core import z_mfie_faces_self, z_mfie_faces_mutual
from openmodes.core import z_efie_faces_self, z_efie_faces_mutual
from openmodes.constants import pi, c
and context (functions, classes, or occasionally code) from other files:
# Path: openmodes/operator/singularities.py
# def singular_impedance_rwg(basis, num_terms, rel_tol, normals):
# """Precalculate the singular impedance terms for an object
#
# Parameters
# ----------
# basis: LinearTriangleBasis object
# The basis functions representing the object for which to calculate the
# singularities
# num_terms: integer
# The number of singular terms to extract
# rel_tol: float
# The desired relative tolerance of the singular integrals
# normals: ndarray(num_triangles, 3) of float, optional
# The surface normals, required for n x operator forms
#
# Returns
# -------
# singular_terms : dictionary of SingularSparse object
# Each key "T_EFIE", "T_MFIE" and "N_MFIE" has a value withthe sparse
# array of singular impedance terms for that operator
# """
#
# if not isinstance(basis, LinearTriangleBasis):
# raise ValueError("Basis functions are not RWG based")
#
# # Check if this part's singularities have previously been calculated
# # Note that higher accuracy calculations will not be used if a lower
# # accuracy is requested. This avoids non-deterministic behaviour.
# normals_hash = hashlib.sha1(normals).hexdigest()
# unique_id = ("RWG", basis.id, rel_tol, normals_hash, num_terms)
# if unique_id in cached_singular_terms:
# return cached_singular_terms[unique_id]
#
# sharing_nodes = basis.mesh.triangles_sharing_nodes()
#
# # slightly inefficient reordering and resizing of nodes array
# polygons = np.ascontiguousarray(basis.mesh.polygons)
# nodes = np.ascontiguousarray(basis.mesh.nodes, dtype=np.float64)
# num_faces = len(polygons)
#
# singular_terms = {"T_EFIE": MultiSparse([(np.float64, (num_terms,)), # phi
# (np.float64, (num_terms, 3, 3))]), # A
# "T_MFIE": MultiSparse([(np.float64, (num_terms, 3, 3))]), # A
# "N_MFIE": MultiSparse([(np.float64, (num_terms, 3, 3))]), # A
# }
#
# logging.info("Integrating singular terms for basis function %s, with %d "
# "terms, relative tolerance %e" % (basis, num_terms, rel_tol))
#
# # find the neighbouring triangles (including self terms) to integrate
# # singular part
# for p in range(0, num_faces): # observer
# sharing_triangles = set()
# for node in polygons[p]:
# sharing_triangles = sharing_triangles.union(sharing_nodes[node])
# # find any neighbouring elements which are touching
# for q in sharing_triangles: # source
# # at least one node is shared between p and q
# normal = normals[p]
# res = face_integrals_yla_oijala(nodes[polygons[q]], rule.points, rule.weights,
# nodes[polygons[p]], normal_o=normal)
# if q != p:
# # The self triangle terms are not evaluated for MFIE
# singular_terms["T_MFIE"][p, q] = (res[3],)
# singular_terms["N_MFIE"][p, q] = (res[2],)
# singular_terms["T_EFIE"][p, q] = (res[1], res[0])
#
# # Arrays are currently put into fortran order, under the assumption
# # that they will mostly be used by fortran routines.
# cached_singular_terms[unique_id] = {k: v.to_csr(order='F')
# for k, v in singular_terms.items()}
# return cached_singular_terms[unique_id]
#
# Path: openmodes/constants.py
. Output only the next line. | num_faces_o = len(basis_o.mesh.polygons) |
Predict the next line for this snippet: <|code_start|>
transform_s = transform_o
else:
# calculate mutual impedance
num_faces_s = len(basis_s.mesh.polygons)
res = z_mfie_faces_mutual(nodes_o, basis_o.mesh.polygons,
nodes_s, basis_s.mesh.polygons,
gamma_0, integration_rule.points,
integration_rule.weights, normals,
tangential_form)
transform_s, _ = basis_s.transformation_matrices
Z_faces, Z_dgamma_faces = res
if np.any(np.isnan(Z_faces)):
raise ValueError("NaN returned in impedance matrix")
if np.any(np.isnan(Z_dgamma_faces)):
raise ValueError("NaN returned in impedance matrix derivative")
Z = transform_o.dot(transform_s.dot(Z_faces.reshape(num_faces_o*3,
num_faces_s*3,
order='C').T).T)
Z_dgamma = transform_o.dot(transform_s.dot(Z_dgamma_faces.reshape(num_faces_o*3,
num_faces_s*3,
<|code_end|>
with the help of current file imports:
import numpy as np
from openmodes.operator.singularities import singular_impedance_rwg
from openmodes.core import z_mfie_faces_self, z_mfie_faces_mutual
from openmodes.core import z_efie_faces_self, z_efie_faces_mutual
from openmodes.constants import pi, c
and context from other files:
# Path: openmodes/operator/singularities.py
# def singular_impedance_rwg(basis, num_terms, rel_tol, normals):
# """Precalculate the singular impedance terms for an object
#
# Parameters
# ----------
# basis: LinearTriangleBasis object
# The basis functions representing the object for which to calculate the
# singularities
# num_terms: integer
# The number of singular terms to extract
# rel_tol: float
# The desired relative tolerance of the singular integrals
# normals: ndarray(num_triangles, 3) of float, optional
# The surface normals, required for n x operator forms
#
# Returns
# -------
# singular_terms : dictionary of SingularSparse object
# Each key "T_EFIE", "T_MFIE" and "N_MFIE" has a value withthe sparse
# array of singular impedance terms for that operator
# """
#
# if not isinstance(basis, LinearTriangleBasis):
# raise ValueError("Basis functions are not RWG based")
#
# # Check if this part's singularities have previously been calculated
# # Note that higher accuracy calculations will not be used if a lower
# # accuracy is requested. This avoids non-deterministic behaviour.
# normals_hash = hashlib.sha1(normals).hexdigest()
# unique_id = ("RWG", basis.id, rel_tol, normals_hash, num_terms)
# if unique_id in cached_singular_terms:
# return cached_singular_terms[unique_id]
#
# sharing_nodes = basis.mesh.triangles_sharing_nodes()
#
# # slightly inefficient reordering and resizing of nodes array
# polygons = np.ascontiguousarray(basis.mesh.polygons)
# nodes = np.ascontiguousarray(basis.mesh.nodes, dtype=np.float64)
# num_faces = len(polygons)
#
# singular_terms = {"T_EFIE": MultiSparse([(np.float64, (num_terms,)), # phi
# (np.float64, (num_terms, 3, 3))]), # A
# "T_MFIE": MultiSparse([(np.float64, (num_terms, 3, 3))]), # A
# "N_MFIE": MultiSparse([(np.float64, (num_terms, 3, 3))]), # A
# }
#
# logging.info("Integrating singular terms for basis function %s, with %d "
# "terms, relative tolerance %e" % (basis, num_terms, rel_tol))
#
# # find the neighbouring triangles (including self terms) to integrate
# # singular part
# for p in range(0, num_faces): # observer
# sharing_triangles = set()
# for node in polygons[p]:
# sharing_triangles = sharing_triangles.union(sharing_nodes[node])
# # find any neighbouring elements which are touching
# for q in sharing_triangles: # source
# # at least one node is shared between p and q
# normal = normals[p]
# res = face_integrals_yla_oijala(nodes[polygons[q]], rule.points, rule.weights,
# nodes[polygons[p]], normal_o=normal)
# if q != p:
# # The self triangle terms are not evaluated for MFIE
# singular_terms["T_MFIE"][p, q] = (res[3],)
# singular_terms["N_MFIE"][p, q] = (res[2],)
# singular_terms["T_EFIE"][p, q] = (res[1], res[0])
#
# # Arrays are currently put into fortran order, under the assumption
# # that they will mostly be used by fortran routines.
# cached_singular_terms[unique_id] = {k: v.to_csr(order='F')
# for k, v in singular_terms.items()}
# return cached_singular_terms[unique_id]
#
# Path: openmodes/constants.py
, which may contain function names, class names, or code. Output only the next line. | order='C').T).T) |
Predict the next line for this snippet: <|code_start|>
from __future__ import division
def part_ranges_lowest(parent_part, basis_container):
"""Construct the slice objects for the parent part, iterating down only
to the specified lowest level"""
lowest = getattr(basis_container, 'lowest_parts', None)
# get the size of each child part
sizes = [len(basis_container[part]) for part in parent_part.iter_lowest(lowest)]
offsets = np.cumsum([0]+sizes)
ranges = {}
# index of single parts to get the offsets
lowest_part_num = 0
# iterate with parents last, so they can get data from their child objects
for part in parent_part.iter_lowest(lowest, parent_order='after'):
if part in lowest:
ranges[part] = slice(offsets[lowest_part_num], offsets[lowest_part_num+1])
lowest_part_num += 1
else:
# take slice information from first and last child
start = ranges[part.children[0]].start
stop = ranges[part.children[-1]].stop
<|code_end|>
with the help of current file imports:
import numpy as np
import numbers
import collections
import six
import warnings
from openmodes.parts import Part
and context from other files:
# Path: openmodes/parts.py
# class Part(Identified):
# """A part which has been placed into the simulation, and which can be
# modified"""
#
# def __init__(self, location=None):
# super(Part, self).__init__()
#
# self.initial_location = location
# self.transformation_matrix = np.empty((4, 4))
# self.reset()
# self.parent_ref = None
#
# def reset(self):
# """Reset this part to the default values of the original `Mesh`
# from which this `Part` was created, and move it to its initial
# location (the origin if not specified).
# """
# self.transformation_matrix[:] = np.eye(4)
# if self.initial_location is not None:
# self.translate(self.initial_location)
# self._position_updated()
#
# def _position_updated(self):
# "Called when position is updated"
# pass
#
# @property
# def complete_transformation(self):
# """The complete transformation matrix, which takes into account
# the transformation matrix of all parents"""
# if self.parent_ref is None:
# return self.transformation_matrix
# else:
# return self.parent_ref().complete_transformation.dot(
# self.transformation_matrix)
#
# def translate(self, offset_vector):
# """Translate a part by an arbitrary offset vector
#
# Care needs to be take if this puts an object in a different layer
# """
# translation = np.eye(4)
# translation[:3, 3] = offset_vector
#
# self.transformation_matrix[:] = translation.dot(
# self.transformation_matrix)
# self._position_updated()
#
# def rotate(self, axis, angle):
# """
# Rotate about an arbitrary axis
#
# Parameters
# ----------
# axis : ndarray
# the vector about which to rotate
# angle : number
# angle of rotation in degrees
#
# Algorithm taken from
# http://en.wikipedia.org/wiki/Euler%E2%80%93Rodrigues_parameters
# """
#
# # TODO: enable rotation about arbitrary coordinates, and about the
# # centre of the object
#
# axis = np.array(axis, np.float64)
# axis /= np.sqrt(np.dot(axis, axis))
#
# angle = angle*np.pi/180.0
#
# a = np.cos(0.5*angle)
# b, c, d = axis*np.sin(0.5*angle)
#
# matrix = np.array([[a**2 + b**2 - c**2 - d**2,
# 2*(b*c - a*d), 2*(b*d + a*c), 0],
# [2*(b*c + a*d), a**2 + c**2 - b**2 - d**2,
# 2*(c*d - a*b), 0],
# [2*(b*d - a*c), 2*(c*d + a*b),
# a**2 + d**2 - b**2 - c**2, 0],
# [0, 0, 0, 1.0]])
#
# self.transformation_matrix[:] = matrix.dot(self.transformation_matrix)
# self._position_updated()
, which may contain function names, class names, or code. Output only the next line. | ranges[part] = slice(start, stop) |
Given the following code snippet before the placeholder: <|code_start|> return edges_array
def triangles_sharing_nodes(self):
"""Return a set of all the triangles which share each node"""
polygons = [OrderedSet() for _ in range(len(self.nodes))]
for count, t_nodes in enumerate(self.polygons):
# tell each node that it is a part of this triangle
for node in t_nodes:
polygons[node].add(count)
return polygons
@property
def shortest_edge(self):
"""The shortest edge in the mesh"""
return self.edge_lens.min()
@property
def max_distance(self):
"""The furthest distance between any two nodes in this mesh"""
return np.sqrt(np.sum((self.nodes[:, None, :] -
self.nodes[None, :, :])**2, axis=2)).max()
def fast_size(self):
"""A fast estimate of the size of the mesh, based on the maximum
distance along any of the three cartesian axes"""
return max(np.max(self.nodes, axis=0)-np.min(self.nodes, axis=0))
<|code_end|>
, predict the next line using imports from the current file:
import logging
import numpy as np
from openmodes.helpers import Identified, cached_property
from openmodes.external.ordered_set import OrderedSet
from collections import OrderedDict
and context including class names, function names, and sometimes code from other files:
# Path: openmodes/helpers.py
# class Identified(object):
# """An object which can be uniquely identified by an id number. It is
# assumed that any object which subclasses Identified is immutable, so that
# its id can be used for caching complex results which depend on this object.
# """
#
# def __init__(self):
# self.id = uuid.uuid4()
#
# def __hash__(self):
# return self.id.__hash__()
#
# def __eq__(self, other):
# return hasattr(other, 'id') and (self.id == other.id)
#
# def __repr__(self):
# "Represent the object by its id, in addition to its memory address"
# return ("<%s at 0x%08x with id %s>" % (str(self.__class__)[8:-2],
# id(self),
# str(self.id)))
#
# class cached_property(object):
# """
# A property that is only computed once per instance and then replaces itself
# with an ordinary attribute. Deleting the attribute resets the property.
#
# Taken from https://github.com/pydanny/cached-property/blob/master/cached_property.py
# Original source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76
# Copyright under MIT License
# """
#
# def __init__(self, func):
# self.__doc__ = getattr(func, '__doc__')
# self.func = func
#
# def __get__(self, obj, cls):
# if obj is None:
# return self
# value = obj.__dict__[self.func.__name__] = self.func(obj)
# return value
. Output only the next line. | @property |
Predict the next line for this snippet: <|code_start|> np.roll(vertices, 2, axis=1))**2, axis=2))
@cached_property
def closed_surface(self):
"""Whether the mesh represents a closed surface corresponding to a
solid object"""
edges, triangles_shared_by_edges = self.get_edges(True)
sharing_count = np.array([len(n) for n in triangles_shared_by_edges])
return np.all(sharing_count == 2)
def combine_mesh(meshes, nodes=None):
"""Combine several meshes into one, optionally overriding their node
locations"""
mesh_class = type(meshes[0])
all_nodes = []
all_polygons = []
node_offset = 0
# using existing mesh nodes if not overridden
if nodes is None:
nodes = [mesh.nodes for mesh in meshes]
for mesh, current_nodes in zip(meshes, nodes):
if type(mesh) != mesh_class:
raise TypeError("Cannot combine meshes of different types")
all_nodes.append(current_nodes)
<|code_end|>
with the help of current file imports:
import logging
import numpy as np
from openmodes.helpers import Identified, cached_property
from openmodes.external.ordered_set import OrderedSet
from collections import OrderedDict
and context from other files:
# Path: openmodes/helpers.py
# class Identified(object):
# """An object which can be uniquely identified by an id number. It is
# assumed that any object which subclasses Identified is immutable, so that
# its id can be used for caching complex results which depend on this object.
# """
#
# def __init__(self):
# self.id = uuid.uuid4()
#
# def __hash__(self):
# return self.id.__hash__()
#
# def __eq__(self, other):
# return hasattr(other, 'id') and (self.id == other.id)
#
# def __repr__(self):
# "Represent the object by its id, in addition to its memory address"
# return ("<%s at 0x%08x with id %s>" % (str(self.__class__)[8:-2],
# id(self),
# str(self.id)))
#
# class cached_property(object):
# """
# A property that is only computed once per instance and then replaces itself
# with an ordinary attribute. Deleting the attribute resets the property.
#
# Taken from https://github.com/pydanny/cached-property/blob/master/cached_property.py
# Original source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76
# Copyright under MIT License
# """
#
# def __init__(self, func):
# self.__doc__ = getattr(func, '__doc__')
# self.func = func
#
# def __get__(self, obj, cls):
# if obj is None:
# return self
# value = obj.__dict__[self.func.__name__] = self.func(obj)
# return value
, which may contain function names, class names, or code. Output only the next line. | all_polygons.append(mesh.polygons+node_offset) |
Continue the code snippet: <|code_start|># 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 this program. If not, see <http://www.gnu.org/licenses/>.
#-----------------------------------------------------------------------------
"""Calculate multipole decompositions"""
def multipole_fixed(max_l, points):
"""Calculate all frequency-independent quantities for the multipole
decomposition.
These depend only on the coordinates of the points, and need only be
calculated once for each object and reused at multiple frequencies"""
num_l = max_l + 1
l = np.arange(num_l)[:, None]
m_pos = np.arange(num_l)[None, :]
m = np.hstack((m_pos, np.arange(-max_l, 0)[None, :]))
r = np.sqrt(np.sum(points**2, axis=1))
theta = np.arccos(points[:, 2]/r)
phi = np.arctan2(points[:, 1], points[:, 0])
st = np.sin(theta)
ct = np.cos(theta)
<|code_end|>
. Use current file imports:
import numpy as np
import scipy.special
from scipy.special import factorial
from openmodes.constants import eta_0
and context (classes, functions, or code) from other files:
# Path: openmodes/constants.py
. Output only the next line. | sp = np.sin(phi) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Created on Wed Jun 18 16:12:15 2014
@author: dap124
"""
from __future__ import print_function
def test_pickling_references():
"""Test that references to parent objects survive the pickling and
upickling process"""
def save():
name = "SRR"
mesh_tol = 1e-3
sim = openmodes.Simulation(name=name)
mesh = sim.load_mesh(osp.join(openmodes.geometry_dir, name+'.geo'),
<|code_end|>
using the current file's imports:
import openmodes
import os
import os.path as osp
import dill as pickle
import tempfile
import numpy as np
from openmodes.sources import PlaneWaveSource
and any relevant context from other files:
# Path: openmodes/sources.py
# class PlaneWaveSource(object):
# def __init__(self, e_inc, k_hat, material=FreeSpace, p_inc=None):
# """Generate a plane wave with a given direction of propagation and
# magnitude and direction of the electric field
#
# Parameters
# ----------
# e_inc: ndarray[3]
# Incident field polarisation in free space
# k_hat: ndarray[3], real
# Incident wave vector in free space
# n: real, optional
# Refractive index of the background medium, defaults to free space
# eta: real, optional
# Characteristic impedance of background medium, defaults to free
# space
# p_inc: real, optional
# If specified, the incident power will be scaled to ensure constant
# power.
# """
#
# self.e_inc = np.asarray(e_inc)
# k_hat = np.asarray(k_hat)
# self.k_hat = k_hat/np.sqrt(np.dot(k_hat, k_hat))
# self.material = material
# self.h_inc = np.cross(k_hat, self.e_inc) # unscaled
# self.p_inc = p_inc
#
# def electric_field(self, s, r):
# """Calculate the electric field distribution at a given frequency
#
# Parameters
# ----------
# s : complex
# Complex frequency at which to evaluate fields
# r : ndarray, real
# The locations at which to calculate the field. This array can have
# an arbitrary number of dimensions. The last dimension must of size
# 3, corresponding to the three cartesian coordinates
#
# Returns
# -------
# E : ndarray, complex
# An array with the same dimensions as r, giving the field at each
# point
# """
# jk = self.k_hat*self.material.n(s)*s/c
#
# e_inc = self.e_inc
#
# if self.p_inc is not None:
# # scale the incident power if requested
# h_inc = self.h_inc/self.material.eta(s)
# p_unscaled = np.sqrt(np.sum(np.cross(e_inc, h_inc.conj()).real)**2)
# e_inc = e_inc*np.sqrt(self.p_inc/p_unscaled)
#
# # Dimensions are expanded so that r can have an arbitrary number
# # of dimensions
# return e_inc*np.exp(np.dot(r, -jk))[..., None]
#
# def magnetic_field(self, s, r):
# """Calculate the magnetic field distribution at a given frequency
#
# Parameters
# ----------
# s : complex
# Complex frequency at which to evaluate fields
# r : ndarray, real
# The locations at which to calculate the field. This array can have
# an arbitrary number of dimensions. The last dimension must of size
# 3, corresponding to the three cartesian coordinates
#
# Returns
# -------
# E : ndarray, complex
# An array with the same dimensions as r, giving the field at each
# point
# """
# jk = self.k_hat*self.material.n(s)*s/c
#
# h_inc = self.h_inc/self.material.eta(s)
# if self.p_inc is not None:
# # scale the incident power if requested
# h_inc = self.h_inc/self.material.eta(s)
# p_unscaled = np.sqrt(np.sum(np.cross(self.e_inc, h_inc.conj()).real)**2)
# h_inc = h_inc*np.sqrt(self.p_inc/p_unscaled)
#
# return h_inc*np.exp(np.dot(r, -jk))[..., None]
. Output only the next line. | mesh_tol=mesh_tol) |
Given snippet: <|code_start|> 2*(c*d - a*b), 0],
[2*(b*d - a*c), 2*(c*d + a*b),
a**2 + d**2 - b**2 - c**2, 0],
[0, 0, 0, 1.0]])
self.transformation_matrix[:] = matrix.dot(self.transformation_matrix)
self._position_updated()
class SinglePart(Part):
"""A single part, which corresponds exactly to one set of basis
functions"""
def __init__(self, mesh, material=PecMaterial, location=None):
Part.__init__(self, location)
self.mesh = mesh
self.material = material
# A SinglePart is uniquely identified by its mesh and material. i.e.
# all parts with the same unique_id would have the same modes etc. This
# must be used with care since it does not account for the background
# material (presumably the same for all parts), and it may be
# invalidated by a Green's function for inhomogeneous media.
self.unique_id = (mesh.id, material.id)
@property
def nodes(self):
"The nodes of this part after all transformations have been applied"
transform = self.complete_transformation
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from openmodes.helpers import Identified, PicklableRef
from openmodes.material import PecMaterial
import numpy as np
import uuid
and context:
# Path: openmodes/helpers.py
# class Identified(object):
# """An object which can be uniquely identified by an id number. It is
# assumed that any object which subclasses Identified is immutable, so that
# its id can be used for caching complex results which depend on this object.
# """
#
# def __init__(self):
# self.id = uuid.uuid4()
#
# def __hash__(self):
# return self.id.__hash__()
#
# def __eq__(self, other):
# return hasattr(other, 'id') and (self.id == other.id)
#
# def __repr__(self):
# "Represent the object by its id, in addition to its memory address"
# return ("<%s at 0x%08x with id %s>" % (str(self.__class__)[8:-2],
# id(self),
# str(self.id)))
#
# class PicklableRef(object):
# """A weak reference which can be pickled. This is achieved by
# creating a strong reference to the object at pickling time, then restoring
# the weak reference when unpickling. Note that unless the object being
# referenced is also pickled and referenced after unpickling, the weak
# reference will be dead after unpickling.
# """
#
# def __init__(self, obj, callback=None):
# self.ref = weakref.ref(obj, callback)
#
# def __call__(self):
# return self.ref()
#
# def __getstate__(self):
# return {'ref': self.ref()}
#
# def __setstate__(self, state):
# self.ref = weakref.ref(state['ref'])
#
# Path: openmodes/material.py
# class IsotropicMaterial(Identified):
# def __init__(self, name, epsilon_r, mu_r):
# def eta(self, s):
# def eta_r(self, s):
# def n(self, s):
which might include code, classes, or functions. Output only the next line. | return transform[:3, :3].dot(self.mesh.nodes.T).T + transform[:3, 3] |
Predict the next line after this snippet: <|code_start|>
class SinglePart(Part):
"""A single part, which corresponds exactly to one set of basis
functions"""
def __init__(self, mesh, material=PecMaterial, location=None):
Part.__init__(self, location)
self.mesh = mesh
self.material = material
# A SinglePart is uniquely identified by its mesh and material. i.e.
# all parts with the same unique_id would have the same modes etc. This
# must be used with care since it does not account for the background
# material (presumably the same for all parts), and it may be
# invalidated by a Green's function for inhomogeneous media.
self.unique_id = (mesh.id, material.id)
@property
def nodes(self):
"The nodes of this part after all transformations have been applied"
transform = self.complete_transformation
return transform[:3, :3].dot(self.mesh.nodes.T).T + transform[:3, 3]
def __contains__(self, key):
"""Although a single part is not a container, implementing
`__contains__` allows recursive checking to be greatly simplified"""
return self == key
<|code_end|>
using the current file's imports:
from openmodes.helpers import Identified, PicklableRef
from openmodes.material import PecMaterial
import numpy as np
import uuid
and any relevant context from other files:
# Path: openmodes/helpers.py
# class Identified(object):
# """An object which can be uniquely identified by an id number. It is
# assumed that any object which subclasses Identified is immutable, so that
# its id can be used for caching complex results which depend on this object.
# """
#
# def __init__(self):
# self.id = uuid.uuid4()
#
# def __hash__(self):
# return self.id.__hash__()
#
# def __eq__(self, other):
# return hasattr(other, 'id') and (self.id == other.id)
#
# def __repr__(self):
# "Represent the object by its id, in addition to its memory address"
# return ("<%s at 0x%08x with id %s>" % (str(self.__class__)[8:-2],
# id(self),
# str(self.id)))
#
# class PicklableRef(object):
# """A weak reference which can be pickled. This is achieved by
# creating a strong reference to the object at pickling time, then restoring
# the weak reference when unpickling. Note that unless the object being
# referenced is also pickled and referenced after unpickling, the weak
# reference will be dead after unpickling.
# """
#
# def __init__(self, obj, callback=None):
# self.ref = weakref.ref(obj, callback)
#
# def __call__(self):
# return self.ref()
#
# def __getstate__(self):
# return {'ref': self.ref()}
#
# def __setstate__(self, state):
# self.ref = weakref.ref(state['ref'])
#
# Path: openmodes/material.py
# class IsotropicMaterial(Identified):
# def __init__(self, name, epsilon_r, mu_r):
# def eta(self, s):
# def eta_r(self, s):
# def n(self, s):
. Output only the next line. | def iter_single(self): |
Predict the next line for this snippet: <|code_start|>
def __init__(self, location=None):
super(Part, self).__init__()
self.initial_location = location
self.transformation_matrix = np.empty((4, 4))
self.reset()
self.parent_ref = None
def reset(self):
"""Reset this part to the default values of the original `Mesh`
from which this `Part` was created, and move it to its initial
location (the origin if not specified).
"""
self.transformation_matrix[:] = np.eye(4)
if self.initial_location is not None:
self.translate(self.initial_location)
self._position_updated()
def _position_updated(self):
"Called when position is updated"
pass
@property
def complete_transformation(self):
"""The complete transformation matrix, which takes into account
the transformation matrix of all parents"""
if self.parent_ref is None:
return self.transformation_matrix
else:
<|code_end|>
with the help of current file imports:
from openmodes.helpers import Identified, PicklableRef
from openmodes.material import PecMaterial
import numpy as np
import uuid
and context from other files:
# Path: openmodes/helpers.py
# class Identified(object):
# """An object which can be uniquely identified by an id number. It is
# assumed that any object which subclasses Identified is immutable, so that
# its id can be used for caching complex results which depend on this object.
# """
#
# def __init__(self):
# self.id = uuid.uuid4()
#
# def __hash__(self):
# return self.id.__hash__()
#
# def __eq__(self, other):
# return hasattr(other, 'id') and (self.id == other.id)
#
# def __repr__(self):
# "Represent the object by its id, in addition to its memory address"
# return ("<%s at 0x%08x with id %s>" % (str(self.__class__)[8:-2],
# id(self),
# str(self.id)))
#
# class PicklableRef(object):
# """A weak reference which can be pickled. This is achieved by
# creating a strong reference to the object at pickling time, then restoring
# the weak reference when unpickling. Note that unless the object being
# referenced is also pickled and referenced after unpickling, the weak
# reference will be dead after unpickling.
# """
#
# def __init__(self, obj, callback=None):
# self.ref = weakref.ref(obj, callback)
#
# def __call__(self):
# return self.ref()
#
# def __getstate__(self):
# return {'ref': self.ref()}
#
# def __setstate__(self, state):
# self.ref = weakref.ref(state['ref'])
#
# Path: openmodes/material.py
# class IsotropicMaterial(Identified):
# def __init__(self, name, epsilon_r, mu_r):
# def eta(self, s):
# def eta_r(self, s):
# def n(self, s):
, which may contain function names, class names, or code. Output only the next line. | return self.parent_ref().complete_transformation.dot( |
Continue the code snippet: <|code_start|> channel = self._requestable_channels[type](
props, **args)
self._conn.add_channels([channel], signal=signal)
if handle.get_type() != HANDLE_TYPE_NONE and type in self._channels:
self._channels[type].setdefault(handle, []).append(channel)
return channel
def channel_for_props(self, props, signal=True, **args):
channel = self.existing_channel(props)
"""Return an existing channel with theses properties if it already
exists, otherwhise return a new one"""
if channel:
return channel
else:
return self.create_channel_for_props(props, signal, **args)
# Should use implement_channel_classes instead.
def _implement_channel_class(self, type, make_channel, fixed, available):
"""Implement channel types in the channel manager, and add one channel
class that is retrieved in RequestableChannelClasses.
self.implement_channel_classes and self.set_requestable_channel_classes
should be used instead, as it allows implementing multiple channel
classes."""
warnings.warn('deprecated in favour of implement_channel_classes',
DeprecationWarning)
self._requestable_channels[type] = make_channel
<|code_end|>
. Use current file imports:
import warnings
from telepathy.errors import NotImplemented
from telepathy.interfaces import (CHANNEL_INTERFACE,
CHANNEL_TYPE_CONTACT_LIST)
from telepathy.constants import HANDLE_TYPE_NONE
from telepathy.server.handle import NoneHandle
and context (classes, functions, or code) from other files:
# Path: telepathy/errors.py
#
# Path: telepathy/interfaces.py
# CONN_MGR_INTERFACE = CONNECTION_MANAGER
# CONN_INTERFACE = CONNECTION
# CHANNEL_INTERFACE = CHANNEL
# CHANNEL_HANDLER_INTERFACE = CHANNEL_HANDLER
# CONN_INTERFACE_ALIASING = CONNECTION_INTERFACE_ALIASING
# CONN_INTERFACE_AVATARS = CONNECTION_INTERFACE_AVATARS
# CONN_INTERFACE_CAPABILITIES = CONNECTION_INTERFACE_CAPABILITIES
# CONN_INTERFACE_PRESENCE = CONNECTION_INTERFACE_PRESENCE
# CONN_INTERFACE_RENAMING = CONNECTION_INTERFACE_RENAMING
#
# Path: telepathy/constants.py
# CONNECTION_HANDLE_TYPE_NONE = HANDLE_TYPE_NONE
# CONNECTION_HANDLE_TYPE_CONTACT = HANDLE_TYPE_CONTACT
# CONNECTION_HANDLE_TYPE_ROOM = HANDLE_TYPE_ROOM
# CONNECTION_HANDLE_TYPE_LIST = HANDLE_TYPE_LIST
# CONNECTION_HANDLE_TYPE_USER_CONTACT_GROUP = HANDLE_TYPE_GROUP
#
# Path: telepathy/server/handle.py
# class NoneHandle(Handle):
# def __init__(self):
# Handle.__init__(self, 0, HANDLE_TYPE_NONE, '')
. Output only the next line. | self._channels.setdefault(type, {}) |
Continue the code snippet: <|code_start|># modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
class ChannelManager(object):
def __init__(self, connection):
self._conn = connection
self._requestable_channels = dict()
self._channels = dict()
self._fixed_properties = dict()
self._available_properties = dict()
self._requestables = list()
<|code_end|>
. Use current file imports:
import warnings
from telepathy.errors import NotImplemented
from telepathy.interfaces import (CHANNEL_INTERFACE,
CHANNEL_TYPE_CONTACT_LIST)
from telepathy.constants import HANDLE_TYPE_NONE
from telepathy.server.handle import NoneHandle
and context (classes, functions, or code) from other files:
# Path: telepathy/errors.py
#
# Path: telepathy/interfaces.py
# CONN_MGR_INTERFACE = CONNECTION_MANAGER
# CONN_INTERFACE = CONNECTION
# CHANNEL_INTERFACE = CHANNEL
# CHANNEL_HANDLER_INTERFACE = CHANNEL_HANDLER
# CONN_INTERFACE_ALIASING = CONNECTION_INTERFACE_ALIASING
# CONN_INTERFACE_AVATARS = CONNECTION_INTERFACE_AVATARS
# CONN_INTERFACE_CAPABILITIES = CONNECTION_INTERFACE_CAPABILITIES
# CONN_INTERFACE_PRESENCE = CONNECTION_INTERFACE_PRESENCE
# CONN_INTERFACE_RENAMING = CONNECTION_INTERFACE_RENAMING
#
# Path: telepathy/constants.py
# CONNECTION_HANDLE_TYPE_NONE = HANDLE_TYPE_NONE
# CONNECTION_HANDLE_TYPE_CONTACT = HANDLE_TYPE_CONTACT
# CONNECTION_HANDLE_TYPE_ROOM = HANDLE_TYPE_ROOM
# CONNECTION_HANDLE_TYPE_LIST = HANDLE_TYPE_LIST
# CONNECTION_HANDLE_TYPE_USER_CONTACT_GROUP = HANDLE_TYPE_GROUP
#
# Path: telepathy/server/handle.py
# class NoneHandle(Handle):
# def __init__(self):
# Handle.__init__(self, 0, HANDLE_TYPE_NONE, '')
. Output only the next line. | def close(self): |
Given the code snippet: <|code_start|>#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
class ChannelManager(object):
def __init__(self, connection):
self._conn = connection
self._requestable_channels = dict()
self._channels = dict()
self._fixed_properties = dict()
self._available_properties = dict()
<|code_end|>
, generate the next line using the imports in this file:
import warnings
from telepathy.errors import NotImplemented
from telepathy.interfaces import (CHANNEL_INTERFACE,
CHANNEL_TYPE_CONTACT_LIST)
from telepathy.constants import HANDLE_TYPE_NONE
from telepathy.server.handle import NoneHandle
and context (functions, classes, or occasionally code) from other files:
# Path: telepathy/errors.py
#
# Path: telepathy/interfaces.py
# CONN_MGR_INTERFACE = CONNECTION_MANAGER
# CONN_INTERFACE = CONNECTION
# CHANNEL_INTERFACE = CHANNEL
# CHANNEL_HANDLER_INTERFACE = CHANNEL_HANDLER
# CONN_INTERFACE_ALIASING = CONNECTION_INTERFACE_ALIASING
# CONN_INTERFACE_AVATARS = CONNECTION_INTERFACE_AVATARS
# CONN_INTERFACE_CAPABILITIES = CONNECTION_INTERFACE_CAPABILITIES
# CONN_INTERFACE_PRESENCE = CONNECTION_INTERFACE_PRESENCE
# CONN_INTERFACE_RENAMING = CONNECTION_INTERFACE_RENAMING
#
# Path: telepathy/constants.py
# CONNECTION_HANDLE_TYPE_NONE = HANDLE_TYPE_NONE
# CONNECTION_HANDLE_TYPE_CONTACT = HANDLE_TYPE_CONTACT
# CONNECTION_HANDLE_TYPE_ROOM = HANDLE_TYPE_ROOM
# CONNECTION_HANDLE_TYPE_LIST = HANDLE_TYPE_LIST
# CONNECTION_HANDLE_TYPE_USER_CONTACT_GROUP = HANDLE_TYPE_GROUP
#
# Path: telepathy/server/handle.py
# class NoneHandle(Handle):
# def __init__(self):
# Handle.__init__(self, 0, HANDLE_TYPE_NONE, '')
. Output only the next line. | self._requestables = list() |
Predict the next line after this snippet: <|code_start|>#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
class ChannelManager(object):
def __init__(self, connection):
self._conn = connection
self._requestable_channels = dict()
self._channels = dict()
self._fixed_properties = dict()
self._available_properties = dict()
<|code_end|>
using the current file's imports:
import warnings
from telepathy.errors import NotImplemented
from telepathy.interfaces import (CHANNEL_INTERFACE,
CHANNEL_TYPE_CONTACT_LIST)
from telepathy.constants import HANDLE_TYPE_NONE
from telepathy.server.handle import NoneHandle
and any relevant context from other files:
# Path: telepathy/errors.py
#
# Path: telepathy/interfaces.py
# CONN_MGR_INTERFACE = CONNECTION_MANAGER
# CONN_INTERFACE = CONNECTION
# CHANNEL_INTERFACE = CHANNEL
# CHANNEL_HANDLER_INTERFACE = CHANNEL_HANDLER
# CONN_INTERFACE_ALIASING = CONNECTION_INTERFACE_ALIASING
# CONN_INTERFACE_AVATARS = CONNECTION_INTERFACE_AVATARS
# CONN_INTERFACE_CAPABILITIES = CONNECTION_INTERFACE_CAPABILITIES
# CONN_INTERFACE_PRESENCE = CONNECTION_INTERFACE_PRESENCE
# CONN_INTERFACE_RENAMING = CONNECTION_INTERFACE_RENAMING
#
# Path: telepathy/constants.py
# CONNECTION_HANDLE_TYPE_NONE = HANDLE_TYPE_NONE
# CONNECTION_HANDLE_TYPE_CONTACT = HANDLE_TYPE_CONTACT
# CONNECTION_HANDLE_TYPE_ROOM = HANDLE_TYPE_ROOM
# CONNECTION_HANDLE_TYPE_LIST = HANDLE_TYPE_LIST
# CONNECTION_HANDLE_TYPE_USER_CONTACT_GROUP = HANDLE_TYPE_GROUP
#
# Path: telepathy/server/handle.py
# class NoneHandle(Handle):
# def __init__(self):
# Handle.__init__(self, 0, HANDLE_TYPE_NONE, '')
. Output only the next line. | self._requestables = list() |
Continue the code snippet: <|code_start|># modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
class ChannelManager(object):
def __init__(self, connection):
self._conn = connection
self._requestable_channels = dict()
self._channels = dict()
self._fixed_properties = dict()
self._available_properties = dict()
self._requestables = list()
<|code_end|>
. Use current file imports:
import warnings
from telepathy.errors import NotImplemented
from telepathy.interfaces import (CHANNEL_INTERFACE,
CHANNEL_TYPE_CONTACT_LIST)
from telepathy.constants import HANDLE_TYPE_NONE
from telepathy.server.handle import NoneHandle
and context (classes, functions, or code) from other files:
# Path: telepathy/errors.py
#
# Path: telepathy/interfaces.py
# CONN_MGR_INTERFACE = CONNECTION_MANAGER
# CONN_INTERFACE = CONNECTION
# CHANNEL_INTERFACE = CHANNEL
# CHANNEL_HANDLER_INTERFACE = CHANNEL_HANDLER
# CONN_INTERFACE_ALIASING = CONNECTION_INTERFACE_ALIASING
# CONN_INTERFACE_AVATARS = CONNECTION_INTERFACE_AVATARS
# CONN_INTERFACE_CAPABILITIES = CONNECTION_INTERFACE_CAPABILITIES
# CONN_INTERFACE_PRESENCE = CONNECTION_INTERFACE_PRESENCE
# CONN_INTERFACE_RENAMING = CONNECTION_INTERFACE_RENAMING
#
# Path: telepathy/constants.py
# CONNECTION_HANDLE_TYPE_NONE = HANDLE_TYPE_NONE
# CONNECTION_HANDLE_TYPE_CONTACT = HANDLE_TYPE_CONTACT
# CONNECTION_HANDLE_TYPE_ROOM = HANDLE_TYPE_ROOM
# CONNECTION_HANDLE_TYPE_LIST = HANDLE_TYPE_LIST
# CONNECTION_HANDLE_TYPE_USER_CONTACT_GROUP = HANDLE_TYPE_GROUP
#
# Path: telepathy/server/handle.py
# class NoneHandle(Handle):
# def __init__(self):
# Handle.__init__(self, 0, HANDLE_TYPE_NONE, '')
. Output only the next line. | def close(self): |
Given the following code snippet before the placeholder: <|code_start|> telepathy.CONNECTION_INTERFACE_CAPABILITIES :
lambda x: self.GetCapabilities(x).items(),
telepathy.CONNECTION_INTERFACE_CONTACT_CAPABILITIES :
lambda x: self.GetContactCapabilities(x).items()
}
for interface in supported_interfaces:
interface_attribute = interface + '/' + self.attributes[interface]
results = functions[interface](handles)
for handle, value in results:
ret[int(handle)][interface_attribute] = value
return ret
# from ContactList
def GetContactListAttributes(self, interfaces, hold):
all_handles = []
for (handle_type, handle) in self._handles.keys():
if handle_type == telepathy.HANDLE_TYPE_CONTACT:
all_handles.append(handle)
return self.GetContactAttributes(all_handles, interfaces, hold)
# from Aliasing
def GetAliasFlags(self):
return 0
def GetAliases(self, handles):
self.check_connected()
ret = dbus.Dictionary(signature='us')
for handle_id in handles:
<|code_end|>
, predict the next line using imports from the current file:
import telepathy
import dbus
import hangups
import asyncio #maybe want to use gobject event loop? depends on python+dbus
from .text_channel import HangupsTextChannel
from os.path import expanduser
and context including class names, function names, and sometimes code from other files:
# Path: tphangups/text_channel.py
# class HangupsTextChannel(telepathy.server.ChannelTypeText,
# telepathy.server.ChannelInterfaceChatState):
#
# #TODO probably pass the conversation object from Hangups client
# def __init__(self, conn, manager, props, object_path=None):
# telepathy.server.ChannelTypeText.__init__(self, conn, manager, props,
# object_path=object_path)
#
# self._implement_property_get(telepathy.CHANNEL_INTERFACE_MESSAGES, {
# 'SupportedContentTypes': lambda: ["text/plain"] ,
# 'MessagePartSupportFlags': lambda: 0,
# 'DeliveryReportingSupport': lambda: telepathy.DELIVERY_REPORTING_SUPPORT_FLAG_RECEIVE_FAILURES,
# 'PendingMessages': lambda: dbus.Array(self._pending_messages.values(), signature='aa{sv}')
# })
#
# self._add_immutables({
# 'SupportedContentTypes': telepathy.CHANNEL_INTERFACE_MESSAGES,
# 'MessagePartSupportFlags': telepathy.CHANNEL_INTERFACE_MESSAGES,
# 'DeliveryReportingSupport': telepathy.CHANNEL_INTERFACE_MESSAGES,
# })
#
# @dbus.service.method(telepathy.CHANNEL_TYPE_TEXT, in_signature='us', out_signature='',
# async_callbacks=('_success', '_error'))
# def Send(self, message_type, text, _success, _error):
# print ("NEW MESSAGE " + text)
# self.Received(15, 34234234, 2, 0 , 0, "Hello!")
. Output only the next line. | handle = self.handle(telepathy.HANDLE_TYPE_CONTACT, handle_id) |
Given the code snippet: <|code_start|># Copyright (C) 2005,2006,2009,2010 Collabora Limited
# Copyright (C) 2005,2006 Nokia Corporation
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
class Handle(object):
def __init__(self, id, handle_type, name):
self._id = id
self._type = handle_type
self._name = name
def get_id(self):
return self._id
def __hash__(self):
return self._id.__hash__()
<|code_end|>
, generate the next line using the imports in this file:
from telepathy.constants import HANDLE_TYPE_NONE
and context (functions, classes, or occasionally code) from other files:
# Path: telepathy/constants.py
# CONNECTION_HANDLE_TYPE_NONE = HANDLE_TYPE_NONE
# CONNECTION_HANDLE_TYPE_CONTACT = HANDLE_TYPE_CONTACT
# CONNECTION_HANDLE_TYPE_ROOM = HANDLE_TYPE_ROOM
# CONNECTION_HANDLE_TYPE_LIST = HANDLE_TYPE_LIST
# CONNECTION_HANDLE_TYPE_USER_CONTACT_GROUP = HANDLE_TYPE_GROUP
. Output only the next line. | def __int__(self): |
Here is a snippet: <|code_start|># modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
LEVELS = {
logging.ERROR: DEBUG_LEVEL_ERROR,
logging.FATAL: DEBUG_LEVEL_CRITICAL,
logging.WARNING: DEBUG_LEVEL_WARNING,
logging.INFO: DEBUG_LEVEL_INFO,
logging.DEBUG: DEBUG_LEVEL_DEBUG,
logging.NOTSET: DEBUG_LEVEL_DEBUG
}
DEBUG_MESSAGE_LIMIT = 800
class Debug(_Debug, DBusProperties, logging.Handler):
def __init__(self, conn_manager, root=''):
<|code_end|>
. Write the next line using the current file imports:
from telepathy.interfaces import DEBUG
from telepathy.constants import (DEBUG_LEVEL_ERROR,
DEBUG_LEVEL_CRITICAL,
DEBUG_LEVEL_WARNING,
DEBUG_LEVEL_INFO,
DEBUG_LEVEL_DEBUG)
from telepathy._generated.Debug import Debug as _Debug
from telepathy.server.properties import DBusProperties
import dbus.service
import logging
import sys
import time
and context from other files:
# Path: telepathy/interfaces.py
# CONN_MGR_INTERFACE = CONNECTION_MANAGER
# CONN_INTERFACE = CONNECTION
# CHANNEL_INTERFACE = CHANNEL
# CHANNEL_HANDLER_INTERFACE = CHANNEL_HANDLER
# CONN_INTERFACE_ALIASING = CONNECTION_INTERFACE_ALIASING
# CONN_INTERFACE_AVATARS = CONNECTION_INTERFACE_AVATARS
# CONN_INTERFACE_CAPABILITIES = CONNECTION_INTERFACE_CAPABILITIES
# CONN_INTERFACE_PRESENCE = CONNECTION_INTERFACE_PRESENCE
# CONN_INTERFACE_RENAMING = CONNECTION_INTERFACE_RENAMING
#
# Path: telepathy/constants.py
# CONNECTION_HANDLE_TYPE_NONE = HANDLE_TYPE_NONE
# CONNECTION_HANDLE_TYPE_CONTACT = HANDLE_TYPE_CONTACT
# CONNECTION_HANDLE_TYPE_ROOM = HANDLE_TYPE_ROOM
# CONNECTION_HANDLE_TYPE_LIST = HANDLE_TYPE_LIST
# CONNECTION_HANDLE_TYPE_USER_CONTACT_GROUP = HANDLE_TYPE_GROUP
#
# Path: telepathy/_generated/Debug.py
# class Debug(dbus.service.Object):
# """\
# An interface for providing debug messages.
#
# This interface is primarily provided by one object per
# service, at the path /org/freedesktop/Telepathy/debug.
# """
#
# @dbus.service.method('org.freedesktop.Telepathy.Debug', in_signature='', out_signature='a(dsus)')
# def GetMessages(self):
# """
# Retrieve buffered debug messages. An implementation could have a
# limit on how many message it keeps and so the array returned from
# this method should not be assumed to be all of the messages in
# the lifetime of the service.
#
# """
# raise NotImplementedError
#
# @dbus.service.signal('org.freedesktop.Telepathy.Debug', signature='dsus')
# def NewDebugMessage(self, time, domain, level, message):
# """
# Emitted when a debug messages is generated if the
# Enabled property is set to TRUE.
#
# """
# pass
#
# Path: telepathy/server/properties.py
# class DBusProperties(dbus.service.Interface):
# def __init__(self):
# if not getattr(self, '_interfaces', None):
# self._interfaces = set()
#
# self._interfaces.add(dbus.PROPERTIES_IFACE)
#
# if not getattr(self, '_immutable_properties', None):
# self._immutable_properties = dict()
#
# if not getattr(self, '_prop_getters', None):
# self._prop_getters = {}
# self._prop_setters = {}
#
# def _implement_property_get(self, iface, dict):
# self._prop_getters.setdefault(iface, {}).update(dict)
#
# def _implement_property_set(self, iface, dict):
# self._prop_setters.setdefault(iface, {}).update(dict)
#
# def _add_immutable_properties(self, props):
# self._immutable_properties.update(props)
#
# def get_immutable_properties(self):
# props = dict()
# for prop, iface in list(self._immutable_properties.items()):
# props[iface + '.' + prop] = self._prop_getters[iface][prop]()
# return props
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v')
# def Get(self, interface_name, property_name):
# if interface_name in self._prop_getters \
# and property_name in self._prop_getters[interface_name]:
# return self._prop_getters[interface_name][property_name]()
# else:
# raise telepathy.errors.InvalidArgument()
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ssv', out_signature='')
# def Set(self, interface_name, property_name, value):
# if interface_name in self._prop_setters \
# and property_name in self._prop_setters[interface_name]:
# self._prop_setters[interface_name][property_name](value)
# else:
# raise telepathy.errors.PermissionDenied()
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='s', out_signature='a{sv}')
# def GetAll(self, interface_name):
# if interface_name in self._prop_getters:
# r = {}
# for k, v in list(self._prop_getters[interface_name].items()):
# r[k] = v()
# return r
# else:
# raise telepathy.errors.InvalidArgument()
, which may include functions, classes, or code. Output only the next line. | self.enabled = False |
Based on the snippet: <|code_start|>
LEVELS = {
logging.ERROR: DEBUG_LEVEL_ERROR,
logging.FATAL: DEBUG_LEVEL_CRITICAL,
logging.WARNING: DEBUG_LEVEL_WARNING,
logging.INFO: DEBUG_LEVEL_INFO,
logging.DEBUG: DEBUG_LEVEL_DEBUG,
logging.NOTSET: DEBUG_LEVEL_DEBUG
}
DEBUG_MESSAGE_LIMIT = 800
class Debug(_Debug, DBusProperties, logging.Handler):
def __init__(self, conn_manager, root=''):
self.enabled = False
self._interfaces = set()
self._messages = []
object_path = '/org/freedesktop/Telepathy/debug'
_Debug.__init__(self, conn_manager._name, object_path)
DBusProperties.__init__(self)
logging.Handler.__init__(self)
self._implement_property_get(DEBUG, {'Enabled': lambda: self.enabled})
self._implement_property_set(DEBUG, {'Enabled': self._set_enabled})
logging.getLogger(root).addHandler(self)
#sys.stderr = StdErrWrapper(self, sys.stderr)
<|code_end|>
, predict the immediate next line with the help of imports:
from telepathy.interfaces import DEBUG
from telepathy.constants import (DEBUG_LEVEL_ERROR,
DEBUG_LEVEL_CRITICAL,
DEBUG_LEVEL_WARNING,
DEBUG_LEVEL_INFO,
DEBUG_LEVEL_DEBUG)
from telepathy._generated.Debug import Debug as _Debug
from telepathy.server.properties import DBusProperties
import dbus.service
import logging
import sys
import time
and context (classes, functions, sometimes code) from other files:
# Path: telepathy/interfaces.py
# CONN_MGR_INTERFACE = CONNECTION_MANAGER
# CONN_INTERFACE = CONNECTION
# CHANNEL_INTERFACE = CHANNEL
# CHANNEL_HANDLER_INTERFACE = CHANNEL_HANDLER
# CONN_INTERFACE_ALIASING = CONNECTION_INTERFACE_ALIASING
# CONN_INTERFACE_AVATARS = CONNECTION_INTERFACE_AVATARS
# CONN_INTERFACE_CAPABILITIES = CONNECTION_INTERFACE_CAPABILITIES
# CONN_INTERFACE_PRESENCE = CONNECTION_INTERFACE_PRESENCE
# CONN_INTERFACE_RENAMING = CONNECTION_INTERFACE_RENAMING
#
# Path: telepathy/constants.py
# CONNECTION_HANDLE_TYPE_NONE = HANDLE_TYPE_NONE
# CONNECTION_HANDLE_TYPE_CONTACT = HANDLE_TYPE_CONTACT
# CONNECTION_HANDLE_TYPE_ROOM = HANDLE_TYPE_ROOM
# CONNECTION_HANDLE_TYPE_LIST = HANDLE_TYPE_LIST
# CONNECTION_HANDLE_TYPE_USER_CONTACT_GROUP = HANDLE_TYPE_GROUP
#
# Path: telepathy/_generated/Debug.py
# class Debug(dbus.service.Object):
# """\
# An interface for providing debug messages.
#
# This interface is primarily provided by one object per
# service, at the path /org/freedesktop/Telepathy/debug.
# """
#
# @dbus.service.method('org.freedesktop.Telepathy.Debug', in_signature='', out_signature='a(dsus)')
# def GetMessages(self):
# """
# Retrieve buffered debug messages. An implementation could have a
# limit on how many message it keeps and so the array returned from
# this method should not be assumed to be all of the messages in
# the lifetime of the service.
#
# """
# raise NotImplementedError
#
# @dbus.service.signal('org.freedesktop.Telepathy.Debug', signature='dsus')
# def NewDebugMessage(self, time, domain, level, message):
# """
# Emitted when a debug messages is generated if the
# Enabled property is set to TRUE.
#
# """
# pass
#
# Path: telepathy/server/properties.py
# class DBusProperties(dbus.service.Interface):
# def __init__(self):
# if not getattr(self, '_interfaces', None):
# self._interfaces = set()
#
# self._interfaces.add(dbus.PROPERTIES_IFACE)
#
# if not getattr(self, '_immutable_properties', None):
# self._immutable_properties = dict()
#
# if not getattr(self, '_prop_getters', None):
# self._prop_getters = {}
# self._prop_setters = {}
#
# def _implement_property_get(self, iface, dict):
# self._prop_getters.setdefault(iface, {}).update(dict)
#
# def _implement_property_set(self, iface, dict):
# self._prop_setters.setdefault(iface, {}).update(dict)
#
# def _add_immutable_properties(self, props):
# self._immutable_properties.update(props)
#
# def get_immutable_properties(self):
# props = dict()
# for prop, iface in list(self._immutable_properties.items()):
# props[iface + '.' + prop] = self._prop_getters[iface][prop]()
# return props
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v')
# def Get(self, interface_name, property_name):
# if interface_name in self._prop_getters \
# and property_name in self._prop_getters[interface_name]:
# return self._prop_getters[interface_name][property_name]()
# else:
# raise telepathy.errors.InvalidArgument()
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ssv', out_signature='')
# def Set(self, interface_name, property_name, value):
# if interface_name in self._prop_setters \
# and property_name in self._prop_setters[interface_name]:
# self._prop_setters[interface_name][property_name](value)
# else:
# raise telepathy.errors.PermissionDenied()
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='s', out_signature='a{sv}')
# def GetAll(self, interface_name):
# if interface_name in self._prop_getters:
# r = {}
# for k, v in list(self._prop_getters[interface_name].items()):
# r[k] = v()
# return r
# else:
# raise telepathy.errors.InvalidArgument()
. Output only the next line. | def _set_enabled(self, value): |
Predict the next line for this snippet: <|code_start|> logging.INFO: DEBUG_LEVEL_INFO,
logging.DEBUG: DEBUG_LEVEL_DEBUG,
logging.NOTSET: DEBUG_LEVEL_DEBUG
}
DEBUG_MESSAGE_LIMIT = 800
class Debug(_Debug, DBusProperties, logging.Handler):
def __init__(self, conn_manager, root=''):
self.enabled = False
self._interfaces = set()
self._messages = []
object_path = '/org/freedesktop/Telepathy/debug'
_Debug.__init__(self, conn_manager._name, object_path)
DBusProperties.__init__(self)
logging.Handler.__init__(self)
self._implement_property_get(DEBUG, {'Enabled': lambda: self.enabled})
self._implement_property_set(DEBUG, {'Enabled': self._set_enabled})
logging.getLogger(root).addHandler(self)
#sys.stderr = StdErrWrapper(self, sys.stderr)
def _set_enabled(self, value):
self.enabled = value
def GetMessages(self):
return self._messages
<|code_end|>
with the help of current file imports:
from telepathy.interfaces import DEBUG
from telepathy.constants import (DEBUG_LEVEL_ERROR,
DEBUG_LEVEL_CRITICAL,
DEBUG_LEVEL_WARNING,
DEBUG_LEVEL_INFO,
DEBUG_LEVEL_DEBUG)
from telepathy._generated.Debug import Debug as _Debug
from telepathy.server.properties import DBusProperties
import dbus.service
import logging
import sys
import time
and context from other files:
# Path: telepathy/interfaces.py
# CONN_MGR_INTERFACE = CONNECTION_MANAGER
# CONN_INTERFACE = CONNECTION
# CHANNEL_INTERFACE = CHANNEL
# CHANNEL_HANDLER_INTERFACE = CHANNEL_HANDLER
# CONN_INTERFACE_ALIASING = CONNECTION_INTERFACE_ALIASING
# CONN_INTERFACE_AVATARS = CONNECTION_INTERFACE_AVATARS
# CONN_INTERFACE_CAPABILITIES = CONNECTION_INTERFACE_CAPABILITIES
# CONN_INTERFACE_PRESENCE = CONNECTION_INTERFACE_PRESENCE
# CONN_INTERFACE_RENAMING = CONNECTION_INTERFACE_RENAMING
#
# Path: telepathy/constants.py
# CONNECTION_HANDLE_TYPE_NONE = HANDLE_TYPE_NONE
# CONNECTION_HANDLE_TYPE_CONTACT = HANDLE_TYPE_CONTACT
# CONNECTION_HANDLE_TYPE_ROOM = HANDLE_TYPE_ROOM
# CONNECTION_HANDLE_TYPE_LIST = HANDLE_TYPE_LIST
# CONNECTION_HANDLE_TYPE_USER_CONTACT_GROUP = HANDLE_TYPE_GROUP
#
# Path: telepathy/_generated/Debug.py
# class Debug(dbus.service.Object):
# """\
# An interface for providing debug messages.
#
# This interface is primarily provided by one object per
# service, at the path /org/freedesktop/Telepathy/debug.
# """
#
# @dbus.service.method('org.freedesktop.Telepathy.Debug', in_signature='', out_signature='a(dsus)')
# def GetMessages(self):
# """
# Retrieve buffered debug messages. An implementation could have a
# limit on how many message it keeps and so the array returned from
# this method should not be assumed to be all of the messages in
# the lifetime of the service.
#
# """
# raise NotImplementedError
#
# @dbus.service.signal('org.freedesktop.Telepathy.Debug', signature='dsus')
# def NewDebugMessage(self, time, domain, level, message):
# """
# Emitted when a debug messages is generated if the
# Enabled property is set to TRUE.
#
# """
# pass
#
# Path: telepathy/server/properties.py
# class DBusProperties(dbus.service.Interface):
# def __init__(self):
# if not getattr(self, '_interfaces', None):
# self._interfaces = set()
#
# self._interfaces.add(dbus.PROPERTIES_IFACE)
#
# if not getattr(self, '_immutable_properties', None):
# self._immutable_properties = dict()
#
# if not getattr(self, '_prop_getters', None):
# self._prop_getters = {}
# self._prop_setters = {}
#
# def _implement_property_get(self, iface, dict):
# self._prop_getters.setdefault(iface, {}).update(dict)
#
# def _implement_property_set(self, iface, dict):
# self._prop_setters.setdefault(iface, {}).update(dict)
#
# def _add_immutable_properties(self, props):
# self._immutable_properties.update(props)
#
# def get_immutable_properties(self):
# props = dict()
# for prop, iface in list(self._immutable_properties.items()):
# props[iface + '.' + prop] = self._prop_getters[iface][prop]()
# return props
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v')
# def Get(self, interface_name, property_name):
# if interface_name in self._prop_getters \
# and property_name in self._prop_getters[interface_name]:
# return self._prop_getters[interface_name][property_name]()
# else:
# raise telepathy.errors.InvalidArgument()
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ssv', out_signature='')
# def Set(self, interface_name, property_name, value):
# if interface_name in self._prop_setters \
# and property_name in self._prop_setters[interface_name]:
# self._prop_setters[interface_name][property_name](value)
# else:
# raise telepathy.errors.PermissionDenied()
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='s', out_signature='a{sv}')
# def GetAll(self, interface_name):
# if interface_name in self._prop_getters:
# r = {}
# for k, v in list(self._prop_getters[interface_name].items()):
# r[k] = v()
# return r
# else:
# raise telepathy.errors.InvalidArgument()
, which may contain function names, class names, or code. Output only the next line. | def add_message(self, timestamp, name, level, msg): |
Predict the next line for this snippet: <|code_start|>
def get_record_level(self, record):
return LEVELS[record.levelno]
def get_record_name(self, record):
name = record.name
if name.contains("."):
domain, category = record.name.split('.', 1)
name = domain + "/" + category
return name
# Wrapper around stderr so the exceptions are logged
class StdErrWrapper(object):
def __init__(self, interface, stderr):
self._buffer = ""
self._interface = interface
self._stderr = stderr
def __getattr__(self, attr):
return getattr(self._stderr, attr)
def write(self, string):
self._stderr.write(string)
if '\n' not in string:
self._buffer += string
return
lines = string.split('\n')
<|code_end|>
with the help of current file imports:
from telepathy.interfaces import DEBUG
from telepathy.constants import (DEBUG_LEVEL_ERROR,
DEBUG_LEVEL_CRITICAL,
DEBUG_LEVEL_WARNING,
DEBUG_LEVEL_INFO,
DEBUG_LEVEL_DEBUG)
from telepathy._generated.Debug import Debug as _Debug
from telepathy.server.properties import DBusProperties
import dbus.service
import logging
import sys
import time
and context from other files:
# Path: telepathy/interfaces.py
# CONN_MGR_INTERFACE = CONNECTION_MANAGER
# CONN_INTERFACE = CONNECTION
# CHANNEL_INTERFACE = CHANNEL
# CHANNEL_HANDLER_INTERFACE = CHANNEL_HANDLER
# CONN_INTERFACE_ALIASING = CONNECTION_INTERFACE_ALIASING
# CONN_INTERFACE_AVATARS = CONNECTION_INTERFACE_AVATARS
# CONN_INTERFACE_CAPABILITIES = CONNECTION_INTERFACE_CAPABILITIES
# CONN_INTERFACE_PRESENCE = CONNECTION_INTERFACE_PRESENCE
# CONN_INTERFACE_RENAMING = CONNECTION_INTERFACE_RENAMING
#
# Path: telepathy/constants.py
# CONNECTION_HANDLE_TYPE_NONE = HANDLE_TYPE_NONE
# CONNECTION_HANDLE_TYPE_CONTACT = HANDLE_TYPE_CONTACT
# CONNECTION_HANDLE_TYPE_ROOM = HANDLE_TYPE_ROOM
# CONNECTION_HANDLE_TYPE_LIST = HANDLE_TYPE_LIST
# CONNECTION_HANDLE_TYPE_USER_CONTACT_GROUP = HANDLE_TYPE_GROUP
#
# Path: telepathy/_generated/Debug.py
# class Debug(dbus.service.Object):
# """\
# An interface for providing debug messages.
#
# This interface is primarily provided by one object per
# service, at the path /org/freedesktop/Telepathy/debug.
# """
#
# @dbus.service.method('org.freedesktop.Telepathy.Debug', in_signature='', out_signature='a(dsus)')
# def GetMessages(self):
# """
# Retrieve buffered debug messages. An implementation could have a
# limit on how many message it keeps and so the array returned from
# this method should not be assumed to be all of the messages in
# the lifetime of the service.
#
# """
# raise NotImplementedError
#
# @dbus.service.signal('org.freedesktop.Telepathy.Debug', signature='dsus')
# def NewDebugMessage(self, time, domain, level, message):
# """
# Emitted when a debug messages is generated if the
# Enabled property is set to TRUE.
#
# """
# pass
#
# Path: telepathy/server/properties.py
# class DBusProperties(dbus.service.Interface):
# def __init__(self):
# if not getattr(self, '_interfaces', None):
# self._interfaces = set()
#
# self._interfaces.add(dbus.PROPERTIES_IFACE)
#
# if not getattr(self, '_immutable_properties', None):
# self._immutable_properties = dict()
#
# if not getattr(self, '_prop_getters', None):
# self._prop_getters = {}
# self._prop_setters = {}
#
# def _implement_property_get(self, iface, dict):
# self._prop_getters.setdefault(iface, {}).update(dict)
#
# def _implement_property_set(self, iface, dict):
# self._prop_setters.setdefault(iface, {}).update(dict)
#
# def _add_immutable_properties(self, props):
# self._immutable_properties.update(props)
#
# def get_immutable_properties(self):
# props = dict()
# for prop, iface in list(self._immutable_properties.items()):
# props[iface + '.' + prop] = self._prop_getters[iface][prop]()
# return props
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v')
# def Get(self, interface_name, property_name):
# if interface_name in self._prop_getters \
# and property_name in self._prop_getters[interface_name]:
# return self._prop_getters[interface_name][property_name]()
# else:
# raise telepathy.errors.InvalidArgument()
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ssv', out_signature='')
# def Set(self, interface_name, property_name, value):
# if interface_name in self._prop_setters \
# and property_name in self._prop_setters[interface_name]:
# self._prop_setters[interface_name][property_name](value)
# else:
# raise telepathy.errors.PermissionDenied()
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='s', out_signature='a{sv}')
# def GetAll(self, interface_name):
# if interface_name in self._prop_getters:
# r = {}
# for k, v in list(self._prop_getters[interface_name].items()):
# r[k] = v()
# return r
# else:
# raise telepathy.errors.InvalidArgument()
, which may contain function names, class names, or code. Output only the next line. | lines[0] = self._buffer + lines[0] |
Based on the snippet: <|code_start|> def get_record_level(self, record):
return LEVELS[record.levelno]
def get_record_name(self, record):
name = record.name
if name.contains("."):
domain, category = record.name.split('.', 1)
name = domain + "/" + category
return name
# Wrapper around stderr so the exceptions are logged
class StdErrWrapper(object):
def __init__(self, interface, stderr):
self._buffer = ""
self._interface = interface
self._stderr = stderr
def __getattr__(self, attr):
return getattr(self._stderr, attr)
def write(self, string):
self._stderr.write(string)
if '\n' not in string:
self._buffer += string
return
lines = string.split('\n')
lines[0] = self._buffer + lines[0]
<|code_end|>
, predict the immediate next line with the help of imports:
from telepathy.interfaces import DEBUG
from telepathy.constants import (DEBUG_LEVEL_ERROR,
DEBUG_LEVEL_CRITICAL,
DEBUG_LEVEL_WARNING,
DEBUG_LEVEL_INFO,
DEBUG_LEVEL_DEBUG)
from telepathy._generated.Debug import Debug as _Debug
from telepathy.server.properties import DBusProperties
import dbus.service
import logging
import sys
import time
and context (classes, functions, sometimes code) from other files:
# Path: telepathy/interfaces.py
# CONN_MGR_INTERFACE = CONNECTION_MANAGER
# CONN_INTERFACE = CONNECTION
# CHANNEL_INTERFACE = CHANNEL
# CHANNEL_HANDLER_INTERFACE = CHANNEL_HANDLER
# CONN_INTERFACE_ALIASING = CONNECTION_INTERFACE_ALIASING
# CONN_INTERFACE_AVATARS = CONNECTION_INTERFACE_AVATARS
# CONN_INTERFACE_CAPABILITIES = CONNECTION_INTERFACE_CAPABILITIES
# CONN_INTERFACE_PRESENCE = CONNECTION_INTERFACE_PRESENCE
# CONN_INTERFACE_RENAMING = CONNECTION_INTERFACE_RENAMING
#
# Path: telepathy/constants.py
# CONNECTION_HANDLE_TYPE_NONE = HANDLE_TYPE_NONE
# CONNECTION_HANDLE_TYPE_CONTACT = HANDLE_TYPE_CONTACT
# CONNECTION_HANDLE_TYPE_ROOM = HANDLE_TYPE_ROOM
# CONNECTION_HANDLE_TYPE_LIST = HANDLE_TYPE_LIST
# CONNECTION_HANDLE_TYPE_USER_CONTACT_GROUP = HANDLE_TYPE_GROUP
#
# Path: telepathy/_generated/Debug.py
# class Debug(dbus.service.Object):
# """\
# An interface for providing debug messages.
#
# This interface is primarily provided by one object per
# service, at the path /org/freedesktop/Telepathy/debug.
# """
#
# @dbus.service.method('org.freedesktop.Telepathy.Debug', in_signature='', out_signature='a(dsus)')
# def GetMessages(self):
# """
# Retrieve buffered debug messages. An implementation could have a
# limit on how many message it keeps and so the array returned from
# this method should not be assumed to be all of the messages in
# the lifetime of the service.
#
# """
# raise NotImplementedError
#
# @dbus.service.signal('org.freedesktop.Telepathy.Debug', signature='dsus')
# def NewDebugMessage(self, time, domain, level, message):
# """
# Emitted when a debug messages is generated if the
# Enabled property is set to TRUE.
#
# """
# pass
#
# Path: telepathy/server/properties.py
# class DBusProperties(dbus.service.Interface):
# def __init__(self):
# if not getattr(self, '_interfaces', None):
# self._interfaces = set()
#
# self._interfaces.add(dbus.PROPERTIES_IFACE)
#
# if not getattr(self, '_immutable_properties', None):
# self._immutable_properties = dict()
#
# if not getattr(self, '_prop_getters', None):
# self._prop_getters = {}
# self._prop_setters = {}
#
# def _implement_property_get(self, iface, dict):
# self._prop_getters.setdefault(iface, {}).update(dict)
#
# def _implement_property_set(self, iface, dict):
# self._prop_setters.setdefault(iface, {}).update(dict)
#
# def _add_immutable_properties(self, props):
# self._immutable_properties.update(props)
#
# def get_immutable_properties(self):
# props = dict()
# for prop, iface in list(self._immutable_properties.items()):
# props[iface + '.' + prop] = self._prop_getters[iface][prop]()
# return props
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v')
# def Get(self, interface_name, property_name):
# if interface_name in self._prop_getters \
# and property_name in self._prop_getters[interface_name]:
# return self._prop_getters[interface_name][property_name]()
# else:
# raise telepathy.errors.InvalidArgument()
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ssv', out_signature='')
# def Set(self, interface_name, property_name, value):
# if interface_name in self._prop_setters \
# and property_name in self._prop_setters[interface_name]:
# self._prop_setters[interface_name][property_name](value)
# else:
# raise telepathy.errors.PermissionDenied()
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='s', out_signature='a{sv}')
# def GetAll(self, interface_name):
# if interface_name in self._prop_getters:
# r = {}
# for k, v in list(self._prop_getters[interface_name].items()):
# r[k] = v()
# return r
# else:
# raise telepathy.errors.InvalidArgument()
. Output only the next line. | self._buffer = lines[-1] |
Given the code snippet: <|code_start|> if len(self._messages) >= DEBUG_MESSAGE_LIMIT:
self._messages.pop()
self._messages.append((timestamp, name, level, msg))
if self.enabled:
self.NewDebugMessage(timestamp, name, level, msg)
# Handle logging module messages
def emit(self, record):
name = self.get_record_name(record)
level = self.get_record_level(record)
self.add_message(record.created, name, level, record.msg)
def get_record_level(self, record):
return LEVELS[record.levelno]
def get_record_name(self, record):
name = record.name
if name.contains("."):
domain, category = record.name.split('.', 1)
name = domain + "/" + category
return name
# Wrapper around stderr so the exceptions are logged
class StdErrWrapper(object):
def __init__(self, interface, stderr):
self._buffer = ""
self._interface = interface
<|code_end|>
, generate the next line using the imports in this file:
from telepathy.interfaces import DEBUG
from telepathy.constants import (DEBUG_LEVEL_ERROR,
DEBUG_LEVEL_CRITICAL,
DEBUG_LEVEL_WARNING,
DEBUG_LEVEL_INFO,
DEBUG_LEVEL_DEBUG)
from telepathy._generated.Debug import Debug as _Debug
from telepathy.server.properties import DBusProperties
import dbus.service
import logging
import sys
import time
and context (functions, classes, or occasionally code) from other files:
# Path: telepathy/interfaces.py
# CONN_MGR_INTERFACE = CONNECTION_MANAGER
# CONN_INTERFACE = CONNECTION
# CHANNEL_INTERFACE = CHANNEL
# CHANNEL_HANDLER_INTERFACE = CHANNEL_HANDLER
# CONN_INTERFACE_ALIASING = CONNECTION_INTERFACE_ALIASING
# CONN_INTERFACE_AVATARS = CONNECTION_INTERFACE_AVATARS
# CONN_INTERFACE_CAPABILITIES = CONNECTION_INTERFACE_CAPABILITIES
# CONN_INTERFACE_PRESENCE = CONNECTION_INTERFACE_PRESENCE
# CONN_INTERFACE_RENAMING = CONNECTION_INTERFACE_RENAMING
#
# Path: telepathy/constants.py
# CONNECTION_HANDLE_TYPE_NONE = HANDLE_TYPE_NONE
# CONNECTION_HANDLE_TYPE_CONTACT = HANDLE_TYPE_CONTACT
# CONNECTION_HANDLE_TYPE_ROOM = HANDLE_TYPE_ROOM
# CONNECTION_HANDLE_TYPE_LIST = HANDLE_TYPE_LIST
# CONNECTION_HANDLE_TYPE_USER_CONTACT_GROUP = HANDLE_TYPE_GROUP
#
# Path: telepathy/_generated/Debug.py
# class Debug(dbus.service.Object):
# """\
# An interface for providing debug messages.
#
# This interface is primarily provided by one object per
# service, at the path /org/freedesktop/Telepathy/debug.
# """
#
# @dbus.service.method('org.freedesktop.Telepathy.Debug', in_signature='', out_signature='a(dsus)')
# def GetMessages(self):
# """
# Retrieve buffered debug messages. An implementation could have a
# limit on how many message it keeps and so the array returned from
# this method should not be assumed to be all of the messages in
# the lifetime of the service.
#
# """
# raise NotImplementedError
#
# @dbus.service.signal('org.freedesktop.Telepathy.Debug', signature='dsus')
# def NewDebugMessage(self, time, domain, level, message):
# """
# Emitted when a debug messages is generated if the
# Enabled property is set to TRUE.
#
# """
# pass
#
# Path: telepathy/server/properties.py
# class DBusProperties(dbus.service.Interface):
# def __init__(self):
# if not getattr(self, '_interfaces', None):
# self._interfaces = set()
#
# self._interfaces.add(dbus.PROPERTIES_IFACE)
#
# if not getattr(self, '_immutable_properties', None):
# self._immutable_properties = dict()
#
# if not getattr(self, '_prop_getters', None):
# self._prop_getters = {}
# self._prop_setters = {}
#
# def _implement_property_get(self, iface, dict):
# self._prop_getters.setdefault(iface, {}).update(dict)
#
# def _implement_property_set(self, iface, dict):
# self._prop_setters.setdefault(iface, {}).update(dict)
#
# def _add_immutable_properties(self, props):
# self._immutable_properties.update(props)
#
# def get_immutable_properties(self):
# props = dict()
# for prop, iface in list(self._immutable_properties.items()):
# props[iface + '.' + prop] = self._prop_getters[iface][prop]()
# return props
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v')
# def Get(self, interface_name, property_name):
# if interface_name in self._prop_getters \
# and property_name in self._prop_getters[interface_name]:
# return self._prop_getters[interface_name][property_name]()
# else:
# raise telepathy.errors.InvalidArgument()
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ssv', out_signature='')
# def Set(self, interface_name, property_name, value):
# if interface_name in self._prop_setters \
# and property_name in self._prop_setters[interface_name]:
# self._prop_setters[interface_name][property_name](value)
# else:
# raise telepathy.errors.PermissionDenied()
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='s', out_signature='a{sv}')
# def GetAll(self, interface_name):
# if interface_name in self._prop_getters:
# r = {}
# for k, v in list(self._prop_getters[interface_name].items()):
# r[k] = v()
# return r
# else:
# raise telepathy.errors.InvalidArgument()
. Output only the next line. | self._stderr = stderr |
Predict the next line after this snippet: <|code_start|> logging.Handler.__init__(self)
self._implement_property_get(DEBUG, {'Enabled': lambda: self.enabled})
self._implement_property_set(DEBUG, {'Enabled': self._set_enabled})
logging.getLogger(root).addHandler(self)
#sys.stderr = StdErrWrapper(self, sys.stderr)
def _set_enabled(self, value):
self.enabled = value
def GetMessages(self):
return self._messages
def add_message(self, timestamp, name, level, msg):
if len(self._messages) >= DEBUG_MESSAGE_LIMIT:
self._messages.pop()
self._messages.append((timestamp, name, level, msg))
if self.enabled:
self.NewDebugMessage(timestamp, name, level, msg)
# Handle logging module messages
def emit(self, record):
name = self.get_record_name(record)
level = self.get_record_level(record)
self.add_message(record.created, name, level, record.msg)
def get_record_level(self, record):
return LEVELS[record.levelno]
<|code_end|>
using the current file's imports:
from telepathy.interfaces import DEBUG
from telepathy.constants import (DEBUG_LEVEL_ERROR,
DEBUG_LEVEL_CRITICAL,
DEBUG_LEVEL_WARNING,
DEBUG_LEVEL_INFO,
DEBUG_LEVEL_DEBUG)
from telepathy._generated.Debug import Debug as _Debug
from telepathy.server.properties import DBusProperties
import dbus.service
import logging
import sys
import time
and any relevant context from other files:
# Path: telepathy/interfaces.py
# CONN_MGR_INTERFACE = CONNECTION_MANAGER
# CONN_INTERFACE = CONNECTION
# CHANNEL_INTERFACE = CHANNEL
# CHANNEL_HANDLER_INTERFACE = CHANNEL_HANDLER
# CONN_INTERFACE_ALIASING = CONNECTION_INTERFACE_ALIASING
# CONN_INTERFACE_AVATARS = CONNECTION_INTERFACE_AVATARS
# CONN_INTERFACE_CAPABILITIES = CONNECTION_INTERFACE_CAPABILITIES
# CONN_INTERFACE_PRESENCE = CONNECTION_INTERFACE_PRESENCE
# CONN_INTERFACE_RENAMING = CONNECTION_INTERFACE_RENAMING
#
# Path: telepathy/constants.py
# CONNECTION_HANDLE_TYPE_NONE = HANDLE_TYPE_NONE
# CONNECTION_HANDLE_TYPE_CONTACT = HANDLE_TYPE_CONTACT
# CONNECTION_HANDLE_TYPE_ROOM = HANDLE_TYPE_ROOM
# CONNECTION_HANDLE_TYPE_LIST = HANDLE_TYPE_LIST
# CONNECTION_HANDLE_TYPE_USER_CONTACT_GROUP = HANDLE_TYPE_GROUP
#
# Path: telepathy/_generated/Debug.py
# class Debug(dbus.service.Object):
# """\
# An interface for providing debug messages.
#
# This interface is primarily provided by one object per
# service, at the path /org/freedesktop/Telepathy/debug.
# """
#
# @dbus.service.method('org.freedesktop.Telepathy.Debug', in_signature='', out_signature='a(dsus)')
# def GetMessages(self):
# """
# Retrieve buffered debug messages. An implementation could have a
# limit on how many message it keeps and so the array returned from
# this method should not be assumed to be all of the messages in
# the lifetime of the service.
#
# """
# raise NotImplementedError
#
# @dbus.service.signal('org.freedesktop.Telepathy.Debug', signature='dsus')
# def NewDebugMessage(self, time, domain, level, message):
# """
# Emitted when a debug messages is generated if the
# Enabled property is set to TRUE.
#
# """
# pass
#
# Path: telepathy/server/properties.py
# class DBusProperties(dbus.service.Interface):
# def __init__(self):
# if not getattr(self, '_interfaces', None):
# self._interfaces = set()
#
# self._interfaces.add(dbus.PROPERTIES_IFACE)
#
# if not getattr(self, '_immutable_properties', None):
# self._immutable_properties = dict()
#
# if not getattr(self, '_prop_getters', None):
# self._prop_getters = {}
# self._prop_setters = {}
#
# def _implement_property_get(self, iface, dict):
# self._prop_getters.setdefault(iface, {}).update(dict)
#
# def _implement_property_set(self, iface, dict):
# self._prop_setters.setdefault(iface, {}).update(dict)
#
# def _add_immutable_properties(self, props):
# self._immutable_properties.update(props)
#
# def get_immutable_properties(self):
# props = dict()
# for prop, iface in list(self._immutable_properties.items()):
# props[iface + '.' + prop] = self._prop_getters[iface][prop]()
# return props
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v')
# def Get(self, interface_name, property_name):
# if interface_name in self._prop_getters \
# and property_name in self._prop_getters[interface_name]:
# return self._prop_getters[interface_name][property_name]()
# else:
# raise telepathy.errors.InvalidArgument()
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ssv', out_signature='')
# def Set(self, interface_name, property_name, value):
# if interface_name in self._prop_setters \
# and property_name in self._prop_setters[interface_name]:
# self._prop_setters[interface_name][property_name](value)
# else:
# raise telepathy.errors.PermissionDenied()
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='s', out_signature='a{sv}')
# def GetAll(self, interface_name):
# if interface_name in self._prop_getters:
# r = {}
# for k, v in list(self._prop_getters[interface_name].items()):
# r[k] = v()
# return r
# else:
# raise telepathy.errors.InvalidArgument()
. Output only the next line. | def get_record_name(self, record): |
Continue the code snippet: <|code_start|> logging.Handler.__init__(self)
self._implement_property_get(DEBUG, {'Enabled': lambda: self.enabled})
self._implement_property_set(DEBUG, {'Enabled': self._set_enabled})
logging.getLogger(root).addHandler(self)
#sys.stderr = StdErrWrapper(self, sys.stderr)
def _set_enabled(self, value):
self.enabled = value
def GetMessages(self):
return self._messages
def add_message(self, timestamp, name, level, msg):
if len(self._messages) >= DEBUG_MESSAGE_LIMIT:
self._messages.pop()
self._messages.append((timestamp, name, level, msg))
if self.enabled:
self.NewDebugMessage(timestamp, name, level, msg)
# Handle logging module messages
def emit(self, record):
name = self.get_record_name(record)
level = self.get_record_level(record)
self.add_message(record.created, name, level, record.msg)
def get_record_level(self, record):
return LEVELS[record.levelno]
<|code_end|>
. Use current file imports:
from telepathy.interfaces import DEBUG
from telepathy.constants import (DEBUG_LEVEL_ERROR,
DEBUG_LEVEL_CRITICAL,
DEBUG_LEVEL_WARNING,
DEBUG_LEVEL_INFO,
DEBUG_LEVEL_DEBUG)
from telepathy._generated.Debug import Debug as _Debug
from telepathy.server.properties import DBusProperties
import dbus.service
import logging
import sys
import time
and context (classes, functions, or code) from other files:
# Path: telepathy/interfaces.py
# CONN_MGR_INTERFACE = CONNECTION_MANAGER
# CONN_INTERFACE = CONNECTION
# CHANNEL_INTERFACE = CHANNEL
# CHANNEL_HANDLER_INTERFACE = CHANNEL_HANDLER
# CONN_INTERFACE_ALIASING = CONNECTION_INTERFACE_ALIASING
# CONN_INTERFACE_AVATARS = CONNECTION_INTERFACE_AVATARS
# CONN_INTERFACE_CAPABILITIES = CONNECTION_INTERFACE_CAPABILITIES
# CONN_INTERFACE_PRESENCE = CONNECTION_INTERFACE_PRESENCE
# CONN_INTERFACE_RENAMING = CONNECTION_INTERFACE_RENAMING
#
# Path: telepathy/constants.py
# CONNECTION_HANDLE_TYPE_NONE = HANDLE_TYPE_NONE
# CONNECTION_HANDLE_TYPE_CONTACT = HANDLE_TYPE_CONTACT
# CONNECTION_HANDLE_TYPE_ROOM = HANDLE_TYPE_ROOM
# CONNECTION_HANDLE_TYPE_LIST = HANDLE_TYPE_LIST
# CONNECTION_HANDLE_TYPE_USER_CONTACT_GROUP = HANDLE_TYPE_GROUP
#
# Path: telepathy/_generated/Debug.py
# class Debug(dbus.service.Object):
# """\
# An interface for providing debug messages.
#
# This interface is primarily provided by one object per
# service, at the path /org/freedesktop/Telepathy/debug.
# """
#
# @dbus.service.method('org.freedesktop.Telepathy.Debug', in_signature='', out_signature='a(dsus)')
# def GetMessages(self):
# """
# Retrieve buffered debug messages. An implementation could have a
# limit on how many message it keeps and so the array returned from
# this method should not be assumed to be all of the messages in
# the lifetime of the service.
#
# """
# raise NotImplementedError
#
# @dbus.service.signal('org.freedesktop.Telepathy.Debug', signature='dsus')
# def NewDebugMessage(self, time, domain, level, message):
# """
# Emitted when a debug messages is generated if the
# Enabled property is set to TRUE.
#
# """
# pass
#
# Path: telepathy/server/properties.py
# class DBusProperties(dbus.service.Interface):
# def __init__(self):
# if not getattr(self, '_interfaces', None):
# self._interfaces = set()
#
# self._interfaces.add(dbus.PROPERTIES_IFACE)
#
# if not getattr(self, '_immutable_properties', None):
# self._immutable_properties = dict()
#
# if not getattr(self, '_prop_getters', None):
# self._prop_getters = {}
# self._prop_setters = {}
#
# def _implement_property_get(self, iface, dict):
# self._prop_getters.setdefault(iface, {}).update(dict)
#
# def _implement_property_set(self, iface, dict):
# self._prop_setters.setdefault(iface, {}).update(dict)
#
# def _add_immutable_properties(self, props):
# self._immutable_properties.update(props)
#
# def get_immutable_properties(self):
# props = dict()
# for prop, iface in list(self._immutable_properties.items()):
# props[iface + '.' + prop] = self._prop_getters[iface][prop]()
# return props
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v')
# def Get(self, interface_name, property_name):
# if interface_name in self._prop_getters \
# and property_name in self._prop_getters[interface_name]:
# return self._prop_getters[interface_name][property_name]()
# else:
# raise telepathy.errors.InvalidArgument()
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='ssv', out_signature='')
# def Set(self, interface_name, property_name, value):
# if interface_name in self._prop_setters \
# and property_name in self._prop_setters[interface_name]:
# self._prop_setters[interface_name][property_name](value)
# else:
# raise telepathy.errors.PermissionDenied()
#
# @dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE, in_signature='s', out_signature='a{sv}')
# def GetAll(self, interface_name):
# if interface_name in self._prop_getters:
# r = {}
# for k, v in list(self._prop_getters[interface_name].items()):
# r[k] = v()
# return r
# else:
# raise telepathy.errors.InvalidArgument()
. Output only the next line. | def get_record_name(self, record): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.